Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Project

OrderWatch (Concurrent CLI)

Start after Part 16

Stage 3

Goal: Build a concurrent command-line tool with coroutines and structured concurrency — generics, reified, variance, supervisorScope/async/withTimeout, and a custom property delegate — entirely offline. Time: ~8 hours · Uses: Parts 13–15 (generics, coroutines, internals/delegates)

Project brief

A quick-commerce app's support desk needs to know, right now, where a batch of orders stand across different delivery partners — Swiggy, Zomato, Dunzo-style partners, the same flavor Part 14's own examples used. In this project you build that check as a CLI tool: it "calls" every partner concurrently, never blocks a thread waiting on one slow partner while the others sit idle, and reports every outcome — success, failure, or timeout — without one bad partner taking down the whole batch.

Nothing here touches the network. Every "API call" is a read from a local fixture file (data/orders.txt) plus a delay() standing in for latency — this project runs fully offline, and still exercises exactly the coroutine machinery a real concurrent partner-integration service would need.

$ java -cp "concurrent-cli.jar:libs/kotlinx-coroutines-core-jvm-1.11.0.jar" MainKt check-all
  retry O-1002 (String): attempt 1/2 failed -- Zomato API returned 503
  retry O-1003 (String): attempt 1/2 failed -- Dunzo API timed out, worth a retry
  retry O-1002 (String): attempt 2/2 failed -- Zomato API returned 503
  [fetch attempts] 0 -> 6
OK       O-1001: Swiggy: ETA 12 min (155ms, 1 attempt(s)) (varies)
FAILED   O-1002: Zomato API returned 503
OK       O-1003: Dunzo: ETA 15 min (253ms, 2 attempt(s)) (varies)
TIMEOUT  O-1004: no response after 503ms (varies)
OK       O-1005: Blinkit: ETA 6 min (405ms, 1 attempt(s)) (varies)
Checked 5 order(s) in 510ms (varies) -- 3/5 OK

Five orders, five different partner behaviours, checked at once, done in about as long as the single slowest one — not the sum of all five.

Files

File What it is
README.md This brief and the step-by-step build guide
OrderRecord.kt The fixture row model: OrderId type alias, FetchMode enum, OrderRecord data class
FixtureRepository.kt A generic, by lazy-cached repository over a flat fixture file
FetchResult.kt The covariant sealed result every check returns — try designing it yourself first!
Retry.kt A reified retry helper
Logged.kt A custom property delegate, reused verbatim from Part 15's own mini-build
OrderChecker.kt The coroutine logic: supervisorScope/async/withTimeout over a batch of orders
Main.kt The command-line entry point (complete reference solution)
data/orders.txt 5 fixture orders covering every FetchMode
libs/ kotlinx-coroutines-core-jvm-1.11.0.jar, the same jar and version Part 14 verified
tests_manual.md Every CLI command to try, with the exact expected (or (varies)) output

How to run

Open a terminal in this folder (kotlinc 2.4.21, JDK 21 Corretto — see ../../TOOLING.md). This project needs kotlinx-coroutines-core-jvm, the same dependency and the same classpath convention Part 14 verified: no Gradle, a jar fetched once and checked in under libs/, kotlinc -cp to compile against it, java -cp with the real class name to run (never java -jar, which silently ignores any -cp you also pass):

kotlinc *.kt -cp libs/kotlinx-coroutines-core-jvm-1.11.0.jar -include-runtime -d concurrent-cli.jar
java -cp "concurrent-cli.jar:libs/kotlinx-coroutines-core-jvm-1.11.0.jar" MainKt help
java -cp "concurrent-cli.jar:libs/kotlinx-coroutines-core-jvm-1.11.0.jar" MainKt check-all

MainKt is the class Kotlin generates for Main.kt's top-level fun main — see Part 14's README section on how kotlinc derives that name from a file name, if you rename the file.

By default, commands read data/orders.txt relative to the current directory — run from this project's folder, or pass --data /path/to/orders.txt.

Features

Command What it does Example
check <orderId>... Check one or more orders concurrently check O-1001 O-1003
check-all Check every order in the fixture file concurrently check-all
watch <times> <intervalMs> Run check-all repeatedly, pausing intervalMs between rounds watch 3 1000
help Show the command list help

Outcomes, not crashes: a batch check never throws just because one order failed or timed out — every order gets its own FetchResult (Success/Failed/TimedOut), printed as OK/FAILED/TIMEOUT. The process still exits 0 after a batch with failures in it, because "3 of 5 partners responded" is a normal, successful run of the tool — see tests_manual.md section 2 for a full transcript. The CLI itself still exits 2 for a genuinely malformed command (see tests_manual.md's usage-error section).

Which Parts each piece uses

Piece Skills Part
typealias OrderId = String type aliases Part 13, section 6
FixtureRepository<T> a generic, type-safe class — this stage's "cache/repository" learning outcome Part 13
sealed class FetchResult<out T> declaration-site variance (out) Part 13, section 3
suspend inline fun <reified T> retrying(...) type erasure and reified, which requires inline Part 13, section 5
OrderChecker.checkAll's supervisorScope { orderIds.map { async(Dispatchers.IO) { ... } } }.awaitAll() structured concurrency, coroutine builders, isolating one task's failure from the rest Part 14
withTimeout(perTaskTimeoutMs) { ... }, catching TimeoutCancellationException cancellation, timeouts Part 14, section 4
delay(...) standing in for every "network call", never Thread.sleep suspend functions vs. blocking calls Part 14, section 1
retrying's catch (e: CancellationException) { throw e } before the generic catch never swallow cancellation, including inside a retry loop Part 14, section 6
Logged<T> and var totalFetchAttempts by Logged(0) { ... } custom property delegates (operator fun getValue/setValue) Part 15, section 6
FixtureRepository.records by lazy delegated properties, computed once Part 15, section 4
OrderRecord.parse(...) on a companion object companion-object factory, same shape as Part 9's Account.open(...) Stage 2, Part 9

Build it step by step

Build in small steps. Compile and run after every step. Try each one yourself before opening the finished .kt files in this folder.

Step 1: The fixture row and a generic repository (Part 13)

What and why: decide what "one order" looks like before writing any concurrency. Every fixture-backed project in this course so far (Stage 1's expense tracker, Stage 2's library system) hand-rolled its own file-reading function; this time, generalize it once:

class FixtureRepository<T>(private val file: File, private val parseLine: (String) -> T) {
    val records: List<T> by lazy {
        file.readLines().filter { it.isNotBlank() && !it.trimStart().startsWith("#") }.map(parseLine)
    }
    fun find(predicate: (T) -> Boolean): T? = records.find(predicate)
}

FixtureRepository<OrderRecord>(File("data/orders.txt"), OrderRecord::parse) reads and parses the file exactly once, the first time anything touches records — by lazy (Part 15) makes that a one-line guarantee instead of a hand-written "have I loaded yet?" boolean flag.

✅ Test: FixtureRepository(file) { OrderRecord.parse(it) }.records.size → 5 against data/orders.txt.

Step 2: A covariant sealed result (Part 13, section 3)

What and why: a batch check needs to report three different outcomes — success (with a value), failure (with a reason), timeout (with how long it waited) — in one List. A plain invariant T can't do this:

sealed class FetchResult<out T> {
    data class Success<T>(val orderId: OrderId, val value: T, val elapsedMs: Long, val attempts: Int) : FetchResult<T>()
    data class Failed(val orderId: OrderId, val reason: String, val attempts: Int) : FetchResult<Nothing>()
    data class TimedOut(val orderId: OrderId, val afterMs: Long) : FetchResult<Nothing>()
}

Without out T, FetchResult<Nothing> (what Failed/TimedOut are) would not be assignable to FetchResult<String>, and checkAll could never return a single List<FetchResult<String>> mixing all three outcomes.

✅ Test: val results: List<FetchResult<String>> = listOf(FetchResult.Success("O-1", "ok", 10, 1), FetchResult.Failed("O-2", "boom", 2)) compiles without a cast.

Step 3: A reified retry helper (Part 13, section 5)

What and why: FLAKY partners fail once and recover — worth one retry before giving up.

suspend inline fun <reified T> retrying(times: Int, label: String, block: suspend (attempt: Int) -> T): Pair<T, Int> {
    repeat(times) { attempt ->
        try {
            return block(attempt) to (attempt + 1)
        } catch (e: kotlinx.coroutines.CancellationException) {
            throw e   // never swallow cancellation -- Part 14's rule, even inside a retry loop
        } catch (e: Exception) {
            println("  retry $label (${T::class.simpleName}): attempt ${attempt + 1}/$times failed -- ${e.message}")
        }
    }
    throw IllegalStateException("retrying() exhausted")
}

T::class.simpleName only compiles because T is reified — type erasure means an ordinary generic function has no T left at runtime to ask about; reified requires inline, which is also what lets this suspend function's non-suspend repeat { } call a suspend lambda directly (the lambda is inlined into this function's own body, not invoked through a separate call frame).

✅ Test: retrying(2, "x") { attempt -> if (attempt == 0) throw RuntimeException("first try fails") else "ok" } returns "ok" to 2.

Step 4: OrderChecker — the coroutine logic (Part 14)

What and why: every order's check must happen concurrently, and one order failing or timing out must never affect the others:

suspend fun checkAll(orderIds: List<OrderId>): List<FetchResult<String>> {
    val results = supervisorScope {
        orderIds.map { orderId -> async(Dispatchers.IO) { fetchOne(orderId) } }.awaitAll()
    }
    totalFetchAttempts += results.sumOf { /* attempts, or 0 for a timeout */ }
    return results
}

Every async starts before any of them is awaited (.map { async { ... } }.awaitAll(), not async { ... }.await() one at a time in a loop) — the same mistake Part 14's "common mistakes" table warns about, and the whole reason this batch finishes in ~500ms instead of ~3000ms. fetchOne wraps the real work in withTimeout(perTaskTimeoutMs) and catches TimeoutCancellationException specifically, before a broader catch (e: Exception).

✅ Test: with the sample fixture, checkAll(listOf("O-1004")) returns a single FetchResult.TimedOut after roughly 500ms, not 2000ms (the fixture's full simulated latency).

🔍 Going deeper: totalFetchAttempts is only ever mutated after awaitAll() returns, never from inside a concurrent async block. Updating shared mutable state from several coroutines at once needs a Mutex or an atomic type to be safe — sidestepping that entirely, by summing each task's own result sequentially afterward, is simpler and exactly as correct for what this counter needs.

Step 5: A custom delegate for the running counter (Part 15, section 6)

What and why: reuses Part 15's own Logged<T> mini-build exactly — two operator functions, nothing more — applied to real information instead of a toy example:

class Logged<T>(initial: T, private val onChange: (name: String, old: T, new: T) -> Unit) {
    private var value: T = initial
    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value
    operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: T) {
        if (newValue != value) { onChange(property.name, value, newValue); value = newValue }
    }
}

var totalFetchAttempts: Int by Logged(0) { _, old, new -> println("  [fetch attempts] $old -> $new") }
    private set

Because OrderChecker is one long-lived instance across a watch run's repeated rounds, the same delegate instance keeps counting across rounds — see tests_manual.md section 5 for the 0 -> 6, then 6 -> 12 transcript.

✅ Test: call checkAll twice on the same OrderChecker and confirm the printed counter only ever goes up, carrying over between calls.

Step 6: Main.kt — the CLI (Stage 1/2 project pattern)

What and why: this is the only file that reads args, calls runBlocking to bridge into the coroutine world, and prints anything.

fun main(args: Array<String>): Unit = runBlocking {
    // parse --data, then dispatch on "check" / "check-all" / "watch" / "help"
}

Exit codes: 0 for a completed batch (even one with individual failures/timeouts inside it), 2 for a command line that doesn't parse at all (unknown command, missing arguments, a non-numeric watch argument).

✅ Test: run every command and error case in tests_manual.md, including section 12's deliberate java -jar failure.


Stretch goals

  • 🟢 A --timeout <ms> global option, instead of the hard-coded 500ms default.
  • 🟢 Sort check-all's output: failures and timeouts first, so the problems are the first thing you see.
  • 🟡 A Mutex-guarded or AtomicInteger-backed version of totalFetchAttempts that is safe to update from inside each concurrent task directly, and a short note on why the current "sum after awaitAll()" design doesn't need one.
  • 🟡 A Flow-based watch command (Part 14's "a first look at Flow") instead of a plain repeat loop with delay between rounds.
  • 🔴 Cancel an in-progress watch cleanly on Ctrl-C (a shutdown hook that cancels the runBlocking scope's Job), and confirm every in-flight task's finally block still runs.
  • 🔴 Package this as a standalone native-ish launcher using Part 16's packaging skills, instead of java -cp "...:..." MainKt.

Checklist

  • I can write a generic class (FixtureRepository<T>) and explain what "type-safe" buys over a Map<String, Any> grab-bag.
  • I can explain why FetchResult<out T> needs out, with FetchResult<Nothing> as the concrete motivating case.
  • I can write a reified inline function and explain why reified requires inline.
  • I started every async before awaiting any of them, and can point at the "common mistakes" case in Part 14 this sidesteps.
  • I caught TimeoutCancellationException specifically, and CancellationException separately inside a retry loop, before a broader catch (e: Exception).
  • I wrote a custom property delegate with operator fun getValue/setValue, and used it for something with real information, not a toy example.
  • I ran every command and error case in tests_manual.md, including the deliberate java -jar failure, and understood why each one behaves the way it does.

Next

🎉 Stage 3 done! Go back to the roadmap and on to Stage 4: DSA in Kotlin, or pick a Stage 5 specialization track.

Search the guide