Blog › Random matching on Socket.IO: how the queue works and where it gets fragile

Random matching on Socket.IO: how the queue works and where it gets fragile

By Gowrishankar Rangasamy · · Updated

Pairing two strangers sounds like a hard problem. In practice the core is about forty lines of server code. The difficult parts are everything around those forty lines. This is a description of how the matching in Chatzyo works, written for someone who might build something similar. It is also an honest list of where the design gets fragile.

The server is Node.js with Socket.IO. Its only job in a video chat is to introduce two browsers and relay their set-up messages. After that, the video travels directly between them over WebRTC (the how it works page explains that part for non-developers).

The waiting list

The whole of matching is one array of sockets, in order of arrival. When a client asks for a partner (the event is find-video), the server runs roughly this:

function tryMatch(socket) {
  if (inRoom[socket.id]) return;                 // already paired
  waiting = waiting.filter(s => s.id !== socket.id);

  let partner = null;
  while (waiting.length) {
    const candidate = waiting.shift();
    if (candidate.connected && candidate.id !== socket.id) { partner = candidate; break; }
  }
  if (!partner) { waiting.push(socket); socket.emit("video-waiting"); return; }

  const room = `video_${socket.id}_${partner.id}`;
  socket.join(room); partner.join(room);
  inRoom[socket.id] = inRoom[partner.id] = room;
  socket.emit("video-matched", { roomId: room, initiator: true });
  partner.emit("video-matched", { roomId: room, initiator: false });
}

Three details in there do real work.

The connected check. Phones lose signal, laptops sleep and tabs get closed. A socket can sit in the waiting list long after its owner has gone. Without the check, the next person would be paired with a ghost and see an empty screen. The check skips the dead entries as it goes.

The initiator flag. Two browsers setting up a WebRTC call must not both send an offer; they would collide. The server settles it before either browser knows the other exists: the person who arrived second, who found someone waiting, is the initiator and makes the offer. The first-comer waits and answers. Nobody negotiates, and exactly one offer exists.

The room name. The room is named from the two socket IDs, so it's unique, and every later message can be addressed with one room ID. The server only relays WebRTC set-up messages for a socket that is in that room.

The 300 ms guard

Each socket remembers the time of its last Start or Next. A request within 300 milliseconds is ignored, silently. The effect is that a rapid double-click can't skip a new person before they have even appeared. The cost is that an ignored request never produces an error, so a client that sends two actions quickly can end up stuck in a state it didn't expect. Any client must space its actions out; I make mine wait 500 ms.

The server resets the guard at the moment a match is made, so a person can leave straight away if the match looks wrong.

Skipping

When someone skips, the server tells their partner, removes both from the room, and puts the skipper back through the matching function after about 100 ms. The delay lets the room cleanup finish first.

The partner is not re-queued by the server. Their browser has to ask again. That's a deliberate simplicity, but it has consequences listed next.

Where it gets fragile

I'm listing these because most tutorials on building a random chat stop before this section.

1. All of it lives in memory. The waiting list, the room map and the pairing records exist only in the server's memory. If the process restarts, everything is gone and nobody is told. A separate article looks at this in detail.

2. A reconnecting client is a new person to the server. When a connection drops and returns, Socket.IO gives it a new ID. The server has no record of the old one. A client that doesn't notice this and doesn't ask for a match again simply waits forever. Mine re-sends its request on every connect while it wants a partner.

3. The person who stays isn't re-queued. If a client forgets to ask again after its partner leaves, it stays on a frozen screen. The server never notices, because as far as it knows, that person left the room cleanly.

4. Skipping doesn't avoid past partners. The queue is first-come, first-served. With few people online, skipping can return you to the person you just left. The server does remember recent partners for a couple of minutes so that a report can be checked, and a person you report or block is kept out of your matches, but nobody else is. The Next article describes how.

What I'd change in a stricter version

None of this is exotic. It is the work that sits between a demo that pairs two tabs and a service people can lean on. If you want to know what the person at the other end of a match sees when you press Next, that's in what happens when you press Next.