Rate Limiting in Kotlin: Libraries and Implementation

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Rate Limiting in Kotlin: Libraries, Strategies, and Practical Examples



Rate limiting is a critically important mechanism for protecting APIs, microservices, and web applications from excessive load, DDoS attacks, and random traffic spikes. In the Kotlin ecosystem, running on top of the JVM, there are several mature libraries that allow flexible implementation of this logic. In this article, we will examine three main approaches and tools: Bucket4j, Resilience4j, and the built-in RateLimiter from Guava.



1. Bucket4j — Advanced Token Bucket Implementation



Bucket4j is a Java library that is perfectly compatible with Kotlin. It implements the Token Bucket algorithm and supports both local and distributed rate limiting (via Redis, Hazelcast, Infinispan).



Key features:

  • Configuration of token count and refill rate.
  • Support for bursts through token accumulation.
  • Lock-free operation in multithreaded environments.
  • Integration with Spring Boot via the bucket4j-spring-boot-starter starter.


Example of a simple rate limiter in Kotlin:

import io.github.bucket4j.Bandwidthimport io.github.bucket4j.Bucketimport io.github.bucket4j.Refillimport java.time.Duration

fun main() { // 10 requests per minute, with the ability to accumulate up to 20 tokens val limit = Bandwidth.classic(20, Refill.greedy(10, Duration.ofMinutes(1))) val bucket = Bucket.builder() .addLimit(limit) .build()

// Check token availability if (bucket.tryConsume(1)) { println("✅ Request allowed") } else { println("❌ Limit exceeded, try again later") }}


For a distributed scenario (e.g., multiple microservice instances) use Bucket4j with Redis:

import io.github.bucket4j.distributed.proxy.ProxyManagerimport io.github.bucket4j.redis.lettuce.Bucket4jLettuceimport io.lettuce.core.RedisClient

val redisClient = RedisClient.create("redis://localhost:6379")val proxyManager: ProxyManager<String> = Bucket4jLettuce .builder(redisClient) .build()

val bucket = proxyManager.builder() .build("user:123", Bucket4jConfiguration( Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(1))) ))


2. Resilience4j — RateLimiter as Part of Circuit Breaker



Resilience4j is a popular resilience library for Java/Kotlin, including not only a rate limiter but also circuit breaker, retry, and bulkhead. Its RateLimiter module is based on the Sliding Window algorithm.



Features:

  • Easy integration with Kotlin coroutines via suspend functions.
  • Configuration of the window period and request limit.
  • Flexible failure handling: exception throwing, fallback, or waiting.


Example with coroutines:

import io.github.resilience4j.ratelimiter.RateLimiterimport io.github.resilience4j.ratelimiter.RateLimiterConfigimport io.github.resilience4j.kotlin.ratelimiter.awaitRateLimiterimport java.time.Durationimport kotlinx.coroutines.runBlocking

val config = RateLimiterConfig.custom() .limitForPeriod(10) // 10 requests .limitRefreshPeriod(Duration.ofSeconds(1)) // per 1 second .timeoutDuration(Duration.ofMillis(500)) // wait timeout .build()

val rateLimiter = RateLimiter.of("api-limiter", config)

suspend fun fetchData(): String { return awaitRateLimiter(rateLimiter) { // Your API call "Data received" }}

fun main() = runBlocking { val result = fetchData() p

Recommendations