Reference library

Caching & Redis

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

6 matches
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 hard

Coalescing duplicate in-flight requests: one shared result for concurrent callers

Runs identical concurrent requests through a single shared call, caching the result while it's in flight and returning the same value to all callers.

concurrency threading coalescing
Python
import time
import threading
from collections import defaultdict


class CoalescingExecutor:
    def __init__(self):
        self._locks = defaultdict(threading.Lock)
        self._in_flight = {}

    def execute(self, key, func):
        with self._locks[key]:
            if key in self._in_flight:
                re…
16 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 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

Mock Redis Distributed Lock in Python with SET NX EX

A minimal in-memory mock of Redis SET NX EX distributed lock semantics for testing concurrent code without a real Redis server.

redis distributed-lock concurrency
Python
import time
import threading
import uuid
from typing import Optional


class RedisLockMock:
    """A minimal mock of Redis SET NX EX distributed lock semantics."""

    def __init__(self):
        self._store = {}  # key -> (value, expiry_epoch)

    def acquire(self, key: str, token: str, ttl_seconds: int) -> bool:
 …
15 0 Open
Caching & Redis medium

Python Redis WATCH optimistic lock mock

A MockRedis class that simulates WATCH/MULTI/EXEC transactions with optimistic locking to detect concurrent modifications before committing.

redis optimistic-locking transactions
Python
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…
12 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.