Rate limiter
- Kotlin course
- Advanced
- Lesson 70/83
- 5 min
Learn the rate limiter pattern.
Rate limiter
A rate limiter limits an operation to a certain rate. The simplest form uses a counter to allow a fixed number of requests; later ones are rejected.
Example: class RateLimiter(val max: Int) { var count = 0; fun tryAcquire(): Boolean { if (count >= max) return false; count++; return true } }. Each call to tryAcquire increases the counter; once max is reached, it returns false. This pattern is used for API quotas and flood protection.
tryAcquire and the counter
tryAcquire asks for a permit; if the counter is below max it returns true and the counter grows. Otherwise it returns false; the request is rejected.
Example: val rl = RateLimiter(2). rl.tryAcquire() returns true twice; the third call returns false. This pattern can be combined with a Mutex to protect a shared resource concurrently.
Practice Write the RateLimiter class
Define class RateLimiter(val max: Int) with var count = 0 and a method fun tryAcquire(): Boolean. The method returns true and increments count if count is less than max; otherwise returns false. In main create RateLimiter(2) and print the results of three tryAcquire calls with println.
Starter code
// RateLimiter class: max and count
// tryAcquire: true if count<max, else false
// in main print three call resultsSample solution
class RateLimiter(val max: Int) {
var count = 0
fun tryAcquire(): Boolean {
if (count >= max) return false
count++
return true
}
}
fun main() {
val rl = RateLimiter(2)
println(rl.tryAcquire())
println(rl.tryAcquire())
println(rl.tryAcquire())
}Expected output
true true false
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the main goal of a rate limiter?
- Limit request count Correct answer
- Compress data
- Cache
- Increase speed
Explanation: A rate limiter limits request count.
2 Match the rate-limiter parts
| Term | Meaning |
|---|---|
class RateLimiter |
Class definition |
max |
Permit cap |
tryAcquire() |
Permit request |
count >= max |
Reject condition |
3 Complete the tryAcquire call
val rl = RateLimiter(2)
val ok = rl.____()
val rl = RateLimiter(2)
val ok = rl.tryAcquire()
Explanation: tryAcquire requests a permit.