Reference library

Caching & Redis

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

4 matches
Caching & Redis easy

How to Build a Redis Leaderboard with ZREVRANGE in Python

Build a sorted leaderboard by storing player scores as a Redis sorted set and reading the top scores with ZREVRANGE in Python.

redis leaderboard zrevrange
Python
import redis
import random

# Connect to local Redis (ensure Redis is running on localhost:6379)
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)

# Clear any existing test data
r.delete("game_scores")

# Simulate player scores
players = ["alice", "bob", "charlie", "dave", "eve"]
for player in…
12 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 easy

Redis Cache Helper Class in Python with TTL

Build a DataHelper class that caches function results in Redis with a default TTL, using get_or_set and clear methods.

redis caching cache-aside
Python
import redis
import json
import time


class DataHelper:
    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 get_or_set(self, key, data_func, ttl=None):
        c…
12 0 Open
Caching & Redis easy

Simple Redis Cache Helper in Python

Build a minimal Redis-backed cache with TTL, JSON serialization, and automated fetching to speed up repeated expensive lookups.

redis caching cache-aside
Python
import time
import redis
import json


class SimpleCache:
    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 get(self, key):
        value = self.client.get(key)…
10 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.