0 XP

Locked Lesson Preview: Chapter 10 requires mastering the Chapter 9 Problem Set (Chapter 9 Problem Set: Fault-Tolerant ETS Session Store with Heir Failover) first.

CH10·L1Guided DemoIntermediate

Prerequisite Required

Chapter 10 requires mastering the Chapter 9 Problem Set (Chapter 9 Problem Set: Fault-Tolerant ETS Session Store with Heir Failover) first.

Guided Demo: Inside gen_tcp:listen/2, accept/1, connect/3 & Live TCP Socket Telemetry

Why This Matters in Production

Every high-throughput network backend in production—from Redis, PostgreSQL, and RabbitMQ to WhatsApp, Discord, and telecom switches—is built on top of raw TCP (Transmission Control Protocol) sockets.

In traditional multithreaded runtimes (Java, C++, Go, Python), handling 50,000 concurrent client connections requires complex thread pools, non-blocking epoll event loops (libuv, Netty), or mutexes that risk catastrophic deadlocks.

In the BEAM VM, raw networking is treated as a first-class concurrency primitive. Every connected TCP socket is mapped directly to a lightweight Erlang process. When bytes arrive on the physical network card, the BEAM port driver translates the operating system's TCP segment into an Erlang message ({tcp, Socket, Data}) and delivers it straight to that process's private mailbox without shared locks!

Important

The BEAM Raw TCP Socket Lifecycle:

  1. gen_tcp:listen(0, Opts): Asks the OS kernel to bind an available port and creates a ListenSocket (the server's front door).
  2. gen_tcp:accept(ListenSocket, Timeout): Blocks the acceptor process until a client completes the 3-way TCP handshake (SYN → SYN-ACK → ACK), returning a dedicated ClientSocket.
  3. Wire Traffic: Incoming bytes bypass userland mutexes and flow directly through the socket port driver to the controlling process.

Deep Concept Breakdown & Under the Hood

1. What is a TCP Socket?

A TCP connection is not a physical cable; it is a stateful contract maintained between two operating system kernels over an IP network:

  • Sequence Numbers & ACKs: Every byte transmitted is numbered. The receiving kernel acknowledges received ranges and automatically retransmits lost packets.
  • The 3-Way Handshake: Connection setup requires three wire segments:
  1. Client sends SYN (Synchronize sequence numbers).
  2. Server responds with SYN-ACK (Acknowledge client SYN and send server SYN).
  3. Client responds with ACK (Acknowledge server SYN).

2. ListenSocket vs. ClientSocket

In Erlang socket programming, the two socket descriptors have completely different responsibilities:

  • ListenSocket (gen_tcp:listen/2): The listening socket is the welcoming front door of your server. It is bound to an IP address and port. Its sole job is to queue incoming connection requests. You cannot send or receive payload data over a ListenSocket.
  • ClientSocket (gen_tcp:accept/2): Calling gen_tcp:accept/2 suspends the acceptor process until a client completes the 3-way handshake. The operating system allocates a dedicated, full-duplex communication pipe (ClientSocket) specifically for that client, while ListenSocket remains free to welcome further connections.

3. Ephemeral Port Binding: Why Port 0?

When calling gen_tcp:listen(Port, Options), specifying port 0 asks the operating system kernel to allocate an unused ephemeral port (typically in the range 49152–65535). You then retrieve the actual bound port using:

1{ok, Port} = inet:port(ListenSocket).

Passing port 0 is essential for parallel automated testing and dynamic microservices, preventing {error, eaddrinuse} port collision errors when multiple test suites run concurrently.

4. Controlling Process of a Socket

On the BEAM, every open socket is owned by an Erlang process known as the controlling process:

  • The process that calls gen_tcp:listen/2 or gen_tcp:accept/2 becomes the initial controlling process.
  • In active modes, socket messages ({tcp, Socket, Data}, {tcp_closed, Socket}) are delivered exclusively to the controlling process's mailbox; in {active, false} passive mode, callers pull bytes explicitly with gen_tcp:recv/3.
  • If the controlling process terminates, the BEAM VM automatically closes the underlying socket file descriptor.

5. Inspecting Live Socket Telemetry: inet:getstat/2

In production Erlang, you do not need external kernel probes to measure network throughput. You can query the OS kernel's socket counters directly from Erlang:

1{ok, Stats} = inet:getstat(Socket, [recv_oct, send_oct, recv_cnt, send_cnt]).
2%% Returns: [{recv_oct, 1024}, {send_oct, 512}, {recv_cnt, 4}, {send_cnt, 2}]
  • recv_oct / send_oct: Total octets (bytes) received and sent over the wire.
  • recv_cnt / send_cnt: Total number of packets transferred through the socket driver.
Warning

Production Networking Trap: Port Starvation & Lingering Sockets:

Every open socket consumes an OS file descriptor. If your connection worker crashes or finishes without calling gen_tcp:close(Socket) in its cleanup path, the socket descriptor remains open in the OS kernel until garbage collection occurs. Under 10,000 connections/sec, your server will hit EMFILE (Too many open files) and fail new connections. Always wrap socket workers in supervised OTP processes.

Official Erlang Docs & Function Reference

1%% Official OTP Signatures (kernel / gen_tcp & inet)
2gen_tcp:listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}
3 Types:
4 Port = inet:port_number()
5 Options = [gen_tcp:listen_option()]
6 ListenSocket = gen_tcp:socket()
7 
8gen_tcp:accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason}
9 Types:
10 ListenSocket = Socket = gen_tcp:socket()
11 Timeout = timeout()
12 
13gen_tcp:connect(Address, Port, Options, Timeout) -> {ok, Socket} | {error, Reason}
14gen_tcp:send(Socket, Packet) -> ok | {error, Reason}
15gen_tcp:recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason}
16gen_tcp:close(Socket) -> ok
17inet:port(Socket) -> {ok, Port}
18inet:getstat(Socket, [StatOption]) -> {ok, [{StatOption, integer()}]}

Consult the attached documentation cards below for gen_tcp:listen/2 and gen_tcp:accept/2 kernel behavior, plus the kernel module links in the references drawer.

Parallel Worked Example: Minimal Loopback Health Probe

Consider a separate domain: a single-request health-check probe (ping_probe_demo) that opens an ephemeral loopback socket, reads a fixed 4-byte <<"PING">> frame in passive mode, replies <<"PONG">>, and confirms receipt via a bounded receive ... after timeout:

1-module(ping_probe_demo).
2-export([run_probe/0]).
3 
4%% @doc Bind an ephemeral port, send a single health probe over loopback, and return the bound port and echoed byte count.
5run_probe() ->
6 {ok, ListenSock} = gen_tcp:listen(0, [binary, {packet, raw}, {active, false}, {reuseaddr, true}]),
7 {ok, Port} = inet:port(ListenSock),
8 Caller = self(),
9 spawn(fun() -> serve_once(ListenSock, Caller) end),
10 {ok, ConnSock} = gen_tcp:connect("127.0.0.1", Port, [binary, {packet, raw}, {active, false}], 2000),
11 ok = gen_tcp:send(ConnSock, <<"PING">>),
12 {ok, <<"PONG">>} = gen_tcp:recv(ConnSock, 4, 2000),
13 ok = gen_tcp:close(ConnSock),
14 ok = gen_tcp:close(ListenSock),
15 receive
16 {served_bytes, ByteCount} -> {ok, Port, ByteCount}
17 after 2000 ->
18 {error, probe_timeout}
19 end.
20 
21serve_once(ListenSock, Caller) ->
22 case gen_tcp:accept(ListenSock, 2000) of
23 {ok, PeerSock} ->
24 {ok, Payload} = gen_tcp:recv(PeerSock, 4, 2000),
25 ok = gen_tcp:send(PeerSock, <<"PONG">>),
26 ok = gen_tcp:close(PeerSock),
27 Caller ! {served_bytes, byte_size(Payload)};
28 {error, Reason} ->
29 Caller ! {probe_error, Reason}
30 end.

What ERTS Does at Runtime

  • Concurrent Peer Handshake: Spawning serve_once/2 before calling gen_tcp:connect/4 lets the BEAM scheduler run acceptor and client concurrently over the OS loopback interface without deadlocking on passive accept/2.
  • Passive Backpressure: Both sides pass {active, false}, so kernel TCP buffers only deliver data when gen_tcp:recv/3 explicitly pulls bytes with a 2000ms timeout.

Assignment Specification

This is a Guided Demonstration implemented in src/tcp_live_demo.erl (-module(tcp_live_demo).). Inspect the pre-wired module in the editor and execute it to observe live loopback socket telemetry:

run_demo/0

  • Input: Zero arguments.
  • Behavior: Opens a passive raw binary listening socket on ephemeral port 0, queries the assigned port via inet:port/1, spawns a background acceptor process calling gen_tcp:accept/2 and tail-recursing in echo_loop/3, connects a loopback client to 127.0.0.1, exchanges three CRLF-delimited test frames (SYN_FRAME, DATA_FRAME, FIN_FRAME) with +ACK: echoes, queries socket statistics via inet:getstat/2, closes both socket descriptors, and waits with a bounded timeout for the acceptor total before returning a summary map with port, frames_exchanged, and bytes_received.
  • Examples:
  • maps:get(frames_exchanged, tcp_live_demo:run_demo()) returns 3.

Click ▷ Run or ▶ Submit to boot the live TCP server and inspect wire transmission telemetry in the terminal.

Rules & Verification Constraints

  • Live Execution: Verified by calling tcp_live_demo:run_demo/0 and confirming frames_exchanged equals 3.
  • AST & Bytecode Enforcements: bf_ast_verifier enforces true tail recursion on echo_loop/3, required remote calls gen_tcp:listen/2, gen_tcp:accept/2, gen_tcp:send/2, and gen_tcp:recv/3, and at least one receive ... after timeout block.
TCP Stream Fragmentation & {active, once}
1/4
TCP Wire:
Chunk 1: "<stream:str"
Chunk 2: "eam to='localhost'><message>Hi</mes"
Chunk 3: "sage><ping id='p1'/>"
BufferBin Leftover
<<"<stream:str">>
Emitted Frames
[] (Waiting for more)
Step 1: Partial Chunk 1 Arrives

TCP packet carries partial XML: "<stream:str". Parser buffers chunk into State#buffer. No frame emitted.

inet:setopts(Sock, [{active, once}])
Official Erlang Docs & Function Reference
OTP Docsgen_tcp:listen
gen_tcp:listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}
OTP Docsgen_tcp:accept
gen_tcp:accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason}
Quick Mental Model CheckPredict Before Coding

What is the critical architectural difference between a ListenSocket and an accepted ClientSocket in Erlang?

{ok, ListenSocket} = gen_tcp:listen(0, [binary, {active, false}]),
{ok, ClientSocket} = gen_tcp:accept(ListenSocket).
Strict Rules & Verification Constraints
Must be tail-recursive:
echo_loop/3

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