The Analogy: The Translation Agency and Its Receipts
A translation agency has one front-desk coordinator and several freelance translators, each working alone in a separate room. A publisher drops off a bundle of documents that all need translating -- a contract, a brochure, a manual -- and the important fact is that none of them depends on any other. The contract does not need the brochure to be finished first; each is a self-contained job that produces its own finished deliverable.
The coordinator handles this the efficient way. They carry the contract to the first translator, hand it over, and take back a small numbered receipt; then, without waiting for a single word to be translated, they carry the brochure to the second translator and pocket a second receipt, and the manual to the third for a third receipt. Handing over a document and taking a receipt costs seconds; the long work of translating belongs to the translators, not the coordinator. Within a minute all three translators are working at once, and the coordinator is back at the desk with three receipts, free to answer the phone.
When the coordinator actually needs a finished translation, they present its receipt. If that translation is already done, they get it back on the spot; if it is not, they wait -- but only for that one job, while the others keep progressing. Because all three started together rather than in turn, the whole bundle is ready in about the time of the single slowest translation, not the sum of all three. A receipt is a claim on a result that may not exist yet; presenting it is the act of collecting the result, blocking only if it is not ready. Some translators are eager and begin the moment they are handed a document; a lazier one will not lift a pen until the coordinator comes back and presents the receipt to start them.
The failure that wastes the afternoon is the coordinator who hands the contract to the first translator and then stands in the doorway waiting for it to be finished before even carrying the brochure to the second. Three jobs that could have overlapped are now done strictly in turn, and a bundle that should have taken one slow translation's worth of time takes three. A subtler failure is handing out a document but losing the receipt: the translation gets finished and then sits on a shelf, its result never collected, and if that job hit a problem nobody ever finds out, because the error only surfaces when a receipt is presented. Handing out work and collecting results are two separate acts, and both have to happen.
Syntax or Core Structure
async starts a coroutine that produces a value and hands you a Deferred -- the receipt. await presents the receipt: it suspends until the value is ready, then returns it. Starting two independent async blocks and awaiting them afterwards runs the work concurrently, which is precisely the fix for the sequential profile from the previous lesson.
import kotlinx.coroutines.*
suspend fun fetchName(id: Int): String {
delay(100L)
return "user" + id
}
suspend fun fetchScore(id: Int): Int {
delay(100L)
return id * 10
}
fun main() = runBlocking {
val nameReceipt = async { fetchName(7) } // handed out, receipt taken
val scoreReceipt = async { fetchScore(7) } // handed out too, both now running
println("both requested")
val profile = nameReceipt.await() + " scored " + scoreReceipt.await()
println(profile)
}
Output:
both requested
user7 scored 70
The two async calls hand out both documents before any translating happens, so "both requested" prints before either fetch resolves. When main reaches the first await it suspends, and now both fetches -- each a 100 ms delay -- run concurrently rather than one after the other. Roughly 100 ms later both receipts can be presented, and the profile is assembled into "user7 scored 70". The values are identical to the sequential version, but the total wait is about 100 ms instead of 200: the slowest single job, not the sum. Handing out both jobs first, then collecting, is the whole technique.
Technical Depth: Deferred, Ordering, and Laziness
launch versus async
Both start a coroutine; they differ in what they hand back and how you wait for it. launch gives a Job you join for completion; async gives a Deferred you await for a value. A Deferred is a Job that also carries a result.
| Builder | Returns | How you collect | Use when |
|---|---|---|---|
| launch | Job | join, completion only | fire-and-forget side effects |
| async | Deferred of T | await, for the value | you need a computed result |
Reaching for async when you never call await is a smell: you asked for a receipt and threw it away. If a coroutine produces no value you care about, launch states that intent more honestly.
Started order and finished order are different
When several async blocks are dispatched on one thread, they begin in the order they were scheduled, but they finish in the order their work completes. Distinct delays make both orders fully predictable.
import kotlinx.coroutines.*
fun main() = runBlocking {
val a = async { println("A started"); delay(30L); println("A finished"); 1 }
val b = async { println("B started"); delay(10L); println("B finished"); 2 }
val c = async { println("C started"); delay(20L); println("C finished"); 3 }
val sum = a.await() + b.await() + c.await()
println("sum = " + sum)
}
Output:
A started
B started
C started
B finished
C finished
A finished
sum = 6
The three coroutines are scheduled in source order on runBlocking's single-threaded event loop, so they print "started" as A, B, C -- each runs up to its delay and suspends. They then resume in delay order: B at 10 ms, C at 20 ms, A at 30 ms, giving the "finished" block B, C, A. Only once all three are done do the three await calls return 1, 2, and 3, summing to 6. The started order follows scheduling; the finished order follows the delays; and the awaits collect the values regardless of which order they finished in.
Lazy start: the translator who waits for the receipt
By default async is eager -- the body is scheduled at once. Passing CoroutineStart.LAZY holds the body until the first await (or an explicit start), like the translator who will not begin until the coordinator returns with the receipt.
| Start mode | When the body begins | Effect |
|---|---|---|
| DEFAULT | scheduled at once, runs when dispatched | eager concurrency |
| LAZY | only on first await or start | deferred until demanded |
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred = async(start = CoroutineStart.LAZY) {
println("lazy body runs")
99
}
println("before await")
println("value: " + deferred.await())
}
Output:
before await
lazy body runs
value: 99
Because the async is lazy, its body does not run when the coroutine is created; "before await" prints first. The body starts only when await presents the receipt, so "lazy body runs" prints next, and the awaited value is 99. Lazy start is useful when you may never need the result, but it also means a lazy async you never await never runs at all.
Collecting many receipts with awaitAll
When you hand out a whole list of jobs, awaitAll presents every receipt at once and returns the results in the list's order, not in finish order. It also fails fast: if any job throws, awaitAll surfaces that exception immediately rather than waiting for the rest.
import kotlinx.coroutines.*
fun main() = runBlocking {
val jobs = (1..4).map { n ->
async { delay(n * 10L); n * n }
}
val results = jobs.awaitAll()
println("squares: " + results)
println("total: " + results.sum())
}
Output:
squares: [1, 4, 9, 16]
total: 30
Four jobs are handed out, computing the squares of 1 through 4 after staggered delays. awaitAll collects them in list order, so results is [1, 4, 9, 16] even though the job for 1 finished first and the job for 4 finished last. Summing gives 30. Using awaitAll is cleaner than a hand-written loop of await calls and makes the fail-fast behaviour explicit.
Real World Example: Loading a Dashboard Concurrently
A dashboard needs three independent sections -- a profile, a feed, and an alert count -- each loaded by its own slow suspend function. Because the sections do not depend on one another, they are handed out as three concurrent async jobs and collected afterwards, so the page is ready in about the time of the slowest section rather than the sum.
import kotlinx.coroutines.*
suspend fun loadProfile(): String { delay(20L); println("profile loaded"); return "profile: Ada" }
suspend fun loadFeed(): String { delay(40L); println("feed loaded"); return "feed: 3 posts" }
suspend fun loadAlerts(): String { delay(10L); println("alerts loaded"); return "alerts: 1 unread" }
suspend fun loadDashboard(): String = coroutineScope {
val profile = async { loadProfile() }
val feed = async { loadFeed() }
val alerts = async { loadAlerts() }
println("all three sections requested")
listOf(profile.await(), feed.await(), alerts.await()).joinToString(" - ")
}
fun main() = runBlocking {
println(loadDashboard())
}
Output:
all three sections requested
alerts loaded
profile loaded
feed loaded
profile: Ada - feed: 3 posts - alerts: 1 unread
The three async calls hand out all three loads before anything blocks, so "all three sections requested" prints first, then the body suspends at the first await. The loads run concurrently and print as they finish, and because their delays are 20, 40, and 10 milliseconds, the finish order is alerts, profile, feed -- shortest first.
The final line is assembled in a different order from the one the sections finished in. The listOf collects profile.await(), feed.await(), alerts.await() in that fixed order, so the joined string always reads profile, feed, alerts regardless of which section's work completed first. Collecting a receipt does not care when the job finished; await simply returns the value once it is ready.
The wall-clock time is about 40 milliseconds, the slowest single load, rather than the 70 milliseconds a sequential version would take. That saving is the entire reason to decompose independent work with async.
The genuine design flaw is that this dashboard is all-or-nothing. Because the three loads share one coroutineScope, if any single section threw -- say the feed service was down -- the scope would cancel the other two coroutines and rethrow, and the user would see an empty page instead of the profile and alerts that loaded perfectly well. A resilient dashboard would isolate each section, wrapping each load in runCatching or using a supervisorScope so one failing section degrades to a placeholder rather than blanking the whole page. As written, the code also fixes the display order at the await sites, so it cannot render each section the instant it arrives; it must wait for all three before showing any.
Common Mistakes
- Awaiting each
asyncimmediately. Writingasync { a() }.await()on one line, thenasync { b() }.await()on the next, runs them sequentially -- the second is not even created until the first finishes. Start all the jobs first, then await them, or the concurrency is imaginary.
- Using
asyncfor work with no result.asynchands you aDeferredyou are meant toawait. If the coroutine produces nothing you need, uselaunch; an unawaitedasyncis a lost receipt.
- Never awaiting a
Deferred. An eagerasyncstill runs, but if it throws and you neverawaitit, the exception surfaces only when the receipt is presented -- which may be never. Always collect the receipts you hand out.
- Assuming await order equals finish order.
awaitreturns a value whenever that job is done; the order you callawaitin fixes the order you read results, not the order the work completed. Do not infer timing from await order.
- Blocking on a
Deferredwith.getCompleted()or busy-waiting. Presenting the receipt isawait, which suspends politely. PollingisCompletedin a loop burns the thread and defeats the point.
- Expecting a lazy
asyncto run on its own. WithCoroutineStart.LAZYthe body waits for the firstawaitorstart. If you neither await nor start it, it never runs, and any value it would have produced never exists.
- Sharing a scope for independent failures. In a plain
coroutineScope, one child's exception cancels its siblings. If sections should fail independently, isolate them withrunCatchingor asupervisorScope.
- Launching
asyncinGlobalScopefor "parallelism". That detaches the work from structured concurrency, so failures and cancellation no longer propagate. Decompose inside a scope you own, such ascoroutineScope.
- Decomposing dependent steps with
async. If step two needs step one's result, they cannot overlap;asyncbuys nothing and only adds noise. Concurrency helps only when the jobs are genuinely independent.
Best Practices
- Start every independent
asyncfirst, thenawaitthem, so the jobs actually overlap instead of running in turn.
- Use
asynconly when you need the produced value; uselaunchfor side-effecting work with no result.
- Collect every receipt: await each
Deferredyou create, so results are used and errors are surfaced.
- Use
awaitAllon a list ofDeferredwhen you want all results together and want any failure to surface promptly.
- Reach for
CoroutineStart.LAZYonly when the result may not be needed, and remember such a job must be started or awaited to run.
- Isolate sections that should fail independently with
runCatchingper job or asupervisorScope, so one failure does not cancel the rest.
- Keep decomposition inside a structured scope like
coroutineScopeso cancellation and errors propagate correctly.
- Decompose with
asynconly genuinely independent work; leave dependent steps as ordinary sequential suspend calls.
Practice Exercises
- Write two suspend functions that each delay 150 milliseconds and return a number. Sum them first with sequential
awaitcalls on one line each, then with twoasyncjobs awaited afterwards, and compare the total wall time of the two versions.
- Create three
asyncjobs with delays of 25, 5, and 15 milliseconds, each printing when it finishes, then await them into a list. Predict both the finish-order prints and the list order, and explain why they differ.
- Write a lazy
asyncwhose body prints a line, and a program that prints "skipping" and never awaits it. Show that the body never runs, then add anawaitand show that it now does.
- Take the dashboard in this lesson, make
loadFeedthrow an exception, and observe that the whole dashboard fails. Then wrap each load inrunCatchingso the profile and alerts still render with a placeholder for the feed.