tracker

package
v2.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Examples

Constants

View Source
const PenalizedThreshold = 0.01

PenalizedThreshold is the throttling probability at or above which Saturation counts a bucket as penalized: a client whose every bucket is at this level has at least 1 request in 100 throttled.

Variables

This section is empty.

Functions

This section is empty.

Types

type Counters

type Counters struct {
	// Registered counts RegisterRequest calls.
	Registered uint64
	// Throttled counts the RegisterRequest calls that returned ShouldThrottle.
	Throttled uint64
	// Successes and Failures count the outcomes applied by ReportOutcome.
	Successes uint64
	Failures  uint64
	// IgnoredOutcomes counts ReportOutcome calls with an unknown outcome.
	// Anything above zero is a bug in the caller.
	IgnoredOutcomes uint64
}

Counters are cumulative totals since the tracker was built. Each field is read separately, so a snapshot taken under load may be off by the requests in flight; differences between two snapshots give rates.

type FairnessTracker

type FairnessTracker struct {
	// contains filtered or unexported fields
}

FairnessTracker is the main entry point for applications. It keeps track of client flows and determines when a request should be throttled to maintain fairness.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/satmihir/fair/v2/pkg/request"
	"github.com/satmihir/fair/v2/pkg/tracker"
)

func main() {
	builder := tracker.NewFairnessTrackerBuilder()
	// For this example only: make a single contention failure block the next call.
	builder.SetPi(1)
	builder.SetLambda(0)
	trk, err := builder.Build()
	if err != nil {
		panic(err) // Cannot serve requests without the tracker.
	}
	defer trk.Close()

	errPoolFull := errors.New("pool is full")
	errThrottled := errors.New("throttled")
	acquire := func(ctx context.Context, clientID []byte, tryAcquire func() error) error {
		if trk.RegisterRequest(ctx, clientID).ShouldThrottle {
			return errThrottled // Do not attempt acquisition or report an outcome.
		}
		err := tryAcquire()
		switch {
		case err == nil:
			trk.ReportOutcome(ctx, clientID, request.OutcomeSuccess)
		case errors.Is(err, errPoolFull):
			trk.ReportOutcome(ctx, clientID, request.OutcomeFailure)
		} // Other errors do not establish contention.
		return err
	}

	ctx := context.Background()
	clientID := []byte("client-42")
	fmt.Println(acquire(ctx, clientID, func() error { return nil }))
	fmt.Println(acquire(ctx, clientID, func() error { return errPoolFull }))
	fmt.Println(acquire(ctx, clientID, func() error { return nil })) // Not forwarded.
}
Output:
<nil>
pool is full
throttled

func NewFairnessTracker

func NewFairnessTracker(trackerConfig *config.FairnessTrackerConfig) (*FairnessTracker, error)

NewFairnessTracker creates a FairnessTracker using the real system clock and ticker.

func NewFairnessTrackerWithClockAndTicker

func NewFairnessTrackerWithClockAndTicker(trackerConfig *config.FairnessTrackerConfig, clock utils.IClock, ticker utils.ITicker) (*FairnessTracker, error)

NewFairnessTrackerWithClockAndTicker creates a FairnessTracker using the provided clock and ticker. It is primarily used for tests and simulations where time needs to be controlled. On success the tracker owns the ticker; on failure the caller retains ownership. Like time.Ticker's channel accessor, ticker.C must return without waiting for a tick or for another goroutine. The tracker never lets time move backward: while the clock reads earlier than a time already observed, decay pauses until the clock catches up.

func (*FairnessTracker) Close

func (ft *FairnessTracker) Close()

Close stops background rotation and releases the ticker. It is safe to call repeatedly or concurrently. Every caller waits for the rotation worker to exit; an in-flight rotation may finish before Close returns. RegisterRequest and ReportOutcome remain usable with the final active and standby structures, so Close leaves that pair open: only structures retired by rotation are closed. Do not call Close from inside a tracker callback: rotation may be waiting for that callback to return.

func (*FairnessTracker) Counters

func (ft *FairnessTracker) Counters() Counters

Counters returns the tracker's cumulative totals. It is cheap enough to call on every metrics scrape.

func (*FairnessTracker) RegisterRequest

func (ft *FairnessTracker) RegisterRequest(ctx context.Context, clientIdentifier []byte) *request.RegisterRequestResult

RegisterRequest records an incoming request and returns whether it should be throttled.

func (*FairnessTracker) ReportOutcome

func (ft *FairnessTracker) ReportOutcome(ctx context.Context, clientIdentifier []byte, outcome request.Outcome) *request.ReportOutcomeResult

ReportOutcome applies an outcome to the active and standby structures. For the same client, overlapping reports may run in either order, but both structures see the same order. Rotation never splits a single report. An outcome other than OutcomeSuccess or OutcomeFailure is ignored.

func (*FairnessTracker) RotationStatus

func (ft *FairnessTracker) RotationStatus() RotationStatus

RotationStatus returns a consistent snapshot, even when logging is disabled.

func (*FairnessTracker) Saturation

func (ft *FairnessTracker) Saturation() Saturation

Saturation scans the active structure and reports how full it is. The scan reads every bucket, so its cost grows with L×M: call it from a metrics scrape, not per request. Requests run alongside it. A rotation that comes due during the scan waits for it to finish, because rotation closes the structure it retires, and requests that arrive while that rotation is waiting wait with it.

type FairnessTrackerBuilder

type FairnessTrackerBuilder struct {
	// contains filtered or unexported fields
}

FairnessTrackerBuilder helps configure and construct a FairnessTracker.

func NewFairnessTrackerBuilder

func NewFairnessTrackerBuilder() *FairnessTrackerBuilder

NewFairnessTrackerBuilder returns a new builder pre-populated with the default configuration.

func (*FairnessTrackerBuilder) Build

Build constructs a tracker using the configuration accumulated on the builder. To build from a complete configuration instead, pass it to NewFairnessTracker.

func (*FairnessTrackerBuilder) SetDecisionSource

func (bl *FairnessTrackerBuilder) SetDecisionSource(source func() float64)

SetDecisionSource sets the function that supplies the uniform random number in [0, 1) behind each throttling decision. Leave it unset in production; a simulation can pass a seeded source to make decisions reproducible.

func (*FairnessTrackerBuilder) SetFinalProbabilityFunction

func (bl *FairnessTrackerBuilder) SetFinalProbabilityFunction(finalProbabilityFunction config.FinalProbabilityFunction)

SetFinalProbabilityFunction sets the function used to derive the final throttling probability from all buckets.

func (*FairnessTrackerBuilder) SetHashKeySource

func (bl *FairnessTrackerBuilder) SetHashKeySource(source io.Reader)

SetHashKeySource sets the reader that supplies bucket placement keys. Leave it unset in production so keys come from crypto/rand; a simulation can pass a seeded reader to make placement reproducible.

func (*FairnessTrackerBuilder) SetIncludeStats

func (bl *FairnessTrackerBuilder) SetIncludeStats(IncludeStats bool)

SetIncludeStats indicates whether the tracker should return detailed stats.

Example
package main

import (
	"context"
	"fmt"

	"github.com/satmihir/fair/v2/pkg/tracker"
)

func main() {
	builder := tracker.NewFairnessTrackerBuilder()
	builder.SetIncludeStats(true)
	builder.SetL(2)
	trk, err := builder.Build()
	if err != nil {
		panic(err)
	}
	defer trk.Close()

	result := trk.RegisterRequest(context.Background(), []byte("client-42"))
	if stats := result.ResultStats; stats != nil {
		fmt.Println("final probability:", stats.FinalProbability)
		fmt.Println("selected buckets:", len(stats.BucketIndexes))
		fmt.Println("bucket probabilities:", stats.BucketProbabilities)
	}
}
Output:
final probability: 0
selected buckets: 2
bucket probabilities: [0 0]

func (*FairnessTrackerBuilder) SetL

func (bl *FairnessTrackerBuilder) SetL(L uint32)

SetL sets the number of levels used by the tracker.

func (*FairnessTrackerBuilder) SetLambda

func (bl *FairnessTrackerBuilder) SetLambda(Lambda float64)

SetLambda sets the decay rate for bucket probabilities. Zero disables decay; rotation still ends a penalty (see SetRotationFrequency).

func (*FairnessTrackerBuilder) SetM

func (bl *FairnessTrackerBuilder) SetM(M uint32)

SetM sets the number of buckets per level.

func (*FairnessTrackerBuilder) SetPd

func (bl *FairnessTrackerBuilder) SetPd(Pd float64)

SetPd sets the decrement probability used on successful requests.

func (*FairnessTrackerBuilder) SetPi

func (bl *FairnessTrackerBuilder) SetPi(Pi float64)

SetPi sets the increment probability used on failed requests.

func (*FairnessTrackerBuilder) SetRotationFrequency

func (bl *FairnessTrackerBuilder) SetRotationFrequency(rotationFrequency time.Duration)

SetRotationFrequency configures how often the internal structures are rotated. A client that stays fully throttled has its own failures discarded at the second successful rotation after the last one it reported, whatever the decay rate is: nominally one to two intervals.

type FairnessTrackerError

type FairnessTrackerError struct {
	*utils.BaseError
}

FairnessTrackerError is returned when the tracker encounters a recoverable error that should be surfaced to the caller.

func NewFairnessTrackerError

func NewFairnessTrackerError(wrapped error, msg string, args ...any) *FairnessTrackerError

NewFairnessTrackerError creates a new FairnessTrackerError that wraps another error with additional context.

type RotationStatus

type RotationStatus struct {
	// Rotations counts successful promotions over the lifetime of the tracker.
	Rotations uint64
	// Failures counts failed attempts over the lifetime of the tracker.
	Failures uint64
	// LastError is the most recent rotation error, cleared on successful rotation.
	LastError error
}

RotationStatus describes background rotation attempts for one tracker. The initial construction is not counted as a rotation attempt.

type Saturation

type Saturation struct {
	// Levels and BucketsPerLevel are the structure's dimensions (L and M).
	Levels          int
	BucketsPerLevel int
	// PenalizedByLevel holds, for each level, the number of buckets at or
	// above PenalizedThreshold after decay.
	PenalizedByLevel []int
	// MeanProbability is the average throttling probability over all buckets:
	// 0 for an empty structure, 1 when every bucket blocks every request.
	MeanProbability float64
}

Saturation describes how much of the active structure is carrying penalties. Clients share buckets, so as more buckets are penalized, more well-behaved clients are throttled for someone else's failures. A structure fills up when there are more misbehaving clients than it was sized for, or when one caller spreads failures across many identifiers.

func (Saturation) PenalizedFraction

func (s Saturation) PenalizedFraction() float64

PenalizedFraction is the share of all buckets that are penalized.

func (Saturation) SharedPenaltyChance

func (s Saturation) SharedPenaltyChance() float64

SharedPenaltyChance estimates the chance that every bucket selected for a client with no failures of its own is at or above PenalizedThreshold. It is the product of each level's penalized share.

It measures how much of the structure is occupied, not how often such a client is rejected. The rejection probability is whatever the buckets hold: with a single bucket at 0.01, this returns 1, yet a client sharing that bucket is throttled 1 time in 100. Alert on it rising: the tuner sizes a structure to keep it at or below 0.0001.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL