Resilient client patterns

You can decide when an API request is safe to retry and choose a bounded delay policy before implementing the retry utility.

Learning outcomes

  • Decide which HTTP requests are safe to retry and implement bounded exponential backoff with full jitter.
  • Use injected timers and clocks to test asynchronous behaviour without waiting for real time.
  • Build normalized restaurant search keys that support consistent caching and prefix invalidation in TanStack Query.
  • Apply optimistic cart updates with guarded rollback while preserving the cart's idempotency key.

A customer places an order from the Expo app just as their phone loses connectivity. The server might have created the order even though the app never received the response. On another screen, a customer types a restaurant name, and the app sends requests for every intermediate character.

These problems need different client-side policies. You need to know when repeating a request is safe, when to delay work, and when to update local state before the server confirms a change.

Idempotent methods and request safety

A request can fail without the server operation failing. The customer app cannot always distinguish a request that never reached the server from one that completed but whose response was lost.

An idempotent method produces the same intended server-side effect when you repeat the same request. This property is important when deciding whether a failed request can be retried.

Consider the methods used by the customer app:

MethodTypical operationRetry considerations
GETRead a restaurant menuGenerally safe to repeat
PUTReplace a resourceRepeating the same replacement should produce the same state
DELETERemove a resourceRepeating a deletion should leave the resource deleted
POSTCreate an orderRepeating can create another order

GET requests are the safest starting point for automatic retries. They retrieve data without intentionally changing server state.

PUT and DELETE can also be idempotent when implemented according to their intended semantics. However, that does not mean every client retry policy should automatically include them.

The retry utility in this course deliberately supports only GET. An undefined request method is also treated as GET.

The order submission problem

The app already sends orders through POST /v1/orders. Repeating this request without duplicate protection can create two orders.

Imagine this sequence:

  1. The app sends an order creation request.
  2. The server creates the order in MySQL.
  3. The response is lost because the phone disconnects.
  4. The app sees a network error.
  5. The customer or client sends another request.

The server might create another order because it cannot know that the second request represents the same logical operation.

The course handles this with an idempotency key.

The app generates a key for one logical order submission and sends it through the Idempotency-Key header.

typescript
await api.request("/v1/orders", {
  method: "POST",
  headers: {
    "Idempotency-Key": orderKey
  },
  body: orderPayload
});

The backend associates the key with the result of the operation. Repeating the same submission with the same key allows the backend to recognize the duplicate and return the existing result rather than create another order.

The key must remain the same across attempts for the same logical operation. Generating a new key for every retry defeats this protection.

An idempotency key also requires server-side support. Adding the header to a request does not automatically make a POST idempotent.

Classifying failures

The existing API client distinguishes HTTP failures from other failures such as network errors.

The retry policy needs to examine both the request method and the failure type.

FailureRetry GET?Reason
Network errorYesCommunication may recover
HTTP 503YesThe server might recover
HTTP 400NoThe request is invalid
HTTP 401NoAuthentication needs attention
HTTP 403NoThe operation is not permitted
HTTP 404NoThe requested resource was not found
HTTP 429NoThe client has been rate limited
HTTP 503 on POSTNoThe request may already have changed server state

The optional retry utility follows these rules:

  • Retry GET requests that fail with an HTTP status of 500 or above.
  • Retry GET requests that fail with a non-ApiError, such as a network error.
  • Do not retry other ApiError responses, including HTTP 429 Too Many Requests.
  • Do not retry non-GET requests.

The distinction matters because retrying a client error without correcting the request usually produces the same failure again.

The retry utility is intentionally narrower than the general definition of idempotent HTTP methods. Even though PUT and DELETE can be idempotent, this exercise does not retry them.

Exponential backoff

Retrying immediately can make an overloaded server's situation worse.

Suppose the backend is temporarily unavailable. A customer app sends a request, receives a 503 response and immediately sends another request. If thousands of devices do this simultaneously, they add more traffic while the backend is recovering.

Exponential backoff increases the maximum waiting period after each failed attempt.

Let n represent the number of the failed attempt, starting at 1. The delay limit is:

typescript
const delayLimit = Math.min(
  maxMs,
  baseMs * 2 ** (n - 1)
);

For the retry utility, the defaults are:

  • baseMs: 200 milliseconds.
  • maxMs: 5000 milliseconds.
  • maxAttempts: 3 total attempts, including the first request.

The calculated delay limit grows as follows:

Failed attemptCalculated delay limit
1200 ms
2400 ms
3800 ms
41600 ms
53200 ms
65000 ms

The maximum delay cap prevents the exponential value from growing indefinitely.

Notice that three total attempts do not mean three retries. The first request is already one attempt. With the default configuration, the client can make two more requests after the initial failure.

It must also stop after the last failure without sleeping again.

Full jitter

Exponential backoff still has a synchronization problem.

Imagine a deployment interrupts 10,000 customer devices at approximately the same time. If every device uses the same backoff schedule, they can all retry after approximately 200 milliseconds, then 400 milliseconds and so on.

This produces another traffic spike.

Jitter adds randomness to the calculated waiting period. Full jitter selects a random delay between zero and the maximum calculated delay.

typescript
const delay = random() * Math.min(
  maxMs,
  baseMs * 2 ** (n - 1)
);

The random() function returns a number between zero and one.

For example, suppose the calculated delay limit is 800 milliseconds.

Random valueActual delay
00 ms
0.25200 ms
0.5400 ms
0.75600 ms
1800 ms

This spreads requests across a time window instead of making all clients wait for the same fixed duration.

The order of the calculation matters. You first apply the maximum delay cap, then multiply the result by the random value.

Bounded retry attempts

Retries need a fixed stopping condition.

Consider a GET request that receives three consecutive 503 responses. With three total attempts, the client sends the request three times and throws the error from the third attempt.

The sequence is:

  1. Send the initial request.
  2. On the first retryable failure, calculate a delay and wait.
  3. Send the second request.
  4. On the second retryable failure, calculate another delay and wait.
  5. Send the third request.
  6. If it fails, throw that error without another wait.

A successful response at any attempt returns its response body immediately.

Server-provided retry delays

The client does not always know how long the server needs to recover.

The HTTP Retry-After header allows a server to communicate a retry delay. When the API client exposes this value as retryAfterSec, the retry utility can use it instead of calculating its own delay.

The conversion is straightforward:

typescript
const delay = error.retryAfterSec * 1000;

The value is expressed in seconds, while the retry utility's sleep function accepts milliseconds.

When retryAfterSec is defined:

  • Use the exact server-provided delay.
  • Do not multiply it by the random value.
  • Do not apply the maxMs cap.

For example, if retryAfterSec is 8, the client waits exactly 8000 milliseconds, even when maxMs is 5000.

This does not mean every response containing a Retry-After header is retried. The response must still satisfy the retry policy.

There is a limitation in the current API client. It currently populates retryAfterSec from HTTP 429 responses. The retry utility deliberately excludes 429 responses, so a 503 response containing a Retry-After header does not automatically reach this branch.

Supporting that behaviour for 503 requires the API client to extract the header from those responses too. That change is outside the retry exercise.

Injected dependencies for retry testing

A retry utility depends on time and randomness. Using real delays and uncontrolled randomness makes its tests slow and unpredictable.

Instead, the utility accepts two injectable dependencies:

  • sleep: A Promise-based delay function.
  • random: A function that supplies the value used for jitter.

The production defaults use setTimeout and Math.random.

Tests can replace them with controlled implementations. A fake sleep function can record requested delays without waiting, while a fake random function can return a known value.

For example, with a random value of 0.5, a retry delay limit of 400 milliseconds should produce a delay of 200 milliseconds.

This lets a test verify the calculation without waiting for real time.

The same dependency-injection principle applies to timer-based utilities. An injected clock separates application behaviour from the actual system clock. The Go exercises use this approach to make time-dependent behaviour testable.

Injected timers and debouncing

Retries handle requests that have already failed. Search debouncing prevents unnecessary requests from being sent in the first place.

Consider a customer typing pizza into a restaurant search field.

Without debouncing, the app might send requests for:

p
pi
piz
pizz
pizza

By the time the first request returns, the customer may already have entered the complete search term.

A debouncer waits until input stops changing for a configured period before executing a callback.

Debouncing is particularly useful for search fields because intermediate input values usually do not need separate network requests.

Trailing-edge behaviour

The optional exercise uses trailing-edge debouncing.

Every new call restarts the waiting period. Only the latest value is passed to the callback after the configured quiet period.

Consider a delay of 300 milliseconds:

TimeEvent
0 msCustomer enters p
100 msCustomer enters pi
200 msCustomer enters piz
300 msNo callback yet
500 msCallback executes with piz

The timer started by each earlier call is replaced. The callback receives the latest value only after 300 milliseconds have passed without another call.

Timer dependencies

Injected timers let you control scheduling without coupling the debouncer to global timer functions.

The exercise defines this interface:

typescript
export type Timers = {
  setTimeout(fn: () => void, ms: number): unknown;
  clearTimeout(id: unknown): void;
};

The default implementation uses the global setTimeout and clearTimeout. Tests can supply an alternative implementation that uses a virtual clock.

The debouncer receives these timer operations as a dependency. It does not need to know whether the timer is real or simulated.

This is the same principle used for the injected clock in the backend. Your business logic depends on a controllable interface instead of directly controlling real time.

Pending values and timer state

A debouncer needs to remember two separate things:

  1. Which value should the callback receive?
  2. Whether a value is currently waiting to be processed?

These are not interchangeable.

A generic debouncer can receive undefined, null, false or 0 as valid values. Testing whether the pending value is truthy would incorrectly discard some of these inputs.

Use a separate boolean to represent pending state.

The debouncer exposes three operations:

OperationBehaviour
call(value)Replace the pending value and restart the timer
cancel()Clear the timer and discard the pending value
flush()Clear the timer and invoke the pending callback immediately

Both the timer callback and flush() should use the same invocation behaviour. This prevents the callback from executing twice for one pending value.

After invocation, the pending state must be cleared.

Virtual clocks

A virtual clock represents time inside a test. Instead of waiting for a real timer, the test advances the clock and checks which scheduled callbacks have executed.

For example, a test can:

  1. Create a debouncer with a 300 ms delay.
  2. Call it with a search term.
  3. Advance virtual time by 200 ms.
  4. Verify that the callback has not executed.
  5. Advance another 100 ms.
  6. Verify that the callback executes exactly once.

This makes timing behaviour deterministic.

The production implementation still uses normal timers. The test controls only the implementation of the injected dependency.

Query key factories and cache consistency

Debouncing reduces the number of requests. It does not solve the problem of identifying and caching their results consistently.

TanStack Query uses query keys to identify cached queries and their parameters.

A query key must describe the data being requested. If two screens request the same restaurant search using different keys, TanStack Query treats them as separate cache entries.

For example:

typescript
["restaurants", "pizza"]
["restaurant", "pizza"]

These keys are different, even though both appear to describe a restaurant search.

A query key factory centralizes key construction so different parts of the app follow the same structure.

For restaurant search, the exercise uses a hierarchical structure:

typescript
["restaurants", "search", normalizedTerm]

Each search term produces a key under the same restaurant prefix.

Normalizing search terms

Customers can enter equivalent search terms with different capitalization or whitespace.

Consider:

" Pizza "
"pizza"
"  PIZZA  "

These inputs should represent the same search term.

The normalizeTerm utility performs three transformations:

  • Trims leading and trailing whitespace.
  • Converts the term to lowercase.
  • Replaces consecutive whitespace characters with one space.

The result for all three examples is:

pizza

The searchKey utility uses this normalized result as its third element.

Conceptually, the helper produces:

typescript
searchKey(" Pizza ");
searchKey("pizza");

Both calls represent the same logical query.

This avoids creating separate cache entries for equivalent user input.

Minimum search length

Not every input should start a request.

An empty search term does not provide a useful query. A single-character term is also excluded by the exercise's search policy.

The canSearch helper checks the normalized term and returns true only when its length is at least 2.

For example:

InputNormalized valuecanSearch
""""false
" """false
"p""p"false
" P ""p"false
"pi""pi"true
"pizza""pizza"true

Always check the normalized value rather than the original input. Otherwise, whitespace could make an empty search appear eligible.

Prefix invalidation

Hierarchical query keys also help when cached data needs refreshing.

Suppose your application has several restaurant-related queries:

typescript
["restaurants", "list"]
["restaurants", "detail", 5]
["restaurants", "search", "pizza"]

You can invalidate all restaurant queries by supplying their common prefix.

typescript
queryClient.invalidateQueries({
  queryKey: ["restaurants"]
});

This is query invalidation. TanStack Query matches queries whose keys begin with the supplied prefix.

You can also invalidate a more specific query when only one set of results needs refreshing.

The important point is consistency. Every screen should use the same query key structure rather than building unrelated arrays independently.

Optimistic updates and rollback

Retries and debouncing control network activity. Optimistic updates solve a different problem: waiting for the server should not prevent the interface from responding to the customer.

Consider a customer adding a menu item to the cart.

A pessimistic implementation waits for the server to confirm the change before updating the UI. On a slow mobile connection, this makes a simple interaction feel delayed.

An optimistic update changes local state first, then sends the corresponding operation to the server.

If the server accepts the change, the app keeps the updated state. If the server rejects it, the app needs to restore the previous state.

The Zustand cart

The app already uses Zustand for cart state. The store is exported as useCart.

Its state includes:

FieldPurpose
restaurantIdIdentifies the restaurant associated with the cart
linesContains the cart's CartLine objects
idempotencyKeyIdentifies the logical order submission

A cart line contains itemId, size, chosen, qty, unitPaise and description.

The store exposes actions such as add, setQty, replaceWith and clear.

For example, adding a line to restaurant 5 uses the existing store:

typescript
const result = useCart.getState().add(5, line);

if (result === "other-restaurant") {
  // Handle the restaurant mismatch.
}

The store can update immediately without waiting for an API request.

The "other-restaurant" result matters because the cart cannot silently combine items from different restaurants.

Snapshotting the previous state

An optimistic operation needs a recovery point.

Before changing the cart, capture the state that must be restored if saving fails:

  • The previous restaurantId.
  • The previous lines array.
  • The previous idempotencyKey.

Then apply the change through the existing Zustand store.

After the mutation, retain the resulting lines array reference. You will need it when deciding whether rollback is still safe.

The overall lifecycle is:

  1. Capture the previous cart state.
  2. Apply the optimistic change.
  3. Capture the resulting lines array.
  4. Send the updated restaurant ID and lines to the server.
  5. Keep the updated state if the request succeeds.
  6. Consider restoring the snapshot if the request fails.

Guarded rollback

A failed request does not always mean that the cart is still in the state created by that request.

Imagine this sequence:

  1. The customer adds item A.
  2. The app updates the Zustand store and starts saving.
  3. Before the save finishes, the customer changes the quantity of item A.
  4. The first save fails.

If the first operation blindly restores its original snapshot, it removes the customer's newer quantity change.

Optimistic rollback must therefore account for intervening changes.

The exercise uses reference equality as a guard.

Each cart mutation creates a new lines array. Immediately after an optimistic update, you retain the reference to that array.

When the request fails, compare it with the current store reference:

typescript
const optimisticLines = useCart.getState().lines;

if (useCart.getState().lines === optimisticLines) {
  // The optimistic lines are still current.
  // The previous snapshot can be restored.
}

If the references differ, another edit has replaced the array. The older operation must not overwrite that newer state.

This is a form of concurrency protection. It does not guarantee correct ordering of overlapping server requests, but it prevents this particular stale rollback from replacing a newer local cart change.

Preserving the idempotency key

The snapshot must include idempotencyKey.

Consider a customer removing the last cart line. The cart becomes empty, and the store may reset its restaurant ID and idempotency key.

If saving the removal fails, restoring only the original lines is incomplete. The cart could contain its original items but no longer have the key associated with its logical order submission.

Restore all three fields together:

  • restaurantId
  • lines
  • idempotencyKey

This preserves the original cart identity after a failed update.

Optimistic updates and TanStack Query

TanStack Query supports a similar lifecycle for optimistic mutations.

Its mutation callbacks commonly use:

  • onMutate to capture the previous state and apply an optimistic change.
  • onError to restore the previous state when the mutation fails.
  • onSettled to perform follow-up reconciliation when needed.

The cart synchronization exercise uses Zustand directly. It does not need to introduce TanStack Query into cartSync.ts.

The same mental model applies, even though the state-management tools differ.

When to avoid optimistic updates

Optimistic updates are not suitable for every operation.

A cart quantity change is usually reversible. A payment transfer is different because the customer must not see a payment as successful before the provider confirms it.

You should be careful with optimistic updates when:

  • The operation is irreversible.
  • Server-side validation determines whether the operation is permitted.
  • The result depends on inventory or pricing that might change.
  • Showing an unconfirmed success could mislead the customer.

For these operations, an explicit pending state is often more appropriate.

Connections to the optional exercises

The three optional exercises apply these patterns to separate parts of the customer app.

API request retry utility places a bounded retry policy around the existing API client. You distinguish safe GET requests from writes, classify retryable failures and calculate delays using exponential backoff, full jitter or a server-provided retryAfterSec.

Cart synchronization helper applies optimistic changes through the existing Zustand store. You preserve a snapshot of the cart and avoid restoring it over newer local changes when a server request fails.

Restaurant search utilities provide a framework-independent debouncer and normalized query key factory. You use injectable timers to control callback execution and build consistent keys for TanStack Query.

These utilities address different failure modes. Retries handle temporary request failures. Optimistic updates improve immediate feedback. Debouncing and query key factories reduce unnecessary work and keep cached search results consistent.

Check your understanding

Question 1 of 4

A customer sends POST /v1/orders and loses connectivity before receiving the response. Which behaviour protects against creating a duplicate order?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (TypeScript, Zustand 5, TanStack Query 5).

Finished Lesson 4.19?