Rate limiting and abuse basics
Understand the idea
A correct handler that says yes to every call will say yes as fast as a script can ask.
The idea
is a check in front of the work. This example keeps an in-memory count for one caller and allows two calls. The first run starts at zero, so the request is allowed and the count becomes 1. The second run starts at 2, so the same route returns 429 and the count stays 2. A real deployment keys the bucket by caller and resets it on a window. The idea is the same. An endpoint that calls an AI service has a sharper version of this problem: each yes can cost money. Counting requests is the start. A budget for that cost comes in the last lesson of the track.
What changes
| Starting count | Limit | This request |
|---|---|---|
| 0 | 2 | 200, then the count is 1 |
| 2 | 2 | 429, and the route body does not run |
| After the paid call | Any | Too late. The call already happened |
The command
Under the limit
3s timeout · one stateless run. Node and Express use Piston when that instance accepts the job (public EMKC execute is whitelist-only; set PISTON_URL or PISTON_TOKEN). Otherwise a local Node process. MongoDB uses a fresh in-memory server per run, then it is stopped.
Over the limit
3s timeout · one stateless run. Node and Express use Piston when that instance accepts the job (public EMKC execute is whitelist-only; set PISTON_URL or PISTON_TOKEN). Otherwise a local Node process. MongoDB uses a fresh in-memory server per run, then it is stopped.
The mistake
Check the result
The open bucket returns 200 and count 1. The full bucket returns 429 and count 2. The notes title is not in the 429 body, because that handler did not run.
Guided challenge
Refuse calls past the limit
allow currently always returns true. Restore the count check so a bucket that is already at the limit returns 429.
Refuse calls past the limit
3s timeout · one stateless run. Node and Express use Piston when that instance accepts the job (public EMKC execute is whitelist-only; set PISTON_URL or PISTON_TOKEN). Otherwise a local Node process. MongoDB uses a fresh in-memory server per run, then it is stopped.
EXPECTED RESULT
status 429 slow down
Hints 0/2
Use all hints or make 3 failed checks (0/3).
Free exploration
Change this example and run it again. Each run is a new process. Nothing is saved.
Your variation
3s timeout · one stateless run. Node and Express use Piston when that instance accepts the job (public EMKC execute is whitelist-only; set PISTON_URL or PISTON_TOKEN). Otherwise a local Node process. MongoDB uses a fresh in-memory server per run, then it is stopped.
Quiz
A quick check for understanding. Retry as often as you like; your learning path stays open.
Ready to call this one understood?
Mark this lesson complete to earn 200 XP. You can always revisit it.