What happens when you INSERT a row in Postgres?
Postgres needs to ensure that data is durable while maintaining good write performance + crash recovery ability. The key is in the Write-Ahead Log (WAL).
(1) Postgres receives the query and determines what data page to place it in. This could already be in memory (buffer pool), or it may have to load one from disk, or even create a new one.
(2) The new record is written to this page in memory only. The page is marked as “dirty” meaning it needs to get flushed to disk in the future, but not immediately.
(3) A new record is inserted into the memory buffer for the WAL. It contains all the information needed to reconstruct the insert.
(4) The WAL is flushed to disk (via fsync or similar) to ensure the data resides in durable storage. After this succeeds, Postgres return success to the client.
When you get a success at the client, the data has definitely been written to the sequential WAL (good write performance) but not necessarily to the table data file (less predictable I/O patterns). The latter happens later on via checkpointing, background jobs, or forced flushes due to memory page eviction. If a server crash happens before the data is flushed, the log is replayed to restore committed data.
The WAL is the key to all of this! It facilitates high-performance I/O and crash recovery.