Go: Check errors when flushing buffered output
A successful write to a buffered writer may only mean that bytes entered its memory buffer. The underlying destination can fail later, when Flush tries to send those bytes.
Set up
Tested on Linux amd64 with Go 1.26.10. Use Bash with Go on your PATH, a text editor, and the mktemp, rm, and rmdir utilities. The example uses only the standard library. Keep the same terminal through cleanup, and stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as go-bufio-flush-delayed-error.go:
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
)
var errSink = errors.New("sink unavailable")
type failingSink struct{}
func (failingSink) Write(p []byte) (int, error) { return 0, errSink }
func main() {
var destination bytes.Buffer
good := bufio.NewWriterSize(&destination, 16)
if _, err := good.WriteString("ready"); err != nil {
panic(err)
}
fmt.Printf("before flush: %q\n", destination.String())
if err := good.Flush(); err != nil {
panic(err)
}
fmt.Printf("after flush: %q\n", destination.String())
bad := bufio.NewWriterSize(failingSink{}, 16)
n, err := bad.WriteString("ready")
if n != 5 || err != nil {
panic("expected buffered write")
}
fmt.Printf("buffered write: bytes=%d error=%v\n", n, err)
err = bad.Flush()
if !errors.Is(err, errSink) {
panic("missing flush error")
}
fmt.Println("flush error:", err)
_, err = bad.WriteString("again")
if !errors.Is(err, errSink) {
panic("missing retained error")
}
fmt.Println("next write error:", err)
}Run:
go run go-bufio-flush-delayed-error.goObserved output:
before flush: ""
after flush: "ready"
buffered write: bytes=5 error=<nil>
flush error: sink unavailable
next write error: sink unavailableRead the result
The first destination stays empty until the explicit flush. The failing destination accepts no bytes, but the short initial write still succeeds because it fits inside the buffer. The failure appears when the buffer is flushed.
After an underlying write error, the buffered writer retains that error. The later write returns it too. Checking only the first write therefore misses the failure. A longer write can reach the underlying destination earlier, so every write still needs its own error check.
Apply it carefully
A deferred call whose return value is discarded cannot report a flush failure to the caller. Flush explicitly where the function can handle or return its error. Flushing is not a disk durability guarantee and does not close the underlying writer. File owners must manage close errors and any required synchronization separately. Do not blindly resend a whole logical record after a partial write: the destination may already contain a prefix.
See the Go standard-library reference.
Clean up
Remove the saved source and the empty scratch directory. Go manages its build cache separately. If the directory is not empty, inspect its contents before removing anything else.
rm -- go-bufio-flush-delayed-error.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.