File Sync Flushes To Stable Storage

Append each record with File.Sync so the durability contract is explicit: bytes reach stable storage before the call returns, surviving a crash.

GoData Integrity

Code

gosnippet
41 lines
package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	dir, err := os.MkdirTemp("", "wal-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "events.log")

	file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
	if err != nil {
		panic(err)
	}
	for i := 1; i <= 3; i++ {
		if _, err := fmt.Fprintf(file, "event-%d\n", i); err != nil {
			panic(err)
		}
		// Sync 把内核页缓存里的字节推到稳定存储:
		// 返回后即使进程崩溃或断电,这条记录也已在磁盘上
		if err := file.Sync(); err != nil {
			panic(err)
		}
		fmt.Println("durable: event", i)
	}
	if err := file.Close(); err != nil {
		panic(err)
	}

	data, err := os.ReadFile(path)
	if err != nil {
		panic(err)
	}
	fmt.Print("replay:\n", string(data))
}

Inside the snippet

File Sync Flushes To Stable Storage is built around the function main.

Repetition is confined to for i := 1; i <= 3; i++ — the rest of the file is straight-line. Failure handling is panic(err): 6 checkpoints abort the program at the point a problem is detected. The cleanup call is deferred to function exit — success, early return, and panic all covered.

Points of care

  • A package manager never enters the picture — calls land on built-ins.
  • panic(err) is the only failure path here: the first problem stops the program.

Putting it to use

Signature: func main()

Printed labels narrate the run: durable: event, replay:\n.

Lines worth quoting

if err != nil {
	panic(err)
}
defer os.RemoveAll(dir)

Interactive Tools for This Topic

FAQ

How are errors reported?
By aborting: each of the 6 `err != nil` branches calls `panic(err)`, so a failure stops the program at the point it is detected.
What does File Sync Flushes To Stable Storage print when run?
The script runs standalone; its 2 labeled outputs include `durable: event`, `replay:\n`.