Skip to content

Quickstart

This tutorial builds a complete Automi pipeline that parses CSV input with retries, a circuit breaker, dead-letter handling, bounded concurrent workers, rate limiting, and size-or-time batching.

Build the Pipeline

Create a main.go file with the following program:

package main

import (
    "context"
    "fmt"
    "os"
    "strconv"
    "strings"
    "time"

    "github.com/vladimirvivien/automi"
)

type Record struct {
    ID    string
    Value int
}

func main() {
    csvInput := "id,val\n1,10\n2,bad\n3,30\n4,5\n5,25\n"

    // Wrap row parsing with exponential retry backoff, a circuit breaker,
    // and a typed error handler that drops bad rows without halting.
    parseRow := automi.Do(func(_ context.Context, row []string) (Record, error) {
        v, err := strconv.Atoi(row[1])
        if err != nil {
            return Record{}, err
        }
        return Record{ID: row[0], Value: v}, nil
    }).
        Retry(3, 25*time.Millisecond, automi.Jitter(0.2)).
        CircuitBreaker(5, 30*time.Second).
        OnError(func(_ context.Context, row []string, err error) error {
            fmt.Fprintf(os.Stderr, "skipped row %v: %v\n", row, err)
            return nil
        })

    // Chain two same-type validation and scaling steps per record.
    validateAndScale := automi.Chain(
        automi.Do(func(_ context.Context, r Record) (Record, error) {
            if r.Value < 10 {
                return Record{}, automi.ErrSkip
            }
            return r, nil
        }),
        automi.Do(func(_ context.Context, r Record) (Record, error) {
            r.Value *= 2
            return r, nil
        }),
    )

    step := parseRow.Then(validateAndScale)
    ctx := context.Background()

    // Stream CSV rows, execute the step chain across 4 ordered workers,
    // and pace downstream emission to at most 100 items/sec.
    records := automi.FromCSV(strings.NewReader(csvInput), automi.SkipHeader()).
        ParMap(step, automi.Workers(4), automi.Ordered()).
        RateLimit(100, automi.Burst(10))

    // Flush whenever 2 records collect or 200ms elapse idle.
    err := automi.Batch(records, automi.MaxSize(2), automi.MaxWait(200*time.Millisecond)).
        Into(ctx, automi.ToFunc(func(_ context.Context, batch []Record) error {
            fmt.Printf("flushed batch: %+v\n", batch)
            return nil
        }))
    if err != nil {
        fmt.Fprintf(os.Stderr, "stream error: %v\n", err)
        os.Exit(1)
    }
}

Run the program:

go run .

You see output similar to:

skipped row [2 bad]: strconv.Atoi: parsing "bad": invalid syntax
flushed batch: [{ID:1 Value:20} {ID:3 Value:60}]
flushed batch: [{ID:5 Value:50}]

How the Stages Work Together

  1. FromCSV(..., SkipHeader()) discards the id,val header and emits each row lazily.
  2. parseRow retries transient errors up to 3 attempts, protects downstream calls with CircuitBreaker, and sends failed rows ([2 bad]) to OnError, which returns nil to convert the failure into ErrSkip.
  3. validateAndScale chains filtering (r.Value < 10 returns ErrSkip) with a transform (r.Value *= 2), then parseRow.Then(validateAndScale) joins them into a single Step[[]string, Record].
  4. ParMap(..., Workers(4), Ordered()) runs that composite step concurrently across four workers while keeping [1, 3, 5] in original input order.
  5. Batch(..., MaxSize(2), MaxWait(200ms)) flushes [1, 3] as a full pair, then flushes the final [5] partial batch when the CSV reader reaches EOF.

Concurrent Side-Effect Variant with ParEach

When your pipeline finishes with a fallible side effect (such as publishing messages or writing database rows) rather than producing downstream items, terminate directly with ParEach:

err := records.ParEach(ctx, 4, func(ctx context.Context, r Record) error {
    fmt.Printf("published: %+v\n", r)
    return nil
})

ParEach runs up to 4 concurrent workers, ignores ErrSkip, cancels sibling workers on the first non-skip error, and blocks until teardown completes.

Next: inspect how Automi executes lazy fusion versus async boundaries in the Execution Model.