Can I mix Ktor with Exposed?
Asked Answered
B

3

9

I am writing a service using Ktor and Exposed ORM which apparently isn't async. I am coming from the Python world and back there using a blocking ORM with a async IO library is a sin as it may block all users in thread. Does the same rule apply in Kotlin? Am I creating a bad architecture?

Biff answered 18/8, 2017 at 15:23 Comment(1)
Why wouldn't it be the same? As long as there is only 1 thread then the same will happen. You could though have a dedicated thread for Exposed. That way Ktor will work on a different, independent thread than Exposed and it won't be a problemTacet
G
6

Exposed uses thread local storage to keep transaction instance accessible to implementation and avoid passing it along with every function call. Since transaction DSL function is executing synchronously and do not release a thread to be reusable by ktor for other calls there shouldn't be any issues with using them together.

Gensler answered 19/8, 2017 at 15:1 Comment(2)
Thanks for your answer! I am now confident and ready for production!Biff
Surely blocking threads for DB work largely defeats the point of using an async framework?Mcentire
N
6

There is coroutine support in Exposed.

Please read the documentation:

https://github.com/JetBrains/Exposed/wiki/Transactions#working-with-coroutines

Northumbrian answered 14/2, 2020 at 9:45 Comment(0)
J
1

Here's a blogpost that shows how to use them together:

https://ryanharrison.co.uk/2018/04/14/kotlin-ktor-exposed-starter.html

I have also successfully done so myself in a test-project but I'm not yet at a point where I'm ready to share the code.

In short, you can use Kotlin coroutines in such a way that you do the database transaction on a thread so they do not block KTOR's request handling loop. If using the right coroutine dispatcher, then this should not give any problem with the threadlocal transaction context.

Jozef answered 11/11, 2018 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.