Tracing requests in Ktor Client
The CallId plugin allows you to trace client requests end-to-end by using unique call IDs. It is particularly useful in microservice architectures to keep track of calls, regardless of how many services a request goes through.
A calling scope might already have a call ID in its coroutine context. By default, the plugin uses the current context to retrieve a call ID and adds it to the context of the specific call using the HttpHeaders.XRequestId header.
Additionally, if a scope comes without a call ID, you can configure the plugin to generate and apply a new call ID.
Add dependencies
To use CallId, add the ktor-client-call-id artifact to your build script:
Install CallId
To install the CallId plugin to your application, pass it to the install function in the specified module. The following examples show how to install CallId:
In an
embeddedServer()function call.In an explicitly defined
module()extension function on theApplicationclass.
Configure CallId
The CallId plugin configuration, provided by the CallIdConfig class, allows you to generate a call ID and add it to the call context.
Generate a call ID
Generate a call ID for a specific request in one of the following ways:
The
useCoroutineContextproperty, enabled by default, adds a generator that uses the currentCoroutineContextto retrieve a call ID. To disable this functionality, setuseCoroutineContexttofalse:
The
generate()function allows you to generate a call ID for an outgoing request. If it fails to generate a call ID, it returnsnull.
You can use multiple methods to generate a call ID. In this way, the first non-null value will be applied.
Add a call ID
After you retrieve a call ID, you have the following options available to add it to the request:
The
intercept()function allows you to add a call ID to the request by using theCallIdInterceptor.
The
addToHeader()function adds a call ID to a specified header. It takes a header as a parameter, which defaults toHttpHeaders.XRequestId.
Example
In the following example, the CallId plugin for the Ktor client is configured to generate a new call ID and add it to the header:
The plugin uses the coroutine context to get a call ID and utilizes the generate() function to generate a new one. The first non-null call ID is then applied to the request header using the addToHeader() function.
In a Ktor server, the call ID can then be retrieved from the header using the retrieve functions from the CallId plugin for the server.
In this way the Ktor server retrieves the ID of the specified header of the request and applies it to the callId property of the call.
For the full example, see client-call-id