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:
- The BEAM launches one OS thread per physical CPU core, called a BEAM Scheduler (Scheduler 1 through Scheduler N).
- Each scheduler maintains a private run queue of runnable processes.
- When a scheduler picks a process, it gives that process a budget of 4,000 reductions (roughly 4,000 function calls or BIF evaluations).
- Every function call, loop iteration, or BIF call decrements the reduction counter by 1.
- 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.
- 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 whetherPidis 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 forPid, includingmemory(total bytes allocated),heap_size(words),reductions(work performed), andmessage_queue_len(pending mailbox items).
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 | undefined3 Types:4 Pid = pid()5 ItemList = [memory | heap_size | reductions | message_queue_len | status]6 InfoList = [{Item, Value}]7 8erlang:system_info(Item) -> Value9 Types:10 Item = process_count | process_limit | schedulers_online | wordsizeOTP 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 metrics5probe_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 => ProcLimit13 }.14 15%% Phase 2: Query isolated process control block (PCB) telemetry16probe_worker(Pid) ->17 case is_process_alive(Pid) of18 true ->19 Items = [memory, heap_size, reductions, message_queue_len],20 case erlang:process_info(Pid, Items) of21 [{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 => QLen27 }};28 undefined ->29 {error, process_exited}30 end;31 false ->32 {error, dead_pid}33 end.Architectural Notes:
- 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. - 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 returnsundefined. - 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()returnsok.
run_bench/1
- Input:
N :: pos_integer()(e.g.2000). - Behavior: Measures the spawn time of
Nconcurrent worker processes usingerlang:monotonic_time(microsecond), samples the memory footprint of the first 50 processes usinginspect_process/1, cleanly terminates all spawned workers viastopmessages, 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, or2688if the process has already terminated. - Examples:
process_bench:inspect_process(Pid)returns2688.
Instructions
- Inspect the implementation of
src/process_bench.erl. - Click
▷ Runto executeprocess_bench:run/0and observe high-speed process spawning in the output drawer. - Click
▶ Submitto run the automated OTP 29 benchmark and memory telemetry verification suite.
Rules & Verification Constraints
- Spawns
Nconcurrent processes and measures real-time allocation. - Average process memory footprint must remain under 4,096 bytes.
- All spawned processes must be cleanly stopped with
stopmessages. - 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.
Mailbox has 3 pending messages: [{log, 1}, {metric, 2}, {urgent, 99}]. Receive block seeks {urgent, Msg}.
erlang:process_info(Pid, ItemList) -> InfoList | undefinederlang:system_info(Item) -> term()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().These rules are verified by bf_ast_verifier:verify_rules/3 on every Submit.
No Tests Executed Yet
Tap Run Tests below to compile your code and inspect Erlang term diffs.