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 2 Processes

What a BEAM process is (not an operating system process), what one costs, and how the schedulers share thousands of them out

Page 1 had two processes, a ticker and a busy loop. Real Elixir programs run thousands. Cowboy, a web server Erlang and Elixir apps use, starts a process for every connection and another for every request. That only works if a process costs next to nothing. This page is about how little, and why.

Here are three tickers and a busy loop, with a crowd of connections waiting alongside them, held three ways: a BEAM process each, a Node async function each, and a Node worker thread each. Pick how many, then add a busy loop.

The simulation with 100 connections, just after the busy loop. BEAM, a process each: 270 KB of this M1's 8 GB, a sliver of the bar, and its three tickers' strips kept their even ticks right through the shaded stretch where the busy loop ran. The tickers kept ticking through the busy loop. Node, an async function each: 66 KB, but its three strips have a gap where the busy loop ran, then one late tick each in red. The tickers stopped while the busy loop ran. Node, a worker thread each: 960 MB, an eighth of the bar, and its strips kept ticking through the busy loop.

The live version of this needs JavaScript. In it, you can pick from 10 to a million connections, add a busy loop, and watch what each way of holding them costs and does.

Only the BEAM manages both. Node's async functions are cheaper than BEAM processes, but they share one thread, so the busy loop stops every ticker. A worker thread each keeps the tickers going, but at about 9 MB a worker they are exceedingly expensive to run. A million BEAM processes take about 2.5 GB, and none of them can hold up the rest. The rest of this page is about what a BEAM process is, what it costs, and where the BEAM runs it.

Not that kind of process

First, the word. To most programmers a process is what ps or Activity Monitor lists: a running program with its own process id, its own memory that the operating system keeps other programs out of, and the operating system deciding when it gets a core.

A BEAM process isn't one of those. The whole BEAM runs on one operating system process. Its schedulers are threads inside that process, one per logical processor. BEAM processes live entirely inside the BEAM.

This script starts 100,000 BEAM processes and asks the operating system what changed:

# Start 100,000 BEAM processes and ask the operating system what changed.
os_pid = System.pid()

threads = fn ->
  {out, 0} = System.cmd("ps", ["-M", "-p", os_pid])
  length(String.split(out, "\n", trim: true)) - 1
end

children = fn ->
  {out, 0} = System.cmd("ps", ["-ax", "-o", "ppid=,pid=,comm="])
  for line <- String.split(out, "\n", trim: true),
      [ppid, pid, comm] = String.split(line, " ", trim: true, parts: 3),
      ppid == os_pid,
      comm != "ps",
      do: "#{pid} #{Path.basename(comm)}"
end

report = fn label ->
  IO.puts(label)
  IO.puts("  BEAM processes:      #{length(Process.list())}")
  IO.puts("  OS process id:       #{os_pid}")
  IO.puts("  its OS threads:      #{threads.()}")
  IO.puts("  its OS children:     #{Enum.join(children.(), ", ")}")
end

report.("before")
pids = for _ <- 1..100_000, do: spawn(fn -> receive do: (:stop -> :ok) end)
report.("after spawning 100,000")
Enum.each(pids, &send(&1, :stop))
$ elixir os-view.exs
before
  BEAM processes:      59
  OS process id:       77690
  its OS threads:      32
  its OS children:     77703 erl_child_setup
after spawning 100,000
  BEAM processes:      100059
  OS process id:       77690
  its OS threads:      32
  its OS children:     77703 erl_child_setup

A hundred thousand new processes, and the operating system saw nothing new. Same process id, same 32 threads, same one child.

The 59 processes before we started are from the BEAM and from Elixir: the code server, the logger, the processes that read the keyboard and write to the terminal. They're ordinary BEAM processes too. (Process.registered() lists the ones with names, like :code_server, :logger, and :user_drv_reader.)

The 32 threads are the 8 schedulers, plus 8 dirty CPU schedulers and 10 dirty I/O schedulers, plus a few helpers. Dirty schedulers run work that can't be counted in reductions, like long calls into native code. The one child, erl_child_setup, is a small program the BEAM starts when it boots. Whenever Elixir runs an outside program, like the ps calls in this script, erl_child_setup is the one that launches it.

So there are two layers of scheduling. The operating system decides which cores the BEAM's scheduler threads run on, and each scheduler decides which BEAM process runs on it. The operating system only ever sees the threads.

So why call them processes?

Because they act like operating system processes in the ways that matter for writing programs. The BEAM Book puts it this way: "Conceptually, Erlang processes are similar to most OS processes". Then: "In practice, there is a huge difference in that Erlang processes are much more lightweight than most OS processes."

Operating system process BEAM process
Has an id 77690 #PID<0.115.0>
Its own memory yes yes, its own heap and stack
What keeps others out the operating system: it maps out what each process may touch, and the CPU checks every memory access against that map the BEAM: none of its instructions can reach another process's memory, so no language that runs on it can either
Talks to others by pipes, sockets, signals messages
Who decides when it runs the operating system, preemptively a BEAM scheduler, preemptively
When it crashes it ends, and its parent process can find out it ends, and processes watching it are notified
Cost to start, on my M1 about 1.4 ms and 830 KB about 1 µs and 2.6 KB

BEAM processes aren't threads either. The book again: "Erlang processes are not like threads — they have no shared memory to modify, they can only communicate via messages". Threads in most languages share their memory with each other, so any thread can change data another thread is using. Data sent from one BEAM process to another is copied, so neither can change what the other is using.

That's what makes preemption safe in the BEAM. In languages like Java or C++, threads get preempted too, and a thread paused halfway through changing shared data leaves it half-changed which could break other threads. That's why threads that share memory need locks. But when a BEAM process runs out of reductions any of its half-changed work is only its own data that no other process can manipulate or even see. The BEAM scheduler can safely pause any process at any function call.

How cheap is cheap?

Here's a script spawning N processes that each sit waiting for a message:

# Spawn N processes that each wait for a message, then measure.
n = String.to_integer(List.first(System.argv()) || "100000")

:erlang.garbage_collect()
memory_before = :erlang.memory(:processes)
start = System.monotonic_time(:microsecond)

pids = for _ <- 1..n, do: spawn(fn -> receive do: (:stop -> :ok) end)

microseconds = System.monotonic_time(:microsecond) - start
bytes = :erlang.memory(:processes) - memory_before

IO.puts("#{n} processes: " <>
        "#{:erlang.float_to_binary(microseconds / n, decimals: 2)} µs each to spawn, " <>
        "#{round(bytes / n)} bytes each, " <>
        "#{:erlang.float_to_binary(bytes / 1_048_576, decimals: 1)} MB in all")

Enum.each(pids, &send(&1, :stop))
$ for n in 1000 10000 100000 1000000; do elixir spawn.exs $n; done
1000 processes: 0.46 µs each to spawn, 2764 bytes each, 2.6 MB in all
10000 processes: 0.59 µs each to spawn, 2674 bytes each, 25.5 MB in all
100000 processes: 0.62 µs each to spawn, 2650 bytes each, 252.7 MB in all
1000000 processes: 0.97 µs each to spawn, 2641 bytes each, 2518.2 MB in all

A million processes in under a second, in about 2.5 GB. The BEAM's default limit is 1,048,576 processes, so a million just fits. (You can raise the limit with the +P flag.)

A brand-new process is 2,616 bytes: 327 words of 8 bytes, which is what the Erlang efficiency guide says to expect. 233 of those words are its heap, where its data lives. The rest is the BEAM's own record of the process. The heap starts small on purpose, so a system can hold millions of processes, and grows when a process needs more. So 2.6 KB is the floor. A process that's holding real data is bigger.

Here's what 2.6 KB looks like next to an operating system process. The top bar is an idle sleep command process, broken down by vmmap, the macOS tool that lists a process's memory. It counts only memory the process has written to, which is its own; the code of the libraries it loads is shared with every other program, so it's left out. The bottom bar is a new BEAM process, from :erlang.process_info/2. Both are drawn to the same scale.

The scale bar: an idle operating system process (sleep) of 834 KB, split into its stack (32 KB), heap (288 KB), libraries' data (289 KB), the kernel's page tables (161 KB), and other (64 KB), drawn the full width. Below it, a new BEAM process of 2,616 bytes is a sliver at the same scale: its memory would hold 326 of them.

The live version of this needs JavaScript. In it, you can zoom in until the BEAM process fills the width, and pick a part to read what it is.

And in Node?

What's the closest thing in Node? It depends which part of a BEAM process you want.

If you want something that runs on its own and can't be held up by a busy loop elsewhere, that's a worker thread. Worker threads are real threads, scheduled preemptively by the operating system. They're not cheap. Here's a script that starts 8 idle ones and waits until each is up (worker-cost.mjs):

// What does an idle worker thread cost? Start N, wait until each is up, measure.
import { Worker, isMainThread, parentPort } from "node:worker_threads";
if (isMainThread) {
  const n = Number(process.argv[2] ?? 8);
  global.gc?.();
  const before = process.memoryUsage().rss;
  const t0 = performance.now();
  const ws = [];
  await Promise.all(Array.from({ length: n }, () => new Promise((resolve) => {
    const w = new Worker(new URL(import.meta.url));
    w.once("message", resolve);
    ws.push(w);
  })));
  const ms = performance.now() - t0;
  const mb = (process.memoryUsage().rss - before) / 1024 / 1024;
  console.log(`${n} idle workers: ${(mb / n).toFixed(1)} MB of RSS each (${mb.toFixed(1)} MB in all), ${(ms / n).toFixed(1)} ms each to start (${ms.toFixed(0)} ms total)`);
  ws.forEach((w) => w.terminate());
} else {
  parentPort.postMessage("up");
  setInterval(() => {}, 1 << 30);
}
$ for i in 1 2 3; do node --expose-gc worker-cost.mjs; done
8 idle workers: 9.6 MB of RSS each (76.7 MB in all), 10.0 ms each to start (80 ms total)
8 idle workers: 9.3 MB of RSS each (74.1 MB in all), 6.5 ms each to start (52 ms total)
8 idle workers: 9.2 MB of RSS each (73.9 MB in all), 6.4 ms each to start (51 ms total)

Each one took 6 to 10 ms to start, and each took about 9.5 MB of memory.

That's eight. Start a few hundred and RSS stops being a good measure on this M1, which has 8 GB: at 500 it said 1.5 to 2.9 MB each. RSS, the resident set size, counts only what's in memory at that moment, and by then the workers' memory wasn't all there; macOS had swapped some of it out. vmmap's physical footprint counts what the process has written to, whether it's resident or not. Here's the same script, measuring that instead (worker-footprint.mjs):

// vmmap's "Physical footprint" for this whole process, in MB
const footprint = () => {
  const out = execFileSync("vmmap", ["-summary", String(process.pid)], { encoding: "utf8", maxBuffer: 1 << 26 });
  const line = out.split("\n").find((l) => l.startsWith("Physical footprint:"));
  const [, n, unit] = line.match(/([\d.]+)([KMG])/);
  return Number(n) * { K: 1 / 1024, M: 1, G: 1024 }[unit];
};
// ...then as in worker-cost.mjs: footprint() before, start N workers, footprint() after
$ for n in 8 100 300 500; do node --expose-gc worker-footprint.mjs $n; done
8 idle workers: 10.1 MB of physical footprint each (0.09 GB in all), 9.7 MB of RSS each
100 idle workers: 9.6 MB of physical footprint each (0.95 GB in all), 9.0 MB of RSS each
300 idle workers: 9.2 MB of physical footprint each (2.70 GB in all), 8.5 MB of RSS each
500 idle workers: 9.0 MB of physical footprint each (4.40 GB in all), 1.5 MB of RSS each

About 9 MB a worker, however many: 500 idle workers took 4.4 GB, more than half of this machine. A thousand would take more than all of it. (I stopped at 500.)

If you want something that waits cheaply for a message, that's an async function paused on a promise. It's the shape a Node server's request handlers take while they wait on a database or the network. And it's cheaper than a BEAM process. Here's the spawn script above, done in Node with N async functions that each wait on a promise (pending.mjs):

// Node's cheapest unit of waiting: N async functions, each paused on a promise
// that a later "message" would resolve. Measure time and V8 heap per one.
const n = Number(process.argv[2] ?? 100000);
const wake = [];
const waiter = async () => { await new Promise((resolve) => wake.push(resolve)); };

global.gc();
const heap0 = process.memoryUsage().heapUsed;
const t0 = performance.now();
const tasks = [];
for (let i = 0; i < n; i++) tasks.push(waiter());
const us = (performance.now() - t0) * 1000;
global.gc();
const heap = process.memoryUsage().heapUsed - heap0;
console.log(`${n} pending async functions: ${(us / n).toFixed(2)} µs each to start, ${Math.round(heap / n)} bytes each of V8 heap`);
wake.forEach((resolve) => resolve());
await Promise.all(tasks);
$ for n in 1000 10000 100000 1000000; do node --expose-gc pending.mjs $n; done
1000 pending async functions: 0.28 µs each to start, 675 bytes each of V8 heap
10000 pending async functions: 0.42 µs each to start, 571 bytes each of V8 heap
100000 pending async functions: 0.65 µs each to start, 563 bytes each of V8 heap
1000000 pending async functions: 0.50 µs each to start, 565 bytes each of V8 heap

About as fast to start, and a fifth of the memory. But a paused async function isn't a process. They all share one thread and one heap, and when one of them wakes up it runs until it pauses again or returns, however long that takes. That's how one busy loop stops every ticker. A BEAM process costs a few hundred bytes more and gets its own heap, its own turn in a run queue, preemptive scheduling, and crash isolation.

Where a new BEAM process runs

When a BEAM process spawns another, the new one goes on the back of the run queue of the scheduler its parent is running on. So a BEAM process that spawns sixteen more puts all sixteen in one line.

The BEAM evens that out in two ways. A scheduler with an empty run queue can pick up a process from another scheduler's queue. The other is migration. Every 8 million reductions or so (2,000 turns' worth), the schedulers compare their run queue lengths. Schedulers with longer queues than average hand processes over to ones with shorter queues.

Here's a parent spawning sixteen busy processes (spread.exs). It counts the processes waiting in each scheduler's run queue just before and just after spawning, and again half a second later. Each new process reports which scheduler it first ran on, then spins for a second:

defmodule Busy do
  def spin(until) do
    if System.monotonic_time(:millisecond) < until, do: spin(until), else: :ok
  end
end

row = fn numbers -> Enum.map_join(numbers, " ", &String.pad_leading("#{&1}", 2)) end
per_scheduler = fn what -> Enum.take(:erlang.statistics(what), System.schedulers_online()) end

me = self()
IO.puts("parent is on scheduler #{:erlang.system_info(:scheduler_id)}")
before = per_scheduler.(:run_queue_lengths)

for i <- 1..16 do
  spawn(fn ->
    send(me, {i, :erlang.system_info(:scheduler_id)})
    Busy.spin(System.monotonic_time(:millisecond) + 1000)
  end)
end

just_after = per_scheduler.(:run_queue_lengths)
Process.sleep(500)
later = per_scheduler.(:active_tasks)
first = for _ <- 1..16, do: (receive do: ({i, s} -> {i, s}))

IO.puts("")
IO.puts("scheduler:              " <> row.(1..System.schedulers_online()))
IO.puts("waiting before:         " <> row.(before))
IO.puts("waiting after spawning: " <> row.(just_after))
IO.puts("half a second later:    " <> row.(later) <> "  (running or waiting)")
IO.puts("")
IO.puts("process:       " <> row.(Enum.map(Enum.sort(first), &elem(&1, 0))))
IO.puts("first ran on:  " <> row.(Enum.map(Enum.sort(first), &elem(&1, 1))))
$ elixir spread.exs
parent is on scheduler 1

scheduler:               1  2  3  4  5  6  7  8
waiting before:          1  0  0  0  0  0  0  0
waiting after spawning: 17  0  0  0  0  0  0  0
half a second later:     4  2  2  1  2  2  2  3  (running or waiting)

process:        1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16
first ran on:   1  1  8  7  7  6  5  8  8  8  1  1  1  1  1  1

Right after spawning, all sixteen were waiting in scheduler 1's queue, the parent's. (The seventeenth was already there before.) But schedulers 5 through 8 had nothing to do, so they took eight of them before those had even run once. That's the "first ran on" row: processes 3 to 10 first ran somewhere other than scheduler 1. Half a second later, every scheduler had work. Not perfectly even, but no one had to write any application level code to spread out the work.

A busy process gets no special treatment

Balancing looks at how much is waiting in each run queue, not at what any one process costs. And when there isn't enough work to keep every scheduler busy, it does the opposite of spreading out: it packs the work onto as few schedulers as it can keep fully loaded, so the rest can sleep. The docs call that scheduler compaction of load, and it's on by default.

Here's a CPU-bound busy loop among six tickers that tick every 10 ms (busy-alone.exs). Every tick notes which scheduler it ran on, and so does the busy loop after each chunk of its work:

$ elixir busy-alone.exs
schedulers online: 8

0–200 ms
  ticks on       8: 114
  busy loop on   

200–1000 ms
  ticks on       1: 429  2: 24  3: 1  4: 2  5: 6  6: 6  7: 9  8: 3
  busy loop on   1: 119  2: 314  3: 7  4: 8  5: 8  6: 7  7: 8  8: 1

1000–2000 ms
  ticks on       1: 565  2: 35
  busy loop on   1: 49  2: 567

2000–3000 ms
  ticks on       1: 399  2: 165  3: 36
  busy loop on   1: 391  2: 197  3: 24

Before the busy loop started, all six tickers ran on one scheduler. Once it started, the BEAM settled on two of its eight schedulers, with a few stray turns elsewhere. For a second the busy loop and the tickers happened to split up, one scheduler each, and then they mixed again. In three runs the shape was the same: a couple of schedulers, shared.

Watch the schedulers share them out

Here's the sixteen busy processes from spread.exs as a simulation, slowed way down. Each row is a scheduler: the process it's running, then its run queue.

Press Spawn 16 busy processes. A parent process starts on one scheduler and spawns sixteen children onto that scheduler's queue. Watch the idle schedulers take processes from it, and then migration move a few more, until each scheduler has about the same amount of work. Press it again while the first sixteen are still running and see where the next batch goes.

Then press Spawn 1,000 waiting processes. Each one runs just long enough to reach its receive, then waits for a message. They pass through the run queues on the way and then leave them, because a waiting process isn't in any run queue.

A moment from the simulation, a few turns after a parent spawned sixteen busy processes onto scheduler 1. Scheduler 1 is running P12 with six more in its queue; schedulers 2 and 3 have two each; schedulers 4 to 8 one each. Running or waiting per scheduler: 7 2 2 1 1 1 1 1. The log: schedulers 6, 7, and 8 had nothing to do and took P5, P6, and P7 from scheduler 1, then migration moved P10 to scheduler 2 and P11 to scheduler 3.

The live version of this needs JavaScript. In it, the idle schedulers take processes from scheduler 1's queue, migration evens out the rest, and you can spawn a thousand waiting processes too.

The simulation's migration is simpler than the real one. It checks the loads every three turns instead of every 2,000, and it doesn't keep track of how long each queue got in between, so it evens things out faster and more neatly than the BEAM does. The real spread.exs run ended half a second later with 4 on one scheduler and 1 on another. It also has no compaction: give it light work and the simulation spreads it out, where the real BEAM packs it onto a few schedulers.

Sources