01 One game, several hands

When you play a grid live in a team, there is only one game in the database: the team's, which the Team model designates with its holder field. Each teammate writes to it from their phone, and each answer (Guess) keeps in author who played it. The other members' games are only pointers to that one, with no answers of their own. When the server loads a member's state, it follows that pointer:

PYTHON
@classmethod
def load(cls, player, grid):
    game = player_games().filter(player=player, grid=grid).first()
    if game is not None and game.is_live_member:
        game = player_games().filter(pk=game.team.holder_id).first() or game
    return cls.for_grid(grid, game, player)

This is what makes multiplayer easy to follow: one score, one error counter, one grid. But it is also what creates the problem. Alice and Bob both see the “Line 4 × Left bank” cell empty. Alice types Saint-Michel, Bob types Odéon, a few milliseconds apart. Both answers are right. Which one fills the cell?

A move, on the server side, is three steps: read the game state, decide (is the cell free, does the station fit), write the answer. If the two requests run in parallel, each reads the grid before the other has written, sees the cell empty and records its answer. That is the classic “read, decide, write” race, and it results in two stations in one cell, double the points, or a database error in the middle of the game.

02 One lock per team

The fix is to make the three steps indivisible for a given team: every move of a team goes through a lock. The whole operation fits in a transaction, and the first thing it does is lock the team's row:

PYTHON
def locked_state(player, grid):
    current = Game.objects.filter(player=player, grid=grid).order_by("-started_at", "-pk").first()
    if current is not None and current.team_id is not None:
        Team.objects.select_for_update().get(pk=current.team_id)
    return GameState.load(player, grid)


def _play_team(grid, player, answers, cell, station):
    with transaction.atomic():
        state = locked_state(player, grid)
        move = play(state, answers, cell, station)
        if move.is_stored:
            guess_of(grid, state, move, state.game_id).save(force_insert=True)
            settle_team(state)
    return GuessPlay(state, move, ...)

select_for_update() translates in SQL to a SELECT … FOR UPDATE:

SQL
BEGIN;
SELECT "game_team"."id", … FROM "game_team" WHERE "game_team"."id" = 42 FOR UPDATE;
-- the game state, read again
-- INSERT INTO "game_guess" …
-- UPDATE "game_game" SET "score" = … WHERE "game_game"."id" = …
COMMIT;

The lock is placed on the team's row and held until the COMMIT. If Bob's transaction reaches the same SELECT … FOR UPDATE while Alice's holds it, PostgreSQL makes it wait. It only restarts once Alice's transaction is committed. The two moves are not played at the same time: they are played one after the other, in the order in which they got the lock.

Alice Python Bob Saint-Michel Odéon lock acquired cell filled COMMIT Bob waits for the lock correct notice: cell found lock acquired grid reloaded cell already taken cell_taken no penalty
The lock lines the two moves up one behind the other: the second sees what the first did.

Why reread the state after the lock

The order of the lines matters. The lock is taken before loading the game state, not after. PostgreSQL runs here at its default isolation level, READ COMMITTED: each query sees what was committed at the moment it starts, not at the start of the transaction. When Bob finally gets the lock, the following queries of his transaction, those of GameState.load, therefore see the answer Alice has just committed.

If I had loaded the state first and locked afterward, Bob would have waited for the lock holding an already stale grid, and he would have written his answer over Alice's. A lock only protects what is read after taking it.

Why the team, and not the game

I could lock the row of the shared game. But each member arrives through their own game, the one that points to the shared game, and I would first have to follow that pointer without a lock to know what to lock. The team's row, on the other hand, is reached directly from the member's game (team_id) and never changes identity: all members lock the same row, always. Hints (_hint_team) and giving up (_give_up_team) take the same lock, so a hint and a move don't cross either, and a game can't be given up twice.

The lock covers a single team. Other teams and solo games never wait for it. The transaction is short: one read of the state, one insert, one score update.

Synchronous code in an asynchronous application

The whole application is asynchronous: the FastAPI routes call Django's ORM with its a* methods (aget, acreate…). But Django's transactions only work in synchronous code, because transaction.atomic() is tied to the current thread's connection. A team's move is therefore written in synchronous code and called through sync_to_async, which runs it in a thread with its own connection:

PYTHON
async def play_guess(grid, player, answers, cell, station):
    state = await GameState.aload(player, grid)
    if state.team_id is not None and not state.is_over:
        return await sync_to_async(_play_team)(grid, player, answers, cell, station)
    ...

The first aload, with no lock, only serves to pick the path: team or solo. The state that counts is the one _play_team rereads under the lock.

03 The first one wins, the second loses nothing

Once under the lock, Bob's move goes through the play function, the same one as for any move. The checks happen in this order:

PYTHON
if state.is_over:
    return move(GuessResult.GAME_OVER)
if cell in state.cells:
    return move(GuessResult.CELL_TAKEN)
if station.pk in state.cells.values():
    return move(GuessResult.ALREADY_USED)
if station.pk in answers[cell].counts:
    ...  # the cell is filled, the points count
    return move(GuessResult.CORRECT, ...)
state.errors += 1
return move(GuessResult.WRONG, -ERROR_PENALTY)
Situation Result Effect
The game is already over game_over nothing is recorded
The cell is already filled cell_taken nothing is recorded
The station is already placed elsewhere already_used nothing is recorded
The station fits correct the cell is filled, the points count
The station doesn't fit wrong one error, −20 points

The order matters: the taken cell is tested before the validity of the station. Bob lands on the second line, whether his answer is right or wrong. His move is not recorded (move.is_stored is false), the cell keeps Alice's answer, and above all he loses neither a point nor an attempt. He didn't make an error: he was beaten to it. If Alice and Bob place the same station in two different cells, the second gets already_used, with no penalty either.

For the API, this is not an error. POST /api/grids/{grid_id}/guesses responds normally (200), and the response simply says that nothing changed:

JSON
{
  "result": "cell_taken",
  "points": null,
  "score": 245,
  "errors": 1,
  "hints": 0,
  "found_count": 4,
  "restarts_count": 0,
  "cell": null,
  "board": null,
  "open_counts": [[3, 0, 5], [2, 4, 1], [6, 2, 3]],
  ...
}

The counters (found_count, errors, hints, restarts_count) are those of the shared game after the move, so they include Alice's answer. You'll see below why that is useful.

04 What Bob sees

Publishing after the COMMIT

Once Alice's move is played, the route publishes a notice to Redis, which the live server passes on to the teammates' pages. This publication happens after the transaction, once _play_team has returned:

PYTHON
played = await services.play_guess(grid, player, answers, cell, station)
...
# What the live server must tell the others, published once the move is committed (it is).
await live_bus.publish(*messages)

This is deliberate. If the notice went out before the COMMIT, Bob's page could reload the grid and not find Alice's answer there yet. Published afterward, a notice always describes a state that a database read can confirm. A refused move (cell_taken, already_used) publishes nothing: it changed nothing.

A delta, and counters that must follow each other

The notice of a team move carries a delta: the cell found and its author, the score, the counters, the number of answers still open in each cell. Bob's page applies it without asking the API for anything. But first it checks that this delta follows exactly what it is showing:

TYPESCRIPT
export const deltaVerdict = (board: Board, delta: BoardDelta): DeltaVerdict => {
  if (delta.restarts_count !== board.restarts_count) return "gap";
  const found = delta.found_count - boardCellsFound(board);
  const errors = delta.errors - board.errors;
  const hints = delta.hints - board.hints;
  if (found <= 0 && errors <= 0 && hints <= 0) return "stale";
  const steps = [found, errors, hints];
  if (steps.every((step) => step === 0 || step === 1) && steps.filter((step) => step === 1).length === 1) return "apply";
  return "gap";
};
  • apply: a single counter moves forward, by exactly one. It is the next move, the page applies it and animates the cell.
  • stale: the page already has all of this. It is a duplicate, or a move it has already received by another path. It ignores it.
  • gap: something is missing in between. A message was lost, or the team restarted the grid. The page reloads the grid from the API.

When Bob's response arrives before the notice

Nothing guarantees the order of arrival between Bob's HTTP response and the WebSocket notice of Alice's move. The notice can even be lost: Redis keeps nothing, and publishing never raises an error. Bob's response is then enough to notice, thanks to its counters:

TYPESCRIPT
export const ownMoveSkipped = (before, counters, move): boolean => {
  if (counters.restarts_count !== before.restarts_count) return true;
  const found = boardCellsFound(before) + Number(move === "found");
  const errors = before.errors + Number(move === "missed");
  const hints = before.hints + Number(move === "hint");
  return counters.found_count !== found || counters.errors !== errors || counters.hints !== hints;
};

For a refused move, move is "none": the page expects unchanged counters. But the response says found_count: 4 while the displayed grid has only 3 cells filled. A move went through in the meantime that the page didn't see: it reloads the grid, and Alice's station appears.

Finally, the page shows a line in the team feed: “Alice found it just before you”. It finds the author in the grid, through the cell's found_by field (the friend code of whoever found it). If it doesn't know them yet, the line becomes “A teammate found it just before you”. And if it was Bob himself who had placed this station elsewhere, it says nothing: this isn't a race, just a station already used. No error message, no cell flashing red.

The best thing is still to avoid the race. When a teammate opens a cell, the others see it light up on their grid. This signal only goes through the live server, without touching the database, and it is often a sign that it's better to look elsewhere.

05 And solo, on two tabs?

A game played solo takes no lock. Only one person plays, and their moves stay asynchronous, with no thread or transaction. But nothing stops you from opening the grid on your phone and on your computer, and playing the same cell on both.

There, the database decides, with two partial uniqueness constraints on the answers:

PYTHON
class Meta:
    constraints = (
        # A cell is found once per game, and a station fills one cell per game.
        models.UniqueConstraint(
            fields=("game", "row", "col"),
            condition=models.Q(correct=True),
            name="unique_found_cell",
        ),
        models.UniqueConstraint(
            fields=("game", "station"),
            condition=models.Q(correct=True),
            name="unique_found_station",
        ),
    )

In PostgreSQL, each becomes a unique index with a WHERE clause:

SQL
CREATE UNIQUE INDEX "unique_found_cell" ON "game_guess" ("game_id", "row", "col") WHERE "correct";

Partial, because a cell can receive several wrong answers, but only one right one. If two right answers arrive at the same time, PostgreSQL refuses the second insert with an IntegrityError. The server doesn't let it bubble up as a 500 error: it rereads the state and replays the move.

PYTHON
move = play(state, answers, cell, station)
try:
    guess = await save_guess(grid, state, move)
except IntegrityError:
    state = await GameState.aload(player, grid)
    move = play(state, answers, cell, station)
    guess = None

Replayed on the up-to-date state, the move lands on cell_taken or already_used, exactly as in a team. It is the optimistic version of the same idea: instead of preventing the race, I let it happen and let the database refuse the loser. That is enough when races are rare, which is the case for a single person.

A known limit

These constraints only cover right answers. Two wrong answers sent at exactly the same time from two tabs are both recorded, and count as two errors. That is the normal case: two wrong answers are still two wrong answers. But they don't go through one after the other, so each can read “2 errors” before the other has written. The game can then end with 4 errors, when it should have stopped at the third. You have to play on two screens in the same millisecond to get there, and it only costs you.

06 How I test it

Two tests cover these cases. The first plays in a team: the owner finds a cell, then their teammate places another station in it, with a page that doesn't know anything yet.

PYTHON
taken = await _play(friend, today, {"row": 0, "col": 1, "station": other.pk})
assert taken["result"] == "cell_taken"
assert taken["points"] is None
assert taken["errors"] == before["errors"]
assert bus.messages == []  # nothing happened: nothing to tell

The second reproduces the race of a solo game without needing two simultaneous requests. It replaces save_guess with a version that records the answer, as if the other request had gone first, then raises the IntegrityError that PostgreSQL would have raised:

PYTHON
async def racing(grid, state, move):
    await real(grid, state, move)  # the other request wrote it first
    raise IntegrityError("unique_found_cell")


monkeypatch.setattr(services, "save_guess", racing)
out = await _play(client, today, solutions[0][0])
assert out["result"] == "cell_taken"

Both tests check the logic of each path. Neither launches two truly concurrent transactions against the lock: there, PostgreSQL does the work, and SELECT … FOR UPDATE does what it has long promised.