Ktor 3.0.2 Help

Retrying failed requests

By default, the Ktor client doesn't retry requests that failed due to network or server errors. You can use the HttpRequestRetry plugin to configure the retry policy for failed requests in various ways: specify the number of retries, configure conditions for retrying a request, or modify a request before retrying.

Add dependencies

HttpRequestRetry only requires the ktor-client-core artifact and doesn't need any specific dependencies.

Install HttpRequestRetry

To install HttpRequestRetry, pass it to the install function inside a client configuration block:

import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.* //... val client = HttpClient(CIO) { install(HttpRequestRetry) }

Configure HttpRequestRetry

Basic retry configuration

A runnable example below shows how to configure the basic retry policy:

val client = HttpClient(CIO) { install(HttpRequestRetry) { retryOnServerErrors(maxRetries = 5) exponentialDelay() } }
  • The retryOnServerErrors function enables retrying a request if a 5xx response is received from a server and specifies the number of retries.

  • exponentialDelay specifies an exponential delay between retries, which is calculated using the Exponential backoff algorithm.

You can learn more about supported configuration options from HttpRequestRetryConfig.

Configure retry conditions

There are also configuration settings that allow you to configure conditions for retrying a request or specify delay logic:

install(HttpRequestRetry) { maxRetries = 5 retryIf { request, response -> !response.status.isSuccess() } retryOnExceptionIf { request, cause -> cause is NetworkError } delayMillis { retry -> retry * 3000L } // retries in 3, 6, 9, etc. seconds }

Modify a request before retrying

If you need to modify a request before retrying, use modifyRequest:

install(HttpRequestRetry) { // Retry conditions modifyRequest { request -> request.headers.append("x-retry-count", retryCount.toString()) } }
Last modified: 05 December 2024