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!
The BEAM Raw TCP Socket Lifecycle:
gen_tcp:listen(0, Opts): Asks the OS kernel to bind an available port and creates aListenSocket(the server's front door).gen_tcp:accept(ListenSocket, Timeout): Blocks the acceptor process until a client completes the 3-way TCP handshake (SYN→SYN-ACK→ACK), returning a dedicatedClientSocket.- 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:
- Client sends
SYN(Synchronize sequence numbers). - Server responds with
SYN-ACK(Acknowledge client SYN and send server SYN). - 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 aListenSocket.ClientSocket(gen_tcp:accept/2): Callinggen_tcp:accept/2suspends 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, whileListenSocketremains 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/2orgen_tcp:accept/2becomes 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 withgen_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.
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) -> ok17inet: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 receive16 {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) of23 {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/2before callinggen_tcp:connect/4lets the BEAM scheduler run acceptor and client concurrently over the OS loopback interface without deadlocking on passiveaccept/2. - Passive Backpressure: Both sides pass
{active, false}, so kernel TCP buffers only deliver data whengen_tcp:recv/3explicitly 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 viainet:port/1, spawns a background acceptor process callinggen_tcp:accept/2and tail-recursing inecho_loop/3, connects a loopback client to127.0.0.1, exchanges three CRLF-delimited test frames (SYN_FRAME,DATA_FRAME,FIN_FRAME) with+ACK:echoes, queries socket statistics viainet:getstat/2, closes both socket descriptors, and waits with a bounded timeout for the acceptor total before returning a summary map withport,frames_exchanged, andbytes_received. - Examples:
maps:get(frames_exchanged, tcp_live_demo:run_demo())returns3.
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/0and confirmingframes_exchangedequals3. - AST & Bytecode Enforcements:
bf_ast_verifierenforces true tail recursion onecho_loop/3, required remote callsgen_tcp:listen/2,gen_tcp:accept/2,gen_tcp:send/2, andgen_tcp:recv/3, and at least onereceive ... aftertimeout block.
TCP packet carries partial XML: "<stream:str". Parser buffers chunk into State#buffer. No frame emitted.
gen_tcp:listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}gen_tcp:accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason}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).echo_loop/3These 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.