Lesson 2 of 9 · 26m
Coroutines: The Mental Model That Prevents Most Bugs
Understand suspend functions, dispatchers, and blocking boundaries so coroutine code scales without hidden thread starvation.
Most coroutine incidents are not exotic race conditions. They are ordinary blocking calls placed on the wrong dispatcher until every worker thread is parked inside a JDBC query or HTTP client. Coroutines make concurrency cheaper; they do not make blocking I/O magical.
A suspend function is a pause point, not a thread
When a function is marked suspend, it may pause and resume later. The important part is where it resumes: on a coroutine dispatcher backed by a limited pool of threads.
suspend fun loadDashboard(userId: UserId): Dashboard {
val user = userRepository.find(userId)
val invoices = invoiceClient.recent(userId)
return Dashboard(user, invoices)
}Sequential-looking code is still sequential. Calling two suspend functions one after the other does not make them concurrent. If they are independent and you want overlap, say so:
suspend fun loadDashboard(userId: UserId): Dashboard = coroutineScope {
val user = async { userRepository.find(userId) }
val invoices = async { invoiceClient.recent(userId) }
Dashboard(user.await(), invoices.await())
}Dispatchers are execution policy
Dispatchers.Default is for CPU-bound work. Dispatchers.IO is for blocking I/O. Dispatchers.Main is UI-thread territory on clients and usually irrelevant on servers. The mistake is assuming every dependency respects those labels.
suspend fun findStatementRows(userId: UserId): List<StatementRow> =
withContext(Dispatchers.IO) {
jdbcTemplate.queryForList(
"select occurred_at, amount_cents from statements where user_id = ?",
StatementRow::class.java,
userId.value,
)
}If your repository uses blocking JDBC, isolate it with Dispatchers.IO at the adapter edge. Do not annotate every suspend function and hope. A dispatcher is a budget, not a magic wand.
Parallelism does not mean unbounded concurrency
async can fan out faster than your database pool, downstream API, or file descriptors can tolerate. Bound the work:
val results = ids.chunked(20).flatMap { chunk ->
coroutineScope {
chunk.map { async(Dispatchers.IO) { fetch(it) } }.awaitAll()
}
}CPU-heavy parsing, compression, crypto, or image processing does not become scalable because it is inside a suspend function. It consumes cores. Dispatchers.Default is sized around CPU count; if one request monopolizes it, latency climbs for unrelated work. Large parallel batch jobs often need explicit worker pools, queues, or even threads — not a forest of unbounded async calls.
Field notes
- Never call blocking JDBC, older HTTP clients, or file I/O on
Dispatchers.Defaultin a hot request path. runBlockingbelongs inmain, tests, and narrow adapters — not as a convenience inside request handling.- Measure dispatcher queue delay. Thread pools can be technically alive while business latency is already dead.
Was this lesson helpful?