Reference library

Caching & Redis

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

8 matches
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 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 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 easy

How to implement a token bucket rate limiter in Python

A thread-safe in-memory token bucket rate limiter that tracks per-key tokens with refill logic, including a usage example after a timed refill.

rate-limiting token-bucket threading
Python
import time
import threading

class TokenBucketRateLimiter:
    def __init__(self, capacity, refill_rate):
        self.capacity = capacity
        self.refill_rate = refill_rate
        self.tokens = capacity
        self.last_refill_time = time.time()
        self.lock = threading.Lock()

    def allow_request(self,…
12 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

Implement a Multi-Level Cache with L1 Memory and L2 Redis in Python

This code implements a simple multi-level cache with an in-process L1 cache (via functools.lru_cache) and a mock Redis L2 cache with TTL, falling back to a slow computation on misses.

cache redis lru_cache
Python
import time
from functools import lru_cache


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

    def get(self, key):
        return self.store.get(key, None)

    def set(self, key, value, ttl=5):
        self.store[key] = (value, time.time() + ttl)

    def get_ttl(self, key):
        value, expiry…
15 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 easy

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.

redis mock ttl
Python
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 …
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.