Skip to content

Steps & Resilience

Step[In, Out] wraps fallible per-item work with retry backoff, circuit breaking, dead-letter handling, and sequential step composition, independent of whether the pipeline runs serially (TryMap) or concurrently (ParMap).

Three linked processing steps showing retry loop backoff, a circuit breaker shield gate, and a dead-letter side chute for failed items

type Step[In, Out any] func(context.Context, In) (Out, error)

Because Step[In, Out] has the exact function signature expected by TryMap and ParMap, any composed step plugs directly into both stages. See the complete runnable API Enrichment & DLQ Example for these primitives working together.

Wrapping and Composing Steps

Do

Do[In, Out any](fn func(context.Context, In) (Out, error)) Step[In, Out] promotes a fallible function into a Step. Passing nil produces a Step that returns ErrNilFunc when invoked.

fetch := automi.Do(func(ctx context.Context, id string) (Profile, error) {
    return api.GetProfile(ctx, id)
})

Then — Heterogeneous Step Chaining

(st Step[In, Out]) Then[Next any](next func(context.Context, Out) (Next, error)) Step[In, Next] chains two stages whose output and input types connect (In -> Out -> Next).

Because next accepts func(context.Context, Out) (Next, error), pass either a plain Go function or another Step[Out, Next] carrying its own .Retry, .CircuitBreaker, or .OnError. Then checks ctx.Err() before each stage and short-circuits immediately on any error or ErrSkip.

pipeline := automi.Do(parseID).
    Retry(2, 20*time.Millisecond).
    Then(automi.Do(fetchProfile).CircuitBreaker(5, 15*time.Second)).
    Then(func(_ context.Context, p Profile) (Summary, error) {
        return p.ToSummary(), nil
    })

If either st or next is nil, calling the returned Step returns ErrNilFunc.

Chain — Same-Type Step Collections

Chain[T any](steps ...Step[T, T]) Step[T, T] composes a sequence of same-type steps sequentially from left to right.

normalize := automi.Chain(
    trimWhitespace,
    validateSchema,
    automi.Do(enrichGeo).Retry(3, 50*time.Millisecond),
)

Chain enforces these contracts:

  • Zero steps: Returns a context-aware identity step.
  • One step: Returns that step directly with zero wrapper overhead.
  • Two or more steps: Defensively clones the slice (slices.Clone) at construction time so mutating a caller slice never races when executed inside ParMap.
  • Any nil element: Calling the returned step returns ErrNilFunc.
  • Cancellation & short-circuit: Checks ctx.Err() before each step and stops immediately on the first non-nil error (including ErrSkip).

Running Step Collections Serially vs. Concurrently

Define a step collection once, then choose execution mode at the stream stage:

// Serial fused execution (zero extra goroutines)
out := stream.TryMap(pipeline)

// Or concurrent worker pool (runs inline if cfg.Workers == 1)
out := stream.ParMap(pipeline, automi.Workers(cfg.Workers), automi.Ordered())

Resilience Policies

Retry

(st Step[In, Out]) Retry(attempts int, initialBackoff time.Duration, opts ...RetryOption) Step[In, Out] retries failed invocations up to attempts total executions (attempts < 1 clamps to 1; negative initialBackoff clamps to 0). A single lazy time.Timer is reused across attempts and stopped cleanly if ctx cancels during backoff wait.

Retry never retries ErrSkip, ErrCircuitOpen, context.Canceled, or context.DeadlineExceeded.

Option Default Behavior
Multiplier(m float64) 2.0 Scales delay by m after each attempt (ignored if m <= 0).
MaxDelay(d time.Duration) unlimited Caps backoff duration per retry attempt (ignored if d <= 0).
Jitter(fraction float64) 0 Applies symmetric random jitter in [0, 1] around delay before clamping to MaxDelay.
RetryIf(pred func(error) bool) retry all others Retries only when pred(err) returns true.
resilientCall := automi.Do(callService).
    Retry(4, 50*time.Millisecond,
        automi.Multiplier(2),
        automi.MaxDelay(time.Second),
        automi.Jitter(0.25),
        automi.RetryIf(isTransient),
    )

CircuitBreaker

(st Step[In, Out]) CircuitBreaker(threshold int, resetAfter time.Duration) Step[In, Out] protects downstream dependencies with a thread-safe three-state breaker (threshold < 1 clamps to 1, negative resetAfter clamps to 0).

stateDiagram-v2
    [*] --> Closed
    Closed --> Open: threshold consecutive failures
    Open --> HalfOpen: resetAfter elapsed (1 probe allowed)
    Open --> Open: calls fail fast with ErrCircuitOpen
    HalfOpen --> Closed: probe succeeds
    HalfOpen --> Open: probe fails or panics
  • ErrSkip and canceled contexts (ctx.Err() != nil) do not increment the consecutive failure count or trip the breaker.
  • While open before resetAfter, calls fail fast with ErrCircuitOpen without invoking st.
  • Once resetAfter elapses, only one concurrent call enters as the half-open probe; competing concurrent calls receive ErrCircuitOpen until the probe completes. A panic during a probe resets the probe flag and re-opens the breaker.

OnError

(st Step[In, Out]) OnError(handler func(context.Context, In, error) error) Step[In, Out] intercepts non-ErrSkip failures together with the typed input value In—suited for structured dead-letter queues or error metrics.

  • ErrSkip bypasses handler directly.
  • Returning nil or ErrSkip from handler converts the failure to ErrSkip so the stream drops the bad item and continues.
  • Returning any other error replaces the failure and halts the stream.
  • Passing nil as handler forwards errors unchanged.
safeParse := automi.Do(parseRow).
    OnError(func(ctx context.Context, row []string, err error) error {
        deadLetters <- FailedRow{Row: row, Err: err}
        return automi.ErrSkip
    })

Method Order Matters

Chain .Retry(...) inside .CircuitBreaker(...) or .OnError(...) to control exact behavior: Do(fn).Retry(3, 50*time.Millisecond).CircuitBreaker(5, 30*time.Second).OnError(sendToDLQ) retries transient errors up to 3 times per item, trips the breaker only when retries are exhausted, and routes final failures to OnError.