Caching & Redis
Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.
Python Redis WATCH optimistic lock mock
A MockRedis class that simulates WATCH/MULTI/EXEC transactions with optimistic locking to detect concurrent modifications before committing.
import time
import threading
class MockRedis:
def __init__(self):
self.data = {}
self.watched = {}
self.lock = threading.Lock()
def get(self, key):
return self.data.get(key)
def set(self, key, value):
self.data[key] = value
def watch(self, *keys):
wi…
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 INCR DECR Counter Mock in Python
Simulate Redis INCR and DECR commands with a Python class to test counter logic without a live Redis server.
class RedisCounter:
def __init__(self):
self._store = {}
def incr(self, key: str, amount: int = 1) -> int:
if key not in self._store:
self._store[key] = 0
self._store[key] += amount
return self._store[key]
def decr(self, key: str, amount: int = 1) -> int:
…
Redis LPUSH RPOP List Queue Mock in Python
Implements a FIFO queue using Redis lists with LPUSH and RPOP commands, simulating task processing in Python.
import redis
import time
r = redis.Redis(host='localhost', port=6379, db=0)
queue_key = 'task_queue'
# Push tasks onto the left side (LPUSH)
r.lpush(queue_key, 'task1')
r.lpush(queue_key, 'task2')
r.lpush(queue_key, 'task3')
# Mock processing: pop from the right side (RPOP) — FIFO order
while r.llen(queue_key) > 0:…
Redis Leaky Bucket Rate Limiting Mock in Python
Simulates a Redis-backed leaky bucket rate limiter using a local class with continuous leaking and token capacity checks.
import time
from collections import deque
class LeakyBucket:
def __init__(self, capacity, leak_rate):
self.capacity = capacity
self.leak_rate = leak_rate
self.water = 0.0
self.timestamp = time.time()
self.history = deque()
def allow(self):
current = time.time(…
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)…
Redis-inspired sliding window rate limiter in Python
A pure-Python sliding window rate limiter using a deque of timestamps, mock-ready for Redis-backed production limits.
import time
from collections import deque
class SlidingWindowRateLimiter:
def __init__(self, max_requests: int, window_seconds: int) -> None:
self.max_requests = max_requests
self.window_seconds = window_seconds
self.requests: dict[str, deque] = {}
def is_allowed(self, client_id: str…
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.