Structured Concurrency in Practice: Cancellation, Timeouts, and Context Propagation
Structured concurrency is a paradigm for managing concurrent code in a hierarchical, scoped way. Instead of fire-and-forget threads or unstructured async tasks, it ties child tasks to a parent scope. When the parent completes (successfully or via cancellation), all children are automatically cleaned up. This prevents leaks, makes cancellation predictable, and simplifies error handling.
Popular implementations:
Kotlin Coroutines (mature, with coroutineScope, supervisorScope).
Swift 5.5+ async/await (with TaskGroup, withTaskCancellationHandler).
Java 21+ (Project Loom's StructuredTaskScope).
Go (with errgroup or custom patterns).
I'll use Kotlin Coroutines for examples, as it's the gold standard for these features. Examples are in Kotlin 1.8+ with kotlinx.coroutines.
1. Cancellation
Cancellation is cooperative : tasks check isActive or use suspend functions that throw CancellationException. In structured concurrency, it's propagated automatically from parent to children.
Key Primitives
coroutineScope { }: Child coroutines cancel when parent does.
cancel(): Sends signal; tasks yield to check it.
withTimeout / withTimeoutOrNull: For bounded cancellation.
Example: Basic Cancellation
kotlin Copy code
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500) // Suspend point: checks for cancellation
}
}
delay(1300) // Let it run briefly
println("Cancelling!")
job.cancel() // Propagates to children (none here, but works in scopes)
job.join() // Waits for clean shutdown
println("Cancelled!")
}
Output (abridged):
code Copy code
I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
Cancelling!
Cancelled!
delay yields, checks cancellation → throws CancellationException.
Non-cancellable: Use NonCancellable context or ensure block.
Supervision : supervisorScope isolates failures—one child cancel doesn't kill siblings.
kotlin Copy code
coroutineScope {
launch { delay(100); throw Error("Boom!") } // Cancels whole scope
launch { delay(200); println("Survives? No.") }
}
supervisorScope { // Use this for fault isolation
launch { delay(100); throw Error("Boom!") } // Doesn't cancel siblings
launch { delay(200); println("Survives! Yes.") }
}
2. Timeouts
Timeouts enforce liveness: cancel if a block exceeds time. Structured: timeout applies to the entire subtree.
Key Primitives
withTimeout(TIME) { }: Throws TimeoutCancellationException (subtype of CancellationException).
withTimeoutOrNull(TIME) { }: Returns null on timeout.
Example: Timeout with Children
kotlin Copy code
suspend fun fetchUserData(userId: String): String {
return coroutineScope { // Structured: timeout kills all fetches
async { fetchFromCache(userId) }
async { fetchFromDB(userId) }
// More children...
}.awaitAll().first { it != null } ?: error("Failed")
}
suspend fun main() {
try {
withTimeout(2000) {
fetchUserData("123")
}
} catch (e: TimeoutCancellationException) {
println("Timeout! All children cancelled.")
}
}
suspend fun fetchFromCache(id: String) = withContext(Dispatchers.IO) { delay(1500); "Cached" }
suspend fun fetchFromDB(id: String) = withContext(Dispatchers.IO) { delay(2500); "DB" }
Timeout cancels entire coroutineScope + its children.
Graceful: I/O suspends check cancellation.
Nested Timeouts : Inner ones don't override outer—use shortest.
3. Context Propagation
Contexts (e.g., CoroutineContext) carry metadata like request IDs, auth tokens, tracing spans. In structured concurrency, propagates implicitly to children unless overridden.
Key Primitives
CoroutineContext: Key-value (e.g., CoroutineName, custom ThreadLocal wrappers).
withContext(context) { }: Changes context for block/children.
Custom elements: Implement ThreadContextElement for auto-propagation.
Example: Request Tracing with Custom Context
kotlin Copy code
import kotlinx.coroutines.*
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.CoroutineContext
// Custom context for request ID (propagates automatically in structured scopes)
class RequestId(val id: String) : AbstractCoroutineContextElement(Key) {
companion object Key : CoroutineContext.Key<RequestId>
}
suspend fun processRequest(reqId: String) {
val ctx = RequestId(reqId)
coroutineScope { // Children inherit ctx
launch {
withContext(ctx) { // Explicit if needed
println("Child 1: Processing ${RequestId.Key[coroutineContext]?.id}")
delay(100)
}
}
launch {
println("Child 2: Processing ${RequestId.Key[coroutineContext]?.id}")
delay(200)
}
}
}
fun main() = runBlocking {
processRequest("REQ-42")
}
Output :
code Copy code
Child 2: Processing REQ-42
Child 1: Processing REQ-42
Auto-propagation : Children inherit parent's context.
ThreadLocal : Use ThreadContextElement for seamless ThreadLocal propagation (e.g., MDC for logging).
Tracing : Integrates with OpenTelemetry—contexts carry spans.
Practical Combined Example: HTTP Client with Timeout, Cancellation, and Tracing
Real-world: Fetch multiple APIs, timeout=5s, trace requests, cancel on user abort.
kotlin Copy code
class TracedHttpClient {
suspend fun fetchParallel(urls: List<String>, reqId: String): List<String> =
withTimeout(5000) {
val ctx = RequestId(reqId)
coroutineScope {
urls.map { url ->
async(ctx) { // Inherit context
println("Fetching $url (req: $reqId)")
httpGet(url) // Suspend fun with I/O
}
}.awaitAll().filterNotNull()
}
}
}
suspend fun httpGet(url: String): String? = withContext(Dispatchers.IO) {
// Simulate cancellable HTTP (use Ktor/OkHttp)
delay(2000)
if (!isActive) return@withContext null
"Data from $url"
}
fun main() = runBlocking {
val client = TracedHttpClient()
launch {
client.fetchParallel(
listOf("api1.com", "api2.com", "api3.com"),
"REQ-ABC"
).also { println("Results: $it") }
}
delay(2500) // Partial results
println("User cancelled!")
cancel() // Cancels scope + propagates timeout/context
}
Behavior :
Children inherit reqId, print it.
Timeout cancels all fetches.
User cancel() propagates instantly.
Best Practices
Always use scopes : coroutineScope / supervisorScope for structure.
Cancellation is cheap : Check isActive in CPU loops.
Timeouts everywhere : Wrap external calls.
Context : Use ThreadContextElement for perf-critical (e.g., logging).
Testing : runTest with TestScope auto-handles timeouts.
Errors : Catch CancellationException sparingly—let it propagate.
Pitfalls
Non-suspending loops : Forget ensure { cleanup() } or yield().
Global scopes : Avoid GlobalScope—leaks!
Context leaks : Override explicitly with emptyCoroutineContext().
For Swift/Java/Go equivalents or deeper dives (e.g., custom dispatchers), ask! Resources: Kotlin Coroutines Guide , StructuredTaskScope JEP .