Rate limiting and cost control for AI endpoints
Understand the idea
An AI route can be hammered into a bill. The refusal has to happen before the provider is called.
The idea
Lesson 19 counted requests. This lesson counts estimated cost. The limit is 20 and each summary costs 5. Under budget, the route calls the stand-in, called becomes true, and the client gets the summary plus spent 5. At spent 18, the next cost would pass 20, so the handler returns 429 and never calls postProvider. called stays false. That is the difference between and cost control. A generic window can still say yes to a call you cannot afford. Check the budget first.
What changes
| Already spent | Next cost | Result |
|---|---|---|
| 0 | 5 | 200, called true, spent 5 |
| 18 | 5 | 429, called false, spent stays 18 |
| Check after fetch | 5 | The provider was already called |
The command
Within budget
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 budget
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
Within budget: 200, summary Summary: Milk, spent 5, called true. Over budget: 429, error AI budget exceeded, spent 18, called false.
Guided challenge
Block the call when the budget is exceeded
The budget check was removed, so the provider is always called. Put back the spent + cost > limit check so this run returns 429 and called stays false.
Block the call when the budget is exceeded
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 AI budget exceeded "called":false
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.