Rust SDK · BufferedRecorder

The default recorder buffers events in memory and flushes in batches on a background tokio task. record(...).await only enqueues, so it never blocks on the network:

use everscribe::recorder::RecorderOptions;
use std::time::Duration;

let rec = es.new_recorder(RecorderOptions {
    buffer_size: 2000,
    flush_interval: Duration::from_secs(2),
    ..Default::default()
});

Options

Configured with RecorderOptions { .., ..Default::default() }. Durations are std::time::Duration.

Field Default Purpose
buffer_size 1000 Capacity of the in-memory event buffer.
flush_size 100 Pending-event count that triggers an immediate flush, and the most events per send. 0 uses the default.
flush_interval 5s Max time between flushes when the size threshold isn't reached. Duration::ZERO uses the default.
flush_timeout 30s Timeout per delivery attempt against the inner recorder; each retry gets a fresh one.
overflow DropNewest Behavior when record finds the buffer full.
drain_timeout 30s Max time close() waits for pending events, plus up to 1s after it cancels the in-flight send.
initial_backoff 500ms Base wait before the first retry of a failed batch.
max_backoff 30s Cap on a single wait between retries.
max_retry_duration 5min How long one batch is retried before its events are dropped as RetriesExhausted.
on_drop None Callback invoked with the events, a DropReason and an error whenever events are discarded. See What happens when delivery fails.
request_timeout 10s Per-request HTTP timeout.
base_url production Override the ingestion endpoint (tests, staging).
auto_idempotency_key false Copy id into idempotency_key when empty.

The backoff and retry options treat Duration::ZERO as the default.

Overflow policies

OverflowPolicy::DropNewest  // drop the incoming event, log a warning (default)
OverflowPolicy::Block       // await until space frees or close() runs
OverflowPolicy::Error       // return RecordError::BufferFull

Close & flush

  • close().await drains pending events, with retries, for up to drain_timeout. It returns Err(DrainTimeout) if the drain timed out, so log what it returns. Call it once, on the path that actually runs at shutdown.
  • flush().await returns Ok(()) once the events queued at call time are delivered or reported to on_drop. Useful in tests and for graceful shutdown sequences. Wrap it in tokio::time::timeout: retries during an outage can take minutes. It never cancels a send.
  • stats() returns a BufferedStats with dropped (only BufferFull drops), dropped_by_reason, flushed, flush_errs, retries, pending and buffer_size for observability.

What happens when delivery fails

record(...).await only puts the event on an in-memory buffer, so your request path never waits on the network. A background tokio task sends batches and handles failures:

Failure What happens
Transport error, timeout, 429 or 5xx Retried with jittered exponential backoff: 500ms first wait, 30s max wait, server Retry-After honored up to that cap. After 5 minutes the batch is dropped as RetriesExhausted. Tune with initial_backoff, max_backoff and max_retry_duration.
400, 409 or 413 The batch is split in half and each half retried, so one bad event does not sink the rest. An event the server still refuses is dropped as Rejected.
Any other 4xx The whole batch is dropped as Rejected.
Buffer full Depends on the overflow policy. DropNewest (default) drops the new event as BufferFull, Block makes record wait for space, Error returns RecordError::BufferFull.
close() drain timeout The in-flight send is canceled and what is left is dropped as Shutdown.
record after close() The event is dropped as Closed, as is a Block wait that close() ends.

Set on_drop to hear about every dropped event:

use std::sync::Arc;
use everscribe::recorder::RecorderOptions;

let rec = es.new_recorder(RecorderOptions {
    on_drop: Some(Arc::new(|events, reason, err| {
        eprintln!(
            "everscribe: dropped {} events ({}): {:?}",
            events.len(),
            reason.as_str(),
            err
        );
    })),
    ..Default::default()
});
  • reason is a DropReason: BufferFull, Rejected, RetriesExhausted, Shutdown or Closed. reason.as_str() gives a lowercase name for metric labels.
  • err is the last delivery error for Rejected and RetriesExhausted. For a BufferFull drop that happens when the middleware records the request event, it is RecordError::BufferFull under Error and RecordError::Timeout (the 15s wait) under Block. Otherwise it is None.
  • The callback must not block and must not call record, flush or close directly; spawn a task if you need to. It may run concurrently. A panic is caught and logged.
  • A dropped event may have been delivered anyway, for example when the last request timed out. Resending it with its original id is safe: the server deduplicates it.
  • Delivered events are immutable. Dropped events cannot be recovered, so route on_drop to your own logs or queue.

Always close().await before the process ends. It drains the buffer, with retries, for up to drain_timeout (30s by default). At the timeout it cancels the send, waits up to 1s more, and returns Err(DrainTimeout). Dropping the recorder without close still delivers what is buffered in the background as long as the runtime keeps running. Only events in hand when the runtime shuts down are lost, and those are not reported to on_drop.

Give flush a deadline. flush() returns Ok(()) once the events queued at the call are delivered or reported to on_drop. It does not return delivery errors and never cancels a send, so wrap it in tokio::time::timeout.

Watch stats(). dropped_by_reason counts drops per reason, retries counts retries, flush_errs counts failed attempts, and dropped counts only BufferFull drops.

For the split budget, custom recorders and middleware edge cases, see Delivery details.

Delivery details

  • Splitting is limited to 32 sends per batch. Events left when that budget runs out are dropped as Rejected.
  • A value that fails to serialize never fails a batch: with_field and diff store it as "[unserializable]" when you add it. See Event shape.
  • Event ids are assigned in record, so a retry resends the same ids and the server deduplicates it.
  • BufferFull and Closed reach on_drop from inside record. The other reasons arrive from the background task or from close().
  • A custom inner recorder decides what is retried through its errors: a RecordError whose transient() is true is retried, as is any attempt flush_timeout cut off. Anything else, after any 400/409/413 split, drops the batch as Rejected. A panic in the inner recorder drops its batch as Rejected with RecordError::InnerPanic, and the background task keeps running.
  • A custom inner recorder should return promptly when its future is dropped. If it ignores cancellation or blocks its thread, close() returns after the 1s grace and reports what is still queued as Shutdown itself, and a late Shutdown report for the in-flight batch can arrive after that. On a current_thread runtime an inner recorder that blocks its thread also blocks close().
  • A flush() can return a moment before close()'s leftovers reach on_drop.
  • Calling close() again, or concurrently, waits for the first call and returns its result. flush() after close() returns at once.

Drops of the middleware's event

The middleware records the request event when the handler finishes, and has no caller to return an error to. If the buffer is full then, the event is reported to on_drop as BufferFull. Under Error the report carries RecordError::BufferFull. Under Block the middleware waits up to 15s for space, then gives up and the report carries RecordError::Timeout.

A custom Recorder that reports its own drops can call everscribe::event::is_auto_recording(&event) to tell this case apart.

Where close goes

axum::serve(...).await runs until the process is killed, so a close().await written after it is only reached if the server is shut down deliberately. Give serve a graceful-shutdown future and close the recorder once it returns.

First, keep a handle. The adapters take the recorder by value (EverscribeLayer::new(recorder, resolve) wraps it in an Arc internally and hands back no accessor), so put it behind your own Arc and give the layer a thin wrapper:

use std::sync::Arc;

use everscribe::event::Event;
use everscribe::recorder::{BufferedRecorder, RecordError, Recorder};

#[derive(Clone)]
struct SharedRecorder(Arc<BufferedRecorder>);

impl Recorder for SharedRecorder {
    async fn record(&self, e: Event) -> Result<(), RecordError> {
        self.0.record(e).await
    }
}

Then mount, serve, and drain:

let rec = Arc::new(es.new_recorder(RecorderOptions::default()));

let app = Router::new()
    .route("/login", post(login))
    .layer(EverscribeLayer::new(SharedRecorder(rec.clone()), resolve_actor));

let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
axum::serve(listener, app)
    .with_graceful_shutdown(shutdown_signal())
    .await?;

// Reached after the signal fired and in-flight requests finished, so the
// last request's events are in the buffer waiting to be drained.
if let Err(e) = rec.close().await {
    eprintln!("everscribe: drain incomplete: {e}");
}

The shutdown future is what makes the close reachable. SIGTERM is what a container runtime sends, so covering only ctrl_c leaves the deploy case dropping its buffer. Both need tokio's signal feature:

async fn shutdown_signal() {
    let ctrl_c = async {
        tokio::signal::ctrl_c().await.expect("ctrl-c handler");
    };
    let sigterm = async {
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .expect("SIGTERM handler")
            .recv()
            .await;
    };
    tokio::select! {
        _ = ctrl_c => {},
        _ = sigterm => {},
    }
}