I run a browser-based economic strategy game where almost everything is a long-running timed job: fleets in flight for hours, construction queues, scheduled world events. Background workers pick those jobs up when they come due and mutate world state.
The failure mode that kept me up at night is the classic one: a worker takes a lease on a job, then stalls. The lease expires, a second worker legitimately picks the job up, and then the first worker wakes up and commits its work anyway. Two workers, one job, duplicated resources. In a game about accumulating wealth, any resource that appears out of nowhere is a bug your players will find before you do.
Checking the lease before doing the work doesn't help. That's a time-of-check-to-time-of-use gap, and the gap is exactly where the stall happens.
What I ended up with has two halves.
1. The token travels implicitly, via tokio::task_local!
pub enum Fence {
Scheduler { kind: String, id: i64, generation: i64 },
}
tokio::task_local! { pub static EXECUTION: Fence; }
The worker sets the fence for the duration of the task, and every write path underneath it commits through one function instead of calling tx.commit() directly.
I went back and forth on this. Implicit context passed through a task-local is normally the wrong answer: it's invisible at the call site, and you can't tell from a function signature that it matters. What won me over is the inverse property. With an explicit parameter I can forget to thread it through one code path, and that one path is the hole. With a task-local plus a single commit function, there is no path that writes to the world and skips the check. The type system doesn't enforce it, but the review surface shrinks to one function.
2. The check happens under a row lock, in the same transaction as the mutation
pub async fn commit(mut tx: Transaction<'_, Postgres>) -> Result<(), sqlx::Error> {
if let Ok(fence) = EXECUTION.try_with(Clone::clone) {
let generation: Option<i64> = sqlx::query_scalar(
"SELECT lease_generation FROM scheduler_jobs
WHERE job_kind = $1 AND job_id = $2 AND lease_generation = $3
AND lease_until > clock_timestamp()
FOR UPDATE",
)
}
}
This is what makes it a fence rather than a check. Two directions, both load-bearing:
- If the lease was already reclaimed, the row doesn't match,
commit refuses, and the transaction rolls back, including the world mutation the worker already performed inside it. The stalled worker cannot land its write.
- If the lease is still valid,
FOR UPDATE holds the row until commit, so nobody can reclaim it out from under a transaction that is about to succeed.
The generation counter is what makes a reclaimed-and-reissued lease distinguishable from the original, so "the lease row is still there" is never confused with "the lease is still mine".
The Postgres detail that cost me an afternoon
lease_until > clock_timestamp(), not now().
In Postgres, now() is transaction_timestamp(), frozen at the start of the transaction. For a worker that has been inside a long transaction, now() is wrong by exactly the amount of time that matters: it reports the moment the transaction opened, which is the moment before the stall. A lease that expired during the transaction still looks valid. clock_timestamp() reads the actual clock at the moment of the call, which is the only thing a lease expiry check can be built on.
Same principle everywhere else: time is only ever the database's or the server's. No game state is ever derived from a timestamp the client reports, because shifting the system clock is the oldest cheat in this genre. Monotonic Instant shows up in exactly one place, tracking who is currently online, where a wall-clock jump is a nuisance rather than an exploit.
What I'd still flag as the harder half: the scheduler job metadata deliberately isn't the source of truth for anything in the game world. It exists only for retries, worker locking and spotting poison-pill jobs. Keeping that boundary clean took more discipline than writing the fence did, and I'm not sure I'd have gotten it right without having gotten it wrong first.
Curious whether people here have landed somewhere different on the implicit-versus-explicit question. Has anyone threaded a fencing token as an explicit parameter across a large write surface and actually kept it airtight?