Retry Logic for Failed Uploads
You'll learn how to automatically retry failed file uploads using exponential backoff to gracefully handle temporary network issues.
Why Uploads Fail (and Deserve a Second Chance)
Network hiccups, server timeouts, and temporary connectivity issues can interrupt uploads. Instead of forcing users to manually restart, smart retry logic—exponential backoff—automatically reattempts the upload with increasing wait times between tries.
Think of it like knocking on a busy friend's door: knock once, wait 1 second. No answer? Wait 2 seconds. Still nothing? Wait 4 seconds. Each retry gives the network more "breathing room" to recover.
The Exponential Backoff Strategy
The pattern doubles the wait time after each failure:
async function uploadWithRetry(file, maxRetries = 3) {
let attempt = 0;
while (attempt < maxRetries) {
try {
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
if (!response.ok) throw new Error('Upload failed');
return await response.json(); // Success!
} catch (error) {
attempt++;
if (attempt >= maxRetries) throw error;
// Exponential backoff: 1s, 2s, 4s, 8s...
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
You can enhance this with jitter (randomizing delays slightly) to prevent synchronized retries from overwhelming recovering servers, or maximum delay caps to avoid waiting too long.
When to Retry vs Fail
Retry for transient errors (network timeouts, 5xx server errors). Don't retry validation failures (4xx errors) or cancelled uploads—those won't succeed with repetition.
Key Takeaway: Exponential backoff retry logic automatically recovers from temporary upload failures by waiting progressively longer between attempts, improving user experience without manual intervention.