| @@ -0,0 +1,77 @@ |
| 1 | +# ADR 0028: Mailboxes under contention, and memory per actor |
| 2 | + |
| 3 | +**Status:** Proposed — 2026-10-11 (issue #98); needs engineering review (#44). |
| 4 | + |
| 5 | +## Context |
| 6 | +- ADR 0004 Revision 1 planned lock-free mailboxes and an atomic actor state. Revision 2 chose per-actor locks instead: everything other actors touch (`Proc`: the mailbox, the wait state, links, monitors, the run state) is behind the actor's own `std::sync::Mutex`. It said the choice would be revisited if profiling showed a hot actor's lock. No benchmark had a hot actor: in `tests/bench/messages.lse` (a ring) each actor has one sender. |
| 7 | +- The goal is many cheap actors: 100,000 and more, in close to no memory each. |
| 8 | +- Issue #98 asked for a loom model of the mailbox, and for a measurement of the lock on many threads. The model is in `runtime/louise_rt/src/otp.rs`. It found a bug (an actor killed while it ran could then park for good, fixed in the same change). |
| 9 | + |
| 10 | +## How other runtimes do it |
| 11 | +- **BEAM** splits the queue. Senders append to an outer queue under the receiver's `msgq` lock. The owner moves the whole outer queue into a private inner queue, which selective receive scans without a lock. The split dates from the first multi-threaded emulator (R13): senders never touch what the owner scans. The outer queue stayed locked. OTP 25 measured many senders to one receiver collapsing on that lock, and adds 64 lock-protected buffers to a receiver once its lock is found taken often (per-sender order is kept by hashing the sender), and removes them when contention ends. The run state is one atomic word (`ACTIVE`, `IN_RUNQ`, `MSG_SIG_IN_Q`...): a sender sets a flag and schedules the process if it was inactive. Any message wakes the receiver; the sender does not look at what it waits for. Since OTP 21, links and monitors are signals in the same queue, so a process has no link lock. A process takes 327–338 words (about 2.6 KB) when spawned, its 233-word heap and stack included. |
| 12 | +- **Pony**: a lock-free intrusive MPSC queue per actor (one atomic swap per push). The sender that finds the queue empty schedules the actor. No selective receive; behaviours run on the scheduler thread's stack, so an actor has no stack of its own (about 270 B). |
| 13 | +- **CAF**: one atomic word per inbox, an intrusive LIFO pushed with a CAS. Tag values mark it empty, closed, or with its reader blocked, and the push that replaces "blocked" schedules the reader. The owner takes the whole stack at once into private queues. This is BEAM's split, lock-free, and the CAS lets a closed inbox refuse messages. |
| 14 | +- **Akka**: a lock-free queue and an atomic status word, whose CAS decides which sender schedules the mailbox. **Tokio**: one atomic word per task (`RUNNING`, `NOTIFIED`...); a notification to a running task only sets a bit, and the thread running it queues it again, as `RunState` does. **Go**: channels are locked. |
| 15 | + |
| 16 | +Sources: OTP's `erl_proc_sig_queue.h`/`.c`, `erl_process.h`, `erl_process_lock.h`; the Erlang blog post "Parallel signal sending optimization" (OTP-16982); OTP 21 release notes (OTP-14589); the efficiency guide (processes, memory); ponyc's `messageq.c` and `actor.h`; CAF's `lifo_inbox.hpp`; Akka's `Mailbox.scala`; Tokio's `task/state.rs`; Go's `runtime/chan.go`. |
| 17 | + |
| 18 | +## Measurements |
| 19 | +A release build (clang, mimalloc), a 22-thread laptop shared with other work (load average 2–3), best of 5. Contention is counted with `--features lock-stats` (below), in a separate run. |
| 20 | + |
| 21 | +| Benchmark | Threads: 1 | 2 | 4 | 8 | 22 | Locks found taken | |
| 22 | +|---|---|---|---|---|---|---| |
| 23 | +| `messages` (a ring, 1 sender per actor) | 60 ms | 60 | 60 | 62 | 61 | 0 | |
| 24 | +| `parallel` (64 actors computing) | 1052 ms | 546 | 300 | 172 | 122 | 0 | |
| 25 | +| `fanin` (64 senders, one collector, 1.28M messages) | **112 ms** | 316 | 469 | 479 | **539** | **28–41%** | |
| 26 | +| `idle` (spawn 100k actors that wait) | 1200 ms | 1045 | 1148 | 1186 | 1244 | 0.03% | |
| 27 | + |
| 28 | +**The lock is not the cost of sending, but it collapses under fan-in.** With one sender per receiver, no acquisition in a million found the lock taken. With 64 senders to one actor, a third did, and 22 threads ran 4.8 times slower than one: about 210 ns per message, against 44 on one thread. |
| 29 | + |
| 30 | +To separate the lock from the rest of the scheduler, `runtime/louise_rt/examples/inbox_fanin.rs` pushes 2.56M messages from P threads into one inbox that one thread drains (ns per message, best of 5): |
| 31 | + |
| 32 | +| Producers | Lock per push and per take (today) | Locked outer queue, swapped out whole (BEAM before OTP 25) | Lock-free MPSC (one swap per push) | |
| 33 | +|---|---|---|---| |
| 34 | +| 1 | 124 | 62 | 101 | |
| 35 | +| 2 | 129 | 95 | 61 | |
| 36 | +| 4 | 159 | 126 | 69 | |
| 37 | +| 8 | 164 | 147 | 62 | |
| 38 | +| 21 | 197 | 201 | 66 | |
| 39 | + |
| 40 | +The lock alone accounts for the 200 ns `fanin` reaches. A locked outer queue only helps with few senders; this is what OTP 25 had to fix. A lock-free inbox stays flat, about 3 times cheaper than a lock from 8 senders. One consumer still bounds the throughput: no design makes fan-in faster on 22 threads than on one. |
| 41 | + |
| 42 | +**Memory per idle actor** (`idle.lse`, 100,000 against 1,000 actors, sampled while they wait): |
| 43 | + |
| 44 | +| | Per actor | |
| 45 | +|---|---| |
| 46 | +| Resident memory | 5.2 KiB | |
| 47 | +| Page tables (not counted as resident) | 4.3 KiB | |
| 48 | +| Memory mappings | 2 | |
| 49 | + |
| 50 | +That is about 9.5 KiB per actor, 0.95 GB for 100,000, against about 2.6 KB per BEAM process. The mailbox's share is a few words: the mutex is 8 bytes, an empty map allocates nothing, and a lock-free inbox would take 8 to 16 bytes. **Stacks dominate.** Each compiled actor reserves 64 MiB (`PROGRAM_STACK_SIZE`, committed lazily) above a guard page: at least one touched 4 KiB page, a page-table page of its own (each reservation spans its own 2 MiB regions), and two mappings, since the guard page splits it. `idle` takes about 12 µs per actor, from its spawn to its unwinding at exit (not profiled: perf was not available). |
| 51 | + |
| 52 | +## Decision |
| 53 | +1. **Keep the per-actor lock for links, monitors and exits.** They are rare, and their ordering with exits is simplest under one lock. |
| 54 | +2. **Replace the mailbox's lock by a lock-free inbox with an owner-private mailbox (proposed, to implement and measure):** |
| 55 | + - The inbox is one atomic word, CAF's design: an intrusive LIFO of message nodes, pushed with a CAS, with tag values for "empty", "closed" (the actor exited: a push fails and the message goes back to its sender, as now) and "owner waiting". |
| 56 | + - The push that replaces "owner waiting" schedules the actor. This replaces the sender's look at `waiting_tags` and `RunState.queued` for messages. |
| 57 | + - The owner takes the whole list with one swap, reverses it (push order), and files it into the tag map it already has (`Mailbox`), which only it touches. Arrival numbers are assigned then. Per-sender order is kept. |
| 58 | + - Before parking, the owner swaps "empty" for "owner waiting"; if the swap fails, messages arrived and it files them first. That swap happens on the scheduler side, after the fiber is suspended (as `RunState::stop` does today), so no thread resumes a fiber still on its way out. |
| 59 | + - A message on a tag the owner does not wait for wakes it, as in BEAM; it files the message and parks again. |
| 60 | + - Timers and kills wake a waiting owner the same way, by pushing a signal node: a timeout carries its wait number, so the owner drops a stale one, as `Proc::time_out` does now. A kill still sets the kill flag and marks the actor exited under its lock first. |
| 61 | +3. **Make memory per actor its own work, with a budget of 2 KiB per idle actor** (issue to be opened). The candidates are smaller, packed stack reservations, which share page tables; giving back the pages of parked and pooled stacks; and moving an idle actor's stack out of its own mapping. Each changes how deep a compiled actor can recurse, which ADR 0004 matched to the interpreter, and needs its own ADR. |
| 62 | + |
| 63 | +`--features lock-stats` (off by default) counts, per scheduler thread, actor-lock acquisitions and those that found the lock taken, and prints them at exit with `LOUISE_LEAKS`. It is how the contention above was measured, and how the change in point 2 is checked. |
| 64 | + |
| 65 | +## Consequences |
| 66 | +- Until point 2 is implemented, an actor many others send to (a logger, a registry, a shared cache) serialises them, and gets slower with more threads. |
| 67 | +- Point 2's targets: `fanin` on 22 threads within 2 times its time on one thread (4.8 times today); `messages` and `parallel` within 5% of their times now; no more memory per idle actor. The loom models in `otp.rs` are rewritten for the inbox first: they already cover sends racing receives, timeouts and kills. |
| 68 | +- Each message costs a node (about 24 bytes) until it is filed, against a slot in the tag map today. |
| 69 | +- Senders no longer read what the receiver waits for, so a selective receive can wake for nothing. The cost is a wake-up per message the receiver does not want at that moment, such as requests arriving while a server waits for a reply. Measured with the change. |
| 70 | +- The models' first finding, an actor killed while it ran parking for good, is fixed. `Proc::park_as` leaves an exited actor ready, except in a blocking call, so it is queued again and unwinds. |
| 71 | + |
| 72 | +## Alternatives rejected |
| 73 | +- **Keep the lock for messages too.** It costs nothing with one sender per receiver, the common case, but it collapses under fan-in, which OTP designs produce on purpose (a server many clients call). |
| 74 | +- **BEAM's split with a locked outer queue.** The microbenchmark matches what OTP 25 measured: with 16 senders or more, it is no better than one lock. |
| 75 | +- **BEAM's OTP 25 buffers, added under contention.** They make a locked queue scale, at the price of 64 buffers per contended actor and a protocol to install and remove them. A lock-free inbox scales without them, and they could still be added later if one inbox line becomes the bottleneck. |
| 76 | +- **Vyukov's MPSC queue (Pony's).** One swap per push, cheaper than a CAS loop under contention, but a push cannot fail, so an exited actor cannot refuse messages. They would need another way to reach their sender for freeing. |
| 77 | +- **Links and monitors as signals in the inbox (OTP 21).** It would remove the last lock, but exits, links and monitors would have to be argued again in terms of signal order. They are rare enough that their lock is not where the time goes. |