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).

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 insideParMap. - Any
nilelement: Calling the returned step returnsErrNilFunc. - Cancellation & short-circuit: Checks
ctx.Err()before each step and stops immediately on the first non-nil error (includingErrSkip).
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
ErrSkipand canceled contexts (ctx.Err() != nil) do not increment the consecutive failure count or trip the breaker.- While open before
resetAfter, calls fail fast withErrCircuitOpenwithout invokingst. - Once
resetAfterelapses, only one concurrent call enters as the half-open probe; competing concurrent calls receiveErrCircuitOpenuntil 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.
ErrSkipbypasseshandlerdirectly.- Returning
nilorErrSkipfromhandlerconverts the failure toErrSkipso the stream drops the bad item and continues. - Returning any other error replaces the failure and halts the stream.
- Passing
nilashandlerforwards 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.