My news reader calls an LLM twice a day to write short briefs for the biggest stories. On two days in a row, a run failed and lost its whole slot. Once DNS failed for a moment. The next time, the reply was cut off mid-JSON, and one parse error threw away every story already written and paid for. Which LLM failures are safe to retry, and what should you keep when a reply is cut short? The rule I ended up with: retry only what cannot have been billed, keep every complete entry before the cut, and record usage as if the worst happened.
This post covers the AI part of my Vietnamese news reader (Bun, Postgres, Gemini through its OpenAI-compatible API), whose story grouping I described in an earlier post. It covers how spending is capped by design, the two failures, which errors get a retry and which do not, how usage is recorded, and how to salvage a reply cut at max_tokens.
Spending is capped before anything can fail
The reader groups articles from several newspapers into stories. Twice a day, a run picks the stories that several outlets carry and asks the model for a title, a two-sentence brief, why it matters, what to watch, and how the outlets differ. A second, smaller request writes the day's digest from those briefs.
Everything about cost is bounded in code, not by hoping:
- Off unless a daily token budget is set.
- Two runs a day, each allowed at most half of the day's budget, so a failed morning cannot spend the evening's share.
- Only stories carried by at least three outlets, and a story is analyzed again only after its article count has doubled.
- At most two requests per run: one for all the stories, one for the digest.
- Each run happens once per slot. It records the slot before calling the model, so a crash or restart never runs it twice.
That last rule is why the failures below hurt. A run that fails has no second chance until the next slot, about 11–13 hours later.
Failure 1: DNS failed for a moment, the slot was lost
One afternoon run failed with getaddrinfo EAI_AGAIN: a temporary DNS failure while resolving the API's hostname. The request never left the machine. The run gave up, the slot was marked done, and the stories had no fresh briefs until the next morning's run, about 13 hours later. The alert for a failed run fired the whole time, which was correct and useless, since there was nothing to do but wait.
Looking closer found a second bug. Failed requests were recorded in the usage table as if they had used their whole max_tokens. A request that never left counted against the day's budget, so the next run had less to spend because of a DNS hiccup.
Which failures are safe to retry
The question that decides a retry is not "is this error transient?" but "could this request have been billed?" A retry of a billed request pays twice. A retry of an unbilled one costs nothing but time.
| Failure | Could it be billed? | Retry? |
|---|---|---|
| Never sent: DNS failure, connection refused | No: nothing reached the API | Yes |
| Refused by the API: 429, 500, 502, 503, 504 | Treated as no: the API produced no output | Yes |
| Other 4xx: bad request, bad key | No, but a retry fails the same way | No |
| Timeout | Maybe: the model may have generated the whole reply | No |
| Reply that is not valid JSON | Yes: the output was generated | No (salvage instead, below) |
Google's troubleshooting guide says the same about which errors are transient: retry 429, 408 and 5xx with exponential backoff, and "do not retry on client errors". My code is narrower than that: it retries 429, 500, 502, 503 and 504, not 408 or every 5xx. The guide does not say whether a refused request is billed. That row of the table is my reasoning from "the API produced no output", not a documented guarantee, so check your provider's billing terms.
The timeout row is the one people tend to get wrong. A 60-second timeout fires on your side. The provider may have finished the generation and billed it, and you just never read the answer. Retrying it can pay for the same output twice.
The retry, in code
Shortened from the app's briefs.ts:
const RETRY_DELAYS_MS = [2_000, 10_000];
const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
const neverSent = (err: unknown) =>
/EAI_AGAIN|ENOTFOUND|ECONNREFUSED|ConnectionRefused|Unable to connect/i.test(String(err));
for (let attempt = 0; ; attempt++) {
try {
raw = await requestOnce(llm, fetchImpl, system, user, maxTokens);
break;
} catch (err) {
const unsent = neverSent(err);
const retryable =
err instanceof LlmRejected ? RETRYABLE_STATUS.has(err.status) : unsent;
if (retryable && attempt < delays.length) {
await Bun.sleep(delays[attempt]);
continue;
}
// Refused or never sent: not billed. A timed-out request may still be.
if (!(err instanceof LlmRejected) && !unsent) {
await recordUsage(db, now, estimatedInput, maxTokens);
}
throw err;
}
}
LlmRejected is a small error class that carries the HTTP status, so the code can tell a 503 from a 401. Two waits, 2 and 10 seconds, are enough for a DNS blip or a short overload. The run still happens once per slot. The retry lives inside that one run, not outside it.
Matching error text with a regex is the weak part. Bun and Node word network errors differently, which is why both ECONNREFUSED and ConnectionRefused are there. A new runtime version could word them differently again, and then a DNS failure would quietly stop being retried. The app's tests throw a DNS error from a fake fetch and check that the run retries. A test for each wording would catch a change like that.
Record usage as if the worst happened
The budget check reads the usage table, so the table has to err on the side of spending:
- A successful reply records the provider's own counts:
usage.prompt_tokensandusage.completion_tokens, with an estimate only when they are missing. - A timeout or an unknown error records the estimated input plus the full
max_tokens, the most it could have cost. - A refused or unsent request records nothing.
The budget can then be wrong in only one direction: a run may skip stories it could have afforded, but it never spends past the cap.
Failure 2: a reply cut at max_tokens threw everything away
The next morning's run failed differently: JSON Parse error: Expected ':' before value. The model's reply had run past max_tokens. The request had asked for 320 output tokens per story, and the Vietnamese briefs ran longer than that estimate. The response's finish_reason was length, and the JSON stopped in the middle of a story.
The code parsed the whole reply with one JSON.parse, so one cut-off story threw away all the complete stories before it. Those stories had been generated and billed. The reply is one JSON object keyed by story ID, so everything up to the last complete entry is still valid if you close the object:
export function parseReply(content: string, finishReason?: string) {
try {
return { value: JSON.parse(content), truncated: false };
} catch (err) {
for (let end = content.lastIndexOf("}"), tries = 0;
end > 0 && tries < 400;
end = content.lastIndexOf("}", end - 1), tries++) {
try {
const value = JSON.parse(`${content.slice(0, end + 1)}}`);
if (value && typeof value === "object" && Object.keys(value).length)
return { value, truncated: true };
} catch {}
}
const cut = finishReason === "length" ? " (cut at max_tokens)" : "";
throw new Error(`LLM reply is not JSON${cut}: ${String(err)}`);
}
}
It walks back from the last } and tries closing the object there, until one parses. The half-written story is dropped, the complete ones are saved, and the run's result carries truncated: true, so the cut shows up in the run's log line. An unusable reply now says whether it was cut, which tells you to look at max_tokens rather than the prompt.
Raise the estimate, keep the budget
The other half of the fix was the estimate itself: 420 output tokens per story instead of 320. The daily budget stayed the same. The run already fits its story list to the budget before calling the model:
while (candidates.length > 0) {
const needed =
estimateTokens(STORY_PROMPT + storyPrompt(candidates)) +
candidates.length * OUTPUT_TOKENS_PER_STORY +
DIGEST_OUTPUT_TOKENS;
if (needed <= allowance) break;
candidates.pop();
}
So a higher estimate per story means fewer stories per run, not more spending. That trade is the right default for a side project: the cap is the promise, and the number of briefs is what bends.
What this does not handle
- A timeout still loses the slot. It is not retried, by design, so a slow API on a run hour still means no briefs until the next run.
- Billing of refused requests is an assumption. I treat 429 and 5xx as unbilled because the API returned no output. The provider's docs do not promise it.
- The salvage fits this reply shape only. It works because the reply is a flat object of independent entries. A nested structure, or one where later entries depend on earlier ones, needs a streaming parser or a smaller request per item.
- JSON mode does not prevent truncation. Asking for JSON output only shapes the reply. A reply cut at
max_tokensis invalid JSON in any mode.
Summary
- Decide retries by "could this have been billed?", not only by "is it transient?". Retry requests that never left, and 429 or 5xx refusals. Do not retry timeouts or bad replies.
- Keep the retry inside the single run of a slot, with short waits (2 s, 10 s), and test the error matching with a fake
fetch. - Record usage pessimistically: the provider's counts on success, input plus full
max_tokenson a timeout, nothing on a refusal. - A reply cut at
max_tokens(finish_reason: "length") still holds complete entries. Close the object at the last complete one and keep them. - When outputs run long, raise the per-item estimate and let the budget cut the number of items, not the cap.
If you've built retry and budget rules around an LLM API, especially around timeouts, I'd love to compare notes. My email is on the home page.
