Asked at
URL Shortener (TinyURL)
Asked from Junior level upFoundations & Storage
Distributed Rate Limiter
Asked from Mid level upAPI Gateway & Security
Distributed Key-Value Store
Asked from Senior level upFoundations & Storage
Distributed Notification Service
Asked from Mid level upMessaging & Queues
Distributed Web Crawler
Asked from Mid level upDistributed Systems
Metrics & Monitoring Platform
Asked from Senior level upObservability & Time-Series
Real-Time Chat App (like WhatsApp or Slack)
Asked from Mid level upReal-Time & WebSockets
Social News Feed (like X/Twitter)
Asked from Mid level upSocial & Feed Systems
Ride-Hailing App (like Uber)
Asked from Senior level upGeospatial & Real-Time
Low-Latency Stock Exchange Matching Engine
Asked from Staff level upFintech & Low Latency
Global Video Streaming Platform (like YouTube or Netflix)
Asked from Senior level upMedia & Streaming
Distributed Hotel & Ticket Reservation System
Asked from Mid level upE-Commerce & Transactions
Shared Document Editor (like Google Docs)
Asked from Staff level upReal-Time & Distributed State
Game Leaderboard
Asked from Junior level upCaching & Data Structures
File Sync Service (Dropbox / Google Drive)
Asked from Mid level upStorage
Payment System
Asked from Senior level upPayments & Transactions
Ad Click Aggregation
Asked from Senior level upStream Processing
AI Support Assistant (RAG)
Asked from Senior level upAI Systems
LLM Inference Platform
Asked from Senior level upAI Systems
Enterprise Semantic Search
Asked from Mid level upAI Systems
AI Code Completion
Asked from Senior level upAI Systems
LLM Gateway
Asked from Senior level upAI Systems
AI Agent That Takes Actions
Asked from Senior level upAI Systems
LLM Evaluation Platform
Asked from Senior level upAI Systems
AI Document Processing Pipeline
Asked from Mid level upAI Systems

Design a Distributed Rate Limiter

Asked from Mid level upDomain: API Gateway & Security
Concepts to know first:

Design a fast, shared rate limiter that protects backend APIs from abusive clients and sudden floods of requests.

An analogy

Think of a rate limiter like a bouncer at a busy club entrance who only lets 10 people enter per minute. If a group of 50 arrives at once, they must wait outside so the club does not get dangerously overcrowded.

Where this design ends up. This is version 3 of 3. Part 5 builds it up from version 1 and says why each part was added.
  1. Clients
    • Client Apps
  2. Gateway
    • Envoy Proxy
  3. Token Store
    • Redis Cluster (Lua)
  4. Rules Store
    • Config Server
  5. Upstream Service
    • Core Microservices

1. Requirements and scope

Functional Requirements
  • Throttle clients exceeding allowed threshold (e.g. 100 req/min per IP/API token).
  • Return HTTP 429 (Too Many Requests) with Retry-After header when limit exceeded.
  • Support customizable rate limits per user tier (Free, Pro, Enterprise).
Non-Functional Requirements & SLAs
  • Minimal latency overhead (< 2ms per request).
  • Keep working when it breaks. If the limiter is down, either let requests through (fail open) or turn them away with a clear error. Decide which up front.
  • Distributed accuracy across multi-node application clusters.
Key Traffic Assumptions: 50,000 requests/sec peak ingress across all gateway nodes.

2. Back-of-the-envelope numbers

Writes and reads each second
  • Writes: 50,000 counter updates a second (50%)
  • Reads: 50,000 limit checks a second (50%)

Balanced: reads and writes are close. Both paths need care, so neither can be slow.

Write Throughput
50,000 evaluations/sec
Read Throughput
50,000 evaluations/sec
Storage Growth
10M users × 64 bytes per counter = ~640 MB in RAM (fits on single Redis node)
RAM Cache Footprint
All active rate limiting states kept in RAM

3. API

POST/api/v1/check-limitThe gateway asks: { clientId, endpoint, cost }. The limiter answers: { allowed: true or false, remaining, retryAfter }.

4. Data model and storage

Storage Strategy: Redis with Lua scripting or local memory sliding window hash map.
Redis Hash: key="rate:{clientId}:{window}", fields={ count: integer, expireAt: timestamp }

5. The design, in three versions

Version 1: Single Node In-Memory Limiter

Each app server counts requests per minute in its own memory, for example with a Guava cache or a plain map.

Rate Limiter v1: In-Memory Token Bucket Version 1 of 3

The picture follows one request through the parts of this version, in order. Under it, switch a part off to see what the request does without it.

One request, step by step

Each numbered arrow is one step. Press "Simulate Request Flow" to follow them one at a time.

Client AppsSpring GatewayLocal JVM MemoryConfig ServerCore Microservices1234
  • The order of the steps
  • A request or its reply

The parts: switch one off

1. Clients

Client AppsAPI Consumers

2. Gateway

Spring GatewayToken Interceptor

3. Token Store

Local JVM MemoryAtomic Counter

4. Rules Store

Config ServerTier Rules (VIP vs Free)

5. Upstream Service

Core MicroservicesBusiness Logic

The steps in words0 of 4 steps shown

  1. Client to GatewayHTTPS · 15ms

    POST /api/v1/orders (Bearer token)

  2. Gateway to RedisLua Script · 1.8ms

    EVALSHA token_bucket.lua user_123

  3. Redis to GatewayRESP · 0.8ms

    Return { allowed: true, remaining: 49 }

  4. Gateway to UpstreamgRPC · 3ms

    Pass request with X-RateLimit headers

Why this version
Zero operational dependencies.
Next bottleneck
State lost on restart; cannot enforce limits across horizontal app instances.

Write path, read path and failures

Each path follows one request through the final design (version 3), one hop at a time.

Read pathCheck one request

  1. Client
  2. Edge rate limiter
  3. Envoy sidecar
  4. Backend service
  1. Client to Edge rate limiter

    A request arrives with an API key. The edge drops obvious floods, such as one IP address sending thousands of requests a second.

  2. Edge rate limiter to Envoy sidecar

    The sidecar is a small proxy beside the service. It finds the token bucket for this API key in its own memory.

  3. Envoy sidecar to Backend service

    If a token is left, it takes one and passes the request on. This check takes well under a millisecond.

  4. Envoy sidecar to Client

    If the bucket is empty, it answers HTTP 429 with a Retry-After header. The backend never sees the request.

Write pathKeep the counters in step

  1. Envoy sidecar
  2. Local syncer
  3. Redis cluster
  1. Envoy sidecar to Local syncer

    Every few hundred milliseconds, the sidecar reports how many tokens each key used.

  2. Local syncer to Redis cluster

    The syncer adds those counts to the shared counter for each key in Redis, in one atomic step.

  3. Redis cluster to Local syncer

    Redis returns how much of the global limit is left for each key.

  4. Local syncer to Envoy sidecar

    Each sidecar gets its share of what is left, and refills its local bucket to match.

What breaks, and what happens then

  • Redis is down

    What users see
    Sidecars cannot learn the global count.
    What the design does
    Fail open: each sidecar keeps limiting with its local bucket. Limits are less exact, but product traffic keeps flowing.
  • A sidecar restarts

    What users see
    Its local buckets start full, so a key may get a short extra burst.
    What the design does
    The next sync, a few hundred milliseconds later, pulls the real counts from Redis.
  • A network break delays the sync

    What users see
    Servers disagree about a key's count for a moment, and the key can go a little over its limit.
    What the design does
    Accept the small drift. Give each sidecar only a slice of the limit, so the total overshoot is bounded.

6. Deep dives

Token Bucket vs Sliding Window Log
A token bucket lets a client burst up to the size of its bucket, and it needs only two numbers per client. A sliding window log counts exactly, but it stores the time of every request, for example in a Redis sorted set. That takes much more memory.

7. Follow-up questions

  • What happens if Redis dies? (Answer: Decide per route. Most APIs fail open, so a limiter outage does not stop all traffic. Costly or sensitive routes, such as login, can fail closed.)

What it costs

The counters are small, about 640 MB for 10 million users. The cost is the extra lookup on every request. Local counters on each server cut those lookups, at the price of a limit that is a little loose.

Another way to design it

For one region and modest traffic, a limit in the API gateway or the load balancer is enough. You build nothing. You give up limits that are shared exactly across many gateways.

8. How answers are judged

A passing answer at Mid level. A complete design with numbers: about 50,000 checks a second, each counter about 64 bytes, so 10 million users fit in roughly 640 MB. It explains the algorithm and goes deep on one part.

How each level is judged
What is judgedJuniorMidSeniorStaff
BreadthHow much of the system does the answer cover?Names the core parts: clients, servers, a database and a cache.Covers the whole main flow, from the request to the stored data and back.Builds a complete design without being led through it.Covers the system, the systems around it and who owns each part.
DepthHow far does it go into the hard parts?Explains what each part does and why it is there.Goes deep on one part, such as the database or the cache.Goes deep on the two or three riskiest parts.Goes deepest where the risk is largest, and explains why the risk is there.
DrivingWho leads the conversation?Follows the interviewer, step by step.Moves forward alone, with an occasional nudge.Leads the conversation from start to finish.Changes the problem when the question asked is not the right one.
Trade-offsAre choices compared and justified?Names more than one option.Says why one option was picked over another.Compares options in detail, with what each one costs.Ties each choice to cost, speed and risk for the business.
Unclear questionsWhat happens when the question is vague?Answers the questions that are asked.Asks questions to make the problem clear.Sets the scope and says what is left out.Questions the assumptions behind the problem itself.
ScopeWhat does it consider beyond the normal path?Covers the normal path, when everything works.Adds what happens when a part fails.Adds growth: what breaks at ten times the load, and the fix.Adds abuse, cost and the daily work of running the system.

Requirements and scope

Strong answer
Before I design, I want to check the scope. Limits can differ by tier, such as Free, Pro and Enterprise, and clients are identified by IP or token. Should the limiter fail open or closed if it breaks itself? I will assume a blocked request should fail fast, in under 2 milliseconds.
Weak answer
Every client gets the same limit, say 100 requests a minute, and any request over that gets a 429 response. Let me start on the Redis design.

Shows: Unclear questionsThe difference: The weak answer picks one flat limit without asking about tiers or what happens if the limiter itself fails, both named in the requirements.

Estimates

Strong answer
50,000 checks a second is the peak across all gateway nodes. With 10 million users and about 64 bytes per counter, that is roughly 640 MB, which fits easily in one Redis node's memory.
Weak answer
For perfect accuracy, I would keep every request's timestamp for each user in a sorted set. 10 million users at 64 bytes each still fits in about 640 MB.

Shows: DepthThe difference: A timestamp per request costs far more memory than one counter per user; 640 MB only holds a simple counter, not a full request log.

Core design

Strong answer
Each client has a Redis key with a token count and its last refill time. A request spends one token if any remain, and tokens refill at a steady rate. The bucket size caps a burst: a full bucket lets at most one limit's worth through at once. A fixed window can let double the limit through at its edge.
Weak answer
Each client gets a Redis key that counts requests in the current one-minute window and resets to zero when the window ends.

Shows: Trade-offsThe difference: A fixed window lets a client send the limit right before it ends and again right after, doubling its real rate for a moment. A token bucket avoids that edge.

Deep dive

Strong answer
The hard part is many gateway nodes checking and raising the same counter at once. Reading the count, then writing it back as two separate calls, lets two requests both read the same value and both pass. A single Lua script does the check and the raise as one atomic step in Redis.
Weak answer
Each gateway node reads the current count from Redis. If it is under the limit, it writes the count plus one back to allow the request.

Shows: DepthThe difference: Two nodes can both read the same count before either writes back, so both let a request through past the limit. One atomic script avoids that race.

Failures and trade-offs

Strong answer
If Redis goes down, I would fail open for most endpoints, so a broken limiter never takes down the product. I would also send an alert so we know it happened. For login and password-reset, I would fail closed instead, since letting every attempt through costs more there than a short outage.
Weak answer
If Redis goes down, I would fail open everywhere, so a broken limiter never blocks a single request across the whole API.

Shows: Trade-offsThe difference: Failing open everywhere leaves login and password-reset unprotected during an outage, where unlimited attempts cost more than a brief outage. The strong answer fails closed there instead.

We wrote this guide in our own words, informed by public interview guides such as AlgoMaster and Hello Interview. We are not connected to either site. Interviewers differ. The guide and the example answers show the direction each level takes, not a checklist.

10. Check your design with your own AI

Write your design first. Then copy this prompt into the AI chat you already use, and add your design at the end. It asks for a score in each area, one fix for each, and two follow-up questions.

The site sends nothing anywhere. An AI review can be wrong, so check what it says against sections 8 and 9.

See the prompt
You are a system design interviewer. Review my design for the interview problem below.

Problem: Design a Distributed Rate Limiter
Design a fast, shared rate limiter that protects backend APIs from abusive clients and sudden floods of requests.

What users must be able to do:
- Throttle clients exceeding allowed threshold (e.g. 100 req/min per IP/API token).
- Return HTTP 429 (Too Many Requests) with Retry-After header when limit exceeded.
- Support customizable rate limits per user tier (Free, Pro, Enterprise).

How well it must work:
- Minimal latency overhead (< 2ms per request).
- Keep working when it breaks. If the limiter is down, either let requests through (fail open) or turn them away with a clear error. Decide which up front.
- Distributed accuracy across multi-node application clusters.

Numbers to assume:
- 50,000 requests/sec peak ingress across all gateway nodes.

Judge my design at the Mid level.
A passing answer at this level: A complete design with numbers: about 50,000 checks a second, each counter about 64 bytes, so 10 million users fit in roughly 640 MB. It explains the algorithm and goes deep on one part.

For each area below, say whether my design is strong, fine or weak. Give one reason and one fix for each:
1. Requirements and scope
2. Estimates
3. Core design
4. Deep dive
5. Failures and trade-offs

Then ask me the two follow-up questions an interviewer would ask next.
Do not write a full model answer for me.

My design:
[Describe your parts, how one request moves through them, and why you chose each one.]