Caching & Redis
Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.
How to Implement a Write-Through Cache in Python with a Mock Database
A thread-safe write-through cache that updates both cache and mock database atomically, computing values only after a successful write to the database.
import threading
import time
import random
class WriteThroughCache:
def __init__(self):
self.cache = {}
self.db = {}
self.lock = threading.Lock()
def write(self, key, value):
with self.lock:
# Simulate slow database write
time.sleep(random.uniform(0.01…
How to Invalidate a Cache in Python with lru_cache
This code demonstrates how to clear the cache of an @lru_cache decorated function in Python using cache_clear(), showing the effect on cached results.
from functools import lru_cache
import time
@lru_cache(maxsize=None)
def expensive_operation(key):
return f"Computed value for {key} at {time.time():.6f}"
def invalidate_cache():
expensive_operation.cache_clear()
if __name__ == "__main__":
print(expensive_operation("alpha"))
print(expensive_operatio…
How to Mock Cache Tag Invalidation in Python
Use unittest.mock.patch with wraps to verify tagged cache entries are invalidated correctly.
import unittest
from unittest.mock import patch
def get_cached_data(cache, key):
"""Return data from cache if present and valid, else None."""
if cache.get(key, {}).get("valid", False):
return cache[key]["data"]
return None
def invalidate_tag_mock(cache, tag):
"""Invalidate all cache entries …
How to Validate and Cache Data with Redis in Python
A beginner-friendly helper that validates email, phone, and age data and caches validated entries in Redis for 5 minutes.
import redis
import json
from functools import wraps
class DataValidator:
def __init__(self, host="localhost", port=6379, db=0):
self.cache = redis.Redis(host=host, port=port, db=db)
self.validators = {
"email": lambda v: "@" in v and "." in v.split("@")[-1],
"phone": lambd…
Browse by section
Each section groups closely related Python snippets.
Caching & Redis — Python code examples
What you will find here
This page collects caching & redis snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.