Measuring KTor Client traffic with a MicroMeter plugin

Anders Sveen
ZTL Payments
Published in
2 min readOct 28, 2022
Stats for different endpoints of number of calls with status codes given.

UPDATE (July 2024): If you are using the New Relic Java agent (and New Relic) the following extension should probably be enough. I recommend testing it before introducing the things in this article that used to be necessary. The extension: https://github.com/newrelic-experimental/newrelic-java-ktor

If you are looking for a Micrometer solution the below should still have enough pointers to work. 😃

We use KTor Client to make calls to third party APIs, and while New Relic gives us good insights (if you use the OkHttp backend) into the average response times based on the host we call, we needed more detailed information about the endpoints and their stats. Even response codes.

Since we use MicroMeter to feed information to New Relic we started looking for a solution.

Luckily some smart people had posted a good starting point for us, this is a summary of that and the few extra things we added.

The good thing about doing this as a plugin is that you pick up and measure all calls and URLs. But this also leads metrics to be measured separately for two URLs with just differing IDs, like /transaction/<transactionId1>/status and /transaction/<transactionId2>/status. Since KTor Client doesn’t really have the concept of a route we had to add that manually. Our solution is a partial duplication of the URL, but we can live with it as third party URLs rarely change. And if it does, it is right next to the actual URL.

With a route, a standard call looks like this (note the route(…) call):

And it will not do anything without “installing” the plugin in the KTor Client. Like this:

MeterRegistry is of course from MicroMeter and dependency injection. 😃

And here’s the actual plugin code:

And voila! You get stats that you can slice and dice any way you like. Check out the top image for one example in New Relic. Since MicroMeter integrates with other platforms you can easily do it where you normally analyze metrics. 😃

Bonus exercise: Tie this metric to the “originating” HTTP request from KTor server (or really any other server in Kotlin).

Create a CoroutineContext.Element to contain the name of incoming call like this:

Add it to the co-routine context through withContext and pick it up in the plugin through coroutineContext[NewRelicTransactionNameContextElement] and add it to the additionalTags in the plugin. 😃

Oh. And we’re hiring developers. If you want to come change the banking industry with us, reach out on recruitment@ztlpay.io .

--

--