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 3 Garbage Collection

Every BEAM process has its own heap and collects its own garbage, so a collection only ever pauses the one process that needed it

Elixir data is immutable: it cannot be changed. Add an item to a list and you get a new list, with the old one still there for anyone still using it. Programs with immutable data make a lot of garbage: old versions of things that nothing uses any more. Something has to find the garbage and take the memory back, and in the BEAM, as in Node, that's a garbage collector.

Garbage collectors in any language have the same problem. To tell what's garbage, they have to look at what the program is using, and that's hard to do while the program keeps changing it. So collectors stop the program, at least for a moment. The interesting question is: stop what, exactly?

Here's a job that gives the collector a lot to do, replayed from real runs in the BEAM and in Node.

The replay 690 ms into both runs, side by side. On the BEAM side the collecting badge is lit: when the builder collects, it's on a dirty CPU scheduler, and the tickers run on. The longest a tick has waited so far is 1 ms. The builder is collecting, and the three tickers are ticking, their strips evenly spaced: 204 ticks so far, 51 of them while the builder was collecting, the worst 1 ms late. On the Node side the collecting badge is lit too: when V8 collects, no JavaScript runs, not even a ticker. The longest a tick has waited so far is 40 ms, and climbing: the builder and all three tickers are paused, and each ticker's strip ends in a red bar for a tick that's still waiting.

The live version of this needs JavaScript. In it, you can play the replay or drag through it, and show each process's heaps.

In Node, every collection stops the tickers, and the ticks they owed come out late in a bunch. In the BEAM, the builder spends much longer collecting, but the tickers don't notice. The difference is what a collection stops. In Node the garbage collector has to stop all of the JavaScript execution. In the BEAM each process has its own individual garbage collector so any garbage collection only needs to stop that individual process.

Each BEAM process has its own heap

Each new BEAM process has a heap of 233 words and its stack lives in the same block. The Erlang docs put it this way: "Each Erlang process has its own stack and heap which are allocated in the same memory block and grow towards each other." The heap fills from one end, with lists, tuples, and everything else the process makes. The stack fills from the other, with the function calls it's in the middle of. "When the stack and the heap meet, the garbage collector is triggered."

The collector copies. It starts from what the process can still reach (its stack, and what that points to), copies all of that into a fresh block, and throws the old block away whole. The garbage is never looked at. That makes a collection cost what the process still uses, not what it threw away. In the docs' words, the algorithm "is proportional to the amount of live data on the heap."

It's also generational, because most data dies young. Data that has survived one collection gets copied to a second block on the next one, the old heap. The usual collection, a minor one, only copies what's new and still in use. Once the old heap is full, a major collection (the docs call it a full sweep) goes through both.

Here's one process doing that. It builds a list a number at a time, and at every step it also makes a short list it never uses again (gc-steps.exs):

defmodule Builder do
  def loop(acc, 0), do: acc
  def loop(acc, n) do
    _garbage = Enum.to_list(1..10)
    loop([n | acc], n - 1)
  end
end

n = String.to_integer(List.first(System.argv()) || "1000")
me = self()
pid = spawn(fn ->
  receive do: (:go -> :ok)
  list = Builder.loop([], n)
  send(me, :done)
  receive do: (:stop -> length(list))
end)
:erlang.trace(pid, true, [:garbage_collection])
send(pid, :go)

# ...then receive the trace messages until :done, pair each collection's
# start with its end, and print a line for each

:erlang.trace/3 sends a message at the start and end of every garbage collection, with the sizes of the heaps. One line per collection:

$ elixir gc-steps.exs 1000
sizes in words of 8 bytes      young heap         old heap
minor   used  220 โ†’  220 of  233   used    0 of    0
major   used  220 โ†’   34 of  233   used    0 of    0
minor   used  216 โ†’   18 of  233   used   18 of  376
minor   used  216 โ†’   18 of  233   used   36 of  376
minor   used  216 โ†’   18 of  233   used   54 of  376
minor   used  216 โ†’   18 of  233   used   72 of  376
minor   used  216 โ†’   18 of  233   used   90 of  376
minor   used  216 โ†’   18 of  233   used  108 of  376
minor   used  216 โ†’   18 of  233   used  126 of  376
minor   used  216 โ†’   18 of  233   used  144 of  376
minor   used  216 โ†’   18 of  233   used  162 of  376
minor   used  216 โ†’   18 of  233   used  180 of  376
minor   used  216 โ†’   18 of  233   used  198 of  376
minor   used  216 โ†’   18 of  233   used  216 of  376
minor   used  216 โ†’   18 of  233   used  234 of  376
minor   used  216 โ†’   18 of  233   used  252 of  376
minor   used  216 โ†’   18 of  233   used  270 of  376
minor   used  216 โ†’   18 of  233   used  288 of  376
minor   used  216 โ†’   18 of  233   used  306 of  376
minor   used  216 โ†’   18 of  233   used  324 of  376
minor   used  216 โ†’   18 of  233   used  342 of  376
minor   used  216 โ†’   18 of  233   used  360 of  376
minor   used  216 โ†’  216 of  233   used  360 of  376
major   used  216 โ†’  396 of  610   used    0 of    0
minor   used  594 โ†’   18 of  610   used  396 of  987
minor   used  598 โ†’   60 of  610   used  414 of  987
minor   used  596 โ†’   64 of  610   used  466 of  987
minor   used  598 โ†’   50 of  610   used  514 of  987
minor   used  600 โ†’   50 of  610   used  564 of  987
minor   used  600 โ†’   50 of  610   used  614 of  987
minor   used  600 โ†’   50 of  610   used  664 of  987
minor   used  600 โ†’   50 of  610   used  714 of  987
minor   used  600 โ†’   50 of  610   used  764 of  987
minor   used  600 โ†’   50 of  610   used  814 of  987
minor   used  600 โ†’   50 of  610   used  864 of  987
minor   used  600 โ†’   50 of  610   used  914 of  987
minor   used  600 โ†’   50 of  610   used  964 of  987
minor   used  600 โ†’  600 of  610   used  964 of  987
major   used  600 โ†’ 1064 of 1598   used    0 of    0
minor   used 1586 โ†’   62 of 1598   used 1064 of 2586
minor   used 1586 โ†’  140 of 1598   used 1110 of 2586
minor   used 1586 โ†’  146 of 1598   used 1250 of 2586
minor   used 1582 โ†’  132 of 1598   used 1380 of 2586
minor   used 1584 โ†’  132 of 1598   used 1512 of 2586
minor   used 1584 โ†’  132 of 1598   used 1644 of 2586
minor   used 1584 โ†’  132 of 1598   used 1776 of 2586

Read it a block at a time. The young heap fills to 216 of its 233 words, and each minor collection keeps only 18: the nine newest numbers in the list, at 2 words each. The rest was the short lists, garbage, and none of it was copied. The 18 words kept last time move to the old heap, which climbs 18 words per collection. When the old heap can't take the next 18, the minor collection gives up (216 โ†’ 216) and a major one takes everything still in use, both heaps, into one bigger young heap (396 of 610). Then it starts again at the new size.

The sizes go 233, 376, 610, 987, 1598, 2586: each is roughly the two before it added together. That's on purpose. The docs: "first a variation of the Fibonacci sequence is used starting at 233 words. Then at about 1 mega words the heap only grows in 20% increments." Heaps shrink too, when a collection finds them mostly empty.

All of this happened inside one process, on its own memory. Nothing in it touched another process's heap, because nothing can: nothing in Elixir can point at another process's memory. So nothing else had to stop.

The replay at the top shows that for every process at once. Press Show the heaps: each BEAM process gets its own young and old heap, filling and collecting on its own, and Node's side gets its one heap.

Who waits?

Here's a bigger job to make that visible. One process builds a list of 10 million pairs and keeps all of it, which is close to the worst case for a copying collector: everything is live, so every collection copies all it looks at and frees nothing. Meanwhile six other processes each try to tick every 10 ms, and note how late each tick was (gc-alone.exs):

defmodule Builder do
  def loop(acc, 0), do: acc
  def loop(acc, n), do: loop([{n, n} | acc], n - 1)
end

defmodule Ticker do
  # Returns every tick as {how late it was, when it was due}, in ยตs.
  def run(due, stop, ticks) do
    now = System.monotonic_time(:microsecond)
    if now >= stop do
      ticks
    else
      Process.sleep(max(0, div(due - now, 1000)))
      late = System.monotonic_time(:microsecond) - due
      run(due + 10_000, stop, [{late, due} | ticks])
    end
  end
end

me = self()
t0 = System.monotonic_time(:microsecond)
for _ <- 1..6, do: spawn(fn -> send(me, {:ticks, Ticker.run(t0 + 10_000, t0 + 4_000_000, [])}) end)

builder = spawn(fn ->
  receive do: (:go -> :ok)
  list = Builder.loop([], 10_000_000)
  send(me, :built)
  receive do: (:stop -> length(list))
end)
:erlang.trace(builder, true, [:garbage_collection, :monotonic_timestamp])
Process.sleep(500)
send(builder, :go)

# ...then collect the trace messages and the ticks, and sort the ticks into
# those that came due while the builder was collecting and the rest
$ for i in 1 2 3; do elixir gc-alone.exs; done
schedulers: 8, dirty CPU schedulers: 8
builder's GCs: 68, 701 ms in all, longest 142 ms
ticks while the builder collected: 420, worst 0 ms late
ticks the rest of the time: 1980, worst 1 ms late
schedulers: 8, dirty CPU schedulers: 8
builder's GCs: 68, 695 ms in all, longest 137 ms
ticks while the builder collected: 420, worst 0 ms late
ticks the rest of the time: 1980, worst 0 ms late
schedulers: 8, dirty CPU schedulers: 8
builder's GCs: 68, 694 ms in all, longest 137 ms
ticks while the builder collected: 426, worst 0 ms late
ticks the rest of the time: 1974, worst 0 ms late

The builder spent about 700 ms collecting, and its biggest collections, near the end, took over a tenth of a second each, once its heaps held a few hundred megabytes. The tickers ticked right through them: hundreds of ticks while the builder collected, none of them even a millisecond late, as on time as the rest of the run.

You might guess the tickers were fine because there were eight schedulers and they ran on different ones. Here it is with one:

$ elixir --erl "+S 1" gc-alone.exs
schedulers: 1, dirty CPU schedulers: 1
builder's GCs: 68, 690 ms in all, longest 133 ms
ticks while the builder collected: 396, worst 0 ms late
ticks the rest of the time: 2004, worst 1 ms late

Still nothing. Had that 133 ms collection run on the only scheduler, it would have had the scheduler's thread for 133 ms, and no ticker could have run. It didn't run there, because the BEAM saw it coming. Before collecting, it adds up how much it will have to go through, and if that's 128K words (a megabyte) or more, it hands the collection to a dirty CPU scheduler. Dirty schedulers are extra scheduler threads for work that can't be counted in reductions. The process waits there while it's collected, and its own scheduler goes on running everyone else.

And in Node?

Node has one heap for all of its JavaScript. Any object can point at any other, so there's no smaller piece to collect on its own. V8 splits that heap into generations too: a small young generation that it collects often, by copying, the same idea as the BEAM's minor collections, and an old generation that a major collection goes through by marking what's in use.

V8 has worked hard on its pauses. Its young collections run in parallel on several threads. Most of the marking for a major collection happens on helper threads while your JavaScript keeps running. But the young collection still stops your JavaScript while it runs, and a major collection still ends with a pause on the main thread to finish the marking. While the collector has the main thread, no callback runs.

Here's the same job in Node: a list of 10 million pairs, all kept, and a ticker every 10 ms (gc-pause.mjs). So the ticker isn't stuck behind one long callback, the builder works in chunks of 10,000 and lets the ticker run between them: the longest the ticker waits on the builder's own code is a chunk, 2 to 4 ms. perf_hooks reports each collection and how long it took.

import { PerformanceObserver } from "node:perf_hooks";
import { setImmediate as letOthersRun } from "node:timers/promises";

const gcs = [];
new PerformanceObserver((list) => gcs.push(...list.getEntries())).observe({ entryTypes: ["gc"] });

const t0 = performance.now();
const ticks = []; // every tick as { late, due }, in ms
let due = t0 + 10;
const tick = () => {
  ticks.push({ late: performance.now() - due, due });
  due += 10;
  if (due < t0 + 4000) setTimeout(tick, Math.max(0, due - performance.now()));
};
setTimeout(tick, 10);

await new Promise((resolve) => setTimeout(resolve, 500));
let list = null;
for (let n = 10_000_000; n > 0; ) {
  for (const end = n - 10_000; n > end; n--) list = { a: n, b: n, tail: list };
  await letOthersRun();
}

// (each chunk is also timed, for the longest chunk of work in the output)
// ...then sort the ticks into those that came due while V8 was collecting
// and the rest, as in gc-alone.exs
$ for i in 1 2 3; do node gc-pause.mjs; done
node v25.9.0, heap used 464 MB, longest chunk of work 3 ms
GCs: 13, 170 ms in all, longest 98 ms
ticks while V8 collected: 17, worst 97 ms late
ticks the rest of the time: 382, worst 7 ms late
node v25.9.0, heap used 464 MB, longest chunk of work 3 ms
GCs: 14, 123 ms in all, longest 56 ms
ticks while V8 collected: 10, worst 51 ms late
ticks the rest of the time: 389, worst 4 ms late
node v25.9.0, heap used 464 MB, longest chunk of work 3 ms
GCs: 14, 126 ms in all, longest 60 ms
ticks while V8 collected: 12, worst 56 ms late
ticks the rest of the time: 387, worst 4 ms late

Be fair to V8 here: it's much faster at this job. It spent 120 to 170 ms collecting where the BEAM spent 700, and its longest pause was usually under half as long. Copying 300 MB of live data, over and over, is exactly what a copying collector is worst at, and V8's mostly-concurrent marking doesn't have to.

But look at who waited. In Node the ticks that came due during a collection waited it out, and the worst of them was late by nearly the whole longest pause, every run, because the pause stopped all the JavaScript there was. The rest of the time the ticker was never more than a few milliseconds late. In the BEAM the builder waited through 700 ms of collections and nobody else waited at all. In a server, the ticker is every other request. One request building something big in Node makes every request wait for its garbage. In the BEAM it only slows down that one request.

The replay at the top is another run of the same job (record-gc.exs and record-gc.mjs), with three tickers that make a little garbage every tick, the way a small request would, so their heaps fill and get collected too. In it the BEAM builder's longest collection was 131 ms, and V8's longest pause was 85 ms.

Most processes never collect at all

There's a cheaper way still to deal with garbage: don't collect it. When a process ends, the BEAM frees its heaps whole, garbage and all, without a collection. A process that finishes before its heap fills up never collects once.

Here are 100,000 short-lived processes that each build a list, sum it, and exit (die-young.exs), with the whole system's count of garbage collections from :erlang.statistics/1 before and after:

{gcs_before, _, _} = :erlang.statistics(:garbage_collection)
for _ <- 1..100_000 do
  spawn(fn -> send(me, Enum.sum(Enum.to_list(1..size))) end)
end
for _ <- 1..100_000, do: (receive do: (_ -> :ok))
{gcs_after, _, _} = :erlang.statistics(:garbage_collection)
$ for size in 50 100 1000 10000; do elixir die-young.exs $size; done
100000 processes, each summing a list of 50: 90 garbage collections
100000 processes, each summing a list of 100: 90 garbage collections
100000 processes, each summing a list of 1000: 800090 garbage collections
100000 processes, each summing a list of 10000: 1500090 garbage collections

With lists of 50 or 100, the whole system did 90 collections, and none of them were the children's. children-gcs.exs runs the same thing while tracing every new process's collections, and counts them:

counter = spawn(fn ->
  loop = fn loop, n -> receive do
    {:trace, _, :gc_minor_end, _} -> loop.(loop, n + 1)
    {:trace, _, :gc_major_end, _} -> loop.(loop, n + 1)
    {:trace, _, _, _} -> loop.(loop, n)
    {:count, from} -> send(from, {:children, n})
  end end
  loop.(loop, 0)
end)
:erlang.trace(:new_processes, true, [:garbage_collection, {:tracer, counter}])

# ...then the same 100,000 processes as die-young.exs, and print the
# system's count of collections and the counter's
$ for size in 50 100; do elixir children-gcs.exs $size; done
size 50: system 390, children's 0
size 100: system 390, children's 0

The script's own process collected more often this time, 390 in all, but the children still did none, at either size. The 90 in die-young.exs were nearly all the script's own process too, running the loop that spawns the children. The children's lists fit in a 233-word heap, so each one did its work and was freed whole. With lists of 1,000 the heap fills and each process collects 8 times. That's still cheap (each collection copies only that one process's small heap), but it's no longer free.

That's the shape of a lot of Elixir programs: a process per request or per job, short-lived, making garbage nobody ever collects. Generational collectors, V8's included, are built on the idea that most data dies young. A BEAM process can make that true for a whole heap at once.

Here are some of them, slowed down. Each fills a little of its heap and is gone, and none of them collects.

The live version of this needs JavaScript. In it, you can spawn short-lived processes, a dozen at a time, and watch each fill a little of its first heap and exit.

Tradeoffs

Two things don't fit the picture of each process alone with its heap.

Big binaries are shared. A binary (a string, a chunk of a file, a network packet) bigger than 64 bytes isn't kept on a process's heap. It's kept once, outside every heap, with a count of the processes using it, and each process holds a small reference to it. That makes sending one to another process cheap, since only the reference is copied. But the count only goes down when the processes holding a reference collect or exit, so a big binary can stay in memory well after it was last used, if a process holding it rarely collects.

And one process with a huge heap is slow to collect, as the builder showed. The BEAM keeps that from holding anyone else up, but it doesn't make it fast.

Sources