Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Beyond the Ordinary: A New Era of Kotlin

Beyond the Ordinary: A New Era of Kotlin

Discover how Kotlin can revolutionize your REST API development. Learn about the powerful features and benefits that make Kotlin a superior choice for building modern, scalable, and efficient APIs. From coroutines to type safety, explore the reasons why Kotlin is the future of REST API development.

Adam Kalmar

October 22, 2024
Tweet

Other Decks in Programming

Transcript

  1. Kotlin Budapest Meetup | 2024 Adam Kalmar October 17, 2024

    Beyond the Ordinary: A New Era of Kotlin
  2. Kotlin Budapest Meetup | 2024 1. Leveraging Kotlin for Server-Side

    Development 2. Overview of Ktor Framework 3. The Big Debate: Ktor vs Spring Boot 4. The Challenges: Java Interoperability Pain Points Writing powerful, asynchronous REST APIs with Kotlin Table of content
  3. Kotlin Budapest Meetup | 2024 Kotlin gives us a new

    way to write powerful code compared to the traditional threading model. Coroutines Kotlin’s syntax is readable. In addition to that, Ktor makes us defining routes and configurations using Kotlin DSL. We can fully leverage existing Java libraries and frameworks. This makes transitioning from Java-based systems easier. And when we combine Kotlin with Ktor’s abilities we get simplicity, flexibility and performance for backend. Kotlin language features Java interoperability Flexible web framework Leveraging Kotlin for Server-Side Development
  4. Kotlin Budapest Meetup | 2024 Leveraging Kotlin for Server-Side Development

    o Kotlin has a library for coroutines o We can do highly concurrent, non-blocking backends easily without relying on 3rd party libraries (like Webflux) o Ktor or Spring Boot built with Kotlin helps us to handle thousands of concurrent requests o The built-in HTTP client with the default engine is non-blocking o We can make sure a coroutine switches threads to offload blocking I/O-bound tasks Let’s do concurrency Coroutines
  5. Kotlin Budapest Meetup | 2024 Leveraging Kotlin for Server-Side Development

    o For using coroutines, we’ll need “kotlinx.coroutines” library o “A coroutine is an instance of a suspendable computation. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works concurrently with the rest of the code. However, a coroutine is not bound to any particular thread. It may suspend its execution in one thread and resume in another one.” Let’s do concurrency Coroutines
  6. Kotlin Budapest Meetup | 2024 Multiple coroutines can run on

    a thread, and they can even switch context. Coroutines Kotlin coroutines are structured, you can launch a new one inside an existing one. They don’t get lost, and the outer scope does not complete until its coroutines.
  7. Kotlin Budapest Meetup | 2024 Leveraging Kotlin for Server-Side Development

    o launch(): launches a coroutine and continues execution o async(): launches a coroutine and gives a Deferred type (job), which we can use to wait o delay(): delays the current coroutine without blocking the current thread o runBlocking(): runs a new coroutine and blocks the current thread until its completion (it’s a bridge) -> it provides a scope Coroutine building blocks Coroutines
  8. Kotlin Budapest Meetup | 2024 Leveraging Kotlin for Server-Side Development

    o Dispatchers.Default: It uses a common pool of shared background threads. This is an appropriate choice for compute-intensive coroutines that consume CPU resources. o Dispatchers.IO: uses a shared pool of on-demand created threads and is designed for offloading of IO-intensive blocking operations (like file I/O and blocking socket I/O). o Dispatchers.Main: represents the UI thread if one is available. o When thread pools completely separate from Dispatchers.Default and Dispatchers.IO are required, they can be created with newSingleThreadContext and newFixedThreadPoolContext Dispatchers Coroutines
  9. Kotlin Budapest Meetup | 2024 Leveraging Kotlin for Server-Side Development

    o When you have a shared resource, you must do locking o It’s important to use mutual exclusion locks that are not blocking threads o Remember: one thread can run multiple coroutines and even switch threads • Traditional locks are bound to specific threads! o We have Mutex and Semaphore in Kotlin, that suspends current coroutine until the lock is acquired o So suspension/resumption logic is not broken o Atomic references, ConcurrentHashMap are non-blocking Mutual exclusion is very important Coroutines
  10. Kotlin Budapest Meetup | 2024 Leveraging Kotlin for Server-Side Development

    o Kotlin’s syntax is readable, Kotlin DSL is friendly o In addition to that, Ktor makes us defining routes and configurations using Kotlin DSL o Kotlin provides solutions for NPEs unlike Java with its type system o Kotlin type system is safer than Java’s o No checked exceptions, smart cast, string templates, extension functions, top-level functions, named arguments, infix, data classes -> you can be more creative Forces the developer to write safe code Kotlin Language features
  11. Kotlin Budapest Meetup | 2024 Leveraging Kotlin for Server-Side Development

    o We can call Java from, but it the interoperability is tricky o The nullability checks behave differently on platform types o Nullability annotations count o We can use 3rd party libraries, but it can be tricky, for example calling suspend function from a non-suspend context o But surprisingly many libraries have Kotlin support (e.g. Resilience4j) o Problems can also occur with Threadlocal, we must be careful. For example, MDC.put data will be lost after resuming the coroutine • We had this issue Using Java libraries Java interoperability
  12. Kotlin Budapest Meetup | 2024 Leveraging Kotlin for Server-Side Development

    o We have Ktor, which will be presented in the next slides o We’re looking for fast and non-blocking web frameowkrs o We can also use other web frameworks with Kotlin like Spring Boot, Javalin o Spring Boot: we can replace Webflux with suspending functions and Flows o Javalin: it’s more lightweight than Ktor and not built on coroutines, so you don’t need to have a deep understanding of coroutines There are a handful of options Flexible web framework
  13. Kotlin Budapest Meetup | 2024 This reasons why I love

    Ktor o Built by JetBrains and it’s pure Kotlin o Takes advantage of coroutines o Takes advantage of Kotlin’s syntax o I can write non-blocking, asynchronous backend without a hassle o Has a non-blocking HTTP client • Which can be used as standalone • Usable with different engines • It’s multiplatform (Android, JS etc) Overview of Ktor Framework Kotlin is not just for Android, Kotlin is for everything! Why is it a good choice for harvesting the power of Kotlin?
  14. Kotlin Budapest Meetup | 2024 o Engine for processing network

    requests o Host and port values used to access a server o SSL settings o Etc. Overview of Ktor Framework To run Ktor application, you need to create and configure a server first. Server configuration includes different settings
  15. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework It

    works with many different engines o Netty, Jetty, Tomcat: popular open-source Java based frameworks o We use Netty for its high performance, event-driven behavior, and it’s lightweight o We could use CIO for the server, but Netty is more battle- tested o CIO is coroutine based and Netty uses event-loop, both are non-blocking
  16. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework You

    can switch engines very easily, you can do that even from configuration
  17. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework You

    can customize it even further. The configuration is based on the current engine.
  18. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework We

    can install plugins and intercept call phase in the request proces o The pipeline is a list of interceptors (Setup, Monitoring, Plugin, Call) o We can use a lot of plugins: compression, logging, CORS, RateLimit o We can intercept request for logging, authentication
  19. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework Developer

    mode o Auto-reloading classes o Extended debug information for pipelines and response pages for HTTP 5XX
  20. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework Logging

    o Ktor uses SLF4J API for Logback or Log4j o Coroutines are handled for MDC o You can use tihs application logger itself, but it’s not recommended in other places o Otherwise you can choose another logger if it suits your needs o You must handle MDC manually: I solved it by intercepting the call phase, populating the call’s coroutine context with custom data that is captured on resumption
  21. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework Responses

    o call.respond() o call.respondHtml() o call.respondText() o call.respondTemplate(“filename”, mapOf()) o HTML DSL, CSS DSL, Mustache, Thymeleaf o For object, you must install ContentNegotiation plugin and configure serialization: JSON, XML, Protobuf o call.respondFile()
  22. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework Exception

    handling StatusPages plugin allows us to respond to an unexpected issues.
  23. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework What

    else you can do with Ktor server o Serving static content: files from filesystem or classpath o Serving SPAs: React, Angular, Vue etc. o Authentication: basic, bearer, form, session, oauth etc o Works with sessions o Swagger UI o Server-Sent Events o Testing engine
  24. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework After

    the server, let’s configure the client. o The Ktor client can be used on many platforms, not just JVM o It can be used with many different engines like Apache, OkHttp, CIO even with Curl o The engine determines the features, for example HTTP/2, websockets etc
  25. Kotlin Budapest Meetup | 2024 Overview of Ktor Framework After

    the server, let’s configure the client.
  26. Kotlin Budapest Meetup | 2024 Hard to compare: ecosystem vs

    web framework Spring Boot Ktor Trust Battle-tested, strong support and integrations make it the go-to choice for enterprise applications Relatively new in the market, cannot provide the same level of ecosystem and documentation Integration MVC-style, has anything you ever wanted, but a lot of annotations and magic behind the scene Routing-based, less integrations, you will have to write things yourself, but there are a lot of libraries: serialization, testing, DI, HTTP, and no annotations Configurations Tweaking of configuration needed if you’d like to change defaults. Butthere is auto-configuration and component scanning, which is convenient Lightweight, you can add new plugins easily, Kotlin DSL. No magic, what you write is what you run but no auto-configuration and component scanning Development Java knowledge is enough, but the learning curve is steep in the ecosystem. Slower startup time Required to know Kotlin, but that’s all. The startup time is quicker Dependencies Huge dependency tree. Harder to bump versions Small dependency tree. Easier to manage. Performance - For Java: traditional threading model, virtual threads, Webflux (NB) - For Kotlin: coroutines, suspending functions (Spring Kotlin Plugin) Coroutines are supported by nature
  27. Kotlin Budapest Meetup | 2024 o It’s hard to choose,

    depends on your requirements o Ktor is ideal for high performance, lightweight applications with a lot of configuration possibilities o Spring Boot is idea for applications that are complex and need its large ecosystem o The Spring framework is already prepared for reactivity, and its Kotlin support makes it possible to detect suspend functions and converts it to a non-blocking, async operation o When the request comes in, the coroutine handles it, and when it’s suspended, the thread is free to use for other things (HTTP call, database query etc) Choose based on your preferences Which one to choose?
  28. Kotlin Budapest Meetup | 2024 o “org.jetbrains.kotlinx:kotlinx-coroutines-reactor”, “org.jetbrains.kotlinx:kotlinx-coroutines-reactive”, “org.jetbrains.kotlinx:kotlinx-coroutines-core” o

    When we add suspend keyword, it means the function can be called from a coroutine context o "org.springframework.boot:spring-boot-starter-webflux” o When we add this dependency, we replace Web MVC with the fully reactive Webflux o Note: you must make sure your HTTP client, DB client etc are also non-blocking Choose based on your preferences, but requests should not be bound to specific threads! Which one to choose?
  29. Kotlin Budapest Meetup | 2024 o KTORM: Kotlin ORM lib

    with SQL DSL o AWS SDK for Kotlin (still under development) o resilience4j-kotlin (circuit breaker, retry, time limiter, rate limiter, bulkhead etc) o Koin, Dagger for dependency injection o Klaxon: JSON parser for Kotlin o Kotlin native instead of GraalVM for native image compilation o OpenAPI generation has some issues o Request validation Whatever you choose, Kotlin is powerful Which one to choose?
  30. Kotlin Budapest Meetup | 2024 Benchmarks Benchmarks: https://leondesilva.medium.com/spring-vs-vert-x-vs-ktor-vs-play-framework-the-performance-battle-for-a-jvm-based-api- gateway-6eebbbd4d1b5 “I

    built 6 applications based on the above options and variations of the options which has the capability of mapping and routing requests as an API gateway. Once the gateway receives a request it calls an underlying service according to the mapping. All applications were built on Java 21 and was running on a 4 core machine with a minimum heap of 256 MB and max heap of 1GB. The tool wrk was used to benchmark the frameworks. Initial load was a 30s warmup load, then a 30s load and finally a 60s load was put on each gateway to measure their performance.”