-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
235: Building a Rate-Limited API Client with Retry Logic
Listen, we've all been there: you've integrated a great third-party API, everything works in staging, and then you hit production and suddenly your logs are screaming with 429 Too Many Requests. Most APIs have these limits to protect their infrastructure, but if your client isn't smart enough to respect them, you're just begging to get your API key blacklisted.
Today, we're going to build a robust client for a hypothetical weather service called "SkyCast." SkyCast is picky—they limit us to a few requests per second, and they occasionally flake out with 503 errors. We need a way to ensure we don't overwhelm them and a way to recover gracefully when they do.
Setting up the SkyCast Mock
Before we get into the logic, let's define what we're dealing with. I'm going to use a simple sealed class for the response so we can explicitly handle the "Rate Limited" state without relying solely on HTTP codes in our business logic.
sealed class ApiResponse<out T> {
data class Success<T>(val data: T) : ApiResponse<T>()
data class Error(val code: Int, val message: String) : ApiResponse<Nothing>()
object RateLimited : ApiResponse<Nothing>()
}
class SkyCastClient {
// Simulate an API call that occasionally fails or rate limits
suspend fun fetchWeather(city: String): ApiResponse<String> {
return when ((1..10).random()) {
in 1..6 -> ApiResponse.Success("Sunny in $city")
in 7..8 -> ApiResponse.RateLimited
else -> ApiResponse.Error(503, "Server Overloaded")
}
}
}
The Naive Retry Approach
My first instinct—and I'll admit I've done this too often in the past—is to just wrap the call in a while loop. If it fails, just try again. It feels intuitive, right?
suspend fun fetchWithNaiveRetry(client: SkyCastClient, city: String): String {
while (true) {
val response = client.fetchWeather(city)
if (response is ApiResponse.Success) return response.data
if (response is ApiResponse.RateLimited) {
println("Rate limited! Retrying immediately...")
// Just loop back and try again
} else {
throw Exception("Permanent error occurred")
}
}
}
Wait, I'm making it worse
I just looked at that code and realized I'm committing a cardinal sin of API integration. If the server tells me I'm sending requests too fast (a 429), and my response is to immediately send another request, I'm not solving the problem—I'm essentially launching a mini-DoS attack on the provider. This is the fastest way to get a permanent IP ban.
We need Exponential Backoff. Instead of hammering the server, we need to wait, and we need to increase that wait time after every subsequent failure. This gives the server breathing room to reset our quota.
Implementing Exponential Backoff
Let's rewrite this. I'll use a higher-order function here. I love this pattern because it allows us to apply this retry logic to any API call, not just the weather one. We'll take a block of code, and if it returns RateLimited, we'll delay the execution by an increasing amount of time.
import kotlinx.coroutines.delay
import kotlin.math.pow
suspend <T> retryWithBackoff(
maxRetries: Int = 3,
initialDelayMillis: Long = 1000,
block: suspend () -> ApiResponse<T>
): T {
var currentDelay = initialDelayMillis
repeat(maxRetries) { attempt ->
val result = block()
if (result is ApiResponse.Success) {
return result.data
}
if (result is ApiResponse.RateLimited) {
println("Attempt ${attempt + 1} failed: Rate limited. Retrying in ${currentDelay}ms...")
delay(currentDelay)
// Exponentially increase the delay: 1s, 2s, 4s...
currentDelay *= 2
} else if (result is ApiResponse.Error) {
throw Exception("API Error: ${result.code} - ${result.message}")
}
}
throw Exception("Max retries reached. API is still rate limiting us.")
}
Putting it all together
Now, the actual call becomes incredibly clean. The business logic doesn't care about the retry loops or the math behind the backoff; it just asks for the weather and expects a result or an exception.
suspend fun main() {
val client = SkyCastClient()
try {
val weather = retryWithBackoff {
client.fetchWeather("London")
}
println("Final Result: $weather")
} catch (e: Exception) {
println("Failed to get weather: ${e.message}")
}
}
By abstracting the retry logic into retryWithBackoff, we've created a reusable safety net. We're respecting the server's limits, handling transient errors, and keeping our main execution path readable. Just remember: whenever you see a 429, slow down. Your API provider will thank you.
📋 Practical Task
Exercise: Build a Resilient StockPriceAPI Client
You are integrating a stock market API that is even more volatile than SkyCast. Create a implementation with the following requirements:
- Create a
StockPriceClientclass with agetPrice(symbol: String)method that returns anApiResponse(you can reuse the sealed class from the lesson). - The
getPricemethod should randomly returnSuccess,RateLimited, orError. - Implement a
retryWithJitterfunction. This should be an improvement over the previous lesson: instead of a strict exponential backoff (1s, 2s, 4s), add a "jitter" (a random amount of time between 0 and 100ms) to the delay. This prevents "thundering herd" problems where many clients retry at the exact same millisecond. - Test the client by attempting to fetch the price for "KOTL" and print the attempt number and the final result to the console.
There are no comments for now.