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