10 / 25 · Service boundaries
Rate limiting
Rate limiting controls how much work an identity or client may request over time. It protects capacity and fairness, but it is not a complete defense against every attack.
Work through a token bucket with 10 tokens and a refill rate of 2 tokens per second. Compare it with a fixed window, then consider shared counters and HTTP 429 responses.
What you will practise
- Distinguish rate and concurrency
- refill a token bucket
- explain shared counters
Before you start: Identity, elapsed time and concurrency.
About 4 minutes · offline-generated English female narration · captions included. Diagrams are conceptual; timings are illustrative.
Download MP4CaptionsListen without the video
Download audioChapters and full transcript
Let us understand rate limiting. A library lets each student borrow a limited number of books so one student cannot empty the shelves. A short burst may be acceptable, but repeated borrowing must remain within a fair rate. The rule needs a reliable way to identify the student, not just the colour of their shoes. Rate limiting controls how much work an identity or client may request over time. It protects capacity and fairness, but it is not a complete defense against every attack.
Follow the normal path. Requests are assigned a deliberate identity key, such as a verified account and endpoint. A spoofable header cannot safely define a protected client budget. The token bucket refills over elapsed time up to its capacity. Capacity permits a bounded burst while the refill rate controls sustained use. SeatSpot protects sign-in and booking attempts from excessive traffic. Public browsing, expensive searches and paid customers may need different budgets; one shared limit for everyone can punish unrelated users.
Now change one condition. Checking and consuming a token must behave as one operation for shared state. Separate reads and writes can overspend under concurrency. A common misunderstanding is this: An IP header is always a reliable user identity. Client-controlled forwarding headers can be forged, and many people share one NAT address. Think about this. Ten tokens are spent immediately. After three idle seconds at two tokens/second, how many tokens remain? Pause the video and make your prediction. Six, capped by the bucket capacity of ten. Concurrent updates need an atomic implementation to preserve that rule.
Let us reason with a concrete example. A teaching token bucket has capacity 10 and refills at 2 tokens/second. If initially full, ten immediate requests can consume ten tokens. After 3 idle seconds it has six tokens, capped at ten. This model ignores distributed races until an atomic implementation is chosen. Choose a key and storage behavior explicitly. Protect critical actions with a deliberate fail-closed or degraded policy rather than silently giving unlimited access after a store failure. These figures are teaching examples, not production guarantees.
Turn the idea into a design decision. A request with enough tokens proceeds, but still faces authorization, request validation and downstream concurrency limits. Passing the limiter is not a correctness guarantee. A request without budget receives a clear rejection and retry guidance where appropriate. Clients should wait rather than creating an immediate retry storm. When you try the practice task, look for this result. Only the available budget is admitted; a 429 response can communicate a retry policy.
Check your understanding. If the shared limiter fails, enforce the chosen endpoint policy and alert. Independent local counters do not preserve a strict global quota across replicas. Here is a challenge. Three replicas each allow 100 requests/minute for one user. Is the global user limit 100? Pause before the answer. Not with independent counters: the user may receive up to roughly 300 across replicas, depending on routing and windows. Use an atomic shared budget or state explicitly that the policy is per instance. For an interview, choose a principal, atomic state and store-failure policy. Say what you would measure, not only which tool you would buy.
Start with an everyday picture
A library lets each student borrow a limited number of books so one student cannot empty the shelves. A short burst may be acceptable, but repeated borrowing must remain within a fair rate. The rule needs a reliable way to identify the student, not just the colour of their shoes.
Why SeatSpot needs this
SeatSpot protects sign-in and booking attempts from excessive traffic. Public browsing, expensive searches and paid customers may need different budgets; one shared limit for everyone can punish unrelated users.
Trace one step at a time
Move through the diagram at your pace. Teal paths are active; unavailable components are labelled.
Identify the principal
Requests are assigned a deliberate identity key, such as a verified account and endpoint. A spoofable header cannot safely define a protected client budget.
Read all six mechanism steps
Identify the principal
Requests are assigned a deliberate identity key, such as a verified account and endpoint. A spoofable header cannot safely define a protected client budget.
Refill the budget
The token bucket refills over elapsed time up to its capacity. Capacity permits a bounded burst while the refill rate controls sustained use.
Consume atomically
Checking and consuming a token must behave as one operation for shared state. Separate reads and writes can overspend under concurrency.
Allow affordable work
A request with enough tokens proceeds, but still faces authorization, request validation and downstream concurrency limits. Passing the limiter is not a correctness guarantee.
Reject excess traffic
A request without budget receives a clear rejection and retry guidance where appropriate. Clients should wait rather than creating an immediate retry storm.
Plan storage failure
If the shared limiter fails, enforce the chosen endpoint policy and alert. Independent local counters do not preserve a strict global quota across replicas.
Pause and make a prediction
Ten tokens are spent immediately. After three idle seconds at two tokens/second, how many tokens remain?
Correct a common misunderstanding
Claim to question: An IP header is always a reliable user identity.
Better explanation: Client-controlled forwarding headers can be forged, and many people share one NAT address.
Run a paper token bucket
- Start a bucket with capacity ten and ten tokens.
- Spend all ten on a burst, then advance time three seconds.
- Refill six and test another burst before enough time passes.
Check what you can explain
This is your self-check, not an automated grade. Try again without the diagram tomorrow.
0 of 3 goals checked. Choose one remaining idea to practise next.
Teach it back
Without looking, explain what this component changes, what it does not solve and what happens if it fails. Use the animation to check your explanation, then switch to Engineering.
Engineering model and trade-offs
Define the principal, scope, sustained rate and burst capacity. A token bucket refills tokens over time; requests consume them. A fixed window is simpler but can admit a boundary burst across adjacent windows.
In a distributed service, per-process counters are not a strict global limit. Use appropriate atomic shared state or a deliberately partitioned budget. Document any best-effort behavior and what happens when the limiter store is unavailable.
A 429 response should communicate a safe retry policy where appropriate. Combine limits with bounded concurrency, authentication and abuse controls. Do not trust a spoofable forwarded-IP header or identify all users behind one NAT as one person without considering fairness.
Token bucket example: capacity, refill rate and bursts
A teaching token bucket has capacity 10 and refills at 2 tokens/second.
Reason with the numbers
If initially full, ten immediate requests can consume ten tokens. After 3 idle seconds it has six tokens, capped at ten. This model ignores distributed races until an atomic implementation is chosen.
Make a decision
Choose a key and storage behavior explicitly. Protect critical actions with a deliberate fail-closed or degraded policy rather than silently giving unlimited access after a store failure.
Token bucket calculation and distributed counters
tokens = min(capacity, tokens + elapsedSeconds * refillRate)
if tokens >= requestCost:
tokens -= requestCost
allow
else:
reject with 429 and retry guidanceConceptual single-key token-bucket algorithm. Reading, refilling and consuming must be atomic for a shared distributed limiter. It is not production middleware.
Where this is used
- Protecting costly or abuse-prone API actions.
- Per-tenant fairness and upstream quota protection.
Common mistakes
- Using independent instance counters as a global guarantee.
- Trusting client-provided IP identity.
- Retrying 429 responses immediately in a tight loop.
Practise a reasoned answer
Answer aloud or write notes before opening the reference. These prompts teach reasoning and trade-offs; they are not claimed questions from a particular company.
Token bucket or fixed window?
Choose a practice depth
- Foundation
- Explain sustained rate and burst allowance.
- Practical
- Choose a principal, atomic state and store-failure policy.
- Advanced
- Discuss distributed budgets, hot keys, NAT fairness and overload beyond request rate.
Self-check rubric
- State the required user outcome and the relevant invariant.
- Explain the normal path and one failure path.
- Name a cost or consistency/latency trade-off.
- Say what you would measure or test before trusting it.
For deeper practice, connect this topic to the previous lesson and identify a shared bottleneck. A longer answer is not automatically a better answer.
Try it before viewing the solution
Three replicas each allow 100 requests/minute for one user. Is the global user limit 100?
Check one key idea
Your explanation and interview notes
Saved only in this browser when storage is available. Export a backup from the course page before clearing browser data or moving devices.
Loading your local notes…
Official references and next reading
The explanation, fictional examples and animations are original teaching material. Vendor behavior depends on the specific product/version; use its documentation before deploying.