Recipe

Windows IOCP primer

I/O Completion Ports are the canonical Windows path for scalable async I/O. One port multiplexes thousands of sockets onto a small worker pool, the kernel dispatches completions, and your threads stay hot. This recipe walks through the minimum viable shape you need before wiring it into a Meridian transport.

1. Create the port and bind a handle

A single HANDLE returned by CreateIoCompletionPort with INVALID_HANDLE_VALUE is your port. Every socket or file handle then re-uses the same call to associate itself, passing a per-connection completion key the kernel will hand back on every event.

2. Post overlapped operations

Each WSARecv or WSASend takes an OVERLAPPED struct that the kernel owns until the operation completes. Wrap it in a per-op context so you can recover buffer, opcode, and connection identity when the dequeue thread sees it again.

3. Drain completions on a thread pool

Worker threads loop on GetQueuedCompletionStatus(or the Ex variant for batching). Size the pool around NumberOfConcurrentThreads; the kernel will park excess threads automatically when concurrency is satisfied.

HANDLE port = CreateIoCompletionPort(
    INVALID_HANDLE_VALUE, NULL, 0, 0);

CreateIoCompletionPort((HANDLE)sock, port,
    (ULONG_PTR)conn, 0);

WSARecv(sock, &conn->wsabuf, 1, NULL,
    &flags, &conn->op.ov, NULL);

DWORD bytes; ULONG_PTR key; OVERLAPPED* ov;
while (GetQueuedCompletionStatus(
    port, &bytes, &key, &ov, INFINITE)) {
  dispatch((Conn*)key, (Op*)ov, bytes);
}