Skip to content

Lesson 9 of 9 · 26m

Operating Kotlin Services: Testing, Observability, and Failure Drills

Test coroutines correctly, expose useful metrics and coroutine context in logs, and rehearse cancellation, timeout, and shutdown behavior before production does.

The first night a Kotlin service goes down, nobody asks whether the code was idiomatic. They ask which dispatcher saturated, whether jobs were cancelled, which downstream timed out, and why the logs do not contain a tenant ID. Operational readiness is part of language adoption. Kotlin gives you leverage; it does not operate the service for you.

Test coroutines with control over time

Use runTest for suspend-heavy unit tests. It gives you virtual time and deterministic scheduling:

@Test
fun `quote timeout returns unavailable`() = runTest {
    val service = PricingService(FakePricingClient(delay = 10.seconds))
    val result = service.quote(request)
    assertEquals(QuoteResult.Unavailable, result)
}

Log context deliberately

Coroutine context does not automatically merge with every logging framework. Use MDC propagation where appropriate:

withContext(MDCContext()) {
    logger.info { "processing order ${order.id}" }
}

At minimum, log correlation ID, tenant, principal, route, coroutine name, and upstream target. Avoid logging raw tokens, secret configuration, or full request bodies. The best incident log answers "whose work was this?" in one glance.

Metrics belong near resource boundaries

Instrument outbound calls, database operations, queues, cache access, and background jobs:

Framework metrics are useful, but dispatcher and pool visibility often decide whether you diagnose saturation in minutes or hours. Measure queue time separately from execution time; a fast database still looks slow if work waited behind 200 blocked coroutines.

Graceful shutdown is a feature

Runtime.getRuntime().addShutdownHook(Thread {
    runBlocking {
        applicationScope.cancel(); withTimeoutOrNull(10.seconds) { drainJobs() }
    }
})

Frameworks handle some of this only if your scopes are connected to the lifecycle. A detached GlobalScope job cannot participate.

Drill cancellation and dependency failure

Do not wait for production to test the important cases:

downstream slower than request timeout
database pool exhausted
deployment during large export

These tests expose whether retries duplicate effects, whether cancellation propagates, and whether resource ownership is real. They also reveal which operations need idempotency keys, durable queues, or compensating actions. Keep performance claims empirical: benchmark production-shaped traffic, not a coroutine printing strings.

Field notes

  • runTest virtual time can hide real contention; use it for logic, not capacity proof.
  • A timeout exception is not enough context; record the upstream, elapsed time, and whether the operation may have committed.
  • Graceful shutdown needs a hard deadline. Operators choose correctness boundaries; the process supervisor eventually chooses force.

Was this lesson helpful?

Sign in to rate