Hello, I'm encountering an issue with Koin's `Requ...
# koin
m
Hello, I'm encountering an issue with Koin's
RequestScope
while handling concurrent POST requests in a Ktor application. The application is set up to use Koin for dependency injection and
RequestScope
for isolating dependencies per request. However, when two requests are made concurrently, one of them fails with the following error:
Copy code
Failed to resolve dependency 'interface <DependencyName>' because of 'Scope 'org.koin.ktor.plugin.RequestScope@1453707788' is closed'
Upon logging the scope IDs, we noticed that the scope initialized for the request is different from the one being logged during the error. For example: • Scope initialized:
org.koin.ktor.plugin.RequestScope@1527158232
• Scope during error:
org.koin.ktor.plugin.RequestScope@1453707788
To debug further, I added a breakpoint in the
setupKoinScope
function in the Koin-Ktor library:
Copy code
internal  fun PluginBuilder<KoinApplication>.setupKoinScope(koinApplication: KoinApplication) {
    // Scope Handling
    on(CallSetup) { call ->
        val scopeComponent = RequestScope(koinApplication.koin)
        call.attributes.put(KOIN_SCOPE_ATTRIBUTE_KEY, scopeComponent.scope)
    }
    on(ResponseSent) { call ->
        call.attributes[KOIN_SCOPE_ATTRIBUTE_KEY].close()
    }
}
I observed that the scope ID logged in
on(CallSetup)
is not the same as the one logged in
on(ResponseSent)
. This suggests that the scope is being replaced or recreated during the request lifecycle, which could explain the mismatch and the "scope is closed" error. 1. Has anyone encountered a similar issue with Koin's
RequestScope
in a Ktor application, where the scope ID changes during the request lifecycle? 2. What could cause the
RequestScope
to be replaced or recreated between
on(CallSetup)
and
on(ResponseSent)
? 3. How can I ensure that the
RequestScope
remains consistent and properly tied to the request lifecycle, especially in a concurrent environment? Any insights or suggestions would be greatly appreciated!
🤔 1
s
Howdy, I read in a different thread last week that ktor has some non-obvious behavior around concurrency handling in its authentication blocks. Do you think this issue may be related? https://kotlinlang.slack.com/archives/C0A974TJ9/p1740648873568719
m
Hey thanks for sharing. I cant directly correlate both issues, but it could be the same issue under the hood. I will keep an eye on the issue created. I will try bumping to latest koin version since i saw there is a fix for multiple creation of scope issue in v4