Redis caching and per-user usage limits
Cache results safely and enforce per-user quotas in Redis, with a clear plan for Redis outages.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 13 minutes to read.
In short
Redis is an in-memory key-value store that the service uses for two jobs: caching results that are expensive to compute, and counting how many model calls each user makes. Cached values get a time to live and keys that include the tenant and the model and prompt versions. Quotas use atomic increments and return 429 when spent, and you decide in advance what happens when Redis is down.
Think of it like this: The cache is a sticky note with yesterday's answer and a use-by date; the quota is a turnstile counter that resets every hour.
Explained simply
Some work is slow or costs money, like asking a language model to summarise a document. If the same request comes in again soon, it is wasteful to do the work twice. A cache keeps the answer for a while so the next identical request can reuse it.
Redis is a very fast store that keeps data in memory. You save a value under a key, and you can tell Redis to delete it after a number of seconds. That lifetime is the TTL, time to live. When the TTL runs out, the next request recomputes the answer and stores it again.
Model calls cost real money, so each user gets a quota, such as 100 questions per hour. Redis keeps a counter per user per hour. Every question adds one. When the counter passes the limit, the API answers 429 Too Many Requests and tells the client when to try again.
Redis can fail like anything else. Decide before it happens what the app should do. For the cache, the safe choice is usually to carry on without it. For quotas, you must choose between letting requests through or refusing them, and write that choice down.
Press Play on a diagram to walk through it one step at a time.
- 1INCR usage key
quota:t1:u7:2026-12-01T10
- 2Over the limit?
Yes: 429 with Retry-After
- 3Look up cache key
Tenant, model and prompt versions in the key
- 4Hit: return cached
No model call, no cost
- 5Miss: call model
Store result with SET ... EX
- Skip Redis and carry on
- Right for the cache: go to the source
- Risk: higher load and cost
- Log and alert on every fallback
- Refuse the request with 503
- Right when a limit protects money or safety
- Risk: an outage for every user
- Keep the error message honest
- Who
- tenant_id
- What data
- docs_version for the tenant
- Which model
- model ID
- prompt template version
- Which input
- SHA-256 of the normalised question
In depth
Cache keys that cannot leak or go stale
A cache key must include everything that changes the answer. For a question about documents that is the tenant, the set of documents or their versions, a hash of the normalised question, the model name and the prompt template version. Leave out the tenant and one company can receive another's answer. Leave out the prompt version and a prompt fix seems to do nothing because old answers keep coming back.
Hash long inputs with SHA-256 so keys stay short. Add a namespace and a schema version at the front, such as qa:v2:, so you can change the stored format later without reading old values. For document-level invalidation, keep a per-tenant counter such as docs_version:t1 that you increment whenever a document is added or deleted, and include it in the key; old entries then simply stop being used and expire.
- Namespace and format version: qa:v2
- Tenant ID, always
- Document set version for the tenant
- Model ID and prompt version
- SHA-256 of the normalised input
TTLs and the cache-aside pattern
The service uses cache-aside: look in Redis first; on a miss, compute from the source, then store the result with SET key value EX seconds. Redis never talks to PostgreSQL or the model itself. The TTL is a safety net: even if you forget an invalidation, data cannot be older than the TTL.
Pick TTLs from how stale the data may be. A model answer for an unchanged document set can live for an hour. A job status that clients poll should live for seconds or not be cached at all. Add a little random jitter to TTLs so many keys created together do not expire at the same moment. If one popular key expires and hundreds of requests miss at once, they all call the model; a short lock with SET key token NX EX 30 lets one request recompute while others wait briefly or serve the old value.
- API to Redis: GET qa:v2:t1:dv7:m3:p5:hash1GET qa:v2:t1:dv7:m3:p5:hash
- Redis to API: nil (miss)2nil (miss)
- API to Model gateway: Generate answer3Generate answer
- Model gateway to API: Answer and token usage4Answer and token usage
- API to Redis: SET key answer EX 36005SET key answer EX 3600
Counting usage atomically
Redis runs each command one at a time, so INCR is atomic: two requests incrementing the same key always get different results, such as 41 and 42. Never read the count, add one in Python and write it back, because two requests can read 41 together and both pass.
A fixed window uses one key per user per period, for example quota:t1:u7:2026-12-01T10 for that hour. Send INCR and EXPIRE together in a MULTI/EXEC transaction through a redis-py pipeline. EXPIRE with the NX flag, available from Redis 7.0, sets the expiry only if the key has none, so later increments do not push it forward. Fixed windows allow a burst at the edge of two windows; if that matters, use a sliding window or a token bucket written as a small Lua script. For cost, you can count tokens instead of requests with INCRBY after the model replies.
Telling the client about limits
When the counter is over the limit, raise HTTPException with status 429 and a Retry-After header in seconds until the window resets. Use a stable error code in the body, such as quota_exceeded, so the UI can show a helpful message instead of a generic failure. Do not count requests that you reject for validation or auth errors, and decide whether a failed model call still uses quota.
Keep two kinds of limits apart. A rate limit protects the service from bursts and is often enforced at a proxy or gateway. A usage quota is a product and cost rule that depends on the user and plan, so the application enforces it. Both can return 429, but the message and Retry-After differ.
Planning for a Redis outage
Give the Redis client short timeouts, for example socket_timeout and socket_connect_timeout of a few hundred milliseconds, so an outage costs little latency. Wrap cache calls so that any RedisError is logged, counted in a metric and treated as a miss. That is fail-open, and it is right for a cache because PostgreSQL and the model remain the source of truth.
Quotas need a decision. Fail-closed refuses model calls with 503 while Redis is down: safe for cost, bad for users. Fail-open allows calls without counting: good for users, but a long outage can run up a large bill. A middle path is a small in-process limit per worker while Redis is down. Locally Redis runs free in Docker; in Azure the managed option is Azure Managed Redis, which is paid, and Azure Cache for Redis is being retired.
- 1Redis call fails or times out
- 2Apply the documented fallback
Miss for cache, chosen policy for quota
- 3Count it in a metric and log once
- 4Alert when the fallback rate rises
- 5Recover and confirm metrics return to normal
- Back to step 1
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Set TTLs on cached results~35m
- 2Build cache keys with tenant and versions~35m
- 3Count usage with atomic increments~35m
- 4Return 429 when a quota is spent~35m
- 5Decide fail-open or fail-closed~35m
Key points
- Every cached value needs a TTL so stale or deleted data ages out by itself.
- Build keys from the tenant, the input hash and the model and prompt versions so tenants never share answers and upgrades never serve old ones.
- Count usage with INCR, which is atomic, and set an expiry on the first increment so each window resets.
- Return 429 Too Many Requests with a Retry-After header when a quota is spent.
- Choose fail-open for the cache and decide deliberately for quotas; write the choice down.
Key terms
Tap a card to flip it. 0/6 known
Examples
import redis.asyncio as redis
r = redis.from_url("redis://localhost:6379/0")
async def charge(tenant: str, user: str, hour: str, limit: int) -> bool:
key = f"quota:{tenant}:{user}:{hour}"
async with r.pipeline(transaction=True) as pipe:
pipe.incr(key)
pipe.expire(key, 3600, nx=True) # only set on the first call
used, _ = await pipe.execute()
return used <= limit # False -> raise HTTPException(429)INCR and EXPIRE NX run together in one MULTI/EXEC transaction; EXPIRE NX needs Redis 7 or later.
Run Redis locally and watch a quota fill up
Prerequisites: Docker and the redis-cli inside the container. Step 1: start Redis. Step 2: increment a quota key five times and set its expiry only once. Step 3: read the TTL to see the window counting down. Evidence: INCR returns 1 to 5 and TTL shows a number below 3600. Cleanup: remove the container. In production you would use a managed Redis service, which costs money, but the commands are the same.
docker run -d --name ragsvc-redis -p 6379:6379 redis:7
docker exec -it ragsvc-redis redis-cli
> INCR quota:t1:u7:2026-12-01T10
(integer) 1
> EXPIRE quota:t1:u7:2026-12-01T10 3600 NX
(integer) 1
> INCR quota:t1:u7:2026-12-01T10
(integer) 2
> TTL quota:t1:u7:2026-12-01T10
(integer) 3594
docker rm -f ragsvc-redisA quota dependency that returns 429 and fails closed
Step 1: build the hourly key from the tenant and user. Step 2: increment and set the expiry in one transaction. Step 3: if Redis fails, refuse with 503, because this team decided an unmetered model bill is worse than a short outage. Step 4: if over the limit, return 429 with Retry-After set to the seconds left in the hour. Test it with a fake clock and a limit of 2: the third call must get 429.
async def enforce_quota(user=Depends(current_user), r=Depends(get_redis)):
now = datetime.now(timezone.utc)
key = f"quota:{user.tenant_id}:{user.id}:{now:%Y-%m-%dT%H}"
try:
async with r.pipeline(transaction=True) as p:
used, _ = await p.incr(key).expire(key, 3600, nx=True).execute()
except RedisError:
raise HTTPException(503, "Usage service unavailable")
if used > user.hourly_limit:
retry = 3600 - (now.minute * 60 + now.second)
raise HTTPException(429, "quota_exceeded", headers={"Retry-After": str(retry)})Quick reference
- SET key value EX 300 stores with a 5-minute TTL; TTL key shows seconds left
- INCR is atomic; never read-modify-write a counter in Python
- EXPIRE key 3600 NX sets the expiry only if none exists (Redis 7.0+)
- Cache keys: namespace, tenant, data version, model, prompt version, input hash
- Cache failure: fail open and treat as a miss
- Quota failure: choose fail-open or fail-closed and document it
- 429 Too Many Requests plus Retry-After in seconds
- redis.asyncio client: create in lifespan, close with await r.aclose()
Common mistakes
- Leaving the tenant out of a cache key, which can show one company's answer to another.
- Reading the counter, adding one in Python and writing it back; two requests can both pass the check.
- Caching forever, so deleted documents keep appearing in cached answers.
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 a function that builds a cache key for a question from the tenant ID, docs version, model ID, prompt version and question text.
- Exercise 2medium
Write a cache-aside helper that returns a cached answer if present, otherwise calls a compute function, stores the result with a TTL plus jitter, and treats Redis errors as a miss.
- Exercise 3hard
A tenant deletes a document. Make sure no cached answer that used that document is served again, without scanning Redis for keys.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is Redis free?
- Redis runs free locally, for example in Docker with the official redis image. Managed services such as Azure Managed Redis or other cloud offerings are paid; check the provider's pricing before creating one.
- Should I cache model answers at all?
- Cache when the same question over the same data is common and a slightly old answer is acceptable. Do not cache personal or highly sensitive answers under shared keys, and keep TTLs short where documents change often.
- Why not keep quotas in PostgreSQL?
- You can, and it is fine at low traffic. Redis handles very frequent increments with less load and has built-in expiry, which makes per-window counters simple.
- What is the difference between a rate limit and a quota?
- A rate limit caps how fast requests arrive, to protect the service. A quota caps how much a user may consume in a period, usually for cost or plan reasons.