Anh Tran dev notes

Production bugs from mobile and backend work, written up with the fix and how it was checked.

Note 16 / Backend / NestJS / LLM

Promise.race does not cancel anything: a job timeout that kept paying for LLM calls and wrote its result late

A Promise.race timeout only stops waiting. The LLM and speech calls inside kept running, billed, and wrote over the retry. How an AbortController, cost-before-check ordering and a write guard fixed it.

By
Trần Thế Anh, Software Engineer
Published
Work done
October 2026, AI Note Taker (NestJS, BullMQ, Postgres)
Stack
NestJS, BullMQ 6, Node fetch and AbortSignal, OpenRouter, AssemblyAI
Reading
7 min, 1,449 words

A meeting-notes job in my NestJS backend hit its time limit, got marked failed, and was retried. The provider dashboards disagreed with that story. The speech-to-text vendor was still being polled three seconds after the job had thrown. The parent job of the analysis flow still wrote its “gaps” record and moved the note to COMPLETED. The question-answering path kept running a rerank and an embedding call after its own 2.5 and 3 second ceilings. Each of those calls is billed.

The cause was one function, and the same shape appeared in a second file. This is the write-up of what it did, what replaced it, and the part that took longest: deciding where in the code a cancelled job is allowed to still do something.

What the old timeout did

BullMQ has no per-job timeout option (that was a feature of the older Bull library), so the base processor wrapped the handler itself. The old version looked like this (rewritten, names changed):

async function withTimeout<T>(run: () => Promise<T>, ms: number): Promise<T> {
  let timer: NodeJS.Timeout | undefined;
  try {
    return await Promise.race([
      run(),
      new Promise<never>((_, reject) => {
        timer = setTimeout(() => reject(new Error("job timed out")), ms);
      }),
    ]);
  } finally {
    clearTimeout(timer);
  }
}

Promise.race settles as soon as one input settles. It does not touch the other input. When the timer wins, the promise from run() is simply no longer observed. Nothing stops it: the fetch is still in flight, the polling loop still sleeps and asks again, a child process still runs.

You can see it in ten lines. I ran this on Node 26.13.0 with a fake provider that takes 300 ms and a 100 ms limit:

   0 --- race only
 108 race: timeout
 307 provider finished, cost recorded, result written
 510 --- with abort
 611 abort: timeout
1013 end

With the race alone, the caller was told “timeout” at 108 ms and the provider still finished, recorded its cost and wrote its result at 307 ms. With a signal passed in and aborted, nothing happened after the timeout line. That is the whole bug in miniature. In the real job the late write also landed on a note that BullMQ had already handed to the next attempt, so an old attempt’s output could overwrite a newer attempt’s work. The same family of overwrite, on a different table, is in stale job results overwriting newer ones.

I want to be careful about what I know here. The symptom list (STT polled after the throw, parent job still writing) comes from my lessons log for this bug, BL-267, written while reading the code and running the new tests. I did not capture a production trace of a late write. The fix has not been through a deploy yet: the log entry is still marked “waiting for check”, and the test evidence is local.

The shape of the fix

Four changes, in the order I would apply them elsewhere.

Abort before you reject. The wrapper creates an AbortController, and when the timer fires it aborts first and rejects second. The reason passed to abort() is the timeout error itself, so any in-flight call that fails with the abort reason reports the right cause:

const controller = new AbortController();
timer = setTimeout(() => {
  const error = new Error(`${job.name} exceeded ${seconds}s`);
  controller.abort(error);
  reject(error);
}, timeoutMs);
// run(controller.signal)

The wrapper still rejects immediately instead of waiting for the handler to wind down. A step that does not listen to the signal must not hold a worker slot a second time.

Pass the signal to the bottom. handle(job, signal) hands it to the service, the service to the provider router, the router to the provider, and the provider to fetch. At each outbound call the caller’s signal is merged with that call’s own ceiling using AbortSignal.any([signal, AbortSignal.timeout(ms)]), so whichever fires first wins. MDN documents that any() returns a signal that aborts when any input aborts, with the reason of the first one. The same signal goes into child processes started with execFile (ffmpeg and the diarization step), and the polling loop for transcription uses a sleep that wakes up on abort instead of sleeping out its 15 seconds and asking once more.

Check the signal before every result write, not every call. signal.throwIfAborted() sits in front of each block that writes a result: the report sections, the embedding insert (also inside the transaction), the artifact save. After an abort the attempt writes nothing, because the retry will redo the work.

Record cost before the check. This one is easy to get backwards. If you check the signal first and throw, the call that already completed at the provider leaves no cost row, and your usage ledger is lower than your invoice. The order in the report code is: call, await recordLlm(...), then the next check. Cost for work that happened is written even when the result is thrown away. The temporary artifact is removed in a finally.

The catch blocks that undid the abort

Passing the signal was the easy half. Several functions caught every error from an LLM call and returned a fallback, which is right for “this block failed, try the bullet-point layout” and wrong for “this attempt was cancelled”. A cancelled attempt that catches its abort error returns ['bullets'], carries on, and calls the model again on a job that is already dead.

The change in each of them is the same two lines at the top of the catch:

} catch (error) {
  signal?.throwIfAborted(); // cancelled is not "block failed"
  logger.warn(`block ${kind} failed: ${(error as Error).message}`);
  return null;
}

I found these by reading each catch that sits around a provider call: the report planner and block generator, speaker refinement, the diarization step and image generation. Any catch that returns a default is a candidate.

How I checked it

The tests that matter are the ones that go red on the old code. The timeout spec has 9 cases; I ran them against a copy of the pre-fix file and all 9 failed, then against the real tree and they passed. A second spec (8 cases) fires the abort while a provider call is in flight and asserts there is no write afterwards and that the cost row exists. A third covers the diarization child process. An independent review applied 19 mutations to the fix, such as removing the abort, dropping the signal before fetch, moving a cost write behind the check, writing after abort, and letting a catch swallow the abort. All 19 turned a test red. The whole backend suite passed (173 suites, 1918 tests) and tsc reported no errors.

The sweep for the rest of the class was a grep, grep -rn 'Promise.race' src | grep -v spec.ts. It returned five places. Two were the ones I fixed. The other three are a health check, a worker bootstrap and a push-notification sender; none of them abandons a billed call, so I left them. Promise.race with a timer is fine when the abandoned work has no side effect. That is the rule I took away: if a timeout is supposed to stop spending money or writing data, it has to stop the work, and race cannot.

What is still open

The new handler contract only helps code that actually forwards the signal. Six processors extend the base class. Three use the signal (analysis, embedding, transcription). The other three (audio preparation, document extraction, bot join) open their own ledger rows and were not changed. If one of them grows a provider call, it inherits the old problem silently, because the type does not force anyone to pass the signal on. A lint rule or making signal a required argument in the provider interface would close that, and I have not done it.

I also have not seen a real provider charge a cancelled request differently. Aborting a fetch closes the connection on my side; whether a vendor stops generating, and whether it still bills the tokens it produced before the close, is the vendor’s behaviour. The fix stops my code from asking again and from writing; it does not claim to refund anything.

Documentation checked

  • AbortSignal.any(): returns a signal aborted by the first input to abort, with that input’s reason. The page also notes there is no way to unsubscribe from the inputs, so remove any listeners you add to the combined signal.
  • BullMQ job options: the type definitions of BullMQ 5 and 6 have no per-job timeout. A comment in my own code claimed v6 had removed one; that comment was wrong, since BullMQ never had it.