MVP Factory
EN
ai startup development

Kotlin coroutines: mastering structured concurrency

KW
Krystian Wiewiór · · 6 min read

Meta description: Deep dive into Kotlin coroutines: Job hierarchy, coroutineScope vs supervisorScope failure semantics, and where CoroutineExceptionHandler actually fires.

Tags: kotlin android architecture backend mobile


TL;DR

Structured concurrency in Kotlin is a correctness contract. The parent-child Job tree determines how exceptions propagate and how cancellations cascade. Using supervisorScope without understanding its failure semantics leads to silently swallowed errors. This post walks through the precise rules governing coroutineScope vs supervisorScope, async/await vs launch error semantics, and where CoroutineExceptionHandler actually fires.


Read this before you ship another coroutine feature

Silent data loss in async Kotlin code almost always has the same root cause: code written around the structured concurrency contract instead of with it. If you have ever shipped a coroutine-based feature only to discover that one branch of a parallel fetch silently failed, never surfaced an exception, and returned stale or empty data, you already know the cost. This post is a precise mental model for how the Job hierarchy actually works, so that never happens again.


The Job tree is not optional

Here is what most teams get wrong about structured concurrency: they treat the coroutine scope as a launching mechanism rather than a lifecycle contract. Every coroutine you launch is a child of a parent Job. When the parent cancels, children cancel. When a child fails with an unhandled exception, it propagates up, cancelling siblings and the parent.

coroutineScope {
    launch { fetchUserProfile() }   // Child A
    launch { fetchUserPosts() }     // Child B — if A throws, B is cancelled
}

This is not a bug. It is the guarantee that prevents half-completed pipelines from corrupting your state. In every production incident I have traced involving silent data loss in async code, the root cause was a coroutine scope used as a fire-and-forget launcher with no accounting for how the Job hierarchy propagates failures.


coroutineScope vs supervisorScope: what actually differs

The distinction comes down to failure propagation direction.

ScopeChild failure propagates to parent?Sibling cancellation on failure?Use when
coroutineScopeYesYesAll-or-nothing operations (transactions, pipelines)
supervisorScopeNoNoIndependent parallel tasks where partial success is valid

supervisorScope replaces the standard Job with a SupervisorJob, which does not forward child failures upward. What this means in practice:

supervisorScope {
    val a = async { fetchUserProfile() }
    val b = async { fetchUserPosts() }

    // If fetchUserProfile throws, b still completes
    // But you MUST call a.await() to surface the exception
    val profile = a.await()   // throws here — do not skip this
    val posts   = b.await()
}

The dangerous pattern is calling launch inside supervisorScope and never attaching a CoroutineExceptionHandler. The exception is swallowed. The coroutine fails. Nothing tells you.


async/await vs launch: different error contracts

This distinction alone eliminates an entire class of production bugs.

  • launch delivers exceptions to the parent Job immediately on failure. In a supervisor scope, they go to CoroutineExceptionHandler or are lost.
  • async holds the exception in the Deferred until you call .await(). The exception does not propagate until that point.
// DANGEROUS: exception inside launch in supervisorScope is lost without a handler
supervisorScope {
    launch {
        throw IllegalStateException("silent failure")
    }
}

// SAFE: exception surfaces on await
supervisorScope {
    val result = async {
        throw IllegalStateException("surfaced failure")
    }
    result.await() // throws here, you handle it
}

In my experience building production systems with parallel data fetching, async/await is almost always the right choice for independent tasks. It defers the exception to a point where you can actually make a decision about it.


CoroutineExceptionHandler placement

This is where teams consistently misconfigure their error handling. CoroutineExceptionHandler is a last-resort handler that fires when a coroutine fails and no parent Job in the hierarchy handles the exception, meaning it reaches the top of the supervision boundary without being caught. Installing it on an inner child coroutine has no effect; the handler is only consulted when exception propagation has nowhere further to go.

val handler = CoroutineExceptionHandler { _, throwable ->
    logger.error("Unhandled coroutine exception", throwable)
}

// Handler MUST be installed at the scope boundary where propagation stops
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO + handler)

scope.launch {
    launch {
        throw RuntimeException("this reaches the handler")
    }
}

If you install the handler on an inner launch, it is ignored because the exception still has a parent Job to propagate through. The practical rule: install CoroutineExceptionHandler on the CoroutineScope that owns the SupervisorJob. Treat it as a telemetry sink for genuinely unexpected failures, not a substitute for structured error handling at callsites.


The pattern that prevents silent data loss

For parallel pipelines where partial failure should be surfaced and handled rather than propagated to cancel everything, the production-grade pattern looks like this:

suspend fun fetchDashboardData(): DashboardData = supervisorScope {
    val profile = async { userRepository.getProfile() }
    val metrics = async { analyticsRepository.getMetrics() }

    DashboardData(
        profile = runCatching { profile.await() }.getOrNull(),
        metrics = runCatching { metrics.await() }.getOrNull()
    )
}

Each failure is explicitly handled at the await callsite. supervisorScope ensures one failure does not cancel its sibling. Nothing is lost silently.


Three takeaways

  1. Default to coroutineScope for operations that must succeed atomically. Reserve supervisorScope for genuinely independent parallel work where partial results are valid and explicitly handled.

  2. Prefer async/await over launch for work that produces a result. The exception is deferred to a controlled callsite rather than propagated through the Job tree at an unpredictable time.

  3. Install CoroutineExceptionHandler at the scope boundary where exception propagation terminates, not on child coroutines. It fires when no parent Job handles the exception. Treat it as an observability hook, not a primary error-handling mechanism.


Conclusion

The Job hierarchy gives you lifecycle and failure propagation guarantees that you would otherwise have to build yourself, usually badly. It has a steeper learning curve than most Kotlin features, but the design is deliberate. Get the scope type right, understand where exceptions actually surface with launch vs async, and put your exception handlers at the right boundary. Do those things consistently and silent data loss in async Kotlin becomes something you read about in other people’s postmortems rather than debug at 2 a.m.


Share: Twitter LinkedIn