Building Retry Logic
Mobile networks in Africa can be unstable. Sometimes a request to SdashAPI will fail not because of a bug, but simply because a cell tower dropped the packet. Implementing automatic retry logic ensures a seamless experience for your users.
Exponential Backoff
2.22.1If a request fails, you shouldn't just spam the server by retrying immediately in a tight loop. Instead, you should wait a short amount of time, retry, and if it fails again, wait slightly longer. This is called Exponential Backoff.
async function fetchWithRetry(url, retries = 3, delay = 1000) {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, { headers: { "AccessToken": "YOUR_KEY" } });
if (!response.ok && response.status === 500) {
throw new Error("Server Error");
}
return await response.json(); // Success! Return the data
} catch (err) {
if (i === retries - 1) throw err; // Out of retries
console.warn(`Request failed. Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 2; // Double the delay for the next attempt
}
}
}When NOT to Retry
2.22.2You should only automatically retry on network failures (promise rejections) or 5xx Server Errors. If the API returns a 401 Unauthorized or a 400 Bad Request, retrying is pointless because your API key is invalid or your parameters are wrong. No amount of retrying will fix those errors!