Skip to content

Instantly share code, notes, and snippets.

@anandwana001
Created October 4, 2025 03:07
Show Gist options
  • Select an option

  • Save anandwana001/5f6a99ab6f7acda1d4e37920770eeade to your computer and use it in GitHub Desktop.

Select an option

Save anandwana001/5f6a99ab6f7acda1d4e37920770eeade to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlin.system.measureTimeMillis
class RateLimitedApiClient {
private val maxConcurrentRequests = 10
private val semaphore = Semaphore(maxConcurrentRequests)
suspend fun makeApiCall(id: Int): String = semaphore.withPermit {
withContext(Dispatchers.IO) {
println("API call $id on ${Thread.currentThread().name}")
delay(1000) // Simulate API call
"Response $id"
}
}
suspend fun batchApiCalls(count: Int): List<String> = coroutineScope {
(1..count).map { id ->
async { makeApiCall(id) }
}.awaitAll()
}
}
fun main() = runBlocking {
val client = RateLimitedApiClient()
val time = measureTimeMillis {
val results = client.batchApiCalls(50)
println("Completed ${results.size} API calls")
}
println("Time taken: $time ms")
println("Limited to 10 concurrent requests despite 64 available IO threads")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment