Try
↑ ↓ move↵ openesc close

Interview prep / Rate limiting algorithms

Mid · Rate limiting algorithms · System design interview question

Your API runs on many servers. How do you enforce one rate limit per user across all of them?

Sketch your own answer first, then compare it with the one below.

A strong answer

The simple approach is a shared store that holds the counter for each user. Every server increments it. The danger is a race: two servers read 19, both admit, and both write 20. The fix is an atomic operation in the store, such as an increment that returns the new value, or a small script that runs the whole check inside the store.

The shared store adds a network hop to every request and becomes a dependency. To cut that, a server can keep a local allowance and sync with the store now and then. That is faster, and the limit becomes approximate, with some slack equal to what can be spent between syncs. Another option is to route each user to a fixed server, for example by hashing the key, so the count is local. That fails when the server goes away.

Decide what happens when the store is down. Failing open keeps the service up and drops protection. Failing closed protects the service and causes an outage. Protective limits usually fail open. Hard quotas, where extra traffic costs money, are more often closed.

Sources

Learn it by running it

The rate limiting algorithms lesson explains the mechanism behind this question, and its lab lets you change the parameters and watch the effect.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms