middleware

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 40 Imported by: 0 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 middleware provides HTTP middleware for the Hardcount API server. Includes rate limiting, idempotency keys, Prometheus metrics, CORS, and cursor-based pagination helpers.

Index

Constants

View Source
const (
	DeadLetterPermanent   = "permanent"
	DeadLetterMaxAttempts = "max_attempts"
)

Dead-letter causes.

Variables

This section is empty.

Functions

func AuditCoverage

func AuditCoverage(isExempt func(method, routePattern string) bool) func(http.Handler) http.Handler

AuditCoverage returns a middleware that DETECTS uncovered mutations. It is a PURE OBSERVER.

It replaces the AuditLog catch-all, which "guaranteed" coverage by writing a row for any mutating /v1 request no handler had claimed — inferring the action and resource from the URL and sniffing the response body for a label. That invented false permanent records in an append-only compliance log (a pricing rule deleted from a meter was recorded as "deleted meter X"), and it covered only the /v1 block, so /v1/auth, /v1/tenants (since removed), /v1/public/*, /v1/webhooks and /v1/bootstrap got nothing at all (ADR-090, RC1 + RC2). Coverage is now DECLARED (the route-audit registry) and EMITTED in the business transaction (audit.Logger.LogInTx). This middleware only reports when reality diverges.

Two invariants, both load-bearing:

  1. It NEVER MUTATES THE RESPONSE. No status swap, no body rewrite, no error injection. The catch-all's response-swapping ancestor (the per-tenant fail-closed 503) is what caused the idempotency-poisoning bug in ADR-089: the business tx had ALREADY committed, so the 503 was a lie — and the Idempotency layer cached that lie for 24h, stranding the real response and inviting a fresh-key double-mutation. Telemetry does not get to overwrite a committed money mutation's answer. Ever.

  2. It NEVER BUFFERS THE BODY. chi's WrapResponseWriter captures the status with a pass-through Write (only Tee() buffers — we never call it) and preserves http.Flusher / http.Hijacker / io.ReaderFrom through typed wrappers. The catch-all buffered every response to sniff a label out of it, and its buffer implemented none of those interfaces — which is why the CSV exports, on a route given a 5-minute timeout precisely BECAUSE it streams, silently accumulated in memory instead of streaming.

isExempt resolves (method, canonical route pattern) against the registry; it is injected because the registry lives in package api (which imports this package).

func AuditUncoveredMutationsByRoute

func AuditUncoveredMutationsByRoute() map[string]float64

AuditUncoveredMutationsByRoute snapshots the uncovered-mutation counter, keyed by route pattern.

It exists so a sibling package's end-to-end suite can assert ZERO uncovered mutations across every route it drives (internal/api's TestMain) — the runtime half of ADR-090's coverage model, complementing the registry's build-time two-way diff. Operators read this signal from Prometheus; this accessor is the in-process equivalent, and it is deliberately narrow: it collects THIS counter only. Gathering the default registry instead would execute every registered collector, including the queue-depth GaugeFuncs, which open a database transaction per scrape.

func CORS

func CORS(allowedOrigins []string) func(http.Handler) http.Handler

CORS lets browser pages on the allowed origins call the API and read the response. github.com/rs/cors answers preflights and sets the headers; Hardcount only decides which origins match.

allowedOrigins comes from config.ParseCORSOrigins, the parser behind the boot check. Two shapes:

  • A bare "*" allows every origin, without credentials. The answer is a literal "*" with no Access-Control-Allow-Credentials, so browsers send no sign-in cookie: a page on another site can call the API with an API key but cannot read a signed-in operator's data.
  • Listed origins match exactly, ignoring case: the same rule as CSRFGuard, which gets the same list. A listed origin may send the sign-in cookie, so a dashboard served from another address can sign in.

The match is ours, not rs/cors's AllowedOrigins, because that option reads an empty list as every origin and an entry with a * inside it as a prefix-and-suffix pattern ("h*" would allow every https origin). The boot check refuses such entries; here they simply match nothing.

An OPTIONS request without Access-Control-Request-Method is not a preflight and goes on to the router.

func CSRFGuard

func CSRFGuard(allowedOrigins []string) func(http.Handler) http.Handler

CSRFGuard is the server-side CSRF defense for the cookie-authenticated dashboard surface. It rejects a state-changing request that a *browser* initiated from a site other than the trusted dashboard, before the request can spend the operator's ambient session cookie.

Why this exists (and why CORS did not already cover it)

CSRF is an ambient-authority problem: the browser attaches hardcount_session to every request to the API automatically, so any page the operator visits can cause a request that carries it. SameSite=Lax narrows this (it withholds the cookie from most cross-site requests) but is not sufficient on its own — it still permits top-level GET navigation, and it does nothing about a cookie being *set* cross-site, which is how the login-fixation variant worked (an attacker's cross-site POST to /v1/auth/login minted and set THEIR session in the victim's browser). The existing CORS middleware is not a defense here at all: it governs whether the attacker's JS may *read the response*, never whether the request *executes* — a form POST or any "simple request" runs the handler regardless of CORS, and a login-fixation attacker never needs to read anything, the Set-Cookie side effect already happened.

The rule

For unsafe methods (POST/PUT/PATCH/DELETE), unless the request carries an Authorization: Bearer header, the request must be same-site:

  • A Bearer request is EXEMPT **only when it carries no session cookie**. A bearer key is a non-ambient credential — an attacker cannot make a victim's browser attach it — so the SDK/server-to-server path (bearer, no cookie) is CSRF-immune and legitimately sends no Origin. But a request bearing BOTH a bearer header AND a session cookie is not a legitimate shape (the SDK has no cookie; the dashboard sends no bearer): it is the "add a junk Authorization header to trip the exemption, let the ambient cookie authenticate" move, which a CORS config that let the attacker's origin send credentials would otherwise let through a preflight (CORS `*` sends none; see CORS). Such a request is origin-checked, not exempted, so the dodge fails regardless of CORS config.
  • Otherwise the browser's Sec-Fetch-Site (which page JS cannot forge) is the primary signal: same-origin and none pass; cross-site is rejected; **same-site passes only if its Origin is an allowlisted dashboard origin** — so a sibling subdomain (subdomain takeover, a user-content host) cannot ride the same-site label plus the Lax cookie into a mutation. Sec-Fetch- Site is absent only on pre-2020 browsers; there we fall back to the same Origin allowlist (the CORS_ALLOWED_ORIGINS list, so the two can't drift).
  • A request carrying NEITHER Sec-Fetch-Site NOR Origin is allowed. This is deliberately not fail-closed: a genuine cross-site attack requires a browser, and every browser that can run the dashboard sets at least one of those headers on a cross-site unsafe request — page JS cannot remove them. So "neither present" means the caller is not a browser (curl, an SDK, a server job); it holds no ambient cookie and cannot be the CSRF vector. Failing closed here would only break non-browser callers for no gain.

This guard belongs ONLY on the dashboard-serving route groups (/v1/auth and the cookie-or-bearer /v1 group). It must not wrap the Stripe webhook group (HMAC-authenticated, server-to-server, no Origin) or the unauthenticated public payment/invoice surfaces (they carry no operator session to abuse).

func CleanExpired

func CleanExpired(ctx context.Context, db *postgres.DB) (int, error)

CleanExpired removes expired idempotency keys across all tenants and returns the number of rows deleted. Runs cross-tenant by design (a background scheduler, not a per-request path), so it uses TxBypass to sidestep the tenant_isolation policy.

func Idempotency

func Idempotency(db *postgres.DB, ignore func(*http.Request) bool) func(http.Handler) http.Handler

Idempotency returns middleware that caches responses for POST/PUT/PATCH requests that include an Idempotency-Key header. If a request with the same key has been processed before, the cached response is returned.

Stripe-compatible enforcement:

  • Same key + same (method, path, body) → replay cached response (sets Idempotent-Replayed: true header).
  • Same key + different (method, path, body) → 422 idempotency_error (protects against client bugs that recycle a key across operations — e.g., retrying POST /invoices with a changed amount under the old key).

ignore (nil = none) names the requests that skip this middleware: the usage routes, whose dedup rule is the idempotency_key each event carries (stored once, forever). A second, header-level cache on top of it only added a 24 h answer replay and a 1 MB body read for the fingerprint, so those routes run as if no header was sent.

func InitLeaderLeaseLost

func InitLeaderLeaseLost(roles ...string)

InitLeaderLeaseLost exports hardcount_leader_lease_lost_total{role, reason="panicked"} at 0 for each role, at boot. The page row is increase(...[1h]) > 0, and a series first exported at 1 has no earlier sample, so the first panicked tick after a start never paged. Prometheus: export a default value such as 0 for any time series you know may exist. Only "panicked" is created: a heartbeat_timeout series created now would page on one timeout, which waits for the heartbeat fix (RL-F2).

func Metrics

func Metrics() func(http.Handler) http.Handler

Metrics returns middleware that records HTTP request metrics.

func MetricsAuth

func MetricsAuth(appEnv string, next http.Handler) http.Handler

MetricsAuth protects the /metrics endpoint with a bearer token. Without METRICS_TOKEN the endpoint is open outside production, for local dev. In production it answers 401 to everyone: the scrape is operational data and costs database queries, and an address allowlist in front of it stops holding once a load balancer makes every caller a private address. It refuses the scrape rather than the boot, so an install that does not scrape metrics keeps billing through the upgrade. appEnv is config.Config.Env.

func MetricsHandler

func MetricsHandler() http.Handler

MetricsHandler returns the Prometheus metrics HTTP handler.

func OpenRedis

func OpenRedis(ctx context.Context, url string) (*goredis.Client, error)

OpenRedis parses url, opens a client and verifies it with a Ping bounded by ctx. An empty url is not an error — it returns (nil, nil), the fail-open shape every limiter accepts. The caller decides the verdict: production REFUSES to boot on an error (cmd/hardcount/main.go), because the general and hosted-invoice limiters fail CLOSED without Redis and a replica would otherwise boot green and 429 its share of traffic; other environments warn and continue fail-open.

func ParseTrustedProxies

func ParseTrustedProxies(spec string) []*net.IPNet

ParseTrustedProxies parses a comma-separated TRUST_PROXY spec of CIDRs and/or bare IPs into networks. A bare IP becomes a /32 (IPv4) or /128 (IPv6). Empty input or "none" yields an empty slice, which means "trust no proxy" — forwarding headers are then never honored.

It uses config.ParseTrustProxy, the parser behind the boot check, which refuses to start on an entry that does not parse. An invalid entry is skipped here only for a caller that did not go through config.Load.

func RecordAutoChargeRetry

func RecordAutoChargeRetry(result string)

RecordAutoChargeRetry records an auto-charge retry result ("succeeded" or "failed").

func RecordBillingCycle

func RecordBillingCycle(generated int)

RecordBillingCycle records billing cycle metrics.

func RecordBillingCycleDuration

func RecordBillingCycleDuration(seconds float64)

RecordBillingCycleDuration records how long a billing cycle took.

func RecordBillingCycleError

func RecordBillingCycleError()

RecordBillingCycleError increments the billing cycle error counter.

func RecordCreditOperation

func RecordCreditOperation(opType string)

RecordCreditOperation records a credit operation by type ("grant", "usage", "expiry", "adjustment").

func RecordDunningRun

func RecordDunningRun(outcome string)

RecordDunningRun records a processed dunning run outcome ("succeeded" or "failed"). The outcome split backs the runbook's dunning-machinery alert on {outcome="failed"} — without it, failed runs had zero metric visibility.

func RecordEmailOutboxDeadLettered

func RecordEmailOutboxDeadLettered(cause string, live bool)

RecordEmailOutboxDeadLettered counts one email moved to 'failed'. Call it only when the mark applied.

func RecordLeaderLeaseLost

func RecordLeaderLeaseLost(role, reason string)

RecordLeaderLeaseLost counts a lost lease (leader.LostFunc adapter).

func RecordPaymentCharge

func RecordPaymentCharge(result string)

RecordPaymentCharge records a payment charge result ("succeeded" or "failed").

func RecordReconcilerSweep

func RecordReconcilerSweep(reconciler, mode string, advanced, errs int)

RecordReconcilerSweep records one recovery-reconciler sweep: a 'run' tick (always, so operators can alert on a reconciler that stops running), plus the items advanced and per-row errors this tick. `mode` is "live"/"test". Powers per-reconciler dashboards/alerts (e.g. a stuck tax-reversal backlog) — previously only auto-charge was metered.

func RecordScheduledCleanup

func RecordScheduledCleanup(table string, rows int)

RecordScheduledCleanup records rows purged by a scheduled cleanup task. Label values match the target table (e.g. "idempotency_keys", "payment_tokens") so operators can alert per-table on sudden surges.

func RecordSchedulerTick

func RecordSchedulerTick()

RecordSchedulerTick stamps the scheduler-liveness gauge; called by the same hook that feeds /health/ready.

func RecordStaleChargeHoldResolution

func RecordStaleChargeHoldResolution(result string)

RecordStaleChargeHoldResolution counts one stale-hold check (ADR-127). "cannot_ask" is a hold Stripe will not answer about (disconnected, key rejected, customer missing): those invoices stay blocked from charging until someone writes them off or fixes the connection, so alert on it being non-zero. A steady "failed" is Stripe unreachable.

func RecordStripeBreakerState

func RecordStripeBreakerState(state string)

RecordStripeBreakerState updates the global breaker state gauge. Called from the breaker's OnStateChange hook. Values mirror gobreaker's semantics: 0=closed (normal), 1=half_open (probing), 2=open (rejecting).

func RecordStripeKeyUnusable

func RecordStripeKeyUnusable(reason string)

RecordStripeKeyUnusable counts a charge not sent because the tenant's Stripe key was refused ("rejected") or is not connected ("not_configured").

func RecordUsageIngested

func RecordUsageIngested(count int)

RecordUsageIngested records usage event ingestion.

func RecordUsageUnpriced

func RecordUsageUnpriced(meterID string, live bool, quantity float64)

RecordUsageUnpriced adds the quantity of one meter's usage that an invoice was built without because no price matched it. live is the mode the invoice was built in.

func RecordWebhookDelivery

func RecordWebhookDelivery(status string)

RecordWebhookDelivery records a webhook delivery status ("succeeded", "failed", or "pending").

func RecordWebhookOutboxDeadLettered

func RecordWebhookOutboxDeadLettered(live bool)

RecordWebhookOutboxDeadLettered counts one webhook outbox row moved to 'failed' after its last attempt. Call it only when the mark applied.

func RecordWebhookOutboxEnqueueFailure

func RecordWebhookOutboxEnqueueFailure(eventType string)

RecordWebhookOutboxEnqueueFailure records a failed attempt to enqueue an event.

func Recoverer

func Recoverer(next http.Handler) http.Handler

Recoverer turns a handler panic into the JSON 500 every other internal error answers (respond.InternalError), and logs the panic with its stack. It replaces chi's Recoverer, which answered an empty 500.

http.ErrAbortHandler is re-panicked, as net/http expects: it aborts the response on purpose. A panic after the handler has started its answer cannot change it; the log still records the panic.

func RegisterLeaderStatus

func RegisterLeaderStatus(query func(context.Context) ([]LeaderStatusRow, error))

RegisterLeaderStatus wires the leader_status collector. Call once at boot; a second call panics (duplicate registration), which is the right outcome for a double-wire.

func RegisterQueueDepthGauges

func RegisterQueueDepthGauges(invoiceGrace time.Duration, count func(query string) (float64, error))

RegisterQueueDepthGauges exports the queue-depth gauges the shipped Grafana dashboard and runbook alert on. Pre-2026-07-06 the dashboard queried hardcount_email_outbox_pending / hardcount_webhook_outbox_pending / hardcount_dunning_active_runs masked by `OR vector(0)` — gauges the binary never exported, so the panels flatlined at 0 through a real backlog.

Gauges resolve at SCRAPE time via one COUNT each (cheap: partial/status indexes; 3s cap). A query failure reports -1 — visibly wrong rather than a healthy-looking 0.

func RequestID

func RequestID(next http.Handler) http.Handler

RequestID replaces chi's middleware.RequestID. It ALWAYS mints the id server-side and NEVER honours an inbound header.

chi's version does this (chi/v5 middleware/request_id.go):

requestID := r.Header.Get("X-Request-Id")   // <- client-controlled
if requestID == "" { requestID = <generated> }

which means any caller could choose the request_id that lands on their own audit_log rows — the column the audit UI presents as forensic correlation evidence, and the value support uses to join a customer's report back to server logs. An attacker could set it to a constant to make their actions unjoinable, collide it with an innocent tenant's traffic, or forge a value that "proves" an action came from somewhere it didn't. Correlation evidence an adversary can write is not evidence. CloudTrail's eventID, Stripe's request id, and GCP's insertId are all server-minted for exactly this reason.

Why we drop the inbound value entirely instead of keeping it for log correlation under a second key:

  • Nothing consumes it as INPUT. (The name still appears in the repo — in tests that forge the header to prove it is ignored, and in the docs that record this decision. An earlier version of this comment told you to grep and promised zero hits, which stopped being true the moment the regression test landed. Do not re-add a claim about grep output; state the property.) Historically the reason was: grep across the repo, web-v2 and docs: there are no hits. Hardcount's published contract is the Hardcount-Request-Id RESPONSE header (respond.go), which the dashboard captures (web-v2 lib/api.ts) and the docs point support at. That contract is unchanged.
  • Cross-service trace continuity belongs to W3C Trace Context, which mw.Tracing() (otelhttp) propagates from inbound headers. Be precise about what that buys today: tracing is a NO-OP unless OTEL_EXPORTER_OTLP_ENDPOINT is set (internal/platform/telemetry), so on a default deployment there is no cross-service correlation channel at all. That is a real, if small, ACCEPTED LOSS: a caller that wants to correlate its own request with a Hardcount audit row must now read the Hardcount-Request-Id response header rather than dictate the id up front. We take that trade because an inbound X-Request-Id would be a second, weaker, UNAUTHENTICATED channel — and it is the one that lands in the compliance log. Closure trigger: a caller with a concrete cross-service correlation need → wire OTLP, not a client-chosen id.
  • Recording the client's string anywhere on the row — even under an honestly-named metadata key — puts unverified client input into a permanent append-only compliance record. The audit redesign's rule is that nothing unverified enters that log; a key nobody reads is not worth the exception.

The id is stored under chi's own RequestIDKey, so chimw.GetReqID(ctx) — the accessor audit.Logger, telemetry.ContextHandler, respond.go and payment/stripe all already call — keeps working unchanged, and there is exactly one place where a request id is born.

func SecurityHeaders

func SecurityHeaders(appEnv string) func(http.Handler) http.Handler

SecurityHeaders adds standard security headers to all responses. These are defense-in-depth measures that enterprise security audits expect. appEnv is config.Config.Env.

func SplitRateLimit

func SplitRateLimit(match func(*http.Request) bool, special, base *RateLimiter) func(http.Handler) http.Handler

SplitRateLimit routes each request to one of two limiters: `special` when match(r) is true, `base` otherwise. Backs the ingest-vs-CRUD split — the ingest surface (usage events + LiteLLM callbacks, one POST per LLM call) needs a bucket orders of magnitude larger than the operator-CRUD default, and squeezing it through the general bucket silently dropped revenue data (LiteLLM retries only on 5xx, so every 429 was a permanently lost event).

func Timeout

func Timeout(d time.Duration) func(http.Handler) http.Handler

Timeout ends the request's context after d. A handler that has written nothing when the time runs out gets the JSON 504 (respond.Timeout). One that already started its answer keeps it. It replaces chi's Timeout, which answered an empty 504.

func TraceRequestAttrs

func TraceRequestAttrs(path func(*http.Request) string) func(http.Handler) http.Handler

TraceRequestAttrs corrects the request span before it ends. otelhttp sets url.path to the raw path, which on the public pages carries a capability token, and client.address to the left-most X-Forwarded-For entry, which any client can write. After the handler returns, this sets:

  • the span name to "{method} {route}" (method alone when nothing routed),
  • http.route to chi's route pattern,
  • url.path to path(r), which must leave no token in the path,
  • client.address to audit.ExtractClientIP, the trusted client IP.

Mount it after Tracing and TrustedClientIP and before anything that can answer without routing (CORS preflight), so every span passes through it.

func Tracing

func Tracing() func(http.Handler) http.Handler

Tracing returns middleware that creates OpenTelemetry spans for each HTTP request. Propagates trace context from incoming headers (W3C Trace Context). When tracing is disabled (noop provider), this adds negligible overhead.

The span starts before routing, so it is named by method alone; TraceRequestAttrs renames it once the route is known.

func TrustedClientIP

func TrustedClientIP(trusted []*net.IPNet) func(http.Handler) http.Handler

TrustedClientIP resolves the client IP with chi's ClientIPFrom* middleware and stores it on the request context; read it with audit.ExtractClientIP (or chi's GetClientIP). r.RemoteAddr is left as the TCP peer.

  • With trusted proxies, chi's ClientIPFromXFF reads X-Forwarded-For only when the TCP peer is inside one of them. It merges every header line, walks right to left past trusted hops and takes the first untrusted address. An entry that is not a bare IP ends the walk with no result.
  • With none, chi's ClientIPFromRemoteAddr uses the TCP peer.

No other header (X-Real-IP, True-Client-IP) is read. When chi resolves nothing, audit.ExtractClientIP falls back to the TCP peer.

Types

type IdempotencyCleaner

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

IdempotencyCleaner adapts CleanExpired to the scheduler's cleaner interface (Cleanup(ctx) (int, error)), matching the shape used by payment.TokenService. Keeps scheduler wiring identical across cleanup tasks, and avoids the scheduler package importing anything from middleware.

func NewIdempotencyCleaner

func NewIdempotencyCleaner(db *postgres.DB) *IdempotencyCleaner

func (*IdempotencyCleaner) Cleanup

func (c *IdempotencyCleaner) Cleanup(ctx context.Context) (int, error)

type LeaderStatusRow

type LeaderStatusRow struct {
	Role               string
	Held               bool
	HasTicked          bool
	LastTickAgeSeconds float64
	Paused             bool
}

LeaderStatusRow is one role's row from the leader_status view, as the metrics collector needs it.

type RateLimiter

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

RateLimiter implements distributed rate limiting using the GCRA (Generic Cell Rate Algorithm) backed by Redis. GCRA is a leaky-bucket variant that smooths traffic instead of allowing burst-then-block at window boundaries.

Powered by go-redis/redis_rate — the official rate limiting companion for go-redis, used across the go-redis ecosystem.

func NewRateLimiter

func NewRateLimiter(rdb *goredis.Client, name string, rate int, window time.Duration) *RateLimiter

NewRateLimiter creates a Redis-backed GCRA rate limiter. name namespaces the limiter's Redis keys so distinct limiters with different parameters don't collide on a shared bucket (e.g. "general", "hosted_invoice", "setup_link"). Example: NewRateLimiter(rdb, "general", 100, time.Minute) = 100 requests per minute with smooth distribution (no boundary bursts). If rdb is nil, the limiter fails open (all requests allowed), unless SetFailClosed or SetLocalFallback says otherwise.

func (*RateLimiter) AllowKey

func (rl *RateLimiter) AllowKey(ctx context.Context, key string) (int, time.Time, bool)

AllowKey is the exported variant of allow() for callers that need to enforce a custom-keyed bucket from within a handler (vs. as middleware). Used by paymentmethods.send-setup-email to enforce a per-customer cooldown — prevents double-click double-emails. Returns (remaining, resetAt, allowed); same fail-open / fail-closed / local-fallback semantics as the middleware path.

func (*RateLimiter) Middleware

func (rl *RateLimiter) Middleware() func(http.Handler) http.Handler

Middleware returns chi-compatible rate limiting middleware. Keys by tenant ID (from auth context) or IP address for unauthenticated requests.

func (*RateLimiter) SetFailClosed

func (rl *RateLimiter) SetFailClosed(v bool)

SetFailClosed controls what happens when Redis is unreachable or unconfigured. Default (false) — fail open: allow all requests. Appropriate for local/dev. true — fail closed: return 429 for every non-infra request. Use in production, where availability without rate limiting is a DDoS vector.

func (*RateLimiter) SetLocalFallback

func (rl *RateLimiter) SetLocalFallback()

SetLocalFallback makes the limiter count requests in this process whenever Redis is not configured or a Redis call fails, in place of the fail-open or fail-closed choice. The in-process count uses the same rate and burst, but it is per replica: with N replicas behind a balancer, one key gets up to N times the limit while Redis is down. Call it after NewRateLimiter and before serving.

Jump to

Keyboard shortcuts

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