AlgoViz

Redis

medium 34 min

Redis keeps its whole dataset in memory and runs commands one after another, so every command is atomic and most take well under a millisecond.

Video lesson · Chapter 1 of 5

Two fans tap the heart

0:00 / 4:45

Video lesson · Chapter 1 of 5

A bus at the wrong stop

0:00 / 3:53

Theory

Read or listen first. About 2 min.

What it is

Redis is a server that holds data structures in memory. A client sends a short command such as GET, INCR or ZADD over TCP and gets a short answer back. The data never has to be fetched from a disk first.

It is more than a key-value cache. A value can be a hash, a list, a set, a sorted set or a stream, and the server knows how to change each one. The program does not have to read the whole value, change it and write it back.

Why it exists

A database page that is not cached costs a disk read, and a popular row may be read thousands of times a second. Keeping the hot data in memory removes that cost. Redis is the usual place to keep it, shared by every application server.

Many small jobs need one shared, fast, correct number: how many requests did this user make, who is at the top, who holds the lock. Because Redis runs one command at a time, these need no extra locking.

A short history

  1. 2009

    The Redis project starts, according to the Linux Foundation's account of its history.

  2. November 2009

    GitHub publishes Resque, a background job library that stores its queues in Redis lists.

  3. February 2016

    Martin Kleppmann publishes an analysis of Redlock and argues that a lock needs a fencing token. The debate is still a standard interview subject.

  4. March 2024

    After a licence change, the Linux Foundation announces Valkey, which continues from Redis 7.2.4 under the BSD licence.

  5. May 2025

    Redis 8 adds the AGPLv3 as a licence choice, so it is again available under an open source licence.

  6. November 2026

    Redis 8.12 is released, with a new encoding for large sorted sets and expiry for set members.

Words to know

Key
The name of a value, such as user:42. Any bytes; people use colons to group names.
TTL
Time to live. When it ends, the key is gone.
Eviction
Removing keys because memory is full, whether or not they have expired.
RDB
A snapshot file of the whole dataset at one moment.
AOF
Append-only file: a log of every write, replayed at start.
Replica
A copy that follows a primary, usually a little behind.
Hash slot
One of 16,384 groups of keys. In a cluster each slot belongs to one primary.
Pipelining
Sending several commands without waiting for each answer.

How it works

Step through the idea, or press Play.

Step 1 of 3

A command arrives. Over TCP, from a pooled connection

Understand it

Start here

The pancake stand

Imagine a pancake stand with one very fast cook and labelled jars within reach. Nothing is fetched from a cellar, and nobody else touches the jars.

One fast cook and the labelled jars
PANCAKEShoneysugarlemoncocoanutsAll in reach

The cook is quick because the work is small and everything is at hand, not because there are many cooks.

Inside

How one server works

One Redis server and one replica

Application servers send commands to one Redis machine. Inside it, one command thread runs each command against the data in memory, and background work writes the RDB and AOF files on disk. A separate replica machine receives the stream of writes.
The thick borders are machines. Reading sockets can use several threads; running commands uses one.

What happens to a command

  1. 1

    Connect

    Clients keep a pool of TCP connections and speak RESP, a simple protocol. The server watches thousands of sockets with epoll or kqueue; the default limit is 10,000 clients.

  2. 2

    Queue and run

    Commands run one at a time on the main thread. Since version 6, extra threads can read and write sockets (io-threads), but they never run two commands together.

  3. 3

    Change memory

    Small collections use a compact form called listpack, up to 512 hash fields or 128 sorted set members by default. Bigger ones switch to hash tables and ordered trees.

  4. 4

    Check the limit

    If a write would exceed maxmemory, the policy evicts keys or refuses the write.

  5. 5

    Record

    With the AOF on, the write is appended to the log. Snapshots are made by a forked child process.

  6. 6

    Replicate

    The write is streamed to replicas. The client's answer does not wait for them.

Data types

Match the structure to the job

The types you will use

TypeGood forExample
StringCached values, countersSET page:7 html EX 60, INCR hits
HashOne object with fieldsHSET user:42 name Asha
ListA simple queueRPUSH jobs a, BLPOP jobs 30
SetUnique members, membershipSADD online 42, SISMEMBER online 42
Sorted setRanking, time windowsZADD board 250 max, ZRANGE board 0 9 REV
StreamA log with consumer groupsXADD orders * item lamp
HyperLogLogApproximate distinct countPFADD visitors 42, PFCOUNT visitors
BitmapMany yes or no flagsSETBIT seen 42 1
A string value may be up to 512 MB, but keep values small: a large one blocks the thread and the network while it is copied.
Shell
# object with fields, and a time to liveHSET user:42 name "Asha" role "admin"EXPIRE user:42 3600HGET user:42 name# queue: add on the right, wait on the left for up to 30 secondsRPUSH queue:mail "job1" "job2"BLPOP queue:mail 30LLEN queue:mail# unique membersSADD online "u1" "u2" "u3"SISMEMBER online "u1"SCARD online# ranking: highest score firstZADD board 100 "asha" 250 "max" 80 "lee"ZINCRBY board 50 "asha"ZRANGE board 0 9 REV WITHSCORESZREVRANK board "max"        # 0 is the topZSCORE board "asha"         # 150
ZRANGE ... REV replaces the older ZREVRANGE. SMEMBERS on a large set returns everything at once: use SSCAN.

A leaderboard costs O(log⁡N)O(\log N) per score change and O(log⁡N+M)O(\log N + M) to read MM rows, with no sorting at read time. Design a leaderboard takes this to a full system.

Round trips

The network is usually the cost

100 commands, one by one or in a pipeline

Tsingle=n(R+s)=100×(0.5+0.01)=51 msTpipe=R+ns=0.5+1=1.5 msT_{\text{single}} = n(R + s) = 100 \times (0.5 + 0.01) = 51\text{ ms} \qquad T_{\text{pipe}} = R + ns = 0.5 + 1 = 1.5\text{ ms}
RR is the round trip and ss the time to run one command. Both are assumptions: measure yours.

Three commands in one trip

A pipeline saves trips. It is not a transaction: other clients' commands may run in between. Use MULTI and EXEC or a script for that. Send batches, not a million commands at once, because the answers wait in memory.

As a cache

Redis in front of a database

The most common job. The reading and writing patterns have their own pages: cache-aside, write-through, cache consistency and thundering herd. Here is how they look with Redis.

Cache-aside with a lock for the rebuild

Other readers fail to take the lock, wait a moment and read the cache again. The token makes sure nobody deletes somebody else's lock.
Python
import json, random, secrets, timeimport redisr = redis.Redis(host="localhost", port=6379, decode_responses=True,                socket_timeout=0.5, socket_connect_timeout=0.5, max_connections=50)RELEASE = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) end return 0"def ttl(base=3600):    return base + random.randint(0, base // 10)      # keys do not all end togetherdef get_user(user_id, load):    key = f"user:{user_id}"    for _ in range(20):        cached = r.get(key)        if cached is not None:            return json.loads(cached)        token = secrets.token_hex(16)        if r.set(f"lock:{key}", token, nx=True, ex=10):            try:                cached = r.get(key)                  # somebody may have just filled it                if cached is not None:                    return json.loads(cached)                row = load(user_id)                if row is not None:                    r.set(key, json.dumps(row), ex=ttl())                return row            finally:                r.eval(RELEASE, 1, f"lock:{key}", token)        time.sleep(0.1)    return load(user_id)                             # give up waiting, not foreverdef save_user(user, store):                          # write-through: database first    store(user)    r.set(f"user:{user['id']}", json.dumps(user), ex=ttl())def delete_user(user_id, remove):    remove(user_id)    r.delete(f"user:{user_id}", f"user:{user_id}:profile", f"user:{user_id}:settings")
Invalidation deletes related keys too. Always set a TTL on cache keys: it is the safety net when a delete is lost.

When Redis is the cache

  • Set a limit

    maxmemory is off by default on 64-bit systems. Without it Redis grows until the machine runs out.

  • Choose a policy

    The default, noeviction, refuses writes when full. A cache usually wants allkeys-lru or allkeys-lfu.

  • Expect it to be empty

    After a restart or a failover the database must survive the misses. Warm it or limit the rebuilds.

  • Use short timeouts

    A slow cache must not be worse than no cache. Fall back, and add a circuit breaker.

Memory

What leaves when memory is full

A write at the limit

Policies named volatile only touch keys with a TTL. With none, they behave like noeviction.

Choosing a policy

PolicyUse when
allkeys-lruSome keys are far hotter than others. The documentation's default advice.
allkeys-lfuScans or bursts would push out keys that are popular over the long run.
allkeys-lrmKeep what is still being changed: evicts the least recently modified key.
allkeys-randomEvery key is about equally likely to be read.
volatile-ttlYour code gives short TTLs to the keys it can spare.
volatile-lru, volatile-lfu, volatile-lrm, volatile-randomOne server holds both cache keys with a TTL and keys that must stay.
noevictionRedis is the only copy. Alert before it fills.
LRU and LFU are approximate: Redis compares a small sample, 5 keys by default. The theory is on cache eviction.

How much memory for the cache?

10 000 000×(40+400+100) B=5.4 GB10\,000\,000 \times (40 + 400 + 100)\text{ B} = 5.4\text{ GB}
Ten million keys, 40 bytes of key, 400 of value and an assumed 100 of bookkeeping. Add room for replication buffers and for copy-on-write while a snapshot child runs.

Durability

Snapshots and the append-only file

RDB snapshotAOF log
WhatThe whole dataset, compact binary fileEvery write, in order
HowA forked child writes it (BGSAVE)Appended as commands run, rewritten in the background
Can loseEverything since the last snapshotAbout one second with everysec
RestartFastSlower: the log is replayed
CostThe fork can pause a large serverLarger files, disk writes
DefaultOn: after 3600 s with 1 change, 300 s with 100, 60 s with 10,000Off

How often the log reaches the disk: appendfsync

  1. 1

    always

    Sync before answering. The safest and the slowest.

  2. 2

    everysec

    Sync once a second in the background. The default, and the usual choice.

  3. 3

    no

    Let the operating system decide. The fastest, with the largest window.

Availability

Replicas and Sentinel

A replica first receives a full snapshot, then a stream of writes. Replication is asynchronous by default: the primary answers the client before replicas confirm. A failover can therefore lose writes that were already acknowledged. WAIT and min-replicas-to-write make the window smaller; they do not make Redis strongly consistent. The theory is on cache replication.

Sentinel promotes a replica

One Sentinel's opinion is subjectively down; a quorum makes it objectively down. Acting needs a majority of all Sentinels.

Sentinel or Cluster?

SentinelCluster
Gives youFailover for one datasetSharding and failover
Memory and writesOne primary's worthGrows with primaries
NeedsAt least 3 Sentinels on separate machinesAt least 3 primaries, plus replicas
ClientAsks Sentinel for the primary's addressCluster-aware, keeps a slot map
Detectiondown-after-milliseconds, for example 5 scluster-node-timeout, 15 s by default
LimitsNo shardingMulti-key commands need one slot
Use one or the other. Cluster does not need Sentinel.

Scaling

Redis Cluster and its slots

Three shards, 16,384 slots

Application servers use a cluster-aware client that sends each key to one of three shards. Each shard is a primary machine and a replica machine. Shard 1 owns slots 0 to 5460, shard 2 owns 5461 to 10922 and shard 3 owns 10923 to 16383. Each primary replicates to its replica.
There is no proxy in the middle: the client works out the slot and goes to the owner directly.

A key belongs to slot CRC16(key) mod 16384. If the name contains a part in braces, only that part is hashed: user:{123}:profile and user:{123}:settings both use 123, slot 5970. Without braces they land in slots 8490 and 9984, and a command that touches both fails with CROSSSLOT, even when one server owns both.

A wrong guess is corrected

MOVED means the slot lives elsewhere for good: update the map. ASK means it is being moved now: ask there once, and keep the map.

Messages

Pub/Sub and streams

Pub/SubStreams
Stored?No. A message with no listener is lostYes, until trimmed
DeliveryAt most onceAt least once with consumer groups
Who gets itEvery subscriberOne consumer per group
ReplayNoYes, by ID
Use forLive notices, telling servers to drop a local cache entryJob queues, activity feeds, event logs that fit in memory
For long retention and very large volume use a log-based queue such as Kafka.
Shell
# live notices: nothing is storedSUBSCRIBE cache:invalidatePUBLISH cache:invalidate "user:42"PSUBSCRIBE "user:*:events"# stream with a consumer group, reading from the start (0); use $ for new entries onlyXGROUP CREATE orders workers 0 MKSTREAMXADD orders MAXLEN ~ 10000 * product lamp qty 2XREADGROUP GROUP workers w1 COUNT 10 BLOCK 5000 STREAMS orders >XACK orders workers 1705123456789-0# what a dead worker left behindXPENDING orders workersXAUTOCLAIM orders workers w2 60000 0
Not acknowledging is not enough to get a message again: it stays pending until the same consumer reads its own backlog or another claims it. Make the work idempotent.
Python
def work(r, stream="orders", group="workers", me="w1"):    try:        r.xgroup_create(stream, group, id="0", mkstream=True)    except redis.ResponseError as e:        if "BUSYGROUP" not in str(e):            # the group already exists            raise    while True:        # first take over what others left for a minute, then new entries        stuck = r.xautoclaim(stream, group, me, min_idle_time=60_000, count=10)[1]        fresh = r.xreadgroup(group, me, {stream: ">"}, count=10, block=5000)        for entry_id, fields in stuck + (fresh[0][1] if fresh else []):            handle(fields)                       # must be safe to run twice            r.xack(stream, group, entry_id)def listen(r, local_cache):    ps = r.pubsub()    ps.subscribe("cache:invalidate")    for m in ps.listen():        if m["type"] == "message":            local_cache.pop(m["data"], None)

Counting

Rate limits

The algorithms and their edge cases are on rate limiter algorithms. In Redis: a fixed window is INCR plus an expiry, a sliding window is a sorted set of timestamps, and a token bucket is a short Lua script. Anything with a check and a change belongs in one script, or two requests can both pass.

Python
SLIDING = """redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, ARGV[1] - ARGV[2])if redis.call('ZCARD', KEYS[1]) >= tonumber(ARGV[3]) then return 0 endredis.call('ZADD', KEYS[1], ARGV[1], ARGV[4])redis.call('PEXPIRE', KEYS[1], ARGV[2])return 1"""BUCKET = """local b = redis.call('HMGET', KEYS[1], 'tokens', 'at')local cap, rate, now = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])local tokens = math.min(cap, (tonumber(b[1]) or cap) + (now - (tonumber(b[2]) or now)) * rate / 1000)local ok = tokens >= 1if ok then tokens = tokens - 1 endredis.call('HSET', KEYS[1], 'tokens', tokens, 'at', now)redis.call('EXPIRE', KEYS[1], math.ceil(cap / rate) + 1)return ok and 1 or 0"""def fixed_window(r, user, limit=100, seconds=60):    key = f"rate:{user}:{int(time.time()) // seconds}"    with r.pipeline() as p:                      # MULTI and EXEC        p.incr(key)        p.expire(key, seconds * 2)        return p.execute()[0] <= limitdef sliding_window(r, user, limit=100, ms=60_000):    now = int(time.time() * 1000)    member = f"{now}-{secrets.token_hex(4)}"     # two requests in one millisecond differ    return r.eval(SLIDING, 1, f"slide:{user}", now, ms, limit, member) == 1def token_bucket(r, user, capacity=100, per_second=10):    return r.eval(BUCKET, 1, f"bucket:{user}", capacity, per_second, int(time.time() * 1000)) == 1
Answer a refused request with 429 and say when to retry. A fixed window lets through up to twice the limit around its edge; the other two do not.

Locks

A lock, and how far to trust it

SET lock:job <random> NX EX 30 takes the lock if nobody has it and lets it expire if the holder dies. Release only if the value is still yours: DELEX key IFEQ value since Redis 8.4, or the small script above on older versions.

Good enough for

  • Avoiding duplicate work that is only wasteful
  • One worker rebuilding a cache entry
  • A scheduled job that is safe to run twice

Not enough alone for

  • Moving money or stock
  • Anything where two holders corrupt data
  • Work that may run longer than the lock lives

Operations

Running it well

What to watch

Look atCommandWhy
Memory and evictionsINFO memory, INFO statsEvictions mean the cache is too small or keys live too long
Hit ratekeyspace_hits, keyspace_missesHits divided by both
Slow commandsSLOWLOG GET 10Anything over 10 ms is kept by default
Replica lagINFO replicationHow much a failover would lose
ClientsCLIENT LISTLeaked connections, large buffers
Big keysredis-cli --bigkeysThey block and they unbalance shards

Do

  • SCAN with a small COUNT
  • UNLINK for large keys: memory is freed in the background
  • Pools sized for your concurrency
  • ACL users, TLS and a private network
  • TTLs with some random spread

Do not

  • KEYS * in production
  • MONITOR on a busy server for long
  • Passwords typed on the command line
  • An open port on the internet
  • Hundreds of megabytes under one key

Licences

VersionLicence
7.2 and earlierBSD 3-clause
8.0 and laterYour choice of RSALv2, SSPLv1 or AGPLv3
ValkeyBSD 3-clause, continues from 7.2.4
Check the exact terms with your company before you offer Redis to others as a service.

Decide

When to choose Redis, and when not

Choose it for

  • Reads and writes that must take under a millisecond or so inside one zone
  • Cached query results and sessions
  • Leaderboards, counters, rate limits, live notices
  • Light job queues
  • Hot data that fits in memory

Choose something else for

  • Data much larger than memory
  • Joins and free-form reports
  • Strong consistency across failovers
  • The only copy of financial records
  • Large files: use object storage
AlternativeSameDifferentChoose it when
MemcachedFast shared cachePlain values, several worker threads, no replication. See the comparisonYou only need get and set
DynamoDBKey lookups at scaleDurable, managed, larger than memory, optional strong reads, higher latencyIt is the system of record
KafkaStreams, consumer groupsDisk based, long retention, more to runEvents must be kept and replayed

The bill

You getYou pay
Very low latencyMemory, the most expensive place to keep data
Atomic commands without locksOne core for commands per shard
Many structures in one toolThe temptation to make it do everything
Simple replicationStale reads and lost writes in a failover
Optional persistenceForks, disk traffic and a loss window
Easy to startNo ad-hoc queries: know the access paths first

Summary

The whole topic in one minute.

Redis is fast because the data is in memory, the commands are small and one thread runs them without locks. That same thread is why one slow command delays everyone, and why more processor work means more shards.

Decide four things on purpose: what happens when memory is full, how much you may lose in a crash, how you survive a dead primary, and how keys are grouped in a cluster. The defaults for the first two are no memory limit and snapshots, which rarely fit a production cache.

  • Memory, small commands and one command thread make Redis fast.
  • One slow command delays everyone. Use SCAN, UNLINK and small values.
  • Set maxmemory and a policy: the default never evicts.
  • RDB loses minutes, AOF everysec about a second, replication a little more in a failover.
  • Sentinel gives failover, Cluster gives sharding and failover over 16,384 slots.
  • Braces in a key name put related keys in one slot.

Sources