Write-Ahead Log

Provide durability guarantee without the storage data structures to be flushed to disk, by persisting every state change as a command to the append only log.

Also known as: Commit Log

Problem

Strong durability guarantee is needed even in the case of the server machines storing data failing. Once a server agrees to perform an action, it should do so even if it fails and restarts losing all of its in-memory state.

Solution

Store each state change as a command in a file on a hard disk ( Figure 3.1 ). A single log is maintained for each server process. It is sequentially appended. A single log, appended sequentially, simplifies handling of logs at restart and the subsequent online operations (when the log is appended with new commands). Each log entry is given a unique identifier. This identifier helps in implementing certain other operations on the log, such as Segmented Log , cleaning the log with Low-Water Mark , and so on. The log updates can be implemented with Singular Update Queue .

Images

Figure 3.1 Write-Ahead Log

Here’s the typical log entry structure:

Click here to view code image

class WALEntry...

  private final Long entryIndex;
  private final byte[] data;
  private final EntryType entryType;
  private final long timeStamp;

The file can be read on every restart and the state can be recovered by replaying all the log entries.

Consider a simple in-memory key-value store:

Click here to view code image

class KVStore...

  private Map<String, String> kv = new HashMap<>();

  public String get(String key) {
      return kv.get(key);
  }

  public void put(String key, String value) {
      appendLog(key, value);
      kv.put(key, value);
  }

  private Long appendLog(String key, String value) {
      return wal.writeEntry(new SetValueCommand(key, value).serialize());
  }

The put action is represented as Command , which is serialized and stored in the log before updating the in-memory hash map.

Click here to view code image

class SetValueCommand...

  final String key;
  final String value;

  public SetValueCommand(String key, String value) {
      this.key = key;
      this.value = value;
  }

  @Override
  public void serialize(DataOutputStream os) throws IOException {
      os.writeInt(Command.SetValueType);
      os.writeUTF(key);
      os.writeUTF(value);
  }

  public static SetValueCommand deserialize(InputStream is) {
      try {
          var dataInputStream = new DataInputStream(is);
          return new SetValueCommand(dataInputStream.readUTF(),
                  dataInputStream.readUTF());
      } catch (IOException e) {
          throw new RuntimeException(e);
      }
  }

This makes sure that once the put method returns successfully, even if the process holding the KVStore crashes, its state can be restored by reading the log file at startup.

Click here to view code image

class KVStore...

  public KVStore(Config config) {
      this.config = config;
      this.wal = WriteAheadLog.openWAL(config);
      this.applyLog();
  }

  public void applyLog() {
      List<WALEntry> walEntries = wal.readAll();
      applyEntries(walEntries);
      applyBatchLogEntries(walEntries);
  }

  private void applyEntries(List<WALEntry> walEntries) {
      for (WALEntry walEntry : walEntries) {
          Command command = deserialize(walEntry);
          if (command instanceof SetValueCommand) {
              SetValueCommand setValueCommand = (SetValueCommand)command;
              kv.put(setValueCommand.key, setValueCommand.value);
          }
      }
  }

Implementation Considerations

It’s important to make sure that entries written to the log file are actually persisted on the physical media. File handling libraries in all programming languages provide a mechanism to force the operating system to flush the file changes to physical media. There is a tradeoff, however, to be considered when using flushing.

Flushing every log write to the disk gives a strong durability guarantee (which is the main purpose of having logs in the first place), but this severely limits performance and can quickly become a bottleneck. If flushing is delayed or done asynchronously, it improves performance but there is a risk of losing entries from the log if the server crashes before entries are flushed. Most implementations use techniques, such as batching, to limit the impact of the flush operation.

Another consideration is to make sure that corrupted log entries are detected while reading the log. To handle this, log entries are usually written with CRC records, which then can be validated when the files are read. While CRC allows detecting corrupted entries at a modest compute cost, even a simple technique like having an end-of-entry marker can be useful. If that marker isn’t present, the log entry wasn’t written and can be discarded on recovery.

Single log files can become difficult to manage and can quickly consume all the storage. To handle this issue, techniques like Segmented Log and Low-Water Mark are used.

The write-ahead log is append-only. Because of this behavior, in case of client communication failure and retries, logs can contain duplicate entries. When the log entries are applied, you need to make sure that the duplicates are ignored. If the final state is something like a HashMap , where the updates to the same key are idempotent, no special mechanism is needed. If they’re not, there needs to be some mechanism to mark each request with a unique identifier and detect duplicates.

It is important to note that write-ahead logging assumes the presence of stable storage. In the event of a media failure, the write-ahead log itself can be lost. To tolerate such failures, it is necessary to use the Replicated Log pattern instead.

Write-ahead logging is a commonly used pattern, particularly due to the characteristics of storage systems used today. It is employed because data is modified in volatile memory (RAM) and then made persistent by storing it on a hard disk. However, in the future, with the emergence of persistent memory products like Intel Optane, 21 the need for write-ahead logging may diminish. Instead, techniques such as write-behind logging [ Arulraj2016 ] can be utilized.

  1. [www.intel.in/content/www/in/en/products/docs/memory-storage/optane-persistent-memory/overview.html](http://www.intel.in/content/www/in/en/products/docs/memory-storage/optane-persistent-memory/overview.html)

Usage in Transactional Storage

Write-ahead log is often used to implement transactional storage. The concept of a transaction guarantees that changes made within a single transaction are done as one atomic operation. Either all the changes are done or none at all. They also ensure that, once done, the changes are durable. Multiple transactions do not interfere with each other, and when the transaction completes, the data store is in a consistent state.

The basic usage of a write-ahead log provides a way to do durable atomic updates. The other two properties of transactions, consistency and isolation, need to be provided by concurrency control mechanism using locks. It can be implemented as discussed in the section “ Locks and Transaction Isolation ” of the Two-Phase Commit pattern.

RocksDB 22 is a good example of how a write-ahead log is used to provide atomic updates. In RocksDB, the key and values, which need to be atomically stored, are written to a batch. The whole batch is then written to the data store. The data store writes a single entry in the write-ahead log for the entire batch. Once the entry is successfully written to the log, it is added to the key-value store.

  1. [https://rocksdb.org](https://rocksdb.org)

For example, if two key-value records need to be added atomically for the keys "author" and "title" , it is done as follows. A write batch is created with both key-value records.

Click here to view code image

KVStore kv = new KVStore(config);
WriteBatch batch = new WriteBatch();
batch.put("title", "Microservices");
batch.put("author", "Martin");

kv.put(batch);

The whole batch is written into the key-value store. The batch is appended to the write-ahead log as a single entry.

Click here to view code image

public void put(WriteBatch batch) {
    appendLog(batch);
    kv.putAll(batch.kv);
}

At restart, when the batch entry is read, the whole batch is applied to restore the keys and values.

Click here to view code image

private void applyBatchLogEntries(List<WALEntry> walEntries) {
    for (WALEntry walEntry : walEntries) {
        Command command = deserialize(walEntry);
        if (command instanceof WriteBatchCommand) {
            WriteBatchCommand batchCommand = (WriteBatchCommand)command;
            WriteBatch batch = batchCommand.getBatch();
            kv.putAll(batch.kv);
        }
    }
}

This makes sure that, in the event of a crash, either the whole batch is available or none of it is available.

Compared to Event Sourcing

A log of changes is similar to the log of events in event sourcing [ Fowler2005 ]. Indeed, when an event-sourced system uses its log to synchronize multiple systems, it is using its log as a write-ahead log. However, an event-sourced system uses its log for more than just that—for example, to be able to reconstruct a state at previous points in history. For this, an event sourcing log is the persistent source of truth and log entries are kept for a long time, often indefinitely.

The entries for a write-ahead log, however, are only needed for state recovery. Thus they can be discarded when all the nodes have acknowledged an update— that is, below the Low-Water Mark .

Examples

  • The log implementation in all consensus algorithms, such as Zab [ Reed2008 ] and Raft [ Ongaro2014 ] is similar to a write-ahead log.

  • The storage implementation in Apache Kafka uses a structure similar to that of commit logs in databases.

  • All the databases, including the nosql databases such as Cassandra, use the write-ahead log technique to guarantee durability.