Note 18 / Backend / NestJS / Postgres
The old job finishes last and wins: fencing background-job writes, and three related ways a queue lies about state
A reprocess click lost to the job it replaced; a status written before the job was queued stuck forever; a timeout reaper closed work that was still alive. Fencing tokens, push-then-write order and fixed BullMQ job ids.
- By
- Trần Thế Anh, Software Engineer
- Published
- Work done
- October 2026, Dramma Short and AI Note Taker (NestJS, Postgres, BullMQ)
- Stack
- NestJS, Prisma, Postgres (UPDATE ... SKIP LOCKED), BullMQ 6 flows, Redis
- Reading
- 8 min, 1,575 words
In a video-publishing backend I wrote, the review of the admin tools turned up this sequence. An admin presses “reprocess” on an episode that is still being processed, this time with a new source URL. When the old job finishes, the episode is READY and plays the old source. The new URL has vanished without any error, and if the episode is deleted while the job runs, the finished job’s uploads stay on object storage with nothing pointing at them.
The cause was one line: the worker that had been running when the admin pressed the button finished last, and it wrote its result by episode id.
In the same month I fixed two cousins of that bug in a second app, a meeting-notes backend that uses BullMQ. They look different, but all three come from a record’s state and a job’s life drifting apart. This note goes through each, in the order of how often I expect other people to hit them.
A result write must prove it still owns the work
The Dramma Short worker is a small Postgres-backed queue. A scheduled tick claims one episode with UPDATE ... WHERE id = (SELECT ... FOR UPDATE SKIP LOCKED), sets it to PROCESSING, stamps processing_started_at = now(), and returns the row. Then it downloads, repackages the video, uploads to R2, and writes the result.
The admin action sets the episode back to QUEUED with the new source. It does not know, or need to know, whether a worker is mid-flight. That is a fine design for a retry button. It is the write at the end of the job that must cope with it.
In the first version the final write was episode.update({ where: { id } }). By the time the old worker finished, the row had been re-queued, but nothing in the WHERE said “only if this is still my attempt”. The old attempt set status = READY with its video URL, overwrote the QUEUED marker, and the next tick had nothing to claim. The reprocess request was lost.
The fix is a fence. The claim returns processing_started_at, and the result write includes it in the condition:
const { count } = await tx.episode.updateMany({
where: {
id: job.id,
status: "PROCESSING",
processingStartedAt: job.processing_started_at,
},
data: { status: "READY", videoUrl, durationSec },
});
if (count === 0) {
// someone re-queued, deleted or recovered this episode: not mine any more
await storage.deletePrefix(outputPrefix);
return;
}
A new claim stamps a new processing_started_at, so a re-queued and re-claimed episode no longer matches the old attempt’s value. The failure write uses the same condition, otherwise a late failure from the old attempt could turn the new attempt’s PROCESSING row into FAILED.
Two details matter. First, count === 0 is a normal outcome and the code must do something useful with it: here it deletes the output directory that attempt just uploaded, which also covers the orphaned files. Each attempt writes to its own directory (the key includes a timestamp), so cleaning up never touches the winner’s files. Second, the check and the write are one statement. Reading the row, comparing in code and then updating would leave a gap for the same race.
The check recorded in my lessons log (BL-488) was local: an episode processing one source, reprocessed with a second one. The log showed the old attempt dropping its result and deleting its prefix, and the episode ended READY with the new source (611 seconds long). An independent review accepted it. The change is in commit 22b833c in that repo. I have not reproduced the race on the production host; the timing needed makes that impractical, and I did not try.
The sweep was grep -rn 'update({ where: { id: job' src, which no longer finds a result write by bare id. The general rule I wrote down: a job that writes a result needs a token from the moment it took the work (status plus claim time, or a version column) in its WHERE, and a plan for what to clean up when the token no longer matches.
Write the state after the push, or undo it when the push fails
The second bug is in the meeting-notes app. The code path to start a bot session wrote the status first (SCHEDULED, UPLOADING) and then added the job to the queue. If Redis was down at that moment, queue.add threw, the API returned 500, and the row stayed at SCHEDULED with no job anywhere. The app enforces one bot per meeting room, so the user could not schedule again until a reaper closed the stale row, which can take up to an hour.
There are two ways to fix this class. One is to wrap the push: write the state, try to enqueue, and if that throws, move the row to a terminal state with a conditional update, then rethrow the original error so the caller can retry. A helper, enqueueOrRevert, does this, and the bot service uses it in the places where the state has to exist before the job does. The conditional update (WHERE status = current) makes it lose gracefully when something else already moved the row, and if the cleanup itself fails the code logs it and still throws the original error, so the first cause is not hidden.
The better fix, where the code allows it, is to reverse the order. In the webhook handler that receives “recording ready” from the bot provider, the job to download the audio is added first and the status is written afterwards. If the push fails, nothing was written, the handler returns 5xx and the provider resends the webhook. If the job finishes before the status write happens, the later write is harmless because the status update only moves forward and ignores a request to go back to UPLOADING from DONE.
This order requires that status writes are monotonic, which is a property worth enforcing in one function, not in every caller. The tests for this (two files, 5 and 2 cases) failed on the old code and passed on the new, and eight deliberate breakages of the new code turned them red. That entry, BL-260, is still marked as fixed but not committed.
A reaper that does not ask the queue
Last, the housekeeping job. It marks a note FAILED, and refunds the usage credit, when it has been in an in-progress status for longer than a threshold. The threshold was only a clock: status plus last-updated time. A note whose transcription legitimately ran past three hours, or a busy analysis queue, passed the threshold while its job was still waiting or running. The note was failed and refunded, then the job finished and its transition found the note already closed, and the LLM results that had been paid for were thrown away.
The fix asks the queue before closing anything. For each note the reaper looks up the jobs by id in the states active, waiting, delayed, waiting-children and prioritized, and skips the note if any is live. If Redis cannot be reached while asking, the answer is “alive”, so an outage cannot make the reaper close everything.
That only works if every job for a note can be found by id, and the parent job of the analysis flow could not: it had a random id. BullMQ flows run child jobs first and the parent after, so for a stretch the children are done and only the parent is waiting. The reaper saw no live child and closed the note. The parent now gets a fixed id derived from the note, meeting-complete-<id>.
Fixed ids have a cost, and the BullMQ documentation states it. A job added with an id that already exists “will just be ignored”, and an id belonging to a job that was removed does not count as a duplicate. So, before re-adding the flow, the producer looks for a leftover parent: a live one means “do not push a second flow”, and a completed or failed one is removed first. Without that step, flow.add would be silently dropped for the parent, and the new children would hang off the old dead parent, leaving the note stuck in ANALYZING. The comment in the code says exactly this; I took it from the lessons entry and the producer code, and I did not test that exact BullMQ behaviour in isolation. The lessons entry records a run of the producer against a real development Redis instance with two simultaneous re-push requests, where only one parent job ran.
What is not finished
BL-260 and BL-261 are tested with specs and with that Redis run, but neither is committed or deployed, and I have not seen them behave on production traffic. The live-job check has no upper bound on how long a note may be considered alive, so a job that is stuck “active” forever would keep its note open indefinitely. I listed it as open. The older random-id parent from before the change can still exist during a transition.
There are also 24 call sites that ignore the boolean returned by the state-transition function. I left them because fixed job ids make a duplicate harmless, and wrote it down as a separate proposal rather than a fix.
Sources
- BullMQ: job ids: custom ids are unique per queue; adding a job with an existing id ignores the new job; removed jobs free their id.