awsretry

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 22, 2025 License: GPL-2.0 Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go Version License Latest Release

MadPixels

Go Reference Documentation

MadPixels AWSRetry

A robust, zero-dependency Go library for handling AWS API retries with intelligent exponential backoff.

Built specifically for AWS SDK v2 (smithy-go).

documentation

📋 Table of Contents

🎯 Why AWSRetry?

Working with AWS feels great until it doesn't. One moment your app is humming along perfectly, the next it's throwing ThrottlingException errors because someone else decided to hammer the same DynamoDB table. Sound familiar?

The Reality of AWS

AWS services are incredibly reliable, but they're not bulletproof. Here's what every AWS developer faces:

🚦 Rate Limits Everywhere
DynamoDB throttles when you hit capacity limits. S3 tells you to "SlowDown" during high traffic. Lambda caps your concurrent executions. It's not AWS being mean - it's protecting the infrastructure.

🌊 Traffic Spikes Happen
Black Friday, viral content, or just bad luck - sometimes your app gets more traffic than expected. AWS services can get overwhelmed, returning temporary errors that resolve in seconds.

🌐 Network Reality
The internet isn't perfect. Packets get lost, connections timeout, and sometimes AWS datacenters have bad days. These issues usually fix themselves quickly.

What Happens Without Proper Retries?
// This looks innocent but fails 10-15% of the time under load
result, err := dynamoClient.GetItem(ctx, input)
if err != nil {
   log.Error("Failed to get user data") // 😭 User sees 500 error
   return err
}

Result: Your users see errors, your monitoring explodes with alerts, and you spend your weekend debugging "infrastructure issues" that aren't really issues.

The AWSRetry Difference
// Same operation, but now it just works™️
result, err := awsretry.ExecuteWithRetry(ctx,
    func(ctx context.Context) (*dynamodb.GetItemOutput, error) {
        return dynamoClient.GetItem(ctx, input)
    },
    awsretry.DynamoDBErrors, // Smart: only retries throttling, not auth errors
    callbacks,               // You see exactly what's happening
)

Result: Your app gracefully handles AWS hiccups, users stay happy, and you sleep better at night.

Smart Retries, Not Dumb Retries

We don't retry everything blindly. AWSRetry knows the difference between:

  • ✅ ProvisionedThroughputExceededException → Definitely retry
  • ✅ ServiceUnavailable → AWS is having a moment, retry
  • ❌ AccessDenied → Your credentials are wrong, don't retry
  • ❌ ValidationException → Your request is malformed, don't retry

This intelligence means faster failures for real problems and automatic recovery for temporary ones.

We maintain a comprehensive list of 50+ AWS error codes that are safe to retry, organized by service and error type.

--

📦 Installation

go get github.com/Mad-Pixels/awsretry
Requirements: Go 1.22+

🚀 Quick Start

Basic Usage
import (
    "context"
    "github.com/Mad-Pixels/awsretry"
    "github.com/aws/aws-sdk-go-v2/service/dynamodb"
)

// Simple retry with defaults
result, err := awsretry.ExecuteWithRetry(ctx,
    func(ctx context.Context) (*dynamodb.GetItemOutput, error) {
        return client.GetItem(ctx, input)
    },
    awsretry.DefaultRetryConfig(),
    nil, // no callbacks
)
Custom Configuration
// Custom retry strategy
config := awsretry.NewRetryConfig(
   5,                       // max retries
   200*time.Millisecond,    // base delay
   2*time.Second,           // max delay  
   1.5,                     // multiplier
   awsretry.DynamoDBErrors, // error types
   awsretry.NoJitter,       // jitter type (NoJitter, FullJitter, EqualJitter)
)

// With logging callbacks
callbacks := awsretry.NewRetryCallbacks().
   WithOnRetry(func(attempt int, err error, delay time.Duration, errorCode string) {
       log.Printf("Retry %d: %s (delay: %v)", attempt, err, delay)
   })

result, err := awsretry.ExecuteWithRetry(ctx, operation, config, callbacks)
Jitter Types:
  • NoJitter - exact calculated delays (predictable)
  • FullJitter - random delay 0 to calculated (AWS recommended)
  • EqualJitter - half fixed + half random delay (balanced)
Service-Specific Examples
// DynamoDB optimized  
config := awsretry.NewRetryConfigSimple(5, 100*time.Millisecond, time.Second, 2.0, awsretry.DynamoDBErrors)

// S3 optimized  
config := awsretry.NewRetryConfigSimple(3, 200*time.Millisecond, 5*time.Second, 1.5, awsretry.S3Errors)

// Conservative approach
config := awsretry.NewRetryConfigSimple(3, 100*time.Millisecond, time.Second, 1.5, awsretry.ConservativeErrors)

🔧 Exponential Backoff

The library uses exponential backoff with the formula:

delay = BaseDelay × (Multiplier ^ attempt)

Capped at MaxDelay to prevent excessive waits.

Contributing

We're open to any new ideas and contributions. We also have some rules and taboos here, so please read this page and our Code of Conduct carefully.

I want to report an issue

If you've found an issue and want to report it, please check our Issues page.

Documentation

Overview

Package awsretry provides robust retry mechanisms for AWS API operations with intelligent exponential backoff and comprehensive error handling.

This package is designed specifically for AWS services using the official AWS SDK v2 (smithy-go) and offers zero external dependencies beyond the Go standard library and smithy-go.

Key Features

  • Zero external dependencies - only uses Go standard library and smithy-go
  • Flexible callback system - integrate with any logging framework
  • Comprehensive error coverage - handles all AWS retryable errors
  • Configurable retry strategies - exponential backoff with customizable parameters
  • Pre-defined error sets - optimized for DynamoDB, S3, Kinesis, and more
  • Context-aware - respects cancellation and timeouts
  • Type-safe - uses Go generics for compile-time safety

Basic Usage

import "github.com/Mad-Pixels/awsretry"

// Simple retry with default configuration
result, err := awsretry.ExecuteWithRetry(ctx,
	func(ctx context.Context) (*dynamodb.GetItemOutput, error) {
		return client.GetItem(ctx, input)
	},
	awsretry.DefaultRetryConfig(),
	nil, // no callbacks
)

Custom Configuration

// Create custom retry configuration
config := awsretry.NewRetryConfig(
	5,                           // max retries
	200*time.Millisecond,        // base delay
	2*time.Second,               // max delay
	1.5,                         // multiplier
	awsretry.DynamoDBErrors,     // error types to retry
)

// Setup callbacks for logging/monitoring
callbacks := awsretry.NewRetryCallbacks().
	WithOnRetry(func(attempt int, err error, delay time.Duration, errorCode string) {
		log.Printf("Retry %d: %s (delay: %v, code: %s)", attempt, err, delay, errorCode)
	}).
	WithOnSuccess(func(totalAttempts int) {
		log.Printf("Success after %d attempts", totalAttempts)
	}).
	WithOnFailure(func(totalAttempts int, finalErr error, reason string) {
		log.Printf("Failed after %d attempts: %s (%s)", totalAttempts, finalErr, reason)
	})

result, err := awsretry.ExecuteWithRetry(ctx, operation, config, callbacks)

Pre-defined Error Sets

The package provides several pre-configured error sets for common AWS services:

  • RateLimitErrors: Only throttling and rate limiting errors
  • ThroughputErrors: Capacity and throughput related errors
  • ServiceErrors: Service availability and server-side errors
  • ConnectionErrors: Network and timeout related errors
  • TemporaryErrors: Comprehensive set of all retryable errors (recommended default)
  • DynamoDBErrors: Optimized for DynamoDB operations
  • KinesisErrors: Optimized for Kinesis operations
  • S3Errors: Optimized for S3 operations

Error Handling

The package automatically detects and retries AWS-specific error codes using smithy-go's APIError interface. It supports case-insensitive error code matching and handles all common AWS transient errors including:

  • Throttling and rate limiting errors
  • Service unavailability errors
  • Timeout and connection errors
  • Throughput exceeded errors
  • Transaction conflicts

Exponential Backoff

The retry strategy uses exponential backoff with the formula:

delay = BaseDelay * (Multiplier ^ attempt)

The delay is capped at MaxDelay to prevent excessively long waits. The backoff strategy helps avoid overwhelming AWS services and provides better success rates during high-traffic periods.

Context Support

All operations respect Go's context for cancellation and timeouts. If the context is cancelled during a retry delay, the operation immediately returns with the context's error.

Thread Safety

All functions and types in this package are safe for concurrent use. The retry logic does not maintain any shared state between operations.

Index

Constants

This section is empty.

Variables

View Source
var (

	// Error429TooManyRequests - HTTP 429 status code indicating rate limiting.
	// Occurs when the request rate exceeds the allowed limit for the API.
	Error429TooManyRequests = "TooManyRequests"

	// ErrorThrottling - Generic throttling error from AWS services.
	// Used by various AWS services when request rate is too high.
	ErrorThrottling = "Throttling"

	// ErrorThrottlingException - Specific throttling exception.
	// More specific version of throttling error with exception suffix.
	ErrorThrottlingException = "ThrottlingException"

	// ErrorThrottledException - Alternative throttling exception format.
	// Some services use this variation of the throttling exception.
	ErrorThrottledException = "ThrottledException"

	// ErrorRequestThrottled - Request-specific throttling error.
	// Indicates that the specific request was throttled due to rate limits.
	ErrorRequestThrottled = "RequestThrottled"

	// ErrorRequestThrottledException - Alternative format for request throttling.
	// Used by some AWS services as a more descriptive throttling error.
	ErrorRequestThrottledException = "RequestThrottledException"

	// ErrorTooManyRequestsException - Exception variant of too many requests.
	// Used by services that prefer exception-style error naming.
	ErrorTooManyRequestsException = "TooManyRequestsException"

	// ErrorEC2ThrottledException - EC2-specific throttling error.
	// Occurs when EC2 API calls are rate limited.
	ErrorEC2ThrottledException = "EC2ThrottledException"

	// ErrorSlowDown - S3-specific rate limiting error.
	// S3 returns this when requests are coming in too fast.
	ErrorSlowDown = "SlowDown"

	// ErrorProvisionedThroughputExceededException - DynamoDB/Kinesis throughput exceeded.
	// Occurs when read/write capacity units are exceeded in DynamoDB or Kinesis shards.
	ErrorProvisionedThroughputExceededException = "ProvisionedThroughputExceededException"

	// ErrorRequestLimitExceeded - Generic request limit exceeded.
	// Used when service-specific request limits are hit.
	ErrorRequestLimitExceeded = "RequestLimitExceeded"

	// ErrorBandwidthLimitExceeded - Network bandwidth limit exceeded.
	// Occurs when data transfer rate exceeds allowed bandwidth.
	ErrorBandwidthLimitExceeded = "BandwidthLimitExceeded"

	// ErrorLimitExceededException - Generic limit exceeded exception.
	// Used by various services for different types of limits.
	ErrorLimitExceededException = "LimitExceededException"

	// ErrorServiceUnavailable - HTTP 503 status indicating service unavailability.
	// Occurs when AWS service is temporarily unavailable or overloaded.
	ErrorServiceUnavailable = "ServiceUnavailable"

	// ErrorInternalServerError - HTTP 500 status indicating server-side error.
	// Temporary server-side error that may succeed on retry.
	ErrorInternalServerError = "InternalServerError"

	// ErrorInternalError - Alternative internal error format.
	// Some services use this variation for internal errors.
	ErrorInternalError = "InternalError"

	// ErrorTemporaryFailure - Generic temporary failure.
	// Indicates a temporary condition that may resolve on retry.
	ErrorTemporaryFailure = "TemporaryFailure"

	// ErrorRequestTimeout - Request timeout error.
	// Occurs when request takes too long to complete.
	ErrorRequestTimeout = "RequestTimeout"

	// ErrorRequestTimeoutException - Request timeout exception format.
	// Exception variant of request timeout.
	ErrorRequestTimeoutException = "RequestTimeoutException"

	// ErrorConnectionError - Generic connection error.
	// Indicates network connectivity issues.
	ErrorConnectionError = "ConnectionError"

	// ErrorHTTPClientError - HTTP client-side error.
	// Indicates issues with HTTP client configuration or connectivity.
	ErrorHTTPClientError = "HTTPClientError"

	// ErrorTransactionInProgressException - Transaction conflict error.
	// Occurs when multiple operations conflict on the same resource.
	ErrorTransactionInProgressException = "TransactionInProgressException"

	// ErrorPriorRequestNotComplete - Previous request still processing.
	// Indicates a previous request is still being processed.
	ErrorPriorRequestNotComplete = "PriorRequestNotComplete"

	// ErrorRetryableException - Generic retryable exception.
	// Indicates that the operation should be retried.
	ErrorRetryableException = "RetryableException"

	// ErrorRequestExpired - Request signature expired.
	// Occurs when request signature is too old, temporary issue.
	ErrorRequestExpired = "RequestExpired"

	// ErrorLambdaConcurrentExecutions - Lambda concurrent execution limit exceeded.
	// Occurs when Lambda function hits concurrent execution limits.
	ErrorLambdaConcurrentExecutions = "TooManyRequestsException"

	// ErrorLambdaResourceConflict - Lambda function update conflicts.
	// Occurs when trying to update Lambda function that's being modified.
	ErrorLambdaResourceConflict = "ResourceConflictException"

	// ErrorECSClusterNotFound - ECS cluster temporary unavailability.
	// Can occur during cluster scaling or updates.
	ErrorECSClusterNotFound = "ClusterNotFoundException"

	// ErrorECSCapacityUpdate - ECS capacity provider update in progress.
	// Occurs when capacity provider is being updated.
	ErrorECSCapacityUpdate = "CapacityProviderUpdateInProgressException"

	// ErrorRDSInstanceNotReady - RDS instance not ready for connections.
	// Occurs during instance startup, backup, or maintenance.
	ErrorRDSInstanceNotReady = "DBInstanceNotReadyFault"

	// ErrorRDSClusterNotReady - RDS cluster not ready for operations.
	// Occurs during cluster operations like scaling or failover.
	ErrorRDSClusterNotReady = "DBClusterNotReadyFault"

	// ErrorRDSBackupInProgress - RDS backup operation in progress.
	// Occurs when backup is blocking other operations.
	ErrorRDSBackupInProgress = "BackupPolicyNotFoundFault"

	// ErrorRDSMaintenanceWindow - RDS maintenance window active.
	// Occurs during scheduled maintenance operations.
	ErrorRDSMaintenanceWindow = "InvalidDBInstanceStateFault"

	// ErrorAPIGatewayThrottling - API Gateway rate limiting.
	// Different from generic throttling, specific to API Gateway.
	ErrorAPIGatewayThrottling = "TooManyRequestsException"

	// ErrorClientException - Generic client exception.
	// Sometimes used for throttling by some services (e.g., ECS).
	ErrorClientException = "ClientException"
)

AWS Error Types. These constants represent common AWS error codes that can be retried.

View Source
var (
	// RateLimitErrors - Contains only rate limiting and throttling related errors.
	// Use this set when you want to retry only on rate limit violations.
	// These errors typically indicate that you're hitting API quotas or limits.
	RateLimitErrors = []string{
		Error429TooManyRequests,
		ErrorThrottling,
		ErrorThrottlingException,
		ErrorThrottledException,
		ErrorRequestThrottled,
		ErrorRequestThrottledException,
		ErrorTooManyRequestsException,
		ErrorEC2ThrottledException,
		ErrorSlowDown,
		ErrorLambdaConcurrentExecutions,
		ErrorAPIGatewayThrottling,
	}

	// ThroughputErrors - Contains throughput and capacity related errors.
	// Use this set for services like DynamoDB, Kinesis, or other capacity-limited services.
	ThroughputErrors = []string{
		ErrorProvisionedThroughputExceededException,
		ErrorRequestLimitExceeded,
		ErrorBandwidthLimitExceeded,
		ErrorLimitExceededException,
	}

	// ServiceErrors - Contains service availability and server-side errors.
	// Use this set to retry on temporary service issues.
	ServiceErrors = []string{
		ErrorServiceUnavailable,
		ErrorInternalServerError,
		ErrorInternalError,
		ErrorTemporaryFailure,
		ErrorRetryableException,
	}

	// ConnectionErrors - Contains connection and timeout related errors.
	// Use this set to retry on network connectivity issues.
	ConnectionErrors = []string{
		ErrorRequestTimeout,
		ErrorRequestTimeoutException,
		ErrorConnectionError,
		ErrorHTTPClientError,
		ErrorRequestExpired,
	}

	// TransactionErrors - Contains transaction and state conflict errors.
	// Use this set for services that support transactions or have state conflicts.
	TransactionErrors = []string{
		ErrorTransactionInProgressException,
		ErrorPriorRequestNotComplete,
		ErrorLambdaResourceConflict,
		ErrorECSCapacityUpdate,
	}

	// TemporaryErrors - Contains all temporary errors including rate limits and service issues.
	// Use this set for comprehensive retry coverage on transient failures.
	// This is the most comprehensive set, recommended for most use cases.
	TemporaryErrors = []string{

		Error429TooManyRequests,
		ErrorThrottling,
		ErrorThrottlingException,
		ErrorThrottledException,
		ErrorRequestThrottled,
		ErrorRequestThrottledException,
		ErrorTooManyRequestsException,
		ErrorEC2ThrottledException,
		ErrorSlowDown,
		ErrorLambdaConcurrentExecutions,
		ErrorAPIGatewayThrottling,

		ErrorProvisionedThroughputExceededException,
		ErrorRequestLimitExceeded,
		ErrorBandwidthLimitExceeded,
		ErrorLimitExceededException,

		ErrorServiceUnavailable,
		ErrorInternalServerError,
		ErrorInternalError,
		ErrorTemporaryFailure,
		ErrorRetryableException,

		ErrorRequestTimeout,
		ErrorRequestTimeoutException,
		ErrorConnectionError,
		ErrorHTTPClientError,
		ErrorRequestExpired,

		ErrorTransactionInProgressException,
		ErrorPriorRequestNotComplete,
		ErrorLambdaResourceConflict,
		ErrorECSCapacityUpdate,

		ErrorRDSInstanceNotReady,
		ErrorRDSClusterNotReady,
		ErrorRDSBackupInProgress,
		ErrorRDSMaintenanceWindow,
	}

	// ConservativeErrors - Contains only the most common and safe-to-retry errors.
	// Use this set when you want to be conservative about retries.
	// Focuses on clear throttling and service unavailability errors.
	ConservativeErrors = []string{
		Error429TooManyRequests,
		ErrorThrottling,
		ErrorThrottlingException,
		ErrorServiceUnavailable,
		ErrorInternalServerError,
	}

	// AggressiveErrors - Contains all possible retryable errors including client exceptions.
	// Use this set when you want maximum retry coverage, including edge cases.
	// Be careful as this includes some client-side errors that might not always be retryable.
	AggressiveErrors = append(TemporaryErrors, ErrorClientException)
)

Predefined Error Sets. These slices group related error types for common retry scenarios.

View Source
var (
	// DynamoDBErrors combines rate limiting and throughput errors.
	// Optimized for DynamoDB operations.
	DynamoDBErrors = append(RateLimitErrors, ThroughputErrors...)

	// KinesisErrors combines rate limiting and throughput errors.
	// Optimized for Kinesis operations.
	KinesisErrors = append(RateLimitErrors, ThroughputErrors...)

	// S3Errors includes S3-specific errors plus general service errors.
	// Optimized for S3 operations.
	S3Errors = append([]string{ErrorSlowDown}, ServiceErrors...)

	// LambdaErrors - Lambda-specific retryable errors.
	// Optimized for AWS Lambda function operations.
	LambdaErrors = []string{
		ErrorLambdaConcurrentExecutions,
		ErrorLambdaResourceConflict,
		ErrorThrottling,
		ErrorServiceUnavailable,
		ErrorInternalServerError,
	}

	// ECSErrors - ECS/Fargate specific retryable errors.
	// Optimized for container service operations.
	ECSErrors = []string{
		ErrorECSClusterNotFound,
		ErrorECSCapacityUpdate,
		ErrorServiceUnavailable,
		ErrorThrottling,
		ErrorClientException,
	}

	// RDSErrors - RDS-specific retryable errors.
	// Optimized for database operations.
	RDSErrors = []string{
		ErrorRDSInstanceNotReady,
		ErrorRDSClusterNotReady,
		ErrorRDSBackupInProgress,
		ErrorRDSMaintenanceWindow,
		ErrorThrottling,
		ErrorServiceUnavailable,
		ErrorInternalServerError,
	}

	// APIGatewayErrors - API Gateway specific retryable errors.
	// Optimized for API Gateway operations.
	APIGatewayErrors = []string{
		ErrorAPIGatewayThrottling,
		ErrorServiceUnavailable,
		ErrorThrottling,
		ErrorInternalServerError,
	}
)

Service-specific Error Sets These sets are optimized for specific AWS services

View Source
var (
	// DefaultRetryableErrors is an alias for TemporaryErrors.
	// This is the recommended default for most applications.
	DefaultRetryableErrors = TemporaryErrors

	// StrictRetryableErrors is an alias for ConservativeErrors.
	// Use when you want minimal, safe retry behavior.
	StrictRetryableErrors = ConservativeErrors

	// ThrottleOnlyErrors is an alias for RateLimitErrors.
	// Use when you only want to retry on rate limiting.
	ThrottleOnlyErrors = RateLimitErrors
)

Common Error Set Aliases Convenient aliases for the most commonly used error sets

Functions

func ExecuteWithRetry

func ExecuteWithRetry[T any](
	ctx context.Context,
	operation func(ctx context.Context) (T, error),
	config RetryConfig,
	callbacks *RetryCallbacks,
) (T, error)

ExecuteWithRetry executes an operation with automatic retry logic for specified error types. It uses exponential backoff strategy and respects context cancellation.

Type Parameters:

  • T: The return type of the operation function

Parameters:

  • ctx: Context for cancellation and timeouts. If canceled, retry loop stops immediately
  • operation: Function to execute that may fail and need retries. Must accept context and return (T, error)
  • config: RetryConfig specifying retry behavior (max attempts, delays, retryable errors)
  • callbacks: Optional RetryCallbacks for observing retry events. Can be nil to disable callbacks

Returns:

  • T: Result of the successful operation
  • error: Last error encountered if all attempts failed, or context cancellation error

Behavior:

  • Executes operation immediately on first attempt (no initial delay)
  • Only retries on errors matching config.RetryableErrors
  • Uses exponential backoff with optional jitter to prevent thundering herd
  • Calls callbacks for retry events, success, and failure
  • Respects context cancellation during delay periods
  • Returns immediately on non-retryable errors

Example:

callbacks := NewRetryCallbacks().WithOnRetry(func(attempt int, err error, delay time.Duration, errorCode string) {
    log.Printf("Retry %d: %s", attempt, err)
})
result, err := ExecuteWithRetry(ctx, func(ctx context.Context) (*eks.DescribeClusterOutput, error) {
    return eksClient.DescribeCluster(ctx, input)
}, DefaultRetryConfig(), callbacks)

Types

type JitterType added in v0.1.0

type JitterType int

JitterType defines the type of jitter to apply to retry delays

const (
	// NoJitter disables jitter - uses exact calculated delays
	NoJitter JitterType = iota
	// FullJitter uses random delay between 0 and calculated delay (AWS recommended)
	FullJitter
	// EqualJitter uses calculated_delay/2 + random(0, calculated_delay/2)
	EqualJitter
)

type RetryCallbacks

type RetryCallbacks struct {
	// OnRetry is called before each retry attempt (not on the initial attempt).
	// Parameters:
	//   - attempt: The attempt number (1-based, so first retry is attempt 2)
	//   - err: The error that caused the retry
	//   - delay: The delay duration before this retry attempt
	//   - errorCode: The AWS error code extracted from the error (empty if not AWS error)
	OnRetry func(attempt int, err error, delay time.Duration, errorCode string)

	// OnSuccess is called when the operation succeeds.
	// Parameters:
	//   - totalAttempts: Total number of attempts made (1 = success on first try)
	OnSuccess func(totalAttempts int)

	// OnFailure is called when all retry attempts are exhausted.
	// Parameters:
	//   - totalAttempts: Total number of attempts made
	//   - finalErr: The final error (either the last retryable error or first non-retryable error)
	//   - reason: Human-readable reason for failure ("max_retries_exceeded", "non_retryable_error", "context_cancelled")
	OnFailure func(totalAttempts int, finalErr error, reason string)
}

RetryCallbacks defines callback functions for retry events. All callbacks are optional (can be nil) and provide hooks for observing retry behavior without forcing dependencies on specific logging frameworks.

func NewRetryCallbacks

func NewRetryCallbacks() *RetryCallbacks

NewRetryCallbacks creates RetryCallbacks with commonly used logging patterns. This is a convenience constructor for typical use cases.

func (*RetryCallbacks) WithOnFailure

func (rc *RetryCallbacks) WithOnFailure(fn func(totalAttempts int, finalErr error, reason string)) *RetryCallbacks

WithOnFailure sets the OnFailure callback and returns the RetryCallbacks for chaining.

func (*RetryCallbacks) WithOnRetry

func (rc *RetryCallbacks) WithOnRetry(fn func(attempt int, err error, delay time.Duration, errorCode string)) *RetryCallbacks

WithOnRetry sets the OnRetry callback and returns the RetryCallbacks for chaining.

func (*RetryCallbacks) WithOnSuccess

func (rc *RetryCallbacks) WithOnSuccess(fn func(totalAttempts int)) *RetryCallbacks

WithOnSuccess sets the OnSuccess callback and returns the RetryCallbacks for chaining.

type RetryConfig

type RetryConfig struct {
	// BaseDelay is the initial delay duration before the first retry attempt.
	// This value is used as the base for exponential backoff calculations.
	// Example: time.Second means first retry after 1 second
	BaseDelay time.Duration

	// MaxDelay is the maximum delay duration between retry attempts.
	// Prevents exponential backoff from growing indefinitely.
	// The calculated delay will be capped at this value.
	// Example: 30*time.Second caps delays at 30 seconds maximum
	MaxDelay time.Duration

	// RetryableErrors is a slice of AWS error codes that should trigger retry attempts.
	// Only errors with codes matching these strings will be retried.
	// Case-insensitive matching is performed.
	// Example: []string{"Throttling", "TooManyRequests", "ServiceUnavailable"}
	RetryableErrors []string

	// Multiplier is the factor by which the delay increases for each retry attempt.
	// Used in exponential backoff: delay = BaseDelay * (Multiplier ^ attempt)
	// Common values: 2.0 for doubling, 1.5 for gentler increase
	// Must be > 1.0 for exponential growth, = 1.0 for constant delay
	Multiplier float64

	// MaxRetries specifies the maximum number of retry attempts after the initial failure.
	// For example, if MaxRetries = 3, the operation will be attempted up to 4 times total
	// (1 initial attempt + 3 retries). Set to 0 to disable retries.
	MaxRetries int

	// Jitter specifies the type of jitter to apply to calculated delays.
	// Jitter helps prevent thundering herd problems when many clients
	// retry simultaneously. Recommended: FullJitter for production use.
	Jitter JitterType
	// contains filtered or unexported fields
}

RetryConfig defines the configuration for retry behavior when executing operations that may encounter transient failures. It supports exponential backoff with configurable error types for retry attempts.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig initialize RetryConfig with default values.

func NewRetryConfig

func NewRetryConfig(maxRetries int, baseDelay, maxDelay time.Duration, multiplier float64, retryableErrors []string, jitter JitterType) RetryConfig

NewRetryConfig creates a custom RetryConfig with all parameters explicitly specified. This function provides full control over retry behavior for specific use cases.

Parameters:

  • maxRetries: Maximum number of retry attempts after initial failure (0 = no retries)
  • baseDelay: Initial delay before first retry (e.g., 100*time.Millisecond)
  • maxDelay: Maximum delay cap for exponential backoff (e.g., 5*time.Second)
  • multiplier: Exponential backoff multiplier (>1.0 for growth, 1.0 for constant delay)
  • retryableErrors: Slice of AWS error codes that should trigger retries
  • jitter: Type of jitter to apply (NoJitter, FullJitter, EqualJitter)

Jitter Strategies:

  • NoJitter: Uses exact calculated delays (predictable but can cause thundering herd)
  • FullJitter: Random delay between 0 and calculated delay (AWS recommended, maximum spread)
  • EqualJitter: Half fixed + half random delay (predictable but prevents synchronization)

Example:

config := NewRetryConfig(5, 200*time.Millisecond, 2*time.Second, 1.5, []string{"Throttling"}, NoJitter)
// Will retry up to 5 times with delays: 200ms, 300ms, 450ms, 675ms, 1012ms (exact values)

configWithJitter := NewRetryConfig(3, 100*time.Millisecond, time.Second, 2.0, awsretry.DynamoDBErrors, FullJitter)
// Will retry up to 3 times with jittered delays around: 100ms, 200ms, 400ms (random values)

configEqualJitter := NewRetryConfig(3, 100*time.Millisecond, time.Second, 2.0, []string{"Throttling"}, EqualJitter)
// Will retry with delays: 50ms+random(0,50ms), 75ms+random(0,75ms), 112ms+random(0,112ms)

func NewRetryConfigSimple added in v0.1.0

func NewRetryConfigSimple(maxRetries int, baseDelay, maxDelay time.Duration, multiplier float64, retryableErrors []string) RetryConfig

NewRetryConfigSimple creates a custom RetryConfig with common parameters. Uses FullJitter by default for production safety.

Parameters:

  • maxRetries: Maximum number of retry attempts after initial failure (0 = no retries)
  • baseDelay: Initial delay before first retry (e.g., 100*time.Millisecond)
  • maxDelay: Maximum delay cap for exponential backoff (e.g., 5*time.Second)
  • multiplier: Exponential backoff multiplier (>1.0 for growth, 1.0 for constant delay)
  • retryableErrors: Slice of AWS error codes that should trigger retries

Example:

config := NewRetryConfigSimple(5, 200*time.Millisecond, 2*time.Second, 1.5, []string{"Throttling"})
// Will retry up to 5 times with FullJitter enabled by default

Directories

Path Synopsis
Package mock provides mocks for testing.
Package mock provides mocks for testing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址