Building a blazing fast microservice with Kotlin using Http4k: Part 1

Aishwarya Raj Pandey
5 min readMar 2, 2021
Http4k and Gradle: Weaponize Kotlin like never before

I started my journey at Pratilipi as an Android Developer with little know-how of Ryan Dahl’s C++ program — NodeJS, which was the go-to paradigm for building microservices. As an over-enthusiastic newcomer, who wanted to touch up all things shiny in pratilipi’s system. I spent the next 2 years flirting with Javascript, a girl who keeps giving you signals why she is just not the one to commit your life with.

Then came, Golang. This was great. Finally some sense of control and much less ambiguity in our relationship. But there was one problem. This one wouldn’t let you be in control. Doing simple tasks became too tedious, a quality which makes you miss your ex even more.

If you don’t cry are you really coding in Javascript?

Enter Kotlin

Keeping things simple. Working with Kotlin has been a breeze. It allows you so much more control over getting shit done which Golang struggles with. Doesn’t add ambiguity with increasing project size and configurations which javascript will strangle you with once the honeymoon period of building CRUD APIs is over.

Kotlin/Http4k

The biggest issue in persuading my managers to pick up Kotlin for the backend has been the lack of popular frameworks and benchmarks with Kotlin. That’s where Http4k shines and puts up amazing numbers when compared to the most used frameworks.

@techempower places http4k higher than Actix/Rust in terms of latency.

Kotlin/Vertx

Another framework that Kotlin devs can take into consideration is vertx which ranks way higher than Javascript and Golang frameworks (Express was at 144th and Gin at 96th) in terms of handling multiple queries as well as provides Coroutines support out of the box.

Vertx outperforms even Http4k over Azure machines in terms of multi-request handling

Microservice with Http4k

Http4k brings the concept of the server as a function to the table (Serverless anyone?). While this is not anything new. It allows us to utilize the functional capabilities of Kotlin to the full.

Gradle

Gradle dependencies to get started with Http4k
A bit like go. But with Javascript powers

The above lines of code are all that you need to get your server started and it provides Health routes out of the box for your microservice. I have used Netty here for the server which can be replaced with Undertow which gives even better performance.

Benchmarks for JSON serialization @techempower

Filters

How many times has it happened that proper authorization requires us to create custom solutions in Golang or require bucket loads of npm packages with Express? Http4k provides this capability out of the box with Filters and Lenses

Clean and simple

As shown above you can a request context filter to your server which will add Zipkin request ids for better observability and can be customized for separate use cases. Apart from that, you can add Gzip filters for response compression. Another use case would be OAuth filter to check for valid user-id. A very clean way of implementing request and response hooks that can be chained together to create whatever control flow you wish for in your server.

Lenses

Language is a required param for this API

Lenses provide simple schema validation for your incoming request as well as outgoing response. Here we can see language is a required param (lenses are available for defaulted params as well), if not present will throw an error which will be caught by the above-mentioned ServerFilter.CatchLensFailure() which in turn would return 400 status code.

inline function to return the response.

The above list response inlined function would wrap the list response with a status code. The function can simply be a DB query that returns a list of ids. These 3 lines are validating the response, wrapping the output as well as providing a status code for it. If anything fails, ServerFilter.CatchLensFailure() will again come into play to respond with a bad request. These are available for Files, path params as well form-encoded URLs.

Routing

I specifically wanted to get the hygiene functionalities out of the way before coming to the big hitters which in http4k are handlers and Router.

The routing class will be wrapped inside the Health handler to provide routes to the server.

Routing should only comprise of 3 things.

  • The route itself
  • What method is allowed
  • What is sent back

Http4k router does all that in 1 single line. Utilizing infix bind() and to() functions to map route to a particular method and return the validated result of topRatedHandler() which has been shown above while discussing Lenses. Adding nested routes is pretty straightforward as well.

Handlers

A Router is a selective request handler, which attempts to match a request. If it cannot, processing falls through to the next Router in the list. Routes can be combined together into a RoutingHttpHandler, which is both a Handler and a Router. Routers can be combined together to form another HttpHandler.

HTTP Handler is what controllers would be in microservices.

Handlers allow you to chain multiple filters to them. This is where you write your business logic. You can serve static files via StaticHandler or RouteBasedHandler for REST API.

That’s it. All you need is a router and handler to get started. In the next part, I will talk about how to add a database and caching layer and hopefully get a working git repo by the end of the series. For whosoever, it may concern I use Intellij Idea IDE

--

--

Aishwarya Raj Pandey

Whether it is product or athletics, I run really fast.