StackPractices
intermediate By Mathias Paulenko

Cache Database Query Results with Redis and Python

Cache expensive database query results in Redis with cache-aside pattern, TTL management, and invalidation on writes for Python applications.

Overview

Every request that re-runs the same expensive query is wasted database work — a product page that executes the same SELECT hundreds of times a minute is the classic example. Caching the result in Redis turns that round-trip into a sub-millisecond lookup. This recipe uses the cache-aside pattern in Python: check Redis first, query the database on a miss, and store the result with a TTL. On top of the basics it covers invalidation on writes, a lock that prevents stampedes, negative caching, and batch reads with MGET. For a Node.js version, see Node.js Caching with Redis.

When to Use This

  • Expensive queries (aggregations, joins, full-text search) that run often
  • Read-heavy workloads where the underlying rows change infrequently
  • Cutting database load during traffic spikes
  • Dashboards and reports where a few minutes of staleness is acceptable
  • Skip it when reads must always return the freshest row — stock levels, balances, or anything where a stale answer is worse than a slow one

Prerequisites

  • Python 3.10+
  • Redis server
  • redis (redis-py) and sqlalchemy packages

Solution

1. Install Dependencies

pip install redis sqlalchemy

2. Cache-Aside Pattern

import json
import redis
from sqlalchemy import create_engine, text

engine = create_engine("postgresql://user:pass@localhost/mydb")
redis_client = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)

NOT_FOUND = "null"  # sentinel for negative caching

def fetch_product_from_db(product_id: int) -> dict | None:
    with engine.connect() as conn:
        result = conn.execute(
            text("SELECT id, name, price FROM products WHERE id = :id"),
            {"id": product_id}
        )
        row = result.fetchone()
    if row is None:
        return None
    return {"id": row.id, "name": row.name, "price": float(row.price)}

def get_product(product_id: int) -> dict | None:
    cache_key = f"product:{product_id}"

    # 1. Check cache — the sentinel marks "known to not exist"
    cached = redis_client.get(cache_key)
    if cached == NOT_FOUND:
        return None
    if cached:
        return json.loads(cached)

    # 2. Fetch from database on miss
    product = fetch_product_from_db(product_id)

    # 3. Store the result — real data for 5 min, misses for 60 s
    if product is None:
        redis_client.setex(cache_key, 60, NOT_FOUND)
    else:
        redis_client.setex(cache_key, 300, json.dumps(product))
    return product

3. Cache Invalidation on Writes

def update_product(product_id: int, name: str, price: float) -> dict:
    with engine.begin() as conn:
        conn.execute(
            text("UPDATE products SET name = :name, price = :price WHERE id = :id"),
            {"id": product_id, "name": name, "price": price}
        )

    # Invalidate cache — next read fetches fresh data
    redis_client.delete(f"product:{product_id}")

    return {"id": product_id, "name": name, "price": price}

def delete_product(product_id: int) -> None:
    with engine.begin() as conn:
        conn.execute(
            text("DELETE FROM products WHERE id = :id"),
            {"id": product_id}
        )

    redis_client.delete(f"product:{product_id}")

4. Caching List Queries

def get_products_by_category(category_id: int, page: int = 1, per_page: int = 20) -> list:
    cache_key = f"products:category:{category_id}:page:{page}:size:{per_page}"

    cached = redis_client.get(cache_key)
    if cached:
        return json.loads(cached)

    offset = (page - 1) * per_page
    with engine.connect() as conn:
        result = conn.execute(
            text("""
                SELECT id, name, price FROM products
                WHERE category_id = :cat
                ORDER BY created_at DESC
                LIMIT :limit OFFSET :offset
            """),
            {"cat": category_id, "limit": per_page, "offset": offset}
        )
        products = [
            {"id": row.id, "name": row.name, "price": float(row.price)}
            for row in result
        ]

    redis_client.setex(cache_key, 300, json.dumps(products))
    return products

def invalidate_category_cache(category_id: int) -> None:
    # Delete all paginated cache entries for this category
    pattern = f"products:category:{category_id}:*"
    keys = list(redis_client.scan_iter(match=pattern, count=100))
    if keys:
        redis_client.delete(*keys)

5. Cache Stampede Prevention with Lock

import time
import uuid

def get_product_with_lock(product_id: int) -> dict | None:
    cache_key = f"product:{product_id}"
    lock_key = f"lock:{cache_key}"

    cached = redis_client.get(cache_key)
    if cached:
        return None if cached == NOT_FOUND else json.loads(cached)

    # Try to acquire the lock — only one worker goes to the DB
    lock_token = str(uuid.uuid4())
    lock_acquired = redis_client.set(lock_key, lock_token, nx=True, ex=10)

    if lock_acquired:
        try:
            # Double-check: another worker may have refilled the cache already
            cached = redis_client.get(cache_key)
            if cached:
                return None if cached == NOT_FOUND else json.loads(cached)

            product = fetch_product_from_db(product_id)
            if product is None:
                redis_client.setex(cache_key, 60, NOT_FOUND)
            else:
                redis_client.setex(cache_key, 300, json.dumps(product))
            return product
        finally:
            # Release the lock only if we still own it (atomic compare-and-delete)
            lua_script = """
            if redis.call("get", KEYS[1]) == ARGV[1] then
                return redis.call("del", KEYS[1])
            else
                return 0
            end
            """
            redis_client.eval(lua_script, 1, lock_key, lock_token)

    # Another worker holds the lock — retry briefly, then fall back to the DB
    for _ in range(5):
        time.sleep(0.1)
        cached = redis_client.get(cache_key)
        if cached:
            return None if cached == NOT_FOUND else json.loads(cached)

    return fetch_product_from_db(product_id)

6. Caching Aggregation Queries

def get_sales_summary(start_date: str, end_date: str) -> dict:
    cache_key = f"sales:summary:{start_date}:{end_date}"

    cached = redis_client.get(cache_key)
    if cached:
        return json.loads(cached)

    with engine.connect() as conn:
        result = conn.execute(
            text("""
                SELECT
                    COUNT(*) as total_orders,
                    SUM(total) as revenue,
                    AVG(total) as avg_order_value
                FROM orders
                WHERE created_at BETWEEN :start AND :end
            """),
            {"start": start_date, "end": end_date}
        )
        row = result.fetchone()

    summary = {
        "total_orders": row.total_orders,
        "revenue": float(row.revenue) if row.revenue else 0,
        "avg_order_value": float(row.avg_order_value) if row.avg_order_value else 0,
    }

    # Cache for 5 minutes — aggregates tolerate staleness
    redis_client.setex(cache_key, 300, json.dumps(summary))
    return summary

7. Write-Through Cache

def create_product_write_through(name: str, price: float, category_id: int) -> dict:
    with engine.begin() as conn:
        result = conn.execute(
            text("""
                INSERT INTO products (name, price, category_id)
                VALUES (:name, :price, :cat)
                RETURNING id, name, price
            """),
            {"name": name, "price": price, "cat": category_id}
        )
        row = result.fetchone()

    product = {"id": row.id, "name": row.name, "price": float(row.price)}

    # Populate cache immediately — no stale window
    redis_client.setex(f"product:{row.id}", 300, json.dumps(product))

    # Invalidate list caches that would include this product
    invalidate_category_cache(category_id)

    return product

8. Batch Cache Loading

def get_products_batch(product_ids: list) -> dict:
    # MGET reads every requested key in a single round-trip
    cache_keys = [f"product:{pid}" for pid in product_ids]
    cached_values = redis_client.mget(cache_keys)

    results = {}
    missing_ids = []

    for pid, cached in zip(product_ids, cached_values):
        if cached:
            results[pid] = json.loads(cached)
        else:
            missing_ids.append(pid)

    # Fetch the misses in one query instead of one query per id
    if missing_ids:
        with engine.connect() as conn:
            placeholders = ",".join(f":id{i}" for i in range(len(missing_ids)))
            params = {f"id{i}": pid for i, pid in enumerate(missing_ids)}
            result = conn.execute(
                text(f"SELECT id, name, price FROM products WHERE id IN ({placeholders})"),
                params
            )
            for row in result:
                product = {"id": row.id, "name": row.name, "price": float(row.price)}
                results[row.id] = product
                redis_client.setex(f"product:{row.id}", 300, json.dumps(product))

    return results

How It Works

sequenceDiagram diagram: participant C as Client
  1. Cache-aside: the application checks Redis before touching the database. A hit returns the stored value; a miss runs the query and writes the result back with a TTL.
  2. Invalidation: every write (INSERT, UPDATE, DELETE) deletes the matching cache keys, so the next read repopulates with fresh data instead of serving yesterday’s row.
  3. Cache stampede: when a hot key expires, every concurrent request would hit the database at the same time. A SET with NX EX lock lets a single worker fetch while the rest retry briefly and, as a last resort, read the DB directly.
  4. Batch loading: MGET reads all the requested keys in one Redis command instead of N round-trips; the misses come back in a single WHERE id IN (...) query.
  5. TTL as safety net: explicit invalidation covers the normal case, and the TTL quietly repairs whatever invalidation misses — a bug, an exception, a bulk UPDATE nobody hooked.

Variants

Cache with TTL Jitter

import random

def set_with_jitter(key: str, value: str, base_ttl: int = 300):
    # Spreading expirations avoids a mass expiry of keys written together
    jitter = random.randint(0, 60)
    redis_client.setex(key, base_ttl + jitter, value)

Read-Through Cache (Transparent)

class ReadThroughCache:
    def __init__(self, redis_client, db_fetch_fn, ttl=300):
        self.redis = redis_client
        self.fetch_fn = db_fetch_fn
        self.ttl = ttl

    def get(self, key: str, *args, **kwargs):
        cached = self.redis.get(key)
        if cached:
            return json.loads(cached)

        value = self.fetch_fn(*args, **kwargs)
        if value is not None:
            self.redis.setex(key, self.ttl, json.dumps(value))
        return value

# Usage
product_cache = ReadThroughCache(
    redis_client,
    lambda pid: fetch_product_from_db(pid),
    ttl=300
)
product = product_cache.get("product:42", 42)

Multi-Level Cache (L1 Memory + L2 Redis)

from cachetools import TTLCache  # pip install cachetools

# L1: in-process cache with its own short TTL — nothing lives forever
l1_cache = TTLCache(maxsize=1000, ttl=60)

def get_product_l1(product_id: int) -> dict | None:
    if product_id in l1_cache:
        return l1_cache[product_id]

    cached = redis_client.get(f"product:{product_id}")
    if cached:
        product = None if cached == NOT_FOUND else json.loads(cached)
    else:
        product = fetch_product_from_db(product_id)

    l1_cache[product_id] = product
    return product

# L1 hit: microseconds. L1 miss -> L2 (Redis) -> DB.
# Keep the L1 TTL short: L1 entries are not invalidated when Redis is,
# so they age out on their own clock.

Cache with Stale-While-Revalidate

def get_product_swr(product_id: int) -> dict | None:
    cache_key = f"product:{product_id}"
    stale_key = f"stale:{cache_key}"

    cached = redis_client.get(cache_key)
    if cached:
        return None if cached == NOT_FOUND else json.loads(cached)

    # The fresh copy expired — check the stale window
    stale = redis_client.get(stale_key)
    if stale:
        # Serve the stale value and refresh in the background
        # (Celery, RQ, or a thread — e.g. refresh_product_cache.delay(product_id))
        return json.loads(stale)

    # No copy at all — fetch synchronously
    product = fetch_product_from_db(product_id)
    if product is None:
        redis_client.setex(cache_key, 60, NOT_FOUND)
        return None

    redis_client.setex(cache_key, 300, json.dumps(product))
    # The stale copy lives 10 extra minutes past the fresh TTL
    redis_client.setex(stale_key, 900, json.dumps(product))
    return product

Best Practices

  • For a deeper guide, see Complete Guide to Redis Caching Strategies.
  • Cache at the right granularity: one key per query plus its parameters, holding the full result — not individual rows you’d have to glue back together.
  • Always set a TTL, even with explicit invalidation: it’s the safety net that repairs stale data when an invalidation silently fails.
  • Use SETEX, not SET + EXPIRE: two commands leave a race window where the key exists with no expiry; SETEX sets value and TTL atomically.
  • Invalidate list caches on writes: creating or deleting a product changes every page of its category, so drop products:category:{id}:* along with product:{id}.
  • Use MGET for batch reads: fetching 100 products with 100 GETs costs 100 round-trips; MGET is one.
  • Watch the hit rate: below ~50% the cache is keyed wrong or the workload isn’t cacheable. Redis reports keyspace_hits and keyspace_misses in INFO stats.

Common Mistakes

  • Caching with no TTL: if invalidation ever fails, the stale value lives forever.
  • Invalidating too broadly: wiping product:* when one product changes clears everything. Delete the specific keys.
  • Skipping negative caching: without the NOT_FOUND sentinel, every request for a missing product goes straight to the database. Cache misses too — with a short TTL.
  • Cache key collisions: namespace your keys (product:42, not 42), or two different queries end up sharing one entry.
  • Forgetting bulk operations: UPDATE products SET price = price * 1.1 bypasses per-key invalidation entirely. Bump a version prefix or flush the affected pattern afterwards.

Frequently Asked Questions

What's the difference between cache-aside and read-through?

In cache-aside the application checks the cache and queries the database itself; in read-through a cache layer does the fetching transparently on a miss. Cache-aside gives you control over invalidation and edge cases; read-through keeps application code simpler.

How do I cache paginated queries?

Put the page and page size in the key — products:category:1:page:3:size:20. When a product in the category changes, delete every page with the pattern products:category:1:* using SCAN, not KEYS (which blocks Redis on large keyspaces).

Should I cache JOINs?

Yes, when the join is expensive and its result is read far more often than the underlying rows change. Cache the denormalized result and invalidate it when any of the joined tables is written — or accept the stale window your TTL gives you.

What is negative caching?

Caching the fact that a key doesn't exist — the NOT_FOUND sentinel in the example above. A short TTL (30–60 seconds) stops repeated database hits for missing products without hiding new inserts for long.

What TTL should I use?

Whatever staleness the feature tolerates. Five minutes (300 s) works for most catalog data; drop to 30–60 s for fast-moving records and stretch past 15 minutes for data that rarely changes. Remember the TTL is a safety net — invalidation on writes is what actually keeps data fresh.

What happens when Redis goes down?

Every request turns into a cache miss and the full read load lands on the database. Set a short connection timeout and wrap Redis calls in a try/except that falls back to the DB — that turns an outage into a latency bump instead of a 500 storm.

How do I measure cache effectiveness?

INFO stats exposes keyspace_hits and keyspace_misses; the hit rate is hits / (hits + misses). Healthy workloads sit above ~80%. If yours is much lower, fix the key design and TTL before throwing memory at it.