You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by pi...@apache.org on 2026/05/25 19:22:02 UTC

(iggy) branch connectors_agent created (now d9444165a)

This is an automated email from the ASF dual-hosted git repository.

spetz pushed a change to branch connectors_agent
in repository https://gitbox.apache.org/repos/asf/iggy.git


      at d9444165a feat(connectors): add agent docs, per-batch observability, atomic state

This branch includes the following new commits:

     new d9444165a feat(connectors): add agent docs, per-batch observability, atomic state

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(iggy) 01/01: feat(connectors): add agent docs, per-batch observability, atomic state

Posted by pi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

spetz pushed a commit to branch connectors_agent
in repository https://gitbox.apache.org/repos/asf/iggy.git

commit d9444165ab6ba7c0e289be82dade956a5bb4a493
Author: spetz <pi...@gmail.com>
AuthorDate: Mon May 25 21:21:48 2026 +0200

    feat(connectors): add agent docs, per-batch observability, atomic state
---
 .claude/skills/connector-runtime/SKILL.md          | 286 ++++++++
 .claude/skills/connector-sdk/SKILL.md              | 152 +++++
 .claude/skills/connector-sink/SKILL.md             | 370 +++++++++++
 .claude/skills/connector-source/SKILL.md           | 346 ++++++++++
 .claude/skills/connector-testing/SKILL.md          | 336 ++++++++++
 .claude/skills/connector-transform/SKILL.md        | 263 ++++++++
 .claude/skills/connectors-overview/SKILL.md        | 236 +++++++
 AGENTS.md                                          | 355 ++++++++++
 Cargo.lock                                         |  13 +
 core/connectors/README.md                          |   2 +
 core/connectors/runtime/Cargo.toml                 |   2 +-
 core/connectors/runtime/README.md                  |  41 ++
 core/connectors/runtime/src/benchmark.rs           | 232 +++++++
 core/connectors/runtime/src/configs/connectors.rs  |  10 +
 core/connectors/runtime/src/configs/runtime.rs     |  83 +++
 core/connectors/runtime/src/error.rs               |   2 -
 core/connectors/runtime/src/log.rs                 |  78 ++-
 core/connectors/runtime/src/main.rs                |   5 +-
 core/connectors/runtime/src/manager/sink.rs        |   1 +
 core/connectors/runtime/src/manager/source.rs      |   1 +
 core/connectors/runtime/src/metrics.rs             | 374 ++++++++++-
 core/connectors/runtime/src/sink.rs                | 107 ++-
 core/connectors/runtime/src/source.rs              | 177 +++--
 core/connectors/runtime/src/state.rs               | 323 +++++++--
 core/connectors/runtime/src/stats.rs               |   6 +
 core/connectors/sdk/src/api.rs                     |   1 +
 core/connectors/sinks/README.md                    |   2 +
 core/connectors/sources/README.md                  |   2 +
 .../tests/connectors/runtime/benchmark.rs          | 721 +++++++++++++++++++++
 .../tests/connectors/runtime/benchmark.toml        |  23 +
 .../runtime/benchmark_config/random_source.toml    |  38 ++
 .../runtime/benchmark_config/stdout_sink.toml      |  35 +
 .../connectors/runtime/benchmark_disabled.toml     |  23 +
 .../benchmark_disabled_config/random_source.toml   |  38 ++
 .../benchmark_disabled_config/stdout_sink.toml     |  35 +
 .../tests/connectors/runtime/benchmark_json.toml   |  26 +
 .../benchmark_json_config/random_source.toml       |  38 ++
 .../runtime/benchmark_json_config/stdout_sink.toml |  35 +
 core/integration/tests/connectors/runtime/mod.rs   |   1 +
 39 files changed, 4637 insertions(+), 182 deletions(-)

diff --git a/.claude/skills/connector-runtime/SKILL.md b/.claude/skills/connector-runtime/SKILL.md
new file mode 100644
index 000000000..30994de9f
--- /dev/null
+++ b/.claude/skills/connector-runtime/SKILL.md
@@ -0,0 +1,286 @@
+---
+name: connector-runtime
+description: Modify the Apache Iggy Connectors runtime (`core/connectors/runtime/`) - the host process that loads plugins, manages lifecycle, and bridges Apache Iggy streams to plugins via FFI. Use when changing plugin loading, the FFI dispatch, the sink/source manager, state storage, config providers, the HTTP control API, metrics, or transforms wiring. NOT for plugin code.
+---
+
+# Modifying the Apache Iggy Connectors Runtime
+
+The runtime is the host. It loads `.so`/`.dylib`/`.dll` plugins, drives their lifecycle, ferries messages between Apache Iggy and plugins, exposes a `/stats`, `/metrics`, and control HTTP API. Bugs here affect every plugin - tread carefully.
+
+## File map
+
+```text
+runtime/src/
+├── main.rs                  Entry, plugin path resolution, SourceApi/SinkApi FFI structs
+├── sink.rs                  Sink lifecycle, Iggy consumer wiring, FFI consume calls
+├── source.rs                Source lifecycle, flume forwarding, state save loop
+├── stream.rs                Stream + consumer/producer setup
+├── transform.rs             Loads transforms from config, applies them in chain
+├── state.rs                 FileStateProvider, ConnectorState file I/O
+├── context.rs               Per-instance context (Iggy client, metrics, config)
+├── error.rs                 RuntimeError with as_code() for HTTP responses
+├── log.rs                   init_logging (text/JSON x telemetry-on/off matrix) + LOG_CALLBACK
+├── benchmark.rs             emit_sink_event / emit_source_event + as_micros (target = iggy_connectors::benchmark)
+├── metrics.rs               Prometheus families + gauges + stage histograms + label caches
+├── stats.rs                 /stats endpoint payload assembly
+├── manager/
+│   ├── mod.rs
+│   ├── sink.rs              SinkManager, status transitions, restart guard
+│   └── source.rs            SourceManager (parallel structure)
+├── configs/
+│   ├── mod.rs
+│   ├── runtime.rs           RuntimeConfig (top-level) + LoggingConfig + LogFormat (text/json)
+│   ├── connectors.rs        ConnectorConfig, SinkConfig, SourceConfig (with verbose + benchmark flags)
+│   └── connectors/
+│       ├── local_provider.rs  Filesystem-based config loader
+│       └── http_provider.rs   HTTP-based config loader
+└── api/                     HTTP control + observability endpoints
+```
+
+## Architecture invariants
+
+Load-bearing assumptions. Breaking them silently corrupts data or hangs the process.
+
+### Plugin instance identity
+
+- Each plugin instance has a globally unique `plugin_id: u32`, monotonically allocated from `PLUGIN_ID: AtomicU32` in `main.rs`. Never reused for the lifetime of the process.
+- The same `.so` may be loaded for many instances - each gets a fresh `plugin_id` but **shares the `Container` (dlopen handle)** via `Arc` in `manager/sink.rs` and `manager/source.rs`.
+- All FFI calls (`iggy_*_open`, `iggy_*_consume`, etc.) are keyed by `plugin_id`. Mixing IDs = data routed to wrong plugin.
+
+### FFI pointer lifetimes
+
+- Config and state are passed as `(*const u8, usize)`. Valid for the call duration only. The plugin **must not retain the pointer** - it must copy if it needs the bytes. The SDK macros do this correctly; don't bypass them.
+- `LogCallback` lifetime spans the entire process - kept in static memory in `log.rs`. Don't make it dynamic.
+
+### Container ownership
+
+- `dlopen2::wrapper::Container<SinkApi>` / `Container<SourceApi>` (FFI structs defined in `main.rs`) is shared via `Arc` across all instances of the same .so.
+- The Arc must outlive every spawned task that calls into the plugin. The manager holds the Arc in `SinkDetails`/`SourceDetails` for the lifetime of the connector.
+- Unloading a .so while a task is mid-FFI-call would segfault. The runtime does not unload .so files. Don't try to add hot reload without rearchitecting.
+
+### Plugin manager state
+
+- `SinkManager` and `SourceManager` use `DashMap<String, Arc<Mutex<Details>>>`. Key = connector key (TOML key field).
+- Status transitions (`Starting → Running → Stopped/Error`) update running counters only on transitions to/from `Running`. See `SinkManager::update_status`.
+- `restart_guard: Arc<Mutex<()>>` prevents concurrent restart of the same connector. `restart_connector()` uses `try_lock()` - if busy, returns OK without restarting. **This is intentional** to prevent thundering-herd restarts.
+
+### Serialization split
+
+- **FFI message payloads** (`TopicMetadata`, `MessagesMetadata`, `RawMessages`, headers): `postcard` - compact binary, stable wire format.
+- **Connector configs** passed to plugin: `serde_json` - human-editable TOML in, JSON over FFI.
+- **`ConnectorState`** bytes inside plugins: `rmp_serde` (MessagePack). The runtime treats the bytes opaquely.
+
+Each is in its place for a reason: stability vs editability vs compactness. Don't mix.
+
+## Benchmark mode
+
+`SinkConfig`/`SourceConfig` carry a `benchmark: bool` (`#[serde(default)]`, env-addressable via `ConfigEnv` as `IGGY_CONNECTORS_<TYPE>_<KEY>_BENCHMARK=true`). Implementation lives in `runtime/src/benchmark.rs` (text event emitters + `as_micros`) and `runtime/src/metrics.rs::{Stage, SinkLabels, SourceLabels, observe_stage_with_labels, STAGE_BUCKETS_SECONDS}`.
+
+**Two independent surfaces**:
+
+1. **Per-batch tracing event** - target `iggy_connectors::benchmark`, gated by `benchmark = true`. One `info!` line per batch with `prepare_us/ffi_us/total_us` for sinks and `decode_us/prepare_us/iggy_send_us/state_save_us/total_us` for sources. Filter via `RUST_LOG=iggy_connectors::benchmark=info`. On startup, the sink/source loop also emits a one-shot `"Benchmark mode enabled for ..."` info log so operators can confirm the flag took effect.
+
+2. **Stage-duration histograms** - `iggy_connector_stage_duration_seconds{connector_key, connector_type, stage}`. **Always on** regardless of the flag. Observed at the same per-stage points the text event uses. Bucket boundaries: `50µs, 100µs, 250µs, 500µs, 1ms, 5ms, 10ms, 50ms, 100ms, 250ms, 500ms, 1s, 5s`. Read via `/metrics` endpoint (requires `[http.metrics] enabled = true` in runtime config). Lets operators do `histogram_quantile(0.95, ...)` queries in Prometheus.
+
+When wiring new stages in the runtime, mirror the existing pattern: capture
+`Instant::now()` before the stage, capture `.elapsed()` after, call
+`metrics.observe_stage_with_labels(&labels.stage_x, elapsed)` using the
+**pre-built labels cache** (`SinkLabels` / `SourceLabels` from `metrics.rs`).
+The cache is built once per consumer/producer task at spawn time and threaded
+through (`Arc<SinkLabels>` for sink, `Arc<SourceLabels>` for source). This
+avoids per-batch `String::to_owned` for the label keys - cost stays at ~10 ns
+per stage (Instant + atomic bucket increment). Histograms are always on
+regardless of the `benchmark` flag; only the verbose text event emission is
+gated.
+
+## Logging format
+
+`LoggingConfig` in `configs/runtime.rs` exposes `format: LogFormat` (`Text` default, `Json`), env-addressable via `IGGY_CONNECTORS_LOGGING_FORMAT=json`. `log::init_logging` matches on `(telemetry.enabled, format)` and installs the correct combination of `fmt::layer()` / `fmt::layer().json()` and the OpenTelemetry layer. The OTel export pipeline is untouched by `format` - only the stdout layer flips between text and JSON.
+
+When extending logging, preserve the 4-branch matrix - tracing-subscriber layers have different concrete types for text vs JSON and cannot be unified without boxing the entire registry.
+
+## The `verbose` flag
+
+`SinkConfig` and `SourceConfig` in `configs/connectors.rs` carry `verbose: bool` (default false via `#[serde(default)]`) at the top level. The runtime threads it through `spawn_consume_tasks` / source equivalent to `consume_messages`, where it gates per-batch log promotion:
+
+```rust
+if verbose {
+    info!("Processing {messages_count} messages for sink connector with ID: {plugin_id}");
+} else {
+    debug!("Processing {messages_count} messages for sink connector with ID: {plugin_id}");
+}
+```
+
+When extending the runtime with new per-batch logging, follow the same pattern - default to `debug!`, upgrade to `info!` when `verbose` is set. Don't introduce a third level. Plugin authors are encouraged to mirror this pattern internally for their own diagnostics.
+
+## Config provider rules
+
+### Local provider (`configs/connectors/local_provider.rs`)
+
+- Reads `*.toml` from `config_dir`. Skips hidden files (`.`) and `Cargo.toml`.
+- Filename convention: `{key}_{type}[_v{N}].toml` (e.g., `postgres_sink_v2.toml`).
+- One TOML deserialized into either `SinkConfig` or `SourceConfig`. Grouped by `key`; highest `version` wins unless `.active_versions.toml` (leading dot - it's a hidden file by convention) overrides. Built by `LocalConnectorsConfigProvider::active_versions_file_path` as `{config_dir}/.active_versions.toml`.
+
+### HTTP provider (`configs/connectors/http_provider.rs`)
+
+- Uses `reqwest_middleware` + `RetryTransientMiddleware`.
+- Retries 5xx + connection errors. **Never retries 4xx** - per the `PermanentHttpError` convention.
+- Default URL templates documented in `runtime/README.md`. Templates configurable via TOML.
+
+### Env-var overrides via `ConfigEnv` derive
+
+`SinkConfig`, `SourceConfig`, and several inner structs derive `ConfigEnv`
+(`configs_derive::ConfigEnv`). This generates env-var addressability with the
+pattern `IGGY_CONNECTORS_<TYPE>_<KEY>_<FIELD>` for primitive fields. Used
+heavily by integration tests to inject testcontainer ports into static TOML -
+see `core/integration/tests/connectors/fixtures/postgres/container.rs` for the
+env-var constants. When adding a config field, mark it `#[config_env(skip)]`
+for compound types or `#[config_env(leaf)]` for primitives that should be
+env-addressable.
+
+### Versioning
+
+- Configs carry `version: u64`. Local provider auto-increments if absent; HTTP provider trusts the server.
+- Restart on version change uses `restart_guard`.
+
+## State storage (`state.rs`)
+
+- File path: `{state_path}/source_{connector_key}.state`.
+- `save()` is crash-atomic: bytes are written to `{path}.tmp`, fsynced, then `rename`d into place. POSIX guarantees the rename, so a crash leaves either the previous good state or the new one - never a truncated file. On Unix, the parent directory is fsynced after the rename as a best-effort to make the rename itself durable. A `Mutex<()>` serializes concurrent saves on the same provider.
+- Save happens after every successful Apache Iggy send. Save failure logs + continues; the next batch retries the write.
+- `load()` returns `Ok(None)` for missing or empty files. The file is created lazily on first successful save.
+- Sinks have no state - only sources.
+
+## Source forwarding loop
+
+Per polling source:
+
+1. `iggy_source_handle(id, send_callback)` - plugin registers itself.
+2. Plugin polls + invokes `send_callback(plugin_id, ptr, len)`.
+3. `send_callback` runs in the SDK macro's spawned task; pushes postcard-serialized `ProducedMessages` into a `flume` channel keyed by `plugin_id` in `SOURCE_SENDERS: Lazy<DashMap<u32, SourceSenderEntry>>`. `SourceSenderEntry` wraps the sender + `Arc<Metrics>` + plugin_key so the FFI callback can bump `errors` on postcard deserialize failure or channel-closed send without needing access to the per-connector runtime context.
+4. `source_forwarding_loop` pulls from the channel, deserializes, applies transforms, encodes via `StreamEncoder`, sends to Iggy producer.
+5. On success, save returned `ConnectorState` via `FileStateProvider`.
+
+Gotchas:
+
+- `SOURCE_SENDERS` must be cleaned up on connector close or **memory leak** (channel + task).
+- The runtime's `spawn_source_handler` wraps the outer
+  `iggy_source_handle(id, callback)` FFI registration call in
+  `tokio::task::spawn_blocking()`. That call returns quickly (the SDK macro
+  internally `runtime.spawn`s an async `handle_messages` task and returns).
+  **Subsequent `send_callback` invocations happen from that async task, not
+  from `spawn_blocking`** - they hand the postcard bytes into a
+  `flume::unbounded` channel that `source_forwarding_loop` drains. A
+  long-running synchronous poll inside the plugin would block one Tokio
+  worker; async polls don't.
+- No timeout on the registration call - a plugin whose `iggy_source_handle` never returns stalls one blocking worker for the lifetime of the runtime.
+
+## Sink consumption loop
+
+Per `[[streams]]` entry per sink:
+
+1. Build / ensure consumer group `iggy-connect-sink-{key}` (note: `connect`, not `connectors` - matches the docker image name `apache/iggy-connect`; see `runtime/src/sink.rs::default_consumer_group`). Overridable via the stream config's `consumer_group` field.
+2. Spawn one task per topic in the stream config (`spawn_consume_tasks`).
+3. Poll Iggy → batch messages (`batch_length` default 1000, `poll_interval` default 5ms). A `consumer.next()` returning `Err` (transport/decode failure at the Iggy client boundary) bumps `errors` and `continue`s - the offset has already auto-committed via `AutoCommit::When(AutoCommitWhen::PollingMessages)`, so the affected message is effectively dropped.
+4. Decode via `Schema::decoder()`. Decode failure logs `error!` and bumps `errors`. `messages_filtered` is reserved for the transform filter contract (`Ok(None)`).
+5. Apply transforms (chain). A transform returning `Ok(None)` filters the message - `messages_filtered{connector_type="Sink"}` is bumped (intentional drop, distinct from `errors`).
+6. Postcard-encode batch as `RawMessages`, headers as separate postcard blob. Per-message failure (missing required field, payload conversion, header serialization) bumps `errors` and skips that message. Batch-level postcard failure (topic metadata, messages metadata, the wrapping `RawMessages`) propagates `Err` out of `process_messages` → `consume_messages` → the spawned task wrapper in `spawn_consume_tasks`, which bumps `errors` for the failed batch + records `set_error`.
+7. Call `iggy_sink_consume(id, topic_meta, messages_meta, messages)`.
+8. Non-zero return → log + increment errors metric.
+
+Gotchas:
+
+- Batch flushes on `current_offset != message_offset` (gap detected) OR batch full - causes higher latency for low-volume topics.
+- Auto-commit happens on poll - idempotency at the sink protects against re-delivery on crash before plugin write.
+
+## Error categorization
+
+`RuntimeError` (`error.rs`) carries `as_code()` for HTTP API responses.
+
+| Class | Fatal? | Example |
+| ------- | -------- | --------- |
+| Config load | yes (process exit) | Bad TOML, missing required field |
+| Iggy client init | yes | Auth failure at startup |
+| State dir create | yes | Permission denied |
+| Plugin .so resolve | per-plugin (FailedPlugin) | Missing file |
+| Plugin open FFI | per-plugin (status = Error) | Plugin returned non-zero |
+| Message decode | per-message (skip) | Bad protobuf bytes |
+| Iggy send | per-batch (metric) | Network blip |
+| State save | per-batch (log) | Disk full |
+
+Fatal errors propagate to `main` and exit. Per-connector and per-message errors are isolated.
+
+## Metrics (`metrics.rs`)
+
+All families labeled by `connector_key` + `connector_type` (the histogram adds `stage`):
+
+- **Counters**: `iggy_connector_messages_{produced,sent,consumed,processed,filtered,errors}_total`.
+  - `messages_filtered_total` - intentional drops by transforms returning `Ok(None)`.
+  - `errors_total` - unexpected drops (decode/encode/build failure, missing field, etc.) AND batch-level failures (Iggy send, state save, transform-error propagation).
+- **Histograms**: `iggy_connector_stage_duration_seconds{stage}` - per-batch stage timing. `stage` ∈ `{Prepare, Ffi, Decode, IggySend, StateSave, Total}`. Buckets `STAGE_BUCKETS_SECONDS` (50µs - 5s, 13 buckets). Always populated regardless of any flag; observation lives next to each stage in `source_forwarding_loop` and `consume_messages`/`process_messages`. Histograms are scrape-served at `/metrics` only when `[http.metrics] enabled = true` in the runtime TOML.
+- **Gauges**: `iggy_connectors_{sources,sinks}_{total,running}`.
+
+`/stats` JSON surface mirrors counters per-connector via `ConnectorStats` (sdk `api.rs`): `messages_filtered`, `errors`, and the kind-specific produced/sent/consumed/processed.
+
+When adding a new metric:
+
+- Add the family to `Metrics` struct + `init`, register with a name + help text.
+- For families with new label sets (like the stage histogram), define an `EncodeLabelSet` struct + `EncodeLabelValue` enum.
+- For histograms, pass a constructor `fn() -> Histogram` to `Family::new_with_constructor`.
+- Add unit tests under `mod tests`; mirror the existing `given_*_when_*_should_*` BDD names.
+
+## Hard rules
+
+1. **Filter drops bump `messages_filtered`** (a transform returning `Ok(None)`
+   is the documented filter contract). **Every non-filter drop bumps `errors`**
+   via `metrics.inc_errors_with_labels(&labels.counter)` before `continue` (or
+   `metrics.inc_messages_filtered_with_labels(&labels.counter, 1)` for the
+   filter case). Hot-path calls always use the pre-built
+   `SinkLabels`/`SourceLabels` cache; the `&str`-based wrappers
+   (`increment_errors`/`increment_messages_filtered`/...) on `Metrics` are
+   `#[cfg(test)]`-only and exist solely for ergonomic test code. Wired at
+   every drop site:
+   - `runtime/src/sink.rs::consume_messages` - `consumer.next()` Err (transport boundary).
+   - `runtime/src/sink.rs::process_messages` - decode, missing required fields (id/offset/checksum/timestamp/origin_timestamp), payload conversion, header serialization (per-message; previously batch-level).
+   - `runtime/src/sink.rs::spawn_consume_tasks` task wrapper - bumps once on any `consume_messages` Err (covers batch-level postcard failures propagated via `?`).
+   - `runtime/src/source.rs::source_forwarding_loop` - payload decode, prepare (transform/encode) failure, Iggy send Err, state save Err.
+   - `runtime/src/source.rs::process_messages` - transform encode failure, `build_iggy_message` failure.
+   - `runtime/src/source.rs::handle_produced_messages` - postcard deserialize failure from plugin, `sender.send` channel-closed (via the `SourceSenderEntry.metrics` handle).
+
+   Both counters surface in `/metrics` (`iggy_connector_messages_filtered_total`, `iggy_connector_errors_total`) and in `/stats` (`ConnectorStats.messages_filtered`, `.errors`). When adding a new code path that drops a message, mirror this pattern.
+2. **Never block the executor.** All I/O is async. `spawn_blocking` only for FFI calls (already in place).
+3. **Plugin ID counter is monotonic.** Don't reset, don't reuse.
+4. **FFI return codes:** `0` success, non-zero failure. Stick to this.
+5. **Don't add static mutable state** beyond the existing `LOG_CALLBACK`, `PLUGIN_ID`, `SOURCE_SENDERS`.
+6. **Always pair `cleanup_sender(id)` with shutdown** for sources (avoid the flume leak).
+7. **Restart uses `restart_guard.try_lock()`** - no thundering-herd regression.
+8. **Don't add timeouts to plugin FFI calls without a kill-task strategy.** A timeout that returns from the runtime but leaves the plugin running has the worst of both worlds.
+
+## Common pitfalls
+
+1. **Mutating `INSTANCES` (in the SDK macro) from the runtime side** - impossible by design; only the macro touches it.
+2. **Calling `iggy_*_open` with a duplicate ID** - returns `-1` by design. If you see this, the runtime forgot to call `iggy_*_close` first.
+3. **Holding a `DashMap` shard guard across `.await`** - causes lockups. Pattern: `.get().clone()` out, drop the guard, await.
+4. **Adding fields to `#[repr(C)]` types without an SDK version bump** - existing plugins will misalign on `postcard::from_bytes`.
+5. **Changing the default consumer group name** without coordinating with operators - they have offsets stored there.
+
+## Before declaring done
+
+```text
+cargo fmt --all
+cargo sort --no-format --workspace
+cargo clippy -p iggy-connectors --all-targets -- -D warnings
+cargo test -p iggy-connectors
+
+# Sanity-build all in-tree plugins:
+cargo build -p iggy_connector_stdout_sink -p iggy_connector_random_source
+
+# Run runtime-focused integration tests (filter via test path; no separate --test target):
+cargo test -p integration -- connectors::runtime::
+
+# Smoke-test with example config:
+IGGY_CONNECTORS_CONFIG_PATH=core/connectors/runtime/example_config/config.toml \
+  cargo run --bin iggy-connectors
+```
+
+Update `runtime/README.md` if endpoints, env vars, or config schema change.
diff --git a/.claude/skills/connector-sdk/SKILL.md b/.claude/skills/connector-sdk/SKILL.md
new file mode 100644
index 000000000..8eed18bae
--- /dev/null
+++ b/.claude/skills/connector-sdk/SKILL.md
@@ -0,0 +1,152 @@
+---
+name: connector-sdk
+description: Extend or modify the Apache Iggy Connectors SDK (`core/connectors/sdk/`). Use when adding a new `Schema` variant, a new `StreamDecoder`/`StreamEncoder`, a new `Error` variant, modifying the `Sink`/`Source`/`Transform` trait surface, the FFI macros, or the `retry`/`api`/`convert` modules. NOT for writing plugins - use `connector-sink` or `connector-source` for those.
+---
+
+# Extending the Apache Iggy Connectors SDK
+
+The SDK (`core/connectors/sdk/`) is the **stable contract** between the runtime and every plugin. Changes ripple to every sink/source in-tree and every third-party plugin. Treat the public surface as a versioned API.
+
+## File map
+
+```text
+sdk/src/
+├── lib.rs              Traits (Sink, Source, StreamDecoder, StreamEncoder),
+│                       Payload, Schema, ConnectorState, Error enum, FFI message structs.
+├── sink.rs             SinkContainer + sink_connector! macro (FFI plumbing).
+├── source.rs           SourceContainer + source_connector! macro (FFI plumbing).
+├── api.rs              ConnectorStatus, ConnectorStats (feature = "api").
+├── convert.rs          owned_value_to_serde_json (simd_json ⇄ serde_json bridge).
+├── log.rs              CallbackLayer for tracing across FFI.
+├── retry.rs            CircuitBreaker, HttpRetryMiddleware, exponential_backoff, jitter.
+├── decoders/           One per schema: json, raw, text, proto, flatbuffer, avro.
+├── encoders/           Mirror of decoders.
+└── transforms/         add_fields, delete_fields, update_fields, filter_fields,
+                        unwrap_envelope, proto_convert, flatbuffer_convert, avro_convert.
+```
+
+## Cardinal rules
+
+1. **Apache 2.0 license header** on every new file.
+2. **`Send + Sync`** on every public trait (FFI runs across thread pools).
+3. **`#[repr(C)]`** on every type that crosses FFI (`Schema`, `TopicMetadata`, `MessagesMetadata`, `RawMessage`, `ProducedMessages`, `ConsumedMessage`, `DecodedMessage`, etc. in `lib.rs`). Adding fields requires bumping the SDK version - existing plugins built against the old layout will misalign on `postcard::from_bytes`.
+4. **postcard** for FFI message serialization (handled by `SinkContainer::consume`, `SourceContainer`'s `handle_messages`). **MessagePack (`rmp_serde`)** for `ConnectorState`. **JSON** (`serde_json`) only for human-editable config that crosses FFI. Don't mix.
+5. **`simd_json::OwnedValue`** for JSON payloads, not `serde_json::Value`. Use `convert::owned_value_to_serde_json` as a bridge when interop is required.
+6. **`BTreeMap`** for headers - deterministic ordering. Never `HashMap` on the wire.
+7. **No breaking changes** to `Sink`/`Source`/`StreamDecoder`/`StreamEncoder`/`Transform` trait signatures without coordinating with all in-tree plugins in the same PR.
+
+## Adding a new `Schema` variant
+
+The `Schema` enum (in `lib.rs`) is `#[repr(C)]` - it crosses FFI. Touch points to update **in one PR**:
+
+1. `Schema` enum: add variant with `#[strum(to_string = "...")]` matching the `serde(rename_all="snake_case")` form.
+2. `Payload` enum: add a matching variant carrying the deserialized form.
+3. `Payload::try_into_vec` - consuming bytes-out path.
+4. `Payload::try_to_bytes` - **borrowing** bytes-out path. For non-trivial payloads (parsed trees), implement a no-clone serialization, not a `clone() + serialize`. See the `Payload::Json` arm for the canonical optimization.
+5. `Payload::Display`.
+6. `Schema::try_into_payload` - bytes → `Payload`.
+7. `Schema::decoder()` - factory returning `Arc<dyn StreamDecoder>`.
+8. `Schema::encoder()` - factory returning `Arc<dyn StreamEncoder>`.
+9. New `decoders/<name>.rs` and `encoders/<name>.rs`.
+10. Update `sdk/README.md` and `core/connectors/README.md` schema list.
+11. Tests: round-trip encode/decode, error paths.
+
+Miss any of these → silent failures at runtime (typically `Error::InvalidPayloadType` or surprising decoder behavior in plugin code).
+
+## Adding a `StreamDecoder` / `StreamEncoder`
+
+Pattern from `decoders/json.rs::JsonStreamDecoder`:
+
+```rust
+pub struct MyStreamDecoder;        // unit struct if stateless
+
+impl StreamDecoder for MyStreamDecoder {
+    fn schema(&self) -> Schema { Schema::MyFormat }
+    fn decode(&self, payload: Vec<u8>) -> Result<Payload, Error> {
+        // Decode payload bytes into Payload::MyFormat(...).
+        // Errors: Error::CannotDecode(Schema::MyFormat), Error::InvalidJsonPayload, etc.
+    }
+}
+```
+
+For **stateful** decoders (proto/avro/flatbuffer) holding schema descriptors:
+
+- Store the schema state directly in the struct (`config`, `message_descriptor`, `schema`). The instance is built once and wrapped in `Arc<dyn>` for sharing - it must be `Send + Sync` but does not need additional locking if construction-time loading is final.
+- Provide **two constructors** when schema loading can fail: lenient `new(config) -> Self` (logs + degrades) AND strict `try_new(config) -> Result<Self, Error>` (fail-fast). Plus a `Default` impl for the no-schema case. Canonical example: `sdk/src/decoders/avro.rs` exports all three (`AvroStreamDecoder::new`, `::try_new`, `Default`).
+- If you genuinely need to mutate the schema after construction (e.g., a `update_config` method), use `&mut self` plus `std::mem::replace(&mut self.config, new_config)` to swap without cloning the old value. Live pattern: `sdk/src/decoders/avro.rs::AvroStreamDecoder::update_config` and `sdk/src/encoders/avro.rs::AvroStreamEncoder::update_config`.
+- A fresh decoder instance is created via `Schema::decoder()` on each call (it returns `Arc<dyn StreamDecoder>`), so per-decoder caching of shared mutable state is the wrong abstraction.
+
+## Adding a new `Error` variant
+
+The `Error` enum (in `lib.rs`) is `Clone + PartialEq + Eq + Hash`. New variants must preserve these. Guidelines:
+
+- **Use existing variants first.** Only add a new one if the failure mode is distinct in handling, not just description. `InvalidConfigValue(String)` covers most "bad config" cases.
+- **Carry context as `String`** - don't add a struct unless multiple discrete fields are needed by callers programmatically.
+- **Document retry semantics in the docstring.** Existing variants (`PermanentHttpError`, `CatalogCommitError`, `TransactionApplyError`) document retry behavior - mirror that style.
+- **Place near related variants** to keep the enum readable top-to-bottom.
+
+## Modifying `Sink` / `Source` / `Transform` traits
+
+**Breaking changes.** Required process:
+
+1. Document migration in the SDK changelog (and `connectors/sdk/README.md`).
+2. Update every in-tree plugin in the same PR. CI builds them all.
+3. Bump SDK minor version.
+4. Note in PR description: dynamic plugins compiled against the old SDK version will fail to load with mismatched FFI symbols.
+
+Non-breaking additions (new default method, new struct field with `#[serde(default)]`, new variant on a non-exhaustive enum) are preferable.
+
+## FFI macros (`sink_connector!`, `source_connector!`)
+
+The macros (in `sink.rs` and `source.rs`) generate:
+
+- `iggy_<kind>_open(id, config_ptr, config_len, [state_ptr, state_len,] log_callback) -> i32`
+- `iggy_sink_consume(id, ...)` / `iggy_source_handle(id, callback) -> i32`
+- `iggy_<kind>_close(id) -> i32`
+- `iggy_<kind>_version() -> *const c_char` (static lifetime, from `env!("CARGO_PKG_VERSION")`)
+
+Invariants:
+
+- **Duplicate-ID guard** returns `-1` if the caller reopens an ID without closing first. Don't remove this - it prevents silent buffered-data loss.
+- `INSTANCES: Lazy<DashMap<u32, SinkContainer<$type>>>` (and `SourceContainer<$type>` mirror) is the only mutable global the macro introduces - keep it that way.
+- Return codes: `0` success, `-1` invalid call, `1` open failure. Don't repurpose.
+
+Changes to the FFI signature must update `runtime/src/main.rs::{SourceApi, SinkApi}` in the same PR.
+
+## `Payload::try_to_bytes(&self)` is non-negotiable for JSON
+
+Plugin authors call this on every consumed message. The implementation in `lib.rs::Payload::try_to_bytes` documents *why* it skips the deep `OwnedValue` clone - replacing `O(n) clone + O(n) serialize` with `O(n) serialize`. If you add a new variant requiring a parsed tree, do the same: serialize in place, don't clone.
+
+## Retry helpers (`retry.rs`)
+
+- `CircuitBreaker`: threshold + cooldown, `try_lock()` on the success path to avoid hot-path contention.
+- `HttpRetryMiddleware`: integrates with `reqwest-middleware`. Retries 429 + 5xx + network errors. Honors `Retry-After`.
+- `max_retries` = **total attempts** including the first try, not extra retries. Document if you change this convention.
+- New helpers must take `Duration` (not `u64 millis`) on the public API. Internal computation uses `humantime` parsing of `String`.
+
+## `ConnectorState`
+
+- Bytes are opaque - the wrapping type does not impose schema.
+- Serialization is MessagePack via `rmp_serde`. Compact, deterministic, well-supported in serde.
+- `serialize`/`deserialize` helpers return `Option<T>` and log on failure. **Failures are non-fatal** - design downstream code to tolerate fresh state.
+- Don't change the underlying format without coordinating with all sources.
+
+## Tests for SDK changes
+
+- Unit tests for any new pure function in the changed module.
+- Round-trip tests for new schemas/transforms (encode → decode == identity for JSON-equivalent payloads).
+- `sdk/tests/` integration tests when the change crosses module boundaries.
+
+## Before declaring done
+
+```text
+cargo fmt --all
+cargo sort --no-format --workspace
+cargo clippy -p iggy_connector_sdk --all-targets --all-features -- -D warnings
+cargo test -p iggy_connector_sdk --all-features
+
+# Rebuild all plugins to catch breaking-change leaks:
+cargo build -p iggy_connector_stdout_sink -p iggy_connector_random_source
+# If FFI signatures changed, also build the runtime:
+cargo build -p iggy-connectors
+```
diff --git a/.claude/skills/connector-sink/SKILL.md b/.claude/skills/connector-sink/SKILL.md
new file mode 100644
index 000000000..277d767ea
--- /dev/null
+++ b/.claude/skills/connector-sink/SKILL.md
@@ -0,0 +1,370 @@
+---
+name: connector-sink
+description: Author a new Apache Iggy connector sink plugin under `core/connectors/sinks/<name>_sink/`. Sinks consume messages from Apache Iggy streams and push them to an external system (DB, search engine, HTTP endpoint, object store). Load when creating, modifying, or reviewing a sink crate.
+---
+
+# Writing an Apache Iggy Connector Sink
+
+A **sink** is a Rust `cdylib` that implements `iggy_connector_sdk::Sink` and exposes FFI symbols via the `sink_connector!` macro. The runtime loads it as `.so`/`.dylib`/`.dll`, polls Apache Iggy streams on its behalf, runs the transform chain, decodes via the configured `Schema`, and hands the sink batches of `ConsumedMessage`. The sink is responsible for getting them to the external system reliably and efficiently.
+
+## Reference exemplars
+
+| Use case | Plugin |
+| ---------- | -------- |
+| Read this first - minimal shape | `sinks/stdout_sink/src/lib.rs` (~100 LOC) |
+| Real-world DB integration with idempotency + transient detection | `sinks/postgres_sink/src/lib.rs` (paired with full integration tests under `core/integration/tests/connectors/postgres/`) |
+| Rich config validation + retry middleware + multiple batch modes | `sinks/http_sink/src/lib.rs` |
+| Backend-specific idioms | `sinks/mongodb_sink/`, `elasticsearch_sink/`, `iceberg_sink/` |
+
+Always read the relevant exemplar end-to-end before writing - the patterns are intentionally repetitive across plugins.
+
+## Cargo.toml skeleton
+
+```toml
+# Apache 2.0 header (copy verbatim from any existing sink Cargo.toml)
+[package]
+name = "iggy_connector_<name>_sink"
+version = "0.4.1-edge.1"          # match the version most other sinks use; check by grepping `version =` in sibling Cargo.toml files
+edition = "2024"
+license = "Apache-2.0"
+publish = false
+# ...keywords, description, repository, homepage all identical to existing sinks
+
+[package.metadata.cargo-machete]
+ignored = ["dashmap", "once_cell"]   # the sink_connector! macro uses them - machete can't see through macros
+
+[lib]
+crate-type = ["cdylib", "lib"]       # cdylib = runtime-loadable; lib = unit tests + reuse
+
+[dependencies]
+async-trait        = { workspace = true }
+dashmap            = { workspace = true }
+iggy_connector_sdk = { workspace = true }
+once_cell          = { workspace = true }
+serde              = { workspace = true }
+tokio              = { workspace = true }
+tracing            = { workspace = true }
+# + your client crate (reqwest, sqlx, mongodb, ...)
+```
+
+Run `cargo sort --no-format --workspace` after edits.
+
+## src/lib.rs skeleton
+
+Code reads top to bottom like a book. Public types first, then `impl`, then private helpers. Don't make the reader jump.
+
+```rust
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements... */   // full Apache header
+
+use async_trait::async_trait;
+use iggy_connector_sdk::{
+    ConsumedMessage, Error, MessagesMetadata, Sink, TopicMetadata, sink_connector,
+};
+use serde::{Deserialize, Serialize};
+use std::str::FromStr;
+use std::time::Duration;
+use tokio::sync::Mutex;
+use tracing::{debug, error, info, warn};
+
+sink_connector!(MySink);   // generates FFI symbols + version export
+
+const CONNECTOR_NAME: &str = "My sink";
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct MySinkConfig {
+    pub endpoint: String,
+    pub batch_size: Option<u32>,
+    pub max_retries: Option<u32>,
+    pub retry_delay: Option<String>,        // humantime, e.g. "500ms"
+    pub verbose_logging: Option<bool>,      // plugin-level verbose - mirror the runtime's `verbose` flag
+    // Every runtime-tunable field is Option<T>; defaults applied in new()
+}
+
+#[derive(Debug)]
+pub struct MySink {
+    id: u32,
+    config: MySinkConfig,
+    batch_size: usize,
+    max_retries: u32,
+    retry_delay: Duration,
+    verbose: bool,
+    client: Option<Client>,
+    state: Mutex<State>,
+}
+
+#[derive(Debug)]
+struct State {
+    messages_processed: u64,
+    errors: u64,
+}
+
+impl MySink {
+    pub fn new(id: u32, config: MySinkConfig) -> Self {
+        let batch_size = config.batch_size.unwrap_or(100) as usize;
+        let max_retries = config.max_retries.unwrap_or(3);
+        let retry_delay = config
+            .retry_delay
+            .as_deref()
+            .and_then(|raw| humantime::Duration::from_str(raw).ok().map(|d| *d))
+            .unwrap_or_else(|| {
+                warn!("Invalid retry_delay for {CONNECTOR_NAME} ID: {id}, defaulting to 500ms");
+                Duration::from_millis(500)
+            });
+        let verbose = config.verbose_logging.unwrap_or(false);
+        Self {
+            id,
+            config,
+            batch_size,
+            max_retries,
+            retry_delay,
+            verbose,
+            client: None,
+            state: Mutex::new(State { messages_processed: 0, errors: 0 }),
+        }
+    }
+}
+
+#[async_trait]
+impl Sink for MySink {
+    async fn open(&mut self) -> Result<(), Error> {
+        let client = build_client(&self.config)
+            .await
+            .map_err(|e| Error::InitError(format!("client build failed: {e}")))?;
+        client.ping()
+            .await
+            .map_err(|e| Error::InitError(format!("connectivity check failed: {e}")))?;
+        self.client = Some(client);
+        info!(
+            "Opened {CONNECTOR_NAME} connector ID: {}, endpoint: {}",
+            self.id, self.config.endpoint
+        );
+        Ok(())
+    }
+
+    async fn consume(
+        &self,
+        topic_metadata: &TopicMetadata,
+        messages_metadata: MessagesMetadata,
+        messages: Vec<ConsumedMessage>,
+    ) -> Result<(), Error> {
+        let Some(client) = self.client.as_ref() else {
+            return Err(Error::InitError("client not initialized".into()));
+        };
+
+        if self.verbose {
+            info!(
+                "{CONNECTOR_NAME} ID: {} consuming {} messages from stream: {}, topic: {}, offset: {}, current_offset: {}",
+                self.id, messages.len(), topic_metadata.stream, topic_metadata.topic,
+                messages_metadata.partition_id, messages_metadata.current_offset
+            );
+        } else {
+            debug!(
+                "{CONNECTOR_NAME} ID: {} consuming {} messages",
+                self.id, messages.len()
+            );
+        }
+
+        let mut last_err: Option<Error> = None;
+        for batch in messages.chunks(self.batch_size) {
+            match self.send_batch(client, batch).await {
+                Ok(()) => { /* counter */ }
+                Err(Error::PermanentHttpError(message)) => {
+                    error!(
+                        "{CONNECTOR_NAME} ID: {} dropping batch (permanent): {message}",
+                        self.id
+                    );
+                }
+                Err(error) => {
+                    last_err = Some(error);
+                }
+            }
+        }
+        match last_err {
+            Some(error) => Err(error),
+            None => Ok(()),
+        }
+    }
+
+    async fn close(&mut self) -> Result<(), Error> {
+        // Adapt to your client: sqlx pool needs `.close().await`; mongodb/elasticsearch/reqwest just drop.
+        if let Some(client) = self.client.take() {
+            let _ = client; // drop; replace with `client.close().await;` if your client requires it
+        }
+        let state = self.state.lock().await;
+        info!(
+            "Closed {CONNECTOR_NAME} connector ID: {}, processed: {}, errors: {}",
+            self.id, state.messages_processed, state.errors
+        );
+        Ok(())
+    }
+}
+
+// Private helpers below this line. Each is referenced from the impl above.
+async fn build_client(config: &MySinkConfig) -> Result<Client, ClientError> { /* ... */ }
+```
+
+## Hard rules
+
+### Lifecycle
+
+- `Sink::consume` takes **`&self`** - never `&mut self`. Mutable state goes behind `tokio::sync::Mutex` / `AtomicU64`. **Prefer atomics for counters** - canonical example: `sinks/mongodb_sink/src/lib.rs` uses `messages_processed: AtomicU64` and `insertion_errors: AtomicU64` and avoids a state lock entirely on the hot path. Use `Mutex<State>` only when multiple fields must update atomically together.
+- `Sink::open` builds the client AND tests connectivity. Fail fast with `Error::InitError`.
+- `Sink::close` flushes + drops resources. Take ownership of `client: Option<Client>` via `.take()`. Whether you then call an explicit close depends on the client crate: sqlx pools have `.close().await` (see `postgres_sink::close`); MongoDB, Elasticsearch, and reqwest clients have no explicit close - dropping is enough (see `mongodb_sink::close` which just calls `self.client.take()`, and `elasticsearch_sink` which assigns `self.client = None;`). Log final stats either way.
+
+### The `verbose` flag (two layers)
+
+- **Runtime-level**: `verbose: bool` lives on `SinkConfig` (TOML top-level field, see `runtime/src/configs/connectors.rs::SinkConfig`). The runtime promotes its own per-batch `debug!` logs to `info!` when set. The sink does not need to read this field directly - it just receives bytes.
+- **Plugin-level**: Optionally expose a similar toggle inside your `plugin_config` (convention: `verbose_logging: Option<bool>` - see `sinks/postgres_sink/src/lib.rs::PostgresSinkConfig::verbose_logging`). Use it to upgrade your own per-batch `debug!` logs to `info!` so operators can opt into deep tracing without recompiling.
+- Default both to `false`. Verbose logs include batch size, offset ranges, latency, header counts.
+
+### The `benchmark` flag
+
+`SinkConfig` carries `benchmark: bool` (`#[serde(default)]`, defaults to
+`false`), env-addressable via `IGGY_CONNECTORS_SINK_<KEY>_BENCHMARK=true`.
+When `true`, the runtime emits one `info!` line per batch on tracing target
+`iggy_connectors::benchmark` with stage timings in microseconds (`prepare_us`,
+`ffi_us`, `total_us`). The sink itself does not read the flag - instrumentation
+lives in `runtime/src/sink.rs`. The corresponding
+`iggy_connector_stage_duration_seconds` histogram (stages `Prepare`, `Ffi`,
+`Total`) is always populated regardless of the flag, so Prometheus dashboards
+work without enabling text events. Include `benchmark = false` in the sample
+TOML so operators discover the option.
+
+### Config
+
+- Every runtime-tunable field is `Option<T>` with a default applied in `new()`. Forward-compat: adding a field doesn't break existing TOML.
+- Durations: `Option<String>`, parsed via `humantime::Duration` in `new()`. Two equivalent idioms in-tree, pick one:
+  - **Inline parse** (used by `sources/random_source`, `sources/postgres_source`): `use humantime::Duration as HumanDuration;` then `HumanDuration::from_str(&raw).map(|d| *d).unwrap_or_else(|_| { warn!(...); fallback })`.
+  - **Local `parse_duration` helper** (used by `sinks/http_sink::parse_duration` and `sdk/src/retry.rs::parse_duration`): `fn parse_duration(input: Option<&str>, default: &str) -> Duration`. Use when several durations need the same fallback logic.
+  Either way, fall back to a default on parse failure with a `warn!` - never panic. We do **not** use `humantime_serde`.
+- **Secrets**: any credential-bearing field (connection strings, API keys,
+  bearer tokens, AWS keys) must be `SecretString` from the `secrecy` crate,
+  with the workspace serde wrapper applied on the field. The wrapper redacts
+  the value during `Debug`/`Display` and during serialization (the `/stats`
+  HTTP surface uses serialization), preventing accidental leaks via
+  `info!("{:?}", config)` or operator dumps. Expose with `.expose_secret()`
+  only at the call site where the underlying client needs the raw value.
+  Plain `String` for a credential is a review-blocker. Pattern (from
+  `sinks/postgres_sink/src/lib.rs::PostgresSinkConfig`):
+
+  ```rust
+  use secrecy::{ExposeSecret, SecretString};
+
+  #[derive(Debug, Clone, Serialize, Deserialize)]
+  pub struct MySinkConfig {
+      #[serde(serialize_with = "iggy_common::serde_secret::serialize_secret")]
+      pub connection_string: SecretString,
+      // ...other fields
+  }
+
+  // At the call site:
+  let pool = PgPoolOptions::new()
+      .connect(self.config.connection_string.expose_secret())
+      .await?;
+  ```
+
+  In-tree uses: `sinks/{postgres,mongodb,elasticsearch,influxdb,delta}_sink`, `sources/{postgres,elasticsearch,influxdb}_source`.
+- **Conflict resolution**: if two config fields can be in an invalid relative ordering, fix it in `new()` and `warn!` - don't return an error. Live pattern: `http_sink` uses `std::mem::swap(&mut retry_delay, &mut max_retry_delay)` when `retry_delay > max_retry_delay` to avoid an `ExponentialBackoff` panic downstream.
+- Validation order: structural validation in `new()`, connectivity validation in `open()`, **never in `consume()`**.
+
+### Payloads (efficiency-critical)
+
+This runs on every message. Patterns from existing plugins:
+
+- Dispatch on `messages_metadata.schema` and the `Payload` enum variant. Handle `Json`, `Raw`, `Text` at minimum. Treat unsupported as `Error::InvalidPayloadType` or fall back to base64 (see `sinks/elasticsearch_sink/src/lib.rs`).
+- **For `Payload::Json`, call `try_to_bytes(&self)`** - serializes the `OwnedValue` tree in a single pass without cloning. Documented and implemented in `sdk/src/lib.rs::Payload::try_to_bytes`. Never `payload.clone().try_into_vec()`.
+- **To take a payload out of `ConsumedMessage` without cloning**, use `std::mem::replace(&mut message.payload, Payload::Raw(vec![]))`. Live pattern in `sinks/http_sink/src/lib.rs` (used inside `send_individual`, `send_ndjson`, `send_json_array`). Copy this verbatim - it's the standard.
+- **Pre-allocate per-batch buffers** with `Vec::with_capacity(messages.len())` (or `messages.len() * <factor>` for serialized bodies). Used in `postgres_sink`, `mongodb_sink`, `quickwit_sink`, `elasticsearch_sink`, `http_sink`. Skipping this wastes reallocations on every batch.
+
+### Headers
+
+- `message.headers: Option<BTreeMap<HeaderKey, HeaderValue>>`. Check `.is_empty()` before iterating - the runtime treats empty as `None`.
+- For binary header values use `v.as_raw()` + base64; for text use `v.to_string_value()`. See `http_sink::EncodedHeader`.
+- `BTreeMap` for deterministic ordering. Don't collect into `HashMap`.
+
+### Errors
+
+Map underlying-library errors into SDK variants:
+
+| Scenario | SDK variant | Retry? |
+| ---------- | ------------- | -------- |
+| Init/connectivity failure | `Error::InitError` | n/a (fails open) |
+| Bad config value | `Error::InvalidConfigValue(field)` | n/a |
+| Single message fails schema validation | `Error::InvalidRecordValue(reason)` | no - skip + log |
+| Transient backend (5xx, conn reset, lock timeout) | `Error::HttpRequestFailed` / `Error::Connection` / `Error::CannotStoreData` | yes |
+| Permanent 4xx, schema mismatch, constraint violation | `Error::PermanentHttpError` / `Error::SchemaMismatch` | **no** - retrying bad data trips circuit breakers |
+| I/O failure mid-write (parquet/iceberg) | `Error::WriteFailure` | caller decides |
+| Catalog commit failure (Iceberg) | `Error::CatalogCommitError` | **no - not idempotent** |
+
+### Retry
+
+Two valid patterns in-tree - pick based on how much control you need:
+
+- **Use SDK helpers** for startup probes and simple request paths: `iggy_connector_sdk::retry::check_connectivity_with_retry(...)` (used in plugin `open()`), or wrap your `reqwest::Client` with `iggy_connector_sdk::retry::HttpRetryMiddleware` for the SDK's default 429/5xx/network policy.
+- **Use `reqwest-middleware` + `reqwest_retry::RetryTransientMiddleware` directly** when you need custom `RetryableStrategy` (e.g., to honor `success_status_codes`, or apply per-status decisions). Canonical example: `sinks/http_sink/src/lib.rs` defines its own `HttpSinkRetryStrategy` and wires it via `RetryTransientMiddleware::new_with_policy_and_strategy(retry_policy, retry_strategy)`.
+- For non-HTTP clients (sqlx, mongodb), write `is_transient_error(&e)` mapping driver-specific codes - see `sinks/postgres_sink/src/lib.rs::is_transient_error` for Postgres SQLSTATEs (`40001`, `40P01`, `57P01-03`, `08000/03/06`).
+- Backoff helpers: `iggy_connector_sdk::retry::exponential_backoff(base, attempt, max)` + `jitter()`.
+- Cap retries. Default cap: 3 total attempts (not 3 retries on top of 1).
+
+### Idempotency
+
+The runtime retries on any `Err`, so the same batch can be redelivered. The strength of the guarantee varies by sink - what's actually implemented in tree:
+
+- **Postgres** (`postgres_sink::build_batch_insert_query`): `id DECIMAL(39, 0) PRIMARY KEY` enforces uniqueness, but the INSERT is plain `INSERT INTO ... VALUES (...)` - no `ON CONFLICT` clause. A duplicate retry triggers a `23505` constraint violation, which `is_transient_error` does NOT mark as transient, so the error propagates. Adding `ON CONFLICT (id) DO NOTHING` is a known improvement.
+- **MongoDB** (`mongodb_sink`): composite `_id` from `build_composite_document_id(stream:topic:partition:message_id)`, written via `insert_many(docs).ordered(false)`. Duplicate-key errors per-document don't abort the batch - effective idempotency under retry.
+- **Elasticsearch** (`elasticsearch_sink::bulk_index_documents`): bulk action specifies only `_index`, **no `_id`** - Elasticsearch auto-generates document ids, so a retry creates new docs. NOT idempotent. Plugins extending this should add `"_id"` to the bulk action header.
+- **HTTP** (`http_sink`): endpoint-dependent. Document the assumption in the plugin README; the SDK does not enforce.
+- **Iceberg** (`iceberg_sink`): transactional commit. `Error::CatalogCommitError` (see SDK `lib.rs::Error`) documents that the transaction is consumed on `commit()` and rebuild-then-retry can duplicate data; callers must check the catalog first.
+
+When writing a new sink, prefer dedup-on-write using the message `id` field. Match a working in-tree example (mongo upsert-style is the cleanest).
+
+### Batching
+
+- Default `batch_size: 100`. Tune per-backend.
+- Chunk via `messages.chunks(self.batch_size)`. Do not buffer across `consume()` calls - the runtime already batches at the consumer-poll boundary.
+- For HTTP backends, support multiple batch modes when applicable (individual / ndjson / json_array / raw) - see `http_sink::BatchMode`.
+
+### Logging
+
+```rust
+info!("Opened <connector> connector ID: {}, endpoint: <redacted>", self.id);
+debug!("Processing batch of {} messages, offset: {}", batch.len(), offset);
+warn!("Retry {attempt}/{max} for <connector> ID: {}, reason: {error}", self.id);
+error!("Failed to <op> for <connector> ID: {}, error: {error}", self.id);
+info!("Closed <connector> connector ID: {}, processed: {}", self.id, count);
+```
+
+Use literal API field names as labels (`offset=`, `current_offset=`) - don't invent.
+
+## Common pitfalls
+
+1. **Missing `[lib] crate-type = ["cdylib", "lib"]`** - the runtime can't dlopen a regular rlib.
+2. **Cloning the whole `Payload::Json`** to serialize - use `try_to_bytes(&self)`.
+3. **Holding `Mutex` across `.await`** when the locked region does I/O.
+4. **`&mut self` on `consume`** - won't compile; you actually need interior mutability.
+5. **Returning the first error and dropping subsequent batches** - track `last_err` and process all, then return.
+6. **Forgetting to map `PermanentHttpError`** - retries hammer the backend with bad data.
+7. **Mutating config in `consume()`** - config is a snapshot from `new()`. Reload requires runtime restart.
+8. **Logging the connection string** - never log secrets. Sinks redact URLs at construction (`http_sink::sanitize_url_for_log` populates an `HttpSink.log_url` field that is safe to print).
+
+## Tests
+
+Unit tests at EOF of `src/lib.rs` (see `connector-testing` skill for the BDD naming + `test_config()` helper conventions).
+
+Real-infra integration tests live under `core/integration/tests/connectors/<backend>/` and use the `#[iggy_harness]` macro plus a backend-specific fixture that spins up a Docker container via `testcontainers-modules`. **Plugins that integrate with external services must have an integration test.** The reference is `core/integration/tests/connectors/postgres/postgres_sink.rs` paired with `core/integration/tests/connectors/fixtures/postgres/`.
+
+## Before declaring done
+
+```text
+cargo fmt --all
+cargo sort --no-format --workspace
+cargo clippy -p iggy_connector_<name>_sink --all-targets -- -D warnings
+cargo test -p iggy_connector_<name>_sink
+
+# If you added integration tests (filter by test name; the integration crate has no
+# per-area --test target, all tests share one binary via tests/mod.rs):
+cargo test -p integration -- connectors::<backend>::<test_name>
+```
+
+Update `core/connectors/sinks/README.md` and add a sample TOML in `core/connectors/runtime/example_config/connectors/`.
diff --git a/.claude/skills/connector-source/SKILL.md b/.claude/skills/connector-source/SKILL.md
new file mode 100644
index 000000000..24641e311
--- /dev/null
+++ b/.claude/skills/connector-source/SKILL.md
@@ -0,0 +1,346 @@
+---
+name: connector-source
+description: Author a new Apache Iggy connector source plugin under `core/connectors/sources/<name>_source/`. Sources poll an external system (DB, API, queue) and produce messages into Apache Iggy streams. Load when creating, modifying, or reviewing a source crate.
+---
+
+# Writing an Apache Iggy Connector Source
+
+A **source** is a Rust `cdylib` that implements `iggy_connector_sdk::Source` and exposes FFI symbols via the `source_connector!` macro. The runtime calls `poll()` in a loop, applies the transform chain, encodes via the configured `Schema`, sends the batch to Apache Iggy, and persists the returned `ConnectorState` to disk after every successful send.
+
+## Reference exemplars
+
+| Use case | Plugin |
+| ---------- | -------- |
+| Read this first - minimal shape with the four canonical state tests | `sources/random_source/src/lib.rs` |
+| Real-world DB integration with multiple consumption modes, cursor + restart tests | `sources/postgres_source/src/lib.rs` (paired with `core/integration/tests/connectors/postgres/postgres_source.rs` and `restart.rs`) |
+| External API with scroll cursor | `sources/elasticsearch_source/src/lib.rs` |
+| Time-series scan | `sources/influxdb_source/src/lib.rs` |
+
+## Cargo.toml skeleton
+
+Identical to a sink's `Cargo.toml` (see `connector-sink` skill) - only the crate name suffix differs (`iggy_connector_<name>_source`) and the upstream client dep changes. Same `[lib] crate-type = ["cdylib", "lib"]`, same `cargo-machete` ignored list.
+
+## src/lib.rs skeleton
+
+Code reads top to bottom like a book. Public types first, `impl Source` afterward, helpers below.
+
+```rust
+/* Apache 2.0 header */
+
+use async_trait::async_trait;
+use iggy_connector_sdk::{
+    ConnectorState, Error, ProducedMessage, ProducedMessages, Schema, Source, source_connector,
+};
+use serde::{Deserialize, Serialize};
+use std::str::FromStr;
+use std::time::Duration;
+use tokio::sync::Mutex;
+use tokio::time::sleep;
+use tracing::{debug, error, info, warn};
+
+source_connector!(MySource);
+
+const CONNECTOR_NAME: &str = "My source";
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct MySourceConfig {
+    pub endpoint: String,
+    pub poll_interval: Option<String>,      // humantime, "10s" default
+    pub batch_size: Option<u32>,
+    pub max_retries: Option<u32>,
+    pub retry_delay: Option<String>,
+    pub verbose_logging: Option<bool>,      // plugin-level verbose - mirror runtime SourceConfig.verbose
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+struct State {
+    cursor: Option<String>,                 // resume token (WAL LSN, scroll id, timestamp, ...)
+    last_offset: u64,
+    messages_produced: u64,
+}
+
+#[derive(Debug)]
+pub struct MySource {
+    id: u32,
+    config: MySourceConfig,
+    poll_interval: Duration,
+    verbose: bool,
+    client: Option<Client>,
+    state: Mutex<State>,
+}
+
+impl MySource {
+    pub fn new(id: u32, config: MySourceConfig, state: Option<ConnectorState>) -> Self {
+        let raw_interval = config.poll_interval.clone().unwrap_or_else(|| "10s".into());
+        let poll_interval = humantime::Duration::from_str(&raw_interval)
+            .map(|d| *d)
+            .unwrap_or_else(|_| {
+                warn!("Invalid poll_interval for {CONNECTOR_NAME} ID: {id}, defaulting to 10s");
+                Duration::from_secs(10)
+            });
+
+        let verbose = config.verbose_logging.unwrap_or(false);
+
+        let restored = state
+            .and_then(|s| s.deserialize::<State>(CONNECTOR_NAME, id))
+            .inspect(|s| info!(
+                "Restored state for {CONNECTOR_NAME} ID: {id}, last_offset: {}, cursor: {:?}",
+                s.last_offset, s.cursor
+            ));
+
+        Self {
+            id,
+            config,
+            poll_interval,
+            verbose,
+            client: None,
+            state: Mutex::new(restored.unwrap_or(State {
+                cursor: None,
+                last_offset: 0,
+                messages_produced: 0,
+            })),
+        }
+    }
+}
+
+#[async_trait]
+impl Source for MySource {
+    async fn open(&mut self) -> Result<(), Error> {
+        let client = build_client(&self.config)
+            .await
+            .map_err(|e| Error::InitError(format!("client build failed: {e}")))?;
+        self.client = Some(client);
+        info!(
+            "Opened {CONNECTOR_NAME} connector ID: {}, endpoint: {}",
+            self.id, self.config.endpoint
+        );
+        Ok(())
+    }
+
+    async fn poll(&self) -> Result<ProducedMessages, Error> {
+        sleep(self.poll_interval).await;            // sleep first - backpressure
+
+        let cursor = { self.state.lock().await.cursor.clone() };   // brief read
+
+        let fetched = self.fetch_since(cursor.as_deref()).await?;  // no lock held
+
+        let mut messages = Vec::with_capacity(fetched.len());
+        let mut next_cursor = None;
+        for row in fetched {
+            let payload = simd_json::to_vec(&row).map_err(|e|
+                Error::Serialization(format!("row serialize: {e}"))
+            )?;
+            messages.push(ProducedMessage {
+                id: Some(row.id as u128),                  // natural ID for idempotency
+                checksum: None,
+                timestamp: None,
+                origin_timestamp: Some(row.created_at_ns),
+                headers: None,
+                payload,
+            });
+            next_cursor = Some(row.cursor_value);
+        }
+
+        if self.verbose {
+            info!(
+                "{CONNECTOR_NAME} ID: {} produced {} messages, next cursor: {:?}",
+                self.id, messages.len(), next_cursor
+            );
+        }
+
+        let persisted = {                                  // brief write
+            let mut state = self.state.lock().await;
+            state.messages_produced += messages.len() as u64;
+            if let Some(c) = next_cursor {
+                state.cursor = Some(c);
+            }
+            ConnectorState::serialize(&*state, CONNECTOR_NAME, self.id)
+        };
+
+        Ok(ProducedMessages {
+            schema: Schema::Json,
+            messages,
+            state: persisted,
+        })
+    }
+
+    async fn close(&mut self) -> Result<(), Error> {
+        // Adapt to your client: sqlx pool has `.close().await` (see postgres_source::close);
+        // elasticsearch/reqwest clients just drop.
+        if let Some(client) = self.client.take() {
+            let _ = client; // drop; or `client.close().await;` for sqlx pools
+        }
+        let state = self.state.lock().await;
+        info!(
+            "Closed {CONNECTOR_NAME} connector ID: {}, total produced: {}",
+            self.id, state.messages_produced
+        );
+        Ok(())
+    }
+}
+
+// Private helpers below.
+async fn build_client(config: &MySourceConfig) -> Result<Client, ClientError> { /* ... */ }
+```
+
+## Hard rules
+
+### `poll()` signature is `&self`
+
+The macro shares the source as `Arc<T>` across the FFI callback and forwarding loop. The signature is `async fn poll(&self) -> ...` - any mutable state goes behind `tokio::sync::Mutex`. **This is the single most common new-contributor mistake.**
+
+### Lock discipline
+
+The fetch path holds the upstream client for the duration of I/O. **Never hold the state `Mutex` across upstream I/O.** Canonical pattern (matches `sources/postgres_source/src/lib.rs::poll_tables`):
+
+```rust
+let cursor = { self.state.lock().await.cursor.clone() };   // brief read
+let rows = client.query(&sql, &[&cursor]).await?;           // no lock held
+let persisted = {                                           // brief write
+    let mut state = self.state.lock().await;
+    state.cursor = Some(new_cursor);
+    ConnectorState::serialize(&*state, CONNECTOR_NAME, self.id)
+};
+```
+
+### State persistence
+
+- `ConnectorState` is `Vec<u8>` serialized via MessagePack (`rmp_serde`). Use `ConnectorState::serialize(&state, NAME, id)` and `ConnectorState::deserialize::<State>(NAME, id)` - both return `Option<T>` and **log on failure (non-fatal)**.
+- The runtime saves to `{state_path}/source_{key}.state` only after a successful Iggy send. On a crash between `poll()` returning and the runtime persisting the save, the **same cursor will be returned on the next poll** - downstream must tolerate at-least-once.
+- **Always return state in every `ProducedMessages`**, including empty polls. Empty-result polls still need to advance watermarks (timestamp source) or affirm "nothing new."
+- Keep `State` small - rewritten after every batch. No unbounded vecs.
+
+### Sleep first
+
+`poll()` must `sleep(self.poll_interval).await` before any work. Without it, an empty source spins a CPU.
+
+### Schema selection
+
+Match `ProducedMessages.schema` to the bytes in `messages[i].payload`:
+
+- JSON-serialized rows → `Schema::Json`
+- Already-protobuf bytes → `Schema::Proto`
+- Already-avro bytes → `Schema::Avro`
+- Opaque → `Schema::Raw`
+
+### Secrets in plugin config
+
+Any credential-bearing field (connection strings, API keys, bearer tokens, AWS keys) must be `SecretString` from the `secrecy` crate, with the workspace serde wrapper applied so `Debug` and serialization both redact. The runtime exposes plugin configs over the `/stats` HTTP surface via serialization, so a plain `String` would leak the secret to anyone who can hit the endpoint. Plain `String` for a credential is a review-blocker. Pattern (matches `sources/postgres_source/src/lib.rs::Postg [...]
+
+```rust
+use secrecy::{ExposeSecret, SecretString};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MySourceConfig {
+    #[serde(serialize_with = "iggy_common::serde_secret::serialize_secret")]
+    pub connection_string: SecretString,
+    // ...other fields
+}
+
+// At the call site (inside open()/poll()):
+let pool = PgPoolOptions::new()
+    .connect(self.config.connection_string.expose_secret())
+    .await?;
+```
+
+In-tree uses: `sources/{postgres,elasticsearch,influxdb}_source`, `sinks/{postgres,mongodb,elasticsearch,influxdb,delta}_sink`.
+
+### `verbose` flag (two layers)
+
+- **Runtime-level**: `verbose: bool` on `SourceConfig` - the runtime upgrades its own per-batch `debug!` to `info!`. The source does not read it.
+- **Plugin-level**: Mirror with `verbose_logging: Option<bool>` in your plugin_config. Use it to upgrade source-internal `debug!` (per-poll counts, cursor advancement) to `info!`. Default false.
+
+### The `benchmark` flag
+
+`SourceConfig` carries `benchmark: bool` (`#[serde(default)]`, defaults to
+`false`), env-addressable via `IGGY_CONNECTORS_SOURCE_<KEY>_BENCHMARK=true`.
+When `true`, the runtime emits one `info!` line per batch on tracing target
+`iggy_connectors::benchmark` with stage timings in microseconds (`decode_us`,
+`prepare_us`, `iggy_send_us`, `state_save_us`, `total_us`). The source itself
+does not read the flag - instrumentation lives in `runtime/src/source.rs`.
+The corresponding `iggy_connector_stage_duration_seconds` histogram (stages
+`Decode`, `Prepare`, `IggySend`, `StateSave`, `Total`) is always populated
+regardless of the flag, so Prometheus dashboards work without enabling text
+events. Include `benchmark = false` in the sample TOML so operators discover
+the option.
+
+### IDs and timestamps
+
+- `ProducedMessage.id: Option<u128>` - set when there is a natural ID (DB primary key, document id). Apache Iggy can dedupe on this.
+- `origin_timestamp: Option<u64>` - source-system event time in nanoseconds. Lets downstream sinks reason about lag.
+- `timestamp` and `checksum` are Iggy-side - leave `None`.
+
+### Concurrency
+
+- The runtime spawns ONE `poll()` task per source. No concurrent `poll()` execution.
+- Don't spawn your own long-running Tokio tasks - the runtime owns the lifecycle, orphans survive `close()`.
+
+### Errors
+
+| Scenario | Variant |
+| ---------- | --------- |
+| Bad config in `new()`/`open()` | `Error::InitError` |
+| Cannot reach external system at startup | `Error::InitError` or `Error::Connection` |
+| Transient fetch failure (retry-worthy) | `Error::Connection` or `Error::HttpRequestFailed` |
+| Permanent fetch failure (auth, schema gone) | `Error::PermanentHttpError` |
+| Row failed to serialize | `Error::Serialization(...)` |
+| State serialization failed | log + skip (non-fatal) |
+
+Returning `Err` from `poll()` is **only logged** by the SDK's FFI bridge
+(`sdk/src/source.rs::handle_messages`) - the loop continues and the next
+`poll()` is still called. The connector status does NOT flip to `Error` from a
+poll failure. Status `Error` is set by the runtime only on transform/encode
+failure, Iggy send failure, or state save failure (see
+`runtime/src/source.rs::source_forwarding_loop` calls to
+`context.sources.set_error`). If you need a poll failure to surface as
+connector unhealth, raise it through the metric counter (which `runtime`
+reads) or escalate to `Error::InitError` from `open()`.
+
+### Logging
+
+```rust
+info!("Opened <connector> connector ID: {}, endpoint: {}", self.id, ...);
+info!("Restored state for <connector> ID: {id}, cursor: {:?}", ...);
+debug!("Polled {} rows for <connector> ID: {}", rows.len(), self.id);
+warn!("Transient fetch failure for <connector> ID: {}, will retry: {error}", self.id);
+error!("Failed to <op> for <connector> ID: {}, error: {error}", self.id);
+info!("Closed <connector> connector ID: {}, total produced: {}", self.id, ...);
+```
+
+Iggy consumer-loop labels use literal API names: `offset=`, `current_offset=`. Don't invent labels.
+
+## Common pitfalls
+
+1. **`async fn poll(&mut self)`** - won't compile. Use `&self` + `Mutex<State>`.
+2. **Holding `state.lock()` across the fetch I/O** - blocks `close()`, causes shutdown timeouts.
+3. **Forgetting to sleep** - 100% CPU on idle source.
+4. **Returning state only on success** - state should also advance on empty polls.
+5. **Unbounded data in `State`** - rewritten every batch; keep O(constant).
+6. **`std::sync::Mutex`** - blocks the executor. Use `tokio::sync::Mutex`.
+7. **Not setting `ProducedMessage.id`** when a stable ID exists - loses idempotency.
+8. **Spawning side tasks** - the runtime owns the scheduler.
+
+## Tests
+
+### Unit tests
+
+Mandatory four canonical state tests (see `connector-testing` skill for full pattern). Copy from `sources/random_source/src/lib.rs::tests`. Plus tests for config defaults, payload building, schema selection.
+
+### Integration tests (real infra)
+
+For any source that reads from a real external system, add tests under `core/integration/tests/connectors/<backend>/`. The pattern uses `#[iggy_harness]` plus a `TestFixture` backed by `testcontainers-modules`. Reference: `core/integration/tests/connectors/postgres/postgres_source.rs` (multiple consumption-mode tests) and `restart.rs` (state survives restart).
+
+## Before declaring done
+
+```text
+cargo fmt --all
+cargo sort --no-format --workspace
+cargo clippy -p iggy_connector_<name>_source --all-targets -- -D warnings
+cargo test -p iggy_connector_<name>_source
+
+# If you added integration tests (filter by test name; the integration crate has no
+# per-area --test target, all tests share one binary via tests/mod.rs):
+cargo test -p integration -- connectors::<backend>::<test_name>
+```
+
+Update `core/connectors/sources/README.md` and add a sample TOML in `core/connectors/runtime/example_config/connectors/`.
diff --git a/.claude/skills/connector-testing/SKILL.md b/.claude/skills/connector-testing/SKILL.md
new file mode 100644
index 000000000..ba2bf1798
--- /dev/null
+++ b/.claude/skills/connector-testing/SKILL.md
@@ -0,0 +1,336 @@
+---
+name: connector-testing
+description: Write tests for Apache Iggy connectors - sinks, sources, transforms, SDK, runtime. Covers BDD unit-test naming, the canonical source state round-trip tests, and the real-infra integration test layout under `core/integration/tests/connectors/` with `testcontainers-modules` + `#[iggy_harness]`. Load when writing or reviewing tests in `core/connectors/` or `core/integration/tests/connectors/`.
+---
+
+# Testing Apache Iggy Connectors
+
+There are **two distinct test layers** in this codebase. Use both - they catch different bugs.
+
+| Layer | Location | What it covers | When required |
+| ------- | ---------- | ---------------- | --------------- |
+| **Unit tests** | `#[cfg(test)] mod tests` at EOF of `<plugin>/src/lib.rs` | Config parsing, defaults, fallbacks, payload conversion, query/document building, state ser/de | Every plugin |
+| **Integration tests** | `core/integration/tests/connectors/<name>/` (uses real backend via Docker) | End-to-end: runtime + plugin + real Postgres/ES/Iceberg/Mongo/etc. + Iggy server | Every plugin that integrates with an external system |
+
+## Unit tests
+
+### Naming - BDD `given_when_should`
+
+Match the convention used in the codebase (`sources/random_source/src/lib.rs::tests`, `sinks/postgres_sink/src/lib.rs::tests`):
+
+```rust
+#[test]
+fn given_persisted_state_should_restore_messages_produced() { ... }
+
+#[test]
+fn given_no_state_should_start_fresh() { ... }
+
+#[test]
+fn given_invalid_duration_should_fall_back_to_default() { ... }
+
+#[test]
+fn given_payload_json_should_serialize_correctly() { ... }
+```
+
+You may **omit one part** when the test is small (`given_X_should_Y` instead of full `given_X_when_Y_should_Z`), but **stay consistent within a file**. Imperative `test_foo` / `does_bar` names are not the convention here.
+
+### `test_config()` helper
+
+Every plugin's tests start with a small helper returning a tuned-down version of the production config. New tests extend it; don't construct from scratch each time.
+
+```rust
+fn test_config() -> RandomSourceConfig {
+    RandomSourceConfig {
+        interval: Some("100ms".to_string()),
+        max_count: Some(100),
+        messages_range: Some((5, 10)),
+        payload_size: Some(50),
+    }
+}
+```
+
+### Async testing pattern
+
+The trait methods are `async`. For unit tests, build a runtime locally - don't add `#[tokio::test]` in `src/lib.rs` (it pulls test macros into prod build):
+
+```rust
+#[test]
+fn given_X_should_Y() {
+    let runtime = tokio::runtime::Runtime::new().unwrap();
+    runtime.block_on(async {
+        // await calls here
+    });
+}
+```
+
+### Mandatory: four canonical source state tests
+
+Every source must have these. Copy from `sources/random_source/src/lib.rs::tests`:
+
+```rust
+#[test]
+fn given_persisted_state_should_restore_<field>() {
+    let state = State { /* fields */ };
+    let serialized = rmp_serde::to_vec(&state).expect("Failed to serialize state");
+    let connector_state = ConnectorState(serialized);
+
+    let source = MySource::new(1, test_config(), Some(connector_state));
+
+    let runtime = tokio::runtime::Runtime::new().unwrap();
+    runtime.block_on(async {
+        let restored = source.state.lock().await;
+        assert_eq!(restored.<field>, /* expected */);
+    });
+}
+
+#[test]
+fn given_no_state_should_start_fresh() {
+    let source = MySource::new(1, test_config(), None);
+    /* assert default state */
+}
+
+#[test]
+fn given_invalid_state_should_start_fresh() {
+    let invalid = ConnectorState(b"not valid msgpack".to_vec());
+    let source = MySource::new(1, test_config(), Some(invalid));
+    /* assert default state */
+}
+
+#[test]
+fn state_should_be_serializable_and_deserializable() {
+    let original = State { /* fields */ };
+    let bytes = rmp_serde::to_vec(&original).unwrap();
+    let restored: State = rmp_serde::from_slice(&bytes).unwrap();
+    assert_eq!(original.<field>, restored.<field>);
+}
+```
+
+State is the only thing that survives a plugin restart. Silent corruption here means lost data on the next deploy.
+
+### Sink unit tests
+
+Cover pure per-message logic:
+
+- Config defaults + optional fields + invalid values → fallback.
+- Payload conversion for each `Payload` variant the sink claims to handle.
+- Header encoding (especially base64 for binary headers).
+- Query/document building (e.g., `postgres_sink::build_batch_insert_query`).
+- Transient vs permanent error classification (e.g., `postgres_sink::is_transient_error`).
+
+### Transform tests
+
+Four branches must be covered (see `connector-transform`):
+
+1. Happy path: matching input → expected output.
+2. Filter path: input that should be dropped returns `Ok(None)`.
+3. Pass-through path: non-JSON payload (or unmatched condition) returns `Ok(Some(unchanged))`.
+4. Invalid config: `new()` returns `Err(Error::InvalidConfigValue(_))`.
+
+### What NOT to mock
+
+- The underlying client lib (sqlx, reqwest, mongodb). Tests would exercise the mock, not the code.
+- The Iggy server.
+- The runtime.
+
+If you need a fake backend, use `wiremock` (a real local HTTP server) - see `core/integration/tests/connectors/http/`.
+
+## Integration tests (real infra via Docker)
+
+The canonical pattern lives in `core/integration/tests/connectors/`. Plugins that integrate with external services (Postgres, Elasticsearch, Iceberg, MongoDB, InfluxDB, Quickwit, HTTP/wiremock) have a paired fixture + test file there.
+
+### Layout
+
+```text
+core/integration/tests/connectors/
+├── mod.rs                        Common helpers (TestMessage, create_test_messages)
+├── fixtures/                     One subdir per backend
+│   ├── postgres/
+│   │   ├── container.rs          PostgresContainer (testcontainers wrapper), env-var consts
+│   │   ├── sink.rs               PostgresSinkFixture, PostgresSinkByteaFixture, PostgresSinkJsonFixture
+│   │   ├── source.rs             PostgresSourceJsonFixture, PostgresSourceJsonbFixture, ...
+│   │   └── mod.rs                re-exports
+│   ├── elasticsearch/  iceberg/  mongodb/  influxdb/  quickwit/  http/  delta/
+│   └── wiremock.rs               HTTP mocking for http_sink tests
+├── postgres/
+│   ├── postgres_sink.rs          The actual #[iggy_harness] tests
+│   ├── postgres_source.rs
+│   ├── restart.rs                Restart + state-survival tests
+│   ├── sink.toml                 Runtime config used by sink tests
+│   ├── source.toml               Runtime config used by source tests
+│   └── mod.rs                    Shared constants (TEST_MESSAGE_COUNT, POLL_ATTEMPTS, ...)
+├── delta/ elasticsearch/ iceberg/ mongodb/ influxdb/ random/ quickwit/ http/ stdout/
+├── http_config_provider/             HTTP config provider end-to-end
+├── runtime/                      Runtime-only tests (error isolation, missing plugin, ...)
+└── api/                          HTTP control plane tests
+```
+
+### The `#[iggy_harness]` proc macro
+
+Each integration test is annotated with this macro from the `integration` crate. It boots an in-process Iggy server (and optionally the connectors runtime) for the duration of the test, runs the seeds, then injects a `&TestHarness` and your fixture.
+
+```rust
+use integration::harness::seeds;
+use integration::iggy_harness;
+
+#[iggy_harness(
+    server(connectors_runtime(config_path = "tests/connectors/postgres/sink.toml")),
+    seed = seeds::connector_stream
+)]
+async fn json_messages_sink_stores_as_bytea(
+    harness: &TestHarness,
+    fixture: PostgresSinkFixture,
+) {
+    let client = harness.root_client().await.unwrap();
+    let pool = fixture.create_pool().await.expect("Failed to create pool");
+    fixture.wait_for_table(&pool, "iggy_messages").await;
+    // ... send messages, assert on rows
+}
+```
+
+Key pieces:
+
+- `server(connectors_runtime(config_path = ...))` boots the connectors runtime against the given TOML.
+- `seed = seeds::connector_stream` runs the named seed to create the test stream/topic.
+- `fixture: PostgresSinkFixture` - the test harness calls `PostgresSinkFixture::setup()` (which spins up the testcontainer) and injects the result.
+- `harness: &TestHarness` (defined in `core/integration/src/harness/orchestrator/harness.rs`) exposes `.root_client().await`, `.connectors_runtime().expect("...").http_url()`, etc. - `connectors_runtime()` returns `Option`, so `.expect()` first.
+
+### Fixture pattern (`TestFixture` trait)
+
+Each fixture implements `integration::harness::TestFixture`. Pattern:
+
+```rust
+// core/integration/tests/connectors/fixtures/<backend>/container.rs
+
+use testcontainers_modules::{
+    <backend_module>,
+    testcontainers::{ContainerAsync, runners::AsyncRunner},
+};
+
+pub struct MyContainer {
+    container: ContainerAsync<<backend_module>::Image>,
+    pub connection_string: String,
+}
+
+impl MyContainer {
+    pub async fn start() -> Result<Self, TestBinaryError> {
+        let container = <backend_module>::Image::default().start().await?;
+        let port = container.get_host_port_ipv4(DEFAULT_PORT).await?;
+        Ok(Self {
+            container,
+            connection_string: format!("...://localhost:{port}"),
+        })
+    }
+}
+```
+
+The fixture itself wraps the container and implements `TestFixture::setup()` to spin it up and inject env vars that the runtime picks up.
+
+### Env-var injection via `ConfigEnv`
+
+The runtime's config structs derive `ConfigEnv` (`configs_derive::ConfigEnv`, applied in `runtime/src/configs/connectors.rs` to `SinkConfig`, `SourceConfig`, `StreamConsumerConfig`, `StreamProducerConfig`). Fields are addressable by env var with a path-built prefix. Three concrete forms observed in `core/integration/tests/connectors/fixtures/postgres/container.rs`:
+
+```rust
+// Plugin-config fields (your sink/source's own config struct):
+//   IGGY_CONNECTORS_<TYPE>_<KEY>_PLUGIN_CONFIG_<FIELD>
+pub const ENV_SINK_CONNECTION_STRING: &str =
+    "IGGY_CONNECTORS_SINK_POSTGRES_PLUGIN_CONFIG_CONNECTION_STRING";
+
+// Indexed nested fields (per-stream entries are a Vec):
+//   IGGY_CONNECTORS_<TYPE>_<KEY>_STREAMS_<INDEX>_<FIELD>
+pub const ENV_SINK_STREAMS_0_STREAM: &str =
+    "IGGY_CONNECTORS_SINK_POSTGRES_STREAMS_0_STREAM";
+
+// Top-level scalar fields on SinkConfig/SourceConfig itself:
+//   IGGY_CONNECTORS_<TYPE>_<KEY>_<FIELD>
+pub const ENV_SINK_PATH: &str =
+    "IGGY_CONNECTORS_SINK_POSTGRES_PATH";
+```
+
+`<TYPE>` is `SINK` or `SOURCE`; `<KEY>` is the connector key (TOML key field, uppercased). `PLUGIN_CONFIG` is the literal segment used when reaching into your plugin's nested config. Fields marked `#[config_env(skip)]` (e.g., `transforms`, `plugin_config` as a whole) are NOT env-addressable; primitive leaves marked `#[config_env(leaf)]` are.
+
+The fixture sets these in `setup()` before the runtime reads its config. This is how a dynamic container port reaches a static TOML.
+
+### Test naming for integration tests
+
+Integration tests use a **descriptive declarative** style, not the unit-test `given_should` form. Match the codebase:
+
+```rust
+async fn json_messages_sink_stores_as_bytea(...) { ... }
+async fn binary_messages_sink_stores_as_bytea(...) { ... }
+async fn json_messages_sink_stores_as_jsonb(...) { ... }
+async fn delete_after_read_source_removes_rows_after_producing(...) { ... }
+async fn processed_column_source_marks_rows_after_producing(...) { ... }
+async fn state_persists_across_connector_restart(...) { ... }
+async fn restart_sink_connector_continues_processing(...) { ... }
+```
+
+Pattern: `<subject>_<action>_<observation>`. Reads like a sentence describing what the test proves.
+
+### Polling vs sleeping
+
+Integration tests poll until an expected condition - never `sleep(big_duration)`. Constants `POLL_ATTEMPTS` and `POLL_INTERVAL_MS` defined per-backend `mod.rs`. Fixture helpers like `PostgresSinkFixture::fetch_rows_as` and `PostgresSinkFixture::wait_for_table` encapsulate the pattern.
+
+### When to add an integration test
+
+- New sink/source plugin → at minimum one happy-path test per supported `Schema` and per supported plugin mode. Concrete coverage in `core/integration/tests/connectors/postgres/`: 3 sink tests (`json_messages_sink_stores_as_bytea`, `binary_messages_sink_stores_as_bytea`, `json_messages_sink_stores_as_jsonb`) backed by 3 sink fixtures, plus 5 source fixtures (`Json`, `Jsonb`, `Bytea`, `Delete`, `Mark`) and a dedicated `restart.rs` for state-survival.
+- Bug fix in a plugin → regression test reproducing the bug.
+- Behavior that crosses the FFI boundary (state restart, transform chain, schema decode) → integration test, not unit test.
+
+### When NOT to add an integration test
+
+- Pure logic (query builder, payload converter) - that's a unit test.
+- Config validation - unit test.
+- Code paths already covered by an equivalent test for another backend, when the new backend has identical behavior.
+
+## SDK + runtime tests
+
+- `core/connectors/sdk/tests/` - cross-module SDK concerns. In tree: `protobuf_integration.rs`, `flatbuffer_integration.rs` (round-trip schema decoders/encoders).
+- Runtime tests live under `core/integration/tests/connectors/runtime/` and `core/integration/tests/connectors/api/`. They exercise the runtime alone (no plugin-specific backend) - error isolation, missing plugin, invalid config, HTTP API contract.
+
+## CI / verification flow
+
+Before pushing:
+
+```text
+cargo fmt --all
+cargo sort --no-format --workspace
+cargo clippy -p <crate> --all-targets -- -D warnings
+cargo test -p <crate>
+```
+
+For integration tests, the relevant package is `integration`. There is **no `--test connectors` target** - the `integration` crate has no `[[test]]` entries and `tests/` is structured as a single binary entry through `tests/mod.rs` with `connectors/`, `server/`, `cli/`, etc. as nested modules. Run via name filter:
+
+```text
+cargo test -p integration -- connectors::postgres::postgres_sink
+cargo test -p integration -- connectors::postgres::                   # all postgres tests
+cargo test -p integration -- connectors::                              # all connector tests
+```
+
+Integration tests assume Docker is available locally and pull images from a public registry on first run.
+
+## Common pitfalls
+
+1. **Skipping integration tests for a real-infra plugin.** Unit tests don't catch FFI/lifecycle/encoding regressions.
+2. **Forgetting the four canonical source state tests.** This is the most common review comment.
+3. **Mocking the client library** instead of using `testcontainers` - test exercises the mock.
+4. **`#[tokio::test]` in `src/lib.rs`** - pulls tokio test macros into prod build. Use `Runtime::new()` instead. (`#[tokio::test]` is fine in `tests/` directories, which compile separately.)
+5. **`unwrap()` in test assertions** - prefer `assert_eq!` / `expect("descriptive")` so failures tell you which step blew up.
+6. **Tests depending on system time** - inject the clock or use `tokio::time::pause()`.
+7. **Hidden coupling via shared globals** (static `AtomicU64`, env vars) - tests must be independent and parallelizable.
+8. **Asserting on `Display` of an error** - use `matches!(err, Error::Variant(_))`. `assert_eq!(err.to_string(), ...)` breaks on message tweaks.
+9. **Sleeping a fixed duration** instead of polling - causes flakes when CI is slow.
+
+## Examples worth copying
+
+| Concern | Where |
+| --------- | ------- |
+| Source state round-trip | `sources/random_source/src/lib.rs::tests` |
+| Config + query-building unit tests | `sinks/postgres_sink/src/lib.rs::tests` |
+| Real-infra sink integration tests | `core/integration/tests/connectors/postgres/postgres_sink.rs` |
+| Real-infra source integration tests | `core/integration/tests/connectors/postgres/postgres_source.rs` |
+| Restart + state survival | `core/integration/tests/connectors/postgres/restart.rs` |
+| Wiremock-driven HTTP sink test | `core/integration/tests/connectors/http/http_sink.rs` |
+| Testcontainer wrapper | `core/integration/tests/connectors/fixtures/postgres/container.rs` |
+| Fixture impl `TestFixture` | `core/integration/tests/connectors/fixtures/postgres/sink.rs` |
+| Runtime-only error-isolation | `core/integration/tests/connectors/runtime/error_isolation.rs` |
+| Transform tests | `sdk/src/transforms/add_fields.rs::tests`, `filter_fields.rs::tests` |
diff --git a/.claude/skills/connector-transform/SKILL.md b/.claude/skills/connector-transform/SKILL.md
new file mode 100644
index 000000000..b345ae9ea
--- /dev/null
+++ b/.claude/skills/connector-transform/SKILL.md
@@ -0,0 +1,263 @@
+---
+name: connector-transform
+description: Add a new transform under `core/connectors/sdk/src/transforms/`. Transforms mutate, filter, or convert messages between source/encode and decode/sink. Use when adding field-level transforms (add/delete/update/filter), format conversions, envelope unwrapping, or similar config-driven message manipulations for Apache Iggy connectors.
+---
+
+# Adding a New Apache Iggy Connector Transform
+
+A transform implements `iggy_connector_sdk::transforms::Transform`. It runs after decode (for sinks) or before encode (for sources), in a chain configured per-connector. Config-driven, composable.
+
+## File map
+
+```text
+sdk/src/transforms/
+├── mod.rs                 Transform trait, TransformType enum, from_config() factory,
+│                          FieldValue + ComputedValue helpers
+├── add_fields.rs          AddFields - append static or computed fields to JSON
+├── delete_fields.rs       DeleteFields - remove fields by key
+├── update_fields.rs       UpdateFields - conditional field replacement
+├── filter_fields.rs       FilterFields - keep/drop messages by key/value pattern
+├── unwrap_envelope.rs     UnwrapEnvelope - promote nested field to top-level payload
+├── proto_convert.rs       ProtoConvert - bidirectional Proto ⇄ Json/Text/Raw/etc.
+├── flatbuffer_convert.rs  FlatBufferConvert
+├── avro_convert.rs        AvroConvert
+└── json/                  Shared JSON helpers (path traversal, ops)
+```
+
+## The trait
+
+```rust
+// sdk/src/transforms/mod.rs - Transform
+pub trait Transform: Send + Sync {
+    fn r#type(&self) -> TransformType;
+    fn transform(
+        &self,
+        metadata: &TopicMetadata,
+        message: DecodedMessage,
+    ) -> Result<Option<DecodedMessage>, Error>;
+}
+```
+
+Semantics:
+
+- **`&self`** - transforms are immutable post-construction. Internal state (compiled regex, parsed paths, schema descriptors) is computed in `new()` and stored as plain struct fields. No locks needed - the whole instance is shared via `Arc<dyn Transform>`.
+- Takes `message` **by value** - the transform owns the `DecodedMessage` and may mutate freely without cloning.
+- Returns `Ok(Some(msg))` to pass through (possibly modified), `Ok(None)` to **filter** (drop silently), `Err(e)` for actual failures.
+- `&TopicMetadata` is for routing-aware logic. Most transforms ignore it.
+
+## Steps to add a new transform
+
+### 1. Create the file
+
+`sdk/src/transforms/my_transform.rs`. Apache 2.0 license header. Code reads top to bottom - config struct, then transform struct, then `impl`, then helpers.
+
+```rust
+/* Apache 2.0 header */
+
+use crate::transforms::{Transform, TransformType};
+use crate::{DecodedMessage, Error, Payload, TopicMetadata};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MyTransformConfig {
+    pub key: String,
+    pub option: Option<bool>,
+}
+
+pub struct MyTransform {
+    config: MyTransformConfig,
+}
+
+impl MyTransform {
+    pub fn new(config: MyTransformConfig) -> Result<Self, Error> {
+        if config.key.is_empty() {
+            return Err(Error::InvalidConfigValue(
+                "my_transform.key must not be empty".into(),
+            ));
+        }
+        Ok(Self { config })
+    }
+}
+
+impl Transform for MyTransform {
+    fn r#type(&self) -> TransformType {
+        TransformType::MyTransform
+    }
+
+    fn transform(
+        &self,
+        _metadata: &TopicMetadata,
+        mut message: DecodedMessage,
+    ) -> Result<Option<DecodedMessage>, Error> {
+        // Most transforms operate only on Payload::Json - non-JSON is a no-op.
+        let Payload::Json(ref mut value) = message.payload else {
+            return Ok(Some(message));
+        };
+
+        // Mutate `value` in place via simd_json::OwnedValue API.
+        // Return Ok(None) to filter, Ok(Some(message)) to pass through.
+
+        Ok(Some(message))
+    }
+}
+```
+
+### 2. Wire into `transforms/mod.rs`
+
+Three edits, all required:
+
+(a) Module declaration + re-export at the top:
+
+```rust
+mod my_transform;
+pub use my_transform::{MyTransform, MyTransformConfig};
+```
+
+(b) Discriminant in `TransformType`:
+
+```rust
+pub enum TransformType {
+    AddFields,
+    // ...
+    MyTransform,   // snake_case form in TOML: "my_transform"
+}
+```
+
+(c) Branch in `from_config()`:
+
+```rust
+TransformType::MyTransform => {
+    // For new transforms, prefer Error::InvalidConfigValue with formatted context -
+    // it preserves the underlying serde_json error. Existing code uses bare
+    // Error::InvalidConfig for most variants (UnwrapEnvelope is the exception).
+    let cfg: MyTransformConfig = serde_json::from_value(raw.clone())
+        .map_err(|error| Error::InvalidConfigValue(format!("my_transform: {error}")))?;
+    Ok(Arc::new(MyTransform::new(cfg)?))
+}
+```
+
+`from_config()` returns `Arc<dyn Transform>` so the same instance is shared across the pipeline.
+
+### 3. Document
+
+Add a TOML usage example to `sdk/README.md`:
+
+```toml
+[transforms.my_transform]
+enabled = true
+key = "some_field"
+option = true
+```
+
+### 4. Tests
+
+Bottom of `my_transform.rs`:
+
+```rust
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn given_matching_field_should_transform() { ... }
+
+    #[test]
+    fn given_non_json_payload_should_passthrough() { ... }
+
+    #[test]
+    fn given_filter_condition_should_drop_message() { /* assert Ok(None) */ }
+
+    #[test]
+    fn given_invalid_config_should_error_in_new() {
+        let cfg = MyTransformConfig { key: "".into(), option: None };
+        assert!(matches!(MyTransform::new(cfg), Err(Error::InvalidConfigValue(_))));
+    }
+
+    fn topic_meta() -> TopicMetadata {
+        TopicMetadata { stream: "s".into(), topic: "t".into() }
+    }
+
+    fn json_message(json: serde_json::Value) -> DecodedMessage { /* ... */ }
+}
+```
+
+## Rules
+
+### Operate on JSON only (mostly)
+
+Most field-level transforms only make sense for `Payload::Json`. Convention (see `add_fields.rs::AddFields::transform`): silently pass through non-JSON:
+
+```rust
+let Payload::Json(ref mut value) = message.payload else {
+    return Ok(Some(message));
+};
+```
+
+Format-conversion transforms (`proto_convert`, `avro_convert`, `flatbuffer_convert`) are the exception - they explicitly convert between variants.
+
+### Mutate `OwnedValue` in place, don't clone-then-replace
+
+`simd_json::OwnedValue` is mutable in place:
+
+```rust
+if let OwnedValue::Object(ref mut obj) = value {
+    obj.insert(key.into(), new_value);
+}
+```
+
+Do NOT clone the value, mutate the clone, then `message.payload = Payload::Json(new)`. The whole point of `&mut value` is in-place mutation.
+
+### Filter semantics
+
+`Ok(None)` drops the message **silently** - no error log, no metric. By design (filters succeed when they decide to drop). For visibility, log at `debug!` level.
+
+### Config validation
+
+Validate in `new()` and return `Err(Error::InvalidConfigValue(...))`. Don't `panic!`. Don't validate on the hot path.
+
+For transforms with regex or compiled patterns, compile once in `new()` and store the compiled form.
+
+### Stateless except for config
+
+Transforms are constructed once at startup and `Arc`-cloned across tasks. Must be `Send + Sync`. No mutable runtime state - if you need accumulator-like behavior, that's not a `Transform`, that's a sink.
+
+### Compiled state goes in the struct, not behind a lock
+
+Things derived from config (compiled regex, parsed paths, schema descriptors) should be computed in `new()` and stored as plain struct fields. The whole instance is shared via `Arc<dyn Transform>`, so per-field locking is unnecessary. See `sdk/src/transforms/filter_fields.rs::FilterFields::new` for the canonical pattern: regexes compile in `new()`, get stored as struct fields, are then read via `&self`.
+
+### `transform()` is sync
+
+The trait method is sync (not `async`). Don't propose making it async - that would require pervasive change across the runtime. Schemas and other external resources should be loaded in `new()` (potentially via a fallible `try_new`), not lazily during `transform()`.
+
+### Errors
+
+| Scenario | Variant |
+| ---------- | --------- |
+| Config validation in `new()` | `Error::InvalidConfigValue("transform_name: ...")` |
+| Per-message validation (bad shape) | `Error::InvalidRecordValue("...")` |
+| Schema resolution failure | `Error::InvalidTransformer` |
+| Format conversion failure | `Error::InvalidPayloadType` |
+
+Returning `Err` from `transform()` stops the message and is logged. For non-fatal field-level issues (field missing when transform expects it), prefer pass-through (`Ok(Some(message))`) unless config explicitly says to fail.
+
+## Common pitfalls
+
+1. **Forgetting one of the three `mod.rs` edits** - module declaration, `TransformType` variant, `from_config()` branch.
+2. **`#[serde(rename_all = "snake_case")]` mismatch** between enum variant name and TOML key.
+3. **Cloning `OwnedValue`** when in-place mutation would work.
+4. **Validating config inside `transform()`** instead of `new()`.
+5. **`std::sync::Mutex` for internal state** on the hot path - precompute in `new()` and store as plain struct fields. Transforms run on every message; locks are wasted work.
+6. **Returning `Err` for a filter** - filters use `Ok(None)`.
+
+## Before declaring done
+
+```text
+cargo fmt --all
+cargo sort --no-format --workspace
+cargo clippy -p iggy_connector_sdk --all-targets --all-features -- -D warnings
+cargo test -p iggy_connector_sdk --all-features
+```
+
+Verify by adding the transform to `core/connectors/runtime/example_config/connectors/` and running the runtime - the transform should apply to each message.
+
+If the transform changes payload shape sufficiently to break downstream sinks (e.g., renaming primary keys), call it out in the PR description.
diff --git a/.claude/skills/connectors-overview/SKILL.md b/.claude/skills/connectors-overview/SKILL.md
new file mode 100644
index 000000000..869c7e661
--- /dev/null
+++ b/.claude/skills/connectors-overview/SKILL.md
@@ -0,0 +1,236 @@
+---
+name: connectors-overview
+description: Entry point and index for the Apache Iggy Connectors subsystem (`core/connectors/`). Load this first when working anywhere under `core/connectors/` - runtime, SDK, sinks, sources, or transforms. Routes to the focused per-area skills.
+---
+
+# Apache Iggy Connectors - Overview
+
+## What sinks and sources are
+
+A **sink** is a plugin that **consumes** messages from one or more Apache Iggy streams and writes them to an external system (Postgres, Elasticsearch, Iceberg, HTTP endpoint, Mongo, object store, stdout, ...). It implements `iggy_connector_sdk::Sink`.
+
+A **source** is a plugin that **produces** messages from an external system into Apache Iggy streams (poll a DB table, scroll an ES index, generate random data, ...). It implements `iggy_connector_sdk::Source`.
+
+Both are compiled as `cdylib` shared libraries (`.so`/`.dylib`/`.dll`) and loaded by the **connectors runtime** at startup via `dlopen`. The runtime drives lifecycle (open/handle/consume/close), bridges Iggy ⇄ plugin via a small FFI, applies optional transforms in between, and persists source state.
+
+### End-to-end flow
+
+```text
+                      ┌─ optional transforms ─┐
+External  ──poll──▶  SOURCE  ──FFI──▶  RUNTIME  ──encode──▶  Apache Iggy stream
+   system    plugin            ▲                    ▲
+                               │                    │
+                       state save (msgpack)         │
+                                                    │
+                       ┌─ optional transforms ─┐    │
+Apache Iggy stream  ──decode──▶  RUNTIME  ──FFI──▶  SINK  ──write──▶ External
+                                              plugin                   system
+```
+
+A message header set on the source side rides through transforms (which may modify, drop, or pass it through) and arrives at the sink with `BTreeMap<HeaderKey, HeaderValue>` headers preserved deterministically.
+
+## Subsystem layout
+
+| Area | Path | Role |
+| ------ | ------ | ------ |
+| Runtime | `core/connectors/runtime/` | Host process: load plugins, drive lifecycle, bridge streams ⇄ plugins, expose `/stats`, `/metrics`, control HTTP API |
+| SDK | `core/connectors/sdk/` | Stable contract: `Sink`/`Source`/`StreamDecoder`/`StreamEncoder`/`Transform` traits, `Payload`/`Schema`, FFI macros, retry helpers |
+| Sinks | `core/connectors/sinks/<name>_sink/` | One crate per sink plugin |
+| Sources | `core/connectors/sources/<name>_source/` | One crate per source plugin |
+| Integration tests | `core/integration/tests/connectors/` | Real-infra tests using `testcontainers-modules` + `#[iggy_harness]` macro |
+
+## Which skill to load
+
+- Writing **a new sink plugin** → `connector-sink`
+- Writing **a new source plugin** → `connector-source`
+- Adding **schemas, decoders, encoders, traits in the SDK** → `connector-sdk`
+- Changing **runtime internals** (FFI, plugin manager, state storage, configs, transforms wiring) → `connector-runtime`
+- Adding **a new transform** (add/delete/update fields, format conversion) → `connector-transform`
+- Writing **unit OR integration tests** for any of the above → `connector-testing`
+
+## Stick to the existing conventions
+
+The connectors codebase is intentionally repetitive across plugins. Cross-plugin consistency makes review, LLM-assisted contribution, and onboarding tractable. Before writing anything new:
+
+1. **Find the closest existing plugin** by shape (DB-write sink → `postgres_sink`; HTTP sink → `http_sink`; polling source → `postgres_source`; etc.).
+2. **Copy its file layout, naming, log format, error mapping, test structure** verbatim. Only the backend-specific code (the client call) should differ.
+3. **If you find yourself reinventing a pattern** (writing your own retry loop, your own batch-mode enum, your own state struct), stop and check whether the SDK or another plugin already has it. The SDK's `retry.rs` covers HTTP retry + circuit breaker. Existing plugins have the batching, idempotency, header-encoding patterns.
+4. **Don't refactor unrelated code in the same PR.** Match conventions; propose convention changes separately.
+
+## Universal rules (every connectors PR)
+
+These apply everywhere - violate them and the PR will be flagged in review.
+
+### Style + structure
+
+1. **Apache 2.0 license header** at the top of every new `.rs` and `Cargo.toml`. Copy from any existing connector file. `.rs` uses `/* ... */`, `Cargo.toml` uses `# ...`.
+2. **Avoid LLM-slop tells: em dashes (—), gratuitous semicolons, hedging narrative ("note that...", "it's important to..."), trailing summaries.** Em dashes and semicolons aren't banned outright (sometimes the right tool), but in this codebase they're almost always a sign of generated prose. Default to hyphens, commas, or rewriting the sentence. Same rule for code, comments, commit messages, PR descriptions.
+3. **Imports at the top of the file.** No inline `use` inside functions or blocks. Group: std, external crates, then `crate::`.
+4. **No banner comments** (`// === Section ===`). Use functions, types, and naming for structure.
+5. **Code reads top to bottom like a book.** Public consts and public functions first; helpers and internals below; deeper-level helpers below those. A reader scrolling top-down should hit each function before they hit any function it calls. Don't make readers jump around the file.
+6. **Precise variable names.** No `b`, `p`, `t`, `m`. Use `batch`, `payload`, `timestamp`, `message`. Match literal API field names as log labels (`offset=`, `current_offset=`) - don't invent.
+7. **Comments explain WHY**, not WHAT. Default to no comment. Add one only when a hidden constraint, invariant, or workaround would surprise a reader.
+
+### Performance
+
+1. **Zero clone in hot loops.** Per-message work runs millions of times. Use `&self`, `&str`, `&[T]`, `&Payload`. For `Payload::Json`, the SDK provides `try_to_bytes(&self)` which does a single serialization pass (no `OwnedValue` clone). To move a field out of a struct without cloning, use `std::mem::replace` / `std::mem::take`.
+2. **`Vec::with_capacity(n)` when building per-batch vectors** - reallocation in hot path is wasted work.
+3. **Avoid `String::from_utf8(bytes)` on every message** when `std::str::from_utf8(&bytes)` (borrowed) works.
+
+### Async + concurrency
+
+1. **`async fn` only.** Never `.block_on()` inside a `Sink`/`Source` impl - the runtime drives the executor.
+2. **`tokio::sync::Mutex` (not `std::sync::Mutex`)** wherever a lock is held across `.await`.
+3. **Hold locks briefly.** Pattern: lock, read/clone what you need, drop the guard, then do I/O. Never hold a `Mutex` across an external I/O await.
+4. **Atomic counters** (`AtomicU64`) preferred over `Mutex<u64>` for hot-path metrics.
+
+### Logging
+
+1. **`tracing`, not `println!`.** `info!` for lifecycle, `debug!` per-batch detail, `warn!` for recoverable issues, `error!` for failures. Every log line includes `connector ID: {self.id}` and the connector name.
+2. **The `verbose` flag.** Both `SinkConfig` and `SourceConfig` carry a `verbose: bool` field at the top level. The **runtime** uses it to upgrade certain `debug!` logs to `info!` (per-batch processing/timing). **Plugins should mirror this** by accepting a similar plugin-level toggle (e.g., `postgres_sink::PostgresSinkConfig::verbose_logging`) and emitting more detailed `info!` logs when set. Verbose is off by default.
+3. **Never log secrets** (connection strings, API keys, tokens). Redact URLs at the log site. Credential-bearing config fields must use `SecretString` with the workspace serde redactor (see Exemplars and the per-area skills).
+
+### Errors
+
+1. **Use `Error::PermanentHttpError` / `Error::SchemaMismatch` / `Error::CatalogCommitError` for non-retryable failures.** Returning a transient variant for bad data trips circuit breakers and hammers the backend.
+2. **No `unwrap()` / `expect()`** on `Result` from external I/O outside tests. Acceptable in tests, in `const` init, and where the invariant is locally provable.
+
+### Toolchain
+
+1. **Never run `cargo install`, `pip install`, `brew install`** etc. without explicit user authorization. Use the toolchain already configured.
+2. **Verification order before declaring done:** `cargo fmt --all` → `cargo sort --no-format --workspace` → `cargo clippy --all-features --all-targets -- -D warnings` → `cargo test`. CI enforces all four.
+
+### Idiomatic Rust
+
+1. **Prefer standard traits over free helpers.** Parsing = `FromStr` + `.parse()`. Formatting = `Display` + `.to_string()`. Conversion = `From`/`TryFrom`. A free `fn parse_foo(s: &str) -> Result<Foo, _>` or `fn format_foo(&Foo) -> String` is a code smell - use the trait.
+2. **`#[serde(default)]` or `Option<T>` for new config fields.** Preserves forward compat - existing TOML files won't break.
+
+## Exemplars
+
+| Purpose | Plugin | Why |
+| --------- | -------- | ----- |
+| Simplest sink (read this first) | `sinks/stdout_sink/` | ~100 LOC, the canonical minimal shape |
+| Real-infra sink with integration tests | `sinks/postgres_sink/` + `core/integration/tests/connectors/postgres/postgres_sink.rs` | Docker testcontainers via `PostgresContainer`, idempotency via PK, `is_transient_error` mapping, both unit + integration tests |
+| Most feature-rich sink config | `sinks/http_sink/` | Validation patterns, batch modes (individual / ndjson / json_array / raw), `std::mem::replace` for zero-copy payload extraction, retry middleware. No external infra in tests though - uses `wiremock` |
+| `AtomicU64` counters on the hot path | `sinks/mongodb_sink/` | Lock-free metric updates instead of `Mutex<State>` |
+| Simplest source | `sources/random_source/` | The four canonical state round-trip tests live here |
+| Real-infra source | `sources/postgres_source/` + `core/integration/tests/connectors/postgres/postgres_source.rs` | Cursor + delete-after-read + processed-column modes, restart-survives-state integration test |
+
+**Read the relevant exemplar end-to-end before writing or modifying a connector.** Patterns are intentionally consistent across plugins - "originality" usually means missing a convention. When in doubt, copy verbatim and adapt the backend-specific bits.
+
+## Concrete efficiency patterns observed in the codebase
+
+These are not theoretical - each is implemented in at least one in-tree plugin or runtime path. Match them.
+
+| Pattern | Where to look | When to use |
+| --------- | --------------- | ------------- |
+| `std::mem::replace(&mut message.payload, Payload::Raw(vec![]))` | `sinks/http_sink/src/lib.rs` (3 sites inside `send_individual`, `send_ndjson`, `send_json_array`) | Taking a payload out of a `&mut ConsumedMessage` without cloning |
+| `std::mem::take(&mut batch)` | `runtime/src/sink.rs::consume_messages`, `runtime/src/manager/{sink,source}.rs` (`handler_tasks`, `task_handles`) | Draining a `Vec` field with one move |
+| `std::mem::swap(&mut a, &mut b)` | `sinks/http_sink/src/lib.rs` (retry_delay vs max_retry_delay validation) | Fixing config-field ordering in `new()` |
+| `std::mem::replace(&mut self.config, new)` | `sdk/src/decoders/avro.rs::update_config`, `sdk/src/encoders/avro.rs::update_config` | Hot-swapping internal config without cloning the old |
+| `Vec::with_capacity(messages.len())` | Every sink that builds per-batch buffers (`postgres_sink`, `mongodb_sink`, `quickwit_sink`, `elasticsearch_sink`, `http_sink`, `iceberg_sink`) | Pre-sizing batch output to exact size |
+| `Vec::with_capacity(messages.len() * 2)` | `sinks/elasticsearch_sink/src/lib.rs` (bulk API needs index-line + doc-line per message) | Pre-sizing with a known multiplier |
+| `String::with_capacity(messages.len() * 256)` and `Vec::with_capacity(messages.len() * 256)` | `sinks/influxdb_sink/src/lib.rs` (line protocol body), `sinks/http_sink/src/lib.rs` (ndjson body) | Heuristic byte-size pre-allocation for serialized bodies |
+| `bytes::Bytes::from(body)` | `sinks/http_sink/src/lib.rs`, `sinks/influxdb_sink/src/lib.rs` | Cheap ref-counted body sharing across retry attempts - `Bytes::try_clone()` is O(1) |
+| `AtomicU64` for counters | `sinks/mongodb_sink/src/lib.rs` (`messages_processed`, `insertion_errors`) | Lock-free per-message metric updates |
+| `Payload::try_to_bytes(&self)` | `sdk/src/lib.rs::Payload::try_to_bytes` (the docstring spells out the optimization) | Serializing `Payload::Json` to bytes without cloning the `OwnedValue` tree |
+| `simd_json::to_owned_value(&mut bytes)` | `sdk/src/decoders/json.rs::JsonStreamDecoder::decode` | In-place JSON parsing (mutates input buffer, no extra allocation) |
+| Brief-lock fetch pattern | `sources/postgres_source/src/lib.rs::poll_tables` | Read cursor under `Mutex`, drop guard, do I/O, take `Mutex` again to write |
+| `is_transient_error(&e)` mapping | `sinks/postgres_sink/src/lib.rs` (SQLSTATE mapping for `40001`, `40P01`, `57P01-03`, `08000/03/06`) | Classifying driver errors for retry vs `PermanentHttpError` |
+| Two-constructor pattern (`new` lenient, `try_new` strict, `Default`) | `sdk/src/decoders/avro.rs::AvroStreamDecoder` | Stateful decoders/encoders where schema loading can fail |
+| Duplicate-ID guard in FFI macro | `sdk/src/sink.rs::sink_connector!`, `sdk/src/source.rs::source_connector!` | Prevents silent buffered-data loss on reopen-without-close |
+| `restart_guard.try_lock()` (not `lock()`) | `runtime/src/manager/sink.rs::restart_connector`, `runtime/src/manager/source.rs::restart_connector` | No thundering-herd restarts |
+| `tokio::time::timeout(Duration::from_secs(5), handle).await` | `runtime/src/manager/sink.rs::stop_connector`, `runtime/src/manager/source.rs::stop_connector` | Bounded wait when joining task handles on shutdown |
+| `flume::unbounded()` channel | `runtime/src/source.rs::spawn_source_handler` (registers `SOURCE_SENDERS` entry; the consumer side is `source_forwarding_loop`) | Cheap MPSC handoff from the SDK's async `handle_messages` task into the runtime's forwarding loop. Note: the FFI registration call `iggy_source_handle(id, callback)` runs in `spawn_blocking`, but the `send_callback` invocations come from the SDK's spawned async task, not from the blocking worker |
+| `tokio::sync::watch::channel(())` | `sdk/src/sink.rs`, `sdk/src/source.rs`, `runtime/src/sink.rs`, `runtime/src/manager/*` | Broadcast a one-shot shutdown signal to many tasks |
+| `dashmap::DashMap` (lock-free concurrent map) | `runtime/src/manager/sink.rs` (`SinkManager`), `runtime/src/source.rs` (`SOURCE_SENDERS`), SDK macro `INSTANCES` | Concurrent keyed access without a single `Mutex` |
+| Connection pool tuning | `sources/postgres_source/src/lib.rs` (`PgPoolOptions::new().max_connections(...)`), `sinks/http_sink/src/lib.rs` (`pool_max_idle_per_host`, `tcp_keepalive`) | Configurable bounds on backend connections |
+| `secrecy::SecretString` + `iggy_common::serde_secret::serialize_secret` | `sinks/postgres_sink/src/lib.rs::PostgresSinkConfig::connection_string` | Secrets that auto-redact on `Debug`/`Display` |
+
+## Common review smells (across all areas)
+
+- `.clone()` on `Payload::Json` or `OwnedValue` - use `try_to_bytes(&self)`.
+- `&mut self` on `Sink::consume` or `Source::poll` impls - won't compile, but flag any creative workaround.
+- `std::sync::Mutex` held across `.await` - swap for `tokio::sync::Mutex`.
+- Missing `[lib] crate-type = ["cdylib", "lib"]` in plugin `Cargo.toml`.
+- Missing Apache 2.0 header.
+- Source plugin without the four canonical state tests (see `connector-testing`).
+- New silent message drop without a metric counter increment.
+- Wrapping `format!()` around args passed to `error!`/`warn!`/`info!`/`debug!` - e.g., `error!("foo: {}", format!("bar: {}", x))`. The eager `format!()` allocates even when the log level filters the line out. Pass args directly: `error!("foo: {x}")` or `error!(error = %x, "foo")`. (Building a `String` for both logging AND a state field via one `format!()` is fine - that's what the runtime does with `set_error`.)
+- Logging a connection string, API key, or token.
+- Plain `String` for a credential field. Use `SecretString` (`secrecy` crate) with `#[serde(serialize_with = "iggy_common::serde_secret::serialize_secret")]` so the `/stats` surface and `Debug` impls both redact. Expose with `.expose_secret()` only at the call site that needs raw bytes.
+- `tokio::spawn` inside plugin code (the runtime owns lifecycle; orphaned tasks survive `close()`).
+- `std::time::SystemTime::now()` in transforms (non-deterministic, breaks tests).
+
+## Benchmark mode (per-batch timing observability)
+
+Every sink and source supports an opt-in `benchmark = true` flag (`SinkConfig`/`SourceConfig`, also overridable via env `IGGY_CONNECTORS_<TYPE>_<KEY>_BENCHMARK=true`). Two observability surfaces:
+
+1. **Tracing events** (only when flag is on) - one structured `info!` per batch under target `iggy_connectors::benchmark` with per-stage microsecond timings:
+   - Sink: `connector_type, connector_key, stream, topic, partition_id, current_offset, batch_size, processed_count, prepare_us, ffi_us, total_us`
+   - Source: `connector_type, connector_key, stream, topic, batch_size, sent_count, decode_us, prepare_us, iggy_send_us, state_save_us, total_us`
+   - Filter live: `RUST_LOG=iggy_connectors::benchmark=info`
+
+2. **Prometheus histograms** (always on, regardless of flag) - aggregated for proper p50/p95/p99 queries:
+   - Metric: `iggy_connector_stage_duration_seconds{connector_key, connector_type, stage}`
+   - `stage`: `Prepare`, `Ffi` (sink), `Decode`, `IggySend`, `StateSave` (source), `Total` (both)
+   - Buckets: 50µs - 5s, geometric (see `runtime/src/metrics.rs::STAGE_BUCKETS_SECONDS`)
+   - Query example: `histogram_quantile(0.95, sum(rate(iggy_connector_stage_duration_seconds_bucket{stage="Ffi"}[5m])) by (le, connector_key))`
+
+The flag only gates the verbose text event; the histogram observation is always on. Cost when no observers attached: ~50 ns per batch (5 stages × `Instant::now()` + atomic bucket bump). Negligible at every realistic throughput.
+
+Also new in this surface: `iggy_connector_messages_filtered_total{connector_key, connector_type}` counts intentional drops by transforms returning `Ok(None)`, distinct from `errors_total` for unexpected drops. Both also exposed in `/stats` JSON (`ConnectorStats.messages_filtered`, `.errors`).
+
+Implementation: `core/connectors/runtime/src/benchmark.rs` (text-event
+emitters + `as_micros`), `runtime/src/metrics.rs::{Stage, SinkLabels,
+SourceLabels, observe_stage_with_labels}` (pre-built label cache avoids
+per-batch `String` clones on the hot path; `&str`-based wrappers like
+`observe_stage_duration` are `#[cfg(test)]` only). Tests:
+`core/connectors/runtime/src/metrics.rs::tests::given_stage_histogram_*`
+(unit), `core/integration/tests/connectors/runtime/benchmark.rs` (BDD-named
+integration tests: text emission, env override, disabled-flag, histograms
+via `/metrics` scrape, JSON log format end-to-end, parser unit tests).
+
+## Logging format
+
+`runtime/src/configs/runtime.rs::LoggingConfig` exposes `format = "text" | "json"` (text default), env-addressable via `IGGY_CONNECTORS_LOGGING_FORMAT=json`. `runtime/src/log.rs::init_logging` matches on `(telemetry.enabled, format)` to install the right `fmt::layer()`/`fmt::layer().json()` combined with the OpenTelemetry layer when telemetry is on. JSON applies to the stdout layer only - the OTel export pipeline is unaffected by this flag.
+
+## File map cheat-sheet
+
+```text
+core/connectors/
+├── README.md
+├── runtime/
+│   ├── src/
+│   │   ├── main.rs              FFI structs (SinkApi, SourceApi), plugin resolution
+│   │   ├── manager/{sink,source}.rs  Plugin lifecycle, restart_guard, status transitions
+│   │   ├── configs/             Local + HTTP config providers, ConfigEnv derive
+│   │   ├── {sink,source,stream,transform,state,context}.rs
+│   │   └── api/                 HTTP control plane (/sinks, /sources, /stats, /metrics)
+│   └── example_config/          Reference TOML
+├── sdk/
+│   └── src/
+│       ├── lib.rs               Sink/Source traits, Payload, Schema, Error
+│       ├── {sink,source}.rs     FFI containers + sink_connector!/source_connector! macros
+│       ├── decoders/encoders/   Per-schema (json/raw/text/proto/flatbuffer/avro)
+│       ├── transforms/          add_fields, delete_fields, update_fields, filter_fields,
+│       │                        unwrap_envelope, proto_convert, flatbuffer_convert, avro_convert
+│       └── retry.rs             CircuitBreaker, HttpRetryMiddleware
+├── sinks/<name>_sink/
+└── sources/<name>_source/
+
+core/integration/tests/connectors/         # Integration tests (real infra)
+├── fixtures/                               # testcontainers-modules wrappers per backend
+│   ├── postgres/   (PostgresContainer, PostgresSinkFixture, PostgresSourceJsonFixture, ...)
+│   ├── elasticsearch/  (Elasticsearch container + sink/source fixtures)
+│   ├── mongodb/ iceberg/ influxdb/ quickwit/ http/ delta/
+│   └── wiremock.rs                         # for HTTP sink tests
+├── postgres/      postgres_sink.rs, postgres_source.rs, restart.rs, sink.toml, source.toml
+├── elasticsearch/  ...
+├── runtime/       error_isolation.rs and friends
+└── api/           HTTP API endpoint tests
+```
+
+## Note on referenced files
+
+This skill set deliberately cites files by path + symbol (`PostgresContainer::start` in `core/integration/tests/connectors/fixtures/postgres/container.rs`) rather than line numbers. Line numbers go stale on the first refactor; symbol names survive. Grep the symbol if you need the exact spot.
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 000000000..5f550bb40
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,355 @@
+# Apache Iggy Agent Guidelines
+
+**Apache Iggy (Incubating)** is a persistent message streaming platform
+written in Rust, capable of processing millions of messages per second
+at ultra-low latency. It uses a thread-per-core shared-nothing
+architecture with `io_uring` and `compio` for low-level I/O. Supported
+transports: QUIC, WebSocket, TCP (custom binary protocol), and HTTP
+(REST). Client SDKs ship in Rust, .NET, Java, Python, Go, C++, and
+Node.js. A connectors subsystem ingests from and egresses to external
+systems via dynamically loaded plugins.
+
+> The skill set under `.claude/skills/` is currently scoped to the
+> connectors subsystem (`core/connectors/`). Other areas follow the
+> universal principles in this file. Deeper per-area skills will be
+> added as needed.
+
+## Quick reference
+
+```bash
+# Verification order is enforced by CI (.github/actions/rust/pre-merge).
+# Skipping any step means a broken PR.
+cargo fmt --all                                                       # format (step 1)
+cargo sort --no-format --workspace                                    # sort Cargo.toml deps (step 2)
+                                                                      # --no-format is required: without it,
+                                                                      # multi-line feature arrays get flattened
+                                                                      # and taplo then re-formats them, churning
+                                                                      # the workspace.
+cargo clippy --all-features --all-targets -- -D warnings              # lint (step 3, CI uses --all-features)
+cargo test -p <crate>                                                 # tests (step 4)
+
+cargo machete --with-metadata                                         # unused-dep detector (CI)
+cargo check --all --all-features                                      # full-workspace check
+cargo doc --no-deps --all-features --quiet                            # doctests + docs
+
+# Non-Rust lint scripts (mirror CI). Pass --fix to auto-fix where supported.
+./scripts/ci/taplo.sh [--check|--fix]                                 # TOML formatting
+./scripts/ci/markdownlint.sh [--fix]                                  # Markdown lint
+./scripts/ci/shellcheck.sh [--fix]                                    # Shell lint
+./scripts/ci/license-headers.sh [--check|--fix]                       # Apache 2.0 headers
+./scripts/ci/trailing-whitespace.sh [--fix]                           # trailing whitespace
+./scripts/ci/trailing-newline.sh [--fix]                              # final newline
+./scripts/ci/sync-rust-version.sh [--check|--fix]                     # sync rust-toolchain.toml across SDKs
+./scripts/ci/python-sdk-version-sync.sh [--check|--fix]               # Python SDK version sync
+./scripts/ci/uv-lock-check.sh [--check|--fix]                         # uv.lock freshness
+./scripts/ci/binary-artifacts.sh --check                              # no committed binaries
+./scripts/ci/third-party-licenses.sh --validate --manifest <path>     # ASF third-party license enumeration
+typos                                                                  # spelling (configured in .typos.toml)
+
+# Run things
+cargo run --bin iggy-server                                           # server
+cargo run --bin iggy -- <subcommand>                                  # CLI
+IGGY_CONNECTORS_CONFIG_PATH=... cargo run --bin iggy-connectors       # connectors runtime
+./scripts/run-bdd-tests.sh                                            # cross-SDK BDD suite
+./scripts/run-benches.sh                                              # benchmark suite
+```
+
+## Pre-commit hooks
+
+`.pre-commit-config.yaml` wires all of the lint scripts above plus
+`cargo fmt`, `cargo sort --no-format --workspace`, and (on push)
+`cargo clippy --all-features --all-targets -- -D warnings`. Install
+once and the hooks run on every commit:
+
+```bash
+# Classic pre-commit (Python):
+pre-commit install
+pre-commit run --all-files
+
+# Or prek (Rust reimplementation, drop-in faster replacement):
+prek install
+prek run --all-files
+```
+
+Both read the same `.pre-commit-config.yaml`. CI re-runs the same hooks,
+so locally-installed hooks catch issues before push.
+
+## Structure
+
+```text
+iggy/
+├── core/
+│   ├── server/           Iggy server binary
+│   ├── server-ng/        Next-gen server rewrite (Viewstamped Replication, WIP)
+│   ├── sdk/              Rust client SDK
+│   ├── cli/              iggy CLI
+│   ├── connectors/       Connectors runtime + SDK + sinks/sources
+│   ├── common/           Shared types (IggyDuration, IggyTimestamp, ...)
+│   ├── binary_protocol/  Wire format (stable)
+│   ├── configs/          Config plumbing + ConfigEnv derive
+│   ├── ai/mcp/           MCP server for AI integration
+│   ├── bench/            Benchmark suite
+│   ├── integration/      Cross-crate integration tests (real iggy-server + testcontainers backends)
+│   ├── simulator/        Deterministic simulator
+│   ├── tools/            Operational tools
+│   ├── harness_derive/   #[iggy_harness] proc macro
+│   ├── consensus/        Raft consensus (Miri-checked, unsafe-heavy iobuf)
+│   ├── journal/          WAL / journal layer
+│   ├── message_bus/      In-process bus
+│   ├── shard/            Shard runtime
+│   └── metadata, partitions, server_common, configs_derive, clock
+├── foreign/              Java / .NET / Python / Go / C++ / Node.js bindings
+├── bdd/                  Cross-language BDD tests (Gherkin)
+├── examples/             Per-SDK runnable examples
+├── helm/                 Helm charts
+├── web/                  Web UI
+└── scripts/              CI + release + dev scripts
+```
+
+## Where to look
+
+| Task                     | Location                           | Notes                                                |
+| ------------------------ | ---------------------------------- | ---------------------------------------------------- |
+| Wire protocol / commands | `core/binary_protocol/`            | Stable binary format                                 |
+| Server internals         | `core/server/src/`                 | TCP/QUIC/HTTP/WS handlers                            |
+| Next-gen server          | `core/server-ng/`                  | Viewstamped Replication rewrite (WIP)                |
+| Client SDK               | `core/sdk/src/`                    | Async Rust client                                    |
+| Connectors runtime       | `core/connectors/runtime/`         | FFI plugin host -> skill `connector-runtime`         |
+| Connectors plugins       | `core/connectors/{sinks,sources}/` | One crate per plugin                                 |
+| Connectors SDK           | `core/connectors/sdk/`             | Sink/Source traits, FFI macros                       |
+| Integration tests        | `core/integration/tests/`          | Real `iggy-server` processes via `TestHarness`       |
+| Cross-SDK BDD            | `bdd/`                             | Gherkin features against every SDK                   |
+| Benchmark suite          | `core/bench/`                      | Producer/consumer micro and end-to-end               |
+
+## Skills (deep dives)
+
+Currently scoped to the **connectors subsystem**. Load
+`connectors-overview` first for any change under `core/connectors/`.
+
+- [connectors-overview](.claude/skills/connectors-overview/SKILL.md) -
+  entry point and index. Universal rules, exemplars, efficiency patterns.
+- [connector-runtime](.claude/skills/connector-runtime/SKILL.md) -
+  FFI, plugin lifecycle, manager, state, metrics, benchmark mode,
+  logging format.
+- [connector-sdk](.claude/skills/connector-sdk/SKILL.md) -
+  Sink/Source traits, decoders/encoders, transforms, retry helpers.
+- [connector-sink](.claude/skills/connector-sink/SKILL.md) /
+  [connector-source](.claude/skills/connector-source/SKILL.md) -
+  per-plugin authoring guides.
+- [connector-transform](.claude/skills/connector-transform/SKILL.md) -
+  add/delete/update/filter fields, format conversion.
+- [connector-testing](.claude/skills/connector-testing/SKILL.md) -
+  BDD naming, `#[iggy_harness]`, testcontainers fixtures.
+
+For other subsystems, fall back to the principles below. No
+subsystem-specific CLAUDE.md or AGENTS.md is shipped beyond this file.
+
+## Tooling we rely on
+
+CI (`.github/workflows/pre-merge.yml`, `.github/actions/rust/pre-merge/`)
+installs and uses these. Match locally to reproduce CI behavior.
+
+| Tool                                          | Purpose                                  | Where invoked                                    |
+| --------------------------------------------- | ---------------------------------------- | ------------------------------------------------ |
+| `cargo fmt`                                   | Rust formatter                           | pre-commit, CI `fmt` task                        |
+| `cargo sort`                                  | Sort `[dependencies]` blocks             | pre-commit (`--no-format`), CI                   |
+| `cargo clippy`                                | Lint with `--all-features --all-targets` | pre-push, CI `clippy` task                       |
+| `cargo machete`                               | Unused-dep detector                      | CI `machete` task                                |
+| `cargo nextest` + `cargo-rail`                | DAG-scoped test execution                | CI `test-*` tasks                                |
+| `cargo llvm-cov`                              | Coverage                                 | CI `test-*` + `coverage-baseline.yml`            |
+| `cargo http-registry`                         | Local alt-registry for publish probes    | CI `verify-publish` task                         |
+| Miri                                          | UB detection on unsafe-heavy crates      | CI `miri` (binary_protocol + consensus)          |
+| `taplo`                                       | TOML formatter / checker                 | pre-commit, CI                                   |
+| `markdownlint-cli` (`markdownlint`)           | Markdown linter                          | pre-commit, CI                                   |
+| `shellcheck`                                  | Shell linter                             | pre-commit, CI                                   |
+| `typos`                                       | Spelling                                 | pre-commit                                       |
+| `cargo about` + `license-checker-rseidelsohn` | Third-party license enumeration          | `scripts/ci/third-party-licenses.sh`             |
+| Apache RAT / `license-headers.sh`             | Apache 2.0 source-header check           | pre-commit, CI                                   |
+| `uv`                                          | Python lockfile / env                    | `scripts/ci/uv-lock-check.sh`                    |
+| `ruff`                                        | Python formatter + linter                | pre-commit (`foreign/python`, `bdd`, `examples`) |
+| `golangci-lint`                               | Go linter                                | pre-push (`foreign/go`)                          |
+
+## Core principles
+
+Apply to every change in this repo.
+
+1. **Apache 2.0 header on every new source file.** `.rs` uses
+   `/* ... */`, `Cargo.toml` and shell use `# ...`. Copy verbatim from
+   any sibling file. Enforced by `./scripts/ci/license-headers.sh` and
+   by the pre-commit hook.
+2. **Avoid LLM-slop tells: em dashes, gratuitous semicolons, hedging
+   narrative, trailing summaries.** Not strict bans (sometimes the right
+   tool) but in this codebase they almost always mark generated text.
+   Default to hyphens, commas, or rewriting. Applies to code, comments,
+   commits, PR descriptions, and docs.
+3. **Verification order is mandatory:** `cargo fmt --all` ->
+   `cargo sort --no-format --workspace` -> `cargo clippy --all-features
+   --all-targets -- -D warnings` -> `cargo test`. Plus
+   `./scripts/ci/taplo.sh --check`. CI enforces all of them.
+4. **Always pass `--no-format` to `cargo sort`.** Without it, multi-line
+   feature arrays in `Cargo.toml` get flattened, which then conflicts
+   with `taplo`. The pre-commit hook already uses the correct flag.
+5. **Idiomatic Rust over free helpers.** `FromStr` not `parse_foo`,
+   `Display` not `format_foo`, `From`/`TryFrom` not
+   `to_foo_from_bar`. Structured `Err` enums, not `String`.
+6. **Imports at the top of every file.** No inline `use` inside
+   functions or blocks. Group: std, external crates, then `crate::`.
+7. **Precise names.** No `b`, `p`, `t`, `m`. Use `batch`, `payload`,
+   `timestamp`, `message`. Match literal API field names as log
+   labels (`offset=`, `current_offset=`), never invent.
+8. **Comments explain WHY, not WHAT.** Default to no comment. Add
+   one only when a hidden constraint, invariant, or workaround would
+   surprise a future reader. Never reference the current task or PR.
+9. **Never `cargo install`** or any package-manager mutation without
+   explicit authorization. Use the toolchain pinned in
+   `rust-toolchain.toml`. CI installs additional cargo tools on demand
+   per task.
+10. **No `unwrap()` / `expect()` on Results from external I/O** outside
+    tests. Acceptable in tests, in `const` init, and where the
+    invariant is locally provable.
+11. **`tokio::sync::Mutex` (not `std::sync::Mutex`)** wherever a lock
+    is held across `.await`. Hold locks briefly: lock, clone what
+    you need, drop the guard, then do I/O.
+12. **Code reads top to bottom like a book.** Public consts and
+    public functions first, helpers below, deeper helpers below
+    those. A reader scrolling top-down should hit each function
+    before any function it calls.
+13. **Zero clone in hot loops.** Per-message work runs millions of
+    times. Use `&self`, `&str`, `&[T]`. Prefer `Vec::with_capacity(n)`
+    when the size is known. For connector `Payload::Json`,
+    `try_to_bytes(&self)` serializes without cloning the tree.
+14. **Forward-compatible config.** New TOML fields use
+    `#[serde(default)]` or `Option<T>` so existing configs continue
+    to load.
+
+## Connectors-specific invariants
+
+Applied to any change under `core/connectors/`. The connectors skills
+expand on each of these.
+
+- **Every silent drop bumps a metric.** Intentional transform filter
+  (`Ok(None)`) -> `messages_filtered`. Anything else -> `errors`.
+  Pre-built `SinkLabels`/`SourceLabels` caches are threaded through
+  the hot path so metric calls avoid per-batch `String` allocations.
+- **Stage timings are always observed.** The
+  `iggy_connector_stage_duration_seconds` histogram populates
+  regardless of the per-connector `benchmark` flag. The flag only
+  gates the optional per-batch tracing event under the
+  `iggy_connectors::benchmark` target.
+- **FFI pointers are call-scoped.** Plugins must copy config and
+  state bytes if they need them past the call. The SDK macros do this
+  correctly. Do not bypass them.
+- **Serialization split:** FFI payloads use `postcard`, connector
+  configs use `serde_json`, connector state uses `rmp_serde`
+  (MessagePack). Stability vs editability vs compactness, in that
+  order. Do not mix.
+
+## Testing
+
+- **Unit tests** at the bottom of `src/lib.rs` (or per-module).
+- **In-crate integration tests** under `<crate>/tests/`.
+- **Cross-crate integration** under `core/integration/tests/`. The
+  harness (`core/integration/src/harness/`) spawns **real**
+  `iggy-server` processes (`ServerHandle`), the connectors runtime
+  (`ConnectorsRuntimeHandle`), the MCP server (`McpHandle`), and
+  client connections (`ClientHandle`). The `#[iggy_harness]` proc
+  macro (`core/harness_derive/`) wires fixtures and orchestrates
+  lifecycle. Suites cover `cli/`, `cluster/`, `config_provider/`,
+  `connectors/`, `data_integrity/`, `mcp/`, `sdk/`, `server/`
+  (scenarios, retention, message cleanup, concurrent access,
+  consumer groups), `state/`, and `storage/`. Inside `connectors/`,
+  external backends (Postgres, Elasticsearch, Mongo, Quickwit, etc.)
+  are spun up with `testcontainers-modules`. Test artifacts and
+  logs land in `test_logs/` for post-run inspection.
+- **Cross-SDK BDD** under `bdd/`. Gherkin features executed against
+  every language SDK. Driver: `scripts/run-bdd-tests.sh`.
+
+BDD test naming: `given_X_when_Y_should_Z` (3-part). Promote to
+4-part `given_X_when_Y_then_Z_should_W` only when there is a distinct
+intermediate "then" state worth naming. Be consistent within a file.
+
+Run a single integration test:
+
+```bash
+cargo test -p integration -- connectors::runtime::benchmark::given_logging_format_json
+```
+
+## Pitfalls a first-time agent will hit
+
+- **Docker is required for most integration tests.** Connector
+  backends (Postgres, Elasticsearch, Mongo, Quickwit, InfluxDB, ...)
+  spin up via `testcontainers-modules`. Without a running Docker
+  daemon, the affected suites fail at container startup, not at
+  assertion time.
+- **`cargo sort` without `--no-format` will churn the workspace.**
+  Plain `cargo sort --workspace` flattens multi-line feature arrays
+  in `Cargo.toml`, which `taplo` then re-expands. Always pass
+  `--no-format`. The pre-commit hook already does.
+- **The Rust toolchain is pinned to a specific version** in
+  `rust-toolchain.toml`. If your system `cargo` is older, builds
+  fail on transitive deps that require the pinned `rustc`. Prefer
+  rustup so the pin auto-resolves.
+- **`test_logs/` grows quickly.** Each integration test snapshots
+  `local_data` and server logs on exit. Wipe it between major
+  refactors to avoid disk pressure and stale-state confusion.
+- **Miri jobs cover `core/binary_protocol/` and `core/consensus/`.**
+  Any change touching `unsafe` in those crates needs extra review.
+  Miri does not work on crates that pull `compio` (`io_uring`
+  syscalls cannot be emulated), so do not try to expand Miri
+  coverage there.
+- **The integration crate has no `--test` target.** All tests live
+  in a single `mod.rs` binary. Filter by test path:
+  `cargo test -p integration -- connectors::runtime::benchmark`.
+- **Connector plugins are dlopened by path.** If you build with a
+  non-default target dir or in release mode, update the `path` field
+  in each connector TOML or the runtime will not find the `.so` /
+  `.dylib`.
+- **Secrets in plugin configs must use `SecretString`.** Plain
+  `String` fields containing credentials get logged on `Debug` and
+  serialized in plaintext in `/stats`. See the connectors skills for
+  the exact `secrecy` + `serde_secret::serialize_secret` pattern.
+
+## Local state directories
+
+Running the server, connectors runtime, or the test suite creates
+several gitignored directories at the repo root. They are safe to
+delete to reset local state:
+
+- `local_data/` - default server data dir (`messages_path`, etc.).
+- `local_state/` - connectors runtime state (`source_*.state` files).
+- `test_logs/` - per-test logs and `local_data` snapshots written by
+  the integration harness on test exit.
+- `performance_results/` - benchmark output (`./scripts/run-benches.sh`).
+- `target/` - cargo build output.
+
+If a test hang or crash leaves a stale `local_data` inside `test_logs/`,
+delete the offending subdirectory. The harness regenerates everything
+on the next run.
+
+## Commit and PR conventions
+
+- Conventional commits with scope: `feat(connectors): ...`,
+  `fix(server): ...`, `docs(sdk): ...`. Subject <= 72 chars.
+  Enforced by `.github/workflows/pr-title.yml` (allowed types and
+  scopes listed there).
+- Body answers "why was this needed?" before "what did you do?". No
+  bullet lists of files changed. Git already shows that.
+- Co-authored-by trailer when applicable.
+
+## Releases
+
+- Versions are kept in sync across the workspace and all SDKs by
+  `scripts/extract-version.sh --check` (pre-commit) and
+  `scripts/ci/sync-rust-version.sh` /
+  `scripts/ci/python-sdk-version-sync.sh`.
+- The Rust crate publish chain is verified by
+  `scripts/verify-crates-publish.sh` against a local
+  `cargo-http-registry` alt-registry.
+- Third-party license enumeration for each binary artifact is
+  produced by `scripts/ci/third-party-licenses.sh` (ASF release policy).
+
+## Discussion and support
+
+- Design discussions: <https://github.com/apache/iggy/discussions>
+- Community chat: <https://discord.gg/apache-iggy>
+- Documentation: <https://iggy.apache.org/docs/>
diff --git a/Cargo.lock b/Cargo.lock
index f835ac9ae..4dbc9e027 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13041,6 +13041,16 @@ dependencies = [
  "web-time",
 ]
 
+[[package]]
+name = "tracing-serde"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1"
+dependencies = [
+ "serde",
+ "tracing-core",
+]
+
 [[package]]
 name = "tracing-subscriber"
 version = "0.3.23"
@@ -13051,12 +13061,15 @@ dependencies = [
  "nu-ansi-term",
  "once_cell",
  "regex-automata",
+ "serde",
+ "serde_json",
  "sharded-slab",
  "smallvec",
  "thread_local",
  "tracing",
  "tracing-core",
  "tracing-log",
+ "tracing-serde",
 ]
 
 [[package]]
diff --git a/core/connectors/README.md b/core/connectors/README.md
index cdef67789..f955a4872 100644
--- a/core/connectors/README.md
+++ b/core/connectors/README.md
@@ -15,6 +15,8 @@ The [docker image](https://hub.docker.com/r/apache/iggy-connect) is available, a
 - **Data transformation**: Supports data transformation with the help of existing functions.
 - **Powerful configuration**: Define your sinks, sources, and transformations in the configuration file or fetch them from a remote HTTP API.
 - **Flexible configuration providers**: Support for local file-based and HTTP-based configuration providers for centralized configuration management.
+- **Observability**: Prometheus metrics with per-stage latency histograms, plus an opt-in per-batch tracing benchmark target.
+- **Structured logging**: Selectable text or JSON log format via `[logging]` configuration.
 
 ## Quick Start
 
diff --git a/core/connectors/runtime/Cargo.toml b/core/connectors/runtime/Cargo.toml
index bc43ea79a..0f7882267 100644
--- a/core/connectors/runtime/Cargo.toml
+++ b/core/connectors/runtime/Cargo.toml
@@ -74,7 +74,7 @@ toml = { workspace = true }
 tower-http = { workspace = true }
 tracing = { workspace = true }
 tracing-opentelemetry = { workspace = true }
-tracing-subscriber = { workspace = true }
+tracing-subscriber = { workspace = true, features = ["json"] }
 
 [dev-dependencies]
 tempfile = { workspace = true }
diff --git a/core/connectors/runtime/README.md b/core/connectors/runtime/README.md
index 8f4e0b854..a3ae11ba6 100644
--- a/core/connectors/runtime/README.md
+++ b/core/connectors/runtime/README.md
@@ -34,10 +34,24 @@ path = "local_state"
 [connectors]
 config_type = "local"
 config_dir = "path/to/connectors"
+
+[logging] # Optional logging configuration
+format = "text" # Options: "text" (default), "json"
 ```
 
 The path to the configuration can be overridden by `IGGY_CONNECTORS_CONFIG_PATH` environment variable. Each configuration section can be also additionally updated by using the following convention `IGGY_CONNECTORS_SECTION_NAME.KEY_NAME` e.g. `IGGY_CONNECTORS_IGGY_USERNAME` and so on.
 
+## Logging
+
+By default, the runtime emits human-readable text logs via the `tracing` crate. Switching `logging.format` to `json` produces structured JSON lines (one event per line, machine-parseable). When telemetry is enabled, the chosen format applies to the local stdout layer; OpenTelemetry export is unaffected.
+
+```toml
+[logging]
+format = "json"
+```
+
+`RUST_LOG` controls verbosity and per-target filtering (e.g. `RUST_LOG=info,iggy_connectors::benchmark=info`).
+
 ## Configuration Providers
 
 The runtime supports two types of configuration providers for managing connector configurations:
@@ -187,6 +201,24 @@ transport = "grpc" # Options: "grpc", "http"
 endpoint = "http://localhost:4317"
 ```
 
+## Benchmark Mode
+
+Each connector configuration accepts an optional `benchmark` flag. When set to `true`, the runtime emits a per-batch `info!` event on the `iggy_connectors::benchmark` tracing target with stage timings in microseconds. This is opt-in and adds a single tracing call per processed batch.
+
+```toml
+type = "sink"
+key = "stdout"
+# ... other fields ...
+benchmark = true
+```
+
+Emitted fields:
+
+- **sink**: `connector_key`, `stream`, `topic`, `partition_id`, `current_offset`, `batch_size`, `processed_count`, `prepare_us`, `ffi_us`, `total_us`
+- **source**: `connector_key`, `stream`, `topic`, `batch_size`, `sent_count`, `decode_us`, `prepare_us`, `iggy_send_us`, `state_save_us`, `total_us`
+
+Filter the stream via `RUST_LOG=iggy_connectors::benchmark=info`. The corresponding stage durations are also recorded in the `iggy_connector_stage_duration_seconds` histogram regardless of this flag, so Prometheus dashboards remain available without enabling text events.
+
 ## Metrics
 
 The runtime exposes Prometheus-compatible metrics via the `/metrics` endpoint when enabled. The following metrics are available:
@@ -204,8 +236,15 @@ The runtime exposes Prometheus-compatible metrics via the `/metrics` endpoint wh
 - `iggy_connector_messages_sent_total`: Messages sent to Iggy (source)
 - `iggy_connector_messages_consumed_total`: Messages consumed from Iggy (sink)
 - `iggy_connector_messages_processed_total`: Messages processed and sent to sink plugin
+- `iggy_connector_messages_filtered_total`: Messages intentionally dropped by transforms returning `Ok(None)`
 - `iggy_connector_errors_total`: Errors encountered
 
+### Stage Duration Histograms (labeled with `connector_key`, `connector_type`, `stage`)
+
+- `iggy_connector_stage_duration_seconds`: Per-batch processing stage duration
+
+Stages: `Prepare`, `Ffi`, `Decode`, `IggySend`, `StateSave`, `Total`. Histograms are always exposed (independent of `benchmark`); buckets cover 50us to 5s.
+
 ## Stats
 
 The `/stats` endpoint provides runtime and per-connector statistics in JSON format. This includes system resource usage, connector counts, and detailed per-connector metrics with version information.
@@ -239,6 +278,7 @@ The `/stats` endpoint provides runtime and per-connector statistics in JSON form
       "enabled": true,
       "messages_produced": 1000,
       "messages_sent": 1000,
+      "messages_filtered": 0,
       "errors": 0
     },
     {
@@ -251,6 +291,7 @@ The `/stats` endpoint provides runtime and per-connector statistics in JSON form
       "enabled": true,
       "messages_consumed": 1000,
       "messages_processed": 1000,
+      "messages_filtered": 0,
       "errors": 0
     }
   ]
diff --git a/core/connectors/runtime/src/benchmark.rs b/core/connectors/runtime/src/benchmark.rs
new file mode 100644
index 000000000..9c32418b5
--- /dev/null
+++ b/core/connectors/runtime/src/benchmark.rs
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use std::time::Duration;
+use tracing::info;
+
+/// Tracing target for per-batch benchmark events. Filter via
+/// `RUST_LOG=iggy_connectors::benchmark=info`.
+pub const TARGET: &str = "iggy_connectors::benchmark";
+
+#[inline]
+pub fn as_micros(elapsed: Duration) -> u64 {
+    elapsed.as_micros() as u64
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn emit_sink_event(
+    connector_key: &str,
+    stream: &str,
+    topic: &str,
+    partition_id: u32,
+    current_offset: u64,
+    batch_size: usize,
+    processed_count: usize,
+    prepare_us: u64,
+    ffi_us: u64,
+    total_us: u64,
+) {
+    info!(
+        target: TARGET,
+        connector_type = "sink",
+        connector_key = connector_key,
+        stream = stream,
+        topic = topic,
+        partition_id = partition_id,
+        current_offset = current_offset,
+        batch_size = batch_size,
+        processed_count = processed_count,
+        prepare_us = prepare_us,
+        ffi_us = ffi_us,
+        total_us = total_us,
+        "benchmark"
+    );
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn emit_source_event(
+    connector_key: &str,
+    stream: &str,
+    topic: &str,
+    batch_size: usize,
+    sent_count: usize,
+    decode_us: u64,
+    prepare_us: u64,
+    iggy_send_us: u64,
+    state_save_us: u64,
+    total_us: u64,
+) {
+    info!(
+        target: TARGET,
+        connector_type = "source",
+        connector_key = connector_key,
+        stream = stream,
+        topic = topic,
+        batch_size = batch_size,
+        sent_count = sent_count,
+        decode_us = decode_us,
+        prepare_us = prepare_us,
+        iggy_send_us = iggy_send_us,
+        state_save_us = state_save_us,
+        total_us = total_us,
+        "benchmark"
+    );
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::sync::{Arc, Mutex};
+    use tracing::Subscriber;
+    use tracing::field::{Field, Visit};
+    use tracing_subscriber::Layer;
+    use tracing_subscriber::layer::Context;
+    use tracing_subscriber::layer::SubscriberExt;
+    use tracing_subscriber::registry::Registry;
+
+    #[derive(Debug, Default, Clone)]
+    struct CapturedEvent {
+        target: String,
+        message: String,
+        fields: std::collections::BTreeMap<String, String>,
+    }
+
+    struct CaptureLayer {
+        events: Arc<Mutex<Vec<CapturedEvent>>>,
+    }
+
+    struct FieldVisitor<'a> {
+        out: &'a mut std::collections::BTreeMap<String, String>,
+        message: &'a mut String,
+    }
+
+    impl Visit for FieldVisitor<'_> {
+        fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
+            if field.name() == "message" {
+                *self.message = format!("{value:?}");
+            } else {
+                self.out
+                    .insert(field.name().to_string(), format!("{value:?}"));
+            }
+        }
+
+        fn record_str(&mut self, field: &Field, value: &str) {
+            if field.name() == "message" {
+                *self.message = value.to_string();
+            } else {
+                self.out.insert(field.name().to_string(), value.to_string());
+            }
+        }
+
+        fn record_u64(&mut self, field: &Field, value: u64) {
+            self.out.insert(field.name().to_string(), value.to_string());
+        }
+
+        fn record_i64(&mut self, field: &Field, value: i64) {
+            self.out.insert(field.name().to_string(), value.to_string());
+        }
+    }
+
+    impl<S: Subscriber> Layer<S> for CaptureLayer {
+        fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
+            let mut captured = CapturedEvent {
+                target: event.metadata().target().to_string(),
+                ..Default::default()
+            };
+            let mut visitor = FieldVisitor {
+                out: &mut captured.fields,
+                message: &mut captured.message,
+            };
+            event.record(&mut visitor);
+            self.events.lock().unwrap().push(captured);
+        }
+    }
+
+    fn capture<F: FnOnce()>(emit: F) -> Vec<CapturedEvent> {
+        let events: Arc<Mutex<Vec<CapturedEvent>>> = Arc::new(Mutex::new(Vec::new()));
+        let layer = CaptureLayer {
+            events: events.clone(),
+        };
+        let subscriber = Registry::default().with(layer);
+        tracing::subscriber::with_default(subscriber, emit);
+        let guard = events.lock().unwrap();
+        guard.clone()
+    }
+
+    #[test]
+    fn given_zero_duration_when_formatted_should_be_zero_micros() {
+        assert_eq!(as_micros(Duration::from_secs(0)), 0);
+    }
+
+    #[test]
+    fn given_some_duration_when_formatted_should_match_micros() {
+        assert_eq!(as_micros(Duration::from_micros(1234)), 1234);
+    }
+
+    #[test]
+    fn given_sink_event_emitted_when_captured_should_contain_all_fields() {
+        let events = capture(|| {
+            emit_sink_event("postgres", "qw", "records", 0, 100, 50, 50, 234, 1456, 1700);
+        });
+        let event = events
+            .iter()
+            .find(|event| event.target == TARGET && event.message == "benchmark")
+            .expect("benchmark event should be captured");
+        assert_eq!(event.fields.get("connector_type").unwrap(), "sink");
+        assert_eq!(event.fields.get("connector_key").unwrap(), "postgres");
+        assert_eq!(event.fields.get("stream").unwrap(), "qw");
+        assert_eq!(event.fields.get("topic").unwrap(), "records");
+        assert_eq!(event.fields.get("batch_size").unwrap(), "50");
+        assert_eq!(event.fields.get("processed_count").unwrap(), "50");
+        assert_eq!(event.fields.get("prepare_us").unwrap(), "234");
+        assert_eq!(event.fields.get("ffi_us").unwrap(), "1456");
+        assert_eq!(event.fields.get("total_us").unwrap(), "1700");
+    }
+
+    #[test]
+    fn given_source_event_emitted_when_captured_should_contain_all_fields() {
+        let events = capture(|| {
+            emit_source_event(
+                "random",
+                "example_stream",
+                "example_topic",
+                25,
+                23,
+                12,
+                34,
+                567,
+                89,
+                750,
+            );
+        });
+        let event = events
+            .iter()
+            .find(|event| event.target == TARGET && event.message == "benchmark")
+            .expect("benchmark event should be captured");
+        assert_eq!(event.fields.get("connector_type").unwrap(), "source");
+        assert_eq!(event.fields.get("connector_key").unwrap(), "random");
+        assert_eq!(event.fields.get("batch_size").unwrap(), "25");
+        assert_eq!(event.fields.get("sent_count").unwrap(), "23");
+        assert_eq!(event.fields.get("decode_us").unwrap(), "12");
+        assert_eq!(event.fields.get("prepare_us").unwrap(), "34");
+        assert_eq!(event.fields.get("iggy_send_us").unwrap(), "567");
+        assert_eq!(event.fields.get("state_save_us").unwrap(), "89");
+        assert_eq!(event.fields.get("total_us").unwrap(), "750");
+    }
+}
diff --git a/core/connectors/runtime/src/configs/connectors.rs b/core/connectors/runtime/src/configs/connectors.rs
index 70e4f18a9..ae788a8f1 100644
--- a/core/connectors/runtime/src/configs/connectors.rs
+++ b/core/connectors/runtime/src/configs/connectors.rs
@@ -84,6 +84,8 @@ pub struct CreateSinkConfig {
     pub plugin_config: Option<serde_json::Value>,
     #[serde(default)]
     pub verbose: bool,
+    #[serde(default)]
+    pub benchmark: bool,
 }
 
 impl CreateSinkConfig {
@@ -99,6 +101,7 @@ impl CreateSinkConfig {
             plugin_config_format: self.plugin_config_format,
             plugin_config: self.plugin_config.clone(),
             verbose: self.verbose,
+            benchmark: self.benchmark,
         }
     }
 }
@@ -119,6 +122,8 @@ pub struct SinkConfig {
     pub plugin_config: Option<serde_json::Value>,
     #[serde(default)]
     pub verbose: bool,
+    #[serde(default)]
+    pub benchmark: bool,
 }
 
 #[derive(Debug, Default, Clone, Serialize, Deserialize)]
@@ -132,6 +137,8 @@ pub struct CreateSourceConfig {
     pub plugin_config: Option<serde_json::Value>,
     #[serde(default)]
     pub verbose: bool,
+    #[serde(default)]
+    pub benchmark: bool,
 }
 
 impl CreateSourceConfig {
@@ -147,6 +154,7 @@ impl CreateSourceConfig {
             plugin_config_format: self.plugin_config_format,
             plugin_config: self.plugin_config.clone(),
             verbose: self.verbose,
+            benchmark: self.benchmark,
         }
     }
 }
@@ -167,6 +175,8 @@ pub struct SourceConfig {
     pub plugin_config: Option<serde_json::Value>,
     #[serde(default)]
     pub verbose: bool,
+    #[serde(default)]
+    pub benchmark: bool,
 }
 
 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
diff --git a/core/connectors/runtime/src/configs/runtime.rs b/core/connectors/runtime/src/configs/runtime.rs
index adbae2fb5..d716c93dc 100644
--- a/core/connectors/runtime/src/configs/runtime.rs
+++ b/core/connectors/runtime/src/configs/runtime.rs
@@ -142,6 +142,89 @@ pub struct ConnectorsRuntimeConfig {
     pub connectors: ConnectorsConfig,
     pub state: StateConfig,
     pub telemetry: TelemetryConfig,
+    pub logging: LoggingConfig,
+}
+
+#[derive(Debug, Default, Clone, Deserialize, Serialize, ConfigEnv)]
+pub struct LoggingConfig {
+    #[serde(default)]
+    #[config_env(leaf)]
+    pub format: LogFormat,
+}
+
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum LogFormat {
+    #[default]
+    Text,
+    Json,
+}
+
+impl Display for LogFormat {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        match self {
+            LogFormat::Text => write!(f, "text"),
+            LogFormat::Json => write!(f, "json"),
+        }
+    }
+}
+
+impl FromStr for LogFormat {
+    type Err = String;
+    fn from_str(s: &str) -> Result<Self, Self::Err> {
+        match s.to_ascii_lowercase().as_str() {
+            "text" => Ok(LogFormat::Text),
+            "json" => Ok(LogFormat::Json),
+            other => Err(format!("Invalid log format: {other}")),
+        }
+    }
+}
+
+#[cfg(test)]
+mod log_format_tests {
+    use super::*;
+
+    #[test]
+    fn given_no_explicit_value_when_defaulted_should_be_text() {
+        assert_eq!(LogFormat::default(), LogFormat::Text);
+    }
+
+    #[test]
+    fn given_text_string_when_parsed_should_return_text_variant() {
+        assert_eq!(LogFormat::from_str("text").unwrap(), LogFormat::Text);
+        assert_eq!(LogFormat::from_str("TEXT").unwrap(), LogFormat::Text);
+    }
+
+    #[test]
+    fn given_json_string_when_parsed_should_return_json_variant() {
+        assert_eq!(LogFormat::from_str("json").unwrap(), LogFormat::Json);
+        assert_eq!(LogFormat::from_str("Json").unwrap(), LogFormat::Json);
+    }
+
+    #[test]
+    fn given_invalid_string_when_parsed_should_return_err() {
+        assert!(LogFormat::from_str("yaml").is_err());
+        assert!(LogFormat::from_str("").is_err());
+    }
+
+    #[test]
+    fn given_log_format_when_displayed_should_match_lowercase_variant_name() {
+        assert_eq!(LogFormat::Text.to_string(), "text");
+        assert_eq!(LogFormat::Json.to_string(), "json");
+    }
+
+    #[test]
+    fn given_toml_with_logging_section_when_deserialized_should_use_format() {
+        let toml = r#"format = "json""#;
+        let parsed: LoggingConfig = toml::from_str(toml).expect("parse logging");
+        assert_eq!(parsed.format, LogFormat::Json);
+    }
+
+    #[test]
+    fn given_toml_without_format_field_when_deserialized_should_default_to_text() {
+        let parsed: LoggingConfig = toml::from_str("").expect("parse empty logging");
+        assert_eq!(parsed.format, LogFormat::Text);
+    }
 }
 
 #[derive(Debug, Clone, Serialize, Deserialize, ConfigEnv)]
diff --git a/core/connectors/runtime/src/error.rs b/core/connectors/runtime/src/error.rs
index 0f6705faf..d56d2e38a 100644
--- a/core/connectors/runtime/src/error.rs
+++ b/core/connectors/runtime/src/error.rs
@@ -29,8 +29,6 @@ pub enum RuntimeError {
     FailedToSerializeMessagesMetadata,
     #[error("Failed to serialize raw messages")]
     FailedToSerializeRawMessages,
-    #[error("Failed to serialize headers")]
-    FailedToSerializeHeaders,
     #[error("Connector SDK error")]
     ConnectorSdkError(#[from] iggy_connector_sdk::Error),
     #[error("Iggy client error")]
diff --git a/core/connectors/runtime/src/log.rs b/core/connectors/runtime/src/log.rs
index 3dd40b496..91923e618 100644
--- a/core/connectors/runtime/src/log.rs
+++ b/core/connectors/runtime/src/log.rs
@@ -17,7 +17,7 @@
  * under the License.
  */
 
-use crate::configs::runtime::{TelemetryConfig, TelemetryTransport};
+use crate::configs::runtime::{LogFormat, LoggingConfig, TelemetryConfig, TelemetryTransport};
 use iggy_connector_sdk::LogCallback;
 use opentelemetry::trace::TracerProvider;
 use opentelemetry::{KeyValue, global};
@@ -31,38 +31,58 @@ use tracing_subscriber::EnvFilter;
 use tracing_subscriber::layer::SubscriberExt;
 use tracing_subscriber::util::SubscriberInitExt;
 
-pub fn init_logging(telemetry_config: &TelemetryConfig, version: &'static str) {
-    let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("INFO"));
-
-    let fmt_layer = tracing_subscriber::fmt::layer();
+pub fn init_logging(
+    telemetry_config: &TelemetryConfig,
+    logging_config: &LoggingConfig,
+    version: &'static str,
+) {
+    let env_filter =
+        || EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("INFO"));
+
+    match (telemetry_config.enabled, logging_config.format) {
+        (true, LogFormat::Text) => {
+            let (logger_provider, tracer_provider) = init_telemetry(telemetry_config, version);
+            let tracer = tracer_provider.tracer(telemetry_config.service_name.clone());
+            global::set_tracer_provider(tracer_provider);
+            global::set_text_map_propagator(TraceContextPropagator::new());
+            tracing_subscriber::registry()
+                .with(env_filter())
+                .with(tracing_subscriber::fmt::layer())
+                .with(OpenTelemetryTracingBridge::new(&logger_provider))
+                .with(OpenTelemetryLayer::new(tracer))
+                .init();
+        }
+        (true, LogFormat::Json) => {
+            let (logger_provider, tracer_provider) = init_telemetry(telemetry_config, version);
+            let tracer = tracer_provider.tracer(telemetry_config.service_name.clone());
+            global::set_tracer_provider(tracer_provider);
+            global::set_text_map_propagator(TraceContextPropagator::new());
+            tracing_subscriber::registry()
+                .with(env_filter())
+                .with(tracing_subscriber::fmt::layer().json())
+                .with(OpenTelemetryTracingBridge::new(&logger_provider))
+                .with(OpenTelemetryLayer::new(tracer))
+                .init();
+        }
+        (false, LogFormat::Text) => {
+            tracing_subscriber::registry()
+                .with(env_filter())
+                .with(tracing_subscriber::fmt::layer())
+                .init();
+        }
+        (false, LogFormat::Json) => {
+            tracing_subscriber::registry()
+                .with(env_filter())
+                .with(tracing_subscriber::fmt::layer().json())
+                .init();
+        }
+    }
 
     if telemetry_config.enabled {
-        let (logger_provider, tracer_provider) = init_telemetry(telemetry_config, version);
-
-        let service_name = telemetry_config.service_name.clone();
-        let tracer = tracer_provider.tracer(service_name);
-        global::set_tracer_provider(tracer_provider);
-        global::set_text_map_propagator(TraceContextPropagator::new());
-
-        let otel_logs_layer = OpenTelemetryTracingBridge::new(&logger_provider);
-        let otel_traces_layer = OpenTelemetryLayer::new(tracer);
-
-        tracing_subscriber::registry()
-            .with(env_filter)
-            .with(fmt_layer)
-            .with(otel_logs_layer)
-            .with(otel_traces_layer)
-            .init();
-
         info!(
-            "Logging initialized with telemetry enabled, service name: {}",
-            telemetry_config.service_name
+            "Logging initialized (format: {}, telemetry enabled, service name: {})",
+            logging_config.format, telemetry_config.service_name
         );
-    } else {
-        tracing_subscriber::registry()
-            .with(env_filter)
-            .with(fmt_layer)
-            .init();
     }
 }
 
diff --git a/core/connectors/runtime/src/main.rs b/core/connectors/runtime/src/main.rs
index 45ccff667..97baaf03f 100644
--- a/core/connectors/runtime/src/main.rs
+++ b/core/connectors/runtime/src/main.rs
@@ -44,6 +44,7 @@ use std::{
 use tracing::{error, info};
 
 mod api;
+mod benchmark;
 pub(crate) mod configs;
 pub(crate) mod context;
 pub(crate) mod error;
@@ -138,7 +139,7 @@ async fn main() -> Result<(), RuntimeError> {
         .await
         .expect("Failed to load configuration");
 
-    log::init_logging(&config.telemetry, VERSION);
+    log::init_logging(&config.telemetry, &config.logging, VERSION);
 
     std::fs::create_dir_all(&config.state.path).expect("Failed to create state directory");
 
@@ -418,6 +419,7 @@ struct SinkConnectorPlugin {
     consumers: Vec<SinkConnectorConsumer>,
     error: Option<String>,
     verbose: bool,
+    benchmark: bool,
 }
 
 struct SinkConnectorConsumer {
@@ -449,6 +451,7 @@ struct SourceConnectorPlugin {
     state_storage: StateStorage,
     error: Option<String>,
     verbose: bool,
+    benchmark: bool,
 }
 
 struct SourceConnectorProducer {
diff --git a/core/connectors/runtime/src/manager/sink.rs b/core/connectors/runtime/src/manager/sink.rs
index 9c6cafa1e..1660684ff 100644
--- a/core/connectors/runtime/src/manager/sink.rs
+++ b/core/connectors/runtime/src/manager/sink.rs
@@ -214,6 +214,7 @@ impl SinkManager {
             consumers,
             callback,
             config.verbose,
+            config.benchmark,
             metrics,
             context.clone(),
         );
diff --git a/core/connectors/runtime/src/manager/source.rs b/core/connectors/runtime/src/manager/source.rs
index 14fbb2c0d..2f4c6b03b 100644
--- a/core/connectors/runtime/src/manager/source.rs
+++ b/core/connectors/runtime/src/manager/source.rs
@@ -218,6 +218,7 @@ impl SourceManager {
             plugin_id,
             key,
             config.verbose,
+            config.benchmark,
             producer,
             encoder,
             transforms,
diff --git a/core/connectors/runtime/src/metrics.rs b/core/connectors/runtime/src/metrics.rs
index 8d9c29cdb..3f14e8763 100644
--- a/core/connectors/runtime/src/metrics.rs
+++ b/core/connectors/runtime/src/metrics.rs
@@ -22,8 +22,10 @@ use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue};
 use prometheus_client::metrics::counter::Counter;
 use prometheus_client::metrics::family::Family;
 use prometheus_client::metrics::gauge::Gauge;
+use prometheus_client::metrics::histogram::Histogram;
 use prometheus_client::registry::Registry;
 use std::sync::Arc;
+use std::time::Duration;
 use tracing::error;
 
 #[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
@@ -38,6 +40,94 @@ pub enum ConnectorType {
     Sink,
 }
 
+#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
+pub struct StageLabels {
+    pub connector_key: String,
+    pub connector_type: ConnectorType,
+    pub stage: Stage,
+}
+
+#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelValue)]
+pub enum Stage {
+    Prepare,
+    Ffi,
+    Decode,
+    IggySend,
+    StateSave,
+    Total,
+}
+
+const STAGE_BUCKETS_SECONDS: [f64; 13] = [
+    50e-6, 100e-6, 250e-6, 500e-6, 1e-3, 5e-3, 10e-3, 50e-3, 100e-3, 250e-3, 500e-3, 1.0, 5.0,
+];
+
+#[derive(Debug, Clone)]
+pub struct SinkLabels {
+    pub counter: ConnectorLabels,
+    pub stage_prepare: StageLabels,
+    pub stage_ffi: StageLabels,
+    pub stage_total: StageLabels,
+}
+
+impl SinkLabels {
+    pub fn new(plugin_key: &str) -> Self {
+        let key = plugin_key.to_owned();
+        Self {
+            counter: ConnectorLabels {
+                connector_key: key.clone(),
+                connector_type: ConnectorType::Sink,
+            },
+            stage_prepare: StageLabels {
+                connector_key: key.clone(),
+                connector_type: ConnectorType::Sink,
+                stage: Stage::Prepare,
+            },
+            stage_ffi: StageLabels {
+                connector_key: key.clone(),
+                connector_type: ConnectorType::Sink,
+                stage: Stage::Ffi,
+            },
+            stage_total: StageLabels {
+                connector_key: key,
+                connector_type: ConnectorType::Sink,
+                stage: Stage::Total,
+            },
+        }
+    }
+}
+
+#[derive(Debug, Clone)]
+pub struct SourceLabels {
+    pub counter: ConnectorLabels,
+    pub stage_decode: StageLabels,
+    pub stage_prepare: StageLabels,
+    pub stage_iggy_send: StageLabels,
+    pub stage_state_save: StageLabels,
+    pub stage_total: StageLabels,
+}
+
+impl SourceLabels {
+    pub fn new(plugin_key: &str) -> Self {
+        let key = plugin_key.to_owned();
+        let stage = |s: Stage| StageLabels {
+            connector_key: key.clone(),
+            connector_type: ConnectorType::Source,
+            stage: s,
+        };
+        Self {
+            counter: ConnectorLabels {
+                connector_key: key.clone(),
+                connector_type: ConnectorType::Source,
+            },
+            stage_decode: stage(Stage::Decode),
+            stage_prepare: stage(Stage::Prepare),
+            stage_iggy_send: stage(Stage::IggySend),
+            stage_state_save: stage(Stage::StateSave),
+            stage_total: stage(Stage::Total),
+        }
+    }
+}
+
 #[derive(Debug, Clone)]
 pub struct Metrics {
     registry: Arc<Registry>,
@@ -49,7 +139,9 @@ pub struct Metrics {
     messages_sent: Family<ConnectorLabels, Counter>,
     messages_consumed: Family<ConnectorLabels, Counter>,
     messages_processed: Family<ConnectorLabels, Counter>,
+    messages_filtered: Family<ConnectorLabels, Counter>,
     errors: Family<ConnectorLabels, Counter>,
+    stage_duration_seconds: Family<StageLabels, Histogram, fn() -> Histogram>,
 }
 
 impl Metrics {
@@ -64,7 +156,10 @@ impl Metrics {
         let messages_sent = Family::<ConnectorLabels, Counter>::default();
         let messages_consumed = Family::<ConnectorLabels, Counter>::default();
         let messages_processed = Family::<ConnectorLabels, Counter>::default();
+        let messages_filtered = Family::<ConnectorLabels, Counter>::default();
         let errors = Family::<ConnectorLabels, Counter>::default();
+        let stage_duration_seconds: Family<StageLabels, Histogram, fn() -> Histogram> =
+            Family::new_with_constructor(stage_histogram);
 
         registry.register(
             "iggy_connectors_sources_total",
@@ -106,11 +201,21 @@ impl Metrics {
             "Messages processed and sent to sink plugin",
             messages_processed.clone(),
         );
+        registry.register(
+            "iggy_connector_messages_filtered_total",
+            "Messages intentionally dropped by transforms returning Ok(None)",
+            messages_filtered.clone(),
+        );
         registry.register(
             "iggy_connector_errors_total",
             "Errors encountered",
             errors.clone(),
         );
+        registry.register(
+            "iggy_connector_stage_duration_seconds",
+            "Per-batch processing stage duration in seconds",
+            stage_duration_seconds.clone(),
+        );
 
         Self {
             registry: Arc::new(registry),
@@ -122,7 +227,9 @@ impl Metrics {
             messages_sent,
             messages_consumed,
             messages_processed,
+            messages_filtered,
             errors,
+            stage_duration_seconds,
         }
     }
 
@@ -174,49 +281,120 @@ impl Metrics {
         self.sinks_running.dec();
     }
 
+    pub fn observe_stage_with_labels(&self, labels: &StageLabels, duration: Duration) {
+        self.stage_duration_seconds
+            .get_or_create(labels)
+            .observe(duration.as_secs_f64());
+    }
+
+    #[cfg(test)]
     pub fn increment_messages_produced(&self, key: &str, count: u64) {
-        self.messages_produced
-            .get_or_create(&ConnectorLabels {
+        self.inc_messages_produced_with_labels(
+            &ConnectorLabels {
                 connector_key: key.to_owned(),
                 connector_type: ConnectorType::Source,
-            })
-            .inc_by(count);
+            },
+            count,
+        );
     }
 
+    #[cfg(test)]
     pub fn increment_messages_sent(&self, key: &str, count: u64) {
-        self.messages_sent
-            .get_or_create(&ConnectorLabels {
+        self.inc_messages_sent_with_labels(
+            &ConnectorLabels {
                 connector_key: key.to_owned(),
                 connector_type: ConnectorType::Source,
-            })
-            .inc_by(count);
+            },
+            count,
+        );
     }
 
+    #[cfg(test)]
     pub fn increment_messages_consumed(&self, key: &str, count: u64) {
-        self.messages_consumed
-            .get_or_create(&ConnectorLabels {
+        self.inc_messages_consumed_with_labels(
+            &ConnectorLabels {
                 connector_key: key.to_owned(),
                 connector_type: ConnectorType::Sink,
-            })
-            .inc_by(count);
+            },
+            count,
+        );
     }
 
+    #[cfg(test)]
     pub fn increment_messages_processed(&self, key: &str, count: u64) {
-        self.messages_processed
-            .get_or_create(&ConnectorLabels {
+        self.inc_messages_processed_with_labels(
+            &ConnectorLabels {
                 connector_key: key.to_owned(),
                 connector_type: ConnectorType::Sink,
-            })
-            .inc_by(count);
+            },
+            count,
+        );
     }
 
+    #[cfg(test)]
+    pub fn increment_messages_filtered(
+        &self,
+        key: &str,
+        connector_type: ConnectorType,
+        count: u64,
+    ) {
+        self.inc_messages_filtered_with_labels(
+            &ConnectorLabels {
+                connector_key: key.to_owned(),
+                connector_type,
+            },
+            count,
+        );
+    }
+
+    #[cfg(test)]
     pub fn increment_errors(&self, key: &str, connector_type: ConnectorType) {
-        self.errors
-            .get_or_create(&ConnectorLabels {
+        self.inc_errors_with_labels(&ConnectorLabels {
+            connector_key: key.to_owned(),
+            connector_type,
+        });
+    }
+
+    #[cfg(test)]
+    pub fn observe_stage_duration(
+        &self,
+        key: &str,
+        connector_type: ConnectorType,
+        stage: Stage,
+        duration: Duration,
+    ) {
+        self.observe_stage_with_labels(
+            &StageLabels {
                 connector_key: key.to_owned(),
                 connector_type,
-            })
-            .inc();
+                stage,
+            },
+            duration,
+        );
+    }
+
+    pub fn inc_messages_produced_with_labels(&self, labels: &ConnectorLabels, count: u64) {
+        self.messages_produced.get_or_create(labels).inc_by(count);
+    }
+
+    pub fn inc_messages_sent_with_labels(&self, labels: &ConnectorLabels, count: u64) {
+        self.messages_sent.get_or_create(labels).inc_by(count);
+    }
+
+    pub fn inc_messages_consumed_with_labels(&self, labels: &ConnectorLabels, count: u64) {
+        self.messages_consumed.get_or_create(labels).inc_by(count);
+    }
+
+    pub fn inc_messages_processed_with_labels(&self, labels: &ConnectorLabels, count: u64) {
+        self.messages_processed.get_or_create(labels).inc_by(count);
+    }
+
+    pub fn inc_messages_filtered_with_labels(&self, labels: &ConnectorLabels, count: u64) {
+        self.messages_filtered.get_or_create(labels).inc_by(count);
+    }
+
+    pub fn inc_errors_with_labels(&self, labels: &ConnectorLabels) {
+        self.errors.get_or_create(labels).inc();
     }
 
     pub fn get_messages_produced(&self, key: &str) -> u64 {
@@ -263,6 +441,49 @@ impl Metrics {
             })
             .get()
     }
+
+    pub fn get_messages_filtered(&self, key: &str, connector_type: ConnectorType) -> u64 {
+        self.messages_filtered
+            .get_or_create(&ConnectorLabels {
+                connector_key: key.to_owned(),
+                connector_type,
+            })
+            .get()
+    }
+
+    #[cfg(test)]
+    pub(crate) fn get_stage_duration_sample_count(
+        &self,
+        key: &str,
+        connector_type: ConnectorType,
+        stage: Stage,
+    ) -> u64 {
+        let output = self.get_formatted_output();
+        let stage_label = match stage {
+            Stage::Prepare => "Prepare",
+            Stage::Ffi => "Ffi",
+            Stage::Decode => "Decode",
+            Stage::IggySend => "IggySend",
+            Stage::StateSave => "StateSave",
+            Stage::Total => "Total",
+        };
+        let type_label = match connector_type {
+            ConnectorType::Source => "Source",
+            ConnectorType::Sink => "Sink",
+        };
+        let needle = format!(
+            "iggy_connector_stage_duration_seconds_count{{connector_key=\"{key}\",connector_type=\"{type_label}\",stage=\"{stage_label}\"}}"
+        );
+        output
+            .lines()
+            .find_map(|line| line.strip_prefix(&needle))
+            .and_then(|rest| rest.trim().parse::<u64>().ok())
+            .unwrap_or(0)
+    }
+}
+
+fn stage_histogram() -> Histogram {
+    Histogram::new(STAGE_BUCKETS_SECONDS.iter().copied())
 }
 
 #[cfg(test)]
@@ -475,4 +696,117 @@ mod tests {
         assert_eq!(metrics.get_errors("test-sink", ConnectorType::Sink), 1);
         assert_eq!(metrics.get_errors("nonexistent", ConnectorType::Source), 0);
     }
+
+    #[test]
+    fn given_filtered_counter_when_incremented_should_register_under_labels() {
+        let metrics = Metrics::init();
+        metrics.increment_messages_filtered("filter-source", ConnectorType::Source, 7);
+        metrics.increment_messages_filtered("filter-sink", ConnectorType::Sink, 3);
+        metrics.increment_messages_filtered("filter-source", ConnectorType::Source, 5);
+
+        assert_eq!(
+            metrics.get_messages_filtered("filter-source", ConnectorType::Source),
+            12
+        );
+        assert_eq!(
+            metrics.get_messages_filtered("filter-sink", ConnectorType::Sink),
+            3
+        );
+        assert_eq!(
+            metrics.get_messages_filtered("nonexistent", ConnectorType::Source),
+            0
+        );
+
+        let output = metrics.get_formatted_output();
+        assert!(output.contains("iggy_connector_messages_filtered_total"));
+        assert!(output.contains("connector_key=\"filter-source\""));
+        assert!(output.contains("connector_key=\"filter-sink\""));
+    }
+
+    #[test]
+    fn given_filtered_counter_unique_per_connector_type_when_same_key_should_be_separate() {
+        let metrics = Metrics::init();
+        metrics.increment_messages_filtered("shared", ConnectorType::Source, 2);
+        metrics.increment_messages_filtered("shared", ConnectorType::Sink, 4);
+
+        assert_eq!(
+            metrics.get_messages_filtered("shared", ConnectorType::Source),
+            2
+        );
+        assert_eq!(
+            metrics.get_messages_filtered("shared", ConnectorType::Sink),
+            4
+        );
+    }
+
+    #[test]
+    fn given_stage_histogram_when_observations_recorded_should_increment_sample_count() {
+        let metrics = Metrics::init();
+        metrics.observe_stage_duration(
+            "pg",
+            ConnectorType::Sink,
+            Stage::Prepare,
+            Duration::from_micros(120),
+        );
+        metrics.observe_stage_duration(
+            "pg",
+            ConnectorType::Sink,
+            Stage::Prepare,
+            Duration::from_micros(340),
+        );
+        metrics.observe_stage_duration(
+            "pg",
+            ConnectorType::Sink,
+            Stage::Ffi,
+            Duration::from_millis(2),
+        );
+
+        assert_eq!(
+            metrics.get_stage_duration_sample_count("pg", ConnectorType::Sink, Stage::Prepare),
+            2
+        );
+        assert_eq!(
+            metrics.get_stage_duration_sample_count("pg", ConnectorType::Sink, Stage::Ffi),
+            1
+        );
+        assert_eq!(
+            metrics.get_stage_duration_sample_count("pg", ConnectorType::Sink, Stage::Total),
+            0
+        );
+    }
+
+    #[test]
+    fn given_stage_histogram_when_encoded_should_expose_bucket_metrics() {
+        let metrics = Metrics::init();
+        metrics.observe_stage_duration(
+            "es",
+            ConnectorType::Source,
+            Stage::IggySend,
+            Duration::from_micros(750),
+        );
+        let output = metrics.get_formatted_output();
+        assert!(output.contains("iggy_connector_stage_duration_seconds"));
+        assert!(output.contains("connector_key=\"es\""));
+        assert!(output.contains("stage=\"IggySend\""));
+        assert!(output.contains("iggy_connector_stage_duration_seconds_bucket"));
+        assert!(output.contains("iggy_connector_stage_duration_seconds_count"));
+        assert!(output.contains("iggy_connector_stage_duration_seconds_sum"));
+    }
+
+    #[test]
+    fn given_stage_histogram_when_same_label_set_used_twice_should_share_bucket() {
+        let metrics = Metrics::init();
+        for _ in 0..5 {
+            metrics.observe_stage_duration(
+                "k",
+                ConnectorType::Sink,
+                Stage::Total,
+                Duration::from_micros(80),
+            );
+        }
+        assert_eq!(
+            metrics.get_stage_duration_sample_count("k", ConnectorType::Sink, Stage::Total),
+            5
+        );
+    }
 }
diff --git a/core/connectors/runtime/src/sink.rs b/core/connectors/runtime/src/sink.rs
index 0ab3c9547..bd72bc4c6 100644
--- a/core/connectors/runtime/src/sink.rs
+++ b/core/connectors/runtime/src/sink.rs
@@ -17,10 +17,11 @@
  * under the License.
  */
 
+use crate::benchmark;
 use crate::configs::connectors::SinkConfig;
 use crate::context::RuntimeContext;
 use crate::log::LOG_CALLBACK;
-use crate::metrics::Metrics;
+use crate::metrics::{Metrics, SinkLabels};
 use crate::{
     FailedPlugin, PLUGIN_ID, RuntimeError, SinkApi, SinkConnector, SinkConnectorConsumer,
     SinkConnectorPlugin, SinkConnectorWrapper, resolve_plugin_path, transform,
@@ -147,6 +148,7 @@ pub async fn init(
             consumers: vec![],
             error: init_error.clone(),
             verbose: config.verbose,
+            benchmark: config.benchmark,
         });
 
         if let Some(error) = init_error {
@@ -228,6 +230,7 @@ pub fn consume(
                 consumers,
                 sink.callback,
                 plugin.verbose,
+                plugin.benchmark,
                 &context.metrics,
                 context.clone(),
             );
@@ -237,7 +240,7 @@ pub fn consume(
     handles
 }
 
-#[allow(clippy::type_complexity)]
+#[allow(clippy::type_complexity, clippy::too_many_arguments)]
 pub(crate) fn spawn_consume_tasks(
     plugin_id: u32,
     plugin_key: &str,
@@ -249,16 +252,25 @@ pub(crate) fn spawn_consume_tasks(
     )>,
     callback: ConsumeCallback,
     verbose: bool,
+    benchmark: bool,
     metrics: &Arc<Metrics>,
     context: Arc<RuntimeContext>,
 ) -> (watch::Sender<()>, Vec<JoinHandle<()>>) {
+    if benchmark {
+        info!(
+            "Benchmark mode enabled for sink connector with ID: {plugin_id}, key: {plugin_key}. \
+             Per-batch events on target 'iggy_connectors::benchmark'."
+        );
+    }
     let (shutdown_tx, shutdown_rx) = watch::channel(());
     let mut task_handles = Vec::new();
+    let labels = Arc::new(SinkLabels::new(plugin_key));
     for (consumer, decoder, batch_size, transforms) in consumers {
         let plugin_key = plugin_key.to_string();
         let metrics = metrics.clone();
         let shutdown_rx = shutdown_rx.clone();
         let context = context.clone();
+        let labels = labels.clone();
         let handle = tokio::spawn(async move {
             if let Err(error) = consume_messages(
                 plugin_id,
@@ -268,8 +280,10 @@ pub(crate) fn spawn_consume_tasks(
                 transforms,
                 consumer,
                 verbose,
+                benchmark,
                 &plugin_key,
                 &metrics,
+                &labels,
                 shutdown_rx,
             )
             .await
@@ -277,6 +291,7 @@ pub(crate) fn spawn_consume_tasks(
                 error!(
                     "Failed to consume messages for sink connector with ID: {plugin_id}: {error}"
                 );
+                metrics.inc_errors_with_labels(&labels.counter);
                 context
                     .sinks
                     .set_error(&plugin_key, &error.to_string())
@@ -297,8 +312,10 @@ pub(crate) async fn consume_messages(
     transforms: Vec<Arc<dyn Transform>>,
     mut consumer: IggyConsumer,
     verbose: bool,
+    benchmark: bool,
     plugin_key: &str,
     metrics: &Arc<Metrics>,
+    labels: &SinkLabels,
     mut shutdown_rx: watch::Receiver<()>,
 ) -> Result<(), RuntimeError> {
     info!("Started consuming messages for sink connector with ID: {plugin_id}");
@@ -322,7 +339,11 @@ pub(crate) async fn consume_messages(
             break;
         };
         let Ok(message) = message else {
-            error!("Failed to receive message.");
+            error!(
+                "Failed to receive message for sink connector with ID: {plugin_id} from stream: {}, topic: {}",
+                topic_metadata.stream, topic_metadata.topic
+            );
+            metrics.inc_errors_with_labels(&labels.counter);
             continue;
         };
 
@@ -336,7 +357,7 @@ pub(crate) async fn consume_messages(
 
         let messages = std::mem::take(&mut batch);
         let messages_count = messages.len();
-        metrics.increment_messages_consumed(plugin_key, messages_count as u64);
+        metrics.inc_messages_consumed_with_labels(&labels.counter, messages_count as u64);
         let messages_metadata = MessagesMetadata {
             partition_id,
             current_offset,
@@ -354,7 +375,7 @@ pub(crate) async fn consume_messages(
             );
         }
         let start = Instant::now();
-        let processed_count = match process_messages(
+        let (processed_count, ffi_elapsed) = match process_messages(
             plugin_id,
             messages_metadata,
             &topic_metadata,
@@ -362,10 +383,12 @@ pub(crate) async fn consume_messages(
             &consume,
             &transforms,
             &decoder,
+            metrics,
+            labels,
         )
         .await
         {
-            Ok(count) => count,
+            Ok(result) => result,
             Err(error) => {
                 error!(
                     "Failed to process {messages_count} messages for sink connector with ID: {plugin_id}. {error}",
@@ -374,8 +397,12 @@ pub(crate) async fn consume_messages(
             }
         };
 
-        metrics.increment_messages_processed(plugin_key, processed_count as u64);
+        metrics.inc_messages_processed_with_labels(&labels.counter, processed_count as u64);
         let elapsed = start.elapsed();
+        let prepare_elapsed = elapsed.saturating_sub(ffi_elapsed);
+        metrics.observe_stage_with_labels(&labels.stage_prepare, prepare_elapsed);
+        metrics.observe_stage_with_labels(&labels.stage_ffi, ffi_elapsed);
+        metrics.observe_stage_with_labels(&labels.stage_total, elapsed);
         if verbose {
             info!(
                 "Consumed {messages_count} messages in {:#?} for sink connector with ID: {plugin_id}",
@@ -387,6 +414,23 @@ pub(crate) async fn consume_messages(
                 elapsed
             );
         }
+        if benchmark {
+            let total_us = benchmark::as_micros(elapsed);
+            let ffi_us = benchmark::as_micros(ffi_elapsed);
+            let prepare_us = total_us.saturating_sub(ffi_us);
+            benchmark::emit_sink_event(
+                plugin_key,
+                &topic_metadata.stream,
+                &topic_metadata.topic,
+                partition_id,
+                current_offset,
+                messages_count,
+                processed_count,
+                prepare_us,
+                ffi_us,
+                total_us,
+            );
+        }
     }
     info!("Stopped consuming messages for sink connector with ID: {plugin_id}");
     Ok(())
@@ -494,6 +538,7 @@ pub(crate) async fn setup_sink_consumers(
     Ok(consumers)
 }
 
+#[allow(clippy::too_many_arguments)]
 async fn process_messages(
     plugin_id: u32,
     messages_metadata: MessagesMetadata,
@@ -502,7 +547,9 @@ async fn process_messages(
     consume: &ConsumeCallback,
     transforms: &Vec<Arc<dyn Transform>>,
     decoder: &Arc<dyn StreamDecoder>,
-) -> Result<usize, RuntimeError> {
+    metrics: &Arc<Metrics>,
+    labels: &SinkLabels,
+) -> Result<(usize, std::time::Duration), RuntimeError> {
     let messages = messages.into_iter().map(|message| ReceivedMessage {
         id: message.header.id,
         offset: message.header.offset,
@@ -516,6 +563,11 @@ async fn process_messages(
     let count = messages.len();
     let decoded_messages = messages.into_iter().flat_map(|message| {
         let Ok(payload) = decoder.decode(message.payload) else {
+            error!(
+                "Failed to decode message payload (id: {}, offset: {}) for sink connector with ID: {plugin_id}",
+                message.id, message.offset
+            );
+            metrics.inc_errors_with_labels(&labels.counter);
             return None;
         };
 
@@ -540,8 +592,9 @@ async fn process_messages(
             current_message = transform.transform(topic_metadata, message)?;
         }
 
-        // The transform may return no message based on some conditions
+        // Filter contract: transform returning Ok(None) is an intentional drop.
         let Some(message) = current_message else {
+            metrics.inc_messages_filtered_with_labels(&labels.counter, 1);
             continue;
         };
 
@@ -549,6 +602,7 @@ async fn process_messages(
             error!(
                 "ID should be present. Failed to process message for sink connector with ID: {plugin_id}"
             );
+            metrics.inc_errors_with_labels(&labels.counter);
             continue;
         };
 
@@ -556,6 +610,7 @@ async fn process_messages(
             error!(
                 "Offset should be present. Failed to process message with ID: {id} for sink connector with ID: {plugin_id}"
             );
+            metrics.inc_errors_with_labels(&labels.counter);
             continue;
         };
 
@@ -563,6 +618,7 @@ async fn process_messages(
             error!(
                 "Checksum should be present. Failed to process message with ID: {id}, offset: {offset} for sink connector with ID: {plugin_id}"
             );
+            metrics.inc_errors_with_labels(&labels.counter);
             continue;
         };
 
@@ -570,6 +626,7 @@ async fn process_messages(
             error!(
                 "Timestamp should be present. Failed to process message with ID: {id}, offset: {offset} for sink connector with ID: {plugin_id}"
             );
+            metrics.inc_errors_with_labels(&labels.counter);
             continue;
         };
 
@@ -577,6 +634,7 @@ async fn process_messages(
             error!(
                 "Origin timestamp should be present. Failed to process message with ID: {id}, offset: {offset} for sink connector with ID: {plugin_id}"
             );
+            metrics.inc_errors_with_labels(&labels.counter);
             continue;
         };
 
@@ -584,23 +642,22 @@ async fn process_messages(
             error!(
                 "Failed to get message payload for message with ID: {id}, offset: {offset} for sink connector with ID: {plugin_id}"
             );
+            metrics.inc_errors_with_labels(&labels.counter);
             continue;
         };
 
-        let headers: Result<Vec<u8>, RuntimeError> = if let Some(headers) = message.headers {
-            Ok(postcard::to_allocvec(&headers).map_err(|error| {
-                error!("Failed to serialize headers for message with ID: {id}, offset: {offset} for sink connector with ID: {plugin_id}. {error}");
-                RuntimeError::FailedToSerializeHeaders
-            })?)
-        } else {
-            Ok(vec![])
-        };
-
-        let Ok(headers) = headers else {
-            error!(
-                "Failed to serialize message headers for message with ID: {id}, offset: {offset} for sink connector with ID: {plugin_id}"
-            );
-            continue;
+        let headers = match message.headers {
+            Some(headers) => match postcard::to_allocvec(&headers) {
+                Ok(bytes) => bytes,
+                Err(error) => {
+                    error!(
+                        "Failed to serialize headers for message with ID: {id}, offset: {offset} for sink connector with ID: {plugin_id}. {error}"
+                    );
+                    metrics.inc_errors_with_labels(&labels.counter);
+                    continue;
+                }
+            },
+            None => vec![],
         };
 
         messages.push(RawMessage {
@@ -639,6 +696,7 @@ async fn process_messages(
         RuntimeError::FailedToSerializeRawMessages
     })?;
 
+    let ffi_start = Instant::now();
     (consume)(
         plugin_id,
         topic_meta.as_ptr(),
@@ -648,6 +706,7 @@ async fn process_messages(
         messages.as_ptr(),
         messages.len(),
     );
+    let ffi_elapsed = ffi_start.elapsed();
 
-    Ok(processed_count)
+    Ok((processed_count, ffi_elapsed))
 }
diff --git a/core/connectors/runtime/src/source.rs b/core/connectors/runtime/src/source.rs
index 5d992a60b..1c514afe5 100644
--- a/core/connectors/runtime/src/source.rs
+++ b/core/connectors/runtime/src/source.rs
@@ -34,13 +34,15 @@ use std::{
     collections::{BTreeMap, HashMap},
     str::FromStr,
     sync::{Arc, atomic::Ordering},
+    time::{Duration, Instant},
 };
 use tracing::{debug, error, info, trace, warn};
 
+use crate::benchmark;
 use crate::configs::connectors::SourceConfig;
 use crate::context::RuntimeContext;
 use crate::log::LOG_CALLBACK;
-use crate::metrics::ConnectorType;
+use crate::metrics::SourceLabels;
 use crate::{
     FailedPlugin, PLUGIN_ID, RuntimeError, SourceApi, SourceConnector, SourceConnectorPlugin,
     SourceConnectorProducer, SourceConnectorWrapper, resolve_plugin_path,
@@ -50,7 +52,13 @@ use crate::{
 use iggy_connector_sdk::api::ConnectorStatus;
 use tokio::task::JoinHandle;
 
-pub static SOURCE_SENDERS: Lazy<DashMap<u32, Sender<ProducedMessages>>> = Lazy::new(DashMap::new);
+pub struct SourceSenderEntry {
+    pub sender: Sender<ProducedMessages>,
+    pub metrics: Arc<crate::metrics::Metrics>,
+    pub labels: Arc<SourceLabels>,
+}
+
+pub static SOURCE_SENDERS: Lazy<DashMap<u32, SourceSenderEntry>> = Lazy::new(DashMap::new);
 
 pub fn cleanup_sender(plugin_id: u32) {
     SOURCE_SENDERS.remove(&plugin_id);
@@ -182,6 +190,7 @@ pub async fn init(
             state_storage,
             error: init_error.clone(),
             verbose: config.verbose,
+            benchmark: config.benchmark,
         });
 
         if let Some(error) = init_error {
@@ -350,14 +359,22 @@ pub(crate) async fn source_forwarding_loop(
     plugin_id: u32,
     plugin_key: String,
     verbose: bool,
+    benchmark: bool,
     producer: IggyProducer,
     encoder: Arc<dyn StreamEncoder>,
     transforms: Vec<Arc<dyn Transform>>,
     state_storage: StateStorage,
     receiver: Receiver<ProducedMessages>,
     context: Arc<RuntimeContext>,
+    labels: Arc<SourceLabels>,
 ) {
     info!("Source connector with ID: {plugin_id} started.");
+    if benchmark {
+        info!(
+            "Benchmark mode enabled for source connector with ID: {plugin_id}, key: {plugin_key}. \
+             Per-batch events on target 'iggy_connectors::benchmark'."
+        );
+    }
     context
         .sources
         .update_status(
@@ -374,10 +391,11 @@ pub(crate) async fn source_forwarding_loop(
     };
 
     while let Ok(produced_messages) = receiver.recv_async().await {
+        let total_start = Instant::now();
         let count = produced_messages.messages.len();
         context
             .metrics
-            .increment_messages_produced(&plugin_key, count as u64);
+            .inc_messages_produced_with_labels(&labels.counter, count as u64);
         if verbose {
             info!("Source connector with ID: {plugin_id} received {count} messages");
         } else {
@@ -385,11 +403,13 @@ pub(crate) async fn source_forwarding_loop(
         }
         let schema = produced_messages.schema;
         let mut messages: Vec<DecodedMessage> = Vec::with_capacity(count);
+        let decode_start = Instant::now();
         for message in produced_messages.messages {
             let Ok(payload) = schema.try_into_payload(message.payload) else {
                 error!(
                     "Failed to decode message payload with schema: {schema} for source connector with ID: {plugin_id}",
                 );
+                context.metrics.inc_errors_with_labels(&labels.counter);
                 continue;
             };
 
@@ -407,72 +427,114 @@ pub(crate) async fn source_forwarding_loop(
             });
             number += 1;
         }
+        let decode_elapsed = decode_start.elapsed();
+        context
+            .metrics
+            .observe_stage_with_labels(&labels.stage_decode, decode_elapsed);
 
-        let Ok(iggy_messages) =
-            process_messages(plugin_id, &encoder, &topic_metadata, messages, &transforms)
-        else {
+        let prepare_start = Instant::now();
+        let Ok(iggy_messages) = process_messages(
+            plugin_id,
+            &encoder,
+            &topic_metadata,
+            messages,
+            &transforms,
+            &context.metrics,
+            &labels,
+        ) else {
             let error_msg = format!(
                 "Failed to process {count} messages by source connector with ID: {plugin_id} before sending them to stream: {}, topic: {}.",
                 producer.stream(),
                 producer.topic()
             );
             error!("{error_msg}");
-            context
-                .metrics
-                .increment_errors(&plugin_key, ConnectorType::Source);
+            context.metrics.inc_errors_with_labels(&labels.counter);
             context.sources.set_error(&plugin_key, &error_msg).await;
             continue;
         };
+        let prepare_elapsed = prepare_start.elapsed();
+        context
+            .metrics
+            .observe_stage_with_labels(&labels.stage_prepare, prepare_elapsed);
+        let sent_count = iggy_messages.len();
 
+        let iggy_send_start = Instant::now();
         if let Err(error) = producer.send(iggy_messages).await {
             let error_msg = format!(
-                "Failed to send {count} messages to stream: {}, topic: {} by source connector with ID: {plugin_id}. {error}",
+                "Failed to send {sent_count} messages to stream: {}, topic: {} by source connector with ID: {plugin_id}. {error}",
                 producer.stream(),
                 producer.topic(),
             );
             error!("{error_msg}");
-            context
-                .metrics
-                .increment_errors(&plugin_key, ConnectorType::Source);
+            context.metrics.inc_errors_with_labels(&labels.counter);
             context.sources.set_error(&plugin_key, &error_msg).await;
             continue;
         }
+        let iggy_send_elapsed = iggy_send_start.elapsed();
+        context
+            .metrics
+            .observe_stage_with_labels(&labels.stage_iggy_send, iggy_send_elapsed);
 
         context
             .metrics
-            .increment_messages_sent(&plugin_key, count as u64);
+            .inc_messages_sent_with_labels(&labels.counter, sent_count as u64);
 
         if verbose {
             info!(
-                "Sent {count} messages to stream: {}, topic: {} by source connector with ID: {plugin_id}",
+                "Sent {sent_count} of {count} messages to stream: {}, topic: {} by source connector with ID: {plugin_id}",
                 producer.stream(),
                 producer.topic()
             );
         } else {
             debug!(
-                "Sent {count} messages to stream: {}, topic: {} by source connector with ID: {plugin_id}",
+                "Sent {sent_count} of {count} messages to stream: {}, topic: {} by source connector with ID: {plugin_id}",
                 producer.stream(),
                 producer.topic()
             );
         }
 
-        let Some(state) = produced_messages.state else {
-            debug!("No state provided for source connector with ID: {plugin_id}");
-            continue;
-        };
-
-        match &state_storage {
-            StateStorage::File(file) => {
-                if let Err(error) = file.save(state).await {
-                    let error_msg = format!(
-                        "Failed to save state for source connector with ID: {plugin_id}. {error}"
-                    );
-                    error!("{error_msg}");
-                    context.sources.set_error(&plugin_key, &error_msg).await;
-                    continue;
+        let state_save_start = Instant::now();
+        let mut state_save_elapsed = Duration::ZERO;
+        if let Some(state) = produced_messages.state {
+            match &state_storage {
+                StateStorage::File(file) => {
+                    if let Err(error) = file.save(state).await {
+                        let error_msg = format!(
+                            "Failed to save state for source connector with ID: {plugin_id}. {error}"
+                        );
+                        error!("{error_msg}");
+                        context.metrics.inc_errors_with_labels(&labels.counter);
+                        context.sources.set_error(&plugin_key, &error_msg).await;
+                        continue;
+                    }
+                    debug!("State saved for source connector with ID: {plugin_id}");
                 }
-                debug!("State saved for source connector with ID: {plugin_id}");
             }
+            state_save_elapsed = state_save_start.elapsed();
+            context
+                .metrics
+                .observe_stage_with_labels(&labels.stage_state_save, state_save_elapsed);
+        } else {
+            debug!("No state provided for source connector with ID: {plugin_id}");
+        }
+        let total_elapsed = total_start.elapsed();
+        context
+            .metrics
+            .observe_stage_with_labels(&labels.stage_total, total_elapsed);
+
+        if benchmark {
+            benchmark::emit_source_event(
+                &plugin_key,
+                &topic_metadata.stream,
+                &topic_metadata.topic,
+                count,
+                sent_count,
+                benchmark::as_micros(decode_elapsed),
+                benchmark::as_micros(prepare_elapsed),
+                benchmark::as_micros(iggy_send_elapsed),
+                benchmark::as_micros(state_save_elapsed),
+                benchmark::as_micros(total_elapsed),
+            );
         }
     }
 
@@ -492,6 +554,7 @@ pub(crate) fn spawn_source_handler(
     plugin_id: u32,
     plugin_key: &str,
     verbose: bool,
+    benchmark: bool,
     producer: IggyProducer,
     encoder: Arc<dyn StreamEncoder>,
     transforms: Vec<Arc<dyn Transform>>,
@@ -500,24 +563,33 @@ pub(crate) fn spawn_source_handler(
     context: Arc<RuntimeContext>,
 ) -> Vec<JoinHandle<()>> {
     let (sender, receiver) = flume::unbounded();
-    SOURCE_SENDERS.insert(plugin_id, sender);
+    let plugin_key = plugin_key.to_string();
+    let labels = Arc::new(SourceLabels::new(&plugin_key));
+    SOURCE_SENDERS.insert(
+        plugin_id,
+        SourceSenderEntry {
+            sender,
+            metrics: context.metrics.clone(),
+            labels: labels.clone(),
+        },
+    );
 
     let blocking_handle = tokio::task::spawn_blocking(move || {
         callback(plugin_id, handle_produced_messages);
     });
-
-    let plugin_key = plugin_key.to_string();
     let handler_task = tokio::spawn(async move {
         source_forwarding_loop(
             plugin_id,
             plugin_key,
             verbose,
+            benchmark,
             producer,
             encoder,
             transforms,
             state_storage,
             receiver,
             context,
+            labels,
         )
         .await;
     });
@@ -552,6 +624,7 @@ pub fn handle(
                 plugin_id,
                 &plugin_key,
                 plugin.verbose,
+                plugin.benchmark,
                 producer_wrapper.producer,
                 producer_wrapper.encoder,
                 plugin.transforms,
@@ -572,6 +645,8 @@ fn process_messages(
     topic_metadata: &TopicMetadata,
     messages: Vec<DecodedMessage>,
     transforms: &Vec<Arc<dyn Transform>>,
+    metrics: &Arc<crate::metrics::Metrics>,
+    labels: &SourceLabels,
 ) -> Result<Vec<IggyMessage>, Error> {
     let mut iggy_messages = Vec::with_capacity(messages.len());
     for message in messages {
@@ -584,8 +659,9 @@ fn process_messages(
             current_message = transform.transform(topic_metadata, message)?;
         }
 
-        // The transform may return no message based on some conditions
+        // Filter contract: transform returning Ok(None) is an intentional drop.
         let Some(message) = current_message else {
+            metrics.inc_messages_filtered_with_labels(&labels.counter, 1);
             continue;
         };
 
@@ -594,6 +670,7 @@ fn process_messages(
                 "Failed to encode message payload for source connector with ID: {id}, stream: {}, topic: {}",
                 topic_metadata.stream, topic_metadata.topic
             );
+            metrics.inc_errors_with_labels(&labels.counter);
             continue;
         };
 
@@ -602,6 +679,7 @@ fn process_messages(
                 "Failed to build Iggy message for source connector with ID: {id}, stream: {}, topic: {}",
                 topic_metadata.stream, topic_metadata.topic
             );
+            metrics.inc_errors_with_labels(&labels.counter);
             continue;
         };
 
@@ -616,22 +694,27 @@ pub(crate) extern "C" fn handle_produced_messages(
     messages_len: usize,
 ) {
     unsafe {
-        if let Some(sender) = SOURCE_SENDERS.get(&plugin_id) {
-            let messages = std::slice::from_raw_parts(messages_ptr, messages_len);
-            match postcard::from_bytes::<ProducedMessages>(messages) {
-                Ok(messages) => {
-                    if let Err(send_error) = sender.send(messages) {
-                        error!(
-                            "Failed to send messages for source connector with ID: {plugin_id}. Channel closed: {send_error}"
-                        );
-                    }
-                }
-                Err(err) => {
+        // Entry missing = SOURCE_SENDERS already cleaned up during shutdown - benign race,
+        // expected at close. No metric (operator would conflate it with real failures).
+        let Some(entry) = SOURCE_SENDERS.get(&plugin_id) else {
+            return;
+        };
+        let messages = std::slice::from_raw_parts(messages_ptr, messages_len);
+        match postcard::from_bytes::<ProducedMessages>(messages) {
+            Ok(messages) => {
+                if let Err(send_error) = entry.sender.send(messages) {
                     error!(
-                        "Failed to deserialize produced messages for source connector with ID: {plugin_id}. {err}"
+                        "Failed to send messages for source connector with ID: {plugin_id}. Channel closed: {send_error}"
                     );
+                    entry.metrics.inc_errors_with_labels(&entry.labels.counter);
                 }
             }
+            Err(err) => {
+                error!(
+                    "Failed to deserialize produced messages for source connector with ID: {plugin_id}. {err}"
+                );
+                entry.metrics.inc_errors_with_labels(&entry.labels.counter);
+            }
         }
     }
 }
diff --git a/core/connectors/runtime/src/state.rs b/core/connectors/runtime/src/state.rs
index 8fe47adc4..197fa82b8 100644
--- a/core/connectors/runtime/src/state.rs
+++ b/core/connectors/runtime/src/state.rs
@@ -17,16 +17,14 @@
  * under the License.
  */
 
-use std::io::SeekFrom;
-
 use iggy_connector_sdk::{ConnectorState, Error};
+use std::io::ErrorKind;
+use std::path::{Path, PathBuf};
 use strum::Display;
-use tokio::{
-    fs::{File, OpenOptions},
-    io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt},
-    sync::Mutex,
-};
-use tracing::{debug, error, info};
+use tokio::fs::{self, OpenOptions};
+use tokio::io::AsyncWriteExt;
+use tokio::sync::Mutex;
+use tracing::{debug, error, info, warn};
 
 pub trait StateProvider {
     async fn load(&self) -> Result<Option<ConnectorState>, Error>;
@@ -42,72 +40,281 @@ pub enum StateStorage {
 
 #[derive(Debug)]
 pub struct FileStateProvider {
-    path: String,
-    file: Mutex<Option<File>>,
+    path: PathBuf,
+    tmp_path: PathBuf,
+    save_lock: Mutex<()>,
 }
 
 impl FileStateProvider {
     pub fn new(path: String) -> Self {
+        let path = PathBuf::from(path);
+        let tmp_path = tmp_path_for(&path);
         FileStateProvider {
             path,
-            file: Mutex::new(None),
+            tmp_path,
+            save_lock: Mutex::new(()),
         }
     }
 }
 
 impl StateProvider for FileStateProvider {
     async fn load(&self) -> Result<Option<ConnectorState>, Error> {
-        let mut file = OpenOptions::new()
-            .read(true)
-            .write(true)
-            .create(true)
-            .truncate(false)
-            .open(&self.path)
-            .await
-            .map_err(|_| Error::CannotOpenStateFile)?;
-
-        let mut buffer = Vec::new();
-        file.read_to_end(&mut buffer).await.map_err(|error| {
-            error!("Cannot read state file: {}. {error}.", self.path);
-            Error::CannotReadStateFile
-        })?;
-        self.file.lock().await.replace(file);
-        if buffer.is_empty() {
-            info!("State file is empty: {}", self.path);
-            Ok(None)
-        } else {
-            info!("Loaded state file: {}", self.path);
-            Ok(Some(ConnectorState(buffer)))
+        // Orphan tmps are reclaimed by the next save's truncate; deleting
+        // here would race a still-draining save across provider instances.
+        match fs::read(&self.path).await {
+            Ok(buffer) if buffer.is_empty() => {
+                info!("State file is empty: {}", self.path.display());
+                Ok(None)
+            }
+            Ok(buffer) => {
+                info!("Loaded state file: {}", self.path.display());
+                Ok(Some(ConnectorState(buffer)))
+            }
+            Err(error) if error.kind() == ErrorKind::NotFound => {
+                info!(
+                    "State file not found, starting fresh: {}",
+                    self.path.display()
+                );
+                Ok(None)
+            }
+            Err(error) => {
+                error!("Cannot read state file: {}. {error}.", self.path.display());
+                Err(Error::CannotReadStateFile)
+            }
         }
     }
 
     async fn save(&self, state: ConnectorState) -> Result<(), Error> {
-        let mut file = self.file.lock().await;
-        let Some(file) = file.as_mut() else {
-            return Err(Error::CannotReadStateFile);
-        };
-
-        file.set_len(0).await.map_err(|error| {
-            error!("Cannot truncate state file: {}. {error}.", self.path);
-            Error::CannotWriteStateFile
-        })?;
-
-        file.seek(SeekFrom::Start(0)).await.map_err(|error| {
-            error!("Cannot seek state file: {}. {error}.", self.path);
-            Error::CannotWriteStateFile
-        })?;
-
-        file.write_all(&state.0).await.map_err(|error| {
-            error!("Cannot write state file: {}. {error}.", self.path);
-            Error::CannotWriteStateFile
-        })?;
-
-        file.sync_all().await.map_err(|error| {
-            error!("Cannot sync state file: {}. {error}.", self.path);
-            Error::CannotWriteStateFile
-        })?;
-
-        debug!("Saved state file: {}", self.path);
+        let _guard = self.save_lock.lock().await;
+
+        let mut tmp = open_options_for_state()
+            .open(&self.tmp_path)
+            .await
+            .map_err(|error| {
+                error!(
+                    "Cannot create temp state file: {}. {error}.",
+                    self.tmp_path.display()
+                );
+                Error::CannotWriteStateFile
+            })?;
+
+        if let Err(error) = tmp.write_all(&state.0).await {
+            error!(
+                "Cannot write temp state file: {}. {error}.",
+                self.tmp_path.display()
+            );
+            drop(tmp);
+            cleanup_tmp(&self.tmp_path).await;
+            return Err(Error::CannotWriteStateFile);
+        }
+
+        // fdatasync: skip mtime/atime sync. Parent dir is synced separately.
+        if let Err(error) = tmp.sync_data().await {
+            error!(
+                "Cannot sync temp state file: {}. {error}.",
+                self.tmp_path.display()
+            );
+            drop(tmp);
+            cleanup_tmp(&self.tmp_path).await;
+            return Err(Error::CannotWriteStateFile);
+        }
+        drop(tmp);
+
+        if let Err(error) = fs::rename(&self.tmp_path, &self.path).await {
+            error!(
+                "Cannot rename {} -> {}. {error}.",
+                self.tmp_path.display(),
+                self.path.display()
+            );
+            cleanup_tmp(&self.tmp_path).await;
+            return Err(Error::CannotWriteStateFile);
+        }
+
+        sync_parent_dir(&self.path).await;
+
+        debug!("Saved state file: {}", self.path.display());
         Ok(())
     }
 }
+
+fn tmp_path_for(path: &Path) -> PathBuf {
+    let mut name = path
+        .file_name()
+        .map(|n| n.to_os_string())
+        .unwrap_or_default();
+    name.push(".tmp");
+    path.with_file_name(name)
+}
+
+fn open_options_for_state() -> OpenOptions {
+    let mut options = OpenOptions::new();
+    options.write(true).create(true).truncate(true);
+    #[cfg(unix)]
+    options.mode(0o600); // owner-only: state may carry cursors / tokens
+    options
+}
+
+async fn cleanup_tmp(tmp_path: &Path) {
+    if let Err(error) = fs::remove_file(tmp_path).await
+        && error.kind() != ErrorKind::NotFound
+    {
+        warn!(
+            "Failed to remove stale temp state file: {}. {error}.",
+            tmp_path.display()
+        );
+    }
+}
+
+#[cfg(unix)]
+async fn sync_parent_dir(path: &Path) {
+    let Some(parent) = path.parent() else {
+        return;
+    };
+    match fs::File::open(parent).await {
+        Ok(dir) => {
+            if let Err(error) = dir.sync_all().await {
+                warn!(
+                    "Failed to fsync state directory: {}. {error}.",
+                    parent.display()
+                );
+            }
+        }
+        Err(error) => {
+            warn!(
+                "Failed to open state directory for fsync: {}. {error}.",
+                parent.display()
+            );
+        }
+    }
+}
+
+#[cfg(not(unix))]
+async fn sync_parent_dir(_path: &Path) {
+    // Directory fsync is POSIX-only.
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use tempfile::TempDir;
+
+    fn provider_in(dir: &TempDir, name: &str) -> FileStateProvider {
+        FileStateProvider::new(dir.path().join(name).to_string_lossy().to_string())
+    }
+
+    #[tokio::test]
+    async fn given_no_existing_file_when_loaded_should_return_none() {
+        let dir = TempDir::new().unwrap();
+        let provider = provider_in(&dir, "source_test.state");
+        assert!(provider.load().await.unwrap().is_none());
+    }
+
+    #[tokio::test]
+    async fn given_empty_file_when_loaded_should_return_none() {
+        let dir = TempDir::new().unwrap();
+        let path = dir.path().join("source_test.state");
+        fs::write(&path, b"").await.unwrap();
+        let provider = FileStateProvider::new(path.to_string_lossy().to_string());
+        assert!(provider.load().await.unwrap().is_none());
+    }
+
+    #[tokio::test]
+    async fn given_state_when_saved_then_loaded_should_round_trip() {
+        let dir = TempDir::new().unwrap();
+        let provider = provider_in(&dir, "source_test.state");
+        provider
+            .save(ConnectorState(vec![1, 2, 3, 4, 5]))
+            .await
+            .unwrap();
+        let loaded = provider.load().await.unwrap().unwrap();
+        assert_eq!(loaded.0, vec![1, 2, 3, 4, 5]);
+    }
+
+    #[tokio::test]
+    async fn given_multiple_saves_when_loaded_should_return_latest_bytes() {
+        let dir = TempDir::new().unwrap();
+        let provider = provider_in(&dir, "source_test.state");
+        provider.save(ConnectorState(vec![0; 16])).await.unwrap();
+        provider.save(ConnectorState(vec![9; 4])).await.unwrap();
+        let loaded = provider.load().await.unwrap().unwrap();
+        assert_eq!(loaded.0, vec![9; 4]);
+    }
+
+    #[tokio::test]
+    async fn given_successful_save_when_inspected_should_leave_no_tmp_artifact() {
+        let dir = TempDir::new().unwrap();
+        let provider = provider_in(&dir, "source_test.state");
+        provider.save(ConnectorState(vec![42])).await.unwrap();
+        assert!(!provider.tmp_path.exists());
+        assert!(provider.path.exists());
+    }
+
+    #[tokio::test]
+    async fn given_orphaned_tmp_when_loaded_should_ignore_it() {
+        let dir = TempDir::new().unwrap();
+        let provider = provider_in(&dir, "source_test.state");
+        // Simulate a prior-crash leftover (real state + orphan tmp). load()
+        // must read the real file and never confuse it with the tmp.
+        fs::write(&provider.path, vec![1, 2, 3]).await.unwrap();
+        fs::write(&provider.tmp_path, vec![9, 9, 9]).await.unwrap();
+        let loaded = provider.load().await.unwrap().unwrap();
+        assert_eq!(loaded.0, vec![1, 2, 3]);
+    }
+
+    #[tokio::test]
+    async fn given_stale_tmp_when_save_called_should_overwrite_and_succeed() {
+        let dir = TempDir::new().unwrap();
+        let provider = provider_in(&dir, "source_test.state");
+        fs::write(&provider.tmp_path, vec![0xFF; 32]).await.unwrap();
+        provider.save(ConnectorState(vec![1])).await.unwrap();
+        let loaded = provider.load().await.unwrap().unwrap();
+        assert_eq!(loaded.0, vec![1]);
+        assert!(!provider.tmp_path.exists());
+    }
+
+    #[tokio::test]
+    async fn given_state_saved_when_provider_recreated_should_resume_from_disk() {
+        let dir = TempDir::new().unwrap();
+        let path = dir.path().join("source_test.state");
+        let path_str = path.to_string_lossy().to_string();
+        FileStateProvider::new(path_str.clone())
+            .save(ConnectorState(vec![7, 7, 7]))
+            .await
+            .unwrap();
+        let resumed = FileStateProvider::new(path_str)
+            .load()
+            .await
+            .unwrap()
+            .unwrap();
+        assert_eq!(resumed.0, vec![7, 7, 7]);
+    }
+
+    #[tokio::test]
+    async fn given_concurrent_saves_when_completed_should_yield_untorn_state() {
+        use std::sync::Arc;
+        let dir = TempDir::new().unwrap();
+        let provider = Arc::new(provider_in(&dir, "source_test.state"));
+        let mut handles = Vec::new();
+        for byte in 0u8..16 {
+            let provider = provider.clone();
+            handles.push(tokio::spawn(async move {
+                provider.save(ConnectorState(vec![byte; 64])).await
+            }));
+        }
+        for handle in handles {
+            handle.await.unwrap().unwrap();
+        }
+        let loaded = provider.load().await.unwrap().unwrap();
+        assert_eq!(loaded.0.len(), 64);
+        assert!(loaded.0.iter().all(|byte| *byte == loaded.0[0]));
+        assert!(!provider.tmp_path.exists());
+    }
+
+    #[tokio::test]
+    async fn given_empty_state_when_saved_then_loaded_should_return_none() {
+        let dir = TempDir::new().unwrap();
+        let provider = provider_in(&dir, "source_test.state");
+        provider.save(ConnectorState(Vec::new())).await.unwrap();
+        assert!(provider.load().await.unwrap().is_none());
+    }
+}
diff --git a/core/connectors/runtime/src/stats.rs b/core/connectors/runtime/src/stats.rs
index b72110519..7f69552fc 100644
--- a/core/connectors/runtime/src/stats.rs
+++ b/core/connectors/runtime/src/stats.rs
@@ -73,6 +73,9 @@ pub async fn get_runtime_stats(context: &Arc<RuntimeContext>) -> ConnectorRuntim
             messages_sent: Some(context.metrics.get_messages_sent(&source.key)),
             messages_consumed: None,
             messages_processed: None,
+            messages_filtered: context
+                .metrics
+                .get_messages_filtered(&source.key, ConnectorType::Source),
             errors: context
                 .metrics
                 .get_errors(&source.key, ConnectorType::Source),
@@ -94,6 +97,9 @@ pub async fn get_runtime_stats(context: &Arc<RuntimeContext>) -> ConnectorRuntim
             messages_sent: None,
             messages_consumed: Some(context.metrics.get_messages_consumed(&sink.key)),
             messages_processed: Some(context.metrics.get_messages_processed(&sink.key)),
+            messages_filtered: context
+                .metrics
+                .get_messages_filtered(&sink.key, ConnectorType::Sink),
             errors: context.metrics.get_errors(&sink.key, ConnectorType::Sink),
         });
     }
diff --git a/core/connectors/sdk/src/api.rs b/core/connectors/sdk/src/api.rs
index 3341a40a4..9809e28a8 100644
--- a/core/connectors/sdk/src/api.rs
+++ b/core/connectors/sdk/src/api.rs
@@ -112,6 +112,7 @@ pub struct ConnectorStats {
     pub messages_consumed: Option<u64>,
     #[serde(skip_serializing_if = "Option::is_none")]
     pub messages_processed: Option<u64>,
+    pub messages_filtered: u64,
     pub errors: u64,
 }
 
diff --git a/core/connectors/sinks/README.md b/core/connectors/sinks/README.md
index 55c639c33..77f15d8da 100644
--- a/core/connectors/sinks/README.md
+++ b/core/connectors/sinks/README.md
@@ -51,6 +51,7 @@ pub struct SinkConfig {
     pub plugin_config_format: Option<ConfigFormat>,
     pub plugin_config: Option<serde_json::Value>,
     pub verbose: bool, // Log message processing at info level instead of debug (default: false)
+    pub benchmark: bool, // Emit per-batch timing events on the `iggy_connectors::benchmark` target (default: false)
 }
 ```
 
@@ -76,6 +77,7 @@ name = "Stdout sink"
 path = "target/release/libiggy_connector_stdout_sink"
 plugin_config_format = "toml"
 verbose = false # Log message processing at info level instead of debug
+benchmark = false # Emit per-batch timing events on `iggy_connectors::benchmark` target
 
 # Collection of the streams from which messages are consumed
 [[streams]]
diff --git a/core/connectors/sources/README.md b/core/connectors/sources/README.md
index 3f45e149a..834785505 100644
--- a/core/connectors/sources/README.md
+++ b/core/connectors/sources/README.md
@@ -44,6 +44,7 @@ pub struct SourceConfig {
     pub plugin_config_format: Option<ConfigFormat>,
     pub plugin_config: Option<serde_json::Value>,
     pub verbose: bool, // Log message processing at info level instead of debug (default: false)
+    pub benchmark: bool, // Emit per-batch timing events on the `iggy_connectors::benchmark` target (default: false)
 }
 ```
 
@@ -69,6 +70,7 @@ name = "Random source" # Name of the source
 path = "libiggy_connector_random_source" # Path to the source connector
 config_format = "toml"
 verbose = false # Log message processing at info level instead of debug
+benchmark = false # Emit per-batch timing events on `iggy_connectors::benchmark` target
 
 # Collection of the streams to which the produced messages are sent
 [[streams]]
diff --git a/core/integration/tests/connectors/runtime/benchmark.rs b/core/integration/tests/connectors/runtime/benchmark.rs
new file mode 100644
index 000000000..dd2dabb31
--- /dev/null
+++ b/core/integration/tests/connectors/runtime/benchmark.rs
@@ -0,0 +1,721 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use async_trait::async_trait;
+use iggy::prelude::IggyClient;
+use integration::harness::seeds::SeedError;
+use integration::harness::{TestBinaryError, TestFixture, TestHarness, seeds};
+use integration::iggy_harness;
+use std::collections::HashMap;
+use std::time::{Duration, Instant};
+use tokio::time::sleep;
+
+// Layering: tests in this file rely on TWO independent observability surfaces
+// to keep coverage durable against tracing's text-format evolution.
+//
+//   1. Text-event assertions parse the runtime's stdout/stderr via `parse_event_fields`.
+//      Format is tracing-subscriber's default `fmt::layer()` style; parsing is quote-,
+//      ANSI-, and embedded-space-aware and covered by `parser_tests` against synthetic
+//      inputs so the parser itself is locked.
+//   2. Histogram assertions scrape the runtime's Prometheus `/metrics` endpoint and
+//      verify `iggy_connector_stage_duration_seconds_count` per (key, type, stage).
+//      That path is unaffected by any future tracing formatter change.
+//
+// If tracing's default format ever changes incompatibly, text-event tests will fail
+// before any production regression hits ops - and the histogram tests will still pass,
+// pinpointing the issue as test-only formatter coupling rather than a runtime bug.
+const BENCHMARK_TARGET: &str = "iggy_connectors::benchmark";
+const POLL_INTERVAL: Duration = Duration::from_millis(100);
+const POLL_DEADLINE: Duration = Duration::from_secs(10);
+const ZERO_EVENT_OBSERVATION_WINDOW: Duration = Duration::from_secs(2);
+
+#[iggy_harness(
+    server(connectors_runtime(config_path = "tests/connectors/runtime/benchmark.toml")),
+    seed = seeds::connector_stream
+)]
+async fn given_benchmark_enabled_when_batches_flow_should_emit_typed_events(harness: &TestHarness) {
+    let (sink_events, source_events) =
+        wait_for_both_kinds(harness, "stdout_bench", "random_bench").await;
+
+    let runtime_logs = collect_runtime_logs(harness);
+    assert!(
+        runtime_logs.contains("Benchmark mode enabled for sink connector")
+            && runtime_logs.contains("stdout_bench"),
+        "expected sink benchmark startup log in runtime output"
+    );
+    assert!(
+        runtime_logs.contains("Benchmark mode enabled for source connector")
+            && runtime_logs.contains("random_bench"),
+        "expected source benchmark startup log in runtime output"
+    );
+
+    for event in &sink_events {
+        assert_eq!(event.get("connector_type"), Some(&"sink".to_string()));
+        assert_eq!(
+            event.get("connector_key"),
+            Some(&"stdout_bench".to_string())
+        );
+        assert_eq!(event.get("stream"), Some(&"test_stream".to_string()));
+        assert_eq!(event.get("topic"), Some(&"test_topic".to_string()));
+
+        let batch_size = parse_u64(event, "batch_size");
+        let processed_count = parse_u64(event, "processed_count");
+        let prepare_us = parse_u64(event, "prepare_us");
+        let ffi_us = parse_u64(event, "ffi_us");
+        let total_us = parse_u64(event, "total_us");
+
+        assert!(batch_size > 0, "sink batch_size must be > 0: {event:?}");
+        assert!(
+            processed_count <= batch_size,
+            "sink processed_count must be <= batch_size: {event:?}"
+        );
+        assert!(total_us > 0, "sink total_us must be > 0: {event:?}");
+        assert!(
+            prepare_us + ffi_us <= total_us + 100,
+            "sink prepare_us + ffi_us must be <= total_us (with slack): {event:?}"
+        );
+    }
+
+    for event in &source_events {
+        assert_eq!(event.get("connector_type"), Some(&"source".to_string()));
+        assert_eq!(
+            event.get("connector_key"),
+            Some(&"random_bench".to_string())
+        );
+        assert_eq!(event.get("stream"), Some(&"test_stream".to_string()));
+        assert_eq!(event.get("topic"), Some(&"test_topic".to_string()));
+
+        let batch_size = parse_u64(event, "batch_size");
+        let sent_count = parse_u64(event, "sent_count");
+        let total_us = parse_u64(event, "total_us");
+        let decode_us = parse_u64(event, "decode_us");
+        let prepare_us = parse_u64(event, "prepare_us");
+        let iggy_send_us = parse_u64(event, "iggy_send_us");
+        let state_save_us = parse_u64(event, "state_save_us");
+
+        assert!(batch_size > 0, "source batch_size must be > 0: {event:?}");
+        assert!(
+            sent_count <= batch_size,
+            "source sent_count must be <= batch_size (no over-counting on transform/encode drops): {event:?}"
+        );
+        assert!(total_us > 0, "source total_us must be > 0: {event:?}");
+        let stage_sum = decode_us + prepare_us + iggy_send_us + state_save_us;
+        assert!(
+            stage_sum <= total_us + 100,
+            "source stage sum (decode+prepare+iggy_send+state_save) must be <= total_us (with slack): {event:?}"
+        );
+    }
+}
+
+#[iggy_harness(
+    server(connectors_runtime(config_path = "tests/connectors/runtime/benchmark.toml")),
+    seed = seeds::connector_stream
+)]
+async fn given_benchmark_enabled_when_events_emitted_should_respect_runtime_batch_configuration(
+    harness: &TestHarness,
+) {
+    let (sink_events, source_events) =
+        wait_for_both_kinds(harness, "stdout_bench", "random_bench").await;
+
+    let sink_batch_max = sink_events
+        .iter()
+        .map(|event| parse_u64(event, "batch_size"))
+        .max()
+        .unwrap_or(0);
+    assert!(
+        sink_batch_max <= 50,
+        "sink batch_size should not exceed configured batch_length=50, saw {sink_batch_max}"
+    );
+
+    let source_batch_max = source_events
+        .iter()
+        .map(|event| parse_u64(event, "batch_size"))
+        .max()
+        .unwrap_or(0);
+    assert!(
+        (3..=5).contains(&source_batch_max),
+        "source batch_size should fall within configured messages_range=[3,5], saw {source_batch_max}"
+    );
+}
+
+#[iggy_harness(
+    server(connectors_runtime(config_path = "tests/connectors/runtime/benchmark_disabled.toml")),
+    seed = seeds::connector_stream
+)]
+async fn given_benchmark_disabled_when_batches_processed_should_emit_no_events(
+    harness: &TestHarness,
+) {
+    sleep(ZERO_EVENT_OBSERVATION_WINDOW).await;
+
+    let runtime_logs = collect_runtime_logs(harness);
+    assert!(
+        !runtime_logs.is_empty(),
+        "runtime should have produced non-benchmark logs even with benchmark disabled"
+    );
+
+    let sink_events = parse_benchmark_events(&runtime_logs, "sink");
+    let source_events = parse_benchmark_events(&runtime_logs, "source");
+    assert!(
+        sink_events.is_empty(),
+        "expected zero sink benchmark events when benchmark=false, got {} events",
+        sink_events.len()
+    );
+    assert!(
+        source_events.is_empty(),
+        "expected zero source benchmark events when benchmark=false, got {} events",
+        source_events.len()
+    );
+    assert!(
+        !runtime_logs.contains("Benchmark mode enabled for"),
+        "expected no benchmark startup log when benchmark=false"
+    );
+}
+
+#[iggy_harness(
+    server(connectors_runtime(config_path = "tests/connectors/runtime/benchmark_disabled.toml")),
+    seed = seeds::connector_stream
+)]
+async fn given_benchmark_env_var_override_when_toml_says_false_should_emit_events(
+    harness: &TestHarness,
+    _fixture: BenchmarkEnvOverrideFixture,
+) {
+    let (sink_events, source_events) =
+        wait_for_both_kinds(harness, "stdout_off", "random_off").await;
+
+    for event in &sink_events {
+        assert_eq!(event.get("connector_key"), Some(&"stdout_off".to_string()));
+    }
+    for event in &source_events {
+        assert_eq!(event.get("connector_key"), Some(&"random_off".to_string()));
+    }
+}
+
+async fn wait_for_both_kinds(
+    harness: &TestHarness,
+    sink_key: &str,
+    source_key: &str,
+) -> (Vec<HashMap<String, String>>, Vec<HashMap<String, String>>) {
+    let deadline = Instant::now() + POLL_DEADLINE;
+    loop {
+        let logs = collect_runtime_logs(harness);
+        let sink_events = parse_benchmark_events_for_key(&logs, "sink", sink_key);
+        let source_events = parse_benchmark_events_for_key(&logs, "source", source_key);
+        if !sink_events.is_empty() && !source_events.is_empty() {
+            return (sink_events, source_events);
+        }
+        if Instant::now() >= deadline {
+            panic!(
+                "timed out waiting for sink ({}) + source ({}) benchmark events. \
+                 sink seen: {}, source seen: {}. logs:\n{logs}",
+                sink_key,
+                source_key,
+                sink_events.len(),
+                source_events.len(),
+            );
+        }
+        sleep(POLL_INTERVAL).await;
+    }
+}
+
+fn collect_runtime_logs(harness: &TestHarness) -> String {
+    let runtime = harness
+        .connectors_runtime()
+        .expect("connectors runtime handle should be available");
+    let (stdout, stderr) = runtime.collect_logs();
+    format!("{stdout}\n{stderr}")
+}
+
+fn parse_benchmark_events(logs: &str, connector_type: &str) -> Vec<HashMap<String, String>> {
+    logs.lines()
+        .filter(|line| line.contains(BENCHMARK_TARGET))
+        .filter_map(parse_event_fields)
+        .filter(|fields| {
+            fields
+                .get("connector_type")
+                .map(|value| value == connector_type)
+                .unwrap_or(false)
+        })
+        .collect()
+}
+
+fn parse_benchmark_events_for_key(
+    logs: &str,
+    connector_type: &str,
+    connector_key: &str,
+) -> Vec<HashMap<String, String>> {
+    parse_benchmark_events(logs, connector_type)
+        .into_iter()
+        .filter(|fields| {
+            fields
+                .get("connector_key")
+                .map(|value| value == connector_key)
+                .unwrap_or(false)
+        })
+        .collect()
+}
+
+fn parse_event_fields(line: &str) -> Option<HashMap<String, String>> {
+    let payload_start = line.find(BENCHMARK_TARGET)? + BENCHMARK_TARGET.len();
+    let payload = strip_ansi(&line[payload_start..]);
+    let payload = payload.trim_start_matches([':', ' ']);
+    let mut fields = HashMap::new();
+    let bytes = payload.as_bytes();
+    let mut search_from = 0;
+    while let Some(rel) = payload[search_from..].find('=') {
+        let equals_idx = search_from + rel;
+        let key_start = payload[..equals_idx]
+            .rfind(|c: char| c.is_whitespace())
+            .map(|idx| idx + 1)
+            .unwrap_or(0);
+        let key = payload[key_start..equals_idx].trim().to_string();
+        let value_start = equals_idx + 1;
+        let (value, next) = parse_value(bytes, value_start, payload);
+        if !key.is_empty() {
+            fields.insert(key, value);
+        }
+        if next <= equals_idx {
+            break;
+        }
+        search_from = next;
+    }
+    if fields.is_empty() {
+        None
+    } else {
+        Some(fields)
+    }
+}
+
+fn parse_value(bytes: &[u8], start: usize, payload: &str) -> (String, usize) {
+    if start < bytes.len() && bytes[start] == b'"' {
+        let mut cursor = start + 1;
+        let value_start = cursor;
+        while cursor < bytes.len() && bytes[cursor] != b'"' {
+            if bytes[cursor] == b'\\' && cursor + 1 < bytes.len() {
+                cursor += 2;
+            } else {
+                cursor += 1;
+            }
+        }
+        let value = payload[value_start..cursor].to_string();
+        let next = if cursor < bytes.len() {
+            cursor + 1
+        } else {
+            cursor
+        };
+        (value, next)
+    } else {
+        let mut cursor = start;
+        while cursor < bytes.len() && !bytes[cursor].is_ascii_whitespace() {
+            cursor += 1;
+        }
+        (payload[start..cursor].to_string(), cursor)
+    }
+}
+
+fn strip_ansi(input: &str) -> String {
+    let mut out = String::with_capacity(input.len());
+    let mut chars = input.chars().peekable();
+    while let Some(c) = chars.next() {
+        if c == '\u{1b}' && chars.peek() == Some(&'[') {
+            chars.next();
+            for next in chars.by_ref() {
+                if next.is_ascii_alphabetic() {
+                    break;
+                }
+            }
+        } else {
+            out.push(c);
+        }
+    }
+    out
+}
+
+fn parse_u64(event: &HashMap<String, String>, key: &str) -> u64 {
+    event
+        .get(key)
+        .unwrap_or_else(|| panic!("missing field {key} in event {event:?}"))
+        .parse::<u64>()
+        .unwrap_or_else(|error| panic!("field {key} should be u64, got error: {error}: {event:?}"))
+}
+
+#[cfg(test)]
+mod parser_tests {
+    use super::*;
+
+    #[test]
+    fn given_simple_unquoted_fields_when_parsed_should_extract_all() {
+        let line = "...iggy_connectors::benchmark: benchmark partition_id=3 batch_size=42";
+        let fields = parse_event_fields(line).expect("fields parsed");
+        assert_eq!(fields.get("partition_id"), Some(&"3".to_string()));
+        assert_eq!(fields.get("batch_size"), Some(&"42".to_string()));
+    }
+
+    #[test]
+    fn given_quoted_string_values_when_parsed_should_strip_quotes() {
+        let line = "...iggy_connectors::benchmark: benchmark connector_type=\"sink\" connector_key=\"postgres\"";
+        let fields = parse_event_fields(line).expect("fields parsed");
+        assert_eq!(fields.get("connector_type"), Some(&"sink".to_string()));
+        assert_eq!(fields.get("connector_key"), Some(&"postgres".to_string()));
+    }
+
+    #[test]
+    fn given_quoted_value_with_embedded_space_when_parsed_should_preserve_space() {
+        let line = "...iggy_connectors::benchmark: benchmark connector_name=\"my connector\" batch_size=10";
+        let fields = parse_event_fields(line).expect("fields parsed");
+        assert_eq!(
+            fields.get("connector_name"),
+            Some(&"my connector".to_string())
+        );
+        assert_eq!(fields.get("batch_size"), Some(&"10".to_string()));
+    }
+
+    #[test]
+    fn given_ansi_color_codes_when_parsed_should_be_stripped() {
+        let line = "\u{1b}[32miggy_connectors::benchmark\u{1b}[0m: benchmark \u{1b}[3mconnector_type\u{1b}[0m=\"sink\" \u{1b}[3mbatch_size\u{1b}[0m=7";
+        let fields = parse_event_fields(line).expect("fields parsed");
+        assert_eq!(fields.get("connector_type"), Some(&"sink".to_string()));
+        assert_eq!(fields.get("batch_size"), Some(&"7".to_string()));
+    }
+
+    #[test]
+    fn given_line_without_target_when_parsed_should_return_none() {
+        let line = "INFO some_other_target: unrelated message foo=bar";
+        assert!(parse_event_fields(line).is_none());
+    }
+
+    #[test]
+    fn given_logs_with_mixed_targets_when_filtered_should_only_keep_benchmark_events() {
+        let logs = "INFO iggy_connectors::sink: regular log foo=1\n\
+                    INFO iggy_connectors::benchmark: benchmark connector_type=\"sink\" batch_size=4\n\
+                    INFO iggy_connectors::benchmark: benchmark connector_type=\"source\" batch_size=2\n";
+        let sink_events = parse_benchmark_events(logs, "sink");
+        let source_events = parse_benchmark_events(logs, "source");
+        assert_eq!(sink_events.len(), 1);
+        assert_eq!(source_events.len(), 1);
+        assert_eq!(sink_events[0].get("batch_size"), Some(&"4".to_string()));
+        assert_eq!(source_events[0].get("batch_size"), Some(&"2".to_string()));
+    }
+}
+
+#[iggy_harness(
+    server(connectors_runtime(config_path = "tests/connectors/runtime/benchmark.toml")),
+    seed = seeds::connector_stream
+)]
+async fn given_runtime_processing_batches_when_metrics_scraped_should_expose_stage_histograms(
+    harness: &TestHarness,
+) {
+    let (_sink_events, _source_events) =
+        wait_for_both_kinds(harness, "stdout_bench", "random_bench").await;
+
+    let metrics_body = scrape_metrics(harness).await;
+
+    assert!(
+        metrics_body.contains("iggy_connector_stage_duration_seconds"),
+        "expected stage histogram in /metrics, got:\n{metrics_body}"
+    );
+
+    let sink_total_count = parse_metric_value(
+        &metrics_body,
+        "iggy_connector_stage_duration_seconds_count",
+        &[
+            ("connector_key", "stdout_bench"),
+            ("connector_type", "Sink"),
+            ("stage", "Total"),
+        ],
+    );
+    assert!(
+        sink_total_count.is_some_and(|count| count > 0),
+        "sink Total histogram count should be > 0, got {sink_total_count:?}"
+    );
+
+    let sink_ffi_count = parse_metric_value(
+        &metrics_body,
+        "iggy_connector_stage_duration_seconds_count",
+        &[
+            ("connector_key", "stdout_bench"),
+            ("connector_type", "Sink"),
+            ("stage", "Ffi"),
+        ],
+    );
+    assert!(
+        sink_ffi_count.is_some_and(|count| count > 0),
+        "sink Ffi histogram count should be > 0, got {sink_ffi_count:?}"
+    );
+
+    let source_total_count = parse_metric_value(
+        &metrics_body,
+        "iggy_connector_stage_duration_seconds_count",
+        &[
+            ("connector_key", "random_bench"),
+            ("connector_type", "Source"),
+            ("stage", "Total"),
+        ],
+    );
+    assert!(
+        source_total_count.is_some_and(|count| count > 0),
+        "source Total histogram count should be > 0, got {source_total_count:?}"
+    );
+
+    let source_send_count = parse_metric_value(
+        &metrics_body,
+        "iggy_connector_stage_duration_seconds_count",
+        &[
+            ("connector_key", "random_bench"),
+            ("connector_type", "Source"),
+            ("stage", "IggySend"),
+        ],
+    );
+    assert!(
+        source_send_count.is_some_and(|count| count > 0),
+        "source IggySend histogram count should be > 0, got {source_send_count:?}"
+    );
+}
+
+#[iggy_harness(
+    server(connectors_runtime(config_path = "tests/connectors/runtime/benchmark_disabled.toml")),
+    seed = seeds::connector_stream
+)]
+async fn given_benchmark_flag_off_when_metrics_scraped_should_still_expose_histograms(
+    harness: &TestHarness,
+) {
+    sleep(Duration::from_millis(1500)).await;
+
+    let metrics_body = scrape_metrics(harness).await;
+    let count = parse_metric_value(
+        &metrics_body,
+        "iggy_connector_stage_duration_seconds_count",
+        &[
+            ("connector_key", "stdout_off"),
+            ("connector_type", "Sink"),
+            ("stage", "Total"),
+        ],
+    );
+    assert!(
+        count.is_some_and(|count| count > 0),
+        "histograms must populate regardless of the benchmark flag (the flag only gates the text event), got {count:?}\n{metrics_body}"
+    );
+}
+
+async fn scrape_metrics(harness: &TestHarness) -> String {
+    let url = format!(
+        "{}/metrics",
+        harness
+            .connectors_runtime()
+            .expect("connectors runtime handle should be available")
+            .http_url()
+    );
+    let response = reqwest::Client::new()
+        .get(&url)
+        .send()
+        .await
+        .unwrap_or_else(|e| panic!("failed to GET {url}: {e}"));
+    assert_eq!(response.status(), 200, "GET {url} returned non-200");
+    response
+        .text()
+        .await
+        .unwrap_or_else(|e| panic!("failed to read /metrics body: {e}"))
+}
+
+fn parse_metric_value(body: &str, metric: &str, labels: &[(&str, &str)]) -> Option<u64> {
+    body.lines()
+        .filter(|line| line.starts_with(metric))
+        .find_map(|line| {
+            let label_section = line.split('{').nth(1)?.split('}').next()?;
+            for (key, want) in labels {
+                let needle = format!("{key}=\"{want}\"");
+                if !label_section.contains(&needle) {
+                    return None;
+                }
+            }
+            let value_str = line.rsplit_once('}').and_then(|(_, rest)| {
+                let trimmed = rest.trim();
+                trimmed.split_whitespace().next()
+            })?;
+            value_str.parse::<u64>().ok()
+        })
+}
+
+#[iggy_harness(
+    server(connectors_runtime(config_path = "tests/connectors/runtime/benchmark_json.toml")),
+    seed = seeds::connector_stream
+)]
+async fn given_logging_format_json_when_benchmark_events_emitted_should_be_serde_json_parseable(
+    harness: &TestHarness,
+) {
+    let json_events = wait_for_json_benchmark_events(harness, "stdout_json", "random_json").await;
+
+    let sink_event = json_events
+        .iter()
+        .find(|event| {
+            event.get("connector_type").and_then(|v| v.as_str()) == Some("sink")
+                && event.get("connector_key").and_then(|v| v.as_str()) == Some("stdout_json")
+        })
+        .expect("sink benchmark JSON event should be present");
+    let fields = sink_event
+        .get("fields")
+        .or(Some(sink_event))
+        .expect("event has fields");
+    let target = sink_event
+        .get("target")
+        .and_then(|v| v.as_str())
+        .expect("event has target");
+    assert_eq!(target, BENCHMARK_TARGET);
+    for key in [
+        "connector_type",
+        "connector_key",
+        "stream",
+        "topic",
+        "batch_size",
+        "processed_count",
+        "prepare_us",
+        "ffi_us",
+        "total_us",
+    ] {
+        assert!(
+            fields.get(key).is_some(),
+            "sink benchmark JSON event missing field {key}: {sink_event}"
+        );
+    }
+
+    let source_event = json_events
+        .iter()
+        .find(|event| {
+            event.get("connector_type").and_then(|v| v.as_str()) == Some("source")
+                && event.get("connector_key").and_then(|v| v.as_str()) == Some("random_json")
+        })
+        .expect("source benchmark JSON event should be present");
+    let fields = source_event
+        .get("fields")
+        .or(Some(source_event))
+        .expect("event has fields");
+    for key in [
+        "connector_type",
+        "connector_key",
+        "batch_size",
+        "sent_count",
+        "decode_us",
+        "prepare_us",
+        "iggy_send_us",
+        "state_save_us",
+        "total_us",
+    ] {
+        assert!(
+            fields.get(key).is_some(),
+            "source benchmark JSON event missing field {key}: {source_event}"
+        );
+    }
+}
+
+async fn wait_for_json_benchmark_events(
+    harness: &TestHarness,
+    sink_key: &str,
+    source_key: &str,
+) -> Vec<serde_json::Value> {
+    let deadline = Instant::now() + POLL_DEADLINE;
+    loop {
+        let logs = collect_runtime_logs(harness);
+        let mut events = parse_json_benchmark_events(&logs);
+        events.retain(|event| {
+            let fields = event.get("fields").unwrap_or(event);
+            matches!(
+                fields.get("connector_key").and_then(|v| v.as_str()),
+                Some(k) if k == sink_key || k == source_key
+            )
+        });
+        let has_sink = events.iter().any(|event| {
+            event
+                .get("fields")
+                .unwrap_or(event)
+                .get("connector_key")
+                .and_then(|v| v.as_str())
+                == Some(sink_key)
+        });
+        let has_source = events.iter().any(|event| {
+            event
+                .get("fields")
+                .unwrap_or(event)
+                .get("connector_key")
+                .and_then(|v| v.as_str())
+                == Some(source_key)
+        });
+        if has_sink && has_source {
+            // Flatten {fields: {...}} envelopes for assertion convenience.
+            return events
+                .into_iter()
+                .map(|event| {
+                    if let Some(fields) = event.get("fields").cloned() {
+                        let mut merged = fields;
+                        if let (Some(target), Some(merged_obj)) =
+                            (event.get("target"), merged.as_object_mut())
+                        {
+                            merged_obj.insert("target".to_string(), target.clone());
+                        }
+                        merged
+                    } else {
+                        event
+                    }
+                })
+                .collect();
+        }
+        if Instant::now() >= deadline {
+            panic!(
+                "timed out waiting for sink ({sink_key}) + source ({source_key}) JSON benchmark events. \
+                 logs:\n{logs}"
+            );
+        }
+        sleep(POLL_INTERVAL).await;
+    }
+}
+
+fn parse_json_benchmark_events(logs: &str) -> Vec<serde_json::Value> {
+    logs.lines()
+        .filter_map(|line| serde_json::from_str::<serde_json::Value>(line.trim()).ok())
+        .filter(|event| event.get("target").and_then(|v| v.as_str()) == Some(BENCHMARK_TARGET))
+        .collect()
+}
+
+pub struct BenchmarkEnvOverrideFixture;
+
+#[async_trait]
+impl TestFixture for BenchmarkEnvOverrideFixture {
+    async fn setup() -> Result<Self, TestBinaryError> {
+        Ok(Self)
+    }
+
+    fn connectors_runtime_envs(&self) -> HashMap<String, String> {
+        let mut envs = HashMap::new();
+        envs.insert(
+            "IGGY_CONNECTORS_SINK_STDOUT_OFF_BENCHMARK".to_string(),
+            "true".to_string(),
+        );
+        envs.insert(
+            "IGGY_CONNECTORS_SOURCE_RANDOM_OFF_BENCHMARK".to_string(),
+            "true".to_string(),
+        );
+        envs
+    }
+
+    async fn seed(&self, _client: &IggyClient) -> Result<(), SeedError> {
+        Ok(())
+    }
+
+    fn has_seed(&self) -> bool {
+        false
+    }
+}
diff --git a/core/integration/tests/connectors/runtime/benchmark.toml b/core/integration/tests/connectors/runtime/benchmark.toml
new file mode 100644
index 000000000..447ae5bfe
--- /dev/null
+++ b/core/integration/tests/connectors/runtime/benchmark.toml
@@ -0,0 +1,23 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[connectors]
+config_type = "local"
+config_dir = "tests/connectors/runtime/benchmark_config"
+
+[http.metrics]
+enabled = true
diff --git a/core/integration/tests/connectors/runtime/benchmark_config/random_source.toml b/core/integration/tests/connectors/runtime/benchmark_config/random_source.toml
new file mode 100644
index 000000000..20a8d55fd
--- /dev/null
+++ b/core/integration/tests/connectors/runtime/benchmark_config/random_source.toml
@@ -0,0 +1,38 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+type = "source"
+key = "random_bench"
+enabled = true
+version = 0
+name = "Random benchmark source"
+path = "../../target/debug/libiggy_connector_random_source"
+plugin_config_format = "json"
+benchmark = true
+
+[[streams]]
+stream = "test_stream"
+topic = "test_topic"
+schema = "json"
+batch_length = 100
+linger_time = "5ms"
+
+[plugin_config]
+interval = "50ms"
+max_count = 1_000_000
+messages_range = [3, 5]
+payload_size = 100
diff --git a/core/integration/tests/connectors/runtime/benchmark_config/stdout_sink.toml b/core/integration/tests/connectors/runtime/benchmark_config/stdout_sink.toml
new file mode 100644
index 000000000..89451d74c
--- /dev/null
+++ b/core/integration/tests/connectors/runtime/benchmark_config/stdout_sink.toml
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+type = "sink"
+key = "stdout_bench"
+enabled = true
+version = 0
+name = "Stdout benchmark sink"
+path = "../../target/debug/libiggy_connector_stdout_sink"
+benchmark = true
+
+[[streams]]
+stream = "test_stream"
+topics = ["test_topic"]
+schema = "json"
+batch_length = 50
+poll_interval = "5ms"
+consumer_group = "stdout_bench_sink_connector"
+
+[plugin_config]
+print_payload = false
diff --git a/core/integration/tests/connectors/runtime/benchmark_disabled.toml b/core/integration/tests/connectors/runtime/benchmark_disabled.toml
new file mode 100644
index 000000000..16ce3821d
--- /dev/null
+++ b/core/integration/tests/connectors/runtime/benchmark_disabled.toml
@@ -0,0 +1,23 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[connectors]
+config_type = "local"
+config_dir = "tests/connectors/runtime/benchmark_disabled_config"
+
+[http.metrics]
+enabled = true
diff --git a/core/integration/tests/connectors/runtime/benchmark_disabled_config/random_source.toml b/core/integration/tests/connectors/runtime/benchmark_disabled_config/random_source.toml
new file mode 100644
index 000000000..70c0572be
--- /dev/null
+++ b/core/integration/tests/connectors/runtime/benchmark_disabled_config/random_source.toml
@@ -0,0 +1,38 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+type = "source"
+key = "random_off"
+enabled = true
+version = 0
+name = "Random source (benchmark off)"
+path = "../../target/debug/libiggy_connector_random_source"
+plugin_config_format = "json"
+benchmark = false
+
+[[streams]]
+stream = "test_stream"
+topic = "test_topic"
+schema = "json"
+batch_length = 100
+linger_time = "5ms"
+
+[plugin_config]
+interval = "50ms"
+max_count = 1_000_000
+messages_range = [3, 5]
+payload_size = 100
diff --git a/core/integration/tests/connectors/runtime/benchmark_disabled_config/stdout_sink.toml b/core/integration/tests/connectors/runtime/benchmark_disabled_config/stdout_sink.toml
new file mode 100644
index 000000000..062259003
--- /dev/null
+++ b/core/integration/tests/connectors/runtime/benchmark_disabled_config/stdout_sink.toml
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+type = "sink"
+key = "stdout_off"
+enabled = true
+version = 0
+name = "Stdout sink (benchmark off)"
+path = "../../target/debug/libiggy_connector_stdout_sink"
+benchmark = false
+
+[[streams]]
+stream = "test_stream"
+topics = ["test_topic"]
+schema = "json"
+batch_length = 50
+poll_interval = "5ms"
+consumer_group = "stdout_off_sink_connector"
+
+[plugin_config]
+print_payload = false
diff --git a/core/integration/tests/connectors/runtime/benchmark_json.toml b/core/integration/tests/connectors/runtime/benchmark_json.toml
new file mode 100644
index 000000000..af6c4cbbe
--- /dev/null
+++ b/core/integration/tests/connectors/runtime/benchmark_json.toml
@@ -0,0 +1,26 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[connectors]
+config_type = "local"
+config_dir = "tests/connectors/runtime/benchmark_json_config"
+
+[logging]
+format = "json"
+
+[http.metrics]
+enabled = true
diff --git a/core/integration/tests/connectors/runtime/benchmark_json_config/random_source.toml b/core/integration/tests/connectors/runtime/benchmark_json_config/random_source.toml
new file mode 100644
index 000000000..e8c6f71ba
--- /dev/null
+++ b/core/integration/tests/connectors/runtime/benchmark_json_config/random_source.toml
@@ -0,0 +1,38 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+type = "source"
+key = "random_json"
+enabled = true
+version = 0
+name = "Random source (json log)"
+path = "../../target/debug/libiggy_connector_random_source"
+plugin_config_format = "json"
+benchmark = true
+
+[[streams]]
+stream = "test_stream"
+topic = "test_topic"
+schema = "json"
+batch_length = 100
+linger_time = "5ms"
+
+[plugin_config]
+interval = "50ms"
+max_count = 1_000_000
+messages_range = [3, 5]
+payload_size = 100
diff --git a/core/integration/tests/connectors/runtime/benchmark_json_config/stdout_sink.toml b/core/integration/tests/connectors/runtime/benchmark_json_config/stdout_sink.toml
new file mode 100644
index 000000000..c2c95481a
--- /dev/null
+++ b/core/integration/tests/connectors/runtime/benchmark_json_config/stdout_sink.toml
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+type = "sink"
+key = "stdout_json"
+enabled = true
+version = 0
+name = "Stdout sink (json log)"
+path = "../../target/debug/libiggy_connector_stdout_sink"
+benchmark = true
+
+[[streams]]
+stream = "test_stream"
+topics = ["test_topic"]
+schema = "json"
+batch_length = 50
+poll_interval = "5ms"
+consumer_group = "stdout_json_sink_connector"
+
+[plugin_config]
+print_payload = false
diff --git a/core/integration/tests/connectors/runtime/mod.rs b/core/integration/tests/connectors/runtime/mod.rs
index e5b353fc3..3233ae831 100644
--- a/core/integration/tests/connectors/runtime/mod.rs
+++ b/core/integration/tests/connectors/runtime/mod.rs
@@ -17,4 +17,5 @@
  * under the License.
  */
 
+mod benchmark;
 mod error_isolation;