I/O and Syscalls
The cost of crossing into the kernel and what the scheduler does meanwhile. Buffer your I/O.
Reading or writing a file asks the operating system to do work through a syscall. Thousands of tiny reads or writes can spend more time on those requests than on useful processing. We will batch them with buffers.
Content You May Want to Check First
- The Scheduler (article, Internals for Interns): what the runtime does when a goroutine enters a system call.
- The Network Poller (article, Internals for Interns): how Go keeps a blocking API on top of non-blocking network I/O.
Learning Objectives
By the end of this module, you will:
- Understand why many small I/O calls are expensive
- Use buffered writes and larger reads
- Count write syscalls with
straceon Linux - Handle write errors and flush the final buffer
The Concept: Crossing Into the Kernel
Crossing into the operating system
A syscall transfers control to the kernel, which performs an operation and returns. Go also does bookkeeping so other goroutines can continue when a syscall blocks. This is more work than copying a few bytes into memory.
Sockets often let Go wait for readiness without holding an operating-system thread. Regular-file I/O can block a thread. Either way, reducing unnecessary calls can help.
Batch small writes
*os.File does not collect small writes into a Go buffer. A loop that calls fmt.Fprintf(f, ...) once per record normally makes a write syscall for every record.
bufio.Writer collects those small writes in memory, then sends a larger chunk to the underlying writer. Its default buffer is 4 KiB. Large reads provide the same benefit in the other direction.

Finish the write
Always call Flush and check its error. The last part of the output may still be in memory when the loop ends. Closing the underlying file does not flush a separate bufio.Writer for you.
Handle errors from writes as well. Flushing sends buffered bytes to the underlying writer; it does not guarantee that file data is durable on disk.
The Lab
WriteRecords writes 5,000 CSV lines with fmt.Fprintf. CountLines reads a file one byte at a time. The write benchmark uses /dev/null; the read benchmark uses a temporary file. We are mainly measuring call overhead, not disk speed.
Run the commands from the repository root.
Step 1: Measure the baseline
make bench LAB=14
Step 2: Find the cost
On Linux, count writes with:
(cd labs && go build -o /tmp/records ./14-io-syscalls/cmd/records)
strace -c -f -e trace=write /tmp/records -mode=before
Expect about 5,001 writes: one per record plus the program’s final message. If strace is unavailable, continue with the benchmarks. The optional cmd/syscallcost demo compares individual call costs on Linux.
Step 3: Fix it
Edit labs/14-io-syscalls/after.go. Keep before.go as the baseline.
- In
WriteRecordsAfter, createbufio.NewWriter(f)and write to it instead of directly tof. Check write errors and return the finalFlusherror. Benchmark this change first. - Then replace
fmt.Fprintfwithstrconv.AppendIntandappendinto a reusedline []byte. Reset it withline[:0]for each record, keeping the exact CSV format. - In
CountLinesAfter, read blocks into a 32 KiB buffer and count newlines withbytes.Count(buf[:n], []byte{'\n'}). Process any bytes returned before handlingio.EOFor another error.
Step 4: Check and compare
(cd labs && go test ./14-io-syscalls/)
make bench LAB=14
Reference solution (make solution LAB=14), on my machine:
| Benchmark | Before | After |
|---|---|---|
WriteRecords |
855.89 µs | 86.35 µs |
WriteRecords allocations |
14,730 | 4 |
CountLines |
13.431 ms | 4.830 µs |
Understanding the Results
WriteRecords improves in two stages. Buffering removes most small syscalls; direct formatting into a reused slice removes the extra fmt work and boxing allocations. Together they make it about 10x faster here.
CountLines makes a few large reads instead of tens of thousands of one-byte reads. It uses a larger temporary buffer but does much less coordination with the operating system.
Rebuild /tmp/records and run -mode=after under strace. The reference solution reduces writes from about 5,001 to 24. Correctness tests also catch missing output caused by forgetting Flush.
Key Takeaways
- Batch small file writes with
bufio.Writer. - Read blocks instead of one byte at a time.
- Always handle errors and check the final
Flush. - Buffering and avoiding formatting allocations are separate improvements.
Going Further (optional)
- Try a 64 KiB writer buffer. Does it help beyond the default size?
- Run
/tmp/records -mode=noflushand compare the output size. - Reuse the read buffer across calls. How do
B/opandallocs/opchange?