config

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: 4 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

Constants

View Source
const MaxRotationBytes = 64 << 20

MaxRotationBytes is the per-tracker budget for estimated peak bucket storage. It applies to tuned and manual configurations alike, not to process-wide RSS.

Variables

This section is empty.

Functions

func CalculateL

func CalculateL(B, M uint32, p float64) uint32

CalculateL computes the levels needed for a collision probability at most p with B buckets per level and M bad flows: (1 - (1 - 1/B)^M)^L <= p. It returns 0 if B < 2, M == 0, p is not in (0, 1), or the required level count cannot be represented by a uint32.

Types

type FairnessTrackerConfig

type FairnessTrackerConfig struct {
	// Size of the row at each level
	M uint32
	// Number of levels in the structure
	L uint32
	// The delta P to add to a bucket's probability when there's an error
	Pi float64
	// The delta P to subtract from a bucket's probability when there's a success
	Pd float64
	// The exponential decay rate for the probabilities, per second. Zero
	// disables decay but not forgiveness: rotation still ends a penalty (see
	// RotationFrequency).
	Lambda float64
	// The interval between rotations. It also bounds how long a client's own
	// feedback is remembered: a client that stays fully throttled reports no
	// outcomes, so its failures are discarded at the second successful
	// rotation after the last one it reported, whatever Lambda is. That is
	// nominally one to two intervals. It is not a deadline for admission: a
	// failed rotation delays it, and buckets the client shares with others
	// can still be penalized. See "How long a penalty lasts" in the README.
	RotationFrequency time.Duration
	// Include result stats. Useful for debugging but may slightly affect performance.
	IncludeStats bool
	// The function to choose the final probability from all the bucket probabilities
	FinalProbabilityFunction FinalProbabilityFunction
	// HashKeySource supplies the secret keys that place clients in buckets.
	// Sixteen bytes are read for every structure a tracker builds, including
	// one at each rotation. Leave it nil in production so that keys come from
	// crypto/rand. A simulation or test can supply a seeded reader to make
	// placement reproducible; it has no effect on the random draw behind each
	// throttling decision. A reader shared by several trackers must be safe
	// for concurrent use.
	HashKeySource io.Reader
	// DecisionSource returns the uniform random number in [0, 1) behind each
	// throttling decision: a request is throttled when the number is below
	// the client's probability, so probability 0 never throttles. Leave it
	// nil in production to use math/rand's generator. A simulation or test
	// can supply a seeded source to make decisions reproducible; calling
	// rand.Seed no longer does that, because it has had no effect since
	// Go 1.24. The function must be safe for concurrent use if requests are
	// made concurrently.
	DecisionSource func() float64
}

FairnessTrackerConfig defines the parameters for the underlying data structure used by the fairness tracker. Most users will rely on GenerateTunedStructureConfig to populate this struct.

func DefaultFairnessTrackerConfig

func DefaultFairnessTrackerConfig() *FairnessTrackerConfig

DefaultFairnessTrackerConfig returns a configuration that should work well for most applications without any additional tuning. It panics only if the library's own default constants stop producing a valid configuration, which would be a bug in the library and is covered by its tests.

func GenerateTunedStructureConfig

func GenerateTunedStructureConfig(expectedClientFlows, bucketsPerLevel, tolerableBadRequestsPerBadFlow uint32) (*FairnessTrackerConfig, error)

GenerateTunedStructureConfig creates a configuration tuned for the expected scale of your application.

Parameters:

  • expectedClientFlows: number of concurrent clients you expect.
  • bucketsPerLevel: number of buckets per level in the data structure.
  • tolerableBadRequestsPerBadFlow: number of failed requests tolerated before a flow is fully blocked.

All arguments must be positive. At least two buckets per level are needed to avoid certain collisions. An unrepresentable level count is an error.

func (*FairnessTrackerConfig) ValidateStructure

func (c *FairnessTrackerConfig) ValidateStructure() error

ValidateStructure checks the parameters needed by the underlying data structure. Dimensions must fit the rotating tracker's allocation budget. RotationFrequency is checked separately by callers that start a real ticker.

type FinalProbabilityFunction

type FinalProbabilityFunction func([]float64) float64

FinalProbabilityFunction chooses a final probability from a slice of bucket probabilities.

var (

	// MinFinalProbabilityFunction returns the smallest probability in the
	// slice. It is the default implementation used by the tracker. An empty
	// slice gives 0: with no buckets there is nothing to throttle on. A
	// tracker never passes one, because it always has at least one level.
	MinFinalProbabilityFunction FinalProbabilityFunction = func(buckets []float64) float64 {
		if len(buckets) == 0 {
			return 0
		}

		minVal := 1.
		for _, b := range buckets {
			minVal = math.Min(minVal, b)
		}

		return minVal
	}

	// MeanFinalProbabilityFunction returns the mean of all bucket
	// probabilities and can be used in scenarios where the minimum value is
	// too strict. An empty slice gives 0, as for MinFinalProbabilityFunction.
	MeanFinalProbabilityFunction FinalProbabilityFunction = func(buckets []float64) float64 {
		if len(buckets) == 0 {
			return 0
		}

		var total float64
		for _, b := range buckets {
			total += b
		}

		return total / float64(len(buckets))
	}
)

Jump to

Keyboard shortcuts

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