Caching & Redis
Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.
How to Build a Bloom Filter to Reduce Cache Misses in Python
Implement a probabilistic Bloom filter in Python that lets a cache quickly determine which keys are definitely not present, reducing expensive source lookups on cache misses.
import hashlib
import random
class BloomFilter:
def __init__(self, size=100, num_hashes=3):
self.size = size
self.num_hashes = num_hashes
self.bit_array = [0] * size
def _hashes(self, item):
result = []
for i in range(self.num_hashes):
hash_value = int(hash…
How to Implement a Negative Cache with TTL in Python
This code provides a TTL mock cache that stores negative results (cache misses) for a short time to reduce repeated lookups of missing keys.
from time import time, sleep
class TTLMockCache:
def __init__(self, ttl_seconds=5):
self.ttl = ttl_seconds
self.store = {}
self.negative_cache = {}
def get(self, key):
now = time()
if key in self.store:
value, expires_at = self.store[key]
if exp…
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.