๐ฌ Rate limiting: cheat sheet
๐จ The analogyA sweet jar refilled with one sweet a minute: grab a few at once, but never beat the refill rate.
๐ The regular explanationCapping how many requests a client can make in a period, to protect a service from overload and abuse. The token bucket allows short bursts while enforcing a steady average rate.
- To get into the kitchen you must take a sweet from the jar. The jar holds at most 3 sweets.
- The visitor comes in three times quickly. Each time they take a sweet, and in they go.
- A fourth time, but the jar is empty. "Come back in a minute."
- Someone drops one sweet into the jar every minute. After a minute there's one, so the visitor can come in once.
- Everyone gets their own jar, labelled with their name. A greedy visitor empties only their own jar.
- Ana's jar is still full, so she walks straight in.
- The kitchen is protected too. Even if many visitors arrive together, only so many get in each minute.
- The kitchen has two doors. If each door kept its own jar, a visitor could take sweets from both and get twice as many.
- So both doors check one shared jar in the middle.
- Whichever door the visitor tries next, the jar is empty.
- Normally the doorman checks the shared jar first, and only guests who get a sweet go on to the cook.
- The jar is stuck in a locked cupboard. The doorman can't check it.
- This doorman waves everyone through so nobody goes hungry. Now the whole crowd reaches the cook, who is swamped. (A strict doorman would turn them all away instead.)
- The jar is back. The doorman checks it again, and the cook can catch up, but the crowd got through unchecked for a while.
๐งฉ Key questions
- You arrive in a rush and the jar has three sweets. What can you do?
- Take the three now, then wait for the next refill. The jar allows a short burst, but over time never more than the refill rate.
- Why does everyone get their own jar?
- So one greedy visitor can't empty the jar and lock everyone else out. The kitchen also limits how many people get in overall.
- The kitchen has several doors. Why do they share one jar?
- Otherwise you could just use another door to get more sweets. One shared jar keeps the limit true however you come in.
- The shared jar is stuck in a locked cupboard. The doorman waves everyone through. What is the risk?
- The crowd reaches the cook unchecked and swamps the stove. Waving everyone through keeps guests happy but drops the protection. A strict doorman would keep the stove safe and turn guests away.