Retry URLSession Requests Without Duplicating Writes

The app sends a request to create an export. The connection disappears before the response arrives. Should it send the request again?

“The request failed” is not enough information. The server may have created the export successfully and lost the response on the way back. A second request can create a second export.

A useful retry policy answers two questions separately: could another attempt help, and is another attempt safe for this operation?

Classify the operation before the error

HTTP defines idempotent method semantics, and cautions against automatically retrying non-idempotent requests unless the client knows repetition is safe or knows the original operation was not applied. That distinction is described in RFC 9110.

For an app client, I like making the decision explicit:

enum RetrySafety {
    case repeatable
    case serverDeduplicated
    case unsafe
}

repeatable means the endpoint’s actual contract allows repetition. serverDeduplicated means the backend recognizes repeated attempts at one logical operation. unsafe is the default when we have neither guarantee.

Do not infer the entire policy from the method string. A poorly designed GET can still trigger a side effect, and a well-designed POST can support server-side deduplication. The contract matters.

Keep one identity for one user action

For a create-export endpoint that supports idempotency, generate the operation ID when the user starts that export, then persist it with the body or durable job:

struct PendingExport: Codable, Sendable {
    let operationID: UUID
    let projectID: UUID
    let format: String
}

func applyOperationIdentity(_ job: PendingExport, to request: inout URLRequest) {
    request.setValue(
        job.operationID.uuidString,
        forHTTPHeaderField: "Idempotency-Key")
}

That header name is a contract with this example’s backend. Adding it does not make an arbitrary endpoint idempotent. The service must associate the key with the operation, reject incompatible reuse, and define how long deduplication lasts. Stripe’s idempotent-request documentation is one concrete example of a service that documents those semantics.

Every retry uses the same operation ID and the same logical payload. A new user action gets a new ID. Generating a fresh UUID inside the retry loop defeats the purpose.

This is a case where client-only bookkeeping is insufficient: after a lost response, only the service can know whether the authoritative write committed. Prefer an existing backend idempotency or operation-status facility over inventing a second retry database in the app.

Make delay selection a pure function

The following policy allows at most three application-level attempts, recognizes a small set of transient failures, adds jitter, and respects a server-provided minimum delay:

import Foundation

func retryDelay(
    safety: RetrySafety,
    completedAttempts: Int,
    statusCode: Int? = nil,
    transportError: URLError.Code? = nil,
    serverMinimumDelay: TimeInterval? = nil,
    remainingBudget: TimeInterval,
    jitter: Double
) -> TimeInterval? {
    guard safety != .unsafe,
        (1..<3).contains(completedAttempts),
        remainingBudget.isFinite, remainingBudget > 0,
        (serverMinimumDelay ?? 0).isFinite,
        (0...1).contains(jitter)
    else { return nil }

    let retryableStatus =
        statusCode.map {
            [429, 502, 503, 504].contains($0)
        } ?? false
    let retryableTransport =
        transportError.map {
            [URLError.timedOut, .networkConnectionLost, .cannotConnectToHost]
                .contains($0)
        } ?? false
    guard retryableStatus || retryableTransport else { return nil }

    let backoff =
        pow(2, Double(completedAttempts - 1))
        * (0.5 + 0.5 * jitter)
    let delay = max(backoff, max(0, serverMinimumDelay ?? 0))
    guard delay < remainingBudget else { return nil }
    return delay
}

This is an example policy, not a universal table of retryable errors. Tune the status and transport cases to the endpoint. A 401 should go through the app’s authentication flow. A validation error should return to the user. Cancellation should end the work.

Nonfinite time inputs are rejected before computing a delay; a malformed parsed value must not turn into an immediate retry. Supply either the response status or the transport error from the attempt being evaluated. Keep the original response body available for useful error reporting; reducing every failure to “bad server response” loses information.

The function returns nil when it declines another automatic attempt. That can mean unsafe repetition, exhausted attempts, a permanent error, or insufficient remaining time. A production policy can return a richer enum if the UI or telemetry needs those reasons.

Do not shorten the server’s requested delay

Retry-After can contain a delay in seconds or an HTTP date. Parse the form the server sent before calling the policy. Its definition is in RFC 9110’s Retry-After section.

If the service asks us to wait 30 seconds and the foreground operation has only 10 seconds left, this policy stops. It does not clamp 30 down to 10 and retry earlier than requested.

For an unsupported or malformed header, use a documented endpoint policy. Do not silently parse an HTTP date as zero seconds. An HTTP-date also involves wall-clock interpretation; keep that conversion separate from the monotonic clock used to track your local operation budget.

Let cancellation interrupt the wait

The URLSession wrapper can call the policy after an attempt, then wait cooperatively:

try Task.checkCancellation()
try await Task.sleep(for: .seconds(delay))
try Task.checkCancellation()

Do not swallow the sleep’s cancellation error and immediately start the next request. That turns a user leaving the screen into another network attempt.

The delay budget only decides whether waiting fits. Apply an appropriate timeout or deadline to the request itself, and account for the entire operation. A two-second backoff followed by a sixty-second request does not satisfy a ten-second user-facing budget.

Also check which layer owns retries. URLSession, an API SDK, your repository, and a view model can otherwise multiply each other’s attempts. Keep one application policy close to the endpoint contract.

Test the dangerous cases first

September 2026 review: the pure policy compiles and its executable checks pass with Swift 6.4. The fixtures cover unsafe writes, transient responses, attempt exhaustion, cancellation, a server minimum, and a delay that exceeds the remaining budget. Jitter is an input, so tests inspect its endpoints without sleeping.

For a backend integration test, intentionally lose the response after the server commits the first write. Retry with the same operation identity and verify there is still exactly one export. Then reuse the key with a different payload and check the service’s documented rejection behavior.

That test proves more than a successful retry after a fake timeout. It proves the app can recover from an ambiguous result without asking the user to clean up duplicate work.