medium.com 8 min read Original Source

Every Time You Call .save(), This Is What Actually Happens

There is a moment in every engineer’s career when they realise they have been calling database methods for years without knowing what those methods actually do. Not the ORM abstraction or the SQL that gets generated, but what physically happens between the application and the disk. The sequence of operations that determines whether your data survives a server crash or disappears quietly into nothing.

I had that moment while debugging a production incident where a batch of records appeared to have been committed successfully but were not recoverable after an unexpected restart. The application had returned a success response. The transaction had closed without error. After the restart, the records were gone. It turned out the database had been configured to acknowledge commits before the write-ahead log reached durable storage, a trade-off someone had enabled months earlier for write throughput and forgotten about. Understanding why this was even possible required understanding something I had assumed I understood, what a database actually does when you tell it to save something.

What follows is that explanation, from the application call down to the physical disk, with every step that most engineers skip over.

The gap between “committed” and “on disk”

When your application calls .save() or executes a COMMIT, the database does not immediately write your data to the actual data files on disk. If it did, databases would be orders of magnitude slower than they are, because disk writes are expensive and every transaction would have to pay the full cost of a synchronous disk operation before returning to the caller.

Instead, the database maintains an in-memory structure called the shared buffer pool. When you write data, it goes into the shared buffer pool first, a large region of memory that acts as a cache between your application and the actual data files. The modified pages sit in memory, marked as dirty, waiting to be flushed to disk by a background process. The transaction committed successfully but only from the application’s perspective. Whereas, from the disk’s perspective, nothing has happened yet.

This is the actual gap where your application believes the data is safe. The data is in memory and hence it is volatile. Fortunately, databases do not rely on memory alone.

If the server loses power or the database process crashes between the commit and the eventual flush to disk, that data is gone without an additional safety mechanism. The database is not lying to you either, when it says the transaction committed. The commit is real. The durability guarantee, however, requires something else entirely.

The write-ahead log

The mechanism that makes committed transactions survive crashes is the write-ahead log, called the WAL in PostgreSQL, the redo log in MySQL, and the transaction log in SQL Server. The name describes exactly what it does: before any change is applied to the actual data pages, a record of that change is written to the log first. Write ahead, then apply.

The WAL does not store a copy of the whole table. It stores enough information to replay or undo each change during recovery: what changed, where it changed, and what the value was before and after. This is significantly smaller than the data pages themselves, which is part of what makes WAL writes fast.

The WAL records every change immediately. On commit, PostgreSQL flushes the WAL to durable storage before acknowledging success (with synchronous_commit = on). If the server crashes after a commit, PostgreSQL can replay the WAL on restart and reconstruct the committed state, even if the data files themselves never received the changes before the crash.

The WAL is append-only and sequential. Appending to a sequential log is dramatically faster than writing to random locations in data files, because sequential disk writes avoid seek time. This is a deliberate design choice, the WAL absorbs the durability cost so that the data files can be written more lazily, in larger batches, at times that are more convenient for the storage system.

Understanding this changes how you read database performance numbers. When someone says PostgreSQL can handle ten thousand writes per second, they largely mean PostgreSQL can sustain that rate of WAL commits. The data files will eventually catch up through a background process called checkpointing, but the WAL is the critical path.

The write path from application to disk

Here is the full path a write takes, from your application call to stable storage:

The shared buffer pool and the WAL operate in parallel. The WAL records every change and flushes to durable storage on commit. The data files receive changes later, through checkpointing. This separation is what gives PostgreSQL both durability and performance, durability comes from the WAL, performance comes from deferring the more expensive random writes to the data files.

What fsync actually does

The WAL is only as durable as the guarantees made about flushing it to disk. This is where fsync enters the picture, and where things get more complicated than most explanations admit.

When a process writes data using normal file I/O, the operating system does not immediately write that data to the physical storage device. It writes to the OS page cache, another layer of in-memory buffering managed by the kernel. The write syscall returns almost immediately, but the data is still in memory. The OS will flush it to disk eventually, based on its own scheduling logic, typically within seconds to minutes.

fsync is the syscall that forces the OS to flush everything in the page cache for a given file to the underlying storage device and wait for confirmation that the device has written it to stable storage. It is slow because it has to wait for the actual hardware. On a spinning disk, fsync latency is typically in the range of five to ten milliseconds. On an SSD, one to two milliseconds. On a network-attached storage device under load, considerably longer.

PostgreSQL calls fsync on the WAL after every transaction commit, by default. This is what the synchronous_commit setting controls. With synchronous_commit = on, the database waits for the WAL flush to complete before telling the application that the transaction committed. The application blocks until the WAL is on stable storage.

With synchronous_commit = off, PostgreSQL acknowledges the commit immediately without waiting for the WAL flush. The data will be flushed within a short window, typically a few hundred milliseconds, but there is a gap during which a crash would lose the most recent commits. PostgreSQL calls this asynchronous commit and explicitly documents that it can lose recent transactions on crash. The application receives a success response, and the data might not survive.

This setting is frequently misunderstood. Engineers enable asynchronous commit for performance without fully internalising what they have traded away. The production incident I described at the start of this article happened on a system where someone had set synchronous_commit = off to improve write throughput, forgotten about it, and six months later encountered the crash scenario that made the trade-off visible.

The checkpoint and what happens to dirty pages

While the WAL handles crash recovery, the data files still need to eventually receive the actual changes. This happens through checkpointing.

A checkpoint is a point in time at which PostgreSQL guarantees that all dirty pages in the shared buffer pool have been flushed to the data files. After a checkpoint, PostgreSQL knows that if it crashes, it only needs to replay WAL records from the checkpoint forward, not from the beginning of time. This bounds the recovery time after a crash.

Checkpoints happen automatically on a schedule controlled by checkpoint_timeout, default five minutes, and when the WAL grows past a size threshold controlled by max_wal_size. During a checkpoint, the background writer flushes dirty pages to disk in a controlled way, spreading the I/O over time to avoid a spike that would impact foreground query performance.

The checkpoint_completion_target setting controls how aggressively PostgreSQL spreads that I/O. A value of 0.9 means PostgreSQL tries to complete the checkpoint over 90 percent of the interval between checkpoints, smoothing out the disk writes across most of the checkpoint cycle rather than doing them all at once.

Tuning these settings is one of the more consequential performance decisions in a PostgreSQL deployment. Checkpoints that are too frequent increase write amplification and slow down normal operations. Checkpoints that are too infrequent mean longer crash recovery times and the possibility of checkpoint-induced I/O spikes when a large checkpoint does run.

What your ORM is not telling you

Most ORM frameworks abstract all of this completely. You call .save(), the ORM generates SQL, the SQL runs in a transaction, the transaction commits, and the method returns. The shared buffer pool, the WAL, the fsync, the checkpoint are all invisible.

This invisibility is useful for application development and dangerous for production operations. The settings that control durability are database configuration, not application code, and they have defaults that may or may not match the requirements of your specific workload.

The default PostgreSQL configuration is designed to be safe rather than fast. synchronous_commit = on by default means every commit waits for the WAL flush. fsync = on by default means the OS page cache flush is forced on every WAL write. These defaults give you the strongest durability guarantees at the cost of throughput.

Systems that prioritise throughput over durability often turn one or both of these off. High-volume analytics ingestion pipelines, logging systems, and metric collectors are common examples where losing a few seconds of data on crash is acceptable and write throughput is the primary constraint. Accepting this trade-off consciously is fine. Accepting it accidentally because someone changed a configuration value without understanding what it controlled is how production incidents happen.

Why this changes how you think about database calls

The practical consequence of understanding this stack is that you stop treating database calls as atomic, instantaneous operations and start thinking about the pipeline: application memory, shared buffer pool, WAL, OS page cache, storage device. Each layer introduces latency and a failure window. Each layer has configuration that determines the trade-off between performance and durability.

A COMMIT that returns successfully means the WAL has been flushed to stable storage, if synchronous_commit is on and fsync is on and the storage device is honest about write completion. Network-attached storage and some consumer SSDs lie about write completion, reporting writes as complete before they have actually written to stable storage, which defeats fsync entirely. This is why production database deployments specify storage devices that support write barriers and do not use consumer hardware with aggressive write caching.

The pg_stat_bgwriter view in PostgreSQL exposes checkpoint statistics that tell you whether your checkpoint configuration is causing problems. High buffers_checkpoint counts relative to buffers_clean suggest that background writer activity is not keeping up and checkpoints are doing too much work. High checkpoint_sync_time suggests that fsync operations during checkpoints are taking longer than expected, often a signal of storage saturation.

These are the numbers that explain why the database is slow when everything in the application looks fine, and why a seemingly unrelated configuration change can cause latency to appear or disappear without any changes to the application code.

The next time you call .save(), you now know what you are asking the system to do. You are asking it to write to memory, record the change in a sequential log, flush that log to stable storage, eventually flush the data pages to disk, and periodically run a checkpoint so that crash recovery stays bounded. All of that happens transparently, configured by settings that have defaults chosen for safety rather than the specific requirements of your workload.

That transparency is a feature of good database design. Understanding what is behind it is what separates engineers who configure databases from engineers who operate them.

This article is part of a series on architectural trade-offs in backend systems. The next pieces cover how these database internals connect to decisions like SQL versus NoSQL, what durability actually means when choosing between database configurations, and how isolation levels interact with the write path described here.