Skip to main content

Rate Limiting

Learning objectives
  • Compare token bucket, leaky bucket, fixed window, sliding log and sliding window counter in accuracy, burst behaviour and memory
  • Build a distributed rate limiter with Redis and an atomic Lua script, and decide what happens when Redis is unavailable
  • Decide where limits belong — edge, gateway, service, or in front of a fragile downstream such as a core banking system
  • Design per-user, per-API-key and per-tenant quotas with fair sharing and correct client signalling (429, Retry-After)

TL;DR​

  • Rate limiting protects availability (overload, retry storms), cost (SMS OTPs, partner fees) and security (credential stuffing, scraping, card testing), and enforces fairness between clients.
  • Token bucket is the default: average rate r with bursts up to capacity B, O(1) state. Sliding window counter is a cheap, accurate approximation for "N per minute" quotas.
  • Fixed windows allow up to 2× the limit around window boundaries; sliding logs are exact but cost memory per request.
  • For many gateway instances, keep state in Redis with an atomic Lua script (one round trip, ≈ sub-millisecond), and decide explicitly whether to fail open or fail closed when Redis is down.
  • Layer limits: IP/bot limits at the edge, per-key/plan limits at the gateway, business-aware and per-account limits in services, and concurrency limits in front of fragile dependencies.
  • Respond with 429 Too Many Requests plus Retry-After; clients must back off with jitter.
  • Rate limits are not business limits. A daily transfer cap is a ledger rule enforced transactionally, not a Redis counter.

Why it matters​

  • Flash sales: bots fire thousands of "Buy" requests per second per account and scalp inventory. Per-user and per-device limits on the purchase endpoint, plus a waiting room, keep the sale fair and the backend alive (see Flash Sale System).
  • Banking login and OTP: credential stuffing and OTP flooding are constant. Each OTP SMS costs money, and "SMS pumping" fraud can generate large bills. Limits per phone number, per account, per device and per IP are standard controls.
  • Card testing: attackers validate stolen card numbers with many small authorizations; per-card, per-merchant and per-IP velocity limits are part of the fraud defence (see Fraud & Risk Systems).
  • Open banking / partner APIs: third-party providers get per-client quotas by contract; one misbehaving partner must not degrade others.
  • Protecting the core: a core banking system or a national payment switch connection may be rated for a fixed TPS. A concurrency limiter in front of it turns overload into fast, explicit rejections instead of timeouts that cascade.

Core concepts​

What to limit, and by which key​

  • Unit: requests per second, requests per minute/day (quotas), concurrent in-flight requests, bytes, or cost units (an export costs 50, a balance read costs 1).
  • Key: IP, user id, API key / OAuth client, tenant, device id, phone number, card PAN token, account, endpoint, or a combination such as (api_key, endpoint).
  • Scope: per instance (local), per region, or global.

The algorithms​

Token bucket. A bucket holds up to B tokens and refills at r tokens per second. Each request takes one token (or cost tokens); if none are available, reject (or wait). Allows bursts up to B, long-run average r. State per key: token count and last refill time.

Leaky bucket. Requests enter a FIFO queue drained at a constant rate; if the queue is full, reject. Output is perfectly smooth — this is traffic shaping, useful when the downstream needs a steady rate (sending to an SMS gateway or a partner bank at its contracted TPS). The cost is added queueing latency. (A "leaky bucket as a meter" variant is equivalent to a token bucket.)

Fixed window counter. Count requests per key in the current window (for example per minute, INCR with a 60 s expiry). O(1) and simple, but a client can send the full limit at 00:59 and again at 01:00 — up to 2× the limit in a short interval.

Sliding window log. Store a timestamp per request (for example in a Redis sorted set), drop entries older than the window, count the rest. Exact, but memory and CPU grow with the limit (a 10,000/hour limit stores up to 10,000 entries per key).

Sliding window counter. Keep counts for the current and previous fixed windows and weight the previous one by how much of it still overlaps the sliding window:

estimate = previous_count × (1 − elapsed_in_current / window) + current_count

Example: limit 100/min; previous minute had 80; we are 15 s into the current minute with 30 so far → 80 × 0.75 + 30 = 90 → allowed. O(1) memory, smooths boundary bursts, slightly approximate (it assumes the previous window's requests were evenly spread). Cloudflare has described using this approach at large scale with very small observed error.

AlgorithmBurst behaviourAccuracyMemory per keyBest for
Token bucketBursts up to B, then rate rExact for its model2 numbersAPI rate limits, default choice
Leaky bucket (queue)No bursts out; queue absorbsExactQueue up to sizeShaping traffic to a fixed-rate downstream
Fixed windowUp to 2× at boundariesCoarse1 counterDaily/monthly quotas, cheap coarse limits
Sliding logNo boundary effectExact1 entry per requestLow limits needing exactness (login attempts, OTP)
Sliding window counterSmoothedApproximate2 countersPer-minute quotas at scale

Concurrency and adaptive limits​

Rate limits cap arrivals; concurrency limits cap in-flight work, which is what actually exhausts threads, connections and downstream capacity (Little's Law: in-flight = rate × latency). If the core banking adapter can sustain 200 concurrent calls, a semaphore of 200 with fast rejection beyond it protects the core regardless of how latency changes. Adaptive limiters (AIMD, or gradient-based algorithms like those in Netflix's concurrency-limits library) adjust the limit automatically from observed latency — useful when downstream capacity varies. See Resilience Patterns.

Distributed rate limiting​

With 20 gateway instances, a per-instance limit of limit/20 is only correct if the load balancer spreads each client's traffic perfectly evenly — it does not. Options:

ApproachAccuracyLatency costFailure behaviour
Local limiter per instance (limit / N)Poor with uneven routingNoneIndependent
Central store (Redis + Lua) per requestGoodOne round trip (≈ 0.2–1 ms)Depends on Redis; choose fail-open or fail-closed
Local buckets that lease tokens in batches from centralGood enoughAmortisedDegrades gracefully
Dedicated rate-limit service (for example Envoy's global rate limit service)GoodOne RPCSame as central store

Key details:

  • Atomicity. "Read count, decide, write count" must be atomic, or concurrent requests all see the same count and all pass. Use a Lua script (executed atomically by Redis) or INCR with expiry for fixed windows.
  • Redis Cluster. Keys used by one script must live in the same hash slot; use hash tags, for example rl:{key:abc}:tb and rl:{key:abc}:win.
  • Clock. Use Redis server time inside the script (or a single trusted clock), not each gateway's local clock.
  • Fail open vs fail closed. For general API limits, fail open (allow) with a local fallback limiter — a Redis outage should not take the whole API down. For security-critical limits (login attempts, OTP sends), fail closed or fall back to a conservative local limit.
  • Hot keys. A single API key at 50k RPS hammers one Redis shard; for very large clients, use local buckets with token leasing.

Where to enforce​

  • Edge (CDN/WAF): coarse per-IP limits and bot detection; cheap rejection before traffic reaches you. Beware carrier-grade NAT: thousands of mobile users can share one IP.
  • API gateway: per API key, per OAuth client, per plan tier, per endpoint. Centralised configuration and consistent responses.
  • Service: limits that need business context — per account OTP sends, per card authorization velocity, cost-weighted limits for expensive operations like statement exports.
  • Outbound: client-side limiters and concurrency caps in front of partners and legacy systems with contracted or physical capacity.
  • Consumers: a queue consumer can be rate-limited to protect what it writes to; the queue absorbs the backlog.

Telling clients​

HTTP/1.1 429 Too Many Requests
Content-Type: application/problem+json
Retry-After: 12
RateLimit-Policy: "default";q=100;w=60
RateLimit: "default";r=0;t=12

{
"type": "https://api.example-bank.vn/problems/rate-limited",
"title": "Too many requests",
"status": 429,
"detail": "Limit of 100 requests per 60 seconds for this API key exceeded."
}
  • 429 Too Many Requests (RFC 6585) means "you, the client, exceeded a limit". 503 Service Unavailable means "the server is overloaded or down" — also often with Retry-After.
  • Retry-After (seconds or an HTTP date) tells well-behaved clients when to try again.
  • Quota headers: many APIs use de facto X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset; the IETF HTTPAPI working group has a draft standard defining RateLimit-Policy and RateLimit fields (the exact syntax has changed between draft versions, so check the current draft).
  • Use a consistent error body (see API Design).
  • Security endpoints: do not leak exact remaining attempts on login or OTP endpoints; a generic message plus Retry-After is enough.
  • Clients: exponential backoff with jitter, honour Retry-After, cap retries. Your own mobile app is a client too.

Fairness and multi-tenancy​

  • Hierarchical limits: global capacity → per tenant/partner → per user. A tenant cannot exceed its share even if global capacity is free, unless you explicitly allow borrowing.
  • Plan tiers: free, standard and premium API plans with different rates and burst sizes.
  • Weighted fair queuing: when capacity is scarce, serve tenants in proportion to weights instead of first-come-first-served, so one partner's burst cannot starve the rest.
  • Priority classes: reserve capacity for critical traffic — payments and authorizations before reporting and exports; shed the lowest class first during overload.
  • Isolation: separate pools, or shuffle sharding (assigning each tenant a small random subset of workers), limit the blast radius of a noisy neighbour.
  • Per-key fairness inside a batch: a merchant uploading 100k payouts should not delay another merchant's 10 payouts — queue per merchant and drain round-robin.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Token bucketBursts allowed, O(1), well understoodBursts may still hurt a fragile backendDefault for API limits
Leaky bucket queueSmooth outputAdds latency, queue memoryShaping to a fixed-rate partner
Fixed windowSimplest, cheapestBoundary bursts up to 2×Daily/monthly quotas
Sliding logExactMemory per requestLow-volume security limits
Sliding window counterAccurate enough, O(1)ApproximatePer-minute quotas at scale
Local onlyNo dependency, zero latencyInaccurate across instancesCoarse protection, fallback
Central RedisAccurate, globalExtra hop, dependencyPer-key quotas across a fleet
Concurrency limitProtects the true bottleneckNeeds tuning or adaptivityIn front of core systems, partners, DBs
Fail openAvailabilityAbuse window during outageGeneral API quotas
Fail closedSafetySelf-inflicted outage riskLogin, OTP, high-risk actions

In practice​

  • In-process limits in Go use golang.org/x/time/rate, a token bucket: rate.NewLimiter(rate.Limit(100), 200) gives 100 events/s with bursts of 200. Use Allow() to reject, Wait(ctx) to block (for outbound shaping), Reserve() to compute a delay. Keep per-key limiters in a map with eviction of idle keys.
  • A distributed token bucket with go-redis and a Lua script (Redis ≥ 5 is assumed, so a script may read TIME and then write):
package ratelimit

import (
"context"
"strconv"
"time"

"github.com/redis/go-redis/v9"
)

// KEYS[1]: bucket key, e.g. "rl:{apikey:abc}:tb"
// ARGV: capacity, refill rate (tokens/s), cost
// Returns: allowed (0/1), remaining tokens, retry-after seconds (as strings).
var tokenBucket = redis.NewScript(`
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])

local t = redis.call('TIME')
local now = tonumber(t[1]) + tonumber(t[2]) / 1000000

local s = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(s[1]) or capacity
local ts = tonumber(s[2]) or now
tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate)

local allowed, retry = 0, 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
retry = (cost - tokens) / rate
end

redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / rate) * 2)
-- Lua numbers become integer replies, so return fractions as strings.
return {allowed, tostring(tokens), tostring(retry)}
`)

type Decision struct {
Allowed bool
Remaining float64
RetryAfter time.Duration
}

type Limiter struct {
rdb *redis.Client
capacity float64
rate float64
}

func (l *Limiter) Allow(ctx context.Context, key string, cost float64) (Decision, error) {
ctx, cancel := context.WithTimeout(ctx, 20*time.Millisecond)
defer cancel()

res, err := tokenBucket.Run(ctx, l.rdb, []string{"rl:{" + key + "}:tb"},
l.capacity, l.rate, cost).Slice()
if err != nil {
return Decision{}, err // caller decides: fail open with a local limiter, or fail closed
}
remaining, _ := strconv.ParseFloat(res[1].(string), 64)
retry, _ := strconv.ParseFloat(res[2].(string), 64)
return Decision{
Allowed: res[0].(int64) == 1,
Remaining: remaining,
RetryAfter: time.Duration(retry * float64(time.Second)),
}, nil
}
  • Observability: count allowed/rejected per key, plan and endpoint; alert on sudden rises in 429s (a client bug or an attack) and on limiter errors (Redis trouble). Log rejected security events for the fraud team.
  • Configuration as data: store limits per plan/tenant in config with versioning and audit, not hard-coded; partners will ask for changes.
  • Load: each limited request is one Redis script call; at 100k RPS that is 100k ops/s on Redis, so shard by key and keep scripts short.

Common pitfalls​

  • Per-IP limits on mobile traffic. Symptom: whole cities of customers on one carrier NAT get 429s during a promotion.
  • Fixed window boundary bursts. Symptom: downstream sees 2× the "limit" every minute boundary.
  • Non-atomic check-then-increment. Symptom: limits are exceeded under concurrency.
  • Fail-closed on a general limiter. Symptom: a Redis failover causes a full API outage.
  • Using Redis counters for business limits. Symptom: daily transfer limits bypassed after a cache eviction or failover — a compliance finding. Enforce such limits in the ledger DB transaction.
  • Limiting by an unauthenticated user id. Symptom: attackers lock real customers out by spamming their username (lockout DoS). Combine user, device and IP keys, and prefer delays or step-up challenges to hard lockouts.
  • Clients ignoring Retry-After. Symptom: retry storms that keep the system at its limit long after the original spike.
  • Only limiting request count. Symptom: one client's expensive exports or searches exhaust the database while within its request quota. Use cost-weighted limits.

Interview angle​

  • Where it appears: "Design a rate limiter" (SDI Vol. 1, Ch. 4) as a standalone question; also inside API gateway, flash sale, login/OTP, and open banking designs.
  • Strong answer covers: requirements (keys, limits, accuracy, latency budget, global vs local), algorithm choice with trade-offs, distributed state with atomic operations, placement in the request path, client signalling (429, Retry-After), failure mode of the limiter itself, multi-tenant fairness, and monitoring.
  • Follow-ups: "What if Redis is down?", "How do you handle 20 gateway instances?", "How do you limit a partner to 1,000 TPS across two regions?", "Token bucket vs sliding window?", "How do you protect the core banking system?", "How do you stop bots in a flash sale without blocking real users?"
  • Red flags: non-atomic counters, ignoring boundary effects, IP-only limits, no failure-mode answer, confusing rate limits with business limits.

Self-check​

1. Explain the token bucket parameters and what a request sees when the bucket is empty.

Capacity B is the maximum burst; refill rate r is the sustained average. Each request consumes tokens; if fewer than its cost remain, it is rejected (or delayed) and the time until enough tokens exist is (cost − tokens) / r, which is a natural Retry-After value.

2. Why can a fixed window allow 2× the limit, and how does the sliding window counter fix it?

A client can use the full limit at the end of one window and again at the start of the next, so a short interval spanning the boundary sees twice the limit. The sliding window counter weights the previous window's count by its remaining overlap with the sliding window, so a burst at 00:59 still counts against requests at 01:00.

3. Your gateway has 20 instances and a partner limit of 1,000 requests/s. Why is "50/s per instance" wrong, and what do you build?

The load balancer does not distribute one partner's traffic evenly, and instance counts change with autoscaling, so per-instance limits both over- and under-limit. Use a shared store: a Redis token bucket keyed by partner, executed atomically via Lua, or local buckets that lease tokens from a central allocator in batches. Decide the fallback (local conservative limit) if Redis is unavailable.

4. When should a limiter fail open and when fail closed?

Fail open for general API quotas: availability matters more than a brief window of over-use, and a local fallback limiter bounds the damage. Fail closed (or to a strict local limit) for security and cost controls such as login attempts, OTP sends and card-testing velocity, where an unlimited window during an outage is exploitable.

5. Scenario: the core banking system degrades above ≈ 300 concurrent calls. Design its protection.

Put an outbound concurrency limiter (semaphore of ≈ 300, or adaptive) in the integration layer, with short queue timeouts and fast rejection beyond it. Prioritise classes: payments and authorizations get reserved capacity; balance inquiries and statements are served from a read model or shed first. Return 503 with Retry-After to channels, and alert on rejection rate. Rate limits at the gateway complement this but do not replace it, because concurrency depends on latency.

6. Why is a daily transfer limit not a rate-limiting problem?

It is a business rule on money with regulatory and contractual weight: it must be exact, durable and checked atomically with the transfer itself. A Redis counter can be evicted, lost on failover or diverge from the ledger. Compute it from (or maintain it in) the ledger database inside the same transaction that records the transfer.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

  1. Implement the Redis token bucket above and a sliding-window-counter variant. Write a Go test that fires 1,000 concurrent requests for one key and asserts the allowed count equals the bucket capacity (± refill during the test).
  2. Put the limiter in an HTTP middleware that returns 429 with Retry-After and a problem-details body; add a local x/time/rate fallback used when Redis errors.
  3. Stop Redis mid-load-test and observe behaviour for fail-open and fail-closed modes.
  4. Design (on paper) the limits for a bank's OTP endpoint: keys, limits, algorithm, failure mode, and what the user sees.

Done looks like: passing concurrency test, a recorded run showing 429s and correct Retry-After, and a one-page OTP limit policy.

Further reading​

  • System Design Interview, Vol. 1 (Alex Xu), Ch. 4 "Design a Rate Limiter".
  • Cloudflare blog, "How we built rate limiting capable of scaling to millions of domains" (2017).
  • Stripe engineering blog, "Scaling your API with rate limiters" (Paul Tarjan, 2017).
  • RFC 6585 (429 Too Many Requests) and RFC 9110 (Retry-After), rfc-editor.org.
  • IETF HTTPAPI draft, "RateLimit header fields for HTTP".
  • golang.org/x/time/rate documentation (pkg.go.dev); Envoy documentation on local and global rate limiting.
  • Netflix Tech Blog, "Performance Under Load" (adaptive concurrency limits).
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).