FOUNDING PRICING · 40% OFFfor the first 1,000 members · from ₹95/month
ArchitectureWhatsApp11 min read

How WhatsApp Scaled to 450 Million Users with Erlang

How WhatsApp used Erlang, FreeBSD and a store-and-forward design to hold over two million connections per server with a very small engineering team.

ShareXLinkedInWhatsApp
A hand holding a smartphone, with a takeaway coffee cup in the foreground.
A hand holding a smartphone, with a takeaway coffee cup in the foreground. Photo: www.Pixel.la Free Stock Photos, CC0, via Wikimedia Commons.

In February 2014, when Facebook announced it was buying WhatsApp, the company's investor Sequoia Capital published two numbers side by side: more than 450 million active users, and 32 engineers. Two years earlier WhatsApp had shown a single server holding over two million open TCP connections. This post explains how that was possible: a runtime built for millions of tiny concurrent tasks, an operating system tuned by people who measured everything, and a product design that kept the server's job small.

A message from phone A reaches an Erlang process on the chat server, which either passes it to the process holding phone B's connection or queues it in a transient offline store until B reconnects.

A note on sources before we start. WhatsApp has published very little about its internals. Almost everything here comes from two short posts on the company's own blog (2011 and 2012), the slides and abstracts of conference talks by WhatsApp engineer Rick Reed (2012 and 2014), and detailed notes on those talks published by High Scalability. All figures are from that period, roughly 2011 to 2014, and say nothing reliable about how WhatsApp runs today.

The problem: millions of phones that mostly sit idle

A chat server has an unusual workload. Every phone with the app open keeps a long-lived TCP connection to the server so that a new message can be pushed to it immediately. Most of those connections do nothing most of the time. A user might send a few dozen messages a day, yet the connection stays open for hours.

So the hard part is not CPU work per message. It is holding an enormous number of mostly idle connections cheaply, waking up the right one when a message arrives, and surviving sudden spikes. Reed's 2012 slides show message rates jumping during football matches and after an earthquake in Mexico: world events hit a messaging service all at once.

The classic way to serve a connection is to give it an operating system thread. That breaks down here. Each kernel thread reserves its own stack and costs a context switch through the kernel every time it runs. A million threads on one machine is not a practical design. WhatsApp needed something where the cost of one more idle connection was close to nothing.

The design: one Erlang process per connection

WhatsApp's backend ran on Erlang. According to High Scalability's 2014 write-up, the server began life as ejabberd, an open-source XMPP chat server written in Erlang, which the team then rewrote heavily over several years, replacing XMPP with its own more compact protocol.

Erlang programs run on a virtual machine called BEAM, and the unit of concurrency is the Erlang process. Despite the name, this is not an operating system process. It is a small data structure managed entirely by the VM, with its own tiny heap and its own mailbox. Creating one is cheap enough that the idiomatic design is one process per activity. For a chat server, that means one process per connected phone. (The same write-up notes that WhatsApp originally used two Erlang processes per connection and cut that to one.)

Three properties of this model matter for the WhatsApp story.

  • No shared memory. Processes communicate only by sending messages to each other's mailboxes. A chat message from A to B is, quite literally, a message sent from the process that owns A's socket to the process that owns B's socket. There are no locks in application code.
  • Preemptive scheduling inside the VM. BEAM runs one scheduler thread per CPU core and gives each Erlang process a small budget of work before moving to the next one. One busy or badly behaved process cannot starve the others, which keeps latency even.
  • Failure isolation. If the code handling one connection crashes, only that process dies. The other two million carry on. Erlang came out of the telephone exchange world, where this property was the whole point.
A technician holding a circuit board stands in front of tall cabinets of an Ericsson AXE digital telephone exchange, photographed in black and white.
An Ericsson AXE digital telephone exchange in the 1980s, the telephone exchange world that Erlang came out of. Photo: Televerkets fotokontor, CC0, via Wikimedia Commons.

Erlang also allows new code to be loaded into a running system. High Scalability reports that the team used this to push fixes without restarting servers or shifting traffic, which matters a great deal when a restart means millions of phones reconnecting at once.

The numbers WhatsApp published

DateWhat was reportedSource
Before the tuning workAbout 200,000 connections per serverReed, Erlang Factory 2012
23 September 20111,016,313 established TCP sessions on one machineWhatsApp blog
6 January 20122,277,845 open sockets on one machine, with about 42% of CPU idleWhatsApp blog
February 2012An unplanned peak of 2.8 million connections on one serverReed, Erlang Factory 2012
Early 2014About 150 chat servers, each planned for about 1 million phonesReed 2014, as reported by High Scalability

The 2012 blog post is unusually specific about the machine: 24 logical CPUs (Intel Xeon X5675), roughly 100 GB of RAM, FreeBSD 8.2-STABLE and Erlang R14B03.

Reed's slides add that a later attempt at three million connections on one box did not succeed at the time of the talk. They also make clear that these were production connections from real users, not a synthetic benchmark: the team's technique was to divert extra live traffic onto one server and watch what broke.

A bar chart of connections on one WhatsApp chat server: about 200,000 before tuning, 1,016,313 in September 2011, 2,277,845 in January 2012, an unplanned peak of 2.8 million in February 2012, and a planned figure of about 1 million phones per server in early 2014.
Reported connections per server, from the first tuning work to the 2014 planning figure

Where the limit really was: contention and kernel limits

The most instructive part of the 2012 talk is what stopped the servers at 200,000 connections. It was not memory, and it was not raw CPU. Reed summarised it as "Contention, contention, contention".

Contention means many CPU cores waiting for the same lock. A 24-core machine only helps if the cores can work independently. If every core has to take one shared lock to read the clock, set a timer or allocate memory, the cores queue up behind each other and the machine behaves like a much smaller one.

According to the slides, every step from 200,000 to 2 million connections was a contention fix, and most of them needed patches to BEAM itself, not just to WhatsApp's application code. Examples listed in the talk include:

  • reducing lock contention around the VM's time-of-day and timer handling,
  • giving each scheduler its own memory allocator instance,
  • patching Mnesia, Erlang's built-in database, so that writes to different tables could proceed concurrently,
  • partitioning in-memory tables and limiting which processes touch each partition.

The team found these with measurement, not guesswork: hardware performance counters, DTrace, and lock counting inside BEAM, which Reed's slides call invaluable. After the fixes, the slides report more than 85% CPU utilisation spread across all 24 logical CPUs, which is what near-linear multi-core scaling looks like.

Two panels compare 24 cores before and after the fixes: on the left every core queues for one shared lock used to read the clock, set a timer or allocate memory, at about 200,000 connections per server; on the right each scheduler has its own allocator and the server holds over 2 million connections.
Contention before and after: one shared lock against per-scheduler resources

FreeBSD tuning. WhatsApp ran on FreeBSD on bare-metal servers. The public material does not give a detailed technical argument for that choice, and Reed's slides say only that FreeBSD performed well alongside Erlang on many cores. It is fair to say the team knew the system deeply and used that knowledge.

The tuning falls into two groups. The first is raising limits that are set for ordinary workloads. The 2012 blog post lists kernel settings such as a maximum of 2.4 million sockets and 3 million open files, plus larger TCP hash tables so that looking up one connection among millions stays fast. Every TCP connection is a socket, every socket is a file descriptor, and default limits are far below a million.

The second group is fixing kernel hot spots. Reed's slides mention backporting a cheaper clock source so that the very frequent time-of-day calls cost less, and backporting a newer network driver after hitting stalls with the existing one.

A close view of rack-mounted servers stacked in a data centre rack, with status lights and numbered rack units.
Rack-mounted servers in a data centre. These are Wikimedia Foundation servers, shown as an illustration; they are not WhatsApp machines. Photo: Victorgrigas, CC BY-SA 3.0, via Wikimedia Commons.

Store and forward: the server keeps almost nothing

The other half of the answer is that WhatsApp asked very little of its servers. Messages were not stored centrally as chat history. The server's job was to pass a message on and then forget it.

If the recipient is connected, the message goes straight to the process holding their connection. If not, it goes into an offline queue. When the recipient's phone reconnects, the queue is drained, the phone acknowledges receipt, the acknowledgement is relayed to the sender, and the server deletes its copy. High Scalability's notes on the 2014 talk describe this offline storage as transient, and report that about half of all messages were read within 60 seconds, so a write-back cache in front of the disk served 98% of reads from memory. History lived on the phones, in a local SQLite database.

Media took a separate path. A photo was uploaded over HTTP to a separate set of multimedia servers, and the chat message carried only a link and a small thumbnail.

This design has a clear cost: a lost phone means lost history unless the user has a backup, and features such as server-side search are impossible. In exchange, the amount of state the backend must keep grows with messages in transit, not with every message ever sent.

Trade-offs and what changed later

Two details from the 2014 talk are worth noting because they cut against the headline numbers.

First, WhatsApp did not run its servers at two million connections each. By 2014 the planning figure was about one million phones per chat server. High Scalability reports the reasons: users had become more active, more work had moved onto those servers, and the team wanted headroom for peaks. A record is a demonstration of capacity, not a sensible operating point.

Second, the system was not immune to failure. The same notes describe an outage on 22 February 2014 lasting 210 minutes. The trigger was not load but a network fault that disconnected and reconnected many nodes at once, which sent an Erlang process-group library into a storm of internal messages. The team had to restart the whole cluster and then patched the library.

On team size, Sequoia's figure of 32 engineers covers all of engineering, including the mobile clients for seven platforms. High Scalability's notes suggest only about ten people worked on the Erlang servers, doing both development and operations. A small stack made this possible: one language on the server, one operating system, Erlang's built-in database for much of the metadata, rented bare-metal hardware and a product with a deliberately short feature list.

The computer science underneath

Kernel threads versus user-level concurrency. An operating system thread is scheduled by the kernel and carries a sizeable stack. Our lesson on processes vs threads covers what each one costs. Erlang processes are a form of green thread: the runtime multiplexes millions of them over a handful of kernel threads, one per core. The lesson on coroutines, green threads and event loops explains this family of designs. Erlang's version differs from Node.js style event loops in that scheduling is preemptive, so you write straight-line blocking code per connection and the VM does the interleaving.

Waiting on many sockets at once. Underneath any such runtime, something must ask the kernel which of a million sockets has data ready. Scanning all of them on each pass is hopeless, which is why operating systems offer readiness notification interfaces. See I/O multiplexing: select, poll and epoll.

Why a server is not limited to 65,535 connections. A TCP connection is identified by four values: source IP, source port, destination IP and destination port. All two million clients connect to the same server port. The limits that matter are file descriptors and memory per socket, which is exactly what the kernel settings above raise. The lesson on sockets and ports walks through this.

Store and forward. The delivery flow, with queues for offline users and acknowledgements, is the core of any messaging design. Our chat system blueprint builds it step by step.

What an interviewer could ask from this

Why not one OS thread per connection? Each thread needs its own stack and kernel scheduling. At a million connections the memory and context-switch cost dominate, even though the connections are idle. User-level processes or an event loop make an idle connection cost a small data structure.

How can one port serve two million clients? The kernel distinguishes connections by the full four-tuple, and the client side of each tuple is different. The practical limits are open file descriptors, socket buffers and kernel table sizes.

What limited WhatsApp's servers before tuning? Lock contention. Cores were waiting on shared locks in the VM and kernel, so adding cores did not add throughput until those locks were split, shortened or avoided.

How would you deliver a message to an offline user? Persist it in a per-user queue, deliver when the user reconnects, wait for the client's acknowledgement, then delete. Delivery is at-least-once, so the client must discard duplicates by message ID.

What does the actor model give you over threads and locks? No shared mutable state, so no data races in application code, and a crash is contained to one actor. The cost is that everything is asynchronous messaging, and overloaded mailboxes become the thing you must monitor.

Takeaways

  • Idle connections are a memory and bookkeeping problem, not a CPU problem. Choose a concurrency model where one more connection costs almost nothing.
  • On a many-core machine, the limit is usually contention on shared locks. Measure it before buying hardware.
  • WhatsApp's small team was the result of a small stack and a server that forgets messages once delivered.
  • Benchmark records are not operating targets. WhatsApp halved its per-server connection target to gain headroom.
  • Know your runtime and kernel well enough to patch them, or pick ones where you will not need to.

Sources

  1. WhatsApp Blog: One million! (23 September 2011)
  2. WhatsApp Blog: 1 million is so 2011 (6 January 2012)
  3. Rick Reed, Scaling to Millions of Simultaneous Connections, Erlang Factory SF 2012 (slides)
  4. Rick Reed, That's 'Billion' with a 'B': Scaling to the Next Level at WhatsApp, Erlang Factory SF Bay 2014 (abstract)
  5. InfoQ: recording of Rick Reed's 2014 talk
  6. Sequoia Capital: Four Numbers That Explain Why Facebook Acquired WhatsApp (19 February 2014)
  7. High Scalability: The WhatsApp Architecture Facebook Bought For $19 Billion
  8. High Scalability: How WhatsApp Grew to Nearly 500 Million Users, 11,000 cores, and 70 Million Messages a Second

Written by the Codevizag Academy team

An independent explainer built from the public sources listed above. Codevizag Academy is not affiliated with WhatsApp. Found a mistake? Write to support@codevizag.com.

More case studies

Understood it? Now prove it.

The lessons behind this case study are free, and 20 problems a month are judged on real test cases at no cost.

Start solving free