Designing a rate limiter means deciding who may make how many requests, over what window, and what happens when someone exceeds it—then implementing that decision so it stays accurate under concurrency and across multiple servers. At its core a rate limiter compares each incoming request against an allowance (tokens or a counter) and either admits the request, delays it, or rejects it with a status code such as HTTP 429. Get the algorithm and the storage model right first; the enforcement point, configuration, and observability come next. A limiter is only as good as its ability to stay consistent when dozens of processes hit the same counter at once.

Start with requirements and a budget

Before choosing an algorithm, pin down the policy in plain terms. Four questions shape everything downstream.

What are you limiting? A per-user limit (say, 60 requests per minute per API key) needs a key derived from identity. An IP-based limit is cheap but blunt—NAT and mobile carriers put many users behind one address. A per-endpoint limit protects a specific expensive route (login, password reset, search). Global limits protect a downstream dependency shared by everyone. Many real systems layer two or three of these at once.

What is the budget and window? "100 requests per second" and "6,000 requests per minute" can describe the same average load but behave differently at the edges. Short windows react fast to bursts; long windows smooth daily quotas.

What happens on rejection? Rejecting with 429 is the default for public APIs. Queuing or delaying suits internal traffic you'd rather slow than drop. Silently shedding is acceptable for low-value background jobs. The choice affects how much state you need—a queue is far more complex than a counter.

What's the accuracy tolerance? A payment API and a marketing email sender have different stakes. Stricter limits usually cost more coordination and latency.

Write the requirement as a testable sentence: "Each API key may send at most 100 requests in any 60-second window; excess requests receive 429 with a Retry-After header, and the decision must be consistent across all gateway instances." That sentence tells you exactly what to build and what to verify.

Pick an algorithm that matches the traffic shape

The classic algorithms trade smoothness against burst tolerance and memory. Understanding the mechanism of each prevents the most common production surprise—a limit that looks right on average but leaks at the boundaries.

Fixed window counter

Divide time into fixed buckets (e.g., each clock minute) and count requests per bucket. Reject when the count exceeds the limit; reset the counter at the boundary.

Mechanism: one integer per key per window. INCR key; if result > limit then reject; also set expiry. Strength: trivial to implement and reason about; very cheap. Failure: the boundary burst. With a limit of 100 per minute, a client can send 100 at 00:59 and another 100 at 01:00—200 requests in roughly two seconds, none of which tripped a counter. The average is fine; the instantaneous spike is not. Use when: bursts across boundaries are harmless (coarse quotas, metrics sampling) or you pair it with a short-window layer.

Sliding window log

Record a timestamp for every accepted request and count how many fall inside the trailing window. Exact, but memory grows with the limit—storing 100,000 timestamps per key is not viable at scale.

Sliding window counter (weighted)

Approximate the trailing window from two adjacent fixed windows. The count for the current window is previous_count × overlap_fraction + current_count, where overlap_fraction is the share of the previous window still inside the trailing window. If the previous minute had 80 requests and the current minute has 40, and you're 15 seconds into the current minute, the estimate is 80 × 0.75 + 40 = 100. This smooths the boundary burst at a fraction of the memory of a log.

Strength: good accuracy, two counters per key, cheap. Failure: it's an estimate; the weighting assumes requests were evenly spread across the previous window, which they often aren't. Document the approximation. Use when: you want near-exact smoothing on a budget. This is the default for many public API gateways.

Token bucket

A bucket holds up to burst tokens and refills at rate tokens per second. Each request removes one token; if the bucket is empty, reject (or queue). Two parameters—refill rate and capacity—separate sustained throughput from burst allowance, which is exactly the control most APIs want.

Mechanism without a timer: store tokens and last_refill. On each request, compute elapsed = now - last_refill, add elapsed × rate, cap at burst, subtract one, and persist. No background job needed. Strength: naturally allows a burst up to capacity then throttles to the refill rate; memory is two numbers per key. Failure: implementation bugs usually live in the arithmetic—forgetting to cap at capacity, using wall-clock time that jumps backward, or storing fractional tokens as integers and losing precision. Use when: you want burst tolerance plus a steady long-run rate. This is the most common choice for API rate limiting.

Leaky bucket

Requests enter a queue of fixed depth and drain at a constant rate. It produces perfectly smooth output (good for protecting a downstream that hates spikes) but adds latency and queue-memory costs, and it doesn't let well-behaved clients burst.

Algorithm Burst behavior State per key Accuracy Best fit
Fixed window Allows boundary bursts 1 counter Average-accurate Coarse quotas
Sliding log Exact One timestamp per request Exact Low limits, high precision
Sliding counter Smoothed 2 counters Approximate Public API gateways
Token bucket Burst up to capacity 2 numbers Exact per refill Most APIs
Leaky bucket No burst Queue depth Smooth output Protecting downstreams

Choose where to enforce and where to store state

A single-process limiter is a variable and a lock. Real systems run many instances behind a load balancer, so the counter must be shared or partitioned—otherwise each instance enforces its own copy and the effective limit multiplies by the instance count.

Enforce at the edge when possible. An API gateway, reverse proxy, or service mesh sidecar can reject early, before requests consume application resources. Edge enforcement is cheap and uniform but may lack the identity context (e.g., a resolved user tier) needed for fine-grained limits.

Store counters in a shared low-latency store. An in-memory data store such as Redis is the common choice because it offers atomic increments, expiry, and sub-millisecond reads. The critical requirement is atomicity: the read-modify-write of a token bucket must not interleave with another request.

Or partition to avoid coordination. If each key is deterministically routed to one limiter instance (consistent hashing), that instance can keep state locally and skip the network hop. The trade-off is rebalancing and losing state on restart.

Handle the store being down. Decide explicitly: fail open (allow traffic, risk overload) or fail closed (reject everything, risk outage). Most teams fail open for availability and rely on circuit breakers downstream, but that decision belongs in the design doc.

Make the counter update atomic under concurrency

This is where most naive limiters break. Two requests arrive simultaneously, both read tokens = 1, both subtract, both are admitted—two requests served with one token. Serialize the whole decision.

Use a server-side atomic operation. In Redis, a Lua script runs atomically, so the read-compute-write of a token bucket executes as one unit. Pseudocode for a token bucket:

If you can't use a scripted store, a compare-and-swap loop (read version, compute, write only if version unchanged, retry on conflict) works but degrades under contention.

Beware the cross-key race. Checking three limits (per-user, per-endpoint, global) as three separate atomic calls is not globally atomic. A request can pass the user check, then fail the global check, having already consumed a user token. Either accept the small overcount, or combine all checks for a request into one scripted operation.

Respect clock skew. Use a single time source (the store's clock, not each app server's) so refill arithmetic is consistent. Wall-clock jumps backward can temporarily inflate allowances.

Define the client contract: status codes, headers, retries

A limiter that rejects without telling clients how to behave creates retry storms that look like attacks.

Status: return 429 Too Many Requests for throttling. Some systems use 503 for load shedding; document which means what. Headers: expose the limit, remaining allowance, and reset time—conventionally RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset, or the older X-RateLimit-* family. Include Retry-After with the seconds until the client may retry. Retry guidance: tell clients to back off with jitter. Without jitter, every rejected client retries at the same instant and synchronizes into a thundering herd. Idempotency: for write endpoints, throttling a retried request must not double-apply the operation; pair limits with idempotency keys where it matters.

Also decide what counts. Does a request that 400s consume a token? Usually yes—the work of parsing and routing still happened—but document it so client-side budgeting matches.

Roll out incrementally, then monitor and tune

Deploying a limiter blind is risky: too strict breaks legitimate clients, too loose protects nothing.

1: Shadow mode first. Compute decisions and log them without rejecting anything. Compare the would-be rejection rate against real traffic. 2: Set limits from observed baselines. Use historical percentiles—e.g., a limit at the 99th-percentile burst—rather than guesses. Leave headroom for legitimate spikes. 3: Enable per-key with a canary. Turn on enforcement for a small traffic slice or a few API keys, watch error rates, then widen. 4: Instrument the limiter itself. Track allowed vs. rejected counts by key and endpoint, the distribution of remaining allowance, latency added by the check, and store error rates. A limiter that silently fails open shows up only as downstream overload.

Success check: after rollout, rejected requests should cluster on genuinely abusive or misconfigured keys, legitimate clients should rarely see 429, and p99 added latency from the check should stay within your budget (single-digit milliseconds for a shared-store call is typical). If rejections are spread evenly across all keys, the limit is probably too tight or the key derivation is wrong.

Tune cadence: revisit limits after traffic shifts, incidents, or product launches. Limits set once and forgotten drift out of alignment with usage.

Common failure modes and how to catch them

Per-instance counters: the limit multiplies by instance count. Symptom: effective throughput far above the configured number. Fix: shared or partitioned state. Non-atomic updates: occasional over-admission under load. Symptom: rejection counts lower than expected during bursts. Fix: atomic script or CAS. Boundary bursts: fixed-window spikes at minute edges. Symptom: short overload despite "correct" average. Fix: sliding window or token bucket. No expiry on counters: memory grows without bound as keys accumulate. Symptom: store memory climbing. Fix: set TTL on every key. Key derivation leaks: limiting by raw IP punishes shared networks; limiting by an unauthenticated header invites spoofing. Fix: derive keys from verified identity. Fail-open without a backstop: store outage becomes a downstream outage. Symptom: cascading failures during a cache incident. Fix: circuit breakers and a degraded local limit. Retry amplification: clients hammer without backoff. Symptom: sustained 429s with no drop in load. Fix: Retry-After plus client-side jittered backoff.

A worked sizing example

Suppose an API handles 50,000 requests per second at peak across 20 gateway instances, with 200,000 distinct API keys active per minute. Using a token bucket in a shared store: two numbers per key (token count, last refill) plus key overhead, call it roughly 100 bytes per key. 200,000 keys is about 20 MB of state—comfortable for an in-memory store. Each request costs one atomic scripted call at sub-millisecond latency; the aggregate rate of 50,000 calls per second is well within a single well-provisioned store, but you'd shard keys across a small cluster for redundancy. (These figures are illustrative sizing inputs, not measurements; validate against your own store's throughput.) This estimate is the kind of back-of-envelope check that reveals whether shared state is even necessary at your scale—sometimes partitioning by key is simpler than adding a shared dependency.

FAQ

Should the limiter be a library or a standalone service? A library keeps the decision in-process and avoids a network hop but can't share state across languages and services cleanly. A service or sidecar centralizes policy and state at the cost of latency and another dependency. Many teams start with a library against a shared store and migrate to a dedicated edge service as the number of services grows.

How do I limit fairly across tiers (free vs. paid)? Make the limit a function of the key's tier, resolved before the check—for example, a lookup of the tier then a bucket sized per tier. Keep the tier lookup cached and versioned so a plan change propagates predictably.

What about distributed denial-of-service traffic? A rate limiter shapes legitimate load; it is not a DDoS defense on its own. Volumetric attacks should be absorbed upstream by network-level filtering and a CDN before they reach your limiter, which would otherwise spend its budget counting junk.

Do I need exact limits or is approximate fine? For most APIs, approximate (sliding counter) is fine and much cheaper. Exact limits matter where money or contractual quotas are at stake—billing meters, per-customer SLAs—and there you may want exact accounting in the billing system rather than the limiter.