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?
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.
There is coroutine support in Exposed.
Please read the documentation:
https://github.com/JetBrains/Exposed/wiki/Transactions#working-with-coroutines
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.
© 2022 - 2024 — McMap. All rights reserved.