Ktor ? Arrow

This example is going to be presented as part of the Kotlin webinar series.

This repo showcases how Arrow helps with frequent pain points in backend development. Needless to say, the implementation is very simplistic in many other aspects we do not cover in the webinar; in particular we try to keep the number of files as a minimum.

The example

The repo contains a small HTTP service built with Ktor responsible for handling orders. The behavior comprises the following steps:

  1. The order comes in as JSON, and we perform some simple validation (like the amount in the order is positive),
  2. We then validate against the warehouse service that enough of each product still exist,
  3. Finally, we send a request to the billing microservice, which is responsible for handling the payments.

The order is represented as a simple set of data classes marked as @Serializable.

Validation

Steps (1) and (2) involve validation logic, in both cases we take a functional approach to the problem. That is, instead of creating functions which directly check the values, we build a larger validator by combining small building blocks. More concretely, Validated is used.

Validation against the warehouse is a bit trickier, since it involves several calls to an external service. This example highlights how the tools provided by Arrow Fx, like parTraverse, integrate very well with the suspend mechanism and take care of cancellation when required.

Retries

A very common situation is for the billing microservice in step (3) to be completely external to our infrastructure. One fewer headache for us, except for those moments in which that service becomes unstable or unresponsive. Arrow Fx provides simple ways to retry those calls, and even introduce a circuit breaker to prevent saturation after some downtime.

GitHub

View Github