io_uring Explained: Two Ring Buffers, No Callbacks
I was reading about how an OS knows an I/O task has finished, and asked myself the question most people ask: is it a callback? For io_uring it isn't, and the real answer is simpler than a callback. This post builds the mental model step by step, with the data structures written as TypeScript types so you can read them like code.
The problem: how do I know the read finished?
You ask the kernel to read 4 KB from a file. The disk is slow compared to the CPU, so something has to bridge the gap. There are three classic answers:
- Blocking:
read()puts your thread to sleep until the data is there. Simple, but the thread does nothing meanwhile. - Readiness (
epoll): the kernel says "this fd is ready, now you callread()". It doesn't really work for regular disk files, which always look ready. - Completion (
io_uring): you hand over the whole job, the kernel does it, and later you collect the finished result.
The big picture
The two entries, as TypeScript types
The kernel's real structs are C (struct io_uring_sqe and struct io_uring_cqe). Here they are as TypeScript, trimmed to the fields that matter for a read. This is a mental model, not something you'd actually run in Node.
// What you WRITE into the submission queue
type SQE = {
opcode: "READ" | "WRITE" | "FSYNC" | "ACCEPT" | "RECV" | "SEND" /* ...many more */;
fd: number; // which file / socket
off: bigint; // file offset to read from
addr: bigint; // pointer to YOUR buffer (kernel fills it)
len: number; // how many bytes
flags: number; // e.g. link this request to the next one
user_data: bigint; // YOUR tag, echoed back untouched
};
// What you READ from the completion queue
type CQE = {
user_data: bigint; // same tag you put in the SQE
res: number; // bytes transferred, or -errno on failure
flags: number;
};
user_data is the whole trick for matching. Completions can arrive in a different order than you submitted, so the kernel copies your tag into the result and you look up what it belonged to.
// Your side: remember what each tag means
const pending = new Map<bigint, { path: string; resolve: (n: number) => void }>();
function readCompleted(cqe: CQE) {
const job = pending.get(cqe.user_data);
if (!job) return;
pending.delete(cqe.user_data);
if (cqe.res < 0) throw new Error(`read ${job.path} failed: errno ${-cqe.res}`);
job.resolve(cqe.res); // cqe.res bytes are now in your buffer
}
The ring: head and tail
Each queue is a fixed-size circular array with two counters, a head and a tail. One side only ever moves the tail (producer), the other only ever moves the head (consumer). Because each counter has exactly one writer, there are no locks.
type Ring<T> = {
entries: (T | null)[]; // fixed size, power of two
head: number; // consumer reads here, then advances
tail: number; // producer writes here, then advances
mask: number; // entries.length - 1, so index = counter & mask
};
// SQ: you are the producer, kernel is the consumer
// CQ: kernel is the producer, you are the consumer
function push<T>(r: Ring<T>, item: T): boolean {
if (r.tail - r.head === r.entries.length) return false; // full
r.entries[r.tail & r.mask] = item;
r.tail++; // publish
return true;
}
function pop<T>(r: Ring<T>): T | null {
if (r.head === r.tail) return null; // empty
const item = r.entries[r.head & r.mask];
r.head++;
return item;
}
Counters only ever increase and the & mask wraps them onto the array. That is how "full" and "empty" are told apart without an extra flag. (Real io_uring is a little more indirect: the SQ ring stores indices into a separate SQE array. The idea is the same.)
Producer and consumer: who owns what
There are two rings, and the roles flip between them. On the SQ your app is the producer and the kernel is the consumer. On the CQ it's the other way round. Each ring has exactly one producer and one consumer, so each counter has exactly one writer.
As types:
type Side = "app" | "kernel";
type RingRoles = {
producer: Side; // writes entries, then advances TAIL
consumer: Side; // reads entries, then advances HEAD
};
const SQ: RingRoles = { producer: "app", consumer: "kernel" };
const CQ: RingRoles = { producer: "kernel", consumer: "app" };
// The rule that makes it lock-free:
// each counter has exactly ONE writer, so nobody ever fights over it.
And the two loops your app actually runs, one per ring:
// App as PRODUCER of the SQ
function submit(sq: Ring<SQE>, sqe: SQE, job: Pending) {
pending.set(sqe.user_data, job); // remember what this tag means
if (!push(sq, sqe)) {
// SQ full: the kernel hasn't consumed enough yet. Wait or submit first.
}
}
// App as CONSUMER of the CQ
function reap(cq: Ring<CQE>) {
let cqe: CQE | null;
while ((cqe = pop(cq)) !== null) {
readCompleted(cqe); // look up user_data, run the continuation
}
}
Two details keep this safe without locks:
- Write the entry first, publish the tail second. The producer fills the slot, then advances the tail with a release store. The consumer reads the tail with an acquire load, so it can never see the new tail before the entry's contents. Real code uses memory barriers for this; liburing hides them.
- Full rings. If you don't reap the CQ fast enough, it fills up. Newer kernels hold the extra completions internally and set an overflow flag instead of losing them, but you should still reap promptly.
Who knows what: the tag and the map
This is the part that confuses most people, so here it is plainly. The kernel never knows which job a result belongs to. Your app does, because it keeps a private map from tag to job. The only thing both sides share is the tag.
The full life of one request, in order:
- Save the job in your map under a tag, say
7. - Submit an SQE with
user_data = 7. - The kernel does the I/O and posts a CQE with
user_data = 7copied in. - Reap the CQE, meaning take it off the CQ and advance the head so the slot can be reused.
- Look up
7in your map. Your app, not the kernel, decides which job this is, and runs it.
// Two different steps, both inside your app:
const cqe = pop(cq); // REAP: take the entry off the shared ring
const job = pending.get(cqe.user_data); // LOOKUP: your own private map
job?.onDone(cqe.res); // continue the job
Think of a coat check. The kernel hands back the ticket number and has no idea what is in your coat.
Try it
Play with a tiny simulation. Submit a few reads, let the "disk" finish them (in any order, like real life), then reap the completions.
How you find out it's done
Once the kernel has posted a CQE, your app still has to notice it. You can sleep until it arrives, keep glancing at the CQ, or let an event loop wake you. They differ in how many syscalls (requests from your program to the kernel) you pay and how much CPU you burn.
Optional deep dive: submit modes, wait modes, and what libuv does
Two separate questions get mixed up here, so split them: how requests get submitted and how you notice completions.
Submitting: normal or SQPOLL
type SubmitMode =
| { kind: "enter" } // you call io_uring_enter() to hand the batch to the kernel
| { kind: "sqpoll" }; // a kernel thread watches the SQ, so you never make a syscall to submit
With sqpoll the kernel dedicates a thread that keeps watching your SQ (submission queue). When you push an SQE, that thread picks it up. The price is a CPU core spinning. It sleeps after a quiet spell, and you then wake it with a syscall.
Waiting: three ways to notice a new CQE
type WaitMode =
| { kind: "enter-and-wait"; waitNr: number } // io_uring_enter(): sleep until N CQEs exist
| { kind: "poll-cq-tail" } // read the CQ tail from shared memory, zero syscalls
| { kind: "epoll-wakeup"; ringFd: number }; // put the ring's file descriptor on an epoll watch list
- enter-and-wait: one syscall that sleeps until at least N completions exist. No CPU while waiting, one syscall per wait.
- poll-cq-tail: you never sleep. You check whether the CQ's tail counter moved. That is a plain memory read, so no syscall, but it burns CPU while you spin.
- epoll-wakeup: a file descriptor (the small number the kernel gives you as a handle to a file, socket or ring) can be added to epoll, a Linux feature where you give the kernel a list of things to watch and sleep until any one of them has news. The ring itself has such a handle. When completions arrive it becomes readable and epoll wakes you.
They combine freely. A common pairing is sqpoll to submit plus poll-cq-tail to reap, which means zero syscalls on the hot path.
What libuv does
libuv is the C library underneath Node.js that runs its event loop. Reading its src/unix/linux.c (the v1.x branch at the time of writing), it does not pick one mode. It combines them:
- The loop sleeps in
epoll_pwait(), the call that blocks until something on the watch list is ready. This is the only place it sleeps, and it covers sockets and timers too. - At setup, it adds the io_uring ring's file descriptor to that watch list, asking only for "readable" (
POLLIN), meaning completions. - When a file operation finishes, the ring's handle becomes readable and
epoll_pwaitwakes. - libuv then runs
uv__poll_io_uring. It reads the CQ's head and tail from shared memory, collects every finished entry, moves the head forward to free the slots, and runs each job's callback.
// libuv, in this post's terms
const submit: SubmitMode = { kind: "enter" }; // SQPOLL is off by default
const wait: WaitMode = { kind: "epoll-wakeup", ringFd }; // then it reaps by reading the CQ in memory
Details worth knowing:
- SQPOLL is opt-in. libuv only creates it when the loop flag
UV_LOOP_ENABLE_IO_URING_SQPOLLis set and theUV_USE_IO_URINGenvironment variable is unset or positive. Its own source comment says SQPOLL is "all kinds of buggy", and it refuses it below kernel 5.10.186 because older kernels let the SQPOLL thread use 100% CPU. - Files only. libuv uses io_uring for file operations such as read, write, open, close, fsync, rename and stat. Sockets still go through epoll.
- Check your own version. I read the current branch. The libuv bundled with your Node version may be older and behave differently, and I haven't traced every call in the file.
Then who is the "callback"?
Underneath, the disk finishes via a hardware interrupt, typically from the NVMe controller after it has DMA'd the data into memory. The kernel's interrupt path then writes the CQE. So there is a callback, but it lives inside the kernel. What reaches your program is just a new entry in memory.
epoll vs io_uring in one table
| epoll | io_uring | |
|---|---|---|
| Kernel tells you | "fd is ready, now call read()" | "read is done, data is in your buffer" |
| Syscalls per operation | 2 or more | 0 to 1, and batched |
| Regular disk files | Don't really work | Work |
Conclusion
The takeaway: io_uring swaps "call me when you're ready" for a shared mailbox. You drop requests in one slot, the kernel drops answers in another, and a user_data tag ties them together. The speed comes from batching and from skipping syscalls, not from any magic in the disk.
Caveats worth knowing: it's Linux only (kernel 5.1+), and its security track record has been rocky enough that some container runtimes and Google's infrastructure restrict it. Check your platform before building on it.
References
- Efficient IO with io_uring, Jens Axboe (the original design paper)
- Lord of the io_uring, a beginner-friendly guide
- io_uring Looks Illegal, nubskr (video walkthrough)
- io_uring(7) man page
- LWN: Ringing in a new asynchronous I/O API