6.2 fsync: Confirming the Write Reached Persistent Media

To solve this problem, the operating system must be asked to push the cached data down to the disk device and to return only after waiting until the device confirms it has been recorded on the persistent medium. This system call is fsync. (On Windows, an API with a different name does the same job, but here the widely used name fsync is used for all of them.) When committing a transaction, the database hands the log buffer contents to the operating system, calls fsync, and responds "committed" to the user only after fsync returns. The "moment of being safely stored" in the second line of the WAL rule in Chapter 5 means exactly the moment this fsync completes.

fsync is expensive. Writing to the operating system cache takes only microseconds, but fsync must make a round trip to the disk device, so it takes tens to hundreds of microseconds on an SSD and several milliseconds on a hard disk. On a hard disk, it is hard to exceed a few hundred fsync calls per second, and this becomes the upper bound on "the number of transactions that can be committed per second." If every commit does one fsync, no matter how fast the CPU or how large the memory, more than a few hundred commits per second are not possible.

There is one more problem. In some cases fsync returns after pushing data only as far as the third layer, the disk device cache. The device responds done at the moment it receives the data into its own cache rather than the persistent medium. On such a device, data is lost on power loss even after fsync. That is why server storage devices are equipped with a battery or capacitor that preserves the cache contents when power is cut, or are operated with the write cache turned off. This is why the advice to "check the disk write cache setting" comes up when setting up a database server. No matter how correctly the software calls fsync, durability is not guaranteed if the hardware responds done before the data is recorded on the persistent medium.