Systems and Networking · 16 min · free lesson

Syscalls and Buffering

A syscall is a controlled trip into the kernel, and it is not free.

Core idea

Buffering can combine small writes; measure the boundary cost and handle errors explicitly.

Small writes enter BufWriter and an underlying writer; short writes and errors remain possible, and flushing is not a durability guarantee.
Buffering can reduce underlying writes. It does not guarantee one syscall, and flush errors must be handled.

Understand it

Operating-system file, socket and thread operations may enter the kernel. The transition and requested work can make many small operations expensive, but no fixed cost ratio applies to every workload. That is why buffering and batching can help when per-call overhead matters, while event loops can handle many mostly idle connections efficiently. Interviewers ask this to see whether you know where the cost of IO actually is.

A system call crosses from user code into the kernel to request a privileged operation. The transition and work on the other side have cost, but there is no single fixed ratio to a function call: data size, caching, contention, device latency, and kernel path all matter. Buffered I/O can combine many small writes into fewer requests. Scatter/gather I/O can send several buffers in one call. Batching is valuable when per-call overhead is a measurable part of the workload, not as a rule to apply blindly.

An event loop uses readiness or completion notifications so a thread need not block separately on every mostly idle connection. epoll and io_uring expose different Linux models, but neither guarantees superiority for every operation. A simple blocking read may be the best choice for a small tool. In Rust, a crate's API may buffer or batch internally, so profile the actual program before assuming the source line maps to one syscall.

In an interview, describe one concrete path: a program calls write, the kernel validates the request and copies or references data according to the API, then the call returns a result that may be partial or an error. Explain why a loop must handle short writes. If the question is performance, propose a measurement: syscall count, bytes per call, time waiting on I/O, and tail latency. The answer should connect the kernel boundary to the observed workload, not just name a fashionable interface.

Batching introduces a latency tradeoff: waiting to accumulate a large buffer can delay one small urgent write. Set a flush policy based on payload size or time budget. Partial I/O remains possible even after batching, so the loop must track bytes completed and retry the rest without duplicating already-sent data.

BufWriter batches bytes for an underlying Write implementation, which need not be an operating-system file. A flush can perform multiple writes because of short writes; large payloads may go directly to the underlying writer. Call flush() and handle its result when buffered output must be submitted before continuing: errors during drop cannot be reported to your caller. Flushing is not a promise that bytes are durable on storage; durability needs the relevant file and filesystem policy.

Interview follow-up: When does flush differ from durability, and what happens to errors discovered while BufWriter is dropped?

Read the code

use std::io::{self, BufWriter, Write};
fn write_lines<W: Write>(out: &mut W, lines: &[&str]) -> io::Result<()> {
    for line in lines {
        out.write_all(line.as_bytes())?;
        out.write_all(b"\n")?;
    }
    Ok(())
}
fn main() -> io::Result<()> {
    let lines = ["one", "two"];
    let mut direct = Vec::new();
    write_lines(&mut direct, &lines)?;
    let mut buffered = BufWriter::with_capacity(64, Vec::new());
    write_lines(&mut buffered, &lines)?;
    buffered.flush()?;
    assert_eq!(&direct, buffered.get_ref());
    println!("Both writers produced the same bytes");
    Ok(())
}

This in-memory example checks identical output and explicit flush error handling. Vec is not a kernel file: this program does not measure syscalls. A real underlying writer may need multiple writes, and large writes can bypass the buffer.

Practice starter

// Write implementation and input bytes are provided by the caller.
for byte in data {
    socket.write_all(&[byte])?;
}

Practise this code in Playground ↗

Try it

Count the syscalls in a hot loop and remove the ones that are avoidable.

What success looks like: Explain the measured request count, flush policy, partial-write handling and latency tradeoff.

Check your understanding

What should be investigated in this byte-at-a-time writer?

Reveal the answer
  1. Adding async syntax alone guarantees that all writes become one syscall.
  2. Measure tiny-write overhead and consider batching while preserving latency and errors.
  3. write_all guarantees this loop has exactly one kernel transition per byte.

Write can be buffered or user-defined. Errors are propagated by ?. Measure the actual boundary; batching still needs partial-write and flush policy.

Go deeper

Common misconception: write_all guarantees this loop has exactly one kernel transition per byte.

write_all promises nothing about the kernel. socket is only some Write implementation: it may buffer a byte and make no call, or retry after an interrupt. Count transitions on the real writer.

  1. Identify the contract: A syscall is a controlled trip into the kernel, and it is not free.
  2. Trace the concrete example: This in-memory example checks identical output and explicit flush error handling. Vec is not a kernel file: this program does not measure syscalls. A real underlying writer may need multiple writes, and large writes can bypass the buffer.
  3. Test the changed constraint: When does flush differ from durability, and what happens to errors discovered while BufWriter is dropped?

Transfer challenge: When does flush differ from durability, and what happens to errors discovered while BufWriter is dropped?

Connections

  • Virtual Memory: Pages, faults, and resident size
  • TCP vs UDP: Streams, datagrams, and trade-offs
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Syscalls and Buffering (courseId "interview", lessonId "q-syscalls")
Link: https://crabrix.com/learn/interview/q-syscalls/
Goal: Buffering can combine small writes; measure the boundary cost and handle errors explicitly.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=interview/q-syscalls) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.