DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
Mountain View desk9 min

Designing Safer API Failover in an Android App

Network availability does not mean an API endpoint is healthy. Learn which layer should handle each failure, how to classify errors, bound retries, and keep writes safe during Android API failover.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An Android app should not switch API endpoints just because the device reports a connection. “Network available” means the operating system has a usable network path. It does not tell you whether your API origin is reachable, healthy, or safe to call again. Safer failover comes from giving each failure to the layer that can actually fix it, classifying errors before any retry, bounding every retry by both attempt count and elapsed time, and treating repeated writes as a separate question from repeated reads.

Five layers that are often treated as one

Most failover bugs in Android clients come from one layer quietly doing another layer’s job. A retry loop wrapped around a request that the HTTP client already retried, or a network callback used as proof that a server is healthy, are two common examples. The responsibilities separate cleanly:

As an Amazon Associate I earn from qualifying purchases.

Layer Typical component What it can recover What it cannot decide
Operating-system network transitions ConnectivityManager and NetworkCallback Tells the app that a network became available, changed, or was lost Whether any particular API origin is healthy
HTTP-client route recovery OkHttp (or the client you ship) Trying another route when connection establishment fails in limited cases, such as a host that resolves to several addresses Choosing a different API base URL, or whether a request body is safe to send again
Application endpoint selection Your network or repository layer Moving traffic to an alternate origin that has compatible API and data semantics Whether that origin holds the same data or accepts the same credentials
Retry policy Your call wrapper Repeating transient failures with increasing, bounded delays Whether the operation is idempotent or the server already applied it
Persistent synchronization WorkManager and a local queue Finishing deferred work after constraints such as a connected network are met An interactive answer inside a user’s deadline

Design each failure path by asking which row owns it. A DNS failure on one address may belong to OkHttp. A 503 from an origin that is overloaded belongs to your retry policy and possibly your endpoint selection. A queued profile edit belongs to persistent sync. Keeping these ownership lines explicit is what prevents a short outage from multiplying into a storm of requests.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Network availability is not endpoint health

Android’s connectivity APIs report transitions on the device, not the state of your service. Registering a NetworkCallback tells you that a network became available, changed capabilities, or was lost. Two caveats matter for failover design:

#1 Best Overall
Sale
Samsung Galaxy A17 5G Smart Phone 128GB US 1 Yr Manufacturer Warranty Black
  • YOUR CONTENT, SUPER SMOOTH: The ultra-clear 6.7" FHD+ Super AMOLED display of Galaxy A17 5G helps bring your content to life, whether you're scrolling through recipes or video chatting with loved ones.¹
  • LIVE FAST. CHARGE FASTER: Focus more on the moment and less on your battery percentage with Galaxy A17 5G. Super Fast Charging powers up your battery so you can get back to life sooner.²
  • MEMORIES MADE PICTURE PERFECT: Capture every angle in stunning clarity, from wide family photos to close-ups of friends, with the triple-lens camera on Galaxy A17 5G.
  • NEED MORE STORAGE? WE HAVE YOU COVERED: With an improved 2TB of expandable storage, Galaxy A17 5G makes it easy to keep cherished photos, videos and important files readily accessible whenever you need them.³
  • BUILT TO LAST: With an improved IP54 rating, Galaxy A17 5G is even more durable than before.⁴ It’s built to resist splashes and dust and comes with a stronger yet slimmer Gorilla Glass Victus front and Glass Fiber Reinforced Polymer back.
  • Callback values can be stale. The API reference warns that querying network capabilities synchronously from inside a callback can return outdated or null values. Use the callback as a trigger to re-evaluate state, and read the details in a context where you can handle the result properly.
  • Losing events are not guaranteed. onLosing is not guaranteed to fire before a sudden loss, such as a network dropping out of range. Code that depends on it for a graceful switch will sometimes be surprised.

A reasonable use of the callback is to resume a paused sync queue or to schedule a lightweight probe after a network becomes available. Deciding that an origin is healthy requires evidence from your own requests, such as recent success rates or response times against that origin.

What OkHttp already recovers, and what it does not

OkHttp can select another route when connection establishment fails, in limited cases such as a host that resolves to multiple addresses. That is transport recovery for one origin. It does not switch your app from api.example.com to a backup base URL, and it does not decide whether a failed write was applied.

OkHttp also retries some connection failures internally. The behavior is controlled through OkHttpClient.Builder, including retryOnConnectionFailure, and the defaults can change across versions, so confirm the setting in the version you ship. If your application wraps the call in its own retries, the total number of attempts is the product of both layers. Three application attempts over an HTTP client that retries twice can produce nine network attempts for one user tap. Choose one place to own the attempt budget, and where a call must not be replayed at the transport level, make that explicit in the client configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The Android media documentation recommends a single network-stack instance within an app when using HttpEngine, Cronet, or OkHttp. That recommendation is stated in the media context, and the HttpEngine guidance is scoped to API 34 or S extensions 7. Treat it as a good default for sharing connection pools, not as a rule for every Android network workload.

Rank #2
Tracfone Motorola Moto G 2025, 64GB, Saphire Blue (Locked to
  • Carrier: This phone is locked to Tracfone, which means this device can only be used on the Tracfone wireless network. Tracfone plan required, activating is easy, just 3 steps.
  • DISPLAY: Immersive viewing on a 6.7-inch super-bright 120Hz display with powerful stereo speakers and Bass Boost for cinematic entertainment.
  • CAMERA SYSTEM: Advanced 50MP Quad Pixel camera captures sharp, detailed photos and videos in any lighting condition
  • PERFORMANCE: Lightning-fast 5G connectivity paired with a powerful processor and RAM Boost for smooth multitasking.
  • BATTERY LIFE: Long-lasting 5000mAh battery with TurboPower charging technology delivers hours of power in minutes.

Classify errors before you retry

Android’s offline-first architecture guidance recommends classifying network errors and setting a maximum retry count. It also says not to retry unauthorized requests until proper credentials are available. The exact list of retryable HTTP statuses, and which ones deserve honoring a Retry-After header, comes from your API contract. The Android sources do not supply a universal list.

Outcome Typical examples Retry? Notes
Failure before the request was sent No route, DNS resolution failure, connect timeout Yes, bounded An alternate endpoint is worth considering only if one exists and is compatible
Timeout before a response Read or call timeout with no status line Only if the operation is safe to repeat The server may have applied the write (see the next section)
Transient server response Statuses the API contract marks as temporary, such as 503 or 429 where documented Yes, with backoff Honor Retry-After when the API sends it
Unauthorized 401 with an expired access token Not until a credential remedy exists Refresh the credential once, then stop and surface the failure
Deterministic client error 400, 404, 422 for a malformed or invalid request No Repeating the same request will not change the result; fix the input or the contract mismatch

The classification belongs in one function that every network call uses. If each screen decides for itself what counts as retryable, the same backend error will be retried in some places and not others.

Make writes safe to repeat before replaying them

A timeout does not prove that the server failed to apply a request. The request may have reached the server, been committed, and lost its response on the way back. Replaying a non-idempotent write in that state can create a duplicate order, a second payment attempt, or a repeated comment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The general engineering pattern is an idempotency key. The client generates one unique key per logical operation, sends it with every attempt, and the server uses it to return the original result rather than applying the change again. This is a server-side contract. The Android sources reviewed do not specify an idempotency protocol, so confirm that the API supports one before you build automatic replay on top of it.

Rank #3
Sale
Samsung Galaxy A17 5G Smart Phone 128GB, US 1 Yr Manufacturer Warranty Blue
  • YOUR CONTENT, SUPER SMOOTH: The ultra-clear 6.7" FHD+ Super AMOLED display of Galaxy A17 5G helps bring your content to life, whether you're scrolling through recipes or video chatting with loved ones.¹
  • LIVE FAST. CHARGE FASTER: Focus more on the moment and less on your battery percentage with Galaxy A17 5G. Super Fast Charging powers up your battery so you can get back to life sooner.²
  • MEMORIES MADE PICTURE PERFECT: Capture every angle in stunning clarity, from wide family photos to close-ups of friends, with the triple-lens camera on Galaxy A17 5G.
  • NEED MORE STORAGE? WE HAVE YOU COVERED: With an improved 2TB of expandable storage, Galaxy A17 5G makes it easy to keep cherished photos, videos and important files readily accessible whenever you need them.³
  • BUILT TO LAST: With an improved IP54 rating, Galaxy A17 5G is even more durable than before.⁴ It’s built to resist splashes and dust and comes with a stronger yet slimmer Gorilla Glass Victus front and Glass Fiber Reinforced Polymer back.

Without server support, use one of these safer paths:

  • Replay only reads and operations the server documents as idempotent, such as a PUT that replaces a full resource with the same content.
  • Queue the write locally with its client-generated identifier, and reconcile by fetching server state before replaying.
  • Surface the outcome to the user when deferral would change the meaning of the action, for example a time-sensitive booking.

Bound recovery by attempts and by time

Android’s offline-first guidance describes exponential backoff this way: “In exponential backoff, the app keeps attempting to read from the network data source with increasing time intervals until it succeeds, or other conditions dictate that it should stop.” That final clause is the important part. Backoff without a stopping condition is just a slower endless loop. Every policy needs three limits: a maximum attempt count, an overall time budget tied to what the user is waiting for, and a cap on individual delays.

The following sketch shows the shape of a bounded interactive retry. It catches cancellation and rethrows it, applies a capped exponential delay with a little jitter, and checks the budget before sleeping. The predicate isRetryable should be the single classification function described above.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlin.random.Random

suspend fun <T> callWithBudget(
    maxAttempts: Int = 3,
    baseDelayMs: Long = 500L,
    maxDelayMs: Long = 4_000L,
    budgetMs: Long = 10_000L,
    isRetryable: (Throwable) -> Boolean,
    block: suspend (attempt: Int) -> T
): T {
    val started = System.nanoTime()
    var attempt = 1
    while (true) {
        try {
            return block(attempt)
        } catch (e: CancellationException) {
            throw e
        } catch (e: Throwable) {
            val elapsedMs = (System.nanoTime() - started) / 1_000_000
            val delayMs = minOf(maxDelayMs, baseDelayMs shl (attempt - 1))
            val outOfBudget = elapsedMs + delayMs > budgetMs
            if (!isRetryable(e) || attempt >= maxAttempts || outOfBudget) throw e
            delay(delayMs + Random.nextLong(0, delayMs / 4 + 1))
            attempt++
        }
    }
}

Choose the budget from the user-facing deadline, not from the library defaults. A pull-to-refresh that shows a spinner can tolerate a few seconds; a checkout step usually cannot tolerate a silent ten-second retry and should show a clear state instead.

Rank #4
Sale
Samsung Galaxy S26 Ultra, Unlocked Android Smartphone, 512GB, Black
  • PRIVACY DISPLAY: Automatically hide your screen from those beside you. The built-in privacy display can be preset¹ to turn on when receiving notifications, typing passwords, or using specific apps
  • TYPE IT IN. TRANSFORM IT FAST: Enhance any shot in seconds on your smartphone by using Photo Assist² with Galaxy AI.³ Add objects, restore details, or apply new styles by simply typing or tapping
  • NIGHTS, CAPTURED CLEARLY: From gigs to city lights, record and capture moments after dark with clarity using Nightography so your photos and videos stay crisp and clear on your Samsung Galaxy
  • MAKE IT. EDIT IT. SHARE IT: Turn everyday moments into something personal with creative tools built right into your mobile phone, whether it’s a special contact photo, custom wallpaper, an invitation or more⁴
  • HELP THAT KEEPS UP: Stay in the moment while Now Nudge with Galaxy AI helps you respond faster and stay organized with smart suggestions⁵ that appear exactly when you need them on your phone
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Endpoint failover: only when the service supports it

Application-level failover to an alternate origin is a service-specific design. The Android sources do not define a universal algorithm, health threshold, circuit-breaker policy, or failback interval. Before adding one, confirm that the alternate origin meets these conditions:

  • Compatible API version. The same request and response schema, or a documented way to tell which version each origin speaks.
  • Consistent data. Writes made through one origin are visible through the other within a window your app can tolerate, or the app can detect and handle divergence.
  • Credentials that work on both. Tokens issued by one origin are accepted by the other, and the refresh flow does not depend on the failing origin.
  • Valid TLS for the alternate host. Certificates cover the alternate hostname, and certificate pinning, if used, includes the backup keys.
  • Defined health criteria. For example, a rolling window of recent requests with a failure ratio and minimum sample size, measured by your own traffic rather than the connectivity callback.
  • A failback rule. Decide when traffic returns to the primary origin, and avoid switching back on the first successful probe if the primary is still flapping.

If these conditions cannot be met, a second origin adds risk without adding safety. In that case, prefer cached reads, a clear offline state, and queued writes.

Choose the right execution lifetime

Interactive and background work fail differently, and they should not share one code path. Android’s architecture guidance uses local data and queues for offline-first behavior. WorkManager is suited to persistent synchronization that can wait for connectivity and retry later.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Aspect Interactive user action Persistent background sync
Deadline The user is waiting on screen Eventually consistent, hours are acceptable if the data is correct
Failure surface Immediate message with a retry control or a clear pending state Logged and surfaced through sync status, not blocking the UI
Retry mechanism Bounded in-process call wrapper with a time budget WorkManager retry with backoff under constraints
Survives process exit No Yes, when the work is enqueued persistently
Best fit Login, payment confirmation, loading a screen Uploading queued edits, refreshing cached content

A background sync can be expressed with a connected-network constraint and exponential backoff:

Best Value
Tracfone Moto g Play 2024 Prepaid Phone with a 1-Yr Plan Included
  • Carrier: This phone is locked to Tracfone, which means this device can only be used on the Tracfone wireless network. Activating is easy, just 3 steps.
  • ACTIVATION Promotion: Includes 1500 min, 1500 texts & 1500 MB Data + add more as you need it
  • CAMERA SYSTEM: 50MP Quad Pixel camera. Capture sharper, more vibrant photos day or night with 4x the light sensitivity.
  • PERFORMANCE: Blazing-fast Qualcomm performance. Get the speed you need for great entertainment with a Snapdragon 680 processor and 4GB of RAM.
  • 64GB built-in storage. Get plenty of room for photos, movies, songs, and apps. Made for US
val request = OneTimeWorkRequestBuilder<SyncWorker>()
    .setConstraints(
        Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()
    )
    .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
    .build()

WorkManager.getInstance(context).enqueueUniqueWork(
    "queue-sync",
    ExistingWorkPolicy.KEEP,
    request
)

Inside the worker, return Result.retry() only for failures your classification marks as transient. Return Result.failure() for deterministic errors, and leave authorization failures in a state that waits for a credential refresh rather than retrying blindly. Note that WorkManager’s retry policy does not replace the attempt limits you set in your own code; check the worker’s stop conditions as part of the same design.

Measure and test the failure modes

Recovery logic is hard to trust until it has been exercised. Log enough to explain each outcome without leaking secrets or payloads. Useful fields are the selected origin, attempt number, failure class, elapsed time, and final result. Never log access tokens, authorization headers, or request bodies that contain personal data.

Test these scenarios on a real device or emulator, and record what your build actually does:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. DNS or address failure for the primary origin, with and without an alternate origin configured.
  2. A connection that times out before any response arrives.
  3. A write that the server applies, followed by a dropped response, to confirm that replay does not duplicate the change.
  4. An expired access token, to confirm that the app refreshes once and does not loop.
  5. Server overload that returns the transient statuses your contract defines, including a Retry-After value if the API sends one.
  6. A Wi-Fi to mobile handoff during an in-flight request, and a return to Wi-Fi during a queued sync.

Record the results against the budgets you chose. If a scenario produces more network attempts than your design allows, the fix is almost always to remove a duplicated retry layer rather than to add a new one.

Quick Recap

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.