Backend for mobile engineers with Kotlin and Ktor

Yevhenii Kanivets
Nov 26, 2020 · 5 min read

How many times were you thinking about writing your backend for mobile apps you are working on? And how many times have you chosen Firebase instead? Are there any better options at the moment?

Image for post
Image for post

In this article, I'll describe our experience of writing Kotlin backend for Codeforces WatchR mobile apps using Ktor, which is officially positioned as follows:

An asynchronous framework for creating microservices, web applications, and more. It’s fun, free, and open source.

Why backend is needed?

Codeforces WatchR started almost 3 years ago as a pet-project, which used official Codeforces API to simply fetch and display data from server. But with time we came up with many additional features, for which the existing API wasn't convenient or even sufficient. So what to do in such a case?

For a while, we were implementing all the logic on mobile clients. Fortunately enough, we had migrated to Kotlin Multiplatform about a year ago, so at least we needed to implement the logic only once in the common module.

BTW, full story is described in article Kotlin Multiplatform: ready, steady, …

Image for post
Image for post

But eventually, we hit the roadblock with features, which are simply can't be done without some kind of real backend:

  • working with big amounts of historical and operational data

In general, backend is needed for anything, that requires cross-device communication and data/logic centralization.

Why not Firebase?

First of all, Firebase is a great choice for some kinds of projects, especially MVPs (Minimum Viable Product). It allows shipping the first versions of your apps faster and cheaper. But it has 3 disadvantages once you get the traction:

  • you are locked inside the platform because all your code heavily relies on Firebase, and you can't simply swap to other services

Shortly, Firebase's main advantage is simplicity, but you certainly can find alternatives with much better flexibility and price/value ratio.

Why Ktor?

Our previous experience is in mobile development, so we are mainly used to Kotlin and Swift. Even though there is decent progress in bringing Swift to backend, it's not officially supported by Apple and community is rather small.

On other hand, Ktor is officially developed and supported by JetBrains, creators of Kotlin. They aren't only investing into the dedicated team, but also actively promoting the technology, organizing conferences, etc.

Image for post
Image for post
From official Ktor site

Ktor is the first-class citizen of the Kotlin ecosystem, which means deep integration with the language itself and all its features, like coroutines, sealed classes, multiplatform distribution, extensibility, and so on.

Ktor design has been obviously inspired by other popular frameworks. For example, I've noticed a close resemblance to Laravel. So experienced backend developers won't be surprised too much when switching to Kotlin world.

Kotlin is fully compatible with any existing Java libraries or frameworks, so you can easily integrate Ktor with Spring or Hibernate, for example. But of course, there are Kotlin-first libraries for the most popular tasks.

Architecture

Ktor is a minimalistic modular framework, so there are only a few absolutely necessary things available out of the box. Everything else is implemented as pluggable features, which are injected directly into Pipeline.

The pipeline is a structure containing a sequence of functions (blocks/lambdas) that are called one after another, distributed in phases topologically ordered, with the ability to mutate the sequence and to call the remaining functions in the pipeline and then return to current block.

Pipelines are used in Ktor as an extension mechanism to plug functionality in at the right place. For example, a Ktor application defines five main phases: Setup, Monitoring, Features, Call and Fallback. The routing feature defines its own nested pipeline inside the application’s call phase.

Image for post
Image for post
From Ruslan Ibragimov's presentation at Kotlin Night Kiev

Other than that, Ktor isn't forcing you for any particular approach, so you are free to choose and implement the architecture that fits your needs best.

In our case, we implemented classical MVC (Model — View — Controller) architecture with a public API instead of View and dedicated Interactors, which encapsulate all business logic related to each endpoint.

Image for post
Image for post

Application

To create Ktor server, you simply need to create new project, declare the application entry point, and install a few features to start with. In our case, these features are ContentNegotiation and Routing.

At the moment we have a single route, which returns compiled Newsfeed from different sources, ready to be consumed by mobile clients.

GetNewsInteractor is using Codeforces, YouTube, and other repositories to fetch data from 3rd party resources and database, which is abstracted through Exposed library (officially supported by JetBrains as well).

All data transformation happens thanks to another officially supported library — kotlinx.serialization, but you have other popular libraries available too.

The best part here that you can simply copy your API classes from Kotlin Backend to Kotlin Multiplatform common module, and it will work.

Hosting

Ktor application is compiled to a jar file, which then can be run anywhere you want, from Raspberry Pi to the dedicated AWS instance. We've chosen Heroku for its simplicity, free plans, and transparent subscription-based pricing.

Image for post
Image for post

Bottom line

Voilà! We have our own fully-functional backend written in Kotlin, which is perfectly suited to our needs, and open to changes in any direction we would like to take in the future. And we still can use some Firebase on the backend ;)

I hope this article will motivate more mobile engineers to get the full potential from their mobile apps by applying their Kotlin skills on the backend side. Let's unlock more cool stuff together!

Featured in Kotlin Weekly #227 and Android Weekly #445.

xorum.io

Engaging #EdTech solutions for Mobile (iOS | Android | KMP) and Web (Kotlin | Ktor)

Thanks to Alla Dubovska

Yevhenii Kanivets

Written by

Professional Mobile Engineer since 2014, passionated by #EdTech, learning and teaching. Competitive programming enthusiast. Marathon Finisher.

xorum.io

xorum.io

Engaging #EdTech solutions for Mobile (iOS | Android | Kotlin Multiplatform) and Web (Kotlin | Ktor | Vue.js)

Yevhenii Kanivets

Written by

Professional Mobile Engineer since 2014, passionated by #EdTech, learning and teaching. Competitive programming enthusiast. Marathon Finisher.

xorum.io

xorum.io

Engaging #EdTech solutions for Mobile (iOS | Android | Kotlin Multiplatform) and Web (Kotlin | Ktor | Vue.js)

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store