Prompt
how to cache api responses with ttl
Latest observation
Oct 25, 2026
OpenAI APIWeb search: off
To cache API responses with a TTL (time to live), you generally:
-
Choose a cache store
- In-memory cache for simple/single-instance apps
- Redis/Memcached for shared/distributed caching
-
Use a cache key
- Build a key from the request details, e.g.:
- endpoint path
- query params
- headers that affect the response
- authenticated user/tenant if needed
- Build a key from the request details, e.g.:
-
On each request
- Check cache first
- If found and not expired, return cached response
- If missing/expired, call the API, store the result with TTL, then return it
Basic pattern
cache_key = make_key(request)
if cache.exists(cache_key):
return cache.get(cache_key)
response = fetch_from_api(request)
cache.set(cache_key, response, ttl=300) // 5 minutes
return response
Example in Python with Redis
import json
import redis
import requests
r = redis.Redis(host='localhost', port=6379, db=0)
def get_weather(city):
cache_key = f"weather:{city.lower()}"
cached = r.get(cache_key)
if cached:
return json.loads(cached)
response = requests.get(f"https://api.example.com/weather?city={city}")
data = response.json()
# TTL in seconds
r.setex(cache_key, 300, json.dumps(data))
return data
Example in Node.js with Redis
import Redis from "ioredis";
import fetch from "node-fetch";
const redis = new Redis();
async function getWeather(city) {
const cacheKey = `weather:${city.toLowerCase()}`;
const cached = await redis.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
const res = await fetch(`https://api.example.com/weather?city=${city}`);
const data = await res.json();
// TTL = 300 seconds
await redis.set(cacheKey, JSON.stringify(data), "EX", 300);
return data;
}
Important TTL tips
-
Set TTL based on how often data changes
- Static data: longer TTL
- Frequently changing data: shorter TTL
-
Prevent cache stampede
- If many requests miss at once, they may all hit the API
- Use locking, request coalescing, or stale-while-revalidate
-
Cache only what makes sense
- Avoid caching highly personalized or sensitive data unless keys are user-specific
-
Consider invalidation
- TTL helps expire data automatically, but sometimes you also need manual invalidation after updates
HTTP-level caching option
If you control the API or want client/proxy caching, you can also use headers like:
Cache-Control: max-age=300
ETag: "abc123"
This tells browsers and intermediate caches to store the response for 300 seconds.
If you want, I can show:
- a framework-specific example (FastAPI, Express, Django, Spring)
- a local in-memory cache version
- or a cache-aside pattern with Redis and TTL in more detail.