Caching & Redis
Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.
Cache Asides in Python with a Read-Through Loader
Implements a cache-aside pattern with a read-through loader that fetches missing keys from a backing data store and caches them.
class DataStore:
"""Mock database with a few records."""
def __init__(self):
self.data = {1: "Alice", 2: "Bob", 3: "Charlie"}
def get(self, key):
print(f"Loading key {key} from database")
return self.data.get(key)
class CacheAsideLoader:
"""Cache-aside pattern with a read-thr…
Cache Data in Redis with Python
A beginner-friendly Redis cache helper that stores JSON strings with a TTL and retrieves them with the redis-py client.
import redis
class DataCache:
def __init__(self, host="localhost", port=6379, db=0):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
def cache_data(self, key, value, ttl=60):
self.client.setex(key, ttl, value)
def get_cached_data(self, key):
return …
Cache Warming with Python: Preload Hot Keys
Demonstrates a simple LRU-like cache with a warm method that preloads hot keys with mock values using OrderedDict.
import time
from collections import OrderedDict
class CacheWarm:
def __init__(self, capacity=3):
self.capacity = capacity
self.cache = OrderedDict()
self.hot_keys = []
def warm(self, keys):
"""Preload hot keys into cache with mock values."""
for key in keys:
…
How to Build a Redis Leaderboard with ZREVRANGE in Python
Build a sorted leaderboard by storing player scores as a Redis sorted set and reading the top scores with ZREVRANGE in Python.
import redis
import random
# Connect to local Redis (ensure Redis is running on localhost:6379)
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
# Clear any existing test data
r.delete("game_scores")
# Simulate player scores
players = ["alice", "bob", "charlie", "dave", "eve"]
for player in…
How to Cache Function Results with Redis in Python
A RedisCache helper class caches function results using a decorator, with JSON serialization and TTL-based expiry.
import redis
import json
from functools import wraps
class RedisCache:
def __init__(self, host='localhost', port=6379, db=0, ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.ttl = ttl
def cached(self, key_prefix):
def decorator(func):
…
How to Implement Namespaced Cache Keys for Tenant Isolation in Python
Build a tenant-aware cache wrapper that prefixes keys with tenant and namespace, and test it with mocks.
from keyvaluestore import SimpleCache
from unittest.mock import patch
class TenantCache(SimpleCache):
def __init__(self, tenant_id, namespace="default"):
super().__init__()
self.tenant_id = tenant_id
self.namespace = namespace
def _key(self, key):
return f"tenant:{self.tenant_…
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 Iterate Redis Keys with SCAN in Python
Iterate all Redis keys matching a pattern using the SCAN command with a mock client to simulate pagination.
import redis
def scan_keys(client, pattern="*", count=10):
keys = []
cursor = 0
while True:
cursor, batch = client.scan(cursor=cursor, match=pattern, count=count)
keys.extend(batch)
if cursor == 0:
break
return keys
if __name__ == "__main__":
# Mock Redis clien…
How to Mock a Cache Key Schema Version Bump in Python
Show how to test a cache key schema bump by mocking the class-level version attribute with unittest.mock.
from unittest import mock
class VersionCache:
SCHEMA_VERSION = 1
def __init__(self, key_prefix="cache"):
self.key_prefix = key_prefix
def build_key(self, resource_id):
return f"{self.key_prefix}:schema-v{self.SCHEMA_VERSION}:{resource_id}"
def bump_schema(self):
# Simulated …
How to Use Redis HSET and HGET in Python
This code demonstrates how to store and retrieve hash data in Redis using Python's redis library with HSET, HGET, HGETALL, and HDEL commands.
import redis
# Connect to Redis (adjust host/port as needed)
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
# Clear any existing data for demonstration
r.delete('user:1')
# HSET - Store a hash
r.hset('user:1', mapping={'name': 'Alice', 'age': 30, 'city': 'New York'})
# HGET - Retrieve a …
How to Use Redis ZADD and ZRANGE in Python
Add members to a Redis sorted set with ZADD and retrieve them in score order with ZRANGE in Python.
import redis
client = redis.Redis(host='localhost', port=6379, db=0)
client.delete('scores')
members = {'alice': 30, 'bob': 20, 'carol': 50}
for name, score in members.items():
client.zadd('scores', {name: score})
result = client.zrange('scores', 0, -1)
print(result)
How to Use Redis as a Cache in Python
A beginner-friendly RedisCache helper that stores, retrieves, and deletes JSON values with automatic TTL expiration using the redis-py client.
import json
import time
import redis
class RedisCache:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.default_ttl = default_ttl
def set(self, key, value, ttl=None):
"""Store a v…
How to Use lru_cache in Python for Cache-on-Miss Population
Demonstrates lru_cache to automatically populate cache on a miss and serve subsequent calls from cache, with cache info stats.
from functools import lru_cache
@lru_cache(maxsize=None)
def fetch_user(user_id):
"""Simulates a slow database fetch."""
print(f"Cache miss: fetching user {user_id} from database")
return {"id": user_id, "name": f"User {user_id}"}
if __name__ == "__main__":
user = fetch_user(1)
print(f"First call…
How to cache filtered data in Redis with Python
This code caches filtered list results in Redis using an MD5 hash key, returning cached results when available.
import redis
import json
import hashlib
import time
cache = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
def filter_data(data, predicate_key, predicate_value):
"""Filter a list of dicts by key-value pair, with Redis caching."""
cache_key = hashlib.md5(
f"{predicate_key}:{pred…
How to create a stable cache key from function arguments in Python
Generate a stable SHA-256 cache key from normalized function arguments, with keyword order normalized and tests using mocks.
import hashlib
import json
from unittest.mock import Mock
def make_cache_key(*args, **kwargs):
"""Normalize args/kwargs into a stable hash key for caching."""
normalized = {
"args": [repr(arg) for arg in args],
"kwargs": {key: repr(value) for key, value in sorted(kwargs.items())}
}
pa…
How to implement a token bucket rate limiter in Python
A thread-safe in-memory token bucket rate limiter that tracks per-key tokens with refill logic, including a usage example after a timed refill.
import time
import threading
class TokenBucketRateLimiter:
def __init__(self, capacity, refill_rate):
self.capacity = capacity
self.refill_rate = refill_rate
self.tokens = capacity
self.last_refill_time = time.time()
self.lock = threading.Lock()
def allow_request(self,…
How to memoize a function in Python with lru_cache
Use functools.lru_cache to memoize a recursive Fibonacci function, caching results for a fixed number of calls to avoid repeated computation.
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
if __name__ == "__main__":
for i in range(10):
print(f"fib({i}) = {fibonacci(i)}")
print(f"Cache info: {fibonacci.cache_info()}")
How to use Redis MGET MSET pipeline in Python
Store multiple keys atomically and read them efficiently with Redis MSET/MGET, then batch commands with a pipeline to cut round trips.
import redis # v4.x+ required
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
# Sample data to store
r.flushdb()
data = {"name": "Alice", "age": "30", "city": "Berlin"}
# MSET: store multiple key-value pairs in one command
r.mset(data)
# MGET: fetch multiple keys in one round trip
keys =…
Redis Cache Helper Class in Python with TTL
Build a DataHelper class that caches function results in Redis with a default TTL, using get_or_set and clear methods.
import redis
import json
import time
class DataHelper:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.default_ttl = default_ttl
def get_or_set(self, key, data_func, ttl=None):
c…
Redis GET SET EX TTL mock in Python
A thread-safe Python class mimicking Redis GET, SET with EX, and TTL commands for in-memory testing.
import time
import threading
from typing import Optional, Callable
class RedisTTLMock:
def __init__(self):
self._store: dict[str, tuple[str, float]] = {}
self._lock = threading.Lock()
def set(self, key: str, value: str, ex: Optional[int] = None) -> bool:
expiry = time.time() + ex if …
Redis INCR DECR Counter Mock in Python
Simulate Redis INCR and DECR commands with a Python class to test counter logic without a live Redis server.
class RedisCounter:
def __init__(self):
self._store = {}
def incr(self, key: str, amount: int = 1) -> int:
if key not in self._store:
self._store[key] = 0
self._store[key] += amount
return self._store[key]
def decr(self, key: str, amount: int = 1) -> int:
…
Redis LPUSH RPOP List Queue Mock in Python
Implements a FIFO queue using Redis lists with LPUSH and RPOP commands, simulating task processing in Python.
import redis
import time
r = redis.Redis(host='localhost', port=6379, db=0)
queue_key = 'task_queue'
# Push tasks onto the left side (LPUSH)
r.lpush(queue_key, 'task1')
r.lpush(queue_key, 'task2')
r.lpush(queue_key, 'task3')
# Mock processing: pop from the right side (RPOP) — FIFO order
while r.llen(queue_key) > 0:…
Redis SADD SMEMBERS Set Mock in Python
A lightweight mock of Redis SADD and SMEMBERS using Python sets for testing or local caching.
class RedisSetMock:
def __init__(self):
self.sets = {}
def sadd(self, key, *members):
if key not in self.sets:
self.sets[key] = set()
before = len(self.sets[key])
self.sets[key].update(members)
return len(self.sets[key]) - before
def smembers(self, key)…
Simple Redis Cache Helper in Python
Build a minimal Redis-backed cache with TTL, JSON serialization, and automated fetching to speed up repeated expensive lookups.
import time
import redis
import json
class SimpleCache:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.default_ttl = default_ttl
def get(self, key):
value = self.client.get(key)…
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.