# The Coroutine Tree: What Scope, Job, and Cancellation Actually Mean

> A coroutine isn't a loose background task you fire and forget. It's a node in a tree rooted at a scope, and that tree is why cancellation cascades, why async can swallow an exception until the worst possible moment, and why GlobalScope is the most common leak in Android code.

**Date:** 2026-10-21T00:00:00.000Z
**Tags:** Coroutines, Concurrency

## What a coroutine actually is

A coroutine is a unit of work that can pause partway through and resume
later, without blocking the thread it's running on. The function that can
pause is marked `suspend`.

Calling a suspend function doesn't run start-to-finish the way a normal
function call does. At the point where it has nothing to do yet (waiting
on IO, a `delay()`, another coroutine), it hands control back to the
dispatcher. It resumes from that exact point once the result is ready.

## The intuition

`launch { }` and `async { }` read like "spawn a background task and move
on." That's the picture most tutorials build, and it's wrong in a specific
way: it treats a coroutine as free-floating, the same way you'd fire a
thread and forget it exists.

* Every coroutine starts inside a `CoroutineScope`, and that scope is a
  boundary on how long the coroutine is allowed to live.
* Every coroutine has a `Job`, an object that tracks its state and its
  position in a tree of parent and child coroutines.
* Cancel a parent, and every descendant in that tree gets cancelled too.
  Not because of some special-cased recursive cancel loop, but because
  that's what the tree is.

Think of `launch`/`async` less as "spawn a task" and more as "add a branch
to this tree." A long list of separately memorized rules (why cancellation
cascades, why one child's crash can take down its siblings, why
`GlobalScope` is dangerous) collapses into one picture: the tree.

```mermaid caption="launch and async don't spawn independent tasks, they each add a child Job as a new branch under the Job that called them" figureNumber={1}
flowchart TD
    Root["CoroutineScope: root Job"]
    A["Job A (launch)"]
    B["Job B (async, returns Deferred)"]
    A1["Job A1 (launch)"]
    B1["Job B1 (async, returns Deferred)"]

    Root --> A
    Root --> B
    A --> A1
    B --> B1
```

Every box here is a `Job`. `launch` and `async` are just two different ways
to add one, with one real difference: `launch` hands you back nothing but
a handle to the branch itself, `async` hands you back a `Deferred` that
also carries the branch's eventual result. Cancel `Root`, and `A`, `A1`,
`B`, and `B1` all get cancelled with it, because they're not separate
things you'd need to track down individually, they're just the part of
this tree underneath it.

## How suspension actually works: a state machine

The Kotlin compiler has no runtime magic for pausing a function mid-call.
It rewrites a `suspend` function into a state machine: each suspension
point becomes a numbered state, and the function's local variables get
hoisted (Moved out of the function's local stack frame and into a persistent object, so the value survives even after the function pauses and its stack frame goes away.)
into a Continuation (The compiler-generated object that remembers where a suspended function should resume and what was in scope when it paused. Passed around like a hidden extra parameter to every suspend function call.)
that remembers where to resume.

```kotlin
suspend fun loadUser(id: String): User {
    val token = fetchToken()          // state 0, suspends here
    val profile = fetchProfile(token) // state 1, suspends here
    return profile.toUser()           // state 2, returns
}
```

Calling `loadUser` doesn't block anything waiting for `fetchToken`. It
hands back a `Continuation` and returns control to the dispatcher. When
the token arrives, the dispatcher invokes that continuation, which
resumes `loadUser` at state 1 with `token` already restored from where it
was stashed.

```mermaid caption="loadUser suspends at fetchToken, freeing the thread, and resumes via its Continuation once the token arrives" figureNumber={2}
sequenceDiagram
    participant Caller
    participant Dispatcher
    participant loadUser as loadUser (state machine)
    participant IO as Network/IO

    Caller->>Dispatcher: launch { loadUser(id) }
    Dispatcher->>loadUser: run from state 0
    loadUser->>IO: fetchToken()
    loadUser-->>Dispatcher: suspend, return Continuation
    Dispatcher-->>Caller: thread freed
    IO-->>Dispatcher: token ready, resume(Continuation)
    Dispatcher->>loadUser: resume at state 1 (token restored)
    loadUser->>IO: fetchProfile(token)
    loadUser-->>Dispatcher: suspend, return Continuation
    IO-->>Dispatcher: profile ready, resume(Continuation)
    Dispatcher->>loadUser: resume at state 2
    loadUser-->>Caller: return User
```

This is also why cancellation is cooperative, not immediate (more on that
below): a coroutine can only be interrupted at a suspension point, because
that's the only moment the state machine hands control back to a
scheduler that can check anything.

## Bridging callback APIs into the tree: `suspendCancellableCoroutine`

Not every suspension point comes from calling another `suspend` function.
Android is full of callback-based APIs (`ActivityResultCaller`, listener-style
SDKs, anything that finishes by invoking a callback instead of returning a
value) that know nothing about coroutines. `suspendCancellableCoroutine` is
how you turn one of those into a real suspension point instead of a side
channel the tree can't see.

```kotlin
suspend fun awaitLocation(): Location = suspendCancellableCoroutine { continuation ->
    val listener = LocationListener { location -> continuation.resume(location) }
    locationProvider.requestLocation(listener)

    continuation.invokeOnCancellation {
        locationProvider.removeListener(listener)
    }
}
```

Where the state machine above gets its `Continuation` generated and wired by
the compiler, `suspendCancellableCoroutine` hands you that `Continuation`
directly. You hold onto it inside the lambda, kick off the callback-based
API, and resume it manually once the real callback fires with a result.

```mermaid caption="Two ways awaitLocation can end: the listener fires first, or the parent cancels first and invokeOnCancellation tears the listener down instead" figureNumber={3}
sequenceDiagram
    participant Caller
    participant awaitLocation as awaitLocation (continuation)
    participant Provider as LocationProvider

    Caller->>awaitLocation: launch { awaitLocation() }
    awaitLocation->>Provider: requestLocation(listener)
    awaitLocation-->>Caller: suspends, thread freed

    alt Location arrives first
        Provider-->>awaitLocation: listener(location)
        awaitLocation-->>Caller: resume(location)
    else Parent cancels first
        Caller->>awaitLocation: cancel()
        awaitLocation->>Provider: removeListener(listener)
        awaitLocation-->>Caller: resume with CancellationException
    end
```

`invokeOnCancellation` is the part that actually ties this into the tree.
Say the scope that called `awaitLocation()` gets cancelled while a location
request is still pending. Nothing about `locationProvider` knows that
happened, it'll keep calling `listener` until something tells it to stop.
Without `invokeOnCancellation`, that listener keeps living past the point
the coroutine that created it no longer exists, a leak with the same shape
as the `GlobalScope` leak later in this post. The cancellation handler runs
exactly when the parent cancels, removing the listener before it can fire
again.

That's what makes a callback-based API feel like an ordinary node in the
tree rather than a side door into it: cancellation can reach into it from a
parent, the same as it reaches any suspension point generated by the
compiler.

## Dispatchers: why one thread runs many coroutines

A `Job` says what a coroutine's relationship is to other coroutines. A
`CoroutineDispatcher` says which thread, or thread pool, actually runs it.
Those are two different questions, and conflating them is where "a thread
can only do one thing at a time" intuition misleads people.

* A suspended coroutine isn't occupying a thread at all. It's a
  continuation sitting on the heap, waiting to be resumed.
* A dispatcher only needs a thread for the moments a coroutine is actively
  running code, not for the moments it's suspended.
* Thousands of coroutines can be suspended at once on zero threads. Only
  the ones actively executing need a thread each.

That's why coroutines are cheap compared to threads. An OS thread reserves
its own call stack upfront (commonly around 1MB on the JVM), whether it's
busy or idle. A suspended coroutine is just a `Continuation` object,
generally a few dozen bytes, parked on the heap until something resumes
it.

*\[Interactive demo: DispatcherInterleaveDemo — view this post in a browser for the live version.]*

This isn't just an abstract scheduling puzzle. The same single-thread
interleaving is what makes an ordinary press-and-hold button animation
work:

```kotlin
val scope = rememberCoroutineScope()
val scale = remember { Animatable(1f) }

Modifier.pointerInput(Unit) {
    detectTapGestures(onPress = {
        scope.launch { scale.animateTo(1.2f) } // queued, doesn't run inline
        tryAwaitRelease()                      // suspends here, thread freed
        scope.launch { scale.animateTo(1f) }   // retargets the same Animatable
    })
}
```

`scope.launch` doesn't run the grow animation inline, it schedules a new
`Job` on `rememberCoroutineScope()`'s dispatcher (the UI thread) and
returns immediately. `tryAwaitRelease()` then suspends, handing the thread
back, which is exactly what lets the grow animation's own suspension
points (`withFrameNanos`, waiting for the next frame) get a turn at all.
Nothing here runs in parallel: the `onPress` coroutine and the animation
coroutine take turns on one thread, the same interleaving as the demo
above, just with a finger on the screen instead of a button labeled
"Launch coroutine."

## Where the tree leaks: GlobalScope

```kotlin
class UserViewModel : ViewModel() {
    fun loadUser(id: String) {
        // Leak: this coroutine's parent is GlobalScope, which never gets
        // cancelled. It keeps running after the ViewModel is cleared,
        // holding a reference to it the whole time.
        GlobalScope.launch {
            val user = repository.fetchUser(id)
            _uiState.value = UiState.Loaded(user)
        }
    }
}
```

```kotlin
class UserViewModel : ViewModel() {
    fun loadUser(id: String) {
        // Fixed: viewModelScope's Job is a child of this ViewModel's
        // lifecycle. onCleared() cancels it, which cancels this launch
        // too, because it's actually in the tree.
        viewModelScope.launch {
            val user = repository.fetchUser(id)
            _uiState.value = UiState.Loaded(user)
        }
    }
}
```

`GlobalScope` isn't scoped to anything, which is exactly the problem. It
has no parent, so nothing in your app's lifecycle can reach up and cancel
it.

## `launch` vs `async`: the exception timing nobody gets right

The common claim is "`launch` throws immediately, `async` waits until you
call `.await()`." That's only half true, and the half that's missing is
the half that matters.

```kotlin
coroutineScope {
    launch {
        throw IllegalStateException("boom")
        // Propagates immediately: cancels this scope's other children
        // and rethrows once they've wound down.
    }
}
```

```kotlin
coroutineScope {
    val deferred = async {
        throw IllegalStateException("boom")
        // Still propagates immediately through the parent job, same as
        // launch above, because this async has a structured parent.
        // await() is never even reached.
    }
    deferred.await()
}
```

```kotlin
val deferred = GlobalScope.async {
    throw IllegalStateException("boom")
    // Only deferred here: this async has no structured parent to
    // propagate to, so the exception just sits in the Deferred until
    // something calls await() on it. Forget to call await(), and the
    // exception disappears silently.
}
```

The rule isn't "`launch` vs `async`." It's "does this coroutine have a
parent in the tree." Nested inside a scope, both propagate the same way:
immediately, through the tree. It's only a bare, parentless `async` where
the "wait for `.await()`" behavior shows up, and that's the same root
cause as the `GlobalScope` leak above: no parent means nothing propagates
automatically.

> **The fundamental**
>
> This is **structured concurrency**: every coroutine has a parent, scoped
> to a `CoroutineScope` that defines its lifetime. A `Job` isn't just a
> handle, it's the coroutine's position in that tree. Cancellation flows
> down the tree (cancel a parent, every descendant cancels), and failure
> flows up it (an unhandled child failure cancels its siblings and
> propagates to the parent), unless something deliberately cuts one of
> those edges.

## Elsewhere: same fundamental, different framework

* **Swift's structured concurrency**: a `Task` spawned inside a
  `TaskGroup` is a child of that group the same way. Cancel the parent
  `Task` and `Task.isCancelled` flips true down the whole tree, and a
  group's children get cancelled when one of them throws, the same
  propagation shape as above.
* **Python's Trio**: literally where the term "structured concurrency"
  was coined. Trio's nursery (Trio's name for a scope: a block you must open before spawning any child task, which doesn't exit until every child it opened has finished or been cancelled.)
  is the scope. You can't spawn a task without one, and the nursery block
  doesn't exit until every child it opened has finished, the same
  lifetime-boundary idea as a `CoroutineScope`.
* **Python's `asyncio.TaskGroup`** (3.11+): added specifically to bring
  Trio's structured model into `asyncio`, which previously let you fire
  `asyncio.create_task()` with no parent at all, the exact `GlobalScope`
  problem above.
* **Go**, by contrast, has no structured concurrency primitive in the
  language. A bare `go func() {}()` is `GlobalScope.launch` by default:
  nothing tracks it, nothing cancels it automatically. `errgroup` and
  `context.Context` exist specifically as the bolted-on fix for not having
  a tree built in.
* **Node/TypeScript** is in the same bucket as Go. A `Promise` has no
  built-in cancellation at all, and `Promise.all` rejects as soon as one
  promise rejects without cancelling the others. They keep running,
  unobserved. `AbortController`/`AbortSignal` is the closest analog to a
  `Job`, but it's manual: you create a signal and pass it down explicitly
  to whatever chooses to check it. Nothing propagates it or builds a tree
  out of it automatically.

## Job types

`Job` isn't one fixed behavior, it's an interface with variants that each
change one rule about how the tree propagates failure or exposes manual
control. The tree shape (parent/child, cancel flows down) stays the same
across all of them.

| Job type | Created by | Cancels siblings on failure? | Typical use |
|---|---|---|---|
| `Job` | `launch`/`async` default, `coroutineScope { }` | Yes | Default structured concurrency: "if one part fails, stop the whole operation" |
| `SupervisorJob` | `SupervisorJob()`, `supervisorScope { }`, `viewModelScope` | No, for direct children only | Independent parallel work under one scope: "if one part fails, the rest should keep going" |
| `CompletableJob` | What `Job()`/`SupervisorJob()` factory functions actually return | Same as the base it wraps | Manually marking a job done via `complete()`/`completeExceptionally()`, orthogonal to the supervisor distinction |

The "direct children only" column is the detail that trips people up: a
`SupervisorJob`'s protection doesn't reach past its immediate children. If
one of those children `launch`es its own grandchildren, a grandchild's
failure still propagates normally up to its immediate parent (the direct
child) and cancels that child's own sub-branch. The supervisor only stops
the failure from climbing past itself.

## Edge cases

### Cancellation is cooperative, not immediate

Calling `job.cancel()` doesn't interrupt code mid-statement the way
killing a thread does. It flips a flag that gets checked at suspension
points, which is why a busy loop with no `delay()`, no `yield()`, no
suspending call inside it, just keeps running after it's "cancelled":

```kotlin
val job = launch {
    while (true) {
        // No suspension point in this loop: isActive never gets checked
        // automatically, so cancel() has nothing to interrupt.
        computeSomething()
    }
}
job.cancel() // the loop above keeps running forever
```

The fix is to check `isActive`, or call `ensureActive()`, inside the loop.
That gives cancellation a point to actually take effect.

### `CancellationException` doesn't propagate as a failure

```kotlin
val job = launch {
    try {
        doWork()
    } catch (e: Exception) {
        log.error("doWork failed", e) // also catches CancellationException
    }
}
job.cancel()
// doWork() keeps running past the catch block: cancel() threw
// CancellationException to unwind the coroutine, but this catch
// swallowed it like any other Exception, so nothing actually stops.
```

Cancelling a coroutine doesn't just flip a flag. It throws a
`CancellationException` at the coroutine's current suspension point, the
same mechanism a real failure uses to unwind the call stack.

The difference is what happens once that exception reaches the `Job`:

* The coroutine machinery specifically checks for `CancellationException`
  and treats it as "this branch finished because it was told to," not a
  failure.
* It never gets reported to a `CoroutineExceptionHandler`.
* Unlike the failures in the `launch`/`async` section above, it doesn't
  cancel siblings or propagate to the parent as an error.

That's why catching `Exception` broadly inside a coroutine is a real bug,
not just bad style. `CancellationException` is a subtype of `Exception`,
so a blanket catch swallows it along with everything else, and the
coroutine keeps running after it was supposedly cancelled.

The fix is to catch a narrower type, or rethrow when the caught exception
is a `CancellationException`:

```kotlin
val job = launch {
    try {
        doWork()
    } catch (e: CancellationException) {
        throw e // let cancellation keep propagating
    } catch (e: Exception) {
        log.error("doWork failed", e)
    }
}
job.cancel()
// The CancellationException branch rethrows immediately, so cancellation
// still unwinds the coroutine. A real failure from doWork() still falls
// through to the logging branch below it, same as before.
```

### `withContext` doesn't add a branch

`withContext` takes a suspending lambda just like `launch`/`async`, which
makes it tempting to read it as spawning another branch too. It doesn't.

```kotlin
suspend fun loadUser(id: String): User {
    val user = withContext(Dispatchers.IO) {
        repository.fetchUserBlocking(id) // runs on IO, caller suspends here
    }
    // Reached only once the block above finishes. Same coroutine, same
    // Job as loadUser itself, just back on the original dispatcher.
    log.info("loaded $user")
    return user
}
```

`withContext` hands back no `Job`, no `Deferred`, nothing to hold onto.
It suspends the calling coroutine, switches dispatcher (or whatever
context element you passed) for the duration of the block, and resumes
with the result once that block finishes. Nothing runs concurrently with
the call site, there's no second branch to track, it's the same node in
the tree the whole time. Cancel the parent while a coroutine is sitting
inside a `withContext` block, and that block gets cancelled right along
with it, the same as any other suspension point, because it was never a
separate node to begin with.

### `runBlocking` is a bridge, not a tree member

Like `withContext` above, `runBlocking` doesn't add a branch to an
existing tree either, but for the opposite reason: it isn't meant to fit
the usual picture at all. It exists to call suspending code from
non-suspending code (`main()`, a JVM test, a callback that isn't itself a
coroutine), and it does that by blocking the calling thread until its
coroutine body finishes. Nest `runBlocking` somewhere deep in production
Android code and you've reintroduced the exact thread-blocking the rest
of this system exists to avoid.

## Real-world usage

* `viewModelScope` / `lifecycleScope`: Android's pre-built scopes tied to
  a `ViewModel`'s or `LifecycleOwner`'s lifetime, so you get the tree for
  free instead of managing a `Job` by hand.
* Flow collection: `flow.collect { }` runs inside whatever scope called
  it, so cancelling that scope stops collection too, same tree.
* `WorkManager`'s `CoroutineWorker`: the library owns a scope per work
  request and cancels it if the work is cancelled or times out, so
  `doWork()` doesn't need to manage its own `Job`.

**A coroutine is never floating free. It's always a node in a tree, and
the tree, not the coroutine itself, is the thing you're actually
managing.**


---

Canonical page: https://recomposed.blog/coroutine-tree