Yazan.
Alle Artikel

Artikel liegen derzeit auf Englisch vor; der Rest der Seite folgt Ihrer gewählten Sprache.

2 Min. LesezeitRedisDatabasesBackend

How Redis Makes Your App Fast: Redis for Speed, the Database for Truth

How Redis Makes Your App Fast: Redis for Speed, the Database for Truth cover

If your app gets the same request 1,000 times a day, does it really need to ask the database 1,000 times?

Usually, no. And that's why people put Redis in front of it.

Redis keeps data in memory, so reading from it is really fast, often well under a millisecond.

Check Redis first

Most of the time it's used like this:

  1. The app checks Redis first.
  2. If the data isn't there, it gets it from the database and saves a copy in Redis for a few minutes.
  3. Every request after that gets the answer straight from memory, and the database gets a break.
Ten requests for the same product: the first goes to the database and takes 38 ms, the next nine come from Redis in under half a millisecond each
The first request takes the slow path. The next nine never touch the database. (Timings are illustrative.)

This is called cache-aside, and in Python it's only a few lines:

import json
import redis

cache = redis.Redis()

def get_product(product_id):
    key = f"product:{product_id}"
    cached = cache.get(key)
    if cached is not None:
        return json.loads(cached)               # fast path: straight from memory

    product = db.fetch_product(product_id)      # slow path: ask the database
    cache.setex(key, 300, json.dumps(product))  # keep a copy for five minutes
    return product

The expiry matters. Without one, a changed price can stay wrong in the cache forever. With one, the worst case is a few minutes of a stale answer, and the code that changes a product can delete its key so the next read fetches the new value straight away.

The one thing I always keep in mind

Especially working on payments: I use Redis to make things fast, not to keep the final record. If it crashes, the latest writes can be lost. That's fine for a cache. It's not fine for someone's balance.

So my rule is simple.

Redis for speed. The database for truth.

What was the first thing you used Redis for?

First shared on LinkedIn.