0 XP

Locked Lesson Preview: Chapter 5 requires mastering the Chapter 4 Problem Set (Chapter 4 Problem Set: Binary Network Packet & Multi-Frame TLV Stream Parser (packet_parser.erl)) first.

CH5·L1Guided DemoIntermediate

Prerequisite Required

Chapter 5 requires mastering the Chapter 4 Problem Set (Chapter 4 Problem Set: Binary Network Packet & Multi-Frame TLV Stream Parser (packet_parser.erl)) first.

Lightweight BEAM Processes (~2.5 KB), Preemptive Reductions & Process Introspection BIFs

Why This Matters in Production

In traditional backend languages like Java, C++, Python, or Go, concurrency is built on operating system threads or cooperative coroutines sharing a single global address space. An OS thread allocates between 1 MB and 8 MB of stack memory, incurs kernel context-switch penalties of 1,000 to 2,000 CPU cycles, and forces all threads to share one global heap. When two threads mutate shared memory simultaneously, you suffer from Race Conditions, Lost Updates, and Deadlocks. Preventing these race conditions requires complex locking schemes (mutexes, semaphores, read-write locks), which degrade throughput and introduce latency spikes when the global garbage collector initiates "Stop-the-World" pauses.

The BEAM Virtual Machine was designed for telecom switches requiring 99.9999999% uptime ("nine nines"). It adopts the Actor Model, where processes share absolutely zero memory. A BEAM process is not an OS thread; it is an ultralightweight user-space memory container. A freshly spawned BEAM process starts with only 309 words (~2.5 KB on 64-bit systems) of RAM, encompassing its private stack, private heap, mailbox queue descriptor, and process control block. Because processes are isolated, each process executes garbage collection on its own private heap without stopping or even pausing any other process on the machine.

Deep Concept Breakdown & Under the Hood

1. Isolated Heaps vs. Shared-Memory GC

In shared-memory platforms, a background garbage collector must periodically freeze the entire application to trace object references across all threads. On the BEAM, every process owns a private heap. When process <0.142.0> accumulates temporary terms, ERTS performs generational garbage collection solely on <0.142.0>'s heap. If a process short-circuits or terminates, the runtime reclaims its entire memory block in a single O(1) deallocation—bypassing GC entirely!

2. Preemptive Reduction Scheduling (The 4,000-Reduction Rule)

In cooperative systems (like Node.js event loops, Python asyncio, or early Go runtimes), an accidental long-running computation or infinite loop (while(true)) monopolizes the thread, freezing network sockets, health checks, and peer traffic.

The BEAM prevents compute starvation through Preemptive Reduction Counters:

  1. The BEAM launches one OS thread per physical CPU core, called a BEAM Scheduler (Scheduler 1 through Scheduler N).
  2. Each scheduler maintains a private run queue of runnable processes.
  3. When a scheduler picks a process, it gives that process a budget of 4,000 reductions (roughly 4,000 function calls or BIF evaluations).
  4. Every function call, loop iteration, or BIF call decrements the reduction counter by 1.
  5. The instant the reduction counter reaches zero, the scheduler preempts the process, pushes it to the back of the run queue, and immediately context-switches to the next process.
  6. A CPU-bound mathematical loop or rogue user payload can never starve other chat rooms, TCP sockets, or telemetry aggregators!

3. Real-Time Process Introspection BIFs

The BEAM provides built-in functions (BIFs) to inspect runtime internals without third-party profilers:

  • self() -> pid(): Returns the current process's unique identifier.
  • is_process_alive(Pid) -> boolean(): Confirms whether Pid is actively running.
  • processes() -> [pid()]: Returns a snapshot list of every active process in the VM.
  • erlang:system_info(process_count) -> integer(): Returns the total live process count.
  • erlang:process_info(Pid, ItemList) -> [{Item, Value}] | undefined: Queries internal VM metrics for Pid, including memory (total bytes allocated), heap_size (words), reductions (work performed), and message_queue_len (pending mailbox items).
WarningProduction Concurrency Trap: Millions of Processes Still Require Memory Discipline

While spawning 100,000 BEAM processes consumes only ~250 MB of base RAM (at ~2.5 KB per process), processes that retain large terms in their state or allow unhandled messages to accumulate in their mailboxes will quickly grow to dozens of megabytes each. Always monitor process heaps using erlang:process_info(Pid, memory) and implement strict mailbox hygiene.

Official Erlang Docs & Function Reference

1%% Official OTP Signature (erts / erlang)
2erlang:process_info(Pid, ItemList) -> InfoList | undefined
3 Types:
4 Pid = pid()
5 ItemList = [memory | heap_size | reductions | message_queue_len | status]
6 InfoList = [{Item, Value}]
7 
8erlang:system_info(Item) -> Value
9 Types:
10 Item = process_count | process_limit | schedulers_online | wordsize

OTP documentation specifies types and return values explicitly. erlang:process_info/2 takes a PID and a list of queried metric atoms, returning an association list or undefined if the target process has already halted. Use the Official OTP Doc Cards below for full signature references.

Parallel Worked Example

The following operations probe demonstrates querying cluster schedulers and isolated process memory in production:

1-module(telemetry_probe).
2-export([probe_system/0, probe_worker/1]).
3 
4%% Phase 1: Query global node scheduler and process limit metrics
5probe_system() ->
6 Schedulers = erlang:system_info(schedulers_online),
7 ProcCount = erlang:system_info(process_count),
8 ProcLimit = erlang:system_info(process_limit),
9 #{
10 schedulers_online => Schedulers,
11 active_processes => ProcCount,
12 max_process_limit => ProcLimit
13 }.
14 
15%% Phase 2: Query isolated process control block (PCB) telemetry
16probe_worker(Pid) ->
17 case is_process_alive(Pid) of
18 true ->
19 Items = [memory, heap_size, reductions, message_queue_len],
20 case erlang:process_info(Pid, Items) of
21 [{memory, Bytes}, {heap_size, HeapWords}, {reductions, Reds}, {message_queue_len, QLen}] ->
22 {ok, #{
23 bytes => Bytes,
24 heap_words => HeapWords,
25 reductions => Reds,
26 mailbox_len => QLen
27 }};
28 undefined ->
29 {error, process_exited}
30 end;
31 false ->
32 {error, dead_pid}
33 end.

Architectural Notes:

  1. Global Introspection via erlang:system_info/1: Reads VM-level metrics (O(1)) directly from ERTS without locks, capturing online schedulers and live process counts.
  2. Process Control Block Sampling: erlang:process_info(Pid, Items) atomically inspects the memory allocation and pending message count of an isolated actor. If the process terminates concurrently during the call, ERTS safely returns undefined.
  3. Structured Domain Telemetry: Rather than dumping raw ERTS tuple lists, the probe maps metrics into an explicit {ok, Map} contract suitable for downstream metrics ingestion.

Assignment Specification

This is a Guided Interactive Demo. Explore the concurrency and telemetry capabilities of the BEAM VM in src/process_bench.erl.

Functions Provided

run/0

  • Input: None (()).
  • Behavior: Executes the default 2,000 process benchmark and prints formatted benchmark statistics (total spawn duration, per-process latency, and average memory footprint) to standard output. Returns ok.
  • Examples:
  • process_bench:run() returns ok.

run_bench/1

  • Input: N :: pos_integer() (e.g. 2000).
  • Behavior: Measures the spawn time of N concurrent worker processes using erlang:monotonic_time(microsecond), samples the memory footprint of the first 50 processes using inspect_process/1, cleanly terminates all spawned workers via stop messages, and returns a telemetry summary map #{spawned => N, avg_memory_bytes => AvgMem, elapsed_us => ElapsedUs}.
  • Examples:
  • process_bench:run_bench(2000) returns #{spawned => 2000, avg_memory_bytes => 2688, elapsed_us => 4250}.

inspect_process/1

  • Input: Pid :: pid().
  • Behavior: Queries the internal VM process control block via erlang:process_info(Pid, memory) to retrieve the process's allocated memory footprint in bytes. Returns the integer byte size, or 2688 if the process has already terminated.
  • Examples:
  • process_bench:inspect_process(Pid) returns 2688.

Instructions

  1. Inspect the implementation of src/process_bench.erl.
  2. Click ▷ Run to execute process_bench:run/0 and observe high-speed process spawning in the output drawer.
  3. Click ▶ Submit to run the automated OTP 29 benchmark and memory telemetry verification suite.

Rules & Verification Constraints

  • Spawns N concurrent processes and measures real-time allocation.
  • Average process memory footprint must remain under 4,096 bytes.
  • All spawned processes must be cleanly stopped with stop messages.
  • Automated verifier checks module compilation, exports (run/0, run_bench/1, inspect_process/1), AST rules (erlang:process_info/2, erlang:monotonic_time/1, list_comprehension, guards), and live OTP memory bounds.
Selective Receive & The BEAM Save Queue
1/4
Process Mailbox (Scan: {log, 1})FIFO Order
{log, 1}
{metric, 2}
{urgent, 99} (Target)
Internal Save Queue (Unmatched Buffer)
Empty
Step 1: Unprocessed Mailbox Queue

Mailbox has 3 pending messages: [{log, 1}, {metric, 2}, {urgent, 99}]. Receive block seeks {urgent, Msg}.

receive {urgent, Msg} -> ... end
Official Erlang Docs & Function Reference
OTP Docserlang:process_info
erlang:process_info(Pid, ItemList) -> InfoList | undefined
OTP Docserlang:system_info
erlang:system_info(Item) -> term()
Quick Mental Model CheckPredict Before Coding

Why can an accidental infinite loop like loop() -> loop(). in one BEAM process never freeze the rest of an Erlang web server or XMPP gateway?

%% A rogue compute-heavy loop running on CPU Core 1:
cpu_intensive_loop() ->
    cpu_intensive_loop().
Strict Rules & Verification Constraints

These rules are verified by bf_ast_verifier:verify_rules/3 on every Submit.