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 ¶
New constructs a Limiter. Does NOT start the background refresh loop — call Start(ctx) for that, typically from main / Init.
func (*Limiter) Allow ¶
Allow returns true if a request keyed by `key` should proceed. Decision order:
- If key is in the blocked set (in-memory cache of BlockStore), deny + record a Hit asynchronously.
- If the per-key token bucket allows the request, permit.
- 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 ¶
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 ¶
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.
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.