cd /news/developer-tools/two-postgres-deadlocks-one-rule-lock… · home › topics › developer-tools › article
[ARTICLE · art-177905] src=dev.to ↗ pub= topic=developer-tools verified=true sentiment=· neutral

Two Postgres deadlocks, one rule: lock the region first

A developer building Last Thaw, a free browser strategy game with up to 100 players across 408 map regions, fixed two Postgres deadlocks caused by inconsistent row-lock ordering in its region-settlement transactions. The root cause was a training-order path that locked its own region first before locking other regions, conflicting with homecoming-army and loyalty passes that lock regions in ascending id order; the fix makes any order that may draw resources from other regions lock all of the player's regions up front in ascending order. The deadlocks appeared 14 times in one night's match and were only caught by reading the Postgres log, since the worker's retry masked the failures.

recommendation

Audit every transaction that locks more than one row and make them acquire locks in one consistent order, then review the Postgres log nightly since retries can hide deadlocks.

more in playbook: Running AI in production
by read7 min views4 publishedNov 28, 2026

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.

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
}

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.

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

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)));

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.

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

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));

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.

"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

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.

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;
}

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

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.

── more in #developer-tools 4 stories · sorted by recency
── more on @last thaw 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/two-postgres-deadloc…] indexed:0 read:7min 2026-11-28 · —