Caching & Redis
Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.
How to Add TTL Jitter to Cache Expiration in Python
A Python decorator that adds random jitter to cache TTLs, staggering expiration times to prevent cache avalanche.
import random
import time
from functools import wraps
def add_jitter(ttl: float, jitter_range: float = 0.1) -> float:
"""Add random jitter (as % of TTL) to stagger cache expiration and prevent avalanche."""
jitter = random.uniform(-jitter_range, jitter_range)
return ttl * (1 + jitter)
def cache_with_jitt…
How to Implement Probabilistic Early Expiration in Python
A Python mock of probabilistic early expiration for caches, using a heap-based expiry queue and random eviction to approximate cache stampede protection.
import heapq
import random
import time
class ProbabilisticEarlyExpirationMock:
def __init__(self, capacity=1024, expiration_probability=0.1):
self.capacity = capacity
self.expiration_probability = expiration_probability
self._items = {}
self._expiry_heap = []
self._next_id…
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 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…
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_…
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 …
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.