Tutorials/Exposed vs Storm: Ktor

Ktor services, side by side

Both libraries are written for Kotlin and run in coroutine-based Ktor services. They differ in where transactions are required and in how the data layer reaches the routes.

Series · Exposed to Storm5 min readKotlin

01The task

A Ktor service with a read endpoint and a write endpoint: fetch a user by id, and register a pet together with its first visit in one transaction, sending a welcome mail only after the commit.

02The Exposed way

Exposed connects a Database at startup. Every operation runs inside a transaction block, and suspendTransaction is the form for coroutines:

Application.kt Kotlin · Exposed + Ktor
1
2
3
4
5
6
7
8
9
10
11
12
13
fun Application.module() {
    Database.connect(hikariDataSource())

    routing {
        get("/users/{id}") {
            val id = call.parameters.getOrFail("id").toInt()
            val user = suspendTransaction {   // every operation runs in a transaction
                User.findById(id)?.toResponse()
            }
            call.respond(user ?: HttpStatusCode.NotFound)
        }
    }
}

Many Ktor services are built this way. Exposed requires the transaction block for every operation, including a single read, so every route that touches the database has one.

03The Storm way

Storm ships a Ktor plugin. install(Storm) builds the connection pool from application.conf and registers every repository interface in the compile-time type index. It creates them during installation, so a broken definition fails at startup. Route handlers get them with repository<T>():

Application.kt Kotlin · Storm + Ktor
1
2
3
4
5
6
7
8
9
10
11
12
13
interface UserRepository : EntityRepository<User, Int>

fun Application.module() {
    install(Storm)   // pool from application.conf, repositories from the type index

    routing {
        get("/users/{id}") {
            val users = repository<UserRepository>()
            val user = users.findById(call.parameters.getOrFail("id").toInt())
            call.respond(user ?: HttpStatusCode.NotFound)
        }
    }
}

A read outside a transaction borrows a pooled connection for the one query and returns it. For endpoints without custom queries, entity(User::class) and projection(OwnerSummary::class) give a repository without declaring an interface. Writes that belong together go in a transaction block, a suspend function that carries the transaction in the coroutine context:

Routes.kt Kotlin · Storm + Ktor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
post("/owners/{id}/pets") {
    val request = call.receive<NewPetRequest>()
    val owner = entity(Owner::class).getById(call.parameters.getOrFail("id").toInt())
    val pets = repository<PetRepository>()
    val visits = repository<VisitRepository>()

    val pet = transaction {
        val pet = pets.insertAndFetch(request.toPet(owner))
        visits.insert(request.firstVisit(pet))
        onCommit { mailer.sendWelcome(owner, pet) }
        pet
    }

    call.respond(HttpStatusCode.Created, pet)
}

onCommit runs after the commit, so a rollback never sends the mail. The block runs on Storm's transaction dispatcher and completes there, and a cancelled call stops the statement the block is waiting on. To give every route in a group its own transaction without code in the handlers, wrap the routes in transactional { }. See the transactions comparison for the full mapping.

Services that take their dependencies through Ktor's dependency injection resolve the template and each repository with by dependencies: the plugin registers them under their own types.

In Ktor's development mode the plugin also turns on performance and design advice in the log, such as a DISTINCT over a to-many join or a deep offset. The advice tutorial walks through it.

04The translation table

Exposed + KtorStorm + Ktor
Database.connect(dataSource) at startupinstall(Storm), pool from application.conf
suspendTransaction { } around every operationReads without a transaction; transaction { } or transactional { } routes for writes
Table objects and DAO entitiesRepository interfaces, registered at install, fetched with repository<T>()
DAO entities used inside the transaction, or mapped to response typesEntities are plain values, serialized directly
StatementInterceptor.afterCommit, registered on the transactiononCommit { } in the block

05Keep going

The reference documentation covers the details: