Caching & Redis
Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.
How to Cache Function Results in Redis with Python
A Python decorator that caches function results in Redis using TTL, with optional fakeredis for testing without a server.
import redis
import json
import time
try:
import fakeredis
except ImportError:
fakeredis = None
from functools import wraps
def cache_redis(cache_key_prefix="cache", ttl=60):
"""Decorator to cache function results in Redis."""
if fakeredis:
r = fakeredis.FakeStrictRedis()
else:
r…
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 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 Mock Redis EXPIRE, TTL, and PERSIST in Python
A lightweight in-memory MockRedis class that simulates Redis key expiration, TTL, and persist behavior for tests and local development.
import time
class MockRedis:
def __init__(self):
self._store = {}
self._expiry = {}
def set(self, key, value):
self._store[key] = value
self._expiry.pop(key, None)
return True
def expire(self, key, ttl_seconds):
if key not in self._store:
retur…
How to Mock Redis Pipeline Batch Commands in Python
Create a lightweight MockRedis class that simulates Redis pipeline batching with SET, GET, and DELETE operations for testing without a live server.
import redis
import time
class MockRedis:
def __init__(self):
self.data = {}
def pipeline(self):
return MockPipeline(self)
def execute(self, commands):
results = []
for cmd in commands:
op, args = cmd[0], cmd[1:]
if op == "SET":
se…
How to Mock Redis Pub/Sub in Python
Test Redis pub/sub logic without a live server using an in-memory fake that queues published messages per channel.
import redis
import time
import threading
class MockRedisPubSub:
def __init__(self):
self.channels = {}
def publish(self, channel, message):
if channel not in self.channels:
return 0
for subscriber in self.channels[channel]:
subscriber.put(message)
ret…
How to Mock Redis Streams Consumer Groups in Python
Simulate Redis Streams producer and consumer group behavior in Python using a standalone mock class for testing and development.
import time
import json
from collections import defaultdict
class RedisStreamMock:
def __init__(self):
self.streams = defaultdict(list)
self.consumer_groups = defaultdict(dict)
self.pending_entries = defaultdict(list)
def xadd(self, stream, fields):
entry_id = f"{time.time_ns(…
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 Mock a Redis Transaction with MULTI/EXEC in Python
A minimal in-memory mock of Redis MULTI/EXEC transactions that queues commands and applies them atomically on EXEC.
class RedisTransactionMock:
def __init__(self):
self.data = {}
self.queue = []
self.in_transaction = False
def multi(self):
self.in_transaction = True
self.queue = []
return "OK"
def set(self, key, value):
if self.in_transaction:
self.qu…
How to Mock zlib Compression for Cache Values in Python
Compress cache values with zlib and mock the compress function in unit tests to simulate cache behavior.
import zlib
from unittest.mock import patch
def compress_value(data: bytes) -> bytes:
"""Compress data using zlib and return the compressed bytes."""
return zlib.compress(data)
def decompress_value(compressed: bytes) -> bytes:
"""Decompress zlib data and return the original bytes."""
return zlib.deco…
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 mock Redis geospatial commands (GEOADD) in Python
Implement a lightweight Python mock of Redis geospatial commands (GEOADD, GEODIST, GEOSEARCH) using the Haversine formula for testing without a Redis server.
import math
import heapq
class MockRedisGeo:
def __init__(self):
self.members = {}
def geoadd(self, key, longitude, latitude, member):
if key not in self.members:
self.members[key] = {}
self.members[key][member] = (longitude, latitude)
def geodist(self, key, member1,…
Implement a TTL cache with a mock clock in Python
This code creates a simple TTL cache that stores values with an expiration timestamp and allows injecting a mock time function to test expiry behavior deterministically.
import time
from functools import wraps
class TTLCache:
def __init__(self, ttl_seconds):
self.ttl = ttl_seconds
self.cache = {}
self._now = time.time
def set_mock_time(self, mock_time_fn):
"""Inject a mock time function for testing TTL expiry."""
self._now = mock_time_…
Mock Redis Distributed Lock in Python with SET NX EX
A minimal in-memory mock of Redis SET NX EX distributed lock semantics for testing concurrent code without a real Redis server.
import time
import threading
import uuid
from typing import Optional
class RedisLockMock:
"""A minimal mock of Redis SET NX EX distributed lock semantics."""
def __init__(self):
self._store = {} # key -> (value, expiry_epoch)
def acquire(self, key: str, token: str, ttl_seconds: int) -> bool:
…
Mock Redis Lua Script Atomic Execution in Python
A MockRedis class that simulates atomic Lua script execution via EVALSHA with a simplified parser for basic commands.
import hashlib
class MockRedis:
def __init__(self):
self.data = {}
self.scripts = {}
def script_load(self, script):
sha = hashlib.sha1(script.encode()).hexdigest()
self.scripts[sha] = script
return sha
def evalsha(self, sha, keys, args):
if sha not in self…
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 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)…
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.