Strange Leaflet

The BEAM at Work
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9

Page 9 What Node needs to match the BEAM

The busy loop and the ticker one last time, with what it takes to make Node's ticker behave like the BEAM's. A steady interval of your own, a worker thread for the busy loop, and the whole leaflet side by side, the BEAM against what Node needs to match it.

The busy loop and the ticker, one last time. This time it's Node with two fixes: one for its ticks, and one for the busy loop.

The simulation just after the busy loop, four lanes. Node, setInterval, built in: a long shaded stretch with no ticks in it, then one red late tick. Took 1.01 s, and the ticker stopped. One late tick; the rest skipped. Node, a steady interval, a dozen lines of your own: the same stretch, then ten red late ticks at once at its end, marked ×10. Took 0.99 s, and the ticker stopped. Its missed ticks all came at once. Node, a steady interval and the busy loop in a worker, the same lines plus a worker thread of about 9 MB: even ticks through its shaded stretch. Took 1.04 s in the worker, and the ticker kept ticking. BEAM, the busy loop in a process, built in, a process about 2.6 KB: even ticks through a shorter shaded stretch. Took 0.81 s, and the ticker kept ticking.

The live version of this needs JavaScript. In it, you can start the busy loop and watch Node's ticker with setInterval, with a steady interval, and with the busy loop in a worker thread, beside the BEAM's.

Page 1 left Node's tickers with two problems. While the busy loop ran, they couldn't tick at all. And afterwards each was on a new beat, nine ticks behind for good, and every interval that came due during the busy loop was locked to that new beat from then on. Here's what it takes to fix both in Node (fixed.mjs).

A steady interval

The second problem is the smaller job. setInterval counts each tick from when the last one ran. A steady interval counts every tick from the start, and runs the ticks it missed. Here's a ticker every 100 ms each way, with the busy loop still on the main thread:

// Like setInterval, except that tick n is due at start + n * period, and a
// tick that came due while the thread was busy runs late instead of not at all
const steadyInterval = (period, onTick) => {
  const start = performance.now();
  let n = 0;
  let timer;
  const fire = () => {
    while (start + (n + 1) * period <= performance.now()) onTick(++n);
    timer = setTimeout(fire, start + (n + 1) * period - performance.now());
  };
  timer = setTimeout(fire, period);
  return () => clearTimeout(timer);
};
$ node fixed.mjs main
 101 ms  tick 1 (1 due)
 200 ms  tick 2 (2 due)
 300 ms  tick 3 (3 due)
 351 ms  busy loop starts
1346 ms  busy loop ends
1347 ms  tick 4 (13 due)
1347 ms  tick 5 (13 due)
1347 ms  tick 6 (13 due)
1347 ms  tick 7 (13 due)
1347 ms  tick 8 (13 due)
1347 ms  tick 9 (13 due)
1347 ms  tick 10 (13 due)
1347 ms  tick 11 (13 due)
1347 ms  tick 12 (13 due)
1347 ms  tick 13 (13 due)
1401 ms  tick 14 (14 due)
1500 ms  tick 15 (15 due)
1600 ms  tick 16 (16 due)

Still nothing while the busy loop ran, but afterwards every tick that came due, and then back on the beat. That's what the BEAM does when native code holds up its scheduler. It's a dozen lines, and it fixes the locking too. Here are four intervals, each made steady: A, B, and D every 100 ms, starting 0, 40, and 90 ms in, and C every 150 ms, starting 20 ms in, with a short busy loop at 500 ms and a longer one at 1000 ms. With plain setInterval, each busy loop would lock the intervals that came due during it onto one beat:

$ node fixed.mjs intervals
busy loops: 501–588 ms, 1001–1411 ms
A  103 201 302 402 588 601 702 802 901 1411 1411 1411 1411 1411 1503 1602 1702 1802 1902
B  142 241 342 441 589 642 741 841 941 1412 1412 1412 1412 1441 1541 1641 1741 1841 1942
D  191 292 391 491 591 692 792 891 991 1412 1412 1412 1412 1492 1591 1691 1791 1891 1991
C  172 321 472 620 771 920 1412 1412 1412 1521 1670 1820 1971

Each one catches up after each busy loop, then goes back to its own beat: A on the hundreds, B forty past, D ninety past, and C every 150 ms. Nothing locks together.

A worker for the busy loop

The first problem needs another thread. Here's the busy loop moved into a worker thread, which sends its result back as a message:

if (!isMainThread) {
  parentPort.postMessage(fib(workerData));
} else {
  // ...the steady ticker, and at 350 ms:
  new Worker(new URL(import.meta.url), { workerData: 40 }).once("message", done);
}
$ node fixed.mjs worker
 101 ms  tick 1 (1 due)
 200 ms  tick 2 (2 due)
 301 ms  tick 3 (3 due)
 351 ms  busy loop starts
 400 ms  tick 4 (4 due)
 500 ms  tick 5 (5 due)
 600 ms  tick 6 (6 due)
 700 ms  tick 7 (7 due)
 800 ms  tick 8 (8 due)
 900 ms  tick 9 (9 due)
1000 ms  tick 10 (10 due)
1100 ms  tick 11 (11 due)
1200 ms  tick 12 (12 due)
1300 ms  tick 13 (13 due)
1396 ms  busy loop ends
1400 ms  tick 14 (14 due)
1501 ms  tick 15 (15 due)
1600 ms  tick 16 (16 due)
1700 ms  tick 17 (17 due)

Every tick on time.

What it asks of the programmer

So Node can do it: a dozen lines of steady interval, and a worker for the busy loop. What that asks of the programmer is a list of things to get right. Knowing the problem exists. Knowing ahead of time which code is CPU-bound, since only that goes to a worker. And each worker's costs: about 9 MB, an entry point of its own, data copied in and out, and its errors and exits handled by hand. In the BEAM, every process is all of that already.

The whole leaflet, side by side

The ticker is one page's worth. Here's every page's: what the BEAM does, and what it takes to get the same in Node.

The BEAM To match it in Node
Taking turns Preemptive schedulers: a busy loop can't stop a ticker. A worker thread for the CPU-bound code, picked out ahead of time, and a steady interval so missed ticks still run.
Processes A process costs about 2.6 KB and a microsecond to start. A million take about 2.5 GB. A worker is about 9 MB and 6 to 10 ms to start, so there are a few of them, not one per request. Async functions are cheaper, but share one thread.
Garbage collection Every process has its own heap, so a collection pauses only the process that needed it. All the JavaScript in a thread shares one heap, so one job's collection pauses every request. A worker is "a new JS engine instance", with a heap of its own.
Messages A process handles one message at a time, so nothing changes its data halfway through a job. A send copies. A queue in front of any state that's read before an await and changed after it, in every place that does that. postMessage copies too, between threads.
When a process dies A crash stays in its process. Links and monitors tell other processes, and a restarter starts it again. One uncaught error ends the whole program, and something outside it has to restart it. A worker's 'error' and 'exit' events work like a monitor. There's nothing like a link, and restarting is code you write.
Other machines A send to another node looks like a local one, and a monitor says when the node can't be reached. A socket, a way to split the stream into messages, an encoding, a way to match replies to requests, and a timeout or heartbeat of your own.
Changing code while it runs A new version of a module loads into the running system, and processes keep what they hold. A new process, with anything worth keeping stored outside it. Most Elixir teams deploy that way too.

Almost every row can be done in Node. A library can take care of some of them, and a careful team can write the rest. The difference is the default. In Node each row is something to know about, choose, and wire in, one problem at a time. In the BEAM it's how every process already runs, and the costs run the other way: native code that holds a scheduler, one huge heap that's slow to collect, and a mailbox with no limit.

Sources