Writing changes to the log first
Write-ahead logging (WAL) is a crash recovery technique: before changing a page in the database, the change is written to a sequential log file on disk. The log is slower but safer than random writes to the main database file. If the system crashes, the log survives, and on restart the database replays every logged change to restore the state at the moment of the crash.
Why log-before-page is essential
If you wrote the page first and then the log, a crash between the two leaves the database in a corrupt state: a page is changed but the change is not logged, so it is lost on restart. WAL reverses this: the log is the source of truth. The in-memory cache can be lost safely because the log has a durable copy. Most databases (PostgreSQL, MySQL InnoDB, SQLite) use WAL for durability.
Performance optimization through batching
Logging every tiny change immediately would be slow. Modern systems buffer changes in memory and write the log in batches, trading some crash-safety window for speed. The commit() call forces a batch write to disk, guaranteeing that the transaction is durable. Tuning the batch size and fsync frequency balances durability guarantees against throughput.