Hi everyone👋
Over the past few years, I have been heavily involved in building backend infrastructure for WebRTC voice and video communication and writing network engines in Go. Over time, everything I built for transport, room routing, and surviving mobile networks grew into a standalone signaling server for messengers and calls. In this article, I will break down its internal architecture and the practical engineering decisions behind it.
Building a signaling server for WebRTC or a messenger looks trivial at first. Spin up an HTTP server, upgrade two connections to WebSocket, read a JSON payload with an SDP offer from one client, and write it to the other socket. In Go, you can put together a working prototype in a single evening.
On a local laptop with two browser tabs open, that code works great. The trouble starts once you deploy to production. Users connect over very different networks. Some sit at home on Wi-Fi, others use mobile data, ride the subway, or step into an elevator mid-call. People switch between home Wi-Fi and cellular networks on the move, share a single external IP across tens of thousands of subscribers behind a mobile carrier or home ISP, and try to shove megabyte-sized payloads or raw encrypted bytes into a text frame. That one-evening prototype suddenly burns through all available RAM on idle sockets, stalls because of a single user in a subway tunnel, and bans entire neighborhoods after mistaking cell tower traffic for a DDoS attack.
Below, I will walk through the internals of my Go signaling server, show the real memory trade-offs, and share the edge cases you inevitably hit when moving from a single binary to a distributed cluster.
Memory Economics at 100,000 Sockets
In a real messenger, 95% of open connections are completely idle at any given second. The app sits open on screen or in a background tab while the user is neither texting nor calling anyone. If the standard library allocates 4 to 8 KB read and write buffers per socket and keeps two dedicated workers running all the time, handling 100,000 connections eats nearly a gigabyte of RAM for thin air before a single message is even sent.
When I designed the Go transport layer from scratch without third-party WebSocket libraries, I immediately faced a choice between standard goroutines and a pure event loop built on epoll or kqueue. Going completely goroutine-free saves the most memory, but it turns parsing fragmented WebSocket frames over a TLS stream into a complex state machine where subtle bugs are easy to introduce. In practice, a single parked read goroutine in Go takes around 2 to 2.5 KB of stack, which adds up to a very reasonable 200 to 250 MB across 100,000 connections. I deliberately kept a linear single-goroutine read loop for code simplicity and readability, and stripped away all the excess memory around buffers and writes instead.
Right after the handshake, the server hijacks the raw TCP socket and drops the reference to the 8 KB buffer allocated by standard net/http. A cold connection reads frame headers and pings into an inline 256-byte array. When a heavy burst of data arrives on the socket, it temporarily leases a 16 KB buffer from a shared sync.Pool, and after four consecutive short reads returns it to the pool and shrinks back down to 256 bytes. The write goroutine does not stay alive forever either. It drains up to 16 packets from the queue, flushes them in a single vectored writev syscall, waits 200 milliseconds for new frames, and exits if the connection stays quiet.
Slow Consumer Isolation and Mixed Wire Formats
The second classic flaw in simple chat servers is blocking broadcast. Suppose twenty people are in a call room and one of them walks into an underpass. Their TCP window fills up and socket writes block. If you broadcast messages directly inside a loop, one stalled phone freezes delivery for the other nineteen participants.
To decouple room participants, outbound delivery runs through two small ring queues per session.
| Buffer or Stage | Configured Cap | Reasoning Behind the Trade-Off |
| Cold socket read buffer | 256 bytes | Fits a frame header and a short ping without leasing memory from the pool |
| Priority queue (hiQ) | 128 packets | Absorbs SDP and chat bursts, drops the socket with code 1008 (slow_consumer) on overflow |
| Ephemeral queue (loQ) | 64 packets | Used for cursors and typing indicators where new frames silently evict old ones without disconnecting |
| Single frame limit | 64 KB | Comfortably fits heavy Simulcast SDP payloads while rejecting 1 MB frames at the header level with code 1009 |
| Replay buffer (ReplayBuffer) | 512 KB per room | Retains up to 256 missed packets for reconnects and protects the node against OOM attacks |
End-to-end encryption (E2EE) transport also deserves special attention. The signaling server never sees encryption keys and acts as a blind courier for raw encrypted bytes. Ciphertext routinely contains null bytes and invalid UTF-8 sequences, which cause a text-mode WebSocket connection to terminate immediately with close code 1007.
Browsers have supported binary frames via ArrayBuffer for a long time, so the main web app runs over the compact binary subprotocol slyber.v1.bin right alongside mobile clients without extra encoding overhead. Still, an ecosystem often includes lightweight web widgets, third-party integrations, or debugging scripts that are much easier to wire up using plain text JSON (slyber.v1.json). So binary and text clients can share the same room without friction, the codec inspects each payload on the fly. Valid UTF-8 JSON goes straight into the text envelope as is, while raw binary ciphertext is automatically wrapped into a pb64 (Base64) field only for sockets that explicitly negotiated text mode.
Mobile Networks and the CGNAT Trap
Even when the server manages memory carefully, real-world radio networks quickly find ways to break a call. In practice, three scenarios cause the most headaches.
The first one involves WebRTC offer collisions (SDP Glare). When two peers join a room at almost the same moment and both send an SDP Offer to each other, media negotiation hits a deadlock. Instead of relying on fragile random backoff timers on the client, I moved arbitration directly into the room core. On join, the server assigns each participant a monotonic JoinSeq number and includes it in the OpSnapshot payload. That makes the rule strict and unambiguous, as the peer with the higher JoinSeq always backs off during a simultaneous offer.
The second scenario happens every time someone walks out of an apartment building onto the street mid-call. The phone switches from the home router to an LTE base station and the old TCP socket dies. If the server evicts the session from the room that very millisecond and broadcasts OpPeerLeft to everyone, the call drops. To prevent that, the initial OpWelcome frame immediately issues temporary 15-minute TURN HMAC credentials along with a dedicated resume_token. I settled on a 15-second session grace window. That gives plenty of time for a cellular radio handover or a short tunnel without leaving ghost peers hanging in rooms for minutes. Once back online with a new IP, the client sends its last seen packet sequence number last_seq, and the room ring buffer replays the ICE candidates missed during the brief disconnect while filtering out private messages meant for other peers.
The third and trickiest trap only surfaces when serving traffic from major mobile carriers. Because of IPv4 exhaustion, thousands of smartphones in the same district share a single external carrier address (CGNAT). A naive rate limiter capped at 50 to 100 connections per IP will either cut off half the city during rush hour or let a single attacker behind that same carrier IP lock out everyone nearby by flooding fake tokens.
To reconcile DDoS protection with mobile carrier networks, I split ingress filtering into two independent stages and added a per-token connection limit.
Under this model, an unauthenticated botnet hits the narrow first stage and gets 429 Too Many Requests without touching legitimate users holding valid JWTs in the second stage. And if a real user has a buggy custom ROM in their pocket causing the app to open sockets in an infinite loop, their personal per-token cap stops it long before exhausting the shared carrier quota. IPv6 rules differ as well, grouping global addresses by /64 subnet to prevent bypassing rate limits via SLAAC interface rotation while keeping exact /128 checks for NAT64 (64:ff9b::/96) traffic so separate IPv4 subscribers are not lumped into the same bucket again.
When One Node Is Not Enough and Why I Removed the Message Broker from the Hot Path
Let me be upfront that you do not need a cluster on day one. In benchmarks, a single Go process comfortably pushes over 350,000 signaling packets per second on a standard ARM processor and holds up to 100,000 open connections in standalone mode. One machine is more than enough for a mid-sized messenger with plenty of headroom. A cluster becomes necessary when you need regional entry points closer to users or zero-downtime node upgrades under 24/7 traffic.
The conventional way to scale WebSocket servers revolves around a message broker like Redis Pub/Sub. Every node is identical, clients land on whichever server they hit, and every message gets serialized and pushed across the shared broker. The catch is that as you add more nodes, that central bus has to chew through the combined traffic of the entire cluster and quickly turns into your tightest bottleneck and single point of fragility.
Instead of a shared message bus, I split server roles into perimeter gateways (Edge) and sharded cores (Core).
Edge nodes sit on the perimeter, terminate client TLS, verify Origin headers and JWT signatures, answer empty pings locally without touching the internal network, and normalize all incoming packets into a unified binary format. Core nodes live inside a private network, know nothing about client JWT secrets, and hold rooms and personal inboxes in RAM. Each gateway computes the target core for any room locally with zero allocations using Rendezvous Hashing (built on FNV-1a and SplitMix64), so participants connecting through different gateways deterministically land on the exact same core without a central coordinator.
Between every Edge and Core sits a pool of 16 sharded TCP links running TLS 1.3, where mutual HMAC authentication is strictly bound to the session keying material (ExportKeyingMaterial) to protect against interception. In parallel, a fast UDP tunnel encrypted with AES-256-GCM runs with a 64-bit sliding anti-replay window. Ephemeral events like mouse coordinates are packed in batches over UDP so a single lost packet on the internal network never stalls the call queue at the TCP layer.
Routing itself looks straightforward right until servers in the cluster start crashing and coming back online. Debugging three failure edge cases took me more time than writing the room engine itself.
Migrating Rooms Without Dropping Client Sockets
When a Core server suddenly loses power, dropping tens of thousands of client WebSocket connections at the Edge is out of the question, or reconnecting clients will trigger a handshake storm. Instead, the gateway detects the broken tunnel, recomputes hashes for orphaned rooms across the surviving cores, and transparently reattaches users using OpTunnelReattach packets.
The subtle part here involves ephemeral state keys (FlagAutoClean), which store published SFU media tracks or operator locks acquired via CAS. If you let clients push their own previous state on reconnect, a malicious peer can easily forge someone else's key. During normal operation, whenever an AutoClean key is legitimately updated, the core syncs a verified copy back to the Edge along with a monotonic version number and deletion tombstones, enforcing a strict quota of 8 KB per room and 32 KB per socket. On failover, the gateway restores onto the new core only the state that the session officially owned.
Preventing Split-Brain After a Core Reboot
Suppose Core-1 crashes and an active call between Alice and Bob fails over to Core-2. A minute later, Core-1 reboots and rejoins the cluster with empty memory. Under pure Rendezvous Hashing, that room once again maps to Core-1. If a third participant, Charlie, joins the call through a neighboring gateway Edge-2 right then, the hash function will route him to the empty Core-1, splitting the room in half.
To prevent split-brain, cores track active rooms and broadcast lightweight OpTunnelRoomPin affinity markers to every gateway. Until Alice and Bob hang up and the room on Core-2 is completely empty, any new participants arriving through any gateway are routed straight to Core-2. Meanwhile, before the recovered Core-1 marks itself ready for traffic, it synchronously pulls a fresh token revocation list from a gateway and reclaims personal inboxes u:<uid> and s:<sid>, ensuring no user banned during downtime slips through a race window and no server notifications get dropped into a black hole.
Quarantining Flapping Nodes and Graceful Drain for Upgrades
Sometimes a server does not die permanently, but gets stuck in a rapid crash-restart loop (for instance, hitting a container memory limit every three seconds). Left unchecked, a flapping node will repeatedly pull a slice of rooms back onto itself and immediately drop them again. To stop that, Edge nodes run a flapping detector. If a core drops its connection three times within a minute or stays up for less than five seconds twice in a row, the gateway places it into temporary quarantine with exponential backoff from 15 seconds up to 2 minutes and stops routing new rooms to it. At the same time, quarantine follows a fail-open policy so that if every other healthy core goes dark at once, the gateway still uses the quarantined node as a last resort rather than taking down the whole cluster.
For routine zero-downtime releases, nodes support a Drain mode. Upon receiving a control command, the node starts returning HTTP 503 to /healthz probes and new connection attempts, then sends connected clients a system OpMigrate frame carrying the address of a peer server and a randomized reconnect jitter of up to 5 seconds. Thousands of client apps smoothly move over to the updated node within seconds without causing a traffic spike.
Hiding the Main Backend Behind the Signaling Gateway
In a typical messenger architecture, a classic REST API for the main backend sits exposed to the internet right next to the signaling server. In practice, that doubles your attack surface, forcing you to maintain duplicate rate limiters, CORS rules, and brute-force protections while making sure an unexpected database error never leaks internal server addresses to the outside world.
Because a messenger client already keeps a persistent WebSocket open to the signaling server anyway, there is no real need to expose the main backend to the public internet at all. In my setup, only the signaling gateways face the outside world, while business logic workers and databases stay inside an isolated private network with zero public ports.
- Single pre-login entry point (/v1/auth). Before a user has a JWT and is allowed to open a socket, sign-up, login, and captcha verification requests pass through a narrow HTTP proxy directly on the signaling gateway. It accepts strictly POST requests with application/json up to 16 KB (blocking legacy browser CSRF attacks via <form> submissions), forwards only topics prefixed with auth., and masks any upstream 500 errors with a generic 502 if an internal database goes down, never leaking internal network details.
- All post-login operations over the socket (sys:app). Once the client obtains a token and establishes a WebSocket, every action from sending chat messages to requesting a one-time presigned URL for uploading heavy video to S3 travels as standard binary RPC frames addressed to sys:app. The signaling server reads the already verified user_id straight from session memory, signs the request with an X-Slyber-Signature (HMAC-SHA256) header, and load-balances it across the internal backend pool.
- Socket-level outbound connection protection. So that even a compromised configuration cannot turn internal webhook, SFU, or backend bridges into a tool for probing cloud infrastructure (SSRF and DNS Rebinding), the HTTP client validates the resolved IP right before opening the TCP socket and strictly blocks all redirects as well as cloud metadata endpoints (169.254.169.254, 100.100.100.200, fd00:ec2::254).
At the end of the day, the gap between a tutorial chat app and production signaling is barely visible on the happy path when two developers call each other over gigabit office fiber. Almost all the engineering effort goes into invisible defenses such as strict byte budgets on every data structure, surviving carrier CGNAT, predictable cluster behavior during hardware failures, and rejecting junk traffic before it ever allocates heap memory. When the transport layer handles those sharp edges on its own, the product code of the messenger stays clean and simple.