Skip to content

Retries

Juli Tera edited this page Apr 11, 2024 · 6 revisions

Retries are performed when the error is a modeled error marked with the retryable trait, a throttling error, a transient error, or a server error. Retry Strategies can customize when and how to perform a retry.

@error("client")
@retryable
@httpError(422)
structure UnprocessableEntityError {
    @httpPayload
    errors: AttributeErrors
}

Usage

When an error is modeled as retryable, the request is retried up to the amount determined in the retry strategy. Assuming that UnprocessableEntityError is modeled as retryable, the following would occur:

client = HighScoreService::Client.new(endpoint: 'http://127.0.0.1:3000')
# => #<HighScoreService::Client ... >

# Assumes service has a validation of "game" having a length of at least 2
# If validation fails, service is expected to return a status code of 422
client.create_high_score(high_score: { game: 'X', score: 123 })
# <Makes 3 total requests with 2 retries>
# raises UnprocessableEntityError (HighScoreService::Errors::UnprocessableEntityError)

Retry Strategy

A Retry Strategy can be any class that responds to the following methods:

  • acquire_initial_retry_token(token_scope)
  • refresh_retry_token(retry_token, error_info)
  • record_success(retry_token)

retry_token is a Struct that has :retry_count and :retry_delay members. error_info is a class that has methods for inspecting the error, such as retryable?, hints, and error_type.

Hearth provides two canned retry strategies: Hearth::Retry::Standard and Hearth::Retry::Adaptive. Both strategies take options such as :max_attempts and :backoff.

client = HighScoreService::Client.new(
  endpoint: 'http://127.0.0.1:3000',
  retry_strategy: Hearth::Retry::Adaptive.new(max_attempts: 2)
)
# => #<HighScoreService::Client ... >

client.list_high_scores
# <Retries up to 1 time>
# => #<Hearth::Output @data=... >