Friendly Fire From Your Network Layer: Auditing Swift Retry Logic Before the Bill Arrives
Photo: smartphone server network cables data center traffic, via images.stockcake.com
Every retry loop starts as a kindness. Someone hits a flaky connection in a hotel lobby, files a bug, and a well-meaning engineer adds a little loop around the request. Three attempts, maybe a one-second sleep. It ships. Nobody thinks about it again until the Monday after a holiday sale, when your API bill triples and the on-call channel fills up with 503s from your own app.
The tricky part about retry logic is that it looks correct in isolation. One client retrying three times is fine. Twenty thousand clients retrying at the same millisecond is a distributed denial-of-service attack that you wrote yourself, shipped to the App Store, and are now paying for.
This is an audit, not a rewrite. The goal is to find every place your Swift code decides to try again, understand how those retries stack up across your app, and put guardrails around them that protect the backend and the user at the same time.
Start With a Census, Not a Fix
Before you touch a single line, list every retry mechanism you have. On most iOS codebases that means searching for a handful of patterns: for attempt in 0..<, while retries <, Task.sleep, custom RetryPolicy types, and any Alamofire or Moya configuration hiding in a shared package.
Split the list into two columns. The first is transport failures — timeouts, lost connectivity, DNS hiccups. The second is HTTP responses — the 429s, 500s, and 503s that come back labeled and polite. They behave differently and they deserve different policies.
While you are in there, note which flows can fire at the same time. The classic offenders are app launch, pull-to-refresh, foreground notifications, and background refresh tasks. If three of those can trigger the same endpoint within a second of each other, you already have a herd. You just have not met it yet.
Instrument Before You Refactor
You cannot budget retries you cannot see. The fastest path to visibility on modern iOS is URLSessionTaskDelegate and its didFinishCollecting metrics, plus a lightweight ledger that records every attempt.
actor RetryLedger {
struct Event {
let endpoint: String
let attempt: Int
let status: Int?
let delay: Duration
let timestamp: Date
}
private var events: [Event] = []
func record(_ event: Event) {
events.append(event)
}
func snapshot() -> [Event] { events }
}
Wire this into your networking client behind a debug flag and ship it to TestFlight. Within a day you will know which endpoints retry the most, how long clients actually wait between attempts, and whether your delays are randomized at all. If the answer to that last question is no, keep reading.
The Bug That Costs Real Money
The naive loop usually looks like this:
for attempt in 0..<3 {
if let response = try? await session.data(for: request) {
return response
}
}
There is no delay, no cap, and no jitter. Every client that fails at second zero retries at second zero. If your outage begins because a load balancer blipped, this loop guarantees the blip becomes a stampede. And because iOS devices share cell towers and conference Wi-Fi, thousands of users hit the retry at almost the same instant.
That is the thundering herd in a nutshell. It is not a backend problem. It is a client design problem wearing a backend costume.
Replace It With Capped, Jittered Backoff
Exponential backoff is table stakes. The part teams forget is full jitter, which spreads retries across the whole window instead of lining everyone up at the same multiplier.
struct Backoff {
let base: Duration = .milliseconds(500)
let cap: Duration = .seconds(30)
func delay(for attempt: Int) -> Duration {
let exp = pow(2.0, Double(attempt))
let ceiling = min(Double(base.components.seconds) * exp, Double(cap.components.seconds))
return .seconds(Double.random(in: 0...ceiling))
}
}
Full jitter trades a slightly higher average latency for a dramatically smoother arrival curve. Your p99 will not love it. Your backend will.
Also respect Retry-After when the server sends it. If the API says wait sixty seconds, waiting two seconds and trying again is not persistence — it is ignoring the answer.
The Part Everyone Skips: Budgets
Backoff protects the server during a recovery. A budget protects it from your client ever getting that far.
Give each session a retry allowance — say, one retry for every ten successful requests, tracked in a token bucket. When the bucket is empty, fail fast and surface a friendly error. This is the difference between a client that retries forever and one that gives up gracefully when the whole world is down.
Pair that with a simple circuit breaker per host. After five consecutive failures, stop calling for thirty seconds and let the queue drain. The user sees a sensible message instead of a spinner that has been spinning since Halloween.
Not Every Failure Deserves a Second Chance
Audit your status handling while you are in there. A 400 means your request is wrong; retrying it three times just makes you wrong louder. Retry on 408, 429, and 5xx. Do not retry a POST that creates an order unless you have an idempotency key on the request. And check how URLSession background tasks behave in your app — they have their own retry semantics that can quietly double up with yours.
Ship the Guardrails, Then Watch
Once the policy is in place, add one dashboard: retries per successful request, broken down by endpoint. If that ratio creeps above five percent on a normal Tuesday, something upstream changed and you want to know before the invoice does.
The retry loop you wrote last spring was not malicious. It was just optimistic. A couple of hours of auditing turns that optimism into a policy that behaves the same way whether ten people are on the network or ten thousand. That is the version you want in the App Store when the next outage hits.