Long polling vs WebSockets: what broke in a multiplayer game

In 2022 I built an online party card game, in the style of Cards Against Humanity, in plain PHP, jQuery and MySQL. For live updates the choice was long polling vs WebSockets, and I went with long polling. The game worked and had 200 players online at the same time on a Hetzner server, but it was held together with duct tape. Long polling is fine when updates are rare and go one way. In a multiplayer game, where many players change shared state every few seconds, it broke in four places, and today I’d build the same game on WebSockets.

Key takeaways

  • Long polling keeps an HTTP request open until the server has news. In PHP each waiting client also holds a worker the whole time.
  • The game checked the database every 0.6 s for every player: about 1,000 queries per second at 200 players, just to ask “anything new?”.
  • Detecting changes by comparing timestamps brought lag and a game state that drifted apart between players.
  • WebSockets cost more to set up, but the server pushes one event to the whole room the moment it happens.
  • Pick long polling for rare, server-to-client updates or locked-down networks. Pick WebSockets for anything interactive.

How long polling worked in my game

The client sent a request to game_polling.php and the server did not answer until something changed. Inside, a while (true) loop checked the lobby every 0.6 seconds:

while (true) {
    // ... is the player still in the lobby? did the lobby reset?
    $sql = "SELECT * FROM lobby WHERE (last_change > :time_change
            OR last_change_players > :time_change2
            OR last_change_round > :time_change3) AND lobby_id = :id";
    // ... if a row came back: build the response, echo it, exit

    if ($counter == 3600) {
        echo $time;
        exit();
    }
    usleep(600000);
}

After 3,600 passes, about 36 minutes, with no news the loop returned the old timestamp and the browser opened a new request. On the client, a jQuery $.ajax call fired polling() again after every response. Every action in the game, like playing a card, picking a winner or kicking a player, was a separate PHP script that wrote to MySQL and stamped last_change with the current time in milliseconds. The polling loops noticed the newer timestamp and sent the update out.

Sequence diagram: my game polling the server every 0.6 s next to the same flow over one WebSocket connection

Where it broke

It broke in four places: lag, database load, game state that differed between players, and patches on the client.

Lag built into the design

A change became visible only on the next pass of the loop, so up to 0.6 s late, plus the round trip and the new request the browser opened afterwards. In a game where everyone waits for the slowest card, players noticed.

The database did the waiting

Each pass ran three SELECT queries per player. At 0.6 s per pass that is about 5 queries per second per player, and with 200 players online roughly 1,000 queries per second, almost all of them answering “no, nothing changed”. On top of that, each waiting player held one PHP worker for as long as the request stayed open. RFC 6202 lists this cost among the known issues of long polling: the server keeps resources allocated for every pending request.

Game state drifted apart

Change detection compared millisecond timestamps written by different requests. A write stamped its time when its script started, but it could commit after a polling loop had already moved its own timestamp past that value, and then nobody saw the change. The end of a round was worse: one request shuffled the cards while another tried to read them. My fix, trimmed:

// Problem
$stmt->execute(['id' => $id]);
if ($stmt->rowCount() == 0) {
    usleep(100000);
    $stmt->execute(['id' => $id]);
}

It waits 100 ms and hopes the other request is done. Usually it was, but when it was not, players saw different hands.

Duct tape on the client

The client had its own patches. If the response started with <, PHP had printed an HTML error, so the client simply polled again. If the response was exactly 13 characters long, it was a timestamp, which meant “nothing happened, ask again”. Any network error showed an alert and reloaded the whole page.

Why I used long polling at all

I used long polling because I did not know WebSockets and I was a bit scared of them. Long polling let me stay inside what I already knew: plain PHP scripts and AJAX.

WebSockets do have a higher entry cost. They need a process that stays alive and keeps connections open, which a classic PHP setup with one script per request does not give you. Reconnects, heartbeats and authentication on the socket are yours to handle. And the proxy in front of the server has to pass the Upgrade handshake through.

I did not count what the shortcut would cost later. Every hour I saved by not learning WebSockets, I paid back with interest, chasing lag and game state that did not match between players.

The same game on WebSockets

With WebSockets each player keeps one connection open, and the server keeps the game state in memory, one object per room. A move arrives as a message, the server checks it against that state, applies it and pushes the result to everyone in the room. Nothing polls, and the timestamps scattered across tables give way to one source of truth.

A minimal version in TypeScript with the ws library:

import { WebSocketServer, type WebSocket } from "ws";

type Room = { players: Set<WebSocket>; version: number };
const rooms = new Map<string, Room>();
const server = new WebSocketServer({ port: 8080 });

server.on("connection", (socket, request) => {
  const roomId = new URL(request.url ?? "/", "http://localhost").searchParams.get("room") ?? "lobby";
  const room = rooms.get(roomId) ?? { players: new Set(), version: 0 };
  rooms.set(roomId, room);
  room.players.add(socket);

  socket.on("message", (data) => {
    const move = JSON.parse(String(data));
    room.version += 1;
    const update = JSON.stringify({ version: room.version, move });
    room.players.forEach((player) => player.send(update));
  });

  socket.on("close", () => room.players.delete(socket));
});

A full game validates the move and applies it to the room’s state before broadcasting. The version number lets a client that reconnects ask for what it missed. If you outgrow one server, a pub/sub channel such as Redis carries the events between instances.

Long polling vs WebSockets, and where polling and SSE fit

Direction Delay Server cost Good for
Polling client asks on a timer up to the interval a request every interval, mostly empty dashboards refreshed every minute
Long polling server answers when it has news low, plus a new request after each answer one open request per client, in classic PHP also a worker rare updates, networks that block WebSockets
Server-sent events server to client only low one open HTTP connection per client notifications, live feeds, progress
WebSockets both ways low one open connection per client, cheap per message games, chat, collaborative editing

My game needed both directions and frequent updates shared by a whole room. That is the last row.

What I would do differently

I would start with WebSockets and keep the game state in the server’s memory, not in MySQL rows with timestamps. The database would store only what has to survive a restart: accounts, card decks, finished games. And I would not let fear of a new tool make the architecture decision for me. The thing I avoided turned out to be easier than the workarounds I wrote to avoid it.

  • websockets
  • long polling
  • php
  • real-time
  • multiplayer

Written by

Bartosz Świtała

Lead Backend Developer at Full Stack House. I build NestJS backends, payments, search and integrations, and write here about what broke and what I learned.