Reference library

Caching & Redis

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

4 matches
Caching & Redis medium

How to Cache Data in Redis with Python

Build a simple Redis cache wrapper that stores and retrieves JSON data with automatic TTL and serialization.

redis cache json
Python
import redis
import json
import time


class Cache:
    def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
        self.client = redis.Redis(host=host, port=port, db=db)
        self.default_ttl = default_ttl

    def get(self, key):
        value = self.client.get(key)
        if value is None:
  …
14 0 Open
Caching & Redis easy

How to Cache Function Results with Redis in Python

A RedisCache helper class caches function results using a decorator, with JSON serialization and TTL-based expiry.

redis caching decorator
Python
import redis
import json
from functools import wraps

class RedisCache:
    def __init__(self, host='localhost', port=6379, db=0, ttl=60):
        self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
        self.ttl = ttl

    def cached(self, key_prefix):
        def decorator(func):
       …
14 0 Open
Caching & Redis medium

How to Serialize Cache Values with JSON and Pickle in Python

Serialize cache values using JSON for simple types or pickle for arbitrary objects, with robust error handling for unsupported types like mocks.

serialization caching json
Python
import json
import pickle
from unittest.mock import Mock

def serialize(value, method="json"):
    """Serialize a cache value using JSON or pickle with type checking."""
    if method == "json":
        try:
            return json.dumps(value).encode("utf-8")
        except TypeError as e:
            raise ValueErro…
11 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.