Caching, rate limiting & cost budgets
Protect your service and budget with caches, per-user limits and spend alerts.
By Invicly Tech, , in AI Engineering with Python. About 12 minutes to read.
In short
Every LLM request costs money, so a public service needs protection. Caching avoids paying twice for the same answer, rate limits stop abuse, and budgets with alerts catch runaway spend early.
Explained simply
A normal web page costs almost nothing per visit. An LLM request can cost a noticeable fraction of a cent, or much more for long prompts. Put a public AI feature online without protection, and one script or one curious user can run up a large bill overnight.
Caching is the first defence. If many users ask the same question, store the answer once and reuse it. The reply is instant and costs nothing.
Rate limiting is the second. Each user or API key gets a fair allowance, such as 20 requests per minute. Above that, the service answers 429 Too Many Requests and says when to try again.
Budgets are the safety net. Track what each user and the whole service spends, send alerts before limits are reached, and have a plan for what happens when they are: a smaller model, shorter answers, or a polite pause.
Press Play on a diagram to walk through it one step at a time.
- 1Authenticate
Identify the user or API key
- 2Rate limit
Reject with 429 if over quota
- 3Check cache
Return stored answer for repeat requests
- 4Call model
Only when nothing cached
- 5Record spend
Add cost to user and daily totals
- 6Alert
Notify when spend nears the budget
- 1Input size limit
Reject huge prompts with 413 or 422
- 2Max output tokens
Caps each reply's cost
- 3Per-user rate and token limits
429 with Retry-After
- 4Per-user daily budget
Stops one account running away
- 5Global budget and alerts
Provider limit as a last resort
In depth
Exact caching, done safely
An exact cache stores answers under a key built from everything that affects the output: model, prompt version, generation parameters, the normalised input (trimmed, maybe lowercased) and, for RAG, the index version. Hash that list with SHA-256 to get a short key, and store the answer in Redis with a time to live (TTL), such as one day.
The big danger is caching personal answers. If the reply depends on who asks (their orders, their documents, their permissions), the user or tenant ID must be part of the key, or one person's answer can be served to another. When in doubt, do not cache that endpoint.
Also think about freshness. Including the index version in the key means re-indexing documents automatically retires old answers. Do not cache errors or partial streamed answers. Measure the hit rate: FAQ-heavy bots often see many repeats, while open-ended chat rarely repeats exactly.
- Key: model, prompt version, params, index version, normalised input
- Add user or tenant ID whenever the answer is personal
- Set a TTL; never cache errors or cut-off answers
Semantic caching and provider prompt caching
A semantic cache embeds each new question and reuses a stored answer when a previous question is similar enough. It raises the hit rate, because how do I reset my password and password reset how? can share one answer. The risk is false matches: cancel my order and do not cancel my order have very similar embeddings. Use a strict similarity threshold, restrict it to FAQ-style questions, scope it per tenant, and test it with your eval set.
Provider prompt caching is a different thing with a similar name. Many providers can reuse the computation for a long prompt prefix they have seen recently, such as your system prompt and documents, which makes those input tokens cheaper and faster. It never returns an old answer; the model still generates a fresh reply. To benefit, put stable content first in the prompt and the changing question last. Check your provider's docs for how it is enabled and priced.
- Same input, same answer
- Very safe if the key is complete
- Hit rate depends on repeats
- Similar question, stored answer
- Higher hit rate
- Risk of wrong matches
- Reuses a repeated prompt prefix
- Cheaper, faster input tokens
- Still generates a new answer
Rate limiting by requests, tokens and concurrency
Counting requests is a start, but one request with a 50-page document can cost a hundred times more than a short question. Good LLM services limit several things per user or key: requests per minute, tokens per minute or per day, and concurrent requests (for example two streams at a time).
Common algorithms: a fixed window counts requests in each clock minute and is simplest. A sliding window smooths the burst at window edges. A token bucket holds up to N permits that refill at a steady rate, allowing short bursts while capping the average. In a multi-server deployment, keep counters in a shared store like Redis, not in process memory.
When a limit is hit, return 429 with a Retry-After header giving seconds to wait. Different plans can get different limits. Protect yourself from the provider's limits too: a global semaphore or queue stops your own traffic from triggering their 429s.
- 1Bucket holds N permits
Full bucket allows a burst
- 2Request takes a permit
Or a number equal to its tokens
- 3Bucket refills steadily
e.g. one permit every 3 seconds
- 4Empty bucket
429 with Retry-After until refill
- Back to step 1
Spend budgets, alerts and graceful degradation
Compute the cost of every call from the token usage the API returns and a price table in config. Then add budget layers. Per request: cap input size and set a maximum output token limit. Per user: a daily spend limit. Per feature and per month: a team budget. Global: a hard spending limit or alert in the provider's console, if offered, set above your own limits as the last line of defence.
Alert early and in steps, for example at 50%, 80% and 100% of a budget. Add an anomaly alert too: spend this hour is three times the usual hour. That catches a stuck agent loop or abuse long before the monthly total looks scary.
Decide in advance what happens at the limit. Options include switching to a smaller, cheaper model, shortening answers, serving cached answers only, or pausing the feature with a clear message. A feature flag that changes this without a deploy is a cheap emergency brake.
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Cache repeated responses~40m
- 2Rate limit per user~40m
- 3Set spend budgets and alerts~40m
Key points
- Rate limit per user or key, not just globally.
- Exact-match caching is simple and safe; key it on model, prompt version and input.
- Set hard spend limits at the provider and your own alerts below them.
- Return a clear 429 with Retry-After when users hit limits.
Key terms
Tap a card to flip it. 0/5 known
Examples
import hashlib, time
cache: dict[str, str] = {}
requests_log: dict[str, list[float]] = {}
def allowed(user: str, limit: int = 20, window: int = 60) -> bool:
now = time.time()
recent = [t for t in requests_log.get(user, []) if now - t < window]
requests_log[user] = recent + [now]
return len(recent) < limit
def cache_key(model: str, prompt_version: str, text: str) -> str:
return hashlib.sha256(f'{model}|{prompt_version}|{text}'.encode()).hexdigest()A per-user sliding window limit and a safe cache key.
A Redis rate limiter as a FastAPI dependency
You run three API servers, so counters must be shared. Step 1: build a key from the user ID and the current window number (time divided by 60). Step 2: INCR the key atomically; on the first hit, set it to expire after the window, so old keys clean themselves up. Step 3: over the limit, raise 429 with Retry-After set to the seconds left in this window. Step 4: add Depends(rate_limit) to the chat route. Limits are module constants, because extra parameters on a dependency would become query parameters anyone could change.
import time
import redis.asyncio as redis
from fastapi import Depends, HTTPException
r = redis.from_url("redis://localhost:6379")
LIMIT, WINDOW = 20, 60 # 20 requests per minute
async def rate_limit(user: str = Depends(current_user)) -> None:
key = f"rl:{user}:{int(time.time() // WINDOW)}"
count = await r.incr(key)
if count == 1:
await r.expire(key, WINDOW)
if count > LIMIT:
retry = WINDOW - int(time.time() % WINDOW)
raise HTTPException(429, "Too many requests", headers={"Retry-After": str(retry)})A per-user daily spend budget with an early alert
Each user may spend up to an example budget of 2 dollars per day. Step 1: before the model call, read today's total for the user and refuse with a clear message if it is spent. Step 2: after the call, compute the real cost from usage and add it with INCRBYFLOAT, which is atomic across servers. Step 3: let the key expire after two days so storage stays small. Step 4: when a user crosses 80% of the budget, send an alert (notify is your own function, for example a Slack webhook).
import datetime
DAILY_BUDGET = 2.00 # dollars per user per day, example value
def spend_key(user: str) -> str:
return f"spend:{user}:{datetime.date.today().isoformat()}"
async def check_budget(user: str) -> None:
if float(await r.get(spend_key(user)) or 0) >= DAILY_BUDGET:
raise HTTPException(429, "Daily usage limit reached. Please try again tomorrow.")
async def record_spend(user: str, cost: float) -> None:
total = await r.incrbyfloat(spend_key(user), cost)
await r.expire(spend_key(user), 2 * 86400)
if total >= 0.8 * DAILY_BUDGET:
notify(f"{user} has used {total / DAILY_BUDGET:.0%} of today's budget")Quick reference
- Cache key: model, prompt version, params, index version and input; add user ID if answers are personal
- Never cache errors or cut-off streamed answers; always set a TTL
- Semantic caches need a strict threshold: cancel and do not cancel look alike to embeddings
- Provider prompt caching cuts input cost for repeated prefixes; put stable content first
- Limit requests, tokens and concurrent streams per user, in a shared store like Redis
- Return 429 with a Retry-After header in seconds
- Cap max output tokens and input size on every request
- Alert at 50%, 80% and 100% of budget, plus on sudden hourly spikes
Common mistakes
- Caching personalised answers and serving them to other users.
- Leaving the cache key without the prompt version, so old answers persist.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write cache_key(model, prompt_version, index_version, text, user=None) that normalises the text (trim, collapse spaces, lowercase) and returns a SHA-256 hex key, including the user only when given.
- Exercise 2medium
Implement an in-memory token bucket class with capacity and refill_per_second, and a take(n) method that returns True if n permits were available.
- Exercise 3hard
Limit each user to two concurrent streams. A third request should get 429 immediately, and the slot must be released even if the stream errors or the client disconnects.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I reduce LLM API costs in production?
- Cache repeated answers, use provider prompt caching for long stable prefixes, cap input and output tokens, route simple requests to smaller models, and set per-user limits and budgets.
- What HTTP status code should a rate limit return?
- 429 Too Many Requests, with a Retry-After header telling the client how many seconds to wait.
- Is semantic caching safe?
- It can serve a wrong answer when two questions look similar but mean different things. Use a strict threshold, limit it to general FAQ-style questions and test it before enabling it widely.
- What should happen when a user reaches their budget?
- Tell them clearly and when it resets, and optionally fall back to a cheaper model or cached answers. Never fail silently.