Sub topic 3
Retry, fallback, and partial failure
This chapter assumes you know the AsyncState type from the earlier chapter, can read TypeScript, and understand that network requests can fail.
Retry and fallback
A retry repeats a failed request after a short wait. Wait longer after each failure so that a struggling server gets room to recover. This is called exponential backoff.
async function withRetry<T>(task: () => Promise<T>, attempts = 3): Promise<T> {
let lastError: unknown;
for (let i = 0; i < attempts; i++) {
try {
return await task();
} catch (err) {
lastError = err;
await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** i));
}
}
throw lastError;
}Retry only errors that may succeed later, such as timeouts and server errors. Do not retry a validation error, because the same input fails every time.
A fallback shows something useful when the request fails for good. Cached data from the last successful load is a common fallback. Label stale data so people know it may be out of date.
Partial failure
A partial failure happens when one part of a screen loads and another part does not. Show the parts that worked and mark the failed part with its own error and retry button. Do not replace the whole screen with one error message.
Timing: delays, flicker, and transitions
Show a spinner only after a short delay, such as 300 ms. A fast response then never flashes a spinner on screen. Cancel the timer when the data arrives early.
function showAfterDelay(delayMs: number, show: () => void): () => void {
const id = setTimeout(show, delayMs);
return () => clearTimeout(id);
}Making state changes accessible
Screen readers announce changes only when the page signals them. Use a polite live region for loading and an assertive alert for errors.
<div role="status" aria-live="polite">Loading projects…</div>
<div role="alert">Couldn't save your changes. Check your connection and try again.</div>Modeling states in code
Add the partial state to your union type so that impossible combinations cannot compile.
type DashboardState =
| { status: "loading" }
| { status: "partial"; profile: string; chartError: string }
| { status: "success"; profile: string; chart: number[] };Reviewing and testing every state
Test each state on purpose: loading, slow loading, empty, error, retry, partial, and success. Check each one with a screen reader and with the keyboard alone.
Exercise
A chart request fails with a 404 error, and the profile request succeeds. Should the screen retry the chart request, and why?
Show answer
No. A 404 means the resource does not exist, so retrying will fail the same way. Show the profile and a clear message about the chart, with no retry button.