Reference library

Caching & Redis

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

35 matches
Caching & Redis medium

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.

caching null-object ttl
Python
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…
17 0 Open
Caching & Redis medium

Cache Stampede Prevention with SingleFlight in Python

Implements a SingleFlight pattern in Python to deduplicate concurrent cache-miss computations and prevent cache stampede.

caching concurrency singleflight
Python
import threading
import time
from functools import wraps


class SingleFlight:
    def __init__(self):
        self._lock = threading.Lock()
        self._inflight = None

    def do(self, key, fn):
        with self._lock:
            if self._inflight is not None:
                return self._inflight[1]
           …
15 0 Open
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 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 easy

How to Cache Function Results with Redis in Python

A RedisCache helper class caches function results using a decorator, with JSON serialization and TTL-based expiry.

redis caching decorator
Python
import redis
import json
from functools import wraps

class RedisCache:
    def __init__(self, host='localhost', port=6379, db=0, ttl=60):
        self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
        self.ttl = ttl

    def cached(self, key_prefix):
        def decorator(func):
       …
14 0 Open
Caching & Redis easy

How to Implement Namespaced Cache Keys for Tenant Isolation in Python

Build a tenant-aware cache wrapper that prefixes keys with tenant and namespace, and test it with mocks.

cache tenant namespace
Python
from keyvaluestore import SimpleCache
from unittest.mock import patch

class TenantCache(SimpleCache):
    def __init__(self, tenant_id, namespace="default"):
        super().__init__()
        self.tenant_id = tenant_id
        self.namespace = namespace

    def _key(self, key):
        return f"tenant:{self.tenant_…
17 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 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 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 easy

How to Invalidate a Cache in Python with lru_cache

This code demonstrates how to clear the cache of an @lru_cache decorated function in Python using cache_clear(), showing the effect on cached results.

lru_cache cache-invalidation functools
Python
from functools import lru_cache
import time

@lru_cache(maxsize=None)
def expensive_operation(key):
    return f"Computed value for {key} at {time.time():.6f}"

def invalidate_cache():
    expensive_operation.cache_clear()

if __name__ == "__main__":
    print(expensive_operation("alpha"))
    print(expensive_operatio…
13 0 Open
Caching & Redis easy

How to Iterate Redis Keys with SCAN in Python

Iterate all Redis keys matching a pattern using the SCAN command with a mock client to simulate pagination.

redis scan keys
Python
import redis

def scan_keys(client, pattern="*", count=10):
    keys = []
    cursor = 0
    while True:
        cursor, batch = client.scan(cursor=cursor, match=pattern, count=count)
        keys.extend(batch)
        if cursor == 0:
            break
    return keys

if __name__ == "__main__":
    # Mock Redis clien…
15 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 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 easy

How to Mock a Cache Key Schema Version Bump in Python

Show how to test a cache key schema bump by mocking the class-level version attribute with unittest.mock.

mock caching unittest
Python
from unittest import mock

class VersionCache:
    SCHEMA_VERSION = 1

    def __init__(self, key_prefix="cache"):
        self.key_prefix = key_prefix

    def build_key(self, resource_id):
        return f"{self.key_prefix}:schema-v{self.SCHEMA_VERSION}:{resource_id}"

    def bump_schema(self):
        # Simulated …
13 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…
11 0 Open
Caching & Redis easy

How to Use Redis as a Cache in Python

A beginner-friendly RedisCache helper that stores, retrieves, and deletes JSON values with automatic TTL expiration using the redis-py client.

redis cache ttl
Python
import json
import time
import redis


class RedisCache:
    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 set(self, key, value, ttl=None):
        """Store a v…
11 0 Open
Caching & Redis easy

How to Use lru_cache in Python for Cache-on-Miss Population

Demonstrates lru_cache to automatically populate cache on a miss and serve subsequent calls from cache, with cache info stats.

lru_cache caching functools
Python
from functools import lru_cache

@lru_cache(maxsize=None)
def fetch_user(user_id):
    """Simulates a slow database fetch."""
    print(f"Cache miss: fetching user {user_id} from database")
    return {"id": user_id, "name": f"User {user_id}"}

if __name__ == "__main__":
    user = fetch_user(1)
    print(f"First call…
15 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

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.