Realtime Matchmaking

Why multiplayer lobbies use WebSockets instead of normal HTTP requests.

The idea

When you click "Find Game", you enter a matchmaking queue. The server needs time to find 9 other players at your skill level. Normal HTTP is designed for quick questions: "Give me this webpage" → "Here it is." If the server takes 30 seconds to find a match, a normal HTTP request will time out, and your browser will disconnect. To solve this, games use WebSockets: a persistent, two-way tunnel. The client says "I'm looking for a game" and then just sits there. Whenever the server is ready, it pushes a "Match Found!" message directly down the tunnel to the client.

Step 1: HTTP Polling (Bad). The client asks "Found a match?" every second. It wastes battery and server CPU.

How it works (The WebSocket Upgrade)

A WebSocket starts as a normal HTTP request. The client asks the server to "upgrade" the connection. If the server agrees, they drop the HTTP protocol and keep the underlying TCP socket open indefinitely. Both sides can now blast binary or JSON messages to each other at any time, instantly, with almost zero overhead.

// 1. Client connects via WebSocket (ws://)
const socket = new WebSocket('ws://game.com/matchmake');

// 2. Client sends a message to enter queue
socket.onopen = () => {
    socket.send(JSON.stringify({ action: "join_queue", elo: 1500 }));
};

// 3. Client waits passively. Zero CPU/Network usage.
socket.onmessage = (event) => {
    const data = JSON.parse(event.data);
    if (data.type === 'MATCH_FOUND') {
        connectToGameServer(data.ipAddress);
    }
};

Cost

WebSockets require Stateful Servers. With HTTP, any load balancer can send your request to any server. With WebSockets, your specific TCP connection is tied to Server #4. If Server #4 reboots, your connection breaks and you are dropped from the queue. Scaling WebSockets requires complex tools (like Redis Pub/Sub) to synchronize state across all the different matchmaking servers.

Watch out for