Reference library

Caching & Redis

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

3 matches
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 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 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

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.