> Markdown version of https://www.artie.com/blogs/postgres-write-ahead-logs. Site index for AI agents: https://www.artie.com/llms.txt

[Back to blog](https://www.artie.com/blogs)

Data know-how September 22, 2024

# Postgres Write-Ahead Logs

[Madison Schott](https://www.artie.com/authors/madison-schott)

[Share on LinkedIn (opens in a new tab)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.artie.com%2Fblogs%2Fpostgres-write-ahead-logs) [Share on X (opens in a new tab)](https://x.com/intent/post?text=Postgres%20Write-Ahead%20Logs\&url=https%3A%2F%2Fwww.artie.com%2Fblogs%2Fpostgres-write-ahead-logs)

## Intro

This is the second part of our deep dive into Postgres logical replication. If you haven’t read through part one on [replica identity](https://www.artie.com/blogs/postgres-table-replica-identity), be sure to check that out. In this part, we’ll discuss how write-ahead logs work, why you want to use them, and their various components and settings.

## Write-ahead logs

Write-ahead logs are what logical replication reads from. They are used to ensure data durability, meaning your data is consistent and protected against data loss. Even if a server machine fails, write-ahead logs ensure your changes persist.

While WAL is enabled by default in Postgres, it’s important that your disk space meets all of the requirements necessary to use WAL files. You can configure different parameters to determine how much information is written to logs and the amount of shared memory they contain.

## How do write-ahead logs work?

Write-ahead logs store each state change as a command with a unique identifier within an append-only file. Each of the commands in this append-only file contains all the information needed to replicate the change.

It stores these commands BEFORE any changes are made. Once the change is committed, the record is marked, indicating to the system that the change was already made. If the system fails, it can read the commands sequentially within the logs, starting from the one it left off on.

Postgres then purges the logs when a checkpoint is complete and the data has been flushed to disk.

## Components of write-ahead logs

1. Logs
2. Checkpoints
3. Buffers
4. Log sequence numbers (LSN)
5. Replication slots

![img\_4.png](https://www.artie.com/editorial/blogs/postgres-write-ahead-logs/01-67aa007687d150a95dadad51-img-4.webp)

### Logs

WAL logs are the files in which various transactions are stored. These logs are written to disk before the changes are made to the database.

### Checkpoints

Checkpoints are points in the sequence of transactions within a log file where all the data is guaranteed to have been updated with the information before the checkpoints. These are particularly important in crashes since the WAL file recovers from the most recent checkpoint. This is then where the system performs the REDO operation.

### Buffers

Postgres refers to buffers as the working units that read and write data to your tables. The buffers of write-ahead logs are typically called transaction log buffers. These determine the amount of memory allocated to storing WAL data which we will configure later in the article when we look at the **wal\_buffers** parameter.

### Log sequence numbers (LSN)

![img\_3.png](https://www.artie.com/editorial/blogs/postgres-write-ahead-logs/02-67aa007678867bddf171e93f-img-3.webp)

A log sequence number (LSN) is a 64-bit byte position in the WAL. LSNs only ever increase and use the `pg_lsn` data type. Subtracting one LSN from another gives the number of bytes of WAL between them, which is how you measure how far a replica or a replication slot has fallen behind.

### Replication slots

Replication slots are reservations for a replication connection to send WAL data to a replica. They are used to safeguard against losing data. Postgres uses them to retain data necessary for WAL, ensuring it is not removed until all necessary changes have been made.

## WAL settings

There are several important parameters you can set to control database performance while using WAL. These include:

* **`wal_level`**
* **`fsync`** and **`wal_sync_method`**
* **`wal_buffers`**
* **`checkpoint_flush_after`**
* **`max_replication_slots`**
* **`max_slot_wal_keep_size`**

### wal\_level

This setting controls how much information is written to your logs. In the case of Postgres replication, you will most likely want to use the default of replica.

However, there are three possible values for **wal\_level**:

* **`minimal`** - only writes the minimum amount of information to the logs. This is not recommended for production.
* **`replica`** (default) - writes enough information to allow for replication
* **`logical`** - writes enough information to allow for logical replication. This is needed to **enable change data capture**.

### fsync and wal\_sync\_method

The **`fsync`** parameter determines whether WAL files are written to disk. By default, this is set to on. You should not disable this setting as it can lead to data loss in the case of a crash.

When **`fsync`** is enabled, **`wal_sync_method`** sets how WAL is forced to disk. The default depends on the platform: **`fdatasync`** on Linux and FreeBSD, and otherwise the first method in this list that the platform supports.

* **`open_datasync`**
* **`fdatasync`**
* **`fsync`**
* **`fsync_writethrough`**
* **`open_sync`**

We recommend using the default settings for both of these parameters, unless you are trying to finetune these settings for performance or adapt to your specific hardware.

### wal\_buffers

This refers to the amount of shared memory used for WAL data that hasn’t yet been written to disk. The default of -1 is usually just right for optimal performance. Increasing it gives WAL more shared memory, so a busy server has to write WAL out less often between commits. It doesn't remove the flush at commit: with the default `synchronous_commit`, each commit still waits for its WAL to reach disk.

Setting this to a large value won't usually help much. It can improve write performance on busy servers where many transactions commit at the same time.

A related setting, **`synchronous_commit`**, is on by default: a commit is only reported as successful once its WAL is flushed to disk. With **`synchronous_commit = off`**, a crash can lose the last few transactions that were reported as committed, though it won't corrupt the database.

Because **wal\_buffers** only takes effect when the server starts, set it in postgresql.conf or with **`ALTER SYSTEM SET wal_buffers = '12MB';`**, then restart Postgres.

### checkpoint\_flush\_after

This parameter allows you to specify the number of pages before already-written data should be flushed to disk. When configured correctly, it helps reduce latency on transactions inserted to WAL.

By flushing data to disk, you are reducing the amount of dirty data in the cache, helping to improve updates out to disk (fsyncs) at checkpoints. This then affects the duration of checkpoints and the memory consumed during them.

A value of 0 disables forced writeback. The maximum is 2MB; higher values let the operating system batch more writes, which can help bulk data operations but makes checkpoint I/O more uneven. The setting governs when data pages are written back during a checkpoint, so it doesn't change how much WAL is kept in pg\_wal.

You can set this value by running **`ALTER SYSTEM SET checkpoint_flush_after = '1MB';`** and then **`SELECT pg_reload_conf();`**

### max\_replication\_slots

**max\_replication\_slots** refers to the maximum number of replication slots that can be used by the server. A replication slot can only be consumed by one process at a time. To use this parameter, wal\_level must be set to replica or higher. The default of this parameter is 10. However, if you change this, keep in mind that it can’t be lower than the current number of slots, or the server will not start.

To change the value of this parameter, run the following command **`ALTER SYSTEM SET max_replication_slots = 20;`**

### max\_slot\_wal\_keep\_size

This parameter specifies the maximum size of the WAL files that the replication slots retain at the time of checkpoint. The size helps to limit the amount of data written to disk while also considering potential lag caused by replication. If the units are not specified, then it defaults to megabytes.

To see the size of your replication slots:

SQL

```
SELECT
  slot_name,
  active,
  pg_size_pretty(
    pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)
  ) AS retained_wal
FROM pg_replication_slots;
```

## Why use write-ahead logs?

Losing data is a nightmare for any data engineer. WAL provides disaster recovery that you may not otherwise get. Write-ahead logs allow for data integrity and consistency when replicating changes from the primary database log. Because changes are first written to WAL, the primary database doesn’t have to sacrifice performance. You really can have the best of both worlds!

While WAL does increase I/O, the overall performance of systems with it enabled tends to be more favorable than those without. This is due to two main behaviors of WAL - **sequential writes** and **checkpoints**.

WAL leverages sequential writes to the database rather than random writes. Sequential writes are more efficient, allowing transactions to be committed faster and the system to be more performant.

Checkpoints within WAL prevent the need to write data to files right away. First, data is written to WAL files in sequential order. Second, an async process is triggered by the **checkpoint\_timeout** or **max\_wal\_size** parameter, whichever comes first.

Another concern of write-ahead logs is their use of storage. Postgres removes or recycles WAL segments after each checkpoint, so normally the WAL directory stays around **`max_wal_size`** (1GB by default). Anything that still needs older WAL holds it on disk: **`wal_keep_size`**, and above all replication slots. An inactive or lagging slot keeps WAL indefinitely, so monitor slot lag and set **`max_slot_wal_keep_size`** as a ceiling. With **`archive_mode`** on, a failing **`archive_command`** also keeps WAL growing, because segments stay until they're archived.

## Conclusion

Write-ahead logs can be a game-changer for disaster recovery when working with Postgres replication. They provide lots of different parameters to ensure it works with your database, giving you the confidence that you need to make changes to your database.

## Related articles

* ### [How to Build Audit Logs Using CDC and SCD Type 2](https://www.artie.com/blogs/how-to-build-audit-logs-using-cdc-and-scd-type-2)

  [Dana Fallon Founding Engineer](https://www.artie.com/authors/dana-fallon)

* ### [PostgreSQL to Snowflake Replication](https://www.artie.com/blogs/postgresql-snowflake-replication)

  [Jacqueline Cheong Co-founder & CEO](https://www.artie.com/authors/jacqueline-cheong)

* ### [Postgres Table Replica Identity](https://www.artie.com/blogs/postgres-table-replica-identity)

  [Robin Tang Co-founder & CTO](https://www.artie.com/authors/robin-tang)

## We’re a data company

## Watch your data replicate live

[Start for free](https://app.artie.com/signup) [Book a demo](https://www.artie.com/contact)
