limiter

package module
v0.0.0-...-b3b8c5a Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 24 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.

README

API Rate Limit with DynamoDB

A distributed rate limiter backed by DynamoDB, using GCRA (Generic Cell Rate Algorithm).

How it works

Each bucket keeps a single value, the theoretical arrival time (TAT), and a request is decided only with conditional UpdateItem. No read is needed: on a failed condition DynamoDB returns the current item (ReturnValuesOnConditionCheckFailure), which tells whether the bucket is idle, busy or exhausted.

case DynamoDB calls
allowed, idle bucket 1 write
allowed, busy bucket 2 writes
denied 1 failed write, then served by a local cache until RetryAfter (0 calls)

GCRA is equivalent to a token bucket that refills token_per_interval tokens per interval up to bucket_size.

Shards

A bucket is split into shards so that a single partition key stays below DynamoDB's 1000 WCU per second. A token bucket allows at most bucket_size + token_per_interval * 1s / interval requests in any second, no matter how many instances (e.g. Lambda) send them, and an allowed request takes up to 2 writes. The default number of shards keeps each shard under 500 allowed requests per second. Set shards explicitly when the expected traffic per bucket id is known.

Requests try shards in random order and skip shards known to be exhausted, up to 2 writes per request. Decision.Remaining is the value of the selected shard.

Registration

PrepareTokens writes a registration item <id>#meta. Shard items <id>#<n> are created on demand, so shards (and the bucket settings) can be changed at any time without re-registering ids. Registered ids are cached per instance (registration_cache, 1 minute by default); RevokeTokens deletes the registration item and other instances stop allowing the id when the cache expires. Ids registered by the token bucket version are still accepted.

Shard items expire by DynamoDB TTL one hour after their bucket becomes full again (or after record_ttl in anonymous mode, whichever is later), so idle, revoked and orphan items do not accumulate.

Usage

rl, err := limiter.New(cfg, dynamodbClient, limiter.WithLogger(logger))

d, err := rl.Allow(ctx, apiKey)
// d.Allowed, d.Remaining, d.RetryAfter
// errors: limiter.ErrInvalidBucketID, limiter.ErrStoreThrottled (DynamoDB capacity), limiter.ErrInternal

net/http middleware (responds 429 with Retry-After for both the rate limit and DynamoDB throttling, which is counted separately by the limiter.dynamodb.throttles metric; sets X-RateLimit-Remaining):

mw := limiterhttp.Middleware(rl, limiterhttp.HeaderKey("x-api-key"), // or limiterhttp.RemoteIP
	limiterhttp.WithTimeout(500*time.Millisecond),                    // bound the latency added by DynamoDB
	limiterhttp.WithSkip(func(r *http.Request) bool { return r.URL.Path == "/healthz" }),
	limiterhttp.WithErrorHandler(func(r *http.Request, err error) { /* log */ }),
	limiterhttp.WithRejectHandler(func(w http.ResponseWriter, r *http.Request, res *limiterhttp.Result) { /* custom body */ }),
)
h := mw(next) // the next handler can read limiterhttp.FromContext(r.Context())

X-RateLimit-Remaining is exact for a single shard and an underestimate for sharded buckets.

Config

Only table_name, token_per_interval and bucket_size are required:

table_name: rate_limit
token_per_interval: 20
bucket_size: 40

All options with their defaults:

table_name: rate_limit
token_per_interval: 20
bucket_size: 40
interval: 60s             # default 60s
# shards: 4               # default: computed from the peak requests per second (see Shards)
additional:
  fail_open: false        # allow requests when DynamoDB fails
  anonymous:              # accept unregistered ids, e.g. IP addresses
    record_ttl: 24h
  negative_cache:         # cache unregistered ids
    size: 1000
    ttl: 5m
  registration_cache:     # cache registered ids (revocation delay)
    size: 10000
    ttl: 1m

Unknown keys are rejected.

Metrics

The library records OpenTelemetry metrics through the global MeterProvider (or limiter.WithMeterProvider). It depends only on the OpenTelemetry API; configure an SDK and exporter in your application.

metric attributes
limiter.decisions limiter.table, limiter.result (allowed / denied / contention / invalid / error), limiter.source (dynamodb / cache)
limiter.dynamodb.throttles limiter.table, aws.dynamodb.operation

contention is a denial because every shard tried was busy with concurrent updates, not over the rate limit.

Bucket ids are never recorded in metrics, and appear in errors and logs only as a hash.

Logging

WithLogger takes a *slog.Logger; logs are discarded by default. The library logs only at debug level for troubleshooting. Errors are returned to the caller (log them there, e.g. with limiterhttp.WithErrorHandler) and counted by metrics, so they are not logged twice.

Test

$ make start-local
$ make test

Documentation

Index

Constants

View Source
const DefaultInterval = 60 * time.Second

DefaultInterval is used when Config.Interval is zero.

Variables

View Source
var (

	// ErrStoreThrottled means DynamoDB throttled the request. It is a server side capacity problem,
	// not that the caller exceeded its rate limit. The caller's rate limit is reported by Decision.Allowed.
	ErrStoreThrottled = errors.New("dynamodb throttled the request")
	// ErrInternal means DynamoDB or the limiter failed unexpectedly.
	ErrInternal = errors.New("internal error")
	// ErrInvalidBucketID means the bucket id is empty, too long or not registered.
	ErrInvalidBucketID = errors.New("invalid bucket id")
)

Functions

func CreateTable

func CreateTable(ctx context.Context, tableName string, client *dynamodb.Client) error

CreateTable creates a table for the limiter and enables TTL. It does nothing if the table exists.

Types

type AdditionalConfig

type AdditionalConfig struct {
	NegativeCache *NegativeCacheConfig `json:"negative_cache,omitempty"`
	// RegistrationCache caches registered bucket ids. Revoked ids are allowed until the entry expires.
	RegistrationCache *RegistrationCacheConfig `json:"registration_cache,omitempty"`
	Anonymous         *AnonymousConfig         `json:"anonymous,omitempty"`
	// FailOpen allows requests when DynamoDB fails. Requests are denied by default (fail-closed).
	FailOpen bool `json:"fail_open,omitempty"`
}

type AnonymousConfig

type AnonymousConfig struct {
	RecordTTL time.Duration `json:"record_ttl"`
}

AnonymousConfig allows not registered bucket id. This is used for such as an IP address basis throttling.

type Config

type Config struct {
	TableName        string        `json:"table_name"`
	TokenPerInterval int64         `json:"token_per_interval"`
	BucketSize       int64         `json:"bucket_size"`
	Interval         time.Duration `json:"interval,omitempty"`
	// Shards is the number of shards per bucket. It is computed from the worst requests per second when zero.
	// Set it explicitly when the expected traffic per bucket id is known.
	// It can be changed at any time; shard items are created on demand.
	Shards           int64             `json:"shards,omitempty"`
	AdditionalConfig *AdditionalConfig `json:"additional,omitempty"`
}

func NewConfig

func NewConfig(r io.Reader) (*Config, error)

type DDBClient

DDBClient is the subset of *dynamodb.Client used by the limiter.

type Decision

type Decision struct {
	// Allowed reports whether the request is within the rate limit.
	Allowed bool
	// Remaining is the estimated number of requests that can be allowed immediately.
	// It is the value of the selected shard.
	Remaining int64
	// RetryAfter is how long to wait until a request is allowed. Zero when Allowed.
	RetryAfter time.Duration
}

Decision is the result of Allow.

type LimitPreparer

type LimitPreparer interface {
	Limiter
	Preparer
}

type Limiter

type Limiter interface {
	// Allow consumes a token of the bucket.
	// An error is returned with a Decision. Decision.Allowed is false on errors unless fail-open is enabled.
	Allow(ctx context.Context, bucketID string) (Decision, error)
}

type NegativeCacheConfig

type NegativeCacheConfig struct {
	Size int           `json:"size"`
	TTL  time.Duration `json:"ttl,omitempty"`
}

NegativeCacheConfig configures negative cache for invalid bucket ids. Size is the maximum number of entries. specifying 0 means to disable cache. TTL is how long an entry is kept. 5 minutes by default.

type Opt

type Opt func(rl *RateLimit)

Opt configures RateLimit.

func WithFailOpen

func WithFailOpen() Opt

WithFailOpen allows requests when DynamoDB fails. The error is still returned.

func WithLogger

func WithLogger(logger *slog.Logger) Opt

WithLogger sets a logger. Logs are discarded by default.

func WithMeterProvider

func WithMeterProvider(mp metric.MeterProvider) Opt

WithMeterProvider sets the OpenTelemetry MeterProvider. The global MeterProvider is used by default, which is a no-op until an OpenTelemetry SDK is configured.

type Preparer

type Preparer interface {
	// PrepareTokens registers a bucket id with a full bucket.
	PrepareTokens(ctx context.Context, bucketID string) error
}

type RateLimit

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

func New

func New(cfg *Config, client DDBClient, opts ...Opt) (*RateLimit, error)

New returns a RateLimit for cfg. client is usually a *dynamodb.Client.

func (*RateLimit) Allow

func (l *RateLimit) Allow(ctx context.Context, bucketID string) (Decision, error)

Allow consumes a token of the bucket.

A sharded bucket tries shards in random order. Shards known to be exhausted (the local deny cache) are skipped, and a shard denied by DynamoDB is cached and the next shard is tried, up to maxShardTries writes. Without this fallback a request could be denied while other shards still have tokens.

func (*RateLimit) PrepareTokens

func (l *RateLimit) PrepareTokens(ctx context.Context, bucketID string) error

PrepareTokens registers the bucket id with a full bucket. An existing bucket is reset.

func (*RateLimit) RevokeTokens

func (l *RateLimit) RevokeTokens(ctx context.Context, bucketID string) error

RevokeTokens deletes the registration of the bucket id. Other instances keep allowing it until their registration cache entries expire (additional.registration_cache.ttl). Shard items expire by TTL. Revoking an unregistered id is not an error.

type RegistrationCacheConfig

type RegistrationCacheConfig struct {
	Size int           `json:"size"`
	TTL  time.Duration `json:"ttl,omitempty"`
}

RegistrationCacheConfig configures the cache of registered bucket ids. Size is the maximum number of entries. specifying 0 means to disable cache (a read per request). TTL is how long an entry is kept. 1 minute by default.

type Revoker

type Revoker interface {
	// RevokeTokens deletes the registration of a bucket id.
	RevokeTokens(ctx context.Context, bucketID string) error
}

Directories

Path Synopsis
Package limiterhttp provides net/http middleware for the limiter.
Package limiterhttp provides net/http middleware for the limiter.
Package mock_limiter is a generated GoMock package.
Package mock_limiter is a generated GoMock package.

Jump to

Keyboard shortcuts

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