Wrzasq.pl

X-Ray tracing for Kotlin Ktor client

Thursday, 09 March 2023, 13:04

Just yesterday I wrote about X-Ray integration for Rust SDK. Tracing is very important in serverless microservice architecture - if you have tens or hundreds of AWS Lambda functions behind API Gateway communicating via SQS queues looking into logs in single place will not be enough - with the main issue very often being lack of that place to look for in the first place. When working with Kotlin and distributed microservices, usually default choice is Ktor (for client). It's possible to track external communication (non-AWS services) with X-Ray, but of course it needs to be recorded. I've build an extension (called feature in Ktor) that saves each external HTTP call as X-Ray trace.

In order to use it just add Maven dependency to your pom.xml (or transform it into your Gradle setup):

        <dependency>
            <groupId>pl.wrzasq.commons</groupId>
            <artifactId>commons-client</artifactId>
            <version>2.0.10</version>
        </dependency>

Afterwards, using it in the code is super simple, as this is a regular Ktor feature - here is an example of JSON API client:

import io.ktor.client.HttpClient
import io.ktor.client.engine.apache.Apache
import io.ktor.client.features.json.JsonFeature
import io.ktor.client.features.json.serializer.KotlinxSerializer
import io.ktor.client.request.get
import kotlinx.serialization.json.Json
import pl.wrzasq.commons.client.XRayFeature

val httpClient = HttpClient(Apache) {
    install(JsonFeature) {
        serializer = KotlinxSerializer(
            // extra configuration if needed
            Json(json)
        )
    }
    install(XRayFeature)
}

httpClient.get<TenantKey>("${url}keys/${tenantKeyId}")

And this is the result in X-Ray console:

Tags: , ,