ratelimit

package
v0.3.0 Latest Latest
Warning

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

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

Overview

Package ratelimit is the abuse-protection layer shared by every HB Labs HTTP service. Two concerns wrapped behind one Limiter:

  • Hot path: a token bucket per key (typically client IP) using `golang.org/x/time/rate`. Cheap, in-memory, per-pod. Absorbs 99% of casual flooding without touching any external store.
  • Cold path: a BlockStore (implemented by the app, e.g. on its database) that persists explicit bans. When a key trips the bucket StrikesToBan times within StrikeWindow, the Limiter records a long-lived ban (BanFor) so the abuser stays blocked across restarts and across pods. A background goroutine refreshes the in-memory blocked set from the store every RefreshInterval so manual bans (or bans from peer pods) propagate within a bounded delay.

For instant cross-pod propagation (no waiting for the next refresh tick) services should subscribe to the NATS subject `ratelimit.block.created` and call Limiter.ApplyRemoteBlock when an event lands. Pull-based refresh stays as the durable fallback.

Wire it in like:

store := myapp.NewBlockStore(db) // any BlockStore; nil keeps bans in memory
rl := ratelimit.New(ratelimit.Options{
    Rate:        rate.Every(12 * time.Second),
    Burst:       3,
    BlockStore:  store,
    BlockReason: "waitlist_flood",
})
rl.Start(ctx)
mux.Handle("/api/waitlist", rl.Middleware(func(r *http.Request) string {
    return clientIP(r)
})(serveWaitlist))

Same Limiter is safe to mount under several routes, but if you want different policies per endpoint (e.g. login = 1/sec, signup = 5/min), build one Limiter per policy.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BlockStore

type BlockStore interface {
	// Add records a block for key until expiresAt with the given
	// reason. Idempotent: re-adding an existing key extends the
	// expiry and bumps the recorded reason.
	Add(ctx context.Context, key, reason string, expiresAt time.Time) error
	// Hit signals that a blocked key tried again. Best-effort —
	// useful for forensics ("this attacker hit us 4321 times after
	// the ban started"); failures are non-fatal.
	Hit(ctx context.Context, key string) error
	// Snapshot returns the currently-active blocks, key → expiry.
	// The Limiter calls this periodically to refresh its in-memory
	// view; implementations should NOT include already-expired rows.
	Snapshot(ctx context.Context) (map[string]time.Time, error)
}

BlockStore persists explicit bans. Implementations are expected to be safe for concurrent use; the Limiter calls them from the request goroutine (Add/Hit) and from a background loop (Snapshot).

type Limiter

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

Limiter is the public type. Build it with New, then call Start once before serving traffic and Stop on shutdown. Allow / Middleware are safe for concurrent use.

func New

func New(opts Options) *Limiter

New constructs a Limiter. Does NOT start the background refresh loop — call Start(ctx) for that, typically from main / Init.

func (*Limiter) Allow

func (l *Limiter) Allow(ctx context.Context, key string) bool

Allow returns true if a request keyed by `key` should proceed. Decision order:

  1. If key is in the blocked set (in-memory cache of BlockStore), deny + record a Hit asynchronously.
  2. If the per-key token bucket allows the request, permit.
  3. Otherwise increment the strike counter; on the StrikesToBan-th strike within StrikeWindow, persist a ban via BlockStore (if configured) and add to the in-memory blocked set.

Allow never blocks on I/O — BlockStore writes happen in a goroutine. Allow itself only touches in-memory state.

func (*Limiter) ApplyRemoteBlock

func (l *Limiter) ApplyRemoteBlock(key string, expiresAt time.Time)

ApplyRemoteBlock applies a ban that originated outside this pod — typically an event from the NATS `ratelimit.block.created` stream published by a sibling pod or by ops tooling. The key starts being rejected on this pod immediately, without waiting for the next BlockStore refresh tick.

Idempotent: a later expiresAt extends the ban, an earlier one is ignored. Past expiries are dropped silently (the event was stale).

func (*Limiter) Middleware

func (l *Limiter) Middleware(keyFn func(*http.Request) string) func(http.Handler) http.Handler

Middleware wraps an http.Handler with Allow. keyFn extracts the rate-limit key from the request (typically a closure around a trusted client-IP helper); when it returns "" the request bypasses the limiter (use that to exempt internal traffic).

On deny: 429 with a Retry-After header derived from BanFor when the key is on the blocklist, or from the bucket's reservation otherwise. Body is a tiny text — APIs that need JSON should wrap the response writer.

func (*Limiter) Start

func (l *Limiter) Start(ctx context.Context)

Start kicks off the background blocklist refresher and the idle-bucket sweeper. Safe to call multiple times — only the first call starts the goroutines. Pass a long-lived context; the goroutines exit when Stop is called or ctx is cancelled.

func (*Limiter) Stop

func (l *Limiter) Stop()

Stop signals the background goroutines to exit. Idempotent.

type Options

type Options struct {
	// Rate is the steady-state refill rate of the per-key bucket.
	// Default: rate.Every(12 * time.Second) → 5 req/min.
	Rate rate.Limit
	// Burst is the bucket capacity — how many requests a key can
	// fire in quick succession before being throttled to Rate.
	// Default: 3.
	Burst int

	// StrikesToBan is how many over-limit requests within
	// StrikeWindow trigger a persisted ban. Default: 5.
	StrikesToBan int
	// StrikeWindow is the rolling window for counting strikes.
	// Default: 5 * time.Minute.
	StrikeWindow time.Duration
	// BanFor is the TTL of a persisted ban. Default: 24 * time.Hour.
	BanFor time.Duration

	// BlockStore persists bans across pod restarts and shares them
	// across replicas. nil = memory-only (bans evaporate on
	// restart, no cross-pod sync). Production: pass a persistent BlockStore.
	BlockStore BlockStore

	// BlockReason is recorded on the persisted block row so an
	// admin reviewing the table can tell which endpoint triggered
	// the ban. Default: "rate_limit_exceeded".
	BlockReason string

	// RefreshInterval controls how often the in-memory blocked set
	// is reloaded from BlockStore. Bounds how stale a remote ban
	// (manual ops, sibling pod) can be on this pod. Default: 60s.
	// For sub-second cross-pod propagation wire NATS into
	// ApplyRemoteBlock — refresh is the durable fallback.
	RefreshInterval time.Duration

	// Logger records diagnostic events (BlockStore failures,
	// escalations, etc.). nil = log.Default. *slog.Logger satisfies
	// this naturally, so existing callers don't need to change.
	Logger logger

	// OnBan is called from the request goroutine the moment a key
	// trips StrikesToBan and earns a persisted ban. Use it to
	// publish a NATS `ratelimit.block.created` event so peer pods
	// can apply the ban without waiting for the next refresh tick.
	// Receives a detached context — do NOT inherit a request ctx
	// here, the publish should outlive the request that triggered
	// the ban. nil = no-op.
	OnBan func(ctx context.Context, key, reason string, expiresAt time.Time)
}

Options configures a Limiter. Zero values pick the defaults documented per-field — sane for a public POST endpoint behind Cloudflare. Override what makes sense for your endpoint.

Jump to

Keyboard shortcuts

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