Redlock race condition: the lock guarded the wrong side
Short answer. A Redlock race condition can survive a lock that is held correctly. A distributed lock answers "am I the only one in here right now?" It does not answer "is the thing I read a moment ago still true?" In EduScale's battle engine, Redlock was held correctly and the state transition it wrapped still ran twice, because the decision to transition was made before the lock was taken and the write inside it had no condition. The fix that holds is a compare-and-set in Postgres (updateMany with the expected status in the where). The lock stays, but only to reduce contention.
What the code claimed
EduScale is a side project of mine: a learning platform with timed multiplayer quiz battles over Socket.io, Postgres through Prisma, and Redis for the socket adapter and a Redlock. The portfolio page for it said the lock sits around the start, submit-answer and complete handlers "so two instances can't both drive the same transition."
The lock existed. withBattleLock in Backend/src/repositories/battle/lock.ts is keyed per battle, turns a lost race into a 409, and releases in a finally. Nobody had read the state machine under it, and the sentence above was false for the first transition it names.
Read, decide, then lock
This is startBattle before commit 996ffad0, abbreviated. The file was battleRepository.ts at the time; it has since been split into repositories/battle/*.
const battle = await prisma.battle.findUnique({ where: { id: battleId }, include: { /* … */ } });
if (!battle) throw createAppError('Battle not found', 404);
if (battle.user_id !== userId)
throw createAppError('Only the creator can start this battle', 403);
if (battle.status !== 'LOBBY')
throw createAppError('Battle must be in LOBBY state to start', 400);
// … ready count, question count …
return this.withBattleLock(battleId, 10_000, async () => {
return prisma.battle.update({
where: { id: battleId },
data: { status: 'IN_PROGRESS' },
});
});
Read, decide, then lock. Two callers both read LOBBY, both pass every guard, then queue for the lock one after the other and both run the update. The lock didn't prevent the double start. It made it orderly.
It was worse than a duplicated battle:started event. update({ where: { id } }) has no condition on status at all. A start request that read LOBBY and then stalled could land after the battle had finished and flip a COMPLETED battle back to IN_PROGRESS, stranding its final leaderboard.
The fix: decide inside, and make the write conditional
Two changes, and the second one is the one that actually holds. The current startBattle in lifecycle.ts:
return withBattleLock(battleId, BATTLE_START_LOCK_TTL_MS, async () => {
const battle = await prisma.battle.findUnique({ /* … */ });
// … the same guards, now under the lock …
const claimed = await prisma.battle.updateMany({
where: { id: battleId, status: 'LOBBY' },
data: { status: 'IN_PROGRESS' },
});
if (claimed.count === 0) {
throw createAppError('This battle has already been started.', 409);
}
// …
});
updateMany with status: 'LOBBY' in the where is a compare-and-set. Postgres evaluates the condition and the write as one statement, so exactly one caller gets count: 1 whatever the lock does. If the lock lapses, or a second instance gets in anyway, the second write still matches zero rows. That is the property a lock on its own can never give you, because the lock lives in a different system from the data it is meant to protect.
battleLockSemantics.test.ts pins this. It records the order of operations and asserts the battle read happens after lock:acquire, asserts prisma.battle.update is never called for the transition, and asserts a count: 0 result becomes a 409. It runs against a mocked Prisma client, so it proves the code asks for a conditional write in the right order. The guarantee that only one conditional write wins comes from Postgres, not from the test.
Serializing is not deduplicating
completeBattle had the other half of the same mistake. It took the lock and then wrote COMPLETED, a fresh ended_at and the whole final leaderboard unconditionally. Nothing checked whether it had already run.
That matters because of what the caller does next. battleSocket.endBattle calls completeBattle and then battleRatingService.applyBattleResult, which reads each player's current rating, computes new Elo values and writes:
update: {
rating: u.newRating,
games_played: { increment: 1 },
wins: { increment: won ? 1 : 0 },
losses: { increment: won ? 0 : 1 },
// …
}
A second completion isn't a harmless repeat. It applies a second Elo delta on top of the first and adds a game nobody played to every record.
And the second completion is the ordinary case. Two paths reach endBattle: the answer-submitted handler and the question-expiry timer. Both await checkAllParticipantsDone, a database round trip, and the answer handler only clears the timer after that await resolves, so the timer can fire inside the window. In a two-player battle where both players answer the last question at about the same moment, both submissions see "everyone is done" and both call endBattle. On two server instances the callers aren't even in the same process.
The fix is the same shape as startBattle. completeBattle in gameplay.ts returns early with alreadyCompleted: true if the battle is already COMPLETED, and the transition itself is updateMany({ where: { id, status: { not: 'COMPLETED' } } }). endBattle applies ratings and broadcasts battle:completed only when alreadyCompleted is false.
battleEndIdempotency.test.ts drives two endBattle calls under Promise.all, with a mocked completeBattle that lets the first caller win the compare-and-set, and asserts applyBattleResult runs once and battle:completed is emitted once. That proves endBattle only applies ratings for the caller that won. Before the fix I reproduced the bug the same way: two concurrent completions, two rating updates.
A lock that can expire under its holder
The TTLs were wrong too. submitAnswer held a 15,000 ms lock around a Prisma interactive transaction whose own timeout was also 15,000 ms. Prisma counts maxWait (time spent waiting for a pool connection) separately from timeout, so the guarded callback was allowed to run for about 17 s under a 15 s lock. And redlock.acquire() never extends a lock. The automaticExtensionThreshold: 500 in cacheService.ts is read only by redlock.using(), and nothing in the codebase calls redlock.using. Redlock also subtracts drift (driftFactor: 0.01), so the 15,000 ms lock really expired at about 14,848 ms.
The budgets now live in utils/deadlines.ts:
export const BATTLE_TX_MAX_WAIT_MS = 2_000;
export const BATTLE_TX_TIMEOUT_MS = 15_000;
/** Must exceed BATTLE_TX_MAX_WAIT_MS + BATTLE_TX_TIMEOUT_MS. */
export const BATTLE_SUBMIT_LOCK_TTL_MS = 20_000;
The test asserts the inequality (maxWait + timeout < ttl) rather than the numbers, and separately asserts that these are the values that actually reach redlock.acquire and prisma.$transaction. A constant nothing reads is not a guard.
The error blamed a rival that didn't exist
One more thing fell out of reading the lock helper. Redlock 5 raises ExecutionError both when the resource is held and when it can't reach Redis at all, and withBattleLock answered 409 "Another action on this battle is already in progress" to both. In September 2026 the backend's health endpoint was reporting redis: error because the instance in REDIS_URL no longer existed, so every start and every answer submission was rejected with an error that named a rival and invited a retry that could never succeed.
The two cases are distinguishable in the error object. ExecutionStats.votesAgainst holds a ResourceLockedError for a lost race and a connection error for an outage. isPureContention in lock.ts now returns true only when every vote against is a ResourceLockedError. Anything else, including shapes it doesn't recognise, is a 503 that says the dependency is unavailable.
When you still want the lock
If the database enforces the invariant, why keep Redlock at all? Contention. submitAnswer recalculates ranks for every participant inside one transaction. The per-battle lock, with retryCount: 10, queues concurrent submissions for the same battle so they run one after another instead of failing against each other in Postgres. It is an optimisation on top of a correct write, not what makes the write correct.
The rule I took away: a lock answers "am I alone?", never "is this still true?" Keep the read and the decision inside the same boundary as the write, then make the write itself conditional, so the database enforces the invariant and the lock only reduces contention.
Checklist
Questions I now ask about any critical section:
- What does the code decide just before entering the lock? If a guard runs outside it, the guard is advisory.
- Is the write conditional on the state the guard checked?
update({ where: { id } })is not.updateMany({ where: { id, status } })is. - If the same call runs twice, does the second run change anything? Serialization is not idempotence.
- Can the lock expire before the guarded work ends? Write the budgets down and assert the inequality in a test.
- Does the "lock unavailable" error distinguish contention from the lock store being down?
The idempotency-keys post covers the same idea from the API side, in the section "Where the atomicity actually lives": push the one operation that must be atomic down to the layer that can guarantee it. The rest of this audit is in EduScale's FINDINGS.md §15, and the running list of defects from my own projects is on /engineering.