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 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 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,…
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:
…
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.