Reference library

Caching & Redis

Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.

22 matches
Caching & Redis medium

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.

cache ttl jitter
Python
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…
15 0 Open
Caching & Redis medium

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.

bloom-filter caching probabilistic
Python
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…
14 0 Open
Caching & Redis medium

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.

redis cache json
Python
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:
  …
14 0 Open
Caching & Redis medium

How to Cache Function Results in Redis with Python

A Python decorator that caches function results in Redis using TTL, with optional fakeredis for testing without a server.

redis caching decorator
Python
import redis
import json
import time
try:
    import fakeredis
except ImportError:
    fakeredis = None

from functools import wraps


def cache_redis(cache_key_prefix="cache", ttl=60):
    """Decorator to cache function results in Redis."""
    if fakeredis:
        r = fakeredis.FakeStrictRedis()
    else:
        r…
14 0 Open
Caching & Redis medium

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.

caching expiration heap
Python
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…
14 0 Open
Caching & Redis medium

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.

cache ttl negative-cache
Python
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…
13 0 Open
Caching & Redis medium

How to Implement a Redis-Like Cache Dictionary in Python

Build a RedisMockDict class that mimics basic Redis key-value operations with TTL support, expiry cleanup, and standard dict-like methods.

redis cache ttl
Python
from collections import OrderedDict
import time

class RedisMockDict:
    def __init__(self, ttl=None):
        self._data = OrderedDict()
        self._ttl = ttl  # default TTL in seconds, None = no expiry
        self._expiry = {}

    def set(self, key, value, ttl=None):
        """Set a key-value pair with optiona…
12 0 Open
Caching & Redis medium

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.

caching write-through threading
Python
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…
12 0 Open
Caching & Redis medium

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.

lfu cache frequency
Python
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]

  …
12 0 Open
Caching & Redis medium

How to Mock Cache Tag Invalidation in Python

Use unittest.mock.patch with wraps to verify tagged cache entries are invalidated correctly.

unittest mock cache
Python
import unittest
from unittest.mock import patch

def get_cached_data(cache, key):
    """Return data from cache if present and valid, else None."""
    if cache.get(key, {}).get("valid", False):
        return cache[key]["data"]
    return None

def invalidate_tag_mock(cache, tag):
    """Invalidate all cache entries …
14 0 Open
Caching & Redis medium

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.

redis mock ttl
Python
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…
14 0 Open
Caching & Redis medium

How to Mock Redis Pipeline Batch Commands in Python

Create a lightweight MockRedis class that simulates Redis pipeline batching with SET, GET, and DELETE operations for testing without a live server.

redis pipeline mock
Python
import redis
import time


class MockRedis:
    def __init__(self):
        self.data = {}

    def pipeline(self):
        return MockPipeline(self)

    def execute(self, commands):
        results = []
        for cmd in commands:
            op, args = cmd[0], cmd[1:]
            if op == "SET":
                se…
14 0 Open
Caching & Redis medium

How to Mock Redis Pub/Sub in Python

Test Redis pub/sub logic without a live server using an in-memory fake that queues published messages per channel.

redis pubsub testing
Python
import redis
import time
import threading


class MockRedisPubSub:
    def __init__(self):
        self.channels = {}

    def publish(self, channel, message):
        if channel not in self.channels:
            return 0
        for subscriber in self.channels[channel]:
            subscriber.put(message)
        ret…
13 0 Open
Caching & Redis medium

How to Mock Redis Streams Consumer Groups in Python

Simulate Redis Streams producer and consumer group behavior in Python using a standalone mock class for testing and development.

redis streams mock
Python
import time
import json
from collections import defaultdict

class RedisStreamMock:
    def __init__(self):
        self.streams = defaultdict(list)
        self.consumer_groups = defaultdict(dict)
        self.pending_entries = defaultdict(list)

    def xadd(self, stream, fields):
        entry_id = f"{time.time_ns(…
14 0 Open
Caching & Redis medium

How to Mock a Redis Session Store Cookie SID in Python

Mock a Redis-backed session store with a cookie-based session ID (SID) in Python, including the create, read, and delete operations.

redis session cookies
Python
import redis
import uuid
import time


class RedisSessionStore:
    def __init__(self, host="localhost", port=6379, db=0, prefix="session:"):
        self.client = redis.Redis(host=host, port=port, db=db)
        self.prefix = prefix

    def create_session(self, timeout_seconds=3600):
        session_id = uuid.uuid4(…
14 0 Open
Caching & Redis medium

How to Mock a Redis Transaction with MULTI/EXEC in Python

A minimal in-memory mock of Redis MULTI/EXEC transactions that queues commands and applies them atomically on EXEC.

redis mock transactions
Python
class RedisTransactionMock:
    def __init__(self):
        self.data = {}
        self.queue = []
        self.in_transaction = False

    def multi(self):
        self.in_transaction = True
        self.queue = []
        return "OK"

    def set(self, key, value):
        if self.in_transaction:
            self.qu…
14 0 Open
Caching & Redis medium

How to Mock zlib Compression for Cache Values in Python

Compress cache values with zlib and mock the compress function in unit tests to simulate cache behavior.

zlib mock caching
Python
import zlib
from unittest.mock import patch

def compress_value(data: bytes) -> bytes:
    """Compress data using zlib and return the compressed bytes."""
    return zlib.compress(data)

def decompress_value(compressed: bytes) -> bytes:
    """Decompress zlib data and return the original bytes."""
    return zlib.deco…
11 0 Open
Caching & Redis medium

How to Serialize Cache Values with JSON and Pickle in Python

Serialize cache values using JSON for simple types or pickle for arbitrary objects, with robust error handling for unsupported types like mocks.

serialization caching json
Python
import json
import pickle
from unittest.mock import Mock

def serialize(value, method="json"):
    """Serialize a cache value using JSON or pickle with type checking."""
    if method == "json":
        try:
            return json.dumps(value).encode("utf-8")
        except TypeError as e:
            raise ValueErro…
12 0 Open
Caching & Redis medium

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.

redis caching validation
Python
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…
15 0 Open
Caching & Redis medium

How to implement Redlock distributed lock in Python

Simulate Redis Redlock multi-instance locking to show how a distributed lock is acquired only when a majority of instances agree.

redlock distributed-locking redis
Python
import time
import random
import threading
from dataclasses import dataclass


@dataclass
class MockRedisLock:
    """Simple mock of a Redis lock instance."""
    name: str
    key: str
    ttl: int
    acquired: bool = False
    expires_at: float = 0.0

    def acquire(self, sleep_fn=time.sleep):
        """Try to ac…
17 0 Open
Caching & Redis medium

How to implement a write-behind cache with async queue in Python

Build an async write-behind cache that queues writes in memory and flushes them in batches to persistent storage.

write-behind cache asyncio
Python
import asyncio
from collections import deque
from dataclasses import dataclass

@dataclass
class CacheEntry:
    key: str
    value: str

class WriteBehindCache:
    def __init__(self, flush_interval=1.0):
        self.cache = {}
        self.queue = deque()
        self.flush_interval = flush_interval
        self._f…
14 0 Open
Caching & Redis medium

How to mock Redis geospatial commands (GEOADD) in Python

Implement a lightweight Python mock of Redis geospatial commands (GEOADD, GEODIST, GEOSEARCH) using the Haversine formula for testing without a Redis server.

redis geospatial haversine
Python
import math
import heapq


class MockRedisGeo:
    def __init__(self):
        self.members = {}

    def geoadd(self, key, longitude, latitude, member):
        if key not in self.members:
            self.members[key] = {}
        self.members[key][member] = (longitude, latitude)

    def geodist(self, key, member1,…
13 0 Open

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.