Skip to content

Ktor instrumentation leaks context when ktor-client is used within server route #16430

@floribe2000

Description

@floribe2000

Describe the bug

When using the opentelemetry-ktor plugin, Spans start to have a wrong parent context after some requests.
This only happens if the Ktor client is used within a route or when withContext with a explicit dispatcher is used.

Steps to reproduce

Create a ktor server project with ktor 3.4.1 and add the opentelemetry plugin (Default configuration works).
Add a route that either invokes a ktor client or uses withContext with any Dispatcher.
Call it a few times (on my machine it seems to happen after 12 successful invocations, might depend on the eventLoop threadpool size).

Expected behavior

Every server route invocation creates a separate span.

Actual behavior

After the initial working calls, at some point spans start having a wrong parent context, leading to nesting or spans being missing if their parent span was dropped by a custom sampler.

Javaagent or library instrumentation version

opentelemetry-ktor-2.25.0-alpha

Environment

JDK: Temurin 21.0.10
OS: macOS 26.3.1 and Amazon Linux 2023 (latest)

Additional context

This might be related to this: #14763

The issue does not appear with the latest ktor version, potentially due to a change of the event loop dispatcher from Unconfined here: ktorio/ktor#5364

I am not entirely sure if this issue is caused by ktor or this library but I assume the cause is in this library since it seems to be related to a context from a previous call leaking to the current one.

Tip

React with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding +1 or me too, to help us triage it. Learn more here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingneeds triageNew issue that requires triage

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions