Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(capture): update DESIGN.md for v1::sinks modules (#60181)

Eli Reismanb9f9034287c1
diff --git a/rust/capture/src/v1/sinks/DESIGN.md b/rust/capture/src/v1/sinks/DESIGN.md
index 6194cc15a9ac..9e733e6a603e 100644
--- a/rust/capture/src/v1/sinks/DESIGN.md
+++ b/rust/capture/src/v1/sinks/DESIGN.md
@@ -11,6 +11,18 @@ Today the only backend is Kafka (via rdkafka); the trait boundaries are
drawn so that future backends (WarpStream, S3, etc.) slot in without
touching request-path code.
+### Endpoint paths
+
+v1 capture endpoints follow the naming scheme
+`/i/v<version>/<scope>/<payload>/`:
+
+| Endpoint | Path | Status |
+|---|---|---|
+| Analytics events | `/i/v1/analytics/events/` | First v1 endpoint |
+
+As additional capture domains migrate to v1 (e.g. AI, replay),
+they register their own paths under the same scheme.
+
```text
┌─────────────┐
│ HTTP layer │
@@ -54,7 +66,7 @@ Key properties:
graph TD
mod["sinks/mod.rs<br>SinkName, Config, Sinks,<br>load_sinks, re-exports"]
constants["constants.rs<br>DEFAULT_PRODUCE_TIMEOUT,<br>SINK_LIVENESS_DEADLINE,<br>SINK_STALL_THRESHOLD"]
- event["event.rs<br>trait Event,<br>build_context_headers"]
+ event["event.rs<br>trait Event"]
sink["sink.rs<br>trait Sink"]
types["types.rs<br>Destination, Outcome,<br>trait SinkResult,<br>BatchSummary"]
router["router.rs<br>Router,<br>RouterError"]
@@ -197,20 +209,27 @@ pub trait Event: Send + Sync {
fn uuid(&self) -> Uuid;
fn should_publish(&self) -> bool;
fn destination(&self) -> &Destination;
- fn headers(&self) -> Vec<(String, String)>;
- fn write_partition_key(&self, ctx: &Context, buf: &mut String);
- fn serialize_into(&self, ctx: &Context, buf: &mut String) -> Result<(), String>;
+ fn headers(&self, ctx: &Context) -> CapturedEventHeaders;
+ fn partition_key(&self, ctx: &Context, buf: &mut String);
+ fn serialize_into(&self, ctx: &Context, buf: &mut String) -> anyhow::Result<()>;
}
```
+`headers` receives the request `Context` so each `Event` implementation
+can combine batch-scoped fields (token, now, historical_migration) with
+event-scoped fields into a single `CapturedEventHeaders`
+(`common_types`). The sink converts the returned struct to its
+transport-specific format via `From<CapturedEventHeaders> for
+OwnedHeaders`.
+
The analytics capture endpoint's `WrappedEvent` implements this trait
(see [section 10](#10-analytics-event-serialization)).
-Other capture endpoints (e.g. session replay, exceptions) would provide
+Other capture endpoints (e.g. session replay, exceptions) provide
their own `Event` implementations without changing any sink code.
### Buffer-reuse pattern
-`write_partition_key` and `serialize_into` write into caller-owned
+`partition_key` and `serialize_into` write into caller-owned
`String` buffers that are cleared between events. This eliminates
per-event allocations after the first iteration — the buffers grow to
high-water mark and stay there for the entire batch.
@@ -226,7 +245,7 @@ high-water mark and stay there for the entire batch.
│ payload_buf.clear() ◄─ no alloc │
│ key_buf.clear() ◄─ no alloc │
│ event.serialize_into(ctx, &payload_buf) │
- │ event.write_partition_key(ctx, &key_buf)│
+ │ event.partition_key(ctx, &key_buf) │
│ producer.send(...) │
└──────────────────────────────────────────────┘
```
@@ -240,29 +259,42 @@ Callers have two orthogonal ways to prevent an event from being produced:
| `should_publish() == false` | Pipeline validation (e.g. `EventResult != Ok`) | Silently skipped, no `SinkResult` returned |
| `Destination::Drop` | Routing logic (e.g. quota limiter) | `topic_for()` returns `None`, event skipped |
-### Header layering
+### Header construction
-Headers are built in two layers to avoid redundant work per event:
+Each `Event` implementation builds the full `CapturedEventHeaders`
+struct per event, combining batch-scoped context (token, now,
+historical_migration) with event-scoped fields (distinct_id, uuid,
+timestamp, session_id, etc.):
```text
- ┌──────────────────────────────────────────┐
- │ Batch-level (once per batch) │
- │ build_context_headers(ctx) │
- │ → token, now, historical_migration? │
- └──────────────────┬───────────────────────┘
- │ merged per-event
- ┌──────────────────▼───────────────────────┐
- │ Event-level (per event) │
- │ event.headers() │
- │ → distinct_id, event, uuid, timestamp, │
- │ session_id?, force_disable_*?, │
- │ dlq_reason/step/timestamp? (if DLQ) │
- └──────────────────────────────────────────┘
+ ┌──────────────────────────────────────────────┐
+ │ event.headers(ctx: &Context) │
+ │ │
+ │ CapturedEventHeaders { │
+ │ token, ◄─ from ctx │
+ │ now, ◄─ from ctx │
+ │ historical_migration, ◄─ from ctx │
+ │ distinct_id, ◄─ from event │
+ │ event, ◄─ from event │
+ │ uuid, ◄─ from event │
+ │ timestamp, ◄─ from event │
+ │ session_id?, ◄─ from event │
+ │ force_disable_*?, ◄─ from event │
+ │ skip_heatmap_processing?, ◄─ from event │
+ │ dlq_reason/step/timestamp? ◄─ from event │
+ │ } │
+ └──────────────────┬───────────────────────────┘
+ │
+ ▼
+ ┌──────────────────────────────────────────────┐
+ │ let headers: OwnedHeaders = headers.into(); │
+ │ (From impl in common_types) │
+ └──────────────────────────────────────────────┘
```
-The sink merges both into transport-specific format (e.g. Kafka
-`OwnedHeaders`) inline during the enqueue phase. There is no separate
-merge function — headers are appended sequentially into `OwnedHeaders`.
+The sink converts `CapturedEventHeaders` to `OwnedHeaders` via the
+`From` impl in `common_types`. There is no separate merge function —
+a single structured type flows from event to transport.
---
@@ -275,11 +307,11 @@ inspecting per-event publish outcomes:
```rust
pub trait SinkResult: Send + Sync {
- fn key(&self) -> Uuid; // event UUID — correlation key
- fn outcome(&self) -> Outcome; // Success | Timeout | RetriableError | FatalError
- fn cause(&self) -> Option<&'static str>; // low-cardinality metric tag
- fn detail(&self) -> Option<Cow<'_, str>>; // human-readable error detail
- fn elapsed(&self) -> Option<chrono::Duration>; // enqueue-to-ack latency
+ fn key(&self) -> Uuid; // event UUID — correlation key
+ fn outcome(&self) -> Outcome; // Success | Timeout | RetriableError | FatalError
+ fn cause(&self) -> Option<&'static str>; // low-cardinality metric tag
+ fn detail(&self) -> Option<Cow<'_, str>>; // human-readable error detail
+ fn elapsed(&self) -> Option<Duration>; // enqueue-to-ack latency (std::time::Duration)
}
```
@@ -294,7 +326,6 @@ Kafka I/O.
```rust
pub enum Outcome {
- InFlight, // pre-resolution default
Success,
Timeout,
RetriableError,
@@ -343,19 +374,27 @@ pub struct BatchSummary {
pub retriable: usize,
pub fatal: usize,
pub timed_out: usize,
- pub errors: HashMap<String, usize>, // cause tag → count
+ pub errors: HashMap<&'static str, usize>, // cause tag → count
}
```
```mermaid
classDiagram
+ class Outcome {
+ <<enum>>
+ Success
+ Timeout
+ RetriableError
+ FatalError
+ }
+
class SinkResult {
<<trait>>
+key() Uuid
+outcome() Outcome
- +cause() Option~str~
+ +cause() Option~static str~
+detail() Option~Cow str~
- +elapsed() Option~Duration~
+ +elapsed() Option~std Duration~
}
class KafkaResult {
@@ -371,12 +410,13 @@ classDiagram
+retriable: usize
+fatal: usize
+timed_out: usize
- +errors: HashMap
+ +errors: HashMap~static str, usize~
+from_results(results) BatchSummary
+all_ok() bool
}
SinkResult <|.. KafkaResult : implements
+ SinkResult --> Outcome : returns
BatchSummary ..> SinkResult : aggregates
```
@@ -400,14 +440,14 @@ corresponds 1:1 to a published event.
┌──────────────────────────▼───────────────────────────────────────┐
│ Phase 1: Enqueue (sequential, per-partition ordering preserved) │
│ │
- │ build_context_headers(ctx) ◄─ once per batch │
- │ │
│ for each event: │
│ ├── should_publish()? → skip if false │
│ ├── topic_for(destination)? → skip if Drop/None │
│ ├── serialize_into(ctx, payload_buf) │
- │ ├── write_partition_key(ctx, key_buf) │
- │ ├── merge context + event headers → OwnedHeaders │
+ │ ├── event.headers(ctx) → CapturedEventHeaders │
+ │ ├── event.partition_key(ctx, key_buf) │
+ │ ├── effective_partition_key(key, headers, dest) → key/None │
+ │ ├── CapturedEventHeaders → OwnedHeaders (via From) │
│ └── producer.send(ProduceRecord) │
│ ├── Ok(ack_future) → push to FuturesUnordered │
│ ├── Err(QueueFull) + retries left → sleep, retry │
@@ -462,11 +502,13 @@ If `producer.send()` returns `QueueFull`, the sink retries up to
rdkafka's background thread time to drain in-flight deliveries. Metrics
track recovery vs exhaustion via `capture_v1_kafka_queue_full_retries_total`.
-An empty partition key buffer signals the event requested no partition
-key (e.g. `force_disable_person_processing` on `AnalyticsMain`). In that
-case `None` is passed to rdkafka so it round-robins; passing `Some("")`
-would hash to a single deterministic partition via murmur2, creating a
-hot partition.
+After serialization and header construction, `effective_partition_key()`
+(`kafka/sink.rs`) decides whether the partition key should be nulled.
+Events always write a key via `partition_key()`; the sink nulls it when
+`force_disable_person_processing` is set and the destination is
+`AnalyticsMain` or `Overflow`. In that case `None` is passed to rdkafka
+so it round-robins; passing `Some("")` would hash to a single
+deterministic partition via murmur2, creating a hot partition.
### Phase 2 — Drain
@@ -513,11 +555,11 @@ The caller correlates results back to original events using
Each sink is identified by a `SinkName` enum variant with a corresponding
env var prefix:
-| Variant | `as_str()` | `env_prefix()` |
-|---|---|---|
-| `Msk` | `msk` | `CAPTURE_V1_SINK_MSK_` |
-| `MskAlt` | `msk_alt` | `CAPTURE_V1_SINK_MSK_ALT_` |
-| `Ws` | `ws` | `CAPTURE_V1_SINK_WS_` |
+| Variant | `as_str()` | `env_prefix()` | `lifecycle_tag()` |
+|---|---|---|---|
+| `Msk` | `msk` | `CAPTURE_V1_SINK_MSK_` | `v1-sink-msk` |
+| `MskAlt` | `msk_alt` | `CAPTURE_V1_SINK_MSK_ALT_` | `v1-sink-msk_alt` |
+| `Ws` | `ws` | `CAPTURE_V1_SINK_WS_` | `v1-sink-ws` |
Active sinks are declared via a CSV env var:
@@ -608,12 +650,21 @@ only needs to specify hosts and topics.
| `max_retries` | `4` | `message.send.max.retries` | Tuned for MSK failover |
| `max_in_flight_requests` | `1000000` | `max.in.flight.requests.per.connection` | |
| `sticky_partitioning_linger_ms` | `10` | `sticky.partitioning.linger.ms` | Keyless message distribution |
+| `broker_address_family` | `""` | `broker.address.family` | Empty = librdkafka default; `v4`/`v6`/`any` |
+| `log_connection_close` | `true` | `log.connection.close` | Log broker connection close events |
+| `queue_buffering_max_messages` | `100000` | `queue.buffering.max.messages` | Max messages buffered in producer queue |
+| `retry_backoff_max_ms` | `1000` | `retry.backoff.max.ms` | Upper bound on exponential retry backoff |
+| `socket_send_buffer_bytes` | `0` | `socket.send.buffer.bytes` | TCP send buffer size; 0 = OS default |
+| `socket_receive_buffer_bytes` | `0` | `socket.receive.buffer.bytes` | TCP receive buffer size; 0 = OS default |
| `enqueue_retry_max` | `3` | _(application-level)_ | QueueFull backpressure retries |
| `enqueue_poll_ms` | `33` | _(application-level)_ | Pause between QueueFull retries |
| `topic_main` | _(required)_ | — | Analytics main topic |
| `topic_historical` | _(required)_ | — | Historical migration topic |
| `topic_overflow` | _(required)_ | — | Overflow topic |
| `topic_dlq` | _(required)_ | — | Dead letter queue topic |
+| `topic_exception` | _(required)_ | — | Error tracking events topic |
+| `topic_heatmap` | _(required)_ | — | Heatmap ingestion topic |
+| `topic_client_ingestion_warning` | _(required)_ | — | Client ingestion warning topic |
Topic resolution is handled by `Config::topic_for(&Destination)`:
@@ -623,6 +674,9 @@ Topic resolution is handled by `Config::topic_for(&Destination)`:
| `AnalyticsHistorical` | `topic_historical` |
| `Overflow` | `topic_overflow` |
| `Dlq` | `topic_dlq` |
+| `ExceptionErrorTracking` | `topic_exception` |
+| `HeatmapMain` | `topic_heatmap` |
+| `ClientIngestionWarning` | `topic_client_ingestion_warning` |
| `Custom(t)` | `t` (passthrough) |
| `Drop` | `None` (skip) |
@@ -709,7 +763,7 @@ the QueueFull retry loop without reallocating the message).
`SendHandle` implements `Future` and maps rdkafka delivery outcomes:
- Channel closed → `ProduceError::DeliveryCancelled` (retriable)
-- Kafka error → `ProduceError::Kafka { code, retriable }` or
+- Kafka error → `ProduceError::Kafka { code }` or
`ProduceError::EventTooBig` for `MessageSizeTooLarge`
### ProduceError
@@ -717,13 +771,15 @@ the QueueFull retry loop without reallocating the message).
```rust
pub enum ProduceError {
EventTooBig { message: String },
- Kafka { code: RDKafkaErrorCode, retriable: bool },
+ Kafka { code: RDKafkaErrorCode },
DeliveryCancelled,
}
```
-Fatal (non-retriable) Kafka codes: `MessageSizeTooLarge`,
-`InvalidMessageSize`, `InvalidMessage`. Everything else is retriable.
+Retriability is computed by `ProduceError::is_retriable()` using
+`is_fatal_kafka_error(code)`. Fatal (non-retriable) Kafka codes:
+`MessageSizeTooLarge`, `InvalidMessageSize`, `InvalidMessage`.
+Everything else is retriable.
---
@@ -851,13 +907,16 @@ All error-related metrics use stable, low-cardinality tags derived from:
### Structured logging
+All sink-level log output uses `ctx_log!` macros which attach
+request-scoped context (token, path, attempt) to the log line.
+
| Level | When | Location |
|---|---|---|
-| `info_span!("v1_publish_batch", ...)` | Wraps entire batch | `kafka/sink.rs` |
-| `debug!` | All events succeeded | `kafka/sink.rs` |
+| `DEBUG` (via `ctx_log!`) | All events succeeded | `kafka/sink.rs` |
| `WARN` (via `ctx_log!`) | Partial batch failure | `kafka/sink.rs` |
| `ERROR` (via `ctx_log!`) | Full batch failure | `kafka/sink.rs` |
| `ERROR` (via `ctx_log!`) | Producer not ready | `kafka/sink.rs` |
+| `ERROR` (via `ctx_log!`) | Event serialization failed | `kafka/sink.rs` |
| `error!` | rdkafka client error callback | `kafka/context.rs` |
| `error!` | All brokers down | `kafka/context.rs` |
| `info!` | Producer connected | `kafka/producer.rs` |
@@ -875,29 +934,38 @@ resolution:
```rust
pub enum Destination {
- AnalyticsMain, // normal analytics events
- AnalyticsHistorical, // historical migration imports
- Overflow, // overflow-routed events
- Dlq, // dead letter queue (event restriction)
- Custom(String), // custom topic passthrough
- Drop, // do not produce
+ AnalyticsMain, // normal analytics events
+ AnalyticsHistorical, // historical migration imports
+ Overflow, // overflow-routed events
+ Dlq, // dead letter queue (event restriction)
+ ExceptionErrorTracking, // $exception events → error tracking pipeline
+ HeatmapMain, // $$heatmap events → heatmap ingestion
+ ClientIngestionWarning, // $$client_ingestion_warning events
+ Custom(String), // custom topic passthrough
+ Drop, // do not produce
}
```
+`Destination::is_analytics_pipeline()` returns `true` for
+`AnalyticsMain` and `AnalyticsHistorical` only. This gate controls
+which events are subject to analytics-scoped restrictions, overflow
+routing, and related pipeline logic.
+
Topic resolution happens inside `kafka::config::Config::topic_for()`,
keeping the Sink trait unaware of topic names.
-### Partition key resolution (WrappedEvent)
+### Partition key resolution
+
+Partition key construction is split between the `Event` implementation
+and the sink:
+
+1. **`Event::partition_key(ctx, buf)`** always writes a key into the
+ buffer. For analytics events (`WrappedEvent`):
```text
┌───────────────────────────────────────────────────┐
- │ write_partition_key(ctx, buf) │
+ │ partition_key(ctx, buf) │
│ │
- │ force_disable_person_processing │
- │ AND destination ∈ {Main, Overflow}? │
- │ ├── yes → return "" (empty = round-robin) │
- │ └── no ──┐ │
- │ │ │
│ cookieless_mode? │
│ ├── yes, capture_internal → "token:127.0.0.1" │
│ ├── yes, normal → "token:client_ip" │
@@ -905,12 +973,26 @@ keeping the Sink trait unaware of topic names.
└───────────────────────────────────────────────────┘
```
+2. **`effective_partition_key()`** (`kafka/sink.rs`) decides whether
+ the key should be nulled before sending to the producer:
+
+```rust
+fn effective_partition_key<'a>(
+ key_buf: &'a str,
+ force_disable_person_processing: bool,
+ destination: &Destination,
+) -> Option<&'a str>
+```
+
+ If `force_disable_person_processing` is set and the destination is
+ `AnalyticsMain` or `Overflow`, the function returns `None`. Otherwise
+ it returns `Some(key_buf)`.
+
Key design choices:
-- **Empty key = round-robin.** An empty buffer signals "no key" to the
- sink. The sink passes `None` to rdkafka, which round-robins across
- partitions. Passing `Some("")` would hash to a single partition via
- murmur2, creating a hot spot.
+- **`None` = round-robin.** `None` is passed to rdkafka, which
+ round-robins across partitions. Passing `Some("")` would hash to a
+ single deterministic partition via murmur2, creating a hot spot.
- **DLQ/Historical/Custom retain key** even when
`force_disable_person_processing` is set — only Main and Overflow
drop the key, matching v0 behavior.
@@ -923,9 +1005,10 @@ Key design choices:
## 10. Analytics event serialization
The `v1::analytics::WrappedEvent` is the concrete `Event` implementation
-for the analytics capture endpoint. It bridges the new v1 event schema
-(`Event`, `Options`, raw `properties`) to the legacy `IngestionEvent`
-shape that downstream ingestion workers expect.
+for the analytics capture endpoint (`/i/v1/analytics/events/`). It
+bridges the new v1 event schema (`Event`, `Options`, raw `properties`)
+to the legacy `IngestionEvent` shape that downstream ingestion workers
+expect.
### Data flow
@@ -1035,7 +1118,7 @@ Fields intentionally omitted vs the legacy `RawEvent`:
`capture_internal` requests (PostHog's own telemetry) have their IP
redacted to `127.0.0.1` in both `serialize_into` (the `ip` field on
-`IngestionEvent`) and `write_partition_key` (cookieless mode).
+`IngestionEvent`) and `partition_key` (cookieless mode).
---
@@ -1059,8 +1142,14 @@ Builder-style API for configuring failure scenarios:
| `with_ack_delay(duration)` | Ack futures sleep before resolving |
| `with_not_ready()` | `is_ready()` returns `false` |
-Records are captured in-memory and inspectable via `with_records(|recs| ...)`
-and `record_count()`.
+Sent records are captured as `OwnedProduceRecord` (owned copies of
+`ProduceRecord`) and inspectable via:
+
+| Method | Purpose |
+|---|---|
+| `record_count()` | Number of records sent |
+| `with_records(\|recs\| ...)` | Inspect captured records under lock |
+| `clear()` | Reset captured records |
### Test infrastructure (sink_tests.rs)