Caching & Redis
Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.
Cache Penetration Null Object Mock in Python
Implement a cache that stores a null marker on misses to prevent repeated database hits, reducing cache penetration.
import time
from collections import defaultdict
from typing import Any, Optional
class Cache:
def __init__(self):
self.store: dict[str, Any] = {}
self.ttl: dict[str, float] = {}
self.null_marker = object()
def get(self, key: str, ttl: int = 60, fallback:
Any = None) -> An…
Consistent Hashing Cache Shard in Python
A minimal consistent hashing ring with virtual nodes that distributes cache keys across shards and minimizes re-mapping when a node is removed.
import hashlib
import bisect
class ConsistentHashRing:
def __init__(self, nodes=None, replicas=3):
self.replicas = replicas
self.ring = {}
self.sorted_keys = []
if nodes:
for node in nodes:
self.add_node(node)
def _hash(self, key):
return i…
How to Cache Data in Redis with Python
Build a simple Redis cache wrapper that stores and retrieves JSON data with automatic TTL and serialization.
import redis
import json
import time
class Cache:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db)
self.default_ttl = default_ttl
def get(self, key):
value = self.client.get(key)
if value is None:
…
How to Implement a Write-Through Cache in Python with a Mock Database
A thread-safe write-through cache that updates both cache and mock database atomically, computing values only after a successful write to the database.
import threading
import time
import random
class WriteThroughCache:
def __init__(self):
self.cache = {}
self.db = {}
self.lock = threading.Lock()
def write(self, key, value):
with self.lock:
# Simulate slow database write
time.sleep(random.uniform(0.01…
How to Implement an LFU Cache in Python
Implement a Least Frequently Used (LFU) cache with frequency tracking dictionaries to evict the least accessed items when capacity is reached.
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.data = {}
self.freq = {}
self.min_freq = 0
def get(self, key: int) -> int:
if key not in self.data:
return -1
self._increment_freq(key)
return self.data[key]
…
How to Validate and Cache Data with Redis in Python
A beginner-friendly helper that validates email, phone, and age data and caches validated entries in Redis for 5 minutes.
import redis
import json
from functools import wraps
class DataValidator:
def __init__(self, host="localhost", port=6379, db=0):
self.cache = redis.Redis(host=host, port=port, db=db)
self.validators = {
"email": lambda v: "@" in v and "." in v.split("@")[-1],
"phone": lambd…
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.