Skip to content

Batching & Flow Control

Automi includes four flow-shaping stages to group items, absorb bursts, cap throughput, and suppress noisy updates. See the runnable Multi-Region Log Pipeline Example for BufferDrop, RateLimit, and Batch together.

Worker pool lanes converging into a timed batch collector tray releasing grouped output packets

Batch — Size or Idle-Wait Grouping

Batch[T any](s Stream[T], opts ...BatchOption) Stream[[]T] collects incoming items into []T slices. Because its output instantiates Stream[[]T], Batch is a package-level function whose return value continues chaining like any other Stream.

Option Default Effect
MaxSize(n int) 1024 Sets maximum elements per batch slice (values <= 0 keep default).
MaxWait(d time.Duration) disabled (0) Sets max wait after the first buffered item before flushing a partial batch (values <= 0 ignored).
err := automi.Batch(telemetryEvents,
    automi.MaxSize(64),
    automi.MaxWait(200*time.Millisecond),
).Into(ctx, automi.ToFunc(func(ctx context.Context, batch []Metric) error {
    return tsdb.WritePoints(ctx, batch)
}))

Size-Only vs. Timed Flushing

  • Size-only (MaxWait unset): Runs synchronously inside the pull loop with zero extra goroutines or timers, flushing partial batches when upstream ends cleanly or errors.
  • Size-or-wait (MaxWait > 0): Launches a bounded upstream pump goroutine (min(maxSize, 64)) and starts a single reused timer only when the first item enters an empty batch. Any accumulated partial batch flushes before emitting a trailing upstream error or EOF.

Buffer and BufferDrop — Bounded Queues & Backpressure

(s Stream[T]) Buffer(size int, opts ...BufferOption) Stream[T] decouples a faster upstream producer from a slower downstream consumer using a bounded queue of size items (size < 1 clamps to 1).

(s Stream[T]) BufferDrop(size int, onDrop func(T), opts ...BufferOption) Stream[T] adds an eviction callback invoked with every discarded item when shedding load.

Option Default Overflow Behavior
Block() Yes (default) Suspends upstream sends until downstream consumes an item.
DropOldest() No Overwrites the oldest buffered item with the newest arrival; calls onDrop(evicted).
DropNewest() No Discards incoming items while full; calls onDrop(incoming).
buffered := automi.FromChan(metricsCh).
    BufferDrop(256, func(ev Metric) {
        droppedMetricsTotal.Add(1)
    }, automi.DropOldest())

Dropping modes use a ring buffer and zero out consumed slots so evicted or delivered pointer values do not linger in memory.


RateLimit — Token Bucket Pacing

(s Stream[T]) RateLimit(perSec float64, opts ...RateOption) Stream[T] caps downstream emission to perSec items per second using a token bucket.

  • Burst(n int) sets bucket burst capacity (1 by default; values <= 0 keep default). Tokens start full at capacity.
  • Passing perSec <= 0 returns a stream yielding a positive-rate validation error ("automi: rate limit must be positive").
  • RateLimit executes inline with no background goroutine, reuses one wait timer, and aborts immediately when ctx cancels.
// Sustain 50 webhooks/sec while absorbing initial bursts up to 10 requests.
err := automi.FromSlice(alerts).
    RateLimit(50, automi.Burst(10)).
    Each(ctx, deliverWebhook)

Debounce — Trailing Quiet Window

(s Stream[T]) Debounce(d time.Duration) Stream[T] suppresses rapid bursts and emits an item only after d elapses with no newer upstream arrival.

  • Passing d <= 0 returns s unchanged.
  • Each arrival replaces any pending item and resets a single reused timer without blocking the upstream reader.
  • Any final pending item flushes when upstream finishes cleanly or before emitting a trailing upstream error.
// Emit reload trigger only after 150ms without another filesystem change event.
reloads := automi.FromChan(fsWatchCh).
    Debounce(150 * time.Millisecond)