Yousef AldabbasSystems & backend engineering
● ENGINEERING NOTESAMMAN, JORDAN
← back to posts

io_uring Explained: Two Ring Buffers, No Callbacks

2026-10-07 · kernel, typescript

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.

TL;DR io_uring is two queues in memory shared between your program and the kernel. You push requests into one, the kernel pushes results into the other. Nobody calls anybody.

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:

  1. Blocking: read() puts your thread to sleep until the data is there. Simple, but the thread does nothing meanwhile.
  2. Readiness (epoll): the kernel says "this fd is ready, now you call read()". It doesn't really work for regular disk files, which always look ready.
  3. Completion (io_uring): you hand over the whole job, the kernel does it, and later you collect the finished result.

The big picture

USER SPACE KERNEL SPACE your app 1. write SQE 4. read CQE SQ ring submission queue CQ ring completion queue 2. kernel starts I/O disk / NVMe (DMA) 3. kernel posts CQE both rings live in memory mapped (mmap) into both sides, so no copying
The whole flow. Green arrows: you and the kernel passing entries through the rings. Orange: the kernel talking to hardware.

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.

your app builds SQEs reaps CQEs kernel runs the I/O posts results SQ ring app = producer app moves tail · kernel moves head push pop CQ ring kernel moves tail · app moves head push pop kernel = producer
Same ring mechanics twice, with the roles swapped. Whoever produces owns the tail, whoever consumes owns the head.

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:

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.

1. Your app savesits private map
1 → read a.txt 2 → read b.txt 3 → recv from socket
2. Your app submitsinto the SQ
1 2 3 only tags go in, no job info
3. Kernel finishesand posts to the CQ
3 1 2 any order, only tags come back
4. Your app looks upeach tag in its map
3 → recv from socket 1 → read a.txt 2 → read b.txt
Read top to bottom. The colors follow one request. The kernel only ever sees the number; the meaning stays in your app.

The full life of one request, in order:

  1. Save the job in your map under a tag, say 7.
  2. Submit an SQE with user_data = 7.
  3. The kernel does the I/O and posts a CQE with user_data = 7 copied in.
  4. Reap the CQE, meaning take it off the CQ and advance the head so the slot can be reused.
  5. Look up 7 in 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.

SQ you produce, kernel consumes
in flight at the disk
CQ kernel produces, you consume
Press "submit read" to start.

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:

  1. 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.
  2. At setup, it adds the io_uring ring's file descriptor to that watch list, asking only for "readable" (POLLIN), meaning completions.
  3. When a file operation finishes, the ring's handle becomes readable and epoll_pwait wakes.
  4. 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_SQPOLL is set and the UV_USE_IO_URING environment 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.

blocking read() thread asleep, can't do anything io_uring submit 3 your app does other work reap 3 disk A disk B disk C three reads in flight at once, finished in any order
Blocking wastes the thread. io_uring lets one thread keep many reads in flight.

epoll vs io_uring in one table

epollio_uring
Kernel tells you"fd is ready, now call read()""read is done, data is in your buffer"
Syscalls per operation2 or more0 to 1, and batched
Regular disk filesDon't really workWork

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