Use MPSC global injection queues, NUMA-local victim preference, and epoll/io_uring parking when all queues are empty.
TL;DR30-second simplified summary▾
Designing an async task runtime (like Tokio, Go's runtime, or Seastar) capable of multiplexing 500,000 concurrent connections and 2M task wakeups/sec across 64 CPU cores requires sub-microsecond local scheduling, zero lock contention, and strict protection against noisy tasks.
The runtime spawns one OS worker thread per core, each owning a 1-slot LIFO Fast-Path plus a 256-slot Chase-Lev Work-Stealing Deque (padded to 64-byte cache lines). External wakeups and local queue overflows land in a sharded Global Injection Queue, which workers poll every 61 ticks for fairness. Idle cores run a randomized XorShift half-batch steal loop capped at cores / 2 searching threads before parking on an epoll/io_uring reactor.
To prevent a single CPU-bound or blocking task from freezing other coroutines, every task poll runs under a 128-poll cooperative budget, synchronous disk/FFI work is isolated onto a dedicated spawn_blocking pool, and >1 ms poll durations trigger immediate runtime telemetry alerts.
Sizing 64 Cores, 500K Tasks & Sub-Microsecond Wakeups.
Why this matters: Define 64-core worker sizing, 2M wakeups/sec throughput, and <500 ns local dispatch budgets.
Target 64 CPU cores handling 500K concurrent async tasks and 2M task wakeups/sec with <500 ns local schedule latency.
Each of the 64 workers allocates a 256-slot pointer ring (~2 KB) plus a 1-slot LIFO fast-slot—keeping hot scheduler state inside L1 cache.
Sizing 64 Cores, 500K Tasks & Sub-Microsecond Wakeups
1.1 Thread Per Core: Matching worker threads to physical cores avoids OS kernel context-switch overhead.
2.Compact Task Header: Intrusive task nodes (64-128B) avoid extra heap allocations on enqueue.
3.Sub-Microsecond Path: Local LIFO fast-slot dispatch bypasses even atomic top/bottom reads.
64 core-pinned workers with 2 KB L1-resident Chase-Lev deques sustain 2M wakeups/sec at <500 ns.
LIFO Fast-Slot + 256-Slot Deque + Global Queue + epoll/io_uring.
Why this matters: Wire the 3-tier task pickup order (Global/61 -> LIFO Slot -> Local Deque -> Half-Steal -> Park) with the I/O reactor.
Each worker loop follows a strict priority order: check Global Injection Queue every 61 ticks, pop LIFO slot, pop Local Deque, else steal half from a random peer.
When all queues are empty, the worker parks on the epoll / io_uring I/O Reactor (or a futex) until a socket becomes readable or a new task wakes it.
LIFO Fast-Slot + 256-Slot Deque + Global Queue + epoll/io_uring
1.LIFO Slot Caveat: Bound consecutive LIFO-slot hops (or count against the 61-tick counter) so two chatty tasks can't starve the deque.
2.I/O Driver Integration: One worker polls epoll/io_uring non-blocking on each tick or when no CPU work remains.
3.External Spawns: Non-worker threads push into the sharded Global Injection Queue and unpark 1 idle worker.
A 4-tier pickup hierarchy balances 20 ns LIFO locality, 61-tick global fairness, and zero-spin epoll parking.
61-Tick Fairness Loop & Half-Batch Steal Scheduler.
Why this matters: Implement the worker event loop with 61-tick global polling, randomized half-steal, and budget-capped task execution.
Ensure every worker advances its monotonic tick counter cleanly and never drops tasks during steal or overflow.
class WorkerScheduler:
def __init__(self, wid: int, peers: list, global_q, rng) -> None:
self.wid = wid
self.peers = peers
self.global_q = global_q
self.rng = rng
self.tick = 0
self.lifo_slot = None
def next_task(self):
self.tick += 1
if self.tick % 61 == 0:
t = self.global_q.try_pop()
if t is not None:
return t
if self.lifo_slot is not None:
t, self.lifo_slot = self.lifo_slot, None
return t
t = self.peers[self.wid].pop_bottom()
if t is not None:
return t
return self._try_steal_half() or self.global_q.try_pop()61-Tick Fairness Loop & Half-Batch Steal Scheduler
1.Zero Lost Wakeups: Falling back to global_q after _try_steal_half() guarantees external tasks are picked up before parking.
2.Atomic LIFO Swap: Clearing lifo_slot before polling prevents re-entrancy loops.
3.Randomized Peer Order: Start victim scan at a random offset to avoid core-0 steal storms.
Combining 61-tick global checks, LIFO fast-slots, and steal-then-global fallbacks guarantees progress and low latency.
64-Byte Cache-Line Padding, NUMA Affinity & Sharded Global Queues.
Why this matters: Eliminate false sharing on top/bottom indices and scale global injection queues across 64 cores.
If top and bottom sit in the same 64-byte cache line, every owner push invalidates a thief's read of top (false sharing).
Align top and bottom to separate 64-byte cache lines (alignas(64)). For 64+ cores, shard the Global Injection Queue across NUMA nodes or use a lock-free MPSC queue so external spawns don't contend on one mutex.
64-Byte Cache-Line Padding, NUMA Affinity & Sharded Global Queues
1.False-Sharing Fix: 64-byte padding can boost multi-core work-stealing throughput by 2-3x under heavy stealing.
2.NUMA-Aware Victims: Stealing from same-socket cores first preserves L3 cache locality.
3.MPSC Global Queue: Lock-free intrusive MPSC queues let I/O threads inject thousands of woken tasks without mutex stalls.
64-byte index padding, NUMA-first stealing, and MPSC global queues keep scaling linear up to 64+ cores.
128-Poll Cooperative Budgets & Blocking-Pool Isolation.
Why this matters: Stop tight async loops and accidental synchronous I/O from starving sibling tasks on the same worker core.
An async task reading from a perpetually ready socket (while stream.ready()) can monopolize a worker core indefinitely.
Assign each task poll slice a 128-operation cooperative budget: once exhausted, Pending is returned and the task re-queues at the back. Route blocking syscalls (fsync, bcrypt, DNS) to a separate spawn_blocking thread pool.
128-Poll Cooperative Budgets & Blocking-Pool Isolation
1.Cooperative Preemption: 128-poll budgets guarantee one noisy socket never starves 10,000 other connections on that core.
2.Dedicated Blocking Pool: Keep bounded blocking thread pools (e.g., max 512 threads) separate from the 64 async workers.
3.Sysmon Handoff: Detaching stalled worker queues prevents FFI/disk stalls from freezing queued coroutines.
128-poll cooperative budgets, spawn_blocking pools, and sysmon queue handoffs isolate noisy and blocking tasks.
Panic Isolation, Cancellation Propagation & Graceful Runtime Drain.
Why this matters: Catch task panics without crashing the worker thread and drain in-flight tasks cleanly on SIGTERM.
An unhandled panic inside one task must not kill the worker thread and orphan 8,000 other tasks.
Wrap every task.poll() in catch_unwind (recording the error on the task's JoinHandle), and propagate structured cancellation tokens so dropped futures release sockets and locks immediately.
Panic Isolation, Cancellation Propagation & Graceful Runtime Drain
1.Worker Thread Survival: Task panics fail only that task's JoinHandle, keeping the worker core and its deque alive.
2.Structured Cancellation: Dropping cancelled futures runs RAII destructors to close file descriptors and release semaphores.
3.Bounded Shutdown: Force-drop stalled background tasks after shutdown_timeout so deploys never hang.
catch_unwind panic boundaries and structured cancellation keep worker threads alive and shutdowns bounded.
Tracking Poll Latency Histograms, Steal Counts & Searching Spikes.
Why this matters: Detect accidental blocking inside async tasks, excessive steal thrashing, and global queue backlogs.
The #1 production issue in async runtimes is someone accidentally calling a blocking mutex or requests.get() on a worker thread.
Export runtime_task_poll_duration_us (p99), runtime_steal_success_total, runtime_budget_forced_yield_total, and runtime_global_queue_depth.
Tracking Poll Latency Histograms, Steal Counts & Searching Spikes
1.2 ms Slow-Poll Canary: Healthy async polls finish in <50 us; >2 ms polls almost always mean accidental blocking I/O.
2.Forced-Yield Spike: Rising 128-poll budget yields flag CPU-bound loops that belong on a compute pool.
3.Global Queue Alert: Alert if global_queue_depth grows monotonically while worker CPU is <50%.
Slow-poll >2 ms stack sampling and forced-yield counters surface hidden blocking bugs before tail latency degrades.
Practice: Make the trade-off yourself.
On a 64-core server, 63 idle workers wake up and race to steal tasks from Worker 0's Chase-Lev deque. What two optimizations eliminate this steal storm?