Lesson 7 of 15
32. Design a Rate Limiter as a Service

32.6 How do you pick the algorithm?

3 min read+10 XP

Step 5: Deep dives (10 minutes)

The service supports a few algorithms and lets each rule choose (Chapter 25):

RuleAlgorithmWhy
Partner API: 100 a minute, bursts OKToken bucket (capacity 100, refill 100/min)Bursty clients, two numbers per key, supports per-call cost
Search: expensiveToken bucket with cost 5Same bucket, weighted calls
Daily quota: 10,000 a dayFixed window per calendar daySimple; a boundary burst over a day barely matters
High-volume per-key limit needing accuracySliding window counterTwo counters, close to exact
Login: 5 per 15 minutes per accountSliding log (or token bucket with capacity 5)Tiny, must be tight
Calls to a fragile partnerLeaky bucket in the outbound clientSmooth output, not just a cap

Default: token bucket. It handles bursts, needs two numbers per key, gives a natural retry_after ((cost − tokens) ÷ refill rate), and supports costs. In the chapter's code, a bucket of 100 allows exactly 100 of 101 instant calls, reports retry after 1 s, and allows the next call 0.6 s later.

Interviewer pushback:

  • "Why not just fixed windows everywhere? They're simplest." → The boundary burst: 2× the limit in a second at the window edge (Chapter 25). Fine for daily quotas, bad for protecting a service per minute.

Memory code: "Bucket by default; pick another only for a named reason."