RequestDeduplication

Ktor client plugin that deduplicates concurrent HTTP requests.

When multiple identical requests are made concurrently, only one actual request is executed, and all callers receive the same response. Once that request completes, the shared response is released and new requests will trigger fresh HTTP calls.

Memory Optimization: The response body is read once into a ByteArray and shared across all concurrent callers. This means memory usage is proportional to the response size, not the number of concurrent callers. Example: 1MB response with 10 concurrent callers = 1MB memory (not 10MB).

Cancellation Behavior:

  • If one caller cancels, other concurrent callers still receive the response

  • If the leader is cancelled, its HTTP call is aborted and surviving waiters retry as a new deduplicated group, which sends a second HTTP request

  • If all callers cancel, the in-flight entry is removed and resources are freed

Plugin Installation Order

Most plugins change the request before it reaches the Send step, where deduplication happens. Their changes are always part of the cache key, wherever they are installed. This covers DefaultRequest, Auth, and any plugin using onRequest. To stop such a header from affecting deduplication, add it to RequestDeduplicationConfig.excludeHeaders.

The exception is a token refreshed by Auth after a 401. That resend starts at the Send step, so the new token is only in the cache key when Auth is installed first. Refreshing works in either order: concurrent callers share one refresh and one resend.

Order only matters for plugins that change the request in on(Send):

  • Installed BEFORE RequestDeduplication: their changes are part of the cache key.

  • Installed AFTER RequestDeduplication: their changes come after deduplication, so they are not part of the cache key, and only run for the request that is actually sent.

Use case: Optimize scenarios where multiple components might request the same data simultaneously

Basic Installation:

val client = HttpClient {
install(RequestDeduplication)
}

With custom configuration:

val client = HttpClient {
install(RequestDeduplication) {
deduplicateMethods = setOf(Get, Head)

// Exclude tracing/telemetry headers that vary per request
excludeHeaders = setOf(
"X-Trace-Id",
"X-Request-Id",
"X-Correlation-Id",
"traceparent",
"tracestate"
)

// Optional: Add minimum deduplication window for fast responses
// Useful when error responses or cached data return very quickly
minWindow = 50 // milliseconds (default: 0)
}
}

Finding headers that vary: If deduplication isn't working as expected, a header probably differs between requests. You can temporarily log the headers to find it:

install(Logging) {
level = LogLevel.HEADERS
}