Skip to main content

Databases · Intermediate · 25 min

Cache database results in Redis with cache-aside and TTLs

By Padding · Updated 18 Nov 2026
Debian 13 (redis:8 image) · Redis 8.12 · Python 3.15 · redis-py 8.2

You will put a Redis 8 cache in front of a slow product lookup in Python, with versioned keys, jittered TTLs, invalidation on write, short-lived "not found" entries, a lock against cache stampedes and an eviction policy, and measure the hit rate and latency it gives you.

On this page

A cache earns its place when the same expensive answer is asked for again and again. A product page is the classic case: thousands of shoppers ask for the same few hundred products, and each request makes the database run the same query. Keeping the answer in Redis for a few minutes turns a slow database read into a memory lookup that takes well under a millisecond.

The pattern in this tutorial is called cache-aside. Your code asks Redis first. On a hit it uses the cached copy. On a miss it reads the database, stores the result in Redis with an expiry time (a TTL), and returns it. Redis never talks to the database itself; your code decides what goes in and when it leaves.

You build a small Python project for an online shop that sells phone accessories. The product lookup is a SQLite query with a deliberate 20 ms pause, standing in for a busy database across a network. You wrap it in a cache, measure the hit rate and latency, and then deal with the problems every real cache meets: stale data after a write, repeated lookups for products that do not exist, a crowd of requests rebuilding the same entry at once, and running out of memory.

Fast responses matter most to the people with the slowest connections. A shopper on a low-end Android phone on prepaid mobile data already waits for every round trip; a server that answers in 2 ms instead of 30 ms makes the page feel responsive on a weak signal.

Step 1 · Build the project and the slow product store

Check that Redis is answering before you start:

Bash
redis-cli ping

It prints PONG. If your Redis requires a password, add --askpass to every redis-cli command in this tutorial, so the password is typed at a prompt instead of landing in your shell history.

Create a throwaway project folder and add redis-py, the official Python client. The version range allows patch releases of 8.2 and nothing newer:

Bash
mkdir -p ~/redis-cache-demo
cd ~/redis-cache-demo
uv init --no-package --python 3.15
uv add "redis>=8.2,<8.3"

Tell the code where Redis is with an environment variable, so the address lives outside the code:

Bash
export REDIS_URL="redis://localhost:6379/0"

If your server needs a password, do not type it into an export line. Create a private file first with install -m 600 /dev/null ~/.redis-cache-demo.env, open it in an editor and add one line such as REDIS_URL=redis://:your-password@localhost:6379/0 (replace the password), then load it with set -a; . ~/.redis-cache-demo.env; set +a.

Now create the database. seed.py makes 1,000 products. Prices are stored in cents as whole numbers, so they add up exactly:

Bash
cat > seed.py <<'PY'
import sqlite3
from contextlib import closing

NAMES = ["Phone case", "USB-C cable", "Power bank", "Earbuds", "Screen protector"]

with closing(sqlite3.connect("shop.db")) as conn, conn:
    conn.execute("DROP TABLE IF EXISTS products")
    conn.execute(
        "CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL,"
        " price_cents INTEGER NOT NULL)"
    )
    conn.executemany(
        "INSERT INTO products (id, name, price_cents) VALUES (?, ?, ?)",
        [(i, f"{NAMES[i % 5]} #{i}", 500 + (i * 137) % 9500) for i in range(1, 1001)],
    )
    print("products:", conn.execute("SELECT count(*) FROM products").fetchone()[0])
PY
uv run seed.py

store.py is the slow data layer the rest of the project calls. It counts every real database read in db_calls, so you can see later how many reads the cache saves:

Bash
cat > store.py <<'PY'
import sqlite3
import threading
import time
from contextlib import closing
from pathlib import Path

DB_PATH = Path(__file__).with_name("shop.db")
DB_DELAY_SECONDS = 0.02  # stands in for a busy database across the network

db_calls = 0
_count_lock = threading.Lock()


def load_product(product_id):
    """Read one product from the database, or None if it does not exist."""
    global db_calls
    with _count_lock:
        db_calls += 1
    time.sleep(DB_DELAY_SECONDS)
    with closing(sqlite3.connect(DB_PATH)) as conn:
        row = conn.execute(
            "SELECT id, name, price_cents FROM products WHERE id = ?", (product_id,)
        ).fetchone()
    if row is None:
        return None
    return {"id": row[0], "name": row[1], "price_cents": row[2]}


def update_price(product_id, price_cents):
    with closing(sqlite3.connect(DB_PATH)) as conn, conn:
        conn.execute(
            "UPDATE products SET price_cents = ? WHERE id = ?", (price_cents, product_id)
        )
PY
uv run python -c "import time, store; t = time.perf_counter(); print(store.load_product(7)); print(f'{(time.perf_counter() - t) * 1000:.0f} ms')"

Check it worked

seed.py printed products: 1000. The last command printed {'id': 7, 'name': 'Power bank #7', 'price_cents': 1459} and a time of a little over 20 ms. Every call to load_product costs that much, however often you ask for the same product.

Step 2 · Add cache-aside reads with versioned keys and jittered TTLs

Three decisions shape every cached entry: the key, the value format and how long it lives.

Keys follow the form app:version:type:id, here shop:v1:product:7. The app prefix keeps this cache apart from anything else in the same Redis. The version lets you change the shape of the cached value safely: when you add a field, bump v1 to v2 and the new code stops reading old entries, which expire on their own. Values are JSON strings, which any language can read.

The TTL is 300 seconds plus a random extra of up to 60. Without that jitter, products cached together (after a deploy, or a busy sale starting) all expire in the same second, and the database takes the whole load at once.

Bash
cat > cache.py <<'PY'
import json
import os
import random

import redis

import store

r = redis.Redis.from_url(os.environ["REDIS_URL"], decode_responses=True)

KEY_VERSION = "v1"
TTL_SECONDS = 300
JITTER_SECONDS = 60

stats = {"hits": 0, "misses": 0}


def product_key(product_id):
    return f"shop:{KEY_VERSION}:product:{product_id}"


def ttl_with_jitter():
    return TTL_SECONDS + random.randint(0, JITTER_SECONDS)


def get_product(product_id):
    key = product_key(product_id)
    cached = r.get(key)
    if cached is not None:
        stats["hits"] += 1
        return json.loads(cached)
    stats["misses"] += 1
    product = store.load_product(product_id)
    if product is not None:
        r.set(key, json.dumps(product), ex=ttl_with_jitter())
    return product
PY

decode_responses=True makes redis-py return Python strings instead of bytes. ex= sets the TTL in the same command as the value, so there is never a moment where the key exists without an expiry.

Try it on product 7. The script deletes the key first, so the first read is always a miss:

Bash
cat > try_cache.py <<'PY'
import time

import cache

cache.r.delete(cache.product_key(7))
for label in ("first read", "second read"):
    start = time.perf_counter()
    product = cache.get_product(7)
    print(f"{label}: {product['name']} in {(time.perf_counter() - start) * 1000:.1f} ms")
print(cache.stats)
PY
uv run try_cache.py
redis-cli GET shop:v1:product:7
redis-cli TTL shop:v1:product:7

Check it worked

The first read takes a little over 20 ms and the second well under 1 ms. The stats line is {'hits': 1, 'misses': 1}. GET shows the JSON for product 7, and TTL shows a number of seconds between 300 and 360.

Step 3 · Measure the hit rate and latency

A cache is only worth its memory if it is hit often. The hit rate is hits divided by all lookups. Measure it, with latency, before trusting the cache.

bench.py replays 200 lookups across 50 popular products, the same sequence every time because the random generator is seeded. It runs them once against the database alone and once through the cache, starting from an empty cache:

Bash
cat > bench.py <<'PY'
import random
import statistics
import time

import cache
import store


def timed(label, lookup, ids):
    times = []
    for product_id in ids:
        start = time.perf_counter()
        lookup(product_id)
        times.append((time.perf_counter() - start) * 1000)
    times.sort()
    p95 = times[int(len(times) * 0.95)]
    print(f"{label}: mean {statistics.mean(times):.2f} ms, p95 {p95:.2f} ms")


for key in cache.r.scan_iter("shop:v1:product:*"):
    cache.r.delete(key)

rng = random.Random(42)
ids = [rng.randint(1, 50) for _ in range(200)]

timed("database only", store.load_product, ids)
timed("with cache   ", cache.get_product, ids)

hits, misses = cache.stats["hits"], cache.stats["misses"]
print(f"hit rate: {hits / (hits + misses):.0%} ({hits} hits, {misses} misses)")
PY
uv run bench.py
redis-cli INFO stats | grep -E '^keyspace_(hits|misses)'

scan_iter walks the keys in small batches with SCAN. Never use KEYS on a live server: it blocks Redis while it reads every key.

The hit rate here comes from counters in your own code. The INFO stats lines are Redis's own count of reads that found a key and reads that did not, across every client since the server started. On a shared server, watch them over time instead of reading them once.

Check it worked

The last line of bench.py reads hit rate: 76% (151 hits, 49 misses): 49 different products appear in the sequence, and each misses once. The database-only mean is a little over 20 ms. The cached mean is around a quarter of that, because a quarter of lookups still go to the database, and the p95 stays high for the same reason. On real traffic the hit rate rises with the TTL and with how concentrated the requests are; a hit rate below about 50% is a sign the TTL is too short or the data is too varied to cache.

Step 4 · Cache "not found" answers briefly

Look up a product that does not exist, three times:

Bash
cat > missing.py <<'PY'
import cache
import store

for attempt in (1, 2, 3):
    print(attempt, cache.get_product(99999))
print("database reads:", store.db_calls)
PY
uv run missing.py

It prints None three times and database reads: 3. The cache only stores products that exist, so every request for a missing one goes to the database. Bots that crawl made-up product IDs, or old links to deleted products, then bypass your cache entirely.

Replace cache.py with a version that stores a marker for "not found", with a TTL of 30 seconds. The marker is a fixed string that no real JSON product can equal. The short TTL matters: when someone creates product 99999, shoppers see "not found" for at most 30 seconds.

Bash
cat > cache.py <<'PY'
import json
import os
import random

import redis

import store

r = redis.Redis.from_url(os.environ["REDIS_URL"], decode_responses=True)

KEY_VERSION = "v1"
TTL_SECONDS = 300
JITTER_SECONDS = 60
MISSING_TTL_SECONDS = 30
MISSING = "__missing__"

stats = {"hits": 0, "misses": 0}


def product_key(product_id):
    return f"shop:{KEY_VERSION}:product:{product_id}"


def ttl_with_jitter():
    return TTL_SECONDS + random.randint(0, JITTER_SECONDS)


def _decode(value):
    return None if value == MISSING else json.loads(value)


def _store(key, product):
    if product is None:
        r.set(key, MISSING, ex=MISSING_TTL_SECONDS)
    else:
        r.set(key, json.dumps(product), ex=ttl_with_jitter())


def get_product(product_id):
    key = product_key(product_id)
    cached = r.get(key)
    if cached is not None:
        stats["hits"] += 1
        return _decode(cached)
    stats["misses"] += 1
    product = store.load_product(product_id)
    _store(key, product)
    return product
PY
uv run missing.py
redis-cli TTL shop:v1:product:99999

If your app creates products, delete the product's key when it does, so a new product never hides behind its own "not found" marker.

Check it worked

The second run of missing.py prints None three times and database reads: 1. TTL shows a number between 1 and 30.

Step 5 · Invalidate the cache when the data changes

A TTL limits how stale an entry can get, but five minutes of an old price is too long when someone changes it. When your code writes to the database, it must also remove the cached copy. Add a write function to cache.py:

Bash
cat >> cache.py <<'PY'


def update_price(product_id, price_cents):
    """Write to the database first, then drop the cached copy."""
    store.update_price(product_id, price_cents)
    r.delete(product_key(product_id))
PY

The order matters. Deleting the key before the database write leaves a gap where another request misses, reads the old price from the database and caches it again. Deleting after the write closes most of that gap. Deleting is also safer than writing the new value into the cache: two updates racing each other can leave the older value in the cache, while a delete always ends with the next read fetching the truth.

Now compare a write that skips the cache with one that goes through update_price. The script first puts product 7 back to its seeded price of 1459 and clears its cached copy, so you can run it as often as you like and get the same output:

Bash
cat > update.py <<'PY'
import cache
import store

# Start from a known state, so the script gives the same output every run.
store.update_price(7, 1459)
cache.r.delete(cache.product_key(7))

print("cached price:", cache.get_product(7)["price_cents"])

store.update_price(7, 1399)  # database only: the cache still holds the old price
print("after a database-only write:", cache.get_product(7)["price_cents"])

cache.update_price(7, 1299)  # database, then delete the cached copy
print("after update_price:", cache.get_product(7)["price_cents"])
PY
uv run update.py

Check it worked

The output is:

Text
cached price: 1459
after a database-only write: 1459
after update_price: 1299

The middle line is the bug you are guarding against: the database says 1399, but shoppers would see 1459 until the TTL ran out. Any code path that writes products (an admin form, a nightly price import) has to go through update_price, or delete the key itself.

Step 6 · Stop a cache stampede with a short lock

When a popular entry expires, every request that arrives before it is rebuilt misses, and all of them query the database for the same row. On a busy product this is a stampede: tens or hundreds of identical queries at once, often at the worst moment.

Simulate it with 20 threads that ask for the same product at the same instant, with the product not in the cache:

Bash
cat > stampede.py <<'PY'
import threading

import cache
import store

PRODUCT_ID = 42
CALLERS = 20

cache.r.delete(cache.product_key(PRODUCT_ID))
start = threading.Barrier(CALLERS)


def shopper():
    start.wait()
    cache.get_product(PRODUCT_ID)


threads = [threading.Thread(target=shopper) for _ in range(CALLERS)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(f"callers: {CALLERS}, database reads: {store.db_calls}")
PY
uv run stampede.py

It prints something like callers: 20, database reads: 20: every caller missed and went to the database.

The fix: on a miss, a caller tries to take a short lock with SET key value NX PX 2000. NX means "only if the key does not exist", so exactly one caller gets it; PX 2000 makes the lock expire after 2,000 ms, so a caller that crashes cannot block the product for ever. The winner reads the database and fills the cache. The others wait a few milliseconds at a time for the value to appear.

Each lock holds a random token, and the lock is released by a small Lua script that deletes it only if the token still matches. If a rebuild ever takes longer than 2 seconds, the lock expires and another caller may take it; without the check, the slow caller would delete someone else's lock. Redis runs a Lua script as one step, so the check and the delete cannot be split by another client.

Replace cache.py with the final version:

Bash
cat > cache.py <<'PY'
import json
import os
import random
import time
import uuid

import redis

import store

r = redis.Redis.from_url(os.environ["REDIS_URL"], decode_responses=True)

KEY_VERSION = "v1"
TTL_SECONDS = 300
JITTER_SECONDS = 60
MISSING_TTL_SECONDS = 30
MISSING = "__missing__"
LOCK_MS = 2000  # longer than the slowest rebuild you expect
WAIT_STEP_SECONDS = 0.01

stats = {"hits": 0, "misses": 0}

_release_lock = r.register_script("""
if redis.call('GET', KEYS[1]) == ARGV[1] then
  return redis.call('DEL', KEYS[1])
end
return 0
""")


def product_key(product_id):
    return f"shop:{KEY_VERSION}:product:{product_id}"


def ttl_with_jitter():
    return TTL_SECONDS + random.randint(0, JITTER_SECONDS)


def _decode(value):
    return None if value == MISSING else json.loads(value)


def _store(key, product):
    if product is None:
        r.set(key, MISSING, ex=MISSING_TTL_SECONDS)
    else:
        r.set(key, json.dumps(product), ex=ttl_with_jitter())


def get_product(product_id):
    key = product_key(product_id)
    cached = r.get(key)
    if cached is not None:
        stats["hits"] += 1
        return _decode(cached)
    stats["misses"] += 1

    lock_key = f"{key}:lock"
    token = uuid.uuid4().hex
    if r.set(lock_key, token, nx=True, px=LOCK_MS):
        try:
            # Another caller may have filled the cache while we took the lock.
            cached = r.get(key)
            if cached is not None:
                return _decode(cached)
            product = store.load_product(product_id)
            _store(key, product)
            return product
        finally:
            _release_lock(keys=[lock_key], args=[token])

    # Someone else is rebuilding this entry: wait for their result.
    deadline = time.monotonic() + LOCK_MS / 1000
    while time.monotonic() < deadline:
        time.sleep(WAIT_STEP_SECONDS)
        cached = r.get(key)
        if cached is not None:
            return _decode(cached)
    # The rebuild took too long: read the database rather than fail the request.
    return store.load_product(product_id)


def update_price(product_id, price_cents):
    """Write to the database first, then drop the cached copy."""
    store.update_price(product_id, price_cents)
    r.delete(product_key(product_id))
PY
uv run stampede.py

The waiting callers still count as misses, because they did not find the value on their first look, but only one of them touched the database. The fallback at the end keeps a request working if the rebuild is slow; set LOCK_MS above the slowest query you expect so the fallback stays rare.

Check it worked

stampede.py now prints callers: 20, database reads: 1. Run the earlier scripts again to confirm nothing else changed: uv run missing.py still ends with database reads: 1, and uv run bench.py still reports hit rate: 76% (151 hits, 49 misses).

Step 7 · Set a memory limit and an eviction policy

A cache fills up. Out of the box Redis has no memory limit and the noeviction policy: on a server with a limit set, it refuses new writes once memory is full instead of dropping old keys. For a cache you want the opposite. With allkeys-lru, Redis removes the keys that were read least recently to make room. Redis approximates LRU by sampling a few keys at a time rather than tracking exact order, which is cheap and close enough for a cache.

See it happen on a second, throwaway Redis on port 6390 with an 8 MB limit and persistence turned off, so your main server is untouched:

Bash
redis-server --port 6390 --save '' --appendonly no --maxmemory 8mb --maxmemory-policy allkeys-lru --dir "$PWD" --pidfile "$PWD/redis-6390.pid" --daemonize yes
for i in $(seq 1 30); do redis-cli -p 6390 ping 2>/dev/null | grep -q PONG && break; sleep 1; done
redis-cli -p 6390 ping

Fill it with 20,000 values of 1 KB each, about 20 MB, through a pipeline that sends commands in batches of 100:

Bash
cat > evict.py <<'PY'
import redis

r = redis.Redis(port=6390, decode_responses=True)
value = "x" * 1024

pipe = r.pipeline(transaction=False)
for i in range(20_000):
    pipe.set(f"shop:v1:product:{i}", value)
    if i % 100 == 99:
        pipe.execute()

# Redis may still be evicting in the background, so read the counts in one
# transaction: they then describe the same moment.
snapshot = r.pipeline(transaction=True)
snapshot.dbsize()
snapshot.info("stats")
snapshot.info("memory")
kept, stats, memory = snapshot.execute()
print(f"keys kept: {kept} of 20000")
print(f"evicted: {stats['evicted_keys']}")
print(f"memory used: {memory['used_memory_human']} (limit {memory['maxmemory_human']})")
PY
uv run evict.py | tee evict.out
redis-cli -p 6390 SHUTDOWN NOSAVE

Check it worked

evict.py prints something like keys kept: 6500 of 20000 and an evicted count that makes up the difference, with memory used close to the 8 MB limit. Every write succeeded; Redis dropped older keys to make room. tee also saves the output to evict.out. SHUTDOWN NOSAVE stops the throwaway server, and redis-cli -p 6390 ping now fails because nothing is listening on that port.

Now set the same kind of limit on your main Redis. Pick a size that leaves room for the operating system and your app: on a 1 GB virtual server, 256 MB is a reasonable start.

Before you run this, check what else lives in this Redis. allkeys-lru may evict any key, including sessions, queues or rate-limit counters that are not cache. If the server holds that kind of data, use volatile-lru instead (it only evicts keys that have a TTL), or give the cache its own Redis instance.

Bash
redis-cli CONFIG SET maxmemory 256mb
redis-cli CONFIG SET maxmemory-policy allkeys-lru
redis-cli CONFIG GET maxmemory-policy

CONFIG SET takes effect at once but is lost on restart. To keep it, add these lines to your Redis config file, usually /etc/redis/redis.conf (edit it with sudo), replacing any existing maxmemory lines:

Text
maxmemory 256mb
maxmemory-policy allkeys-lru

If some products are read far more than others over hours, allkeys-lfu (least frequently used) can keep the popular ones better than LRU. Watch evicted_keys in redis-cli INFO stats: if it climbs steadily while the hit rate falls, the cache is too small for the data you put in it.

Step 8 · Keep private data out of shared keys and clean up

Everything you cached so far is the same for every shopper, which is what makes a shared key like shop:v1:product:7 safe. The dangerous mistake is caching a response that depends on who asked under a key that does not. If the product page includes "your saved address" or "your price as a wholesale buyer" and you cache the whole page under the product key, the next shopper sees the first shopper's details.

Rules to hold to:

  • Cache only data that is the same for everyone under shared keys. Build per-user parts of a page separately, after the cache lookup.
  • If you must cache per-user data, put the user ID in the key (shop:v1:user:812:basket), keep the TTL short and delete the key at logout.
  • Never cache passwords, password hashes, session tokens, API keys, one-time codes or card details. Redis keeps them in plain memory, and anyone who can run redis-cli against the server, or read a backup of it, can read them.
  • Cache responses that differ by language under keys that include the language (shop:v1:product:7:yo for Yoruba), so a shopper never gets another reader's translation.

Check that this cache holds only shared product keys. The command lists any key under shop:v1: that is not a product, or says that there are none:

Bash
redis-cli --scan --pattern 'shop:v1:*' | grep -v -E '^shop:v1:product:[0-9]+$' || echo "only product keys"

When you have finished, remove the cached keys and the demo project. The loop deletes only keys under shop:v1:, so other data in your Redis stays. The last command deletes the whole ~/redis-cache-demo folder:

Bash
redis-cli --scan --pattern 'shop:v1:*' | while read -r key; do redis-cli DEL "$key" > /dev/null; done
cd ~
rm -rf ~/redis-cache-demo

If you set the memory limit only for this tutorial, put the defaults back with redis-cli CONFIG SET maxmemory 0 and redis-cli CONFIG SET maxmemory-policy noeviction, and remove the lines you added to the config file.

Check it worked

The key check printed only product keys. After the clean-up, redis-cli --scan --pattern 'shop:v1:*' prints nothing, and ls ~/redis-cache-demo reports that the folder does not exist.

Next steps

  • Go back over the Redis data types and commands this tutorial relied on, such as SET with NX and EX, TTL and SCAN: /tutorials/learn-redis-data-types-with-redis-cli.
  • Cache at the HTTP layer as well, so browsers and CDNs keep responses and your server never sees the repeat requests: /tutorials/set-caching-headers-for-api-responses.
  • Use sorted sets in the same Redis to slow down password guessing on a login form: /tutorials/throttle-login-attempts-with-redis-sorted-sets.
  • Run your own Redis-compatible server with a password and a memory limit from the start: /tutorials/install-valkey-or-redis-on-ubuntu.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.