Sub topic 8
Retry, fallback, and partial failure
This chapter assumes you have read the earlier chapters on the screen state model, error types, and error messages. You should know that an error state needs a clear cause and a next step. You should also be comfortable reading short TypeScript and HTML snippets. Here we focus on what happens after the error message: how the screen helps people recover.
Why recovery needs its own design
An error message tells a person what went wrong. Recovery is what lets them continue. A screen that only says "Something went wrong" leaves the person stuck. A screen that offers the right next action turns a failure into a short detour.
There are three main recovery tools:
- Retry repeats the same operation, by the user or automatically.
- Fallback shows something useful in place of what failed, such as cached data or a simpler view.
- Partial failure handling keeps the working parts of a screen usable when only some parts failed.
Choose among them by asking two questions. Can the failure fix itself if we try again? Is there still something valuable we can show?
Retry
When retry is appropriate
Retrying only helps when the failure is likely to be temporary. Typical examples are a dropped network connection, a timeout, a server overload (HTTP 503), or a rate limit (HTTP 429). Retrying does not help when the request itself is wrong or forbidden. A validation error (400), a missing resource (404), or a permissions error (403) will fail the same way every time.
This is why the error taxonomy matters in code. The retryable field in the state model from earlier chapters decides whether the screen shows a retry button at all.
| Cause | Retry helps? | Better recovery |
|---|---|---|
| Lost connection | Yes, once the connection returns | Retry button, automatic retry on reconnect |
| Timeout | Often | Retry, with a note if it keeps happening |
| Server error (500, 503) | Sometimes | Automatic retry with backoff, then manual retry |
| Rate limit (429) | Yes, after waiting | Wait for the time given, then retry |
| Validation error | No | Highlight the fields and explain how to fix them |
| Permission denied | No | Explain, and offer a way to request access |
| Not found | No | Offer a link back or a search |
Manual retry
A manual retry is a button labeled with the action, such as "Try again" or "Reload projects". Follow these rules:
- Put the button next to the message, not in a distant toolbar.
- Show a loading state on the button itself while the retry runs. Disable it or mark it busy so a double click does not send two requests.
- Keep the error visible until the retry succeeds, or replace it with a loading state in the same place so the layout does not jump.
- If the retry fails again, say so. An unchanged message after a click looks like a broken button. A small change such as "Still can't connect. Check your network and try again." shows the click did something.
Automatic retry
Automatic retry hides brief failures from the user. It must be limited, or it makes things worse. Use these practices:
- Cap the attempts. Two or three tries is common for interactive screens.
- Use exponential backoff. Wait longer between each attempt, for example 1 second, then 2, then 4. This gives a struggling server time to recover.
- Add jitter. Add a small random amount to each delay. Without it, thousands of clients that failed together will all retry at the same instant.
- Respect server hints. If a response includes a
Retry-Afterheader, wait at least that long. - Only retry safe operations automatically. See the next section.
The function below retries an operation with backoff and jitter. It stops early when the error is marked as not retryable.
class RequestError extends Error {
constructor(message: string, readonly retryable: boolean) {
super(message);
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function withRetry<T>(
operation: () => Promise<T>,
maxAttempts = 3,
baseDelayMs = 500
): Promise<T> {
let lastError: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error;
const retryable = error instanceof RequestError && error.retryable;
if (!retryable || attempt === maxAttempts) {
break;
}
const backoff = baseDelayMs * 2 ** (attempt - 1);
const jitter = Math.random() * baseDelayMs;
await sleep(backoff + jitter);
}
}
throw lastError;
}If every attempt fails, the error still reaches the screen. The user then sees the error state with a manual retry button, so automatic retry never replaces manual retry.
Retrying actions that change data
Retrying a read is almost always safe. Retrying a write can be dangerous. If a "Place order" request times out, you do not know whether the server received it. A blind retry may create two orders.
There are two common ways to handle this:
- Idempotency keys. The client generates a unique key for the action and sends it with each attempt. The server recognizes a repeated key and returns the original result instead of repeating the work.
- Check before repeating. After a timeout, ask the server for the current state, then decide whether to try again.
If neither is available, do not retry automatically. Tell the user what is uncertain: "We couldn't confirm your order. Check your order history before trying again."
Fallback
A fallback shows a reduced but useful version of the screen when the full version is not available. Showing something is usually better than showing an error, as long as the person knows what they are looking at.
Kinds of fallback
- Cached data. Show the last successful result, labeled with its age: "Showing projects from 10:42. Couldn't refresh." This is the most common fallback.
- Default or generic content. If a personalized recommendation list fails, show popular items instead.
- Reduced functionality. If live search fails, offer a basic form that submits and reloads.
- Placeholder for a non-essential piece. If an avatar image fails to load, show the person's initials.
Be honest about stale data
Stale data that looks fresh is misleading. A balance, a stock level, or a delivery status that is hours old can cause real mistakes. When you show cached content:
- Say that it may be out of date, and say when it was last updated.
- Disable or warn on actions that depend on fresh data, such as "Buy now" on a cached price.
- Provide a way to refresh, which is the manual retry from earlier.
- Clear the notice as soon as fresh data arrives.
In terms of the state model, this adds a case where data exists and an error also exists. The simple union from earlier chapters has no way to say that, so the code section below extends it.
When not to use a fallback
Skip the fallback when wrong data would be worse than no data. Examples include medical readings, account security status, and financial totals. In these cases a clear error and a retry button is the safer design.
Partial failure
Most real screens load several things: a profile, a list, a set of notifications, a recommendations panel. If one request fails, the whole screen should not turn into an error page.
Isolate failures by region
Treat each independently loaded region as its own small screen with its own loading, empty, error, and success states. A failure in the recommendations panel then shows an error inside that panel only. The rest of the page stays usable.
Decide which regions are essential. If the main content fails, a page-level error is appropriate. If a secondary widget fails, a local error is enough, and for something truly minor, hiding the widget quietly may be better than showing an error nobody can act on.
Partial failure inside a single list or batch
Partial failure also happens within one operation. A user uploads ten files and three fail. A bulk delete removes seven items and cannot remove two. Handle these in a way that keeps the successes visible:
- Report results as a count and a list: "7 of 10 files uploaded. 3 failed."
- Mark failed items individually, with the reason for each, for example "Too large (max 25 MB)".
- Offer "Retry failed" so the user does not redo the seven that worked.
- Do not roll back the successes unless the operation is truly all-or-nothing, and if it is, say so before it starts.
Show the structure in the state
A page with independent regions has several states at once. Model each region's state separately instead of using one page-wide flag.
type AsyncState<T> =
| { status: "loading" }
| { status: "error"; message: string; retryable: boolean }
| { status: "success"; data: T };
type DashboardState = {
profile: AsyncState<{ name: string }>;
projects: AsyncState<string[]>;
recommendations: AsyncState<string[]>;
};
function isPageFailed(state: DashboardState): boolean {
// Only the essential regions decide whether the whole page fails.
return state.profile.status === "error" || state.projects.status === "error";
}
const example: DashboardState = {
profile: { status: "success", data: { name: "Ada" } },
projects: { status: "success", data: ["Atlas", "Beacon"] },
recommendations: {
status: "error",
message: "Couldn't load recommendations.",
retryable: true,
},
};
console.log(isPageFailed(example)); // false: the page still worksExtending the state model for stale data
To support cached fallback, add a state that carries both data and a problem. This keeps the impossible combination "loading, error, and success at once" out of the code while allowing the real combination "old data plus a refresh failure".
type AsyncState<T> =
| { status: "loading" }
| { status: "error"; message: string; retryable: boolean }
| { status: "success"; data: T }
| {
status: "stale";
data: T;
updatedAt: Date;
message: string;
retryable: boolean;
};
function describe(state: AsyncState<string[]>): string {
switch (state.status) {
case "loading":
return "Loading projects…";
case "error":
return state.retryable ? `${state.message} Try again.` : state.message;
case "stale":
return `Showing projects from ${state.updatedAt.toLocaleTimeString()}. ${state.message}`;
case "success":
return state.data.length === 0
? "No projects yet. Create your first project."
: state.data.join(", ");
}
}
console.log(
describe({
status: "stale",
data: ["Atlas"],
updatedAt: new Date(),
message: "Couldn't refresh.",
retryable: true,
})
);Making recovery accessible
Recovery controls must work for people using screen readers and keyboards.
- Announce a failed retry. Update the text in an existing
role="alert"orrole="status"region so assistive technology reads it. - Keep keyboard focus on the retry button after it is pressed, or move it to the new content if the retry succeeds. Do not let focus fall back to the top of the page.
- Mark a retrying region with
aria-busy="true"and clear it when done. - Give each local retry button a specific name, such as "Retry recommendations", so several identical "Try again" buttons are distinguishable.
<section aria-labelledby="rec-heading">
<h2 id="rec-heading">Recommended for you</h2>
<div role="alert">Couldn't load recommendations.</div>
<button type="button" aria-label="Retry recommendations">Try again</button>
</section>Common mistakes
- Retrying forever. A loop with no cap drains batteries and hammers servers. Always set a limit.
- Retrying without delay. Instant retries often hit the same temporary fault. Use backoff.
- Retrying non-retryable errors. A 403 will not change. Check the error type first.
- Hiding stale data. Cached data with no age label misleads people.
- One error for the whole page. A single failing widget should not hide working content.
- Duplicate writes. Retrying a non-idempotent request without a key can repeat the action.
- Silent failure. Dropping a minor widget is fine only if no one needs it. If the person expects it, tell them it failed.
Exercise
A dashboard loads a profile header, a list of invoices, and a "tips" panel. The tips request fails with a 503, and the invoices request fails with a 403. Describe what the screen should show for each failure, and whether each should be retried automatically.
Show answer
Tips panel (503): the failure is likely temporary and the panel is non-essential. Retry automatically a few times with backoff and jitter. If it still fails, show a small local error with a "Retry tips" button, or hide the panel, and keep the rest of the page working. Invoices (403): permission denied is not temporary, so do not retry. The invoices region is probably essential, so show an explanation such as "You don't have access to invoices," and offer a way to request access or contact an admin. The profile header stays visible because each region has its own state.
Exercise
A user taps "Submit payment" and the request times out. Why is an automatic retry risky, and what two approaches make a retry safe?
Show answer
The server may have processed the payment before the connection dropped, so a blind retry could charge the user twice. Two safe approaches: send an idempotency key with every attempt so the server returns the original result for a repeated key, or query the server for the current payment status before deciding to retry. Without either, show a message asking the user to check their payment history before trying again.