API Caching Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓API Caching runs in O(1) time and O(n) space, in Python as in every other language.
- ✓functools.lru_cache and functools.cache memoise a pure function in-process; hashlib gives you the digest for an ETag.
- ✓Compute a strong ETag from the response body and compare it against If-None-Match, returning 304 with no body when they match.
- ✓The Python trap: The locmem backend is per-process, so with several gunicorn workers the same request returns a cached value from one worker and a fresh one from the next, and a cache clear only clears the worker that handled it.
- ✓A Redis-backed Django cache pays pickle serialisation on both sides, and for large querysets that cost can exceed the query it was avoiding; measure before caching wide objects.
What API Caching actually is
API Caching in Python: what you actually reach for
Python implementation
import hashlib
from django.core.cache import cache
from django.http import HttpResponse, HttpResponseNotModified
def report(request):
key = f"report:v{cache.get('report:version', 1)}:{request.GET.get('range', '7d')}"
body = cache.get(key)
if body is None:
body = build_report(request.GET.get("range", "7d"))
cache.set(key, body, timeout=300)
etag = hashlib.sha256(body.encode()).hexdigest()
if request.headers.get("If-None-Match") == etag:
return HttpResponseNotModified() # 304, no body on the wire
resp = HttpResponse(body)
resp["ETag"] = etag
resp["Cache-Control"] = "private, max-age=60, stale-while-revalidate=300"
return resp
# invalidate by bumping the version, never by hunting for keys to delete
def invalidate() -> None:
cache.set("report:version", cache.get("report:version", 1) + 1)Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for API Caching?
functools.lru_cache and functools.cache memoise a pure function in-process; hashlib gives you the digest for an ETag. Beyond that it is framework territory: Django ships a full cache framework at django.core.cache with locmem, Redis and database backends plus @cache_page, and Flask-Caching provides the equivalent decorators. redis-py or pymemcache is the shared store underneath.
What is the most common Python mistake when implementing API Caching?
The locmem backend is per-process, so with several gunicorn workers the same request returns a cached value from one worker and a fresh one from the next, and a cache clear only clears the worker that handled it. The second trap is decorating a view with @lru_cache: the request object is part of the key and is rarely equal between requests, so the cache never hits and simply leaks memory.
How does API Caching actually perform in Python?
A Redis-backed Django cache pays pickle serialisation on both sides, and for large querysets that cost can exceed the query it was avoiding; measure before caching wide objects. lru_cache is a C-level dict lookup and is essentially free, which is why it is the right tool for pure computation and the wrong one for per-request data. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.