← Back to blog

My Chess Game Worked Perfectly. Until Two People Tried Playing It.

What happens when two players try to play the same chess game? A practical look at Socket.IO matchmaking, server-authoritative state, timers, and reconnections.

Node.jsSocket.IOBackend EngineeringSystem Design Real-Time Applications

Building a chessboard was straightforward. Getting two strangers to play the same game reliably? That was a different engineering problem.

The board looked good.

The pieces moved.

The rules worked.

I could move a knight, capture a pawn, castle my king, and even get checkmated.

Everything seemed fine.

Then came the obvious next step.

What happens when someone else wants to play?

I was building a real-time multiplayer gaming platform called $Play, starting with chess.

The idea was simple: users select a game, choose a time limit, get matched with an opponent, and play.

No complicated setup. No unnecessary friction.

Just pick a game and start playing.

At least, that was the plan.

Because the moment I introduced a second player, I discovered that building a chess game and building a multiplayer chess system are two very different things.

Two Browsers. One Very Confusing Problem.

My initial setup used Node.js, Express, Socket.IO, and chess.js.

The frontend handled the board and user interactions, while the backend was responsible for matchmaking, rooms, and game state.

The flow seemed reasonable.

A player selects a time control.

The server places them in a queue.

Another player selects the same time control.

The server pairs them and creates a game room.

Simple enough.

Except during testing, two players could select the same time limit and still fail to get matched.

Both browsers loaded.

Both connections appeared active.

Both players were waiting.

And nothing happened.

That was when the real debugging started.

A working WebSocket connection doesn't automatically mean you have a working multiplayer system.

It only means the connection exists.

Everything that happens afterward is your responsibility.

Matchmaking Is More Than Finding Two Players

Consider a basic matchmaking implementation:

javascript
const queues = {
  1: [],
  5: [],
  10: []
};

function joinQueue(socket, timeControl) {
  const queue = queues[timeControl];

  if (queue.length > 0) {
    const opponent = queue.shift();

    startGame(opponent, socket);
  } else {
    queue.push(socket);
  }
}

At first glance, this looks fine.

And for a basic single-process prototype, it might be.

But there are questions the code doesn't answer.

What happens if a player clicks the matchmaking button twice?

What if someone disconnects while waiting?

What if the queue contains an old socket that no longer exists?

What happens when the application runs across multiple server instances?

And what if two matchmaking workers attempt to claim the same player?

These aren't theoretical concerns when you're designing a system expected to support real users.

For $Play, the matchmaking rules needed to be explicit.

Players choosing one-minute games should only match with other players choosing one-minute games.

The same applies to five-minute and ten-minute games.

Each player should exist in only one queue or active game at a time.

And once two players are matched, they need to be removed from the queue before another match can claim them.

This is where matchmaking stops being a simple array operation and starts becoming a state-management problem.

A better way to think about the queue

Rather than treating matchmaking as a collection of socket IDs, think of each player as having a lifecycle.

idle → queued → matched → playing → finished

Every transition should have rules.

For example:

  • A queued player cannot join another queue without leaving the first.
  • A matched player cannot be matched again.
  • A disconnected player must not remain available for matchmaking.
  • A game should not begin until both players have been assigned valid roles.

For a single Node.js process, you can enforce these rules with carefully managed in-memory state.

When scaling across multiple instances, however, you'll likely need shared coordination through something like Redis, with atomic operations to prevent duplicate claims.

The important part isn't which database you choose. It's making sure the same player can't exist in two games at once.

The Server Has to Be the Referee

Here's another interesting problem.

Imagine two players are connected to the same game.

Player A moves a pawn.

Their browser updates the board.

A Socket.IO event notifies Player B.

Player B's browser updates its board.

Everything looks synchronized.

But what happens if Player A modifies the JavaScript running in their browser?

What if they send a move that isn't legal?

Or attempt to move twice before their opponent responds?

If the frontend decides what's valid, the game is only as trustworthy as the browser running it.

And browsers belong to users.

That means users can modify them.

The solution is to make the server authoritative.

The client should request a move.

The server should validate it.

Only then should the updated game state be broadcast to both players.

A simplified implementation might look like this:

javascript
socket.on("chess:move", ({ room, from, to }) => {
  const game = activeGames[room];

  if (!game) return;

  const playerColor = game.roles[socket.id];

  if (game.chess.turn() !== playerColor) {
    return;
  }

  const move = game.chess.move({ from, to });

  if (!move) return;

  io.to(room).emit("chess:state", {
    fen: game.chess.fen(),
    lastMove: move
  });
});

This illustrates the basic principle, although production code also needs to verify room membership, handle invalid move exceptions, account for promotions, and enforce game clocks.

The key idea is that the browser doesn't get to declare a move valid.

The server does.

And once the server accepts the move, every connected player receives the same authoritative state.

That single architectural decision eliminates an entire category of synchronization and cheating problems.

Then Came the Chess Clocks

Chess becomes considerably more interesting when time is involved.

For $Play, I wanted players to choose between one-minute, five-minute, and ten-minute games.

Both players should see both clocks.

White's timer starts first.

After White makes a valid move, White's clock stops and Black's begins.

Then the process repeats.

Sounds straightforward.

But here's the catch.

Two browsers don't necessarily agree on what time it is.

A browser tab might be throttled.

A device might briefly lose connectivity.

One player's computer might be running slowly.

If both clients independently calculate the remaining time, their clocks can drift apart.

And in a one-minute chess game, even a small discrepancy can matter.

A more reliable approach is to make the server responsible for timekeeping.

Instead of trusting the browser's countdown, the server tracks the active player's remaining time and when their turn began.

Conceptually:

javascript
function getRemainingTime(game, now) {
  const elapsed = now - game.turnStartedAt;

  return Math.max(
    0,
    game.remainingMs[game.activeColor] - elapsed
  );
}

When a valid move arrives, the server calculates the elapsed time, updates the player's remaining balance, switches turns, and records the new turn's starting timestamp.

Clients can still display smooth countdown animations.

But those animations are visual representations of server-controlled time, not independent sources of truth.

The server also needs an authoritative timeout mechanism, including a final deadline check before accepting a move.

Otherwise, a move that arrives after a player's time expires might incorrectly be accepted.

This is one of those situations where a feature that looks simple on the interface introduces surprisingly interesting backend problems.

What Happens When Someone Refreshes?

At some point, every web developer learns that users will do things you didn't expect.

Refresh the page.

Close the tab.

Switch networks.

Lose internet connectivity.

Open the same application in another browser.

In a traditional website, refreshing usually isn't a major problem.

In a live multiplayer game, it can be.

Socket.IO connections have socket IDs, and reconnecting generally creates a new connection identity.

So if your game identifies players only by their current socket IDs, refreshing can make an existing player appear to be a stranger.

Your server might still have the original game running.

But the returning player no longer has the same socket ID.

Now what?

For $Play, I explored storing the player's room and role in localStorage to help restore the game interface after refresh.

That's useful for client-side recovery.

But it also exposes an important architectural distinction.

Remembering a room isn't the same as proving you belong to it.

A browser can modify localStorage.

So the server shouldn't blindly trust a client that claims to be White in a particular room.

A stronger reconnection design uses an authenticated player identity or a securely issued, validated reconnect token.

The server can then associate the new socket connection with the original player.

Once verified, the returning player receives the current authoritative game state.

The board is restored.

The clocks are synchronized.

And the game continues.

This is the difference between making reconnection appear to work and designing reconnection to work reliably.

A Room Is Not a Game

Socket.IO rooms are incredibly useful.

They allow you to group connections and broadcast events to specific participants.

For example:

javascript
io.to(roomId).emit("chess:state", gameState);

But a room is primarily a messaging mechanism.

It isn't automatically a complete game model.

A real game needs more information.

Who are the players?

Who is White?

Who is Black?

Whose turn is it?

How much time remains?

What was the last valid move?

Has the game ended?

What happens if a player disconnects?

All of this belongs in an explicit game state.

For a small prototype, an in-memory object can work.

But as the platform grows, you have to consider persistence, process crashes, and running multiple server instances.

If the entire game exists only in one Node.js process, restarting that process means losing the game state.

And if another server instance receives a reconnecting player, it may not know the game exists.

That's where architecture becomes important.

A persistent game record, shared coordination layer, and well-defined recovery strategy can help make the system resilient.

Not every application needs all of that on day one.

But knowing when you'll need it is part of building software that can grow.

The Bigger Lesson: Build the System, Not Just the Feature

One reason I find multiplayer engineering interesting is how quickly a small feature forces you to think about larger systems.

Matchmaking introduces concurrency.

Game rooms introduce state management.

Chess clocks introduce time synchronization.

Reconnections introduce identity and recovery.

Multiple server instances introduce distributed coordination.

And suddenly, a simple chess application becomes a practical lesson in backend architecture.

The same principles apply elsewhere.

A ride-hailing platform matching drivers with passengers.

A marketplace connecting buyers and sellers.

A collaborative editor synchronizing changes.

A trading application broadcasting live market data.

Different products.

Similar engineering questions.

Who owns the state?

Who has authority to change it?

What happens when two events occur simultaneously?

What happens when a connection disappears?

And how does the system recover when something fails?

These are the questions that make backend engineering interesting.

Would I Build It Differently Today?

Absolutely.

I'd start by defining the player and game state transitions before implementing the matchmaking interface.

I'd separate matchmaking logic from game-specific rules so that chess, checkers, tic-tac-toe, and future games could share the same underlying infrastructure.

I'd treat reconnection as a core requirement rather than something to address later.

And I'd design the system around one principle:

The server owns the truth. The client displays it.

That doesn't mean every application needs microservices, Kubernetes, Redis clusters, and a complicated distributed architecture from the beginning.

Sometimes a well-structured Node.js monolith is exactly the right choice.

The goal isn't to build the most sophisticated system.

It's to build the simplest system that handles the failures you reasonably expect.

Because the most important test of a multiplayer game isn't whether the pieces move.

It's whether two real people can play, disconnect, reconnect, and finish a match without the system losing track of what's happening.

And that, as it turns out, is a much more interesting engineering problem than drawing a chessboard.

If you've built a real-time application before, what caused you more trouble: synchronization, reconnections, or concurrency?

I'd be interested to hear how other developers approached these problems.