Caching & Redis
Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.
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 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)…
Refresh Proactive TTL Renewal in Python
This snippet implements a proactive TTL renewal pattern that refreshes a cache expiration before it lapses, using a mock counter to track renewals.
import time
from datetime import datetime, timezone
class TTLRenewer:
def __init__(self, ttl_seconds=10, renew_at=0.5):
self.ttl = ttl_seconds
self.last_renewed = time.time()
self.renew_threshold = ttl_seconds * renew_at
self.renewals = 0
def check_and_renew(self):
if …
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.