Everything lives in the till
Picture a busy corner shop with one clever electronic till. It doesn't just take money: it remembers every regular's running tab and how many of each sweet are left. Because everything is right there inside the till, the cashier can answer any question in a blink.
There's a catch. The till keeps all of this in its own little memory, and that memory goes blank when the power goes off. Unless the shop writes things down somewhere that survives a power cut (that's called persistence), a power cut means starting the morning with no tabs at all.
An in-memory store
Redis keeps its whole dataset in RAM. That's why reads and writes take microseconds, and why a single-threaded command loop can serve very high request rates. Valkey, the Linux Foundation fork of Redis 7.2.4 made after Redis's 2024 licence change, works the same way, and everything on this page applies to it too (see Redis and Valkey).
RAM doesn't survive a process restart or a machine reboot. Without persistence, a restarted Redis comes back empty. That's fine for a pure cache that can be refilled from the real database, and a problem for anything else: sessions, rate-limit counters, queues, leaderboards.
Redis offers two persistence mechanisms, which you can use alone or together:
| Mechanism | What it writes | Loses on power loss or OS crash |
|---|---|---|
| RDB | A point-in-time snapshot of the dataset | Everything since the last snapshot |
| AOF | Every write command, appended to a log | Up to about a second, with the default fsync policy |
Persistence protects against restarts. It does nothing if the machine and its disk are gone: that needs replication, covered further down.
A photo of the till
The simplest fix: every so often, take a photo of everything the till remembers and put it in an album in the back room. That photo is called a snapshot.
The cashier can't stop serving to pose for photos, so a helper takes the photo while the cashier carries on. Sales that happen while the photo is being taken aren't in it. If the power goes, the shop restores the till from the latest photo. It's quick, and the album stays small, but anything sold since that photo is gone.
The shop decides how often to take photos: "if a hundred things changed in five minutes, take one".
RDB snapshots
An RDB file (dump.rdb by default) is a compact binary snapshot of the whole dataset at one moment.
BGSAVEforks a child process. The child writes the dataset to a temporary file and renames it over the old one, while the parent keeps serving clients. Thanks to copy-on-write, both share memory pages until the parent modifies one.SAVEdoes the same in the foreground and blocks every client, so you rarely want it.- Save points trigger snapshots automatically.
save 300 100means "after 300 seconds, if at least 100 keys changed". Redis 7's default issave 3600 1 300 100 60 10000;save ""disables them. - On restart, Redis loads the RDB file, which is fast because it's a compact image rather than a list of commands.
Trade-offs: RDB is great for backups (copy the file off the box) and fast restarts, but a crash loses every write since
the last snapshot, often minutes. And fork() isn't free: on a large dataset it can pause Redis for milliseconds or
more, and heavy writes during the snapshot copy many pages, which needs extra RAM.
Sizing for the fork
Leave memory headroom for copy-on-write: the more keys change while the child is writing, the more pages get
duplicated, and in the worst case usage approaches double. On Linux, Redis warns at startup if
vm.overcommit_memory isn't set to 1, because a refused fork means a failed background save. Watch
rdb_last_bgsave_status in INFO persistence and latest_fork_usec in INFO stats.
The receipt roll
Photos miss whatever happened since the last click. So the till also prints every sale on a long receipt roll, called the append-only file: "Ana's tab plus 5", "Bob's tab plus 2", one line after another, never rubbing anything out.
After a power cut, the shop reads the roll from the top and does every sale again, and the till ends up exactly where it was.
The printer has a small memory of its own, and lines only count once they're inked on paper. The shop chooses how careful to be:
- after every sale: wait for the ink before handing back the change. Nothing is lost, but every sale is slower.
- once a second: the printer inks whatever's waiting each second. At most a second of sales is lost.
- whenever the printer likes: fastest, but more lines can be lost.
The roll keeps growing, so every now and then someone writes a short summary on a fresh roll ("Ana owes 8") and throws the long one away.
If the shop keeps both photos and a roll, it fixes the till from the roll, because the roll has the most recent sales. The photos are still handy as copies to keep somewhere else.
The append-only file
With AOF (appendonly yes; it's off by default), Redis appends every write command to a log. On restart it
replays the log to rebuild the dataset.
Writing to the file only puts data in the OS page cache; it's durable once fsync flushes it to disk.
appendfsync chooses when. A Redis process crash alone loses nothing already written, because the page cache
survives it; the window below applies when the machine or OS goes down.
appendfsync | Behaviour | On power loss or OS crash you can lose |
|---|---|---|
always | fsync after every write | Practically nothing, at a big cost in throughput |
everysec (default) | fsync once a second, in a background thread | About one second of writes |
no | Leave flushing to the OS | Whatever the OS hadn't flushed yet (up to about 30 seconds on Linux defaults) |
The log grows forever, so Redis rewrites it in the background (BGREWRITEAOF, or automatically with
auto-aof-rewrite-percentage 100 and auto-aof-rewrite-min-size 64mb). A forked child writes the current dataset as a
compact new base, and the old history is discarded. Since Redis 7.0 the AOF is multi-part: a base file plus
incremental files, tracked by a manifest in appendonlydir. With aof-use-rdb-preamble yes (the default) the base is
written in RDB format, so loading is fast.
Using both
Enable both when the data matters: AOF for a small loss window, RDB files for backups and copying elsewhere. When AOF is enabled, Redis loads it on startup rather than the RDB file, because it's the more complete of the two. If you can accept losing minutes of data, RDB alone is enough; for a pure cache that's refilled from elsewhere, you may need neither.
A trainee at the second till
Photos and rolls help after a power cut, but not if the till itself is smashed. So the shop puts a trainee at a second till, called a replica. The trainee starts from a photo of the main till, then copies each sale as the main till calls it out.
Customers who only want to check their tab can ask the trainee, which keeps the main queue short. The trainee won't take new sales, though: only the main till does that.
The main till doesn't wait for the trainee. It tells the customer "done", then calls out the sale. If it breaks in between, the trainee never heard about a sale the customer was told was done. A careful customer can ask the cashier to check "did you get that?" with the trainee before walking off, which makes losing the sale less likely, but not impossible.
Asynchronous replication
A replica connects with REPLICAOF host port. On first contact, or when it has fallen too far behind, it does a
full sync: the primary makes an RDB snapshot and sends it. After that the primary streams every write command, and a
replica that briefly disconnects resumes with a partial resync from the primary's replication backlog.
- Replication is asynchronous: the primary replies to the client before replicas have the write. Replicas acknowledge their position periodically.
- Replicas are read-only by default (
replica-read-only yes) and reject writes with aREADONLYerror. Reading from them scales reads, but they can be slightly behind, so reads can be stale. WAIT numreplicas timeoutblocks until that many replicas have acknowledged the client's earlier writes. It narrows the window for losing a write, but the Redis docs are explicit that it doesn't make Redis strongly consistent: an acknowledged write can still be lost in a failover.
Two sharp edges
min-replicas-to-write 1 with min-replicas-max-lag 10 makes a primary refuse writes when no replica has
acknowledged it within ten seconds, which limits how much an isolated primary can accept and later lose. And never let
a primary that has persistence turned off restart automatically: it comes back empty, the replicas sync from it,
and they wipe their own copies too.
The floor managers
Someone has to notice when the main till breaks and open the trainee's till for sales. That's the job of the floor managers, and swapping in the trainee's till is called a failover. The shop has three managers, so one confused manager can't cause chaos.
Each manager keeps checking that the tills answer. If one manager thinks the main till is broken, that's only a hunch. Once enough managers agree, they pick one of themselves to act, and most of all the managers must back that choice. With three, the shop still copes if one manager is off sick; with two, one absence would leave nobody able to act. The chosen manager tells the trainee "you're the main till now". When the old till is fixed, it comes back as the new trainee and copies from the new main till.
Sentinel and failover
Redis Sentinel is a separate process (port 26379 by default) that provides monitoring, notification, automatic failover and service discovery for one or more named primaries.
- Each Sentinel pings the primary and its replicas. A Sentinel that gets no valid reply for
down-after-millisecondsmarks it SDOWN (subjectively down). - When at least quorum Sentinels agree, the primary is ODOWN (objectively down).
- To actually fail over, one Sentinel must be elected leader by a majority of all Sentinels. The quorum only detects failure; the majority authorises the failover.
- The leader picks the best replica (lowest
replica-priority, then the largest replication offset; priority 0 is never promoted), promotes it withREPLICAOF NO ONE, and reconfigures the other replicas, and the old primary when it returns, to follow it.
Run at least three Sentinels on machines that fail independently. Because replication is asynchronous, Sentinel doesn't guarantee that acknowledged writes survive a failover: writes the old primary accepted but hadn't sent are gone.
Asking where to pay
A customer doesn't need to remember which till is the main one today. They ask a floor manager, "where do I pay?", and go there. They can check their tab at the trainee's till. When a manager announces "the main till has moved", the customer simply walks over to the new one.
Some shops hire a company that runs the tills, the trainees and the managers for them. They still choose how often photos are taken, and a sale called out just before a crash can still be missed.
Connecting from Java
Clients don't hard-code the primary's address. They ask a Sentinel (SENTINEL get-master-addr-by-name mymaster), and
learn about failovers from Sentinel's +switch-master notifications or a failed connection, then reconnect.
With plain Lettuce, give it the Sentinels and the primary's name, and choose where reads go:
1RedisURI uri = RedisURI.Builder2.sentinel("sentinel-1", 26379, "mymaster")3.withSentinel("sentinel-2", 26379)4.withSentinel("sentinel-3", 26379)5.build();67RedisClient client = RedisClient.create();8StatefulRedisMasterReplicaConnection<String, String> conn =9MasterReplica.connect(client, StringCodec.UTF8, uri);10conn.setReadFrom(ReadFrom.REPLICA_PREFERRED); // reads on replicas, writes on the primary1112conn.sync().set("tab:ana", "5");
With Spring Boot, configure the Sentinels and Boot's auto-configuration builds a RedisSentinelConfiguration and a
LettuceConnectionFactory for you:
1spring:2data:3redis:4sentinel:5master: mymaster6nodes: sentinel-1:26379,sentinel-2:26379,sentinel-3:26379
1@Bean2LettuceClientConfigurationBuilderCustomizer readFromReplicas() {3return builder -> builder.readFrom(ReadFrom.REPLICA_PREFERRED);4}
On Spring Boot 3.5+ you can set spring.data.redis.lettuce.read-from: replica-preferred instead of the customizer.
Only read from replicas when stale data is acceptable. Managed services (Amazon ElastiCache, Google Memorystore, Azure Managed Redis) run replicas and automatic failover for you and give you an endpoint that follows the primary, but replication is still asynchronous, so the same loss window applies; check which persistence options your service offers.