API request retry utility
You build requestWithRetry, an API client wrapper that takes a path and request options and returns the response body. It retries eligible GET failures for up to three attempts by default, using jitter or retryAfterSec.
Ticket
Build app/lib/retry.ts, a reusable wrapper around the API client that retries eligible GET requests after transient failures. It returns the successful response body or throws the error from the last failed attempt.
Mobile connections can fail temporarily, and retrying every failed request is not safe. You need a bounded policy that distinguishes read requests from writes and respects a server-provided retry delay when one is available. The later optional cart and search exercises are independent. Order submission continues to rely on its idempotency-key rather than blind retries.
Acceptance criteria
- A successful first request returns its response body without calling
sleep. - A GET request that fails with an
ApiErrorstatus of503and then succeeds is retried and returns the successful response body. - A GET request that fails with a non-
ApiError, such as a network error, is retried. - An
ApiErrorwith a 4xx status is thrown immediately without another request or a sleep. - A POST request that fails with an
ApiErrorstatus of503is not retried. - When
maxAttemptsis configured, the wrapper makes no more than that number of total attempts and throws the error from the last failed attempt. - The wrapper does not call
sleepafter the final failed attempt. - When
random()returns1, the exponential delay doubles after each failure. With the defaultbaseMsof200, the uncapped delays are200ms,400ms, and800ms. - The wrapper scales each calculated delay by the injected
random()value, using full jitter. - The wrapper caps the exponential backoff value at
maxMsbefore applying jitter. The defaultmaxMsis5000ms. - When a failed
ApiErrorhas a definedretryAfterSec, the wrapper waits exactlyretryAfterSec * 1000milliseconds instead of calculating a jittered delay. It does not apply themaxMscap to this value. - A request with
method: "GET"is retried when it fails with a retryable error.
Constraints
- Create only
app/lib/retry.ts. Do not modifyapp/lib/api.ts, shared test fakes, or provided test files. - Import
ApiErrorandRequestOptionsfrom./api. - Treat an undefined request method as
GET. Only GET requests are eligible for retries. - Retry non-
ApiErrorfailures andApiErrorresponses with a status of500or above. Do not retry otherApiErrorresponses, including HTTP 429 Too Many Requests. - Use three total attempts by default, including the first request. The default
baseMsis200, and the defaultmaxMsis5000. - Calculate the delay before the next attempt after failure number
nasrandom() * min(maxMs, baseMs * 2^(n-1)). - Use
retryAfterSec * 1000exactly when a definedretryAfterSecis present on anApiError. Do not apply jitter or the maximum delay cap to this delay. - Default
sleepto a Promise-based delay usingsetTimeout. DefaultrandomtoMath.random. - Route every wait through the injected
sleepand every jitter calculation through the injectedrandom.
Design direction
Keep the retry policy in app/lib/retry.ts. Let it wrap the existing API client rather than changing the shared client. Use ApiError to distinguish HTTP failures from other thrown errors.
Check the effective request method before entering the retry loop. Keep request options and retry configuration separate. Return the response body directly when a request succeeds.
Consider these trade-offs:
- Retrying only idempotent methods avoids repeating operations that may change server state. Do not extend this policy to POST requests. Order creation uses an idempotency key for duplicate protection.
- Full jitter spreads retries from clients that experienced failures at the same time. The delay remains bounded by
maxMsfor calculated backoff, but a server-provided retry delay takes precedence. - Injected timing and randomness make the policy deterministic in tests. The default implementations still provide normal delays and randomness in the app.
Any layout that meets the contract passes.
How to check your work
Run the exercise tests and then the TypeScript check:
cd backend && make test W=4O1
cd app && npx tsc --noEmitRead the first failing assertion before changing code. It identifies the request behaviour, attempt count, or delay that differs from the contract.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Create
app/lib/retry.tsand exportRetryOptionsandrequestWithRetry. - Retry only eligible GET failures and preserve immediate failures for other HTTP errors.
- Apply bounded exponential backoff with full jitter.
- Respect
retryAfterSecand avoid sleeping after the final attempt. - Pass
make test W=4O1andnpx tsc --noEmit.
Commands
cd backend && make test W=4O1cd app && npx tsc --noEmitTests
W4 O1 Retry with backoff and jitter (12 tests)inapp-tests/lib/retry.test.ts