Implementing Retry Policy (React Native & Beyond)
Source: Dev.to
What is a Retry Policy?
A retry policy is a strategy where your application automatically retries a failed request instead of immediately showing an error to the user.
From the user’s perspective, everything just works:
“I made a request → I saw a loader → I got my result.”
Behind the scenes, your app may have retried that request multiple times before eventually succeeding.
Why Does This Matter?
Network calls are not always reliable. Failures can happen due to temporary server issues (5xx errors), network instability (timeouts, poor connectivity), rate limiting, or other transient failures.
If you immediately show an error, you force users to retry manually, restart their whole flow again, and potentially lose trust in your app.
A retry policy smooths over these temporary issues and improves overall user experience. It’s a universal resilience pattern used across backend services, cloud systems, distributed systems, message queues, and more. When implemented correctly, users never even know something went wrong—that’s the goal.
Implementation
// Helper to pause execution
const wait = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
type RetryOptions = {
retries: number;
delay: number;
factor?: number; // exponential multiplier
};
async function retryRequest(
fn: () => Promise<any>,
{ retries, delay, factor = 2 }: RetryOptions
): Promise<any> {
let attempt = 0;
while (attempt < retries) {
try {
// Try the request; if it succeeds, return the result
return await fn();
} catch (error: any) {
attempt++;
// If we've exhausted retries, re‑throw the error
if (attempt >= retries) throw error;
// Calculate exponential back‑off delay
const backoff = delay * Math.pow(factor, attempt - 1);
await wait(backoff);
}
}
}
// Example request function
const fetchUser = async () => {
const response = await fetch("https://api.example.com/user");
if (!response.ok) {
const err: any = new Error("Request failed");
err.response = { status: response.status };
throw err;
}
return response.json();
};
// Wrapper that applies the retry policy
const getUserWithRetry = async () => {
try {
const data = await retryRequest(fetchUser, {
retries: 3,
delay: 1000, // initial delay in ms
});
console.log("Success:", data);
} catch (error) {
console.log("Final failure:", error);
}
};Call getUserWithRetry() wherever you need to fetch the user. If the request fails due to a transient issue, the retry policy automatically kicks in and attempts the request again behind the scenes.
In Conclusion
Retry policies are a simple but powerful way to improve reliability, reduce user frustration, and handle transient failures gracefully. It’s a small addition that can make your application feel significantly more stable and production‑ready.