Skip to main content

Scenario: Airbnb Distributed Rate Limiting

Diagram convention: Arrows and messages are labeled 1, 2, 3… to show processing order. Each diagram is followed by a Step-by-step flow table explaining every numbered step.

1. The Interview Question​

"Design a distributed rate limiter for a public API: 1M RPS globally, per-tenant limits, burst allowed, fair across regions."

2. Real-World Context​

DimensionDetail
Company / systemAirbnb and similar platforms — public APIs with per-host/per-app tenant quotas
Scale1M RPS globally; 10K+ API tenants; edge + regional enforcement
Why architects careAccuracy vs. latency tradeoff; hot tenant keys; fail-open vs fail-closed policy
Public referencesToken bucket / sliding window; Envoy Rate Limit Service; Redis GCRA

AWS deployment context​

Typical distributed rate limiter on AWS: Amazon CloudFront + AWS WAF at edge (IP/global buckets); API Gateway or ALB + Envoy with local token cache; Amazon ElastiCache Redis Cluster for regional sliding-window counters; ECS Fargate rate-limit service; DynamoDB for tenant quota config; CloudWatch for throttle metrics; Route 53 geo-routing to regional Redis clusters.

Step-by-step flow:

StepActionExplanation
1API requestClient calls GET /v2/listings with API key.
2WAF checkGlobal IP rate limit — blocks DDoS before app tier.
3Edge allowCloudFront forwards to regional API Gateway.
4Local bucketIn-memory token bucket — fast path; approximate.
5Regional checkRedis sliding window — authoritative per-tenant count.
6Lua atomicAtomic check-and-increment — no race conditions.
7Load quotaTenant limit from DynamoDB (cached in Redis).
8AllowRequest forwarded to origin API.
9429 denyLimit exceeded — Retry-After header returned.

3. Step-by-Step Interview Answer​

Minutes 0–8: Requirements​

TypeDetail
Per-tenant1000 req/min default; burst 2000 (token bucket)
Global accuracyWithin 1% of true count — acceptable for SaaS tiers
Latencyp99 check < 5ms (local cache + one Redis hop)
HierarchyGlobal → tenant → endpoint must all pass
PolicyFail-closed for public API; fail-open for internal tier
HeadersX-RateLimit-Limit, Remaining, Reset, Retry-After on 429

Step-by-step flow:

StepActionExplanation
1GlobalTotal platform RPS cap — protects origin.
2TenantPer API key / partner quota.
3EndpointExpensive endpoints get tighter limits.
4IPAnti-scrape layer at WAF.

Minutes 8–20: Two-tier design​

Tier 1 — Edge (local): Token bucket in memory per edge PoP / gateway pod; absorbs burst; approximate; <1ms.

Tier 2 — Regional (authoritative): ElastiCache Redis Cluster with sliding window log (ZSET) or GCRA.

Step-by-step flow:

StepActionExplanation
1RequestClient hits API with tenant API key.
2Local bucketIn-memory token bucket — sub-ms check.
3aFast pathLocal tokens available — skip Redis (approximate).
3bDeferLocal exhausted — authoritative Redis check required.
4CheckLimitRate limit service called with tenant + endpoint.
5Lua scriptAtomic sliding window check-and-increment.
6Result{allowed, remaining, reset_at} returned.
7HeadersX-RateLimit-Remaining: 847 attached to response.
8ForwardRequest proceeds to origin API.

Redis sliding window (ZSET):

key = rl:tenant:{id}:route:{path}:min:{epoch_minute}
ZADD key {timestamp_ms} {request_id}
ZREMRANGEBYSCORE key -inf {now_ms - window_ms}
ZCARD key → compare to limit
EXPIRE key {window_seconds + buffer}

Lua script for atomicity:

-- sliding_window.lua — atomic check-and-increment
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local req_id = ARGV[4]

redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)
local count = redis.call('ZCARD', key)
if count < limit then
redis.call('ZADD', key, now, req_id)
redis.call('EXPIRE', key, math.ceil(window / 1000) + 1)
return {1, limit - count - 1} -- allowed, remaining
else
return {0, 0} -- denied
end

Minutes 20–35: Deep dive​

ChallengeSolution
Redis hot keyShard counter: tenant:123:shard:{hash%16} — aggregate sum
Cross-region driftRegional Redis per region; global cap via separate counter
Race conditionsLua script — single-shard atomic ops
Burst allowanceToken bucket at edge; refill rate + burst capacity
Retry-AfterReturn 429 with header from window reset time

Step-by-step flow:

StepActionExplanation
1Hash shardshard = hash(request_id) % 16 — spread hot key.
2Parallel ZADDEach shard gets fraction of traffic.
3AggregateSum shard counts; deny if total > limit.

Algorithm comparison:

AlgorithmBurstAccuracyMemoryUse tier
Token bucketYes — smooth burstApproximateO(1)Edge local cache
Fixed windowBoundary spikePoor at window edgeO(1)Avoid
Sliding window logNo spikeExactO(limit) per keyRedis authoritative
Sliding window counterModerate~99% accurateO(1)High-volume alternative
GCRAYesExactO(1)Redis Cell style

Minutes 35–45: Failure modes​

FailurePolicyBehavior
Redis partitionFail-closed (public API)Return 503/429 — protect origin
Redis partitionFail-open (internal)Allow traffic — availability over accuracy
Redis slow (>5ms)TimeoutFail-closed for paid tiers
DDoSWAF firstIP bucket before tenant bucket
Clock skewRedis TIMEUse server time in Lua, not client

Step-by-step flow:

StepActionExplanation
1CheckLimitNormal rate limit check.
2Redis timeout3ms timeout — don't block request path.
3PartitionRedis unreachable or slow.
4aFail-closedDeny — protects origin during outage.
4bFail-openAllow — internal APIs prioritize availability.

Capacity math:

MetricValueCalculation
Global RPS1MPlatform peak
Redis ops/s per region~200KAfter local cache absorbs 80%
Tenants10KActive API partners
Ops per check1 (Lua EVALSHA)Single round-trip
Redis nodes6+ shard cluster200K ops ÷ 33K per node

4. Whiteboard Guide​

  1. Left: Clients → CloudFront → WAF (IP bucket)
  2. Center: API Gateway → local token bucket → Redis (authoritative)
  3. Right: Origin API
  4. Label hierarchical limits: global → tenant → endpoint
  5. Draw hot key sharding with 16 shards
  6. Annotate fail-closed vs fail-open policy box

AWS whiteboard layout​

Step-by-step flow:

StepActionExplanation
1Redis checkAuthoritative sliding window per tenant.
2Lua atomicNo race condition on concurrent requests.
3AllowForward to origin with rate limit headers.
4429Deny with Retry-After when over limit.

5. Principal-Level Signals​

  • Token bucket vs sliding window — burst vs accuracy tradeoff
  • Hot key sharding — hash % N spread for top tenants
  • Explicit fail-open vs fail-closed — product decision per API tier
  • Edge + central two-tier — local absorbs 80%; Redis authoritative
  • Hierarchical limits — global AND tenant AND endpoint must pass
  • Lua atomicity — never INCR then GET separately

6. Red Flags​

  • Single Redis key per hot tenant — hot key bottleneck at 50K RPS
  • Fail-open on public API during Redis outage — origin gets DDoS'd
  • Fixed window counter — 2× spike at window boundaries
  • No Retry-After header on 429 — clients retry immediately (retry storm)
  • Rate limit after origin — too late; must be at gateway edge

7. Follow-Up Questions​

QuestionStrong answer
1M RPS — how many Redis ops?~200K/s after 80% local cache hit; 6-node cluster
Token bucket vs sliding window?Bucket for burst at edge; sliding window for accurate billing
Cross-region fairness?Regional Redis + periodic global reconciliation counter
Envoy RLS vs custom?Envoy for K8s mesh; custom for DynamoDB-driven dynamic quotas
How to test accuracy?Load test 10K RPS; measure actual vs allowed within 1%

9. Practice Drill​

Implement mental model: 10K tenants, 1M RPS — how many Redis ops/s? Whiteboard Lua sliding window script from memory.


10. Production High-Level Design​

10.1 Architecture diagram index​

SectionTopic
§2End-to-end AWS deployment
§3Edge + regional two-tier flow
§10.2C4 logical context
§10.3Full multi-region stack
§10.4Global → tenant → endpoint
§11.4Check sequence
§11.5Redis Lua script
§11.6Shard aggregation
§12Regional Redis clusters
§13Metrics and alerts
§146-week rollout
§15Accuracy + failover tests
§16Production readiness

10.2 System context (C4 Level 1)​

10.3 AWS production architecture​

AWS componentRate limit responsibility
CloudFront + WAFIP-level DDoS; 10K req/5min per IP
API GatewayUsage plans; optional first-pass throttle
Envoy + local bucketSub-ms approximate check; 80% cache hit
ElastiCache RedisAuthoritative sliding window per tenant
DynamoDBTenant quota config; plan tier limits
CloudWatchthrottle_rate, redis_latency_p99

10.4 Hierarchical limit evaluation​

Quota tiers (DynamoDB):

Tierreq/minburstfail policy
Free60100fail-closed
Standard10002000fail-closed
Premium1000020000fail-closed
Internalunlimited—fail-open on Redis outage

11. Production Low-Level Design​

11.1 API response headers​

HTTP/1.1 200 OK
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 847
X-RateLimit-Reset: 1735689660
HTTP/1.1 429 Too Many Requests
Retry-After: 42
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1735689660

11.2 DynamoDB quota schema​

{
"tenant_id": "partner_abc",
"plan_tier": "standard",
"limits": {
"global_rpm": 1000,
"burst": 2000,
"endpoints": {
"/v2/search": 100,
"/v2/listings": 500
}
},
"fail_policy": "closed",
"updated_at": "2026-07-28T21:00:00Z"
}

11.3 Local token bucket (edge)​

class LocalTokenBucket:
def __init__(self, rate: float, burst: int):
self.rate = rate # tokens per second
self.burst = burst
self.tokens = burst
self.last_refill = time.monotonic()

def try_consume(self, n: int = 1) -> bool:
now = time.monotonic()
elapsed = now - self.last_refill
self.tokens = min(self.burst, self.tokens + elapsed * self.rate)
self.last_refill = now
if self.tokens >= n:
self.tokens -= n
return True
return False # defer to Redis

11.4 Rate limit check — step-by-step​

Step-by-step flow:

StepActionExplanation
1GET requestClient calls API with tenant key.
2try_consumeLocal token bucket — sub-ms.
3aFast path~80% of requests never hit Redis.
3bRedis checkLocal depleted — authoritative check.
4get_quotaTenant limits from DynamoDB (Redis-cached).
5EVALSHAAtomic sliding window Lua script.
6Resultallowed + remaining count.
7–9ForwardAttach headers; proxy to origin.
8b429Deny with Retry-After.

11.5 Lua sliding window implementation​

def check_rate_limit(tenant_id: str, endpoint: str, request_id: str) -> RateLimitResult:
shard = hash(request_id) % NUM_SHARDS
key = f"rl:{tenant_id}:{endpoint}:shard:{shard}"
now_ms = int(time.time() * 1000)
quota = get_quota(tenant_id) # cached from DynamoDB

allowed, remaining = redis.evalsha(
SLIDING_WINDOW_SHA,
keys=[key],
args=[now_ms, quota.window_ms, quota.limit // NUM_SHARDS, request_id],
)

if not allowed:
# Aggregate across shards for final decision
total = sum(get_shard_count(tenant_id, endpoint, s) for s in range(NUM_SHARDS))
if total >= quota.limit:
return RateLimitResult(allowed=False, retry_after=compute_reset())

return RateLimitResult(allowed=True, remaining=remaining)

11.6 Hot key sharding​

ParameterValue
Shards per hot tenant16
Per-shard limitglobal_limit / 16
AggregationSum all shard ZCARD before deny
Shard selectionhash(request_id) % 16

11.7 Fail policy implementation​

def check_with_policy(tenant_id: str, endpoint: str) -> RateLimitResult:
try:
return check_rate_limit(tenant_id, endpoint, request_id)
except (RedisTimeout, RedisConnectionError) as e:
policy = get_fail_policy(tenant_id) # from DynamoDB
if policy == "closed":
metrics.increment("rate_limit.redis_failure_deny")
return RateLimitResult(allowed=False, status=503)
else:
metrics.increment("rate_limit.redis_failure_allow")
return RateLimitResult(allowed=True) # fail-open

12. HA/DR and Multi-Region​

PrincipleImplementation
Regional RedisEach region enforces independently — no cross-region RTT
Global capSeparate low-frequency global counter; 1% accuracy OK
Quota configDynamoDB global table — consistent tier limits
FailoverRoute 53 shifts traffic; regional Redis already warm

13. Observability and Operations​

MetricAlert threshold
rate_limit.throttle_rate per tenant> 50% for 5 min
rate_limit.redis_latency_p99> 5ms
rate_limit.local_cache_hit_rate< 70% — tune bucket size
rate_limit.redis_failure_deny> 0 — Redis outage
rate_limit.hot_key_shard_skew> 2× average — rebalance

Structured log:

{
"tenant_id": "partner_abc",
"endpoint": "/v2/listings",
"decision": "allow",
"remaining": 847,
"latency_ms": 1.2,
"path": "local_cache",
"shard": null
}

Runbook — Redis outage​

StepAction
1Confirm ElastiCache cluster health in CloudWatch
2Check redis_failure_deny vs redis_failure_allow rates
3Public API: expect 503 spike — communicate to partners
4Internal API: fail-open — monitor origin load
5Failover to replica if single-node failure
6Post-incident: review fail policy per tier

14. Implementation Roadmap (6-Week Rollout)​

WeekDeliverable
1DynamoDB quota schema + tenant tier config API
2Redis sliding window Lua + rate limit service
3Local token bucket in Envoy / API Gateway
4Hierarchical limits + response headers
5Hot key sharding + load test 200K Redis ops/s
6Fail policy per tier + dashboards + runbook

15. Testing Strategy​

TestPass criteria
1000 req/min limitRequest 1001st returns 429 within same window
Burst 2000First 2000 in burst allowed; then throttled
Concurrent 100 threadsNo over-count > 1% vs sequential
Redis outage fail-closedPublic API returns 503 — zero origin overload
Redis outage fail-openInternal API allows traffic — alert fired
Hot tenant 50K RPSShard skew < 2×; p99 < 5ms
Retry-After headerPresent on all 429 responses

16. Architecture Review Checklist​

#GateStatus
1Two-tier: local bucket + Redis authoritative☐
2Lua atomic check-and-increment (no race)☐
3Hierarchical limits: global → tenant → endpoint☐
4Hot key sharding for top tenants☐
5Fail-closed for public API; fail-open for internal☐
6X-RateLimit-* and Retry-After headers on all responses☐
7WAF IP rate limit before tenant limit☐
8Redis p99 latency dashboard + 5ms alert☐
9Load test 200K Redis ops/s per region☐
10Accuracy within 1% at 10K RPS tenant☐