Skip to content

feat: add retry function and @retry decorator #73

Open

Description

@tabkram

Goal

Add a retry() function and @retry() method decorator for transient failures.

const getInvoice = retry(
  async (invoiceId: string) => billingApi.getInvoice(invoiceId),
  {
    attempts: 3,
    backoff: 'exponential',
    initialDelay: 200,
    maxDelay: 2_000,
    jitter: true,
    shouldRetry: (error) => error.status >= 500
  }
);

Scope

  • Configurable maximum attempts
  • Fixed, exponential, and custom backoff
  • Optional jitter and maximum delay
  • shouldRetry(error, attempt) predicate
  • onRetry hook and AbortSignal support
  • Preserve the final error and stack
  • Unit tests and documentation

Trace integration

Model each attempt as a child node and record delay, failure reason, and final outcome.

Acceptance criteria

  • Sync and async functions are supported
  • Non-retryable errors stop immediately
  • Cancellation stops pending delays and rejects predictably
  • Public API is exported from the package entry point

Activity

  1. tabkram commented on Aug 12, 2026

    @tabkram
    OwnerAuthor

    Proposed TypeScript configuration

    export interface RetryOptions<Result = unknown> {
      /** Total number of executions, including the first one. Defaults to 3. */
      attempts?: number;
      /** Delay strategy between attempts. Defaults to exponential backoff. */
      backoff?: RetryBackoff;
      /** Cap for an exponential or custom backoff, in milliseconds. */
      maxDelay?: number;
      /** Randomise delays to avoid retry storms. Defaults to false. */
      jitter?: boolean;
      /** Return true when the error or result should be retried. */
      shouldRetry?: (context: RetryContext<Result>) => boolean | Promise<boolean>;
      /** Runs before the delay preceding a new attempt. */
      onRetry?: (context: RetryContext<Result>) => void | Promise<void>;
    }
    
    export type RetryBackoff =
      | number
      | 'fixed'
      | 'exponential'
      | ((context: RetryContext) => number);
    
    export interface RetryContext<Result = unknown> {
      attempt: number;
      error?: unknown;
      result?: Result;
      delay: number;
    }

    Cancellation should be supplied per call through an AbortSignal, so one caller can cancel without changing a shared retry policy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions