One-to-One Chat
WhatsApp utilizes a lightweight protocol called Gateway to enable fast and efficient one-to-one chatting between users. When a user opens WhatsApp, their device connects to one of WhatsApp's global server clusters closest to their location.
Each server cluster contains thousands of Gateway messaging servers. These Gateway servers maintain persistent sockets to each connected device. When User 1 sends a chat message to User 2, their device sends the encrypted message payload over the existing socket to the Gateway server. The Gateway looks up the recipient's device socket connection and forwards the message.
This direct socket-to-socket architecture removes unnecessary HTTP and TCP overhead that would otherwise be incurred if using traditional REST APIs. It allows WhatsApp to handle over 100 billion messages per day with low latency.
To track mappings between users and Gateway servers, WhatsApp employs a distributed NoSQL database. It maintains a real-time mapping table with entries such as:
1User1ID -> Gateway1
2User2ID -> Gateway2
When User1 sends a message to User2, the database is quickly queried to find the recipient Gateway2 server. The message is then forwarded to Gateway2 which delivers it over the existing socket to User2's device.
WhatsApp redundantly stores the mapping database across its server clusters to maintain high availability. The databases are kept in sync using an optimized replication protocol. If any Gateway server fails, user-to-gateway mappings are quickly recovered from replicas. This delivers enterprise-grade reliability despite the large and growing user base.
Thus, WhatsApp achieves fast 1-to-1 messaging for over 2 billion users by:
- Maintaining persistent device sockets
- Removing overhead through a lightweight Gateway protocol
- Storing real-time user-to-gateway mappings
- Replicating mapping data for high availability
This socketed architecture scales easily for 1-to-1 chats while minimizing latency and infrastructure costs.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.