Rust

llingr-demux for Rust

The llingr-kafka crate provides everything needed to compile the llingr-demux engine into a Rust application or library. Rust primitives connect to the engine through Foreign Function Interface (FFI) bindings.

Host code is essentially just Rust traits to process messages and handle dead-letters. Concurrency is provided by the engine, so engineers can focus on sequential, imperative logic without needing an async runtime such as tokio.

The engine itself is implemented in Go, so the first sections on this page cover how it is built into a Rust program: linked statically into a single binary, or deployed as a standalone artifact beside an application binary and loaded at startup.

  • Same TLA+ verified engine
  • Same per-key ordering with cross-key concurrency
  • Same safe and orderly commits ensuring no message loss
  • Same orderly rebalance coordination avoiding duplicates
  • Redpanda and Kafka compatible (same wire protocol)
  • Typed, fail-fast configuration: no silent no-ops
  • Versioned ABI: a mismatched engine refuses cleanly at startup

Get Started

llingr-kafka is an ordinary crates.io dependency requiring Rust 1.78 or later. The API reference is on docs.rs.

# Cargo.toml [dependencies] llingr-kafka = "0.10"

A minimal consumer is two traits and broker client configuration: a process handler and a dead-letter handler. The same example, with a local Redpanda broker to run it against, is the crate README's quick start.

use llingr_kafka::{Builder, Options, AutoOffsetReset, Message, Traits, ProcessHandler, DeadLetterHandler}; struct Orders; impl ProcessHandler for Orders { fn process(&self, msg: &Message) -> Result<Traits, Box<dyn std::error::Error>> { // Called once per message; in offset order per key, concurrently across keys. // Message bytes are borrowed for this call only: copy out anything you keep. log::info!("key={} partition={} offset={} value={}", msg.key_str().unwrap_or(""), msg.partition(), msg.offset(), msg.value_str().unwrap_or("<binary>")); Ok(Traits::none()) } } // Required: a failed message must land somewhere before its offset commits. struct DeadLetters; impl DeadLetterHandler for DeadLetters { fn handle(&self, msg: &Message, error: &str) -> Result<(), Box<dyn std::error::Error>> { log::error!("dead-letter key={} reason={}", msg.key_str().unwrap_or(""), error); Ok(()) } } fn main() -> Result<(), Box<dyn std::error::Error>> { env_logger::init(); // engine logs arrive via the `log` facade, target `llingr` let engine = Builder::new("orders", Orders, DeadLetters) .brokers("localhost:9092") .consumer_group("quickstart") .options(Options::new().auto_offset_reset(AutoOffsetReset::Earliest)) .build()?; engine.run()?; // blocks; Ctrl-C to exit (graceful shutdown: see Lifecycle & operations) Ok(()) }

Build & deploy

By default cargo build compiles the bundled Go engine and (typically) statically links it into an application binary. The build host needs Go 1.25+ and a C compiler (e.g. build-essential on Ubuntu, Xcode Command Line Tools on macOS).

If a build host lacks Go or C, Docker is recommended for a self-contained build environment, and the crate ships a Dockerfile that installs both.

There are two ways to package llingr-kafka:

  • Single binary (the default): the engine is statically linked into an application, which deploys as a single binary artifact.
  • Side-binary: the engine is built once, typically cached in an artifact repository, and deployed alongside an application.

See docs/building-packaging.md for more details.

OS
Packaging
# One-time toolchain: Rust, a C compiler, and Go 1.25+. sudo apt-get install -y build-essential curl -fsSL -o go.tgz https://dl.google.com/go/go1.25.12.linux-amd64.tar.gz sudo tar -C /usr/local -xzf go.tgz && export PATH=$PATH:/usr/local/go/bin # cargo build compiles the bundled Go engine and statically links it # into the binary: one self-contained executable. cargo build --release # Without Go on the machine: build the engine once in the provided # container and point cargo at it, # make engine && LLINGR_LIB_DIR=dist/<target-triple> cargo build --release # or build the whole application inside the builder image # (docker/Dockerfile ships in the repository).
# Build the engine once as a shared library, from the crate repository. # Needs Go 1.25+ and a C compiler, or Docker (make resolves the route). git clone https://github.com/llingr/llingr-rs-kafka make -C llingr-rs-kafka engine LINK=shared # -> dist/<target-triple>/libllingr.so # Point the application build at it. The build links the engine # dynamically and emits RPATH ($ORIGIN plus the library dir), so dev # binaries under target/ run in place with no copying. export LLINGR_LINK=shared export LLINGR_LIB_DIR=/path/to/llingr-rs-kafka/dist/<target-triple> cargo build --release
# One-time toolchain: the Command Line Tools provide the C compiler # (the full Xcode app is not required), plus Go 1.25+. xcode-select --install curl -fsSL -o go.tgz https://dl.google.com/go/go1.25.12.darwin-arm64.tar.gz sudo tar -C /usr/local -xzf go.tgz && export PATH=$PATH:/usr/local/go/bin # cargo build compiles the engine in: one binary. cargo build --release # macOS is the development platform; production is Linux (glibc). # Linux binaries build on a Linux runner or in the provided builder # image (docker/Dockerfile).
# Build the engine once as a shared library, from the crate repository. # The dylib is stamped with the @rpath install name at link time and # carries the ad-hoc code signature Apple Silicon requires. git clone https://github.com/llingr/llingr-rs-kafka make -C llingr-rs-kafka engine LINK=shared # -> dist/<target-triple>/libllingr.dylib # Point the application build at it: export LLINGR_LINK=shared export LLINGR_LIB_DIR=/path/to/llingr-rs-kafka/dist/<target-triple> cargo build --release # For containers: MODE=docker builds a LINUX libllingr.so instead. make -C llingr-rs-kafka engine LINK=shared MODE=docker

Alpine is not supported. The embedded Go runtime does not initialise on musl, for upstream Go reasons no build flag or musl tuning fixes, so the build fails loudly on a *-musl target rather than producing a binary that crashes at start.

The default single-binary mode ships in a scratch image of roughly 16 MB, smaller than an Alpine-based image. Where a base image is needed, any glibc one works: debian:stable-slim or another Debian/Ubuntu-family image, and the Linux (glibc) steps above apply unchanged.

# The binary is self-contained: deploy the one file. For a scratch # image, build fully static, scoped to the target triple (a global # RUSTFLAGS would fail on the crate's proc-macro dependencies): export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS="-C target-feature=+crt-static" cargo build --release --target x86_64-unknown-linux-gnu # Dockerfile: kernel + binary, roughly 16 MB, nothing else. # FROM scratch # COPY order-processor /order-processor # ENTRYPOINT ["/order-processor"] # Any glibc image (debian:stable-slim) also works without the static # build. Alpine/musl and Windows are not supported.
# Deploy the library NEXT TO the binary. RPATH ($ORIGIN) resolves it: # no ldconfig, no LD_LIBRARY_PATH, no system install. # # order-processor/ # |- order-processor # the application binary # |- libllingr.so # the engine, beside it # # A dynamically linked binary needs a loader, so the image is a glibc # one (debian:stable-slim), not scratch. Engine updates replace the # file; the versioned ABI check refuses a mismatched engine at startup.
# The binary is self-contained and runs in place: cargo run --release # macOS is the development platform. Container deployment is the # Linux (glibc) path: build the Linux binary on a Linux runner or in # the provided builder image (docker/Dockerfile).
# Deploy the dylib NEXT TO the binary. @loader_path RPATH resolves it: # no install_name_tool step and no system install. # # order-processor/ # |- order-processor # the application binary # |- libllingr.dylib # the engine, beside it # # Shipping to Linux containers from a Mac: build the Linux .so with # `make engine LINK=shared MODE=docker` and deploy it inside a glibc # (Debian/Ubuntu) image.

No deployment on Alpine. The embedded Go runtime does not initialise on musl (see step 1). Deployment uses a scratch image (single-binary mode) or a Debian/Ubuntu-family image, following the Linux (glibc) steps.

Handlers & messages

Three traits, two required: process and dead-letter, mirroring the Go engine's demux.NewBuilder(topic, processMessage, writeDeadLetter), plus an optional shutdown callback. Each is a plain Rust trait with a single method, bounded Send + Sync + 'static because the engine invokes handlers concurrently from its per-key workers through &self. What each returns is a contract the engine acts on. Metrics and logs are not traits: Prometheus output is one builder call (see Observability), and engine logs flow into the log facade.

TraitRequiredInvokedContract
ProcessHandleryesPer message, on the worker that owns the message's keyOk(Traits) marks the message eligible to commit and attaches any application trait bits; Err routes it to the dead-letter handler with the error text as the reason
DeadLetterHandleryesWhen process returns Err or panicsRequired so a failed message always has somewhere to go: logging the message and reason is the bare minimum, a real DLQ (topic, table, object store) is recommended. Ok(()) commits the offset and the pipeline continues past the poison message; Err signals an infrastructure failure: emergency shutdown, no commit, redelivery on restart
ShutdownHandlernoOnce, when the consumer exitsreason is "graceful shutdown" or the engine's failure description (e.g. a circuit-breaker trip)

Messages are borrowed

Message borrows its key and value from the engine for exactly the duration of the callback: zero copies on the hot path. The buffers are recycled after the callback returns, so anything retained past the callback must be copied out (to_vec(), to_string()). Rust's lifetimes enforce this for safe code; the constraint matters only where unsafe is used to smuggle a slice out.

AccessorTypeNotes
key_str()Option<&str>The key as UTF-8, safe by construction: the raw key when it is valid UTF-8, base64 when it is binary, the partition number for a keyless record; always Some on delivered records
key()Option<&[u8]>The raw key bytes, or None for a keyless record
value()Option<&[u8]>The payload, borrowed zero-copy; None is a null value (a tombstone), distinct from Some(b""). Alias payload()
value_str()Option<&str>The value as UTF-8, or None when it is null or not valid UTF-8
topic()&strThe record's topic
partition()i32The record's partition
offset()i64The record's offset
timestamp()TimestampNotAvailable, CreateTime or LogAppendTime, with millis() giving milliseconds since the epoch regardless of kind
headers()HeadersAn ordered, borrowed view of the record's headers: keys may repeat, wire order is preserved, find(key) is first-wins, and a null-valued header is value: None

Concurrency comes from the engine

Write handlers as synchronous, blocking code that returns after the message is safe to commit. Blocking is the normal case, not a problem to engineer around: each key has its own worker, so a slow handler holds up only its own key. To process more in parallel, raise concurrent_keys (default 250, max 5,000) rather than spawning threads or tasks.

Do not spawn work that acts on the message and outlives the callback. The engine treats a returned callback as a completed message: late work breaks the at-least-once contract and races the recycled buffers.

Calling async code from a handler works the usual way round: keep a runtime handle from outside the engine and block_on inside the callback. Engine workers are not tokio workers, so blocking them is fine; what you must not do is treat them as if they were (a thread_local! in a handler is per engine thread, not per key).

Panics in handlers are contained at the FFI boundary and never unwind into the engine: a panicking process dead-letters its message with the reason panic in process callback, and the consumer keeps running. This relies on the default panic = "unwind"; under panic = "abort" any handler panic aborts the process.

Configuration

The Kafka client is franz-go, the engine's native client: pure Go, no C broker library, and the client Redpanda builds its own tooling on (rpk, Redpanda Console) and recommends for Go. It speaks the Kafka wire protocol, so the same build runs against Apache Kafka, Redpanda and Amazon MSK.

Configuration is one typed Options builder, attached with the engine builder's options(...) hook. Every typed setter emits a standard Kafka config key, translated to the equivalent franz-go (kgo) option, so configuration written for another Kafka client ports across. Nothing is silently ignored: an unknown key fails at build() with the full supported-key list, and options that would corrupt the engine's guarantees are excluded and fail with the reason.

use llingr_kafka::{AutoOffsetReset, BalanceStrategy, Options}; use std::time::Duration; // The typed setters cover connection and group tuning, fetch sizing, // retries and timeouts, and the TLS/SASL security options (see Security). // Each emits a standard Kafka config key, translated to the native // franz-go (kgo) option; an unknown or invalid key fails at build(). let sasl_password = std::env::var("KAFKA_SASL_PASSWORD")?; let opts = Options::new() .auto_offset_reset(AutoOffsetReset::Earliest) // never miss a message .client_id("order-processor-1") .session_timeout(Duration::from_secs(30)) .heartbeat_interval(Duration::from_secs(3)) .fetch_max_wait(Duration::from_millis(500)) .partition_assignment_strategy(&[BalanceStrategy::CooperativeSticky]) // TLS + SASL, typed: translated to native franz-go security // (kgo.DialTLSConfig / kgo.SASL); security.protocol is computed .tls_ca_location("/etc/ssl/certs/cluster-ca.pem") .sasl_scram_sha256("svc-orders", &sasl_password); // Attach with .options(opts) on the engine builder. Auto-commit is // owned by the engine: offsets commit only when contiguous, so // out-of-order completion can never lose a message.
use llingr_kafka::DemuxConfig; use std::time::Duration; // All thirteen engine settings live on DemuxConfig (Go's WithDemuxConfig), // passed with .demux(...) on the engine builder. Entirely OPTIONAL: unset // values take engine defaults, which suit most workloads; every value is // range-validated at build() and reported as a clean error, not a crash. let demux_config = DemuxConfig::new() // concurrency: how many per-key workers may run at once (default 250) .concurrent_keys(1000) .per_key_buffer_len(32) // per-worker channel buffer (default 16) .worker_shards_count(32) // worker registry shards, power of two (default 16) // broker interaction .poll_timeout(Duration::from_millis(150)) .auto_commit_interval(Duration::from_secs(2)) // lifecycle: how long in-flight work may drain on rebalance/shutdown .drain_timeout(Duration::from_secs(30)) .await_assignments_timeout(Duration::from_secs(60)) // safety valve: dispatch wait before the circuit breaker fires .acquire_worker_timeout_circuit_breaker(Duration::from_secs(90));

How options behave

Option keys are the standard Kafka client names, so configuration written for another Kafka client ports across. Three rules hold throughout:

  • Reserved keys. bootstrap.servers and group.id come from brokers() and consumer_group(), and cannot be overridden through options(...)
  • Duplicates: last write wins, in call order across the typed setters: the layered-config idiom (base configuration, then overrides)
  • Invalid configuration fails loudly. An unsupported or inconsistent option fails at build() with the reason, never a silent no-op

Typed option set

Options translates a curated option set into typed franz-go options, discoverable at compile time. Keys that would corrupt the engine's guarantees are excluded and fail at build() with the reason.

Option keyOptions methodfranz-go option
auto.offset.resetauto_offset_reset(AutoOffsetReset)kgo.ConsumeResetOffset
client.idclient_id(&str)kgo.ClientID
group.instance.idgroup_instance_id(&str)kgo.InstanceID (static membership: pod restarts within the session timeout rejoin without a rebalance)
session.timeout.mssession_timeout(Duration)kgo.SessionTimeout
heartbeat.interval.msheartbeat_interval(Duration)kgo.HeartbeatInterval
rebalance.timeout.msrebalance_timeout(Duration)kgo.RebalanceTimeout, validated to exceed the engine drain timeout (see below)
partition.assignment.strategypartition_assignment_strategy(&[BalanceStrategy])kgo.Balancers: a preference-ordered list of cooperative-sticky, sticky, roundrobin, range (default cooperative-sticky; see below)
fetch.min.bytesfetch_min_bytes(u32)kgo.FetchMinBytes
fetch.max.bytesfetch_max_bytes(u32)kgo.FetchMaxBytes
max.partition.fetch.bytesmax_partition_fetch_bytes(u32)kgo.FetchMaxPartitionBytes
fetch.max.wait.msfetch_max_wait(Duration)kgo.FetchMaxWait
client.rackrack(&str)kgo.Rack (rack-aware fetch-from-follower)
metadata.max.age.msmetadata_max_age(Duration)kgo.MetadataMaxAge (lower it for faster reaction to leadership moves during rolling broker restarts)
socket.connection.setup.timeout.msdial_timeout(Duration)kgo.DialTimeout: TCP and TLS establishment (client default 10s)
connections.max.idle.msconnection_idle_timeout(Duration)kgo.ConnIdleTimeout (client default 30s)
allow.auto.create.topicsallow_auto_topic_creation()kgo.AllowAutoTopicCreation (off by default; the broker must also permit it)
check.crcsdisable_fetch_crc_validation()kgo.DisableFetchCRCValidation (validation is on by default)
enable.metrics.pushdisable_client_metrics_push()kgo.DisableClientMetrics (KIP-714; on by default where the broker supports it)
security.protocol,
ssl.*, sasl.*, aws.*, gcp.*
typed tls_* / sasl_* setterskgo.DialTLSConfig / kgo.SASL, assembled and validated as one unit; see Security

franz-go client options with no standard Kafka key name are set through the same typed builder: client_log_level(ClientLogLevel) for the client's own log verbosity, request_retries(u32) and retry_timeout(Duration) for request retry behaviour, max_concurrent_fetches(u32) for fetch concurrency, and the poll-error trio poll_error_bail_after, poll_error_log_interval and poll_error_backoff governing the sustained-poll-error bail (default: an emergency shutdown after ten minutes of continuous poll failure).

Two opinionated guard rails. Fetch isolation defaults to read_committed and read_uncommitted is rejected: uncommitted reads can deliver records a transaction later aborts. And rebalance.timeout.ms must exceed the engine's drain timeout, checked at startup, so a rebalance never evicts a member that is still draining in-flight work. The defaults (60s rebalance, 20s drain) always satisfy the check.

The consumer-group assignment strategy defaults to cooperative-sticky: a rebalance revokes only the partitions that actually move. partition_assignment_strategy overrides it with a preference-ordered list of BalanceStrategy values; the group coordinator selects the first protocol that every member supports, so a fallback list (cooperative-sticky, sticky, roundrobin, range) lets the consumer join a group whose other members still run legacy eager protocols mid-migration. The delivery guarantees are unchanged either way: the engine drains in-flight work and commits before any handoff; eager protocols just make rebalances more disruptive.

Security

The tls_* and sasl_* setters compute security.protocol: any tls_* setter enables TLS, any sasl_* setter enables SASL, and the emitted protocol is the combination (ssl, sasl_plaintext, or sasl_ssl). The security keys are validated together as one unit at build(): a half-configured or contradictory setup fails with a specific message rather than connecting in a weaker mode than intended. TLS negotiates a minimum of TLS 1.2.

use llingr_kafka::Options; // mTLS with a private CA, typed: security.protocol=ssl is computed. let mtls = Options::new() .tls_ca_location("/etc/ssl/certs/cluster-ca.pem") .tls_client_certificate("/etc/ssl/client.pem", "/etc/ssl/client.key"); // Amazon MSK with IAM: sasl_aws_msk_iam() enables TLS itself (MSK IAM // is TLS-only) and reads credentials from the standard AWS chain. let msk = Options::new() .sasl_aws_msk_iam() .aws_region("eu-west-2"); // OAUTHBEARER, OIDC client-credentials against the IdP token endpoint: let secret = std::env::var("OIDC_CLIENT_SECRET")?; let oidc = Options::new() .tls() .sasl_oauthbearer_oidc("https://idp.example.com/oauth2/token", "svc-orders", &secret);
MechanismConfiguration
TLS (server authentication)tls() for public-CA brokers (system trust roots); tls_ca_location / tls_ca_pem for a private CA
mTLS (client certificates)tls_client_certificate or tls_client_certificate_pem; the client key must be an unencrypted PEM
SASL PLAINsasl_plain(user, password); over TLS this is the Confluent Cloud API-key configuration
SASL SCRAM-SHA-256 / SCRAM-SHA-512sasl_scram_sha256 / sasl_scram_sha512
AWS_MSK_IAM (Amazon MSK)sasl_aws_msk_iam() plus aws_region, aws_profile, aws_assume_role; TLS is enforced
OAUTHBEARER (OIDC client-credentials)sasl_oauthbearer_oidc(endpoint, client_id, secret) plus oauthbearer_scope and oauthbearer_extensions
GCP IAM (Google Managed Service for Apache Kafka)sasl_gcp_iam() plus gcp_principal and gcp_credentials_file; TLS is enforced
Kerberos / GSSAPINot supported
Custom token callbacksNot supported
Encrypted client keys (ssl.key.password)Not supported: a configured value fails at startup with the remedy (decrypt the key before configuring it)
  • Certificates and CAs accept file paths (tls_ca_location, tls_client_certificate) or inline PEM strings (tls_ca_pem, tls_client_certificate_pem)
  • Development toggles are explicit: disable_hostname_verification() keeps chain verification (brokers reached by IP or tunnels); disable_certificate_verification() disables all verification and belongs nowhere near production
  • Secrets come from the environment or mounted files; the Options builder implements Debug with credential values redacted (passwords, secrets and the inline client private key ssl.key.pem), so logging a configuration cannot leak credentials
  • Each mechanism has a runnable example at the crate root: cargo run --example auth_mtls, auth_scram_sha256, auth_sasl_plain, auth_aws_msk_iam, auth_oauthbearer_oidc, auth_gcp_iam
  • Every inconsistency is a startup error with the reason: a SASL mechanism without credentials, conflicting typed and string keys, or an option the engine cannot honour

Engine configuration

The engine ships with production-ready defaults. Thirteen validated settings live on DemuxConfig (mirroring Go's config.DemuxConfig, passed with the builder's demux(...) hook); the whole object is optional, anything left unset takes the engine default, and every value is range-checked at build(), reported as a clean error rather than a crash. Durations are millisecond-granular; a sub-millisecond value rounds up, never silently to zero.

Defaults cover the engine; the surrounding Kafka and Kubernetes configuration may need aligning. The engine has no opinion on Kubernetes timing, autoscaling, or the Kafka client's blocking timeouts, and misalignments cause unnecessary duplicates and re-processing.
The timeout checker shows whether the Kubernetes and Kafka settings line up.

Concurrency & sharding

The primary controls for throughput and resource consumption: how the engine distributes work across its per-key workers.

concurrent_keys

Default: 250 · Min: 1 · Max: 5,000

The primary performance tuning parameter: the maximum number of distinct partition keys processed simultaneously on one consumer instance. Each key gets its own worker, so this directly bounds both throughput and resource consumption, and because handlers block a worker for their duration, it also bounds how many OS threads handler work can occupy at once.

Align it with downstream capacity. If the database pool has 200 connections and each message performs one write, setting it above 200 just moves the queue to the database. Increase it for lightweight processing (in-memory work, fast key-value stores); decrease it for resource-intensive operations. In a consumer group of 50 instances at 500 keys each, effective group concurrency is 25,000 keys.

DemuxConfig::concurrent_keys(n: u32)

per_key_buffer_len

Default: 16 · Min: 1 · Max: 64

Each per-key worker owns a buffered channel; this sets its capacity. Messages for the same key queue here, in order, while the worker processes the current one.

Larger buffers absorb bursts more effectively but lengthen drains during rebalances, because every buffered message must complete before a partition can be handed over. The default of 16 suits most workloads; consider 32-64 only for highly uneven per-key arrival patterns.

DemuxConfig::per_key_buffer_len(n: u32)

worker_shards_count

Default: 16 · Valid: 2, 4, 8, 16, 32, 64 (power of 2)

The demultiplexer distributes keys across independent shards, each with its own mutex, which keeps lock contention low. Keys route to shards by FNV-1a hash with bitwise masking, hence the power-of-2 requirement.

The default of 16 scales near-linearly on modern multi-core machines while keeping the coordinator footprint under 1.5KB. Change it only after profiling: more shards reduce mutex contention but add cache pressure.

DemuxConfig::worker_shards_count(n: u32)

Timing & polling

How often the engine talks to the broker, and how it batches offset commits. These mainly shape latency characteristics and broker load.

poll_timeout

Default: 100ms · Min: 20ms · Max: 2s

How long the polling loop waits when an assigned partition has no messages. This affects CPU use during idle periods and how quickly the engine notices rebalance signals.

Shorter (20-50ms) means faster rebalance detection and lower average latency at slightly higher idle CPU; longer (500ms-2s) suits batch workloads where sub-second rebalance response is not a priority.

DemuxConfig::poll_timeout(d: Duration)

auto_commit_interval

Default: 5s · Min: 250ms · Max: 15s

The cadence of asynchronous offset commits. The committer batches all completed offsets in each interval into a single broker round-trip.

Shorter intervals (250ms-1s) shrink the duplicate window after a crash, since everything processed after the last commit is redelivered; longer intervals reduce broker load but widen that window. Five seconds balances the two for most production deployments.

DemuxConfig::auto_commit_interval(d: Duration)

query_timeout

Default: 5s · Min: 1s · Max: 10s

Maximum time for broker metadata queries: partition assignments, group coordination and similar control-plane operations. The conservative default accounts for brokers under sustained load.

Reduce to 1-2s for well-resourced, co-located clusters; increase to 8-10s for managed services with cross-region metadata replication.

DemuxConfig::query_timeout(d: Duration)

Lifecycle & drains

Shutdown and rebalance coordination: getting these right gives clean handoffs during rolling deployments, scaling events and failure recovery.

drain_timeout

Default: 20s · Min: 2s · Max: 55s

Maximum time for in-flight messages to complete during a rebalance or graceful shutdown. On a rebalance signal the engine stops accepting new messages and waits for active workers to finish their current ones.

The default of 20 seconds aligns with the standard Kubernetes 30-second termination grace period, leaving 10 seconds for the final commit cycle. If processing involves high-tail-latency dependencies (payment gateways, third-party APIs), consider 45-55 seconds and adjust the container grace period to match. Drains that consistently exceed 20 seconds usually indicate a downstream issue, not engine misconfiguration.

DemuxConfig::drain_timeout(d: Duration)

await_assignments_timeout

Default: 50s · Min: 5s · Max: 5m

How long a starting consumer waits for the broker to complete rebalancing and assign partitions before giving up.

Keep it above drain_timeout: worst-case startup includes waiting for existing consumers to drain. The default of 50 seconds gives comfortable headroom over the 20-second drain default, and in rolling deployments startup wait matters less than drain performance, because healthy consumers keep processing while the new instance waits.

DemuxConfig::await_assignments_timeout(d: Duration)

Offset management

The offset committer remultiplexes concurrent completions back into contiguous ranges through a pre-commit cache: a sliding window applied to offsets. These tune its internal structures and rarely need changing.

commit_ingest_channel_len

Default: auto-calculated · Min: 1,000 · Max: 200,000

The buffer between the pipeline and the offset committer. While the committer pauses ingest to perform an async commit, completions queue here; if it fills, the pipeline blocks until the commit finishes.

Auto-calculated as concurrent_keys × 100, clamped between 5,000 and 100,000 (25,000 at the defaults). Override only if metrics show commit-related backpressure; shortening auto_commit_interval is often the better lever, since it shrinks the pause window that causes accumulation.

DemuxConfig::commit_ingest_channel_len(n: u32)

commit_partition_slice_len

Default: 400 · Min: 50 · Max: 2,000

Initial pre-allocated size of the per-partition pre-commit cache, which tracks out-of-order completions and resolves them to the highest contiguous offset safe to commit.

Not a hard limit: the cache grows dynamically. The setting only avoids re-allocations in steady state. Increase towards 1,000-2,000 for high-jitter workloads where widely varying processing times leave wide gaps between completed offsets.

DemuxConfig::commit_partition_slice_len(n: u32)

acquire_commit_guard_timeout

Default: 10s · Min: 100ms · Max: 30s

How long the committer waits to acquire the ingest guard that coordinates the commit cycle with the pipeline.

The default is sufficient for all normal operation; a timeout here signals severe contention and is a symptom to investigate, not a value to tune.

DemuxConfig::acquire_commit_guard_timeout(d: Duration)

Circuit breakers

Safety valves against blocking forever under pathological conditions. They should never fire in normal operation; when one does, the root cause is almost always an external dependency that has stopped responding.

acquire_worker_timeout_circuit_breaker

Default: 60s · Min: 15s · Max: 15m

If a message cannot acquire a worker slot within this time, the engine assumes deadlock or severe resource exhaustion and performs an emergency shutdown, handing partitions to other consumers in the group. Your shutdown handler receives the reason.

The 60-second default is deliberately conservative to avoid false positives during legitimate bursts. A trip usually means a downstream dependency has stopped responding and every worker is blocked in a handler.

DemuxConfig::acquire_worker_timeout_circuit_breaker(d: Duration)

rebalance_pause_polling_timeout

Default: 30s · Min: 10s · Max: 10m

The same class of safety valve, specific to the rebalance drain phase: if workers cannot be paused within this time during a rebalance, the engine treats it as a potential deadlock.

Thirty seconds is ample for heavily loaded workers to finish their current messages; trips point at the same downstream-dependency causes as the worker circuit breaker.

DemuxConfig::rebalance_pause_polling_timeout(d: Duration)

Derived values

Two values are computed from the configuration at startup. They are not settable, but knowing them helps when reading metrics and sizing instances.

WorkerChannelsMapSize

Derived from concurrent_keys & worker_shards_count

Per-shard hash map initial capacity for worker channels: 2 × (concurrent_keys / worker_shards_count), rounded up to a power of 2. At the defaults this is 256 slots per shard, trading modest memory for reduced allocation pressure on the hot path.

MinimumIdleWorkers

Derived from concurrent_keys & worker_shards_count

Per-shard idle workers pre-warmed at startup: the ceiling of concurrent_keys / worker_shards_count, 16 per shard at the defaults. Burst capacity is not limited by this minimum; workers are created on demand and pooled back afterwards. It only ensures the first messages after startup pay no allocation cost.

Lifecycle & operations

run() blocks for the life of the consumer while the engine polls, routes and commits on its own threads. stop(), callable from any ordinary thread, triggers the graceful path: in-flight work drains, offsets commit, and only then do stop() and run() return, so a process that exits after stop() has lost nothing. Two places must never call it: a signal handler (Go code is never async-signal-safe) and a message handler (it would ask the engine to drain the very worker blocked in the call). The pattern below handles both: the signal handler only sets a flag, and a plain thread watches it.

use llingr_kafka::{Builder, DeadLetterHandler, Message, ProcessHandler, Traits}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; struct OrderProcessor; impl ProcessHandler for OrderProcessor { fn process(&self, _msg: &Message) -> Result<Traits, Box<dyn std::error::Error>> { Ok(Traits::none()) } } struct DeadLetters; impl DeadLetterHandler for DeadLetters { fn handle(&self, msg: &Message, error: &str) -> Result<(), Box<dyn std::error::Error>> { eprintln!("dead-letter pk: {} reason: {}", msg.key_str().unwrap_or(""), error); Ok(()) } } fn main() -> Result<(), Box<dyn std::error::Error>> { let engine = Builder::new("customer_orders", OrderProcessor, DeadLetters) .brokers("localhost:9092") .consumer_group("consumer-rust") .build()?; // The signal handler only flips this flag (signal-hook = "0.3"); it // never touches the engine. Go code is not async-signal-safe. let shutdown = Arc::new(AtomicBool::new(false)); signal_hook::flag::register(signal_hook::consts::SIGINT, Arc::clone(&shutdown))?; signal_hook::flag::register(signal_hook::consts::SIGTERM, Arc::clone(&shutdown))?; // An ordinary thread watches the flag and calls the stopper. let stop = engine.stopper(); // Send + 'static: moves into the thread let flag = Arc::clone(&shutdown); std::thread::spawn(move || { while !flag.load(Ordering::Relaxed) { std::thread::sleep(std::time::Duration::from_millis(100)); } stop(); // graceful: drain in-flight work, commit, release run() }); engine.run()?; // blocks here until stop() completes its drain Ok(()) }

Hosting the engine

  • One engine per process. The Go runtime is process-global; a second build() returns a clean error. A failed build (broker briefly unreachable, say) can be retried with a newly constructed Builder
  • Thread budget. The engine's parallelism follows GOMAXPROCS, which must be set in the environment before the process starts (setting it from Rust code has no effect); a process that also runs tokio or rayon, which default to the CPU count as well, needs it budgeted explicitly
  • Liveness is the host's job. A handler blocked on a dead dependency does not crash anything; the circuit breaker fires after its timeout. The per-message Prometheus counters are a natural heartbeat for a watchdog, and sustained poll failure triggers the engine's own emergency shutdown after ten minutes (configurable via poll_error_bail_after)
  • Exiting without stop() is safe but wasteful: uncommitted offsets are simply redelivered on restart (at-least-once); the committer never commits past completed contiguity

Deployment notes

  • Linux (glibc) for production and macOS for development; Alpine/musl is not supported (the embedded Go runtime does not initialise on musl), and neither is Windows
  • Single-binary mode (the default): one self-contained executable, deployable in a scratch image of roughly 16 MB with no shared library, no RPATH and no LD_LIBRARY_PATH
  • Side-binary mode (LLINGR_LINK=shared): libllingr.so deployed next to the binary, resolved by RPATH ($ORIGIN) with no ldconfig and no system install; one engine build can serve several binaries, and an engine update is a file replacement plus restart
  • The ABI is versioned: the crate checks the engine's version at startup and refuses a mismatch cleanly, so an engine/crate skew can never become silent memory corruption
  • Configuration crosses the FFI boundary once, at build(); message processing then crosses with borrowed, zero-copy key and value

Observability

Prometheus metrics are enabled using a builder call, in either of two activation modes: a built-in scrape endpoint the crate serves on its own thread, or a handle mountable on an HTTP server the application already runs. Both expose the same series in the OpenMetrics text format, metering every message, not a sample. The capability is always compiled in; constructing a Metrics value switches it on, and leaving metrics unconfigured costs nothing at runtime.

use llingr_kafka::{Metrics, MetricsHandle, OPENMETRICS_CONTENT_TYPE}; // Mode 1, built-in endpoint: binds the address at build() (an unbindable // address is a clean build error) and answers GET /metrics with the // OpenMetrics exposition, on a dedicated thread. No async runtime. let served = Metrics::serve("0.0.0.0:9464", "/metrics"); // Mode 2, no server: a Clone + Send + Sync handle renders the current // exposition on demand, mountable on any HTTP framework. let (metrics, handle) = Metrics::registry(); fn metrics_response(handle: &MetricsHandle) -> (&'static str, String) { (OPENMETRICS_CONTENT_TYPE, handle.scrape()) } // Either value passes to the engine builder's .metrics(...) hook.

Every per-message series is named llingr_engine_* and labelled by topic, consumer_group, service, team and partition; the service and team labels come from the builder's optional service(name, team) identity, which is how fleet tooling routes and groups telemetry. Cardinality scales with the partition count, not message volume or key count, so the exposition stays bounded under load. The bucket layouts of the latency histograms are pinned to the Go engine's own, so the Rust exposition and the Go engine's reporting line up bucket for bucket.

MetricKindMeaning
llingr_engine_processed_totalcounterEvery message processed; increments once per message, unconditionally
llingr_engine_errored_totalcounterThe process handler returned an error (or panicked; the panic is caught and converted)
llingr_engine_panicked_totalcounterThe Go engine recovered a panic inside its own callback: a bridge fault, not a handler panic
llingr_engine_dead_lettered_totalcounterThe message was routed to the dead-letter handler
llingr_engine_duplicate_totalcounterThe message was a redelivery: the at-least-once duplicate signal
llingr_engine_used_overflow_totalcounterDispatch used the guard-channel overflow path: a capacity signal worth graphing
llingr_engine_queue_depthgaugeCurrent per-partition queue depth
llingr_engine_current_offsetgaugeThe offset currently being processed on the partition
llingr_engine_process_duration_secondshistogramTime in the process handler
llingr_engine_dead_letter_duration_secondshistogramTime in the dead-letter handler
llingr_engine_queue_wait_duration_secondshistogramTime a message waited in the queue before processing

Trait flags: framework and application bits

Traits is a 64-bit flag field recorded for every message. The engine owns bits 0-9 and records the message's fate; the process handler returns bits 10-63 for application classification (Traits::with_bit(n), .set(n), combinable with |). Attempts to set framework bits are masked, so application code cannot forge engine flags. Five framework conditions appear as the Prometheus counters above; the remaining framework bits have getters but no metric, and application bits appear nowhere in this crate's telemetry, so classification that must reach a telemetry pipeline is emitted from the handler itself.

FlagSet whenPrometheus counter
has_process_error()The process handler returned Err, or panicked: the panic is caught at the FFI boundary and converted to the same flagllingr_engine_errored_total
has_process_panic()The Go engine recovered a panic inside its own callback: a bridge fault, not a handler panicllingr_engine_panicked_total
has_dead_letter()The message was routed to the dead-letter handlerllingr_engine_dead_lettered_total
has_duplicate()The message was a redelivery: the at-least-once duplicate signalllingr_engine_duplicate_total
has_used_overflow()Dispatch used the guard-channel overflow path: a capacity signalllingr_engine_used_overflow_total
has_commit_buffered()The message completed out of contiguous order and was held in the gap buffernone
has_orphaned()The work item was orphaned by a rebalance (handled safely)none
has_first_after_rebalance()First message processed on its partition after reassignmentnone

Bandwidth telemetry

The second telemetry stream is wire-level: per-partition byte and message counters and the broker topology, collected by the broker client at a configurable cadence and flushed off the message hot path. It activates together with metrics (either mode) and registers on the same Prometheus registry as the llingr_bandwidth_* series: received and transmitted bytes and message counts per partition, compressed and uncompressed byte counts where the client exposes compression visibility, and cluster-level series for the broker count, assigned partitions, and the broker topology as an info metric. Partition keys and payloads are deliberately excluded.

// Bandwidth collection activates with metrics; the cadences are // configurable on the engine builder. let engine = Builder::new("customer_orders", OrderProcessor, DeadLetters) .brokers("localhost:9092") .consumer_group("consumer-rust") .metrics(Metrics::serve("0.0.0.0:9464", "/metrics")) .bandwidth_stats_interval(Duration::from_secs(30)) // collection cadence .bandwidth_flush_interval(Duration::from_secs(15)) // aggregator flush .build()?;

Engine snapshot

For a point-in-time view of the whole engine, snapshot() returns a typed Snapshot, and snapshot_json() the same JSON document the Go engine's SnapshotHandler serves: topic summary, sliding 15-second throughput windows with latency figures, per-partition offset tracking with gap-buffer depths, guard-channel utilisation and per-shard worker counts. Both are safe from any thread while the engine runs; the JSON mounts on whatever HTTP stack the application already uses, and dashboards built against the Go endpoint apply unchanged.

// The engine's own snapshot, as JSON: servable from any HTTP route. let snapshot_json = engine.snapshot_json()?; // {"summary":{"topicName":"customer_orders","assignedPartitionCount":12, // "totalProcessed":4337870,...}, // "throughput":{"windows":[...15 one-second buckets...], // "avgProcessDuration":"1.4ms",...}, // "preCommits":{"partitions":[{"partition":0,"committedOffset":361488, // "highestReadyOffset":361515,"gapBufferDepth":27,...},...]}, // "concurrency":{"guardActive":63,"guardCapacity":250,...}, // "shards":[{"shard":0,"activeWorkers":11,"pooledWorkers":28},...]}

Engine logs

The engine's own log stream (subscription lifecycle, rebalances, poll errors, the licence notice) flows into the process-global log facade under the target llingr: no stderr scraping, no logger parameter and no wiring. The crate registers its logging before the engine initialises, so startup lines are captured. Any log-compatible logger receives the lines (env_logger, fern, or tracing through tracing-log), with the engine's verbosity controlled independently: RUST_LOG=llingr=debug raises it, RUST_LOG=llingr=off silences it. The franz-go client's own internal logging is separate, controlled by the client_log_level option.

Data privacy

  • Message data (keys and payloads) is never logged by the engine
  • Metric labels are per-partition, never per-key, so telemetry pipelines cannot disclose partition keys
  • The bandwidth series are purely infrastructure-level: bytes, message counts and broker topology, never keys or payloads
  • The engine runs entirely inside the host process: it never hosts anything and has no access to the surrounding infrastructure

Bring high-throughput, low-latency, low-costs, reliability, scalability and operational simplicity to your Rust services

Arrange a Demo