We’re running a Kotlin script to bulk-update user profiles via PUT /api/v2/users/{userId}. It’s hammering the API with concurrent requests using a coroutine flow. We hit the rate limit hard. The response body returns 429 Too Many Requests with a retry-after header, but our current retry logic is just sleeping for a fixed 5s. That’s inefficient and we’re still getting throttled because the retry-after value varies.
Here’s the snippet handling the retry:
val response = httpClient.put("https://api.mypurecloud.com/api/v2/users/$id") {
contentType(ContentType.Application.Json)
setBody(userJson)
}
if (response.status == HttpStatusCode.TooManyRequests) {
val retryAfter = response.headers["Retry-After"]?.toInt() ?: 5
delay(retryAfter * 1000L)
// retry logic here
}
The issue is that Retry-After can be a date string or a delta-seconds integer. Parsing it correctly in Kotlin without exploding is annoying. Also, should I be using an exponential backoff strategy on top of the retry-after value, or is following the header strictly enough? The docs are vague on the exact behavior for bulk operations.
Any code examples for a solid retry handler that respects the Retry-After header in a multi-threaded Kotlin context? We need to avoid blocking all coroutines while waiting for the rate limit to reset.