ReaderTube

AI summary

Yellow marks are automatic key passages. They aren’t personal saved highlights. Select a timestamp to follow along with the video.

This episode introduces the Redis Append Only File (AOF), a feature that logs every write a client performs so the server can replay those operations after a restart and rebuild the same dataset. Using the real Redis source, it traces how a write command's execution in the call function sets the dirty counter, triggers propagation to the AOF, and turns the command into Redis protocol with any needed SELECT or absolute expiry timestamps. It then explains why that protocol is buffered and flushed once per event-loop cycle, how the fsync policies (everysec and always) trade off latency against durability, and how the file is compacted through rewrites when it grows too large. The discussion ends with group commits under the always policy, where replies are held so that one fsync can cover many clients at once.

Series Introduction and Scope

This is the first episode of a series on system software, following the approach of an earlier part of the series that examined a different project. The series looks at low-level code in real source files rather than small toy examples. Real codebases show how and why certain design decisions were made. As software grows, clean designs begin to break down, and developers must make compromises to keep memory usage low and code fast enough. This episode covers the Redis Append Only File (AOF), a Redis feature, and how it is implemented.

What the Append Only File Does

The Append Only File is a Redis feature that logs every write operation that clients perform. When the server restarts, it reads these logged operations back and rebuilds the same dataset that existed before the server stopped.

Observing the AOF Log in Practice

To see this in action, start a Redis server with AOF enabled. In a second terminal, open the AOF file and watch its contents as Redis populates it. Then, in a third terminal, run a few commands. Redis treats this client like any other client, and each write appears in the AOF file as Redis protocol. This protocol is what Redis will execute again when the server restarts. The log for a command such as SET fubar contains more than the SET itself. It also contains a SELECT command. Redis can change the currently selected database, so the SELECT statement must be recorded for the following commands to target the correct database. When the server starts, the selected database is unknown, so the first write after startup generates a SELECT statement. Each command's protocol records its arguments, along with their byte lengths. For example, one argument may be four bytes and another nine bytes.

Recovery After a Restart

After a restart, Redis processes the AOF file again. In the example, the counter returns to the values set in the previous session. This confirms that the logged operations were replayed to restore the data.

Where Writes Are Logged in the Command Code

The command implementations do not contain explicit calls to write to the AOF. Instead, each write command handles its own arguments and performs its operation without logging anything itself. For example, the SET command ends up in a generic set function, which has several entry points, such as SETNX and SETEX, that represent different variants. The generic function stores the key and its new value and then increments the global counter server.dirty. This counter tells the Redis core that the command modified the dataset and should be logged or propagated. The command then sends its reply to the client. Nothing in the command code explicitly writes a log entry.

The call Function as the Execution Core

Every command execution in Redis passes through the call function in server.c. This function is the core of how a command runs and how its effects are recorded. It handles many flags, because commands run from scripts, transactions started with MULTI and EXEC, and other contexts. Every command ultimately goes through this one path, so the function must support many different needs. Its prototype is simple: it takes a client and a set of flags.

How call Prepares and Runs a Command

Before call runs, the client's incoming protocol has already been parsed into an argument vector and an argument count. Inside call, the client is referred to as c. The function uses its flags to decide what to do with the command beyond executing it. For example, flags can specify that a command should be sent to clients that have enabled MONITOR, be logged, update statistics, be written to the AOF, or be replicated. A typical command uses the full set of flags, which covers logging, statistics, and propagation. Call first sends the command to MONITOR clients. It then records the current value of the global server.dirty counter in a local variable, which is the same counter the command implementation increments. Comparing the two values reveals whether the command performed a write. Next, call records the start time and invokes the function pointer associated with the command. This pointer is resolved from argv[0] through a hash table of commands. If execution reaches call, the command is already known to be valid, and its arity, meaning its minimum and maximum argument counts, has already been checked. After the command finishes, call calculates how long it took.

How the Dirty Counter Works

The server.dirty counter must be incremented whenever a command modifies data. The amount of the increment depends on the number of changes. Setting one key increments dirty by one, while a multi-key operation such as MSET increments it by the number of keys it affects. In other words, dirty reflects how many changes the dataset received. RDB persistence uses this counter. The number of changes since the last save determines when Redis should take a new snapshot. From the perspective of AOF semantics, however, the key question is simply whether dirty was incremented at all. Other processing unrelated to this discussion also takes place in call. The important step is the propagation check that follows.

Propagating Commands to the AOF and Replicas

If a command must be propagated, it is sent to the AOF, if AOF is enabled, and to the replication sockets that connect to replicas. Propagation happens when dirty has been incremented or when the propagate flags are set. Commands can also set flags that force propagation even when dirty has not changed. PUBLISH from Pub/Sub is an example. Its messages must reach replicas, because replicas may have subscribers on the same channels. However, PUBLISH should not increment dirty, because that would affect the snapshot-saving triggers. For this reason, the PUBLISH command sets the client force-replication flag. In call, if the propagate flags are not equal to the no-propagate value, the command is propagated by calling the propagate function, which performs the actual propagation.

feedAppendOnlyFile and Replication

Propagation is carried out by two functions: feedAppendOnlyFile and replicationFeedSlaves. Call contains only the logic that decides whether a command should be sent to the AOF or to replication. The actual work happens in these two functions. The AOF path is the first of them. feedAppendOnlyFile receives the command structure, the database ID the client was operating on, the client's argument vector, and its argument count. Those values come directly from the client that executed the command. The function is defined in the AOF source file.

Building the Protocol and Handling Select and Expire

Inside feedAppendOnlyFile, the SELECT statement seen earlier is generated when the database ID of the executed command differs from the last database selected in the AOF. The function then produces the protocol for selecting the database. The function also handles commands that carry expire times. Relative times, such as a key that expires in one hour, are translated into absolute Unix timestamps before being written to the AOF. This matters because if the server stops and restarts thirty minutes later, the expiry should still count down from the original moment, not restart from the full duration. After these translations, the function converts the argument vector into Redis protocol. It does this in the same way for any command.

Buffering Protocol Instead of Writing to Disk

feedAppendOnlyFile does not write to disk. It appends the generated protocol to a buffer, which is later concatenated into a global AOF buffer. The reason for this design lies in how Redis handles concurrency. Redis uses an event loop, which is an event-driven design. A single loop reads from many client descriptors and writes to others. If the server had 50 clients, writing each command directly to disk would block the loop on every operation. Buffering the protocol lets Redis accumulate the data and handle it efficiently in batches.

Executing commands and deferring replies

Redis runs on an event loop, an event-driven design where a single loop reads from many client file descriptors, executes their commands, and then writes the replies back. With the loop serving around 50 clients at once, reading requests and executing commands are the first two steps, and replies are written out afterward. The commands that change the dataset generate AOF (append-only file) protocol, and that protocol is what gets persisted. The replies are sent back to clients only after the buffered data has been handled.

Why the AOF is buffered instead of written directly

Writing to disk after every client command would be very costly. If one cycle of the event loop is reading protocol from 50 clients and executing their commands, calling the write system call separately for each client would be extremely time-consuming. Instead, Redis accumulates all the AOF protocol generated during the cycle in an in-memory buffer. Once every ready client has been processed and a full iteration of the event loop is complete, the entire AOF buffer is written to disk in one operation. This greatly improves performance, since write is a slow system call. Grouping writes from many clients together also makes the later fsync step more efficient.

The flush function and the fsync policies

When appendfsync is set to everysec, the fsync to disk is handled by a background thread, so the main thread does not have to wait for it. In general, though, Redis wants to write once for many clients rather than once per command. The function that performs this work is flushAppendOnlyFile. It takes a force argument because it does not always flush. Whether it actually writes depends on the situation.

When the buffer is flushed

If the accumulated buffer is empty, flushAppendOnlyFile returns immediately, because there is nothing to do. If the force argument is set, the buffer is always written. Otherwise, under the everysec policy, Redis first checks whether a background fsync is already in progress. A background I/O interface reports whether a write is pending, returning true or false.

Postponing the write while an fsync is pending

Even if the background fsync was started some time ago, it may still be in progress, especially on a slow disk where an fsync can take a long time. Redis checks how much time has passed since the last successful fsync. If less than two seconds have elapsed, Redis does not write to the disk yet. Writing to the AOF file while an fsync is still running on the same file would block the write system call. The kernel buffers would not help, because the write would wait for the kernel to finish the fsync before accepting more data. At least in some versions of the Linux kernel, this is the behavior. So the write is postponed when possible.

Forcing the write after a long delay

If too much time has passed, around two seconds with the fsync still pending, Redis stops postponing and writes to disk anyway, even though this may block the main thread. Redis also reports the situation to the user, because it means the disk is too slow and will cause latency problems. This is the code path taken when the write is finally performed. The AOF write is a loop of write calls, handling the case where a short write occurs.

Checks and error handling after the write

After the write completes, Redis runs several checks. First, it calls latency hooks in different parts of the code to record latency events. These let users inspect what is slowing the server with the LATENCY DOCTOR command. Next, Redis checks for short writes. If a write error occurs, it sets an error condition so the server stops accepting new write commands. If the appendfsync policy is always and the write fails with an unrecoverable error, such as a full disk, the server exits. If the error is recoverable, and the policy is not always, Redis sets the error flag and rejects new writes until the situation is resolved, after which it can continue normally.

Triggering AOF rewrites by file size

Redis also tracks the current size of the AOF file, because it needs to trigger an AOF rewrite, a compaction, when the file grows too large. Some operations, such as incrementing a counter, add a record every time they run. If a counter is incremented repeatedly, the AOF keeps growing. A rewrite can express the same final state more compactly, for example as a single SET counter operation instead of many separate increments. The rewrite is therefore triggered based on the size of the AOF file.

Group commits under the always policy

When appendfsync is set to always, Redis must guarantee a specific safety property. If a client sends a write command such as SET foo bar, it should receive the OK reply only after the write has been successfully persisted to disk. This means the data is committed before the client gets confirmation, so the client knows its data is safe. Performing a separate fsync for every client, however, would limit throughput to the number of fsyncs the disk can perform each second, which would be extremely slow.

Batching replies behind a single fsync

Consider ten clients: some run SET foo bar, one runs INCR counter, another runs XADD mystream with temperature readings, and so on. Instead of fsyncing for each client, Redis can hold the replies, perform one fsync that covers all ten clients, and only then allow the replies generated by the commands to be sent to the sockets. Redis attempts this, but the mechanism is fairly complex, because the event loop, the way commands are dispatched, and other parts of the system all interact with each other.

Turn your watchlist into a reading routine

Bring your YouTube videos together, read summaries with key passages marked, and explore the full transcript. Save your own highlights with Pro.

Start with 5 free batteries. Each covers up to 30 minutes of a new summary.

New summaries depend on video availability and demand; processing may take time or require retry.