Reference library

Caching & Redis

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

4 matches
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 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
Caching & Redis easy

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.

redis counter mock
Python
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:
     …
16 0 Open
Caching & Redis easy

Redis SADD SMEMBERS Set Mock in Python

A lightweight mock of Redis SADD and SMEMBERS using Python sets for testing or local caching.

redis mock set
Python
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)…
14 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.