Topic 3 of 4 · 5 min read
Retries, cancel and timeouts in the UI
Goal: Design the visible states for a failed, cancelled or silently retried request so the user knows what happened and what to do next.
Give every request three visible exits, success, failure and cancelled, and make each one say what happened and what the user can do next. Retries and timeouts behind the scenes are fine, as long as the interface never lies about them.
Check yourself · 1 of 3
A user presses Stop while an answer streams. What should the interface show?
Why it matters
LLM calls are slow, variable and fail in many ways: a network drop, a rate limit, a provider overload, a request that takes two minutes. A frontend that treats all of them as "Something went wrong" leaves people guessing whether to wait, retry or give up. A retry that silently duplicates a request can also charge twice or send the same email twice.
How to do it
- Always offer Stop. While streaming, the send button becomes Stop. Wire it to an
AbortControllerand pass itssignaltofetch. Aborting closes the connection, so the server can stop generating too. Keep the text received so far. - Treat abort as a normal state. An abort throws an
AbortError. Catch it separately from real failures and show "Stopped" with the partial answer, not a red error. - Set a timeout.
AbortSignal.timeout(ms)aborts after a set time and raises aTimeoutError, which you can tell apart from a user abort. Pick a limit per feature: a short one for autocomplete, a long one for document analysis. - Retry only what is safe. Retry automatically for network drops and temporary server errors, with exponential backoff and a small cap on attempts. Do not auto-retry a request that has side effects unless it carries an idempotency key.
- Show retries that last. If the first retry works within a second or two, say nothing. If it takes longer, show "Reconnecting, attempt 2 of 3" so a long wait has a reason.
- Map errors to messages. Rate limit: "Too many requests, try again in 20 seconds". Timeout: "This is taking longer than usual". Offline: "No connection". Each with a retry button where retrying makes sense, and a short reference id for support.
- Show the error where the action happened, in the conversation or form, not a toast that disappears.
Before and after
// Weak: no cancel, every failure looks the same
try { await send(prompt); } catch { toast("Something went wrong"); }
// Better: stop, timeout and error kind are separate states
const ctl = new AbortController();
const signal = AbortSignal.any([ctl.signal, AbortSignal.timeout(60_000)]);
try {
await send(prompt, { signal });
setState("done");
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") setState("stopped");
else if (err instanceof DOMException && err.name === "TimeoutError") setState("timeout");
else setState({ failed: toUserMessage(err) });
}
What goes wrong
- No Stop button. Users close the tab, and the server keeps generating and billing.
- Aborts shown as errors. A person who pressed Stop sees a red banner.
- Unbounded auto-retry. Three silent retries on a slow endpoint turns a 30 second wait into two minutes.
- Retrying a non-idempotent action. A "send this email" tool call runs twice.
Examples
Error mapping table
function toUserMessage(status: number, retryAfter?: number): string {
if (status === 429) return `Too many requests. Try again in ${retryAfter ?? 30} seconds.`;
if (status === 529 || status === 503) return "The AI service is busy. Retry in a moment.";
if (status === 401) return "Your session expired. Sign in again.";
return "The request failed on our side. Retry, or quote the reference below to support.";
}
Each branch says what failed and what to do. The generic fallback still tells the user to retry or contact support.
Stop keeps the partial answer
A user asks for a 1,500-word report and presses Stop after the first section is useful. The interface keeps the text, marks it "Stopped", and offers Continue and Regenerate. The abort closed the connection, so the provider stops generating and the app is not billed for tokens nobody will read.
Key points
- Wire a Stop control to an AbortController so cancelling closes the connection and keeps the partial answer.
- Handle AbortError and TimeoutError as separate states from real failures.
- Retry automatically only for safe, temporary failures, with capped backoff, and use idempotency keys for requests with side effects.
- Say nothing about a quick retry, but explain a long one with the attempt count.
- Map each error kind to a specific message, a next step and a reference id, shown where the action happened.
Common mistakes
- Shipping streaming with no Stop control, so the only way out is closing the tab.
- Showing a user-initiated abort as a failure.
- Retrying every error automatically, including requests that change data.
- Using one generic message and a disappearing toast for all errors.
Check yourself · 2 of 3
Which request is the riskiest to retry automatically after a network error?
Check yourself · 3 of 3
In the browser, how can your code tell a timeout abort from a user pressing Stop?
Practice items, not counted towards your mastery.
Start here
- AI SDK UI: chatbot (opens in a new tab)DocsFree
Working chat hook with streaming status, stop, regenerate and error states to compare with your own code.
- AbortController (MDN) (opens in a new tab)DocsFree
How to cancel a fetch and what the abort error looks like.
- AbortSignal.timeout() (MDN) (opens in a new tab)DocsFree
A built-in way to abort a request after a fixed time, with a distinct TimeoutError.