Foundations · L1OS essentials for backend engineers

OS essentials for backend engineers

Processes, threads, memory, files and system calls are where your code meets the machine. Know them, and many "random" production failures stop being random.

L1 Must-knowFoundations19 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 7 Nov 2026 · How we check content
Section 1 of 8

What broke

A made-up story to show a common failure. Not about a real company.

This is a made-up example, but each part of it is common. A team moves a Java order service into Kubernetes. The container gets a 512 MiB memory limit. To be safe, they set the JVM heap to 512 MiB too.

Under load, the pod restarts every few hours. kubectl get pod shows the status OOMKilled. The last state has exit code 137. The Kubernetes docs show exactly this pattern: a container goes over its limit, gets killed, restarts, and gets killed again. 1

The team looks at the JVM dashboard. Heap use is at 400 MiB, well under 512 MiB. So who used the memory?

The answer is: the operating system counted more than the heap. The limit applies to the whole container. It counts every thread stack and every native buffer. 3 6 It even counts file pages in the page cache, but the kernel can free those first. Stacks and native memory cannot be freed that way. 3

A week later, the same service fails in a new way. Logs fill with "too many open files". A client library forgot to close sockets. This lesson explains both failures, and the OS ideas behind them.

Section 2 of 8

The idea in simple words

Your program cannot use devices such as disks and network cards directly. The kernel sits in between. It shares the CPU, memory and disks among many programs.

A process is a running program with its own private memory. A thread is one line of execution inside a process. Threads in one process share memory and open files. Each thread has its own stack. 6

When your code needs the kernel, for example to read a file or send bytes on a socket, it makes a system call. That call costs time.

The kernel also keeps limits. It limits how much memory a group of processes may use, and how many files one process may hold open. Some limits are hard. When you hit the memory limit or the open-file limit, the kernel does not slow down politely. It kills the process, or the call fails.

The key idea. Your runtime shows you a small part of the picture, such as the heap. The kernel counts much more: almost all memory, every open file and socket, and time spent waiting. Limits and costs come from the kernel's view, not your runtime's view.

Section 3 of 8

How it works

User mode, kernel mode and system calls

Your code runs in user mode. In user mode it cannot do I/O or other privileged operations. The kernel runs in kernel mode, with full access to the machine. 4

To ask the kernel for something, a program runs a special trap instruction. The CPU jumps into the kernel, which does the work and then returns to user mode. 4 read, write, open, accept and fsync are all system calls.

Context switches

The kernel shares each CPU among many threads. It runs one for a while, then switches to another. To switch, it saves the registers of the running thread and restores those of the next one. This is a context switch. 4

Both steps cost time. In 1996, on a 200 MHz CPU, a system call took about 4 microseconds and a context switch about 6. 4 OSTEP says modern 2–3 GHz systems reach sub-microsecond results. 4 These are the direct costs. OSTEP also notes that many OS operations depend on memory speed, which has not improved as fast as CPUs. 4 A few microseconds is cheap once. It is not cheap 100,000 times per second, so reading a file 1 byte per call is slow.

Virtual memory

Every process gets its own address space. It looks like a large, private block of memory. The OS and hardware map each address to a real place in RAM. 5

So every address your program prints is a virtual address. 5 Two processes can use the same address and never see each other's data. This is how the OS keeps one buggy process from damaging another. 5

The page cache

The kernel keeps recently read and written file data in RAM. This is the page cache. In /proc/meminfo you see it as Cached. 13

The page cache is why the second read of a file is often much faster than the first. It is also why free on a busy server can show little free memory. The useful number is MemAvailable: how much memory new programs can get without the system swapping. 13

Memory limits and the OOM killer

The container runtime puts the processes of each container in a control group, or cgroup. Kubernetes uses it to enforce the container's memory limit. 2 In cgroup v2, memory.max is the hard memory limit. 3

The cgroup counts the page cache, anonymous memory such as heaps and stacks, and some kernel memory, such as TCP socket buffers. 3 When usage reaches memory.max and the kernel cannot reduce it, it runs the OOM killer inside that cgroup. 3 The OOM killer ends a process to get memory back.

memory.events counts these events. oom counts how often the limit was reached, and oom_kill counts processes killed. 3 There is also a softer limit, memory.high. Going over it slows the processes down, but it never calls the OOM killer. 3

In Kubernetes, a container may use more than its request if the node has room, but never more than its limit. 1

Files and file descriptors

When you open a file, the kernel returns a file descriptor. It is a small number, starting from 0, that points into your process's table of file descriptors. 7 A new socket gets a file descriptor too. 8 So do pipes. 10

Each process has a limit, RLIMIT_NOFILE. Calls such as open, pipe and dup that go over it fail with EMFILE. 10 The open(2) man page describes EMFILE as the per-process limit on open file descriptors. 7 Your logs show it as "Too many open files". 9 There is also a system-wide limit, which gives ENFILE. 7

The limit has a soft value, which the kernel enforces, and a hard value, which caps the soft one. A child process inherits its parent's limits. 10

All threads in a process share one descriptor table and one limit. 6 A leak in one library can starve the whole service.

Writes, fsync and durability

Step through one write, with the ← and → keys or the buttons.

write() returns once the data is in the page cache; fsync() waits for the disk Your app Kernel Disk write()user → kernel mode page: dirtydonein RAM only, not on disk fsync()app waits… flushstoredpage: clean done✓ now the data is on the device SeniorPath
  1. Your app calls write() with 4 KB of data. This is a system call: the CPU switches from user mode into the kernel.
  2. The kernel copies the data into a page in the page cache, in RAM, and marks the page dirty. Then write() returns. The data is not on the disk yet. A power cut now loses it.
  3. To make the data durable, the app calls fsync() on the same file descriptor. The call blocks. Your thread waits.
  4. The kernel sends the dirty page to the disk and waits for the device to confirm it has stored the data. Now the page is clean.
  5. Only now does fsync() return. This wait is the cost of durability. A database waits for a flush like this before it confirms a commit, though one flush can serve several commits.
Step 1 of 5

A successful write() does not mean the data is on disk. 11 For normal, buffered writes, the kernel only copied it into the page cache. 3 /proc/meminfo calls this data Dirty: memory waiting to be written back to disk. 13

fsync() sends the file's changed data to the storage device. It blocks, and returns only after the device confirms it has stored the data. 12 If you created a new file, you also need an fsync() on its directory to be sure the entry is on disk. 12

Errors can come late, too. If the kernel fails to write the data back, fsync() reports it. 12 On some filesystems, such as NFS, an error may show up only at a later write(), fsync() or even close(). 11 Always check the return value of fsync().

This wait is real. PostgreSQL waits for its log records to reach permanent storage before it reports a commit. For short transactions, the docs call this delay "a major component of the total transaction time". 14

Seeing it on a real server

Brendan Gregg's USE checklist names the tools for each resource. 15

  • free -m and vmstat 1 for memory use. vmstat columns si and so show swapping. 15
  • dmesg | grep killed to find OOM kills. 15
  • /proc/sys/fs/file-nr for system-wide open files. 15
  • strace to catch calls that fail with EMFILE. 15
Section 4 of 8

Trade-offs

ChoiceGood forCostWatch out for
Many threads in one processSharing memory cheaply.Each thread needs its own stack. Locks for shared data.One bad thread can corrupt shared memory or leak shared descriptors.
Many processesIsolation. A crash stays in one process.More memory. Sharing data needs sockets, pipes or shared memory.Each process has its own limits.
write() without fsync()Fast writes.No Data may be lost on a power cut.Fine for caches and logs you can lose.
fsync() on every commitDurable data.Every commit waits for the device.Check its errors. A new file also needs a directory fsync().
Postgres asynchronous commitMuch faster small transactions.The last few transactions can be lost in a crash.Data loss, but not corruption. 14
Memory limit = heap sizeNothing.OOM kills under load.Leave room for stacks and native memory.
Section 5 of 8

At work: how a senior uses this

  • When a pod restarts, check the last state first. The reason OOMKilled means the container hit its memory limit. The cause can be a limit that is too low, or a memory leak. Trust the reason, not the exit code alone.
  • Set the memory limit above the heap. Measure total container memory under load, not only heap graphs.
  • Watch memory.events. Rising high or max counts warn you before a kill. Any oom_kill means a process already died.
  • Treat "too many open files" as a leak until proven otherwise. Raising the limit only buys time.
  • Count open descriptors per process in your dashboards, next to memory.
  • Ask "where does this write become durable?" in every design review that stores data.
Section 6 of 8

With AI

What to ask the agent

"Here is our Kubernetes deployment and JVM flags. Estimate total container memory: heap, thread stacks, metaspace and native buffers. Tell me if the memory limit leaves enough room."

"Search this Go service for every place we open a file, socket or HTTP response body. For each, show where it is closed, and list paths where it is not."

"This code writes an order to a file and then replies 'saved'. Explain which crash could lose the order, and show the smallest fix with fsync."

What to check yourself

  • Every memory number the agent gives is labelled heap, stack or native. Totals that add only the heap are wrong.
  • Each close happens on error paths too, for example in defer or finally.
  • The fsync fix checks the return value, and a new file also gets a directory fsync.
Section 7 of 8

Check yourself

1. Your Java service has a 512 MiB heap. Its container has a 512 MiB memory limit. Why can it still be OOM-killed?

Show answer

The limit counts all the memory of the container, such as thread stacks and native buffers, not only the heap. The cgroup counts the memory of every process in it, not only the heap. Each thread has its own stack, and the JVM also uses native memory. The kernel can free page cache, but not these.

2. A service logs "too many open files" (EMFILE). What has it hit?

Show answer

The per-process limit on open file descriptors, RLIMIT_NOFILE. The open(2) man page defines EMFILE as reaching the per-process limit on open file descriptors. A new socket is a file descriptor too.

3. write() returned success. Then the machine lost power. Is the data safe?

Show answer

Not for sure. write() may only have copied the data to the page cache. Calling fsync() makes it wait for the device. The write(2) man page says a successful write gives no guarantee that the data is on disk. fsync() returns only after the device confirms it has stored the data.

4. Two threads in the same process open files. What do they share?

Show answer

Heap memory and the table of open file descriptors. Each thread has its own stack. The pthreads(7) man page lists shared memory, open file descriptors and resource limits, and says each thread has its own stack.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 15 sources and related lessons
  1. Kubernetes documentation, “Assign Memory Resources to Containers and Pods” (opens in a new tab)
    A container that tries to use 250 MiB under a 100 MiB limit is killed with reason OOMKilled, exit code 137, and restarted again and again.
  2. Kubernetes documentation, “About cgroup v2” (opens in a new tab)
    How the kubelet and the container runtime use cgroups to enforce the CPU and memory limits of pods and containers.
  3. Linux kernel documentation, “Control Group v2” (memory controller) (opens in a new tab)
    memory.max, memory.high and memory.events, what the cgroup counts as memory, and when the OOM killer runs inside a cgroup.
  4. Remzi and Andrea Arpaci-Dusseau, Operating Systems: Three Easy Pieces, chapter 6, “Mechanism: Limited Direct Execution” (opens in a new tab)
    User mode and kernel mode, the trap that starts a system call, what a context switch saves, and how long both take.
  5. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, chapter 13, “The Abstraction: Address Spaces” (opens in a new tab)
    Why each process gets its own private address space, and why every address your program prints is virtual.
  6. Linux man-pages, pthreads(7) (opens in a new tab)
    What threads in one process share (memory, open file descriptors, resource limits) and what each thread has alone (its stack).
  7. Linux man-pages, open(2) (opens in a new tab)
    What a file descriptor is, and the EMFILE and ENFILE errors.
  8. Linux man-pages, socket(2) (opens in a new tab)
    A new socket is a file descriptor, so it fails with EMFILE when the limit is reached.
  9. Linux man-pages, errno(3) (opens in a new tab)
    The text for each error code, including EMFILE, "Too many open files".
  10. Linux man-pages, getrlimit(2) (opens in a new tab)
    RLIMIT_NOFILE, soft and hard limits, and how child processes inherit limits.
  11. Linux man-pages, write(2) (opens in a new tab)
    Why a successful write() does not mean the data is on disk, and where late errors show up.
  12. Linux man-pages, fsync(2) (opens in a new tab)
    What fsync() and fdatasync() flush, that they block until the device is done, and why a new file also needs a directory fsync.
  13. Linux man-pages, proc_meminfo(5) (opens in a new tab)
    The fields in /proc/meminfo, including Cached (the page cache), Dirty and MemAvailable.
  14. PostgreSQL documentation, “Asynchronous Commit” (opens in a new tab)
    Why waiting for the WAL flush is a large part of a short transaction, and what you risk when you skip the wait.
  15. Brendan Gregg, “USE Method: Linux Performance Checklist” (opens in a new tab)
    Which Linux command shows each resource, including memory, the OOM killer and file descriptors.

Related: Locks, atomics and deadlocks · Garbage collection and runtime tuning (coming soon) · Kubernetes and runtime platform basics (coming soon) · Mechanical sympathy: CPU caches and memory · I/O models, zero-copy and kernel bypass (coming soon) · Storage engine internals (coming soon)

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper