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
- Betsy Beyer, Chris Jones, Jennifer Petoff, Niall Richard Murphy (2016). Site Reliability Engineering, chapter 21, Handling Overload.