Chapter Eleven · Problem Five

Rate Limiter

One limit held by twenty servers inside 5 milliseconds, across a 45-minute round.

4 lessons · 45 minutes
The Question

"Design a service that limits how many requests each client may make to an API and rejects the rest."

A token bucket on one machine is a dozen lines, so the algorithm is not where this problem is hard. It begins when twenty servers have to hold one limit between them, inside a few milliseconds, and keep serving when whatever holds the count falls over. The interviewer is listening for how early you say so.

Three block chapters get used here. Chapter 2's Caching at Scale sizes the in-memory nodes, and When the Cache Hurts gives the local copy that saves a node from one loud key. Chapter 4's Leaders, Followers and Everyone says what a failover forgets, CAP and PACELC, Precisely says what this data gives up, and Concurrent Writes and Conflicts brings the summed counter. Chapter 6's Backpressure and Load Shedding, Failure Across Many Services, and Regions and the Arithmetic of Nines bring the refusal, the breaker and the retry storm, and the round trips.

This chapter also pays two debts. When the Cache Hurts left a scanner to be stopped by a limit per client, and Backpressure and Load Shedding left open who gets the 429 across a whole fleet. Both are settled here. Backend Deep Dive's lesson on rate limiting and backpressure builds the same shared bucket in code, for one service on four instances. Here you size it for twenty servers, price it and defend it out loud, and the script is a line you name.

This is a mid-level problem, and a senior candidate is judged on how early the failure policy and the size of the error come up, unasked. The round turns on three things: the algorithm and where each one is wrong, meaning the fixed window's burst at its boundary, the sliding log's memory and the token bucket's refill; one counter shared by many servers within a few milliseconds, and the accuracy given up to get there; and failing open or closed when the counter store is down.

Start a 45-minute clock before you open Scope, and write down your own limiter, with the number you would defend for its error. Scope runs from minute 0 to 10, First Design to 20, Scaling It to 30, and Deep Dives and Curveballs to 45. If your sketch has no number for the error, that is the first thing to look for as you read.

The 45 minutes of this problem, lesson by lesson
Scopeminutes 0-10
→
First Designminutes 10-20
→
Scaling Itminutes 20-30
→
Deep Divesminutes 30-45

Lessons in This Chapter