DEV Community

Matt
Matt

Posted on

Two Postgres deadlocks, one rule: lock the region first

I make Last Thaw, a free browser strategy game. Up to a hundred players start with five settlers on a real map of Earth, cut into 408 regions, and have 30 real days to build an empire while an ice age advances from both poles. It's in early access and I'm looking for people to test it.

Nothing in the game waits for a player to be online. Builds finish, convoys arrive and armies come home on timers, and a worker process settles each of those in its own Postgres transaction. Players and AI tribes send commands through the API at the same time. So at any moment there are several transactions that all want the same handful of rows.

Twice in the past month, two of them wanted the same rows in opposite orders. Postgres did what it does: it picked one, killed it and wrote deadlock detected in its log. Both times the fix was a few lines. The lesson was that a lock order is only a rule if every code path follows it, including the ones you wrote before you had the rule.

Why a region is a lock

A region's stores (wood, stone, food and so on) aren't updated every second. The row holds what was there at settledAt, and anything that touches the region first brings it up to date. That read-then-write has to be atomic, so every path goes through one function:

export async function settleAndLockRegion(tx: Tx, matchId: string, regionId: string, asOf: Date, speed: number, resourceMult = 1) {
  const rows = await tx
    .select()
    .from(matchRegions)
    .where(and(eq(matchRegions.matchId, matchId), eq(matchRegions.regionId, regionId)))
    .for("update"); // row lock, held until the transaction ends
  const row = rows[0];
  if (!row) throw Object.assign(new Error("region not found"), { statusCode: 404 });
  if (asOf.getTime() <= row.settledAt.getTime()) return row; // already up to date
  // ...project production forward to asOf and write it back
}
Enter fullscreen mode Exit fullscreen mode

SELECT ... FOR UPDATE is the whole concurrency story for a single region. Two transactions that want the same region line up, and the second one sees what the first one wrote. I wrote about the settle-on-read idea in an earlier post in this series.

The trouble starts when one transaction needs two regions.

Deadlock one: a training order and an army coming home

Training soldiers costs materials. If the region doesn't have enough, the order can be supplied from your other regions, the same way a build can. So the first version of queueTrain did the natural thing: lock the region the order is for, check the stores, and only if they fall short, lock the rest of your regions to see what they can send.

Now picture a transport coming home at the same moment. Its transaction locks regions too, and so does the pass that works out loyalty in occupied regions. Those take their regions in ascending id order. The training order took its own region first, wherever that fell in the order, and the others after.

training order:    locks region 212 ... then wants region 087
homecoming army:   locks region 087 ... then wants region 212
Enter fullscreen mode Exit fullscreen mode

Neither can finish. Postgres notices after its deadlock timeout and aborts one of them.

This showed up 14 times in one night's match. Nobody lost anything, because the worker retries a failed job and the retry went through. I only knew because I go through the Postgres log every night. If I hadn't been reading that log I'd have shipped it for months.

The fix is to decide up front whether the order might need other regions, and if so take all of them in the one order everything else uses:

// An order that may be supplied from other regions locks every region of mine up front,
// in ascending order like a build.
const canWait = opts.allowWait ?? true;
const mine = canWait
  ? await tx
      .select({ regionId: matchRegions.regionId })
      .from(matchRegions)
      .where(and(eq(matchRegions.matchId, m.id), eq(matchRegions.ownerPlayerId, p.id), isNull(matchRegions.frozenAt)))
      .orderBy(asc(matchRegions.regionId)) // the same order every other transaction uses
  : [];
const locked = new Map<string, MatchRegionRow>();
for (const r of mine) locked.set(r.regionId, await settleAndLockRegion(tx, m.id, r.regionId, now, m.speed, resourceMultOf(m)));
const row = locked.get(regionId) ?? (await settleAndLockRegion(tx, m.id, regionId, now, m.speed, resourceMultOf(m)));
Enter fullscreen mode Exit fullscreen mode

It locks more than it strictly needs when the region can pay on its own. I'm fine with that. It's a short list and the transaction lasts milliseconds. Locking lazily was the optimization that caused the bug.

Deadlock two: a convoy and a build

A few weeks later, a different pair. This time it wasn't two regions. It was a region and a materials route, the row that tracks goods set aside in one region for a build in another.

A build that needs supplies locks the destination region, then adds to (and locks) the route that feeds it. Regions first, then routes. That was the order I'd settled on after the first deadlock.

A convoy arriving with those supplies was older code. It credited each route with what it had carried, and then locked the destination region to unload:

build request:     locks the region ... then wants the route
arriving convoy:   locks the route  ... then wants the region
Enter fullscreen mode Exit fullscreen mode

Same shape, different tables. One deadlock in a night, retried, nothing lost. The fix was to take the region lock before the loop that touches the routes, and reuse it afterwards:

// The region before its routes, the order a build or training order takes them in.
arrivedAt = await lockRegion(tx, m, army.targetRegionId, at);
const relayed: Record<string, number> = {};
for (const s of stops) {
  if (!s.routeId) continue;
  // ...credit the route with what the convoy took from it
}
// ...
const target = arrivedAt ?? (await lockRegion(tx, m, army.targetRegionId, at));
Enter fullscreen mode Exit fullscreen mode

Five lines in, one out. Finding them meant reading the two statements Postgres prints for each side of a deadlock and working out which function each one came from.

Testing a lock order

"It didn't deadlock when I ran it" proves nothing, because a deadlock needs two transactions to interleave in exactly the wrong way. So the tests don't try to cause a deadlock. They check the order directly: hold the lock that should be taken first, start the code under test, and check that it's waiting without holding anything that should come later.

// Hold the destination region in a transaction of our own.
const holder = db.transaction(async (tx) => {
  await tx.select().from(matchRegions).where(/* region D */).for("update");
  locked();
  await released;
});
await isLocked;

const delivery = skip(convoy.arrivesAt.toISOString()); // the convoy arrives now
await new Promise((r) => setTimeout(r, 750));

// Every route into D must still be free: SKIP LOCKED returns only rows nobody holds.
const free = await db.transaction(async (tx) =>
  (await tx.select({ id: tradeRoutes.id }).from(tradeRoutes).where(/* routes to D */).for("update", { skipLocked: true })).length);
expect(free).toBe(before);

release(); // let go of the region
await holder;
await delivery; // and the delivery goes through
Enter fullscreen mode Exit fullscreen mode

FOR UPDATE SKIP LOCKED is the useful trick here. It's meant for job queues, but it also answers "is anyone holding this row right now?" without blocking the test. On the old code this fails: the convoy is holding its routes while it waits for the region. The 750 ms sleep is the one part I don't love, but it only has to be long enough for the delivery to reach its first lock.

The command that vanished

There was a third thing in that log, a day after the convoy fix. A deadlock took an AI tribe's command as its victim. AI tribes use the same commands as humans, and a failed command is normally just the tribe guessing wrong (not enough wood, region changed hands), so failures were dropped quietly. This one was dropped quietly too. Postgres logged it, my app didn't, and I couldn't tell which match or tribe it was.

Now a refusal by the game's rules and a failure of the server are told apart:

try {
  await fn();
  return true;
} catch (err) {
  // Rule refusals carry a statusCode. Anything else is the server's own fault: say so.
  if (typeof (err as { statusCode?: unknown } | null)?.statusCode !== "number")
    log.warn({ err, ...who, proc: "ai" }, "ai command failed");
  return false;
}
Enter fullscreen mode Exit fullscreen mode

It hasn't fired since. If it does, I'll know which two code paths to read.

What I'd tell myself a month ago

  • Write the lock order down in one sentence. Mine is: regions in ascending id order, then routes. The Postgres docs on deadlocks say the same thing in general terms, and I'd read it and nodded and still got it wrong twice.
  • Lazy locking breaks the order. "Lock the one I need, and more only if it turns out I need them" is how both bugs got in.
  • Retries hide deadlocks. They're the reason no player noticed, and the reason I nearly didn't either. Read the database's own log.
  • Test the order, not the deadlock.

If you'd like to see what all those convoys and training orders look like from the player's side, the game is here and the how to play page covers convoys and builds. A running match takes new tribes for its first week, so you can start today. Feel free to borrow the lock-order test for your own code.

Top comments (0)