Riya is on the metro. She opens QuickBite (a made-up food delivery app), adds a biryani, applies a coupon and taps Pay ₹349.
The train enters a tunnel.
- The spinner keeps spinning.
- Did the payment go through?
- Is the coupon gone?
- If she taps Pay again, will she be charged twice?
- If she swipes the app away, what happens to the half-finished order?
Patterns like Circuit Breaker and Saga are usually taught with backend microservices. But a mobile app is also one part of a distributed system, with an unreliable network and a process that the OS can kill. This post shows which patterns help on Android, and where each one stops helping.
The cheat sheet
| Pattern | Question it answers | Android / Kotlin tool |
|---|---|---|
| Timeout | How long do I wait? | OkHttp timeouts, withTimeout
|
| Retry + backoff + jitter | Was it a temporary glitch? | Arrow Schedule, WorkManager backoff |
| Circuit breaker | Should I even try right now? | Arrow CircuitBreaker
|
| Fallback | What do I show if it fails? | Room cache |
| Bulkhead | Can one slow feature starve the others? | coroutine Semaphore
|
| Single-flight | Why are 5 calls refreshing the token? | OkHttp Authenticator + lock |
| Idempotency key | Is it safe to send this again? | UUID + server support |
| Saga | Step 3 failed. How do I undo 1 and 2? | Arrow saga, or Room + WorkManager |
| Outbox | How do I avoid losing a user's write? | Room transaction + WorkManager |
Setup (check the latest versions and Kotlin compatibility before copying):
dependencies {
implementation("io.arrow-kt:arrow-resilience:2.3.0.1")
implementation("androidx.work:work-runtime-ktx:<latest>")
implementation("androidx.room:room-ktx:<latest>")
// plus Retrofit and OkHttp
}
The snippets focus on the patterns. DI, DTOs and most imports are left out.
1. Timeout: never wait forever
val client = OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.callTimeout(15, TimeUnit.SECONDS) // limit for the whole call
.build()
Treat these numbers as starting points and tune them from your own latency data.
The most important rule in this post: a timeout does not mean "it failed". It means "I don't know". The server may have charged Riya, and only the response got lost.
2. Retry with exponential backoff and jitter
Retry only errors that can fix themselves. A 400 Invalid coupon will stay invalid however often you send it.
fun Throwable.isTransient(): Boolean = when (this) {
// Simplification: some IOExceptions (e.g. certificate errors) are permanent
is IOException -> true
is HttpException -> code() == 408 || code() == 429 || code() in 500..599
else -> false
}
val networkRetry =
Schedule.exponential<Throwable>(300.milliseconds)
.jittered() // so thousands of phones don't retry in sync
.and(Schedule.recurs(2)) // 1 call + max 2 retries
.doWhile { error, _ -> error.isTransient() }
// usage (import arrow.resilience.retry)
val menu = networkRetry.retry { api.getMenu(restaurantId) }
Watch out for:
- Retry only reads, or writes that are idempotent.
- Don't stack retries blindly. OkHttp has its own connection-failure recovery. An interceptor, a repository and a worker that each make 3 attempts can multiply into 27 calls.
- If the server sends
Retry-After, respect it. The simple policy above does not read it.
3. Circuit breaker: stop knocking on a closed door
The recommendations service is down. Without a breaker, every screen waits, retries and fails, which costs battery, data and patience.
CLOSED ──too many failures──▶ OPEN ──reset timeout over──▶ HALF-OPEN
▲ ▲ │
│ └────────trial fails───────────┤
└───────────────────────────────────trial succeeds──────────┘
- Closed: calls go through.
-
Open: calls fail immediately with
ExecutionRejected. - Half-open: one trial call is allowed through.
// ONE shared instance per backend service (e.g. a Hilt @Singleton).
// A new breaker per call or per ViewModel remembers nothing useful.
val recoBreaker = CircuitBreaker(
openingStrategy = CircuitBreaker.OpeningStrategy.Count(maxFailures = 3),
resetTimeout = 10.seconds,
exponentialBackoffFactor = 2.0,
maxResetTimeout = 2.minutes,
)
With the Count strategy, the breaker opens once failures exceed the limit, and a success resets the counter.
The trap: 4xx errors can open your breaker
A Retrofit suspend function that returns the body type throws HttpException for non-2xx responses. The breaker sees any exception from its block as a failure, so a few "invalid coupon" responses could block a healthy service. Return business rejections as values:
sealed interface Outcome<out T> {
data class Success<T>(val value: T) : Outcome<T>
data class Rejected(val code: Int) : Outcome<Nothing>
}
suspend fun <T> CircuitBreaker.guard(block: suspend () -> T): Outcome<T> =
protectOrThrow<Outcome<T>> {
try {
Outcome.Success(block())
} catch (e: HttpException) {
if (e.isTransient()) throw e // counts against the breaker
Outcome.Rejected(e.code()) // the service is alive
}
}
A mobile caveat: your breaker lives on one phone and can't tell "server is down" from "Riya is in a tunnel". It also resets when the process dies. It complements server-side protection and does not replace it.
4. Fallback: fail soft
Combine retry, breaker and a cached answer:
sealed interface RecoResult {
data class Fresh(val items: List<Dish>) : RecoResult
data class Stale(val items: List<Dish>) : RecoResult
data object Hidden : RecoResult
}
class RecoRepository(
private val api: RecoApi,
private val dao: DishDao,
private val breaker: CircuitBreaker,
) {
suspend fun load(): RecoResult = try {
// retry is outside, so every attempt is counted by the breaker.
// ExecutionRejected is not transient, so an open circuit isn't retried.
when (val result = networkRetry.retry { breaker.guard { api.recommendations() } }) {
is Outcome.Success -> {
dao.replaceAll(result.value)
RecoResult.Fresh(result.value)
}
is Outcome.Rejected -> cached()
}
} catch (e: CircuitBreaker.ExecutionRejected) {
cached()
} catch (e: IOException) {
cached()
} catch (e: HttpException) {
cached()
}
// No catch (Throwable): it would also swallow coroutine cancellation.
private suspend fun cached(): RecoResult {
val items = dao.getAll()
return if (items.isEmpty()) RecoResult.Hidden else RecoResult.Stale(items)
}
}
Fallbacks suit menus and recommendations. Never fake success for a payment. Show "Checking payment status" instead.
For core screens, go further with offline-first: the UI observes Room, and the network only updates Room. Android's guide treats the local source as the source of truth.
5. Bulkhead: isolate the noisy neighbour
Image uploads for reviews shouldn't take up all the capacity while checkout waits.
class ReviewUploader(private val api: ReviewApi) {
private val permits = Semaphore(permits = 2) // kotlinx.coroutines.sync
suspend fun upload(photo: Photo) = permits.withPermit { api.upload(photo) }
}
Keep one shared ReviewUploader. Note that limitedParallelism(2) limits running threads, not in-flight suspending calls, so the semaphore is the right tool here.
6. Single-flight token refresh
The token expires and five parallel calls get 401. You want one refresh, not five.
class TokenAuthenticator(private val tokens: TokenStore) : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
if (response.priorResponse != null) return null // simple loop guard
synchronized(this) {
val sent = response.request.header("Authorization")
val current = tokens.accessToken()
val fresh = if (sent != "Bearer $current") current // someone already refreshed
else tokens.refreshBlocking() ?: return null
return response.request.newBuilder()
.header("Authorization", "Bearer $fresh")
.build()
}
}
}
refreshBlocking() must use a separate client without this authenticator.
7. Idempotency key: the double-charge killer
Create one ID for one user intent, save it, and reuse it on every retry.
interface CheckoutApi {
@POST("holds")
suspend fun holdStock(@Body body: HoldRequest, @Header("Idempotency-Key") key: String): Hold
@POST("payments")
suspend fun charge(@Body body: ChargeRequest, @Header("Idempotency-Key") key: String): Payment
@POST("orders")
suspend fun confirm(@Body body: ConfirmRequest, @Header("Idempotency-Key") key: String): Order
@POST("payments/{id}/refund")
suspend fun refund(@Path("id") id: String, @Header("Idempotency-Key") key: String)
@DELETE("holds/{id}")
suspend fun releaseHold(@Path("id") id: String, @Header("Idempotency-Key") key: String)
}
The header alone does nothing. The backend must store the key and, for a repeated request, return the original result without doing the work again. A new UUID per retry defeats the whole idea.
(charge here means a wallet or saved payment method. With a payment gateway SDK, follow its flow and verify the status on your server.)
8. Saga: undo what you already did
QuickBite's checkout has three remote steps. There is no single database transaction across them, so each step needs a compensating action.
| Step | Action | Compensation |
|---|---|---|
| 1 | Hold stock | Release hold |
| 2 | Charge ₹349 | Refund |
| 3 | Confirm order | (final step) |
First: where should the saga live?
For money and inventory, prefer a server-side orchestrator. The app sends one POST /checkouts with an idempotency key, then reads the status. The server stays alive when Riya's phone doesn't, and you don't trust a client to issue refunds.
A client-side saga makes sense for flows such as create draft → upload photos → publish listing, or when you must coordinate APIs you don't control. We keep the checkout example because its failures are easy to picture. Any refund endpoint must still be validated by the server.
8a. In-memory saga with Arrow
suspend fun checkout(cart: Cart, checkoutId: String): Order = saga {
val hold = saga({
api.holdStock(HoldRequest(cart.id), "$checkoutId:hold")
}) { api.releaseHold(it.id, "$checkoutId:release") }
val payment = saga({
api.charge(ChargeRequest(cart.id, cart.total), "$checkoutId:charge")
}) { api.refund(it.id, "$checkoutId:refund") }
saga({
api.confirm(ConfirmRequest(hold.id, payment.id), "$checkoutId:confirm")
}) { /* last step: nothing after it can fail */ }
}.transact()
If a later step throws, Arrow runs the compensations of the completed steps. It's clean, but it has two serious holes:
-
Ambiguous failures. If
chargetimes out, that step never "completed", so its refund is not run, yet money may have moved. Ifconfirmtimes out, the code refunds and releases, but the order may actually be confirmed. You must check the status or retry with the same key before compensating. - Process death. This saga's progress is only in memory. If the OS kills the app after the charge, nothing resumes it.
So don't use this version as is for real payments.
8b. Durable saga with Room + WorkManager
Save progress after every step. On an unknown result, retry the same step with the same key. Compensate only on a definite rejection.
enum class Step { STARTED, STOCK_HELD, PAID, CONFIRMED, COMPENSATING, FAILED, NEEDS_SUPPORT }
// Progress of each compensation, tracked separately
enum class UndoStatus { PENDING, DONE, REJECTED } // DONE also means "nothing to undo"
@Entity(tableName = "checkout_saga")
data class CheckoutSaga(
@PrimaryKey val id: String, // the checkoutId
val cartId: String,
val amountPaise: Long,
val step: Step = Step.STARTED,
val holdId: String? = null,
val paymentId: String? = null,
val refund: UndoStatus = UndoStatus.PENDING,
val release: UndoStatus = UndoStatus.PENDING,
)
@Dao
interface SagaDao {
@Query("SELECT * FROM checkout_saga WHERE id = :id")
suspend fun get(id: String): CheckoutSaga?
@Upsert
suspend fun save(saga: CheckoutSaga)
}
class CheckoutWorker(
context: Context,
params: WorkerParameters,
private val dao: SagaDao, // inject with a WorkerFactory / @HiltWorker
private val api: CheckoutApi,
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val id = inputData.getString("id") ?: return Result.failure()
var s = dao.get(id) ?: return Result.failure()
while (true) {
try {
s = when (s.step) {
Step.STARTED -> {
val hold = api.holdStock(HoldRequest(s.cartId), "$id:hold")
s.copy(step = Step.STOCK_HELD, holdId = hold.id)
}
Step.STOCK_HELD -> {
val payment = api.charge(
ChargeRequest(s.cartId, s.amountPaise), "$id:charge"
)
s.copy(step = Step.PAID, paymentId = payment.id)
}
Step.PAID -> {
api.confirm(
ConfirmRequest(s.holdId!!, s.paymentId!!), "$id:confirm"
)
s.copy(step = Step.CONFIRMED)
}
Step.COMPENSATING -> {
val next = compensate(s)
// still unresolved: try again later
if (next.step == Step.COMPENSATING) return Result.retry()
next
}
Step.CONFIRMED -> return Result.success()
Step.FAILED, Step.NEEDS_SUPPORT -> return Result.failure()
}
dao.save(s)
} catch (e: IOException) {
return Result.retry() // outcome unknown: same step, same key
} catch (e: HttpException) {
if (e.isTransient()) return Result.retry()
// Definite rejection. Assumes your API contract guarantees
// that this response means the step did NOT happen.
// compensate() handles its own errors, so this is a forward step
s = s.copy(step = Step.COMPENSATING)
dao.save(s)
}
}
}
// Tries both compensations (refund first). A failed refund
// doesn't stop the hold release. Progress is saved after each one.
private suspend fun compensate(start: CheckoutSaga): CheckoutSaga {
var s = start
if (s.refund == UndoStatus.PENDING) {
val paymentId = s.paymentId
val status =
if (paymentId == null) UndoStatus.DONE
else attemptUndo { api.refund(paymentId, "${start.id}:refund") }
s = s.copy(refund = status)
dao.save(s)
}
if (s.release == UndoStatus.PENDING) {
val holdId = s.holdId
val status =
if (holdId == null) UndoStatus.DONE
else attemptUndo { api.releaseHold(holdId, "${start.id}:release") }
s = s.copy(release = status)
dao.save(s)
}
val results = listOf(s.refund, s.release)
val step = when {
UndoStatus.PENDING in results -> Step.COMPENSATING
UndoStatus.REJECTED in results -> Step.NEEDS_SUPPORT
else -> Step.FAILED // checkout failed, cleanup complete
}
return s.copy(step = step)
}
private suspend fun attemptUndo(call: suspend () -> Unit): UndoStatus = try {
call()
UndoStatus.DONE
} catch (e: IOException) {
UndoStatus.PENDING // outcome unknown: retry with the same key
} catch (e: HttpException) {
if (e.isTransient()) UndoStatus.PENDING else UndoStatus.REJECTED
}
}
Start it as unique work, so a double tap on the same checkout doesn't create two workers:
fun enqueueCheckout(context: Context, checkoutId: String) {
val request = OneTimeWorkRequestBuilder<CheckoutWorker>()
.setInputData(workDataOf("id" to checkoutId))
.setConstraints(
Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork("checkout-$checkoutId", ExistingWorkPolicy.KEEP, request)
}
Production checklist:
- If the app dies after the server succeeds but before
dao.save, the step runs again. Idempotency keys make that safe. - Saving the row and enqueuing the work are not one atomic operation. On app start, re-enqueue unfinished sagas.
- Create the
checkoutIdonce and reuse it while that checkout is unfinished. Unique work can't help if each tap creates a new ID. - WorkManager is for persistent work, not instant work. It may run later, so show a "Processing" state by observing the Room row.
- Keys expire on many servers, and holds expire too. After a long offline gap, check status with the server first. Often you shouldn't charge hours later without asking the user.
- Give
NEEDS_SUPPORTa real UI and alerting. Compensations can fail too. Show support which one was rejected: refund, release or both. If one is rejected while the other is still pending, consider alerting right away. - Releasing the hold even when the refund fails assumes your business rules allow it. If they don't, keep the hold and send both to support.
- Your API should return success for "already refunded" or "already released". Otherwise a finished compensation can look rejected.
- If you already ship the old table, the two new columns need a Room migration.
9. Outbox: never lose a user's write
After delivery, Riya writes a review while offline. Save the review and a "to be sent" record in one Room transaction.
suspend fun submitReview(review: Review) {
db.withTransaction {
db.reviewDao().insert(review.copy(synced = false))
db.outboxDao().insert(
OutboxItem(id = UUID.randomUUID().toString(), reviewId = review.id)
)
}
scheduleOutboxSync() // unique work with a network constraint
}
The worker reads pending items, sends each with OutboxItem.id as the idempotency key, and removes it only after the server accepts it. Move permanently rejected items to a failed state so they don't block the queue.
Think about scheduling too: with KEEP, an item added just as the running worker finishes can be left behind. APPEND_OR_REPLACE is one option, plus a sweep on app start.
Saga vs Outbox: a saga coordinates multiple steps with undo. An outbox makes sure a saved write isn't forgotten.
Back to Riya in the tunnel
| Moment | What protects her |
|---|---|
| Request hangs | Timeout |
| Brief signal drop | Retry with backoff |
| Recommendations service down | Circuit breaker + cached fallback |
| She taps Pay again | Disabled button + same checkout ID + idempotency key |
| She swipes the app away | Saga state in Room + WorkManager |
| Order is rejected after payment | Compensation: refund + release |
| Refund is rejected | Hold release is still attempted, then NEEDS_SUPPORT
|
| Offline review | Outbox |
(Force-stopping the app from system settings is different from swiping it away: scheduled work won't run until the app is opened again.)
What about other libraries?
-
Arrow Resilience: Kotlin-first and multiplatform, with
Schedule,CircuitBreakerandsaga. - Resilience4j: popular on JVM backends. Check its Java and Android compatibility for your version before adding it to an app.
- Plain coroutines: enough for timeouts and a semaphore. Think twice before hand-writing a circuit breaker, because concurrency and half-open behaviour are easy to get wrong.
Don't over-engineer
- A simple read screen: timeout + cache is often enough.
- A flaky, optional backend feature: add a circuit breaker.
- An important write: idempotency + outbox.
- A multi-step transaction: server-side saga first, durable client saga only if you must.
Test the unhappy paths
- Use MockWebServer to return 500s, 429s, slow responses and dropped connections.
- Kill the process between saga steps and check that it resumes.
- Drop the response after the server processes a charge, and verify there is only one charge.
- Test a rejected refund and verify that the hold release is still attempted.
The happy path shows that your app works. These tests show whether Riya can trust it.
References: Arrow Resilience · Arrow CircuitBreaker · Arrow Saga · Android offline-first guide
Which failure has bitten your app in production? Tell me in the comments. 👇
Related Reading
- One Codebase, Two Attack Surfaces: A Practical Guide to Securing Kotlin Multiplatform Apps
- Kotlin Multiplatform for Android Developers: Share Your Business Logic with Ktor, Koin and Clean Architecture
- Real-Time Chat on Android with Socket.IO, Kotlin Flow and Room (Offline-First Architecture)
About the Author
Padmakar Garg is an Android developer with 8+ years of experience in Kotlin, Java, Jetpack Compose, Kotlin Multiplatform, scalable architecture and mobile security.
- Portfolio: gargpadmakar.github.io
- GitHub: github.com/gargpadmakar
Top comments (5)
This is the clearest version of this idea I have read for mobile, especially the line that a timeout does not mean "it failed", it means "I don't know". Most Android posts stop at retry with backoff, but the two traps you call out are the ones that actually bite: 4xx errors opening the circuit breaker, and an in-memory saga dying with the process after a charge has already gone through. I build an offline-first Android app for gig workers, so a lost or duplicated write is not a cosmetic bug, it is someone's shift pay, which is why the durable Room + WorkManager saga and the outbox pattern stood out to me. Saving the write and the "to be sent" record in one transaction is the only part I fully trust when the network drops. One thing I would add from that world: the NEEDS_SUPPORT state needs a real UI, because a stuck checkout that only lives in logs will sit there for days. Which of these has actually bitten you in production, a breaker opening on 4xx errors, or a saga that did not survive process death?
Thank you! I don't have a production war story for either, but the lost saga worries me more, since money can move while the app forgets where it was.
Fully agree that NEEDS_SUPPORT needs a real UI, plus alerting for the team. How do you surface stuck writes to your gig workers?
Great question — and you are right that the lost saga is the scarier one, because a stuck write is invisible to the person it hurts most.
For gig workers I would surface it in three places, not one: first, right on the affected screen in plain language — "Payment status unclear, we are checking — no action needed yet" — never a toast that disappears; second, a persistent "needs attention" list in the app, so a worker who was offline can find the stuck job later, retry it, or reach support from that same screen; and third, on the team side, an alert tied to the same saga ID, because a worker cannot fix a failed compensation on their own.
The key lesson from your post for me is that NEEDS_SUPPORT is not an error state, it is a promise the app still owes someone. Would you make it blocking — the worker cannot take new jobs until it is resolved — or non-blocking with a persistent banner?
"A promise the app still owes someone" is a great way to put it. I like all three places, especially tying the team alert to the same saga ID.
One distinction I'd make in the UI: "we are checking, no action needed yet" fits while the outcome is unknown and the worker is still retrying. In the post's code, NEEDS_SUPPORT is different: a compensation was definitely rejected, and automatic processing stops. There the message should say it needs support, with a reference ID and a clear next step.
On blocking, I'd go non-blocking by default with a persistent banner. For a gig worker, blocking new jobs can turn our failure into their lost income. I'd block only what could make it worse, like paying again for the same transaction or repeating a payout on the affected job. Unrelated work stays open. Any wider limit should be an explicit, server-enforced risk rule, with the reason shown to the worker.
The line that a timeout means "I don't know" is the one I'd want every checkout screen built around. For the Pay step, what happens if Riya clears app data after the outbox row is written but before WorkManager runs it? The idempotency key lived in Room, so the retry after that would mint a new one unless the server can also match on something like a cart id.