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.

fix(personhog): bound writer upsert concurrency and pace flush drains (#82609)

José Sequeira8cca7b28357b
diff --git a/rust/personhog-writer/README.md b/rust/personhog-writer/README.md
index 6b65f72fb937..2686b42cfe4c 100644
--- a/rust/personhog-writer/README.md
+++ b/rust/personhog-writer/README.md
@@ -47,11 +47,13 @@ The writer is a pure applier: the leader admits every record against this servic
The consumer flushes the buffer when any of these conditions are met:
-- **Timer**: every `FLUSH_INTERVAL_MS` (default 5s)
-- **Size threshold**: buffer reaches `FLUSH_BUFFER_SIZE` entries (default 1000)
-- **Backpressure**: buffer reaches `BUFFER_CAPACITY` (default 50k), flush immediately
+- **Timer**: every `FLUSH_INTERVAL_MS` (default 30s)
+- **Size threshold**: buffer reaches `FLUSH_BUFFER_SIZE` entries (default 10k)
+- **Backpressure**: buffer reaches `BUFFER_CAPACITY` (default 100k), flush immediately
- **Shutdown**: graceful shutdown flushes remaining buffer
+Every flush drains at most `FLUSH_BUFFER_SIZE` rows (rounded up to whole partitions), so a backlogged buffer empties as a sequence of bounded batches paced by the writer instead of one giant batch. Whole partitions only: a partition's max offset is safe to commit exactly when every buffered person from it has flushed, so a drained batch's offsets never skip past a person still in the buffer.
+
## Idempotency
The upsert uses `WHERE EXCLUDED.version > COALESCE(table.version, -1)`, so out-of-order or replayed messages from Kafka are safely ignored. The `COALESCE` handles nullable version columns (existing rows with NULL version will accept any update).
@@ -62,7 +64,8 @@ A person whose fields cannot be bound losslessly (malformed uuid, `team_id` beyo
Failures are handled at chunk granularity: the store splits each batch into chunks (sized by `upsert_batch_size`), runs them in parallel against `PgStore::execute_chunk`, and reports successful, transient-failed, and data-failed chunks separately so only the affected rows need retry.
-- **Transient** (connection loss, pool timeout, deadlock): retry just the failed chunks with exponential backoff (1s, 2s, 4s). Successful chunks are not re-executed. After 3 consecutive failures, signal unhealthy and shut down.
+- **Transient** (connection loss, deadlock): retry just the failed chunks with exponential backoff (1s, 2s, 4s). Successful chunks are not re-executed. After 3 consecutive failures, signal unhealthy and shut down.
+- **Saturation** (local pool acquire timeout): the writer's own in-flight statements exceeded pool capacity — self-inflicted, so it retries with the same backoff but never counts toward the consecutive-failure shutdown. Escalating on it would let a slow-PG burst crash-loop the pod, and each restart drops the buffers and redelivers, worsening the load that caused it.
- **Data** (constraint violation, invalid input): fall back to per-row inserts for the failed chunks' rows, isolating the bad records. Per-row upserts run with bounded concurrency (`ROW_FALLBACK_CONCURRENCY`). Successful chunks are not re-executed.
- **Non-transient row failure** (constraint violation, unbindable field): an invariant violation — the leader admitted a record Postgres cannot apply, so admission has a gap. The flush halts via `signal_failure` without committing; Kafka redelivers after restart, and the alarm stands until the gap is fixed. Skipping is never an option: it would permanently diverge PG from the cache and changelog.
- **Chunk task panic**: a spawned chunk task that panics cannot hand its persons back — the task's stack is unwound. The writer treats this as a fatal error, signals failure, and exits. Because Kafka offsets are committed only on full batch success, redelivery after restart recovers the records; the panic payload is captured in the error message for diagnosis.
@@ -75,7 +78,9 @@ The leader serializes a parsed `serde_json::Value` into proto bytes, so they are
## Backpressure
-When the writer is slow (PG latency, connection pool exhaustion), the bounded channel between consumer and writer fills up (capacity: 8 batches). The consumer blocks on channel send, which stops Kafka consumption. This naturally limits memory usage and prevents unbounded buffering.
+Total in-flight statement concurrency is capped by a pod-wide permit budget (`UPSERT_CONCURRENCY`) shared across all writer lanes and both the chunk and per-row paths. A burst of chunks queues at the semaphore — a cheap, unbounded wait — instead of oversubscribing the pool and converting its own fan-out into acquire timeouts.
+
+When the writer is slow (PG latency, pool saturation), size-triggered flushes stop being accepted, the lane buffer grows, and at the hard cap the consumer blocks on channel send, which stops Kafka consumption. Capped drains keep the resulting batches bounded, so the backlog releases at the writer's pace. This naturally limits memory usage and prevents unbounded buffering.
## Kafka consumer configuration
@@ -100,6 +105,8 @@ When the writer is slow (PG latency, connection pool exhaustion), the bounded ch
| `personhog_writer_unapplyable_rows_total{kind}` | counter | Rows PG refused non-transiently (invariant violation, halts the flush) |
| `personhog_writer_chunk_fallback_rows_total` | counter | Rows from data-failed chunks sent to per-row fallback |
| `personhog_writer_chunk_retry_rows_total` | counter | Rows from transient-failed chunks retried as a batch |
+| `personhog_writer_chunk_saturated_rows_total` | counter | Rows from chunks that hit local pool saturation |
+| `personhog_writer_saturation_retries_total` | counter | Retry rounds caused only by pool saturation (never escalate) |
| `personhog_writer_chunk_fatal_total` | counter | Chunk tasks that panicked or were cancelled |
| `personhog_writer_row_fallback_duration_seconds` | histogram | Duration of the per-row fallback for a batch |
| `personhog_writer_row_fallback_in_flight` | gauge | Concurrent per-row upserts in flight during fallback |
@@ -131,9 +138,10 @@ Consumer lag per partition is monitored externally via KMinion (`kminion_kafka_c
| `PG_MAX_CONNECTIONS` | `20` | Connection pool size |
| `PG_TARGET_TABLE` | `personhog_person_tmp` | Target table (`posthog_person` for production cutover) |
| `FLUSH_INTERVAL_MS` | `30000` | Timer-based flush interval (longer = better dedup, higher latency) |
-| `FLUSH_BUFFER_SIZE` | `10000` | Size-based flush trigger |
+| `FLUSH_BUFFER_SIZE` | `10000` | Size-based flush trigger and per-flush drain cap |
| `BUFFER_CAPACITY` | `100000` | Hard cap for backpressure |
| `UPSERT_BATCH_SIZE` | `5000` | Max rows per INSERT statement (chunks execute in parallel) |
+| `UPSERT_CONCURRENCY` | `8` | Pod-wide cap on concurrent upsert statements, shared across lanes |
| `ROW_FALLBACK_CONCURRENCY` | `16` | Max concurrent per-row upserts during per-row fallback |
| `FLUSH_CHANNEL_CAPACITY` | `8` | Channel capacity between tasks |
| `METRICS_PORT` | `9103` | Prometheus metrics HTTP port |
diff --git a/rust/personhog-writer/src/buffer.rs b/rust/personhog-writer/src/buffer.rs
index be59c42ad7e6..0d879b9f910d 100644
--- a/rust/personhog-writer/src/buffer.rs
+++ b/rust/personhog-writer/src/buffer.rs
@@ -4,12 +4,33 @@ use std::collections::HashMap;
use metrics::counter;
use personhog_proto::personhog::types::v1::Person;
+/// A buffered person plus the partition its latest message arrived on, so
+/// drains can select whole partitions.
+struct Buffered {
+ person: Person,
+ partition: i32,
+}
+
+/// A partition-complete slice of the buffer, ready to flush. Offsets cover
+/// exactly the partitions whose entries were drained, so committing them
+/// can never skip past a person still sitting in the buffer.
+pub struct DrainedBatch {
+ pub persons: Vec<Person>,
+ /// Max offset seen per drained partition.
+ pub offsets: HashMap<i32, i64>,
+ /// Oldest message timestamp across the drained partitions (millis
+ /// since epoch), for end-to-end latency measurement.
+ pub oldest_message_ts_ms: Option<i64>,
+}
+
/// In-memory dedup buffer keyed by (team_id, person_id).
/// Later messages for the same person overwrite earlier ones.
pub struct PersonBuffer {
- entries: HashMap<(i64, i64), Person>,
+ entries: HashMap<(i64, i64), Buffered>,
/// Max offset seen per partition for offset commits.
offsets: HashMap<i32, i64>,
+ /// Oldest message timestamp per partition with buffered entries.
+ oldest_ts_ms: HashMap<i32, i64>,
capacity: usize,
}
@@ -18,6 +39,7 @@ impl PersonBuffer {
Self {
entries: HashMap::new(),
offsets: HashMap::new(),
+ oldest_ts_ms: HashMap::new(),
capacity,
}
}
@@ -25,7 +47,7 @@ impl PersonBuffer {
/// Insert a person into the buffer. Later messages for the same person
/// overwrite earlier ones -- Kafka partition ordering guarantees the
/// latest version always arrives last.
- pub fn insert(&mut self, person: Person, partition: i32, offset: i64) {
+ pub fn insert(&mut self, person: Person, partition: i32, offset: i64, ts_ms: Option<i64>) {
self.offsets
.entry(partition)
.and_modify(|o| {
@@ -35,14 +57,25 @@ impl PersonBuffer {
})
.or_insert(offset);
+ if let Some(ts_ms) = ts_ms {
+ self.oldest_ts_ms
+ .entry(partition)
+ .and_modify(|t| {
+ if ts_ms < *t {
+ *t = ts_ms;
+ }
+ })
+ .or_insert(ts_ms);
+ }
+
let key = (person.team_id, person.id);
match self.entries.entry(key) {
Entry::Occupied(mut e) => {
- e.insert(person);
+ e.insert(Buffered { person, partition });
counter!("personhog_writer_messages_deduped_total").increment(1);
}
Entry::Vacant(e) => {
- e.insert(person);
+ e.insert(Buffered { person, partition });
}
}
}
@@ -64,11 +97,55 @@ impl PersonBuffer {
self.offsets.get(&partition).copied()
}
- /// Drain all entries and offsets for flushing.
- pub fn drain(&mut self) -> (Vec<Person>, HashMap<i32, i64>) {
- let persons: Vec<Person> = self.entries.drain().map(|(_, p)| p).collect();
- let offsets = std::mem::take(&mut self.offsets);
- (persons, offsets)
+ /// Drain whole partitions — oldest buffered message first — until at
+ /// least `max_rows` persons are collected or the buffer is empty. A
+ /// partition is never split: its max offset is only safe to commit once
+ /// every buffered person from it is flushed, so a single partition can
+ /// exceed `max_rows` on its own. Returns `None` on an empty buffer.
+ pub fn drain_up_to(&mut self, max_rows: usize) -> Option<DrainedBatch> {
+ if self.entries.is_empty() {
+ return None;
+ }
+
+ let mut keys_by_partition: HashMap<i32, Vec<(i64, i64)>> = HashMap::new();
+ for (key, buffered) in &self.entries {
+ keys_by_partition
+ .entry(buffered.partition)
+ .or_default()
+ .push(*key);
+ }
+
+ // Oldest-first keeps the e2e latency tail short; the partition id
+ // tiebreak makes drain order deterministic.
+ let mut partitions: Vec<i32> = keys_by_partition.keys().copied().collect();
+ partitions
+ .sort_unstable_by_key(|p| (self.oldest_ts_ms.get(p).copied().unwrap_or(i64::MAX), *p));
+
+ let mut persons = Vec::new();
+ let mut offsets = HashMap::new();
+ let mut oldest_message_ts_ms: Option<i64> = None;
+
+ for partition in partitions {
+ if persons.len() >= max_rows {
+ break;
+ }
+ for key in &keys_by_partition[&partition] {
+ let buffered = self.entries.remove(key).expect("key collected above");
+ persons.push(buffered.person);
+ }
+ if let Some(offset) = self.offsets.remove(&partition) {
+ offsets.insert(partition, offset);
+ }
+ if let Some(ts) = self.oldest_ts_ms.remove(&partition) {
+ oldest_message_ts_ms = Some(oldest_message_ts_ms.map_or(ts, |cur| cur.min(ts)));
+ }
+ }
+
+ Some(DrainedBatch {
+ persons,
+ offsets,
+ oldest_message_ts_ms,
+ })
}
}
@@ -96,28 +173,29 @@ mod tests {
#[test]
fn insert_and_drain() {
let mut buf = PersonBuffer::new(100);
- buf.insert(make_person(1, 42, 1), 0, 0);
- buf.insert(make_person(1, 43, 1), 0, 1);
+ buf.insert(make_person(1, 42, 1), 0, 0, None);
+ buf.insert(make_person(1, 43, 1), 0, 1, None);
assert_eq!(buf.len(), 2);
- let (persons, offsets) = buf.drain();
- assert_eq!(persons.len(), 2);
- assert_eq!(offsets[&0], 1);
+ let batch = buf.drain_up_to(usize::MAX).unwrap();
+ assert_eq!(batch.persons.len(), 2);
+ assert_eq!(batch.offsets[&0], 1);
assert_eq!(buf.len(), 0);
+ assert!(buf.drain_up_to(usize::MAX).is_none());
}
#[test]
fn dedup_keeps_latest_message() {
let mut buf = PersonBuffer::new(100);
- buf.insert(make_person(1, 42, 1), 0, 0);
- buf.insert(make_person(1, 42, 2), 0, 1);
- buf.insert(make_person(1, 42, 3), 0, 2);
+ buf.insert(make_person(1, 42, 1), 0, 0, None);
+ buf.insert(make_person(1, 42, 2), 0, 1, None);
+ buf.insert(make_person(1, 42, 3), 0, 2, None);
assert_eq!(buf.len(), 1);
- let (persons, _) = buf.drain();
- assert_eq!(persons[0].version, 3);
+ let batch = buf.drain_up_to(usize::MAX).unwrap();
+ assert_eq!(batch.persons[0].version, 3);
}
#[test]
@@ -125,26 +203,79 @@ mod tests {
let mut buf = PersonBuffer::new(2);
assert!(!buf.is_full());
- buf.insert(make_person(1, 1, 1), 0, 0);
+ buf.insert(make_person(1, 1, 1), 0, 0, None);
assert!(!buf.is_full());
- buf.insert(make_person(1, 2, 1), 0, 1);
+ buf.insert(make_person(1, 2, 1), 0, 1, None);
assert!(buf.is_full());
}
#[test]
fn tracks_max_offset_per_partition() {
let mut buf = PersonBuffer::new(100);
- buf.insert(make_person(1, 1, 1), 0, 10);
- buf.insert(make_person(1, 2, 1), 0, 5);
- buf.insert(make_person(1, 3, 1), 1, 3);
+ buf.insert(make_person(1, 1, 1), 0, 10, None);
+ buf.insert(make_person(1, 2, 1), 0, 5, None);
+ buf.insert(make_person(1, 3, 1), 1, 3, None);
assert_eq!(buf.partition_offset(0), Some(10));
assert_eq!(buf.partition_offset(1), Some(3));
assert_eq!(buf.partition_offset(2), None);
- let (_, offsets) = buf.drain();
- assert_eq!(offsets[&0], 10);
- assert_eq!(offsets[&1], 3);
+ let batch = buf.drain_up_to(usize::MAX).unwrap();
+ assert_eq!(batch.offsets[&0], 10);
+ assert_eq!(batch.offsets[&1], 3);
+ }
+
+ #[test]
+ fn capped_drain_takes_whole_partitions_and_only_their_offsets() {
+ let mut buf = PersonBuffer::new(100);
+ // Partition 0 is older (ts 100), partition 1 newer (ts 200).
+ buf.insert(make_person(1, 1, 1), 0, 10, Some(100));
+ buf.insert(make_person(1, 2, 1), 0, 11, Some(150));
+ buf.insert(make_person(1, 3, 1), 1, 20, Some(200));
+ buf.insert(make_person(1, 4, 1), 1, 21, Some(250));
+
+ let batch = buf.drain_up_to(2).unwrap();
+ assert_eq!(batch.persons.len(), 2);
+ assert!(batch.persons.iter().all(|p| p.id == 1 || p.id == 2));
+ assert_eq!(batch.offsets.len(), 1);
+ assert_eq!(batch.offsets[&0], 11);
+ assert_eq!(batch.oldest_message_ts_ms, Some(100));
+
+ // Partition 1 stays fully buffered, offset uncommitted.
+ assert_eq!(buf.len(), 2);
+ assert_eq!(buf.partition_offset(1), Some(21));
+ assert_eq!(buf.partition_offset(0), None);
+
+ let rest = buf.drain_up_to(2).unwrap();
+ assert_eq!(rest.persons.len(), 2);
+ assert_eq!(rest.offsets[&1], 21);
+ assert_eq!(rest.oldest_message_ts_ms, Some(200));
+ assert!(buf.is_empty());
+ }
+
+ #[test]
+ fn capped_drain_never_splits_a_partition() {
+ let mut buf = PersonBuffer::new(100);
+ for id in 1..=5 {
+ buf.insert(make_person(1, id, 1), 0, id, None);
+ }
+
+ let batch = buf.drain_up_to(2).unwrap();
+ assert_eq!(batch.persons.len(), 5);
+ assert_eq!(batch.offsets[&0], 5);
+ assert!(buf.is_empty());
+ }
+
+ #[test]
+ fn capped_drain_prefers_oldest_partition() {
+ let mut buf = PersonBuffer::new(100);
+ buf.insert(make_person(1, 1, 1), 3, 0, Some(500));
+ buf.insert(make_person(1, 2, 1), 7, 0, Some(100));
+
+ let batch = buf.drain_up_to(1).unwrap();
+ assert_eq!(batch.persons[0].id, 2);
+ assert_eq!(batch.offsets.len(), 1);
+ assert_eq!(batch.offsets[&7], 0);
}
}
diff --git a/rust/personhog-writer/src/config.rs b/rust/personhog-writer/src/config.rs
index 666d8eff8c2b..773e802e4360 100644
--- a/rust/personhog-writer/src/config.rs
+++ b/rust/personhog-writer/src/config.rs
@@ -35,10 +35,12 @@ pub struct Config {
#[envconfig(default = "30000")]
pub flush_interval_ms: u64,
- /// Flush when a lane's buffer reaches this many entries. Sized to produce
- /// multi-chunk batches that exercise the parallel chunk path. Clamped to
- /// half the per-lane capacity (`buffer_capacity / writer_lanes`) so the
- /// nonblocking size flush always fires before a lane's hard cap.
+ /// Flush when a lane's buffer reaches this many entries, and cap how
+ /// many rows a single flush drains: a backlogged lane empties as a
+ /// sequence of batches of roughly this size (whole partitions only)
+ /// instead of one giant batch. Clamped to half the per-lane capacity
+ /// (`buffer_capacity / writer_lanes`) so the nonblocking size flush
+ /// always fires before a lane's hard cap.
#[envconfig(default = "10000")]
pub flush_buffer_size: usize,
@@ -53,6 +55,13 @@ pub struct Config {
#[envconfig(default = "5000")]
pub upsert_batch_size: usize,
+ /// Max concurrent upsert statements against PG, shared across all
+ /// writer lanes and both the chunk and per-row paths. Keep below
+ /// `pg_max_connections` so a burst of chunks queues at the semaphore
+ /// (a cheap, unbounded wait) instead of timing out pool acquires.
+ #[envconfig(default = "8")]
+ pub upsert_concurrency: usize,
+
/// Max concurrent per-row upserts when a batch falls back to the
/// per-row path. Size against `pg_max_connections`; pgbouncer handles
/// backpressure to PG itself.
diff --git a/rust/personhog-writer/src/consumer.rs b/rust/personhog-writer/src/consumer.rs
index 995e4243fb96..c89f68e1bbf9 100644
--- a/rust/personhog-writer/src/consumer.rs
+++ b/rust/personhog-writer/src/consumer.rs
@@ -30,8 +30,6 @@ pub struct FlushBatch {
struct Lane {
buffer: PersonBuffer,
flush_tx: mpsc::Sender<FlushBatch>,
- /// Oldest message timestamp currently buffered in this lane.
- oldest_message_ts_ms: Option<i64>,
}
/// Reads from Kafka, decodes Person protos, buffers with dedup per lane,
@@ -78,7 +76,6 @@ impl ConsumerTask {
.map(|flush_tx| Lane {
buffer: PersonBuffer::new(per_lane_capacity),
flush_tx,
- oldest_message_ts_ms: None,
})
.collect();
Self {
@@ -97,7 +94,9 @@ impl ConsumerTask {
info!(lanes = self.lanes.len(), "Consumer task starting");
loop {
- // Backpressure: flush a full lane immediately
+ // Backpressure: a full lane drains one capped batch before the
+ // loop re-checks, so even the hard-cap path releases its backlog
+ // as bounded batches rather than one giant flush.
if let Some(idx) = self.lanes.iter().position(|l| l.buffer.is_full()) {
counter!("personhog_writer_flushes_by_trigger_total", "trigger" => "backpressure")
.increment(1);
@@ -111,7 +110,7 @@ impl ConsumerTask {
_ = self.handle.shutdown_recv() => {
info!("Shutdown signal, flushing remaining buffers");
for idx in 0..self.lanes.len() {
- if !self.lanes[idx].buffer.is_empty() {
+ while !self.lanes[idx].buffer.is_empty() {
counter!("personhog_writer_flushes_by_trigger_total", "trigger" => "shutdown")
.increment(1);
self.send_flush(idx).await;
@@ -121,8 +120,12 @@ impl ConsumerTask {
}
_ = flush_timer.tick() => {
+ // Drain each lane fully, one capped batch at a time. The
+ // blocking send paces the drain at the writer's speed, so
+ // a backlogged lane empties as a sequence of bounded
+ // batches instead of one giant one.
for idx in 0..self.lanes.len() {
- if !self.lanes[idx].buffer.is_empty() {
+ while !self.lanes[idx].buffer.is_empty() {
counter!("personhog_writer_flushes_by_trigger_total", "trigger" => "timer")
.increment(1);
self.send_flush(idx).await;
@@ -144,20 +147,7 @@ impl ConsumerTask {
.increment(1);
let idx = (partition as usize) % self.lanes.len();
let lane = &mut self.lanes[idx];
-
- if let Some(ts_ms) = ts_ms {
- match lane.oldest_message_ts_ms {
- Some(existing) if ts_ms < existing => {
- lane.oldest_message_ts_ms = Some(ts_ms);
- }
- None => {
- lane.oldest_message_ts_ms = Some(ts_ms);
- }
- _ => {}
- }
- }
-
- lane.buffer.insert(person, partition, offset);
+ lane.buffer.insert(person, partition, offset, ts_ms);
// Size-triggered flushes never block the
// consume loop: if this lane's writer is
@@ -209,18 +199,15 @@ impl ConsumerTask {
info!("Consumer task stopped");
}
- /// Drain a lane's buffer into a batch. Offset and buffer-size gauges
- /// are recorded here, per flush — updating them per message is too
+ /// Drain up to `flush_buffer_size` rows (whole partitions only) from a
+ /// lane's buffer into a batch. Offset and buffer-size gauges are
+ /// recorded here, per flush — updating them per message is too
/// expensive for the consume loop (dynamic-label registry lookups).
fn take_batch(&mut self, idx: usize) -> Option<FlushBatch> {
let lane = &mut self.lanes[idx];
- let (persons, offsets) = lane.buffer.drain();
- let oldest_message_ts_ms = lane.oldest_message_ts_ms.take();
- if persons.is_empty() {
- return None;
- }
+ let batch = lane.buffer.drain_up_to(self.flush_buffer_size)?;
- for (partition, offset) in &offsets {
+ for (partition, offset) in &batch.offsets {
gauge!(
"personhog_writer_partition_offset",
"partition" => partition.to_string()
@@ -231,15 +218,16 @@ impl ConsumerTask {
gauge!("personhog_writer_buffer_size").set(total as f64);
Some(FlushBatch {
- persons,
- offsets,
- oldest_message_ts_ms,
+ persons: batch.persons,
+ offsets: batch.offsets,
+ oldest_message_ts_ms: batch.oldest_message_ts_ms,
})
}
- /// Drain a lane's buffer and send to its writer task, waiting until the
- /// writer accepts it. Used on the timer, shutdown, and hard-capacity
- /// paths, where blocking the consume loop is intended backpressure.
+ /// Drain one capped batch from a lane and send it to the writer task,
+ /// waiting until the writer accepts it. Used on the timer, shutdown, and
+ /// hard-capacity paths, where blocking the consume loop is intended
+ /// backpressure.
async fn send_flush(&mut self, idx: usize) {
let Some(batch) = self.take_batch(idx) else {
return;
diff --git a/rust/personhog-writer/src/error.rs b/rust/personhog-writer/src/error.rs
index 66498c64425f..bcf34147c514 100644
--- a/rust/personhog-writer/src/error.rs
+++ b/rust/personhog-writer/src/error.rs
@@ -9,6 +9,11 @@
pub enum WriteErrorKind {
/// Retrying the same operation may succeed.
Transient,
+ /// Local connection acquisition timed out: the writer's own in-flight
+ /// statements exceeded pool capacity. Retryable, but self-inflicted —
+ /// it says nothing about the database's health, so it must never count
+ /// toward the writer's failure escalation.
+ Saturation,
/// Properties exceed the DB size constraint. Trimming may help.
PropertiesSizeViolation,
/// Unrecoverable data error. Skip this record.
diff --git a/rust/personhog-writer/src/main.rs b/rust/personhog-writer/src/main.rs
index 1335a80ecbb5..ff7aceec0b47 100644
--- a/rust/personhog-writer/src/main.rs
+++ b/rust/personhog-writer/src/main.rs
@@ -47,6 +47,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing::info!("Flush buffer size: {}", config.flush_buffer_size);
tracing::info!("Buffer capacity: {}", config.buffer_capacity);
tracing::info!("Writer lanes: {}", config.writer_lanes);
+ tracing::info!("Upsert concurrency: {}", config.upsert_concurrency);
tracing::info!("Metrics port: {}", config.metrics_port);
let mut manager = Manager::builder("personhog-writer")
@@ -155,6 +156,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)?);
tracing::info!("Subscribed to Kafka topic: {}", config.kafka_topic);
+ // One statement-concurrency budget for the whole pod: every lane's
+ // chunk and per-row statements draw from it, so lanes can overlap
+ // writes without collectively oversubscribing the pool.
+ let upsert_concurrency = config.upsert_concurrency.max(1);
+ if upsert_concurrency > config.pg_max_connections as usize {
+ tracing::warn!(
+ upsert_concurrency,
+ pg_max_connections = config.pg_max_connections,
+ "UPSERT_CONCURRENCY exceeds PG_MAX_CONNECTIONS; excess statements \
+ will queue on pool acquire instead of the semaphore"
+ );
+ }
+ let upsert_permits = Arc::new(tokio::sync::Semaphore::new(upsert_concurrency));
+
// Writer lanes: each lane gets its own channel, store, and task, and
// commits offsets only for the partitions routed to it.
let mut lane_txs = Vec::with_capacity(lanes);
@@ -166,6 +181,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
chunk_size: config.upsert_batch_size,
row_fallback_concurrency: config.row_fallback_concurrency,
},
+ Arc::clone(&upsert_permits),
);
let writer_task =
WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);
diff --git a/rust/personhog-writer/src/pg.rs b/rust/personhog-writer/src/pg.rs
index 1c9f74d26f60..664c08fcfb9f 100644
--- a/rust/personhog-writer/src/pg.rs
+++ b/rust/personhog-writer/src/pg.rs
@@ -219,10 +219,13 @@ async fn run_upsert(
fn classify_error(e: &sqlx::Error) -> WriteErrorKind {
match e {
- sqlx::Error::Io(_)
- | sqlx::Error::PoolTimedOut
- | sqlx::Error::PoolClosed
- | sqlx::Error::WorkerCrashed => WriteErrorKind::Transient,
+ // Waiting on our own pool is backpressure, not database failure —
+ // classified apart so the writer retries without escalating.
+ sqlx::Error::PoolTimedOut => WriteErrorKind::Saturation,
+
+ sqlx::Error::Io(_) | sqlx::Error::PoolClosed | sqlx::Error::WorkerCrashed => {
+ WriteErrorKind::Transient
+ }
sqlx::Error::Database(db_err) => {
if let Some(code) = db_err.code() {
@@ -347,10 +350,10 @@ mod tests {
use super::*;
#[test]
- fn classify_pool_timeout_as_transient() {
+ fn classify_pool_timeout_as_saturation() {
assert!(matches!(
classify_error(&sqlx::Error::PoolTimedOut),
- WriteErrorKind::Transient
+ WriteErrorKind::Saturation
));
}
diff --git a/rust/personhog-writer/src/store.rs b/rust/personhog-writer/src/store.rs
index 4139302a218b..d6665d389394 100644
--- a/rust/personhog-writer/src/store.rs
+++ b/rust/personhog-writer/src/store.rs
@@ -18,6 +18,7 @@ use async_trait::async_trait;
use futures::stream::{self, StreamExt};
use metrics::{counter, gauge, histogram};
use personhog_proto::personhog::types::v1::Person;
+use tokio::sync::Semaphore;
use tokio::task::{JoinError, JoinSet};
use tracing::error;
@@ -37,13 +38,15 @@ pub trait PersonDb: Send + Sync {
/// Outcome of a batch upsert. Reports which chunks (if any) need retry,
/// grouped by failure class so the caller picks the right strategy:
-/// transient chunks are retried as batches after backoff, data-failed
+/// transient chunks are retried as batches after backoff, saturated chunks
+/// are retried without counting toward failure escalation, data-failed
/// chunks fall through to per-row inserts to isolate bad records.
#[derive(Debug)]
pub enum BatchOutcome {
Success,
Partial {
transient: Vec<Person>,
+ saturated: Vec<Person>,
data_failed: Vec<Person>,
},
/// A chunk task panicked. The persons in that chunk are unrecoverable;
@@ -70,6 +73,9 @@ pub struct RowViolation {
pub struct RowFallbackOutcome {
/// Rows that failed transiently; the caller retries them with backoff.
pub transient: Vec<Person>,
+ /// Rows that hit local pool saturation; the caller retries them
+ /// without counting the round toward failure escalation.
+ pub saturated: Vec<Person>,
/// Rows PG cannot apply — invariant violations that must halt the
/// flush without committing.
pub violations: Vec<RowViolation>,
@@ -91,18 +97,26 @@ pub struct StoreConfig {
/// Production person write store. Splits batches into chunks, runs them in
/// parallel against a `PersonDb`, partitions outcomes by failure class, and
/// handles per-row fallback.
+///
+/// Every statement — chunk or row — first takes a permit from `permits`,
+/// which main shares across all lanes' stores. That makes the permit count
+/// the pod-wide ceiling on in-flight statements: a backlogged flush queues
+/// at the semaphore (an unbounded, cheap wait) instead of oversubscribing
+/// the pool and converting its own burst into acquire timeouts.
pub struct PersonWriteStore<D: PersonDb> {
db: Arc<D>,
chunk_size: usize,
row_fallback_concurrency: usize,
+ permits: Arc<Semaphore>,
}
impl<D: PersonDb + 'static> PersonWriteStore<D> {
- pub fn new(db: D, cfg: StoreConfig) -> Self {
+ pub fn new(db: D, cfg: StoreConfig, permits: Arc<Semaphore>) -> Self {
Self {
db: Arc::new(db),
chunk_size: cfg.chunk_size.max(1),
row_fallback_concurrency: cfg.row_fallback_concurrency.max(1),
+ permits,
}
}
@@ -119,6 +133,7 @@ impl<D: PersonDb + 'static> PersonWriteStore<D> {
// here since chunk_size is tuned to match the aggregator flush size.
let outcome = if chunks.len() == 1 {
let chunk = chunks.into_iter().next().unwrap();
+ let _permit = self.acquire_permit().await;
match self.db.execute_chunk(&chunk).await {
Ok(()) => BatchOutcome::Success,
Err(e) => partial_from_failed_chunk(chunk, e.kind),
@@ -134,13 +149,22 @@ impl<D: PersonDb + 'static> PersonWriteStore<D> {
}
pub async fn upsert_row(&self, person: &Person) -> Result<(), WriteError> {
+ let _permit = self.acquire_permit().await;
self.db.execute_row(person).await
}
+ async fn acquire_permit(&self) -> tokio::sync::SemaphorePermit<'_> {
+ self.permits
+ .acquire()
+ .await
+ .expect("upsert permit semaphore is never closed")
+ }
+
/// Run per-row upserts for a batch of persons with bounded concurrency,
/// isolating which rows a data-failed chunk actually cannot apply.
- /// pgbouncer handles PG-side backpressure; our bound is to keep sqlx
- /// pool turnover reasonable and cap memory of in-flight futures.
+ /// The effective bound is min(`row_fallback_concurrency`, free permits):
+ /// each row also takes an upsert permit, so fallback traffic counts
+ /// against the same pod-wide statement ceiling as chunks.
///
/// Transient failures are returned for retry. Non-transient failures
/// are invariant violations (the leader admitted an unapplyable
@@ -168,6 +192,9 @@ impl<D: PersonDb + 'static> PersonWriteStore<D> {
Err(e) if matches!(e.kind, WriteErrorKind::Transient) => {
outcome.transient.push(person);
}
+ Err(e) if matches!(e.kind, WriteErrorKind::Saturation) => {
+ outcome.saturated.push(person);
+ }
Err(e) => {
counter!(
"personhog_writer_unapplyable_rows_total",
@@ -197,13 +224,19 @@ impl<D: PersonDb + 'static> PersonWriteStore<D> {
let mut set: JoinSet<(Vec<Person>, Result<(), WriteError>)> = JoinSet::new();
for chunk in chunks {
let db = Arc::clone(&self.db);
+ let permits = Arc::clone(&self.permits);
set.spawn(async move {
+ let _permit = permits
+ .acquire_owned()
+ .await
+ .expect("upsert permit semaphore is never closed");
let res = db.execute_chunk(&chunk).await;
(chunk, res)
});
}
let mut transient = Vec::new();
+ let mut saturated = Vec::new();
let mut data_failed = Vec::new();
while let Some(joined) = set.join_next().await {
@@ -211,6 +244,7 @@ impl<D: PersonDb + 'static> PersonWriteStore<D> {
Ok((_chunk, Ok(()))) => {}
Ok((chunk, Err(e))) => match e.kind {
WriteErrorKind::Transient => transient.extend(chunk),
+ WriteErrorKind::Saturation => saturated.extend(chunk),
WriteErrorKind::Data | WriteErrorKind::PropertiesSizeViolation => {
data_failed.extend(chunk);
}
@@ -228,16 +262,21 @@ impl<D: PersonDb + 'static> PersonWriteStore<D> {
if !transient.is_empty() {
counter!("personhog_writer_chunk_retry_rows_total").increment(transient.len() as u64);
}
+ if !saturated.is_empty() {
+ counter!("personhog_writer_chunk_saturated_rows_total")
+ .increment(saturated.len() as u64);
+ }
if !data_failed.is_empty() {
counter!("personhog_writer_chunk_fallback_rows_total")
.increment(data_failed.len() as u64);
}
- if transient.is_empty() && data_failed.is_empty() {
+ if transient.is_empty() && saturated.is_empty() && data_failed.is_empty() {
BatchOutcome::Success
} else {
BatchOutcome::Partial {
transient,
+ saturated,
data_failed,
}
}
@@ -261,6 +300,15 @@ fn partial_from_failed_chunk(chunk: Vec<Person>, kind: WriteErrorKind) -> BatchO
counter!("personhog_writer_chunk_retry_rows_total").increment(chunk.len() as u64);
BatchOutcome::Partial {
transient: chunk,
+ saturated: Vec::new(),
+ data_failed: Vec::new(),
+ }
+ }
+ WriteErrorKind::Saturation => {
+ counter!("personhog_writer_chunk_saturated_rows_total").increment(chunk.len() as u64);
+ BatchOutcome::Partial {
+ transient: Vec::new(),
+ saturated: chunk,
data_failed: Vec::new(),
}
}
@@ -268,6 +316,7 @@ fn partial_from_failed_chunk(chunk: Vec<Person>, kind: WriteErrorKind) -> BatchO
counter!("personhog_writer_chunk_fallback_rows_total").increment(chunk.len() as u64);
BatchOutcome::Partial {
transient: Vec::new(),
+ saturated: Vec::new(),
data_failed: chunk,
}
}
@@ -280,6 +329,7 @@ fn kind_label(kind: WriteErrorKind) -> &'static str {
WriteErrorKind::PropertiesSizeViolation => "size",
WriteErrorKind::Data => "data",
WriteErrorKind::Transient => "transient",
+ WriteErrorKind::Saturation => "saturation",
}
}
@@ -439,6 +489,11 @@ mod tests {
}
}
+ /// Store with a permit budget large enough to never constrain a test.
+ fn test_store(db: StubDb, cfg: StoreConfig) -> PersonWriteStore<StubDb> {
+ PersonWriteStore::new(db, cfg, Arc::new(Semaphore::new(64)))
+ }
+
// ── Split helper ────────────────────────────────────────────
#[test]
@@ -472,7 +527,7 @@ mod tests {
#[tokio::test]
async fn upsert_batch_empty_returns_success() {
- let store = PersonWriteStore::new(StubDb::new(), StoreConfig::test_default());
+ let store = test_store(StubDb::new(), StoreConfig::test_default());
assert!(matches!(
store.upsert_batch(Vec::new()).await,
BatchOutcome::Success
@@ -481,7 +536,7 @@ mod tests {
#[tokio::test]
async fn upsert_batch_single_chunk_success() {
- let store = PersonWriteStore::new(StubDb::new(), StoreConfig::test_default());
+ let store = test_store(StubDb::new(), StoreConfig::test_default());
let persons: Vec<Person> = (0..5).map(p).collect();
assert!(matches!(
store.upsert_batch(persons).await,
@@ -492,7 +547,7 @@ mod tests {
#[tokio::test]
async fn upsert_batch_parallel_all_succeed() {
// 6 persons, chunk_size 2 → 3 parallel chunks
- let store = PersonWriteStore::new(
+ let store = test_store(
StubDb::new(),
StoreConfig {
chunk_size: 2,
@@ -511,14 +566,16 @@ mod tests {
#[tokio::test]
async fn upsert_batch_transient_routes_to_transient_bucket() {
let db = StubDb::new().with_chunk_default(ChunkResponse::Err(WriteErrorKind::Transient));
- let store = PersonWriteStore::new(db, StoreConfig::test_default());
+ let store = test_store(db, StoreConfig::test_default());
let persons: Vec<Person> = (0..3).map(p).collect();
match store.upsert_batch(persons).await {
BatchOutcome::Partial {
transient,
+ saturated,
data_failed,
} => {
assert_eq!(transient.len(), 3);
+ assert!(saturated.is_empty());
assert!(data_failed.is_empty());
}
other => panic!("expected Partial, got {other:?}"),
@@ -528,14 +585,16 @@ mod tests {
#[tokio::test]
async fn upsert_batch_data_error_routes_to_data_bucket() {
let db = StubDb::new().with_chunk_default(ChunkResponse::Err(WriteErrorKind::Data));
- let store = PersonWriteStore::new(db, StoreConfig::test_default());
+ let store = test_store(db, StoreConfig::test_default());
let persons: Vec<Person> = (0..3).map(p).collect();
match store.upsert_batch(persons).await {
BatchOutcome::Partial {
transient,
+ saturated,
data_failed,
} => {
assert!(transient.is_empty());
+ assert!(saturated.is_empty());
assert_eq!(data_failed.len(), 3);
}
other => panic!("expected Partial, got {other:?}"),
@@ -546,20 +605,41 @@ mod tests {
async fn upsert_batch_size_violation_routes_to_data_bucket() {
let db = StubDb::new()
.with_chunk_default(ChunkResponse::Err(WriteErrorKind::PropertiesSizeViolation));
- let store = PersonWriteStore::new(db, StoreConfig::test_default());
+ let store = test_store(db, StoreConfig::test_default());
let persons: Vec<Person> = (0..3).map(p).collect();
match store.upsert_batch(persons).await {
BatchOutcome::Partial {
transient,
+ saturated,
data_failed,
} => {
assert!(transient.is_empty());
+ assert!(saturated.is_empty());
assert_eq!(data_failed.len(), 3);
}
other => panic!("expected Partial, got {other:?}"),
}
}
+ #[tokio::test]
+ async fn upsert_batch_saturation_routes_to_saturated_bucket() {
+ let db = StubDb::new().with_chunk_default(ChunkResponse::Err(WriteErrorKind::Saturation));
+ let store = test_store(db, StoreConfig::test_default());
+ let persons: Vec<Person> = (0..3).map(p).collect();
+ match store.upsert_batch(persons).await {
+ BatchOutcome::Partial {
+ transient,
+ saturated,
+ data_failed,
+ } => {
+ assert!(transient.is_empty());
+ assert_eq!(saturated.len(), 3);
+ assert!(data_failed.is_empty());
+ }
+ other => panic!("expected Partial, got {other:?}"),
+ }
+ }
+
// ── Parallel mixed outcomes ────────────────────────────────
#[tokio::test]
@@ -570,7 +650,7 @@ mod tests {
.script_chunk_for_id(0, ChunkResponse::Ok)
.script_chunk_for_id(2, ChunkResponse::Err(WriteErrorKind::Transient))
.script_chunk_for_id(4, ChunkResponse::Err(WriteErrorKind::Data));
- let store = PersonWriteStore::new(
+ let store = test_store(
db,
StoreConfig {
chunk_size: 2,
@@ -582,9 +662,11 @@ mod tests {
match store.upsert_batch(persons).await {
BatchOutcome::Partial {
transient,
+ saturated,
data_failed,
} => {
assert_eq!(transient.len(), 2);
+ assert!(saturated.is_empty());
assert_eq!(transient[0].id, 2);
assert_eq!(transient[1].id, 3);
assert_eq!(data_failed.len(), 2);
@@ -598,7 +680,7 @@ mod tests {
#[tokio::test]
async fn upsert_batch_parallel_all_transient_returns_all_rows() {
let db = StubDb::new().with_chunk_default(ChunkResponse::Err(WriteErrorKind::Transient));
- let store = PersonWriteStore::new(
+ let store = test_store(
db,
StoreConfig {
chunk_size: 2,
@@ -609,9 +691,11 @@ mod tests {
match store.upsert_batch(persons).await {
BatchOutcome::Partial {
transient,
+ saturated,
data_failed,
} => {
assert_eq!(transient.len(), 6);
+ assert!(saturated.is_empty());
assert!(data_failed.is_empty());
}
other => panic!("expected Partial, got {other:?}"),
@@ -627,7 +711,7 @@ mod tests {
.script_chunk_for_id(0, ChunkResponse::Ok)
.script_chunk_for_id(2, ChunkResponse::Panic)
.script_chunk_for_id(4, ChunkResponse::Ok);
- let store = PersonWriteStore::new(
+ let store = test_store(
db,
StoreConfig {
chunk_size: 2,
@@ -651,7 +735,7 @@ mod tests {
#[tokio::test]
async fn upsert_rows_parallel_applies_every_row_cleanly() {
- let store = PersonWriteStore::new(StubDb::new(), StoreConfig::test_default());
+ let store = test_store(StubDb::new(), StoreConfig::test_default());
let persons: Vec<Person> = (0..10).map(p).collect();
let outcome = store.upsert_rows_parallel(persons).await;
assert!(outcome.transient.is_empty());
@@ -661,17 +745,76 @@ mod tests {
#[tokio::test]
async fn upsert_rows_parallel_returns_transient_failures_for_retry() {
let db = StubDb::new().with_row_default(ChunkResponse::Err(WriteErrorKind::Transient));
- let store = PersonWriteStore::new(db, StoreConfig::test_default());
+ let store = test_store(db, StoreConfig::test_default());
let persons: Vec<Person> = (0..5).map(p).collect();
let outcome = store.upsert_rows_parallel(persons).await;
assert_eq!(outcome.transient.len(), 5);
assert!(outcome.violations.is_empty());
}
+ #[tokio::test]
+ async fn upsert_rows_parallel_returns_saturated_rows_for_retry() {
+ let db = StubDb::new().with_row_default(ChunkResponse::Err(WriteErrorKind::Saturation));
+ let store = test_store(db, StoreConfig::test_default());
+ let persons: Vec<Person> = (0..5).map(p).collect();
+ let outcome = store.upsert_rows_parallel(persons).await;
+ assert!(outcome.transient.is_empty());
+ assert_eq!(outcome.saturated.len(), 5);
+ assert!(outcome.violations.is_empty());
+ }
+
+ // ── Permit bound ───────────────────────────────────────────
+
+ #[tokio::test(start_paused = true)]
+ async fn parallel_chunks_respect_the_shared_permit_bound() {
+ struct ConcurrencyDb {
+ current: Arc<AtomicUsize>,
+ max: Arc<AtomicUsize>,
+ }
+
+ #[async_trait]
+ impl PersonDb for ConcurrencyDb {
+ async fn execute_chunk(&self, _chunk: &[Person]) -> Result<(), WriteError> {
+ let now = self.current.fetch_add(1, Ordering::SeqCst) + 1;
+ self.max.fetch_max(now, Ordering::SeqCst);
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ self.current.fetch_sub(1, Ordering::SeqCst);
+ Ok(())
+ }
+
+ async fn execute_row(&self, _person: &Person) -> Result<(), WriteError> {
+ Ok(())
+ }
+ }
+
+ let current = Arc::new(AtomicUsize::new(0));
+ let max = Arc::new(AtomicUsize::new(0));
+ let store = PersonWriteStore::new(
+ ConcurrencyDb {
+ current: Arc::clone(&current),
+ max: Arc::clone(&max),
+ },
+ StoreConfig {
+ chunk_size: 1,
+ row_fallback_concurrency: 4,
+ },
+ Arc::new(Semaphore::new(2)),
+ );
+
+ // 8 persons at chunk_size 1 spawn 8 chunk tasks at once; the permit
+ // budget of 2 must be the only thing bounding them.
+ let persons: Vec<Person> = (0..8).map(p).collect();
+ assert!(matches!(
+ store.upsert_batch(persons).await,
+ BatchOutcome::Success
+ ));
+ assert_eq!(max.load(Ordering::SeqCst), 2);
+ }
+
#[tokio::test]
async fn upsert_rows_parallel_surfaces_unapplyable_rows_as_violations() {
let db = StubDb::new().with_row_default(ChunkResponse::Err(WriteErrorKind::Data));
- let store = PersonWriteStore::new(db, StoreConfig::test_default());
+ let store = test_store(db, StoreConfig::test_default());
let persons: Vec<Person> = (0..5).map(p).collect();
let outcome = store.upsert_rows_parallel(persons).await;
assert!(outcome.transient.is_empty());
diff --git a/rust/personhog-writer/src/writer.rs b/rust/personhog-writer/src/writer.rs
index 1dd8c1357951..764e2a104f09 100644
--- a/rust/personhog-writer/src/writer.rs
+++ b/rust/personhog-writer/src/writer.rs
@@ -13,11 +13,27 @@ use crate::consumer::FlushBatch;
use crate::kafka::PersonConsumer;
use crate::store::{BatchOutcome, PersonDb, PersonWriteStore};
+/// The offset-commit surface the writer needs from Kafka. Abstracted so the
+/// retry loop is testable without a broker.
+pub trait OffsetCommitter: Send + Sync {
+ fn commit_offsets(&self, offsets: &HashMap<i32, i64>)
+ -> Result<(), rdkafka::error::KafkaError>;
+}
+
+impl OffsetCommitter for PersonConsumer {
+ fn commit_offsets(
+ &self,
+ offsets: &HashMap<i32, i64>,
+ ) -> Result<(), rdkafka::error::KafkaError> {
+ PersonConsumer::commit_offsets(self, offsets)
+ }
+}
+
/// Receives batches from the consumer task, writes to the persistent
/// store, and commits Kafka offsets. Runs on its own tokio task so
/// writes don't block consumption.
-pub struct WriterTask<D: PersonDb + 'static> {
- consumer: Arc<PersonConsumer>,
+pub struct WriterTask<D: PersonDb + 'static, C: OffsetCommitter + 'static> {
+ consumer: Arc<C>,
store: PersonWriteStore<D>,
flush_rx: mpsc::Receiver<FlushBatch>,
handle: Handle,
@@ -28,9 +44,9 @@ const MAX_CONSECUTIVE_FAILURES: u32 = 3;
const BASE_BACKOFF: Duration = Duration::from_secs(1);
const MAX_BACKOFF: Duration = Duration::from_secs(5);
-impl<D: PersonDb + 'static> WriterTask<D> {
+impl<D: PersonDb + 'static, C: OffsetCommitter + 'static> WriterTask<D, C> {
pub fn new(
- consumer: Arc<PersonConsumer>,
+ consumer: Arc<C>,
store: PersonWriteStore<D>,
flush_rx: mpsc::Receiver<FlushBatch>,
handle: Handle,
@@ -94,6 +110,7 @@ impl<D: PersonDb + 'static> WriterTask<D> {
// and changelog), Kafka redelivers after restart, and the alarm
// stands until admission's gap is fixed.
let mut remaining: Vec<Person> = persons;
+ let mut saturation_rounds: u32 = 0;
loop {
let to_process = std::mem::take(&mut remaining);
@@ -105,9 +122,11 @@ impl<D: PersonDb + 'static> WriterTask<D> {
BatchOutcome::Partial {
transient,
+ saturated,
data_failed,
} => {
let mut retry = transient;
+ let mut saturated = saturated;
if !data_failed.is_empty() {
counter!("personhog_writer_batch_fallback_total").increment(1);
warn!(
@@ -128,31 +147,54 @@ impl<D: PersonDb + 'static> WriterTask<D> {
return ControlFlow::Break(());
}
retry.extend(fallback.transient);
+ saturated.extend(fallback.saturated);
}
- if retry.is_empty() {
+ if retry.is_empty() && saturated.is_empty() {
self.finish(total_rows, &offsets, oldest_message_ts_ms);
return ControlFlow::Continue(());
}
- // Transient failures remain — retry just those with backoff.
- self.consecutive_failures += 1;
- let backoff = backoff_duration(self.consecutive_failures);
- error!(
- consecutive_failures = self.consecutive_failures,
- transient_rows = retry.len(),
- backoff_ms = backoff.as_millis() as u64,
- "transient failures, retrying"
- );
-
- if self.consecutive_failures >= MAX_CONSECUTIVE_FAILURES {
- self.handle.signal_failure(format!(
- "store flush failed {MAX_CONSECUTIVE_FAILURES} consecutive times"
- ));
- return ControlFlow::Break(());
- }
+ let backoff = if retry.is_empty() {
+ // Only saturation: the pool was busy with our own
+ // statements. Waiting is backpressure, not a strike —
+ // counting it toward escalation would let a slow-PG
+ // burst crash-loop the pod, and each restart drops
+ // the buffers and redelivers, worsening the load
+ // that caused the saturation.
+ saturation_rounds += 1;
+ counter!("personhog_writer_saturation_retries_total").increment(1);
+ let backoff = backoff_duration(saturation_rounds);
+ warn!(
+ saturation_rounds,
+ saturated_rows = saturated.len(),
+ backoff_ms = backoff.as_millis() as u64,
+ "pool saturated, retrying without escalation"
+ );
+ backoff
+ } else {
+ // Real transient failures remain — retry with backoff
+ // and count toward escalation.
+ self.consecutive_failures += 1;
+ let backoff = backoff_duration(self.consecutive_failures);
+ error!(
+ consecutive_failures = self.consecutive_failures,
+ transient_rows = retry.len(),
+ backoff_ms = backoff.as_millis() as u64,
+ "transient failures, retrying"
+ );
+
+ if self.consecutive_failures >= MAX_CONSECUTIVE_FAILURES {
+ self.handle.signal_failure(format!(
+ "store flush failed {MAX_CONSECUTIVE_FAILURES} consecutive times"
+ ));
+ return ControlFlow::Break(());
+ }
+ backoff
+ };
tokio::time::sleep(backoff).await;
+ retry.extend(saturated);
remaining = retry;
}
@@ -206,6 +248,118 @@ fn backoff_duration(consecutive_failures: u32) -> Duration {
mod tests {
use super::*;
+ use std::collections::VecDeque;
+ use std::sync::Mutex;
+
+ use async_trait::async_trait;
+ use lifecycle::{ComponentOptions, Manager};
+
+ use crate::store::{StoreConfig, WriteError, WriteErrorKind};
+
+ /// DB whose chunk calls pop scripted outcomes (None = Ok); an empty
+ /// script succeeds.
+ struct ScriptedDb {
+ responses: Mutex<VecDeque<Option<WriteErrorKind>>>,
+ }
+
+ #[async_trait]
+ impl PersonDb for ScriptedDb {
+ async fn execute_chunk(&self, _chunk: &[Person]) -> Result<(), WriteError> {
+ match self.responses.lock().unwrap().pop_front().flatten() {
+ None => Ok(()),
+ Some(kind) => Err(WriteError {
+ message: format!("scripted: {kind:?}"),
+ kind,
+ }),
+ }
+ }
+
+ async fn execute_row(&self, _person: &Person) -> Result<(), WriteError> {
+ Ok(())
+ }
+ }
+
+ #[derive(Default)]
+ struct RecordingCommitter {
+ commits: Mutex<Vec<HashMap<i32, i64>>>,
+ }
+
+ impl OffsetCommitter for RecordingCommitter {
+ fn commit_offsets(
+ &self,
+ offsets: &HashMap<i32, i64>,
+ ) -> Result<(), rdkafka::error::KafkaError> {
+ self.commits.lock().unwrap().push(offsets.clone());
+ Ok(())
+ }
+ }
+
+ fn scripted_writer(
+ responses: Vec<Option<WriteErrorKind>>,
+ ) -> (
+ WriterTask<ScriptedDb, RecordingCommitter>,
+ Arc<RecordingCommitter>,
+ mpsc::Sender<FlushBatch>,
+ Manager,
+ ) {
+ let committer = Arc::new(RecordingCommitter::default());
+ let store = PersonWriteStore::new(
+ ScriptedDb {
+ responses: Mutex::new(responses.into()),
+ },
+ StoreConfig {
+ chunk_size: 100,
+ row_fallback_concurrency: 4,
+ },
+ Arc::new(tokio::sync::Semaphore::new(8)),
+ );
+ let (tx, rx) = mpsc::channel(1);
+ let mut manager = Manager::builder("test").build();
+ let handle = manager.register("writer", ComponentOptions::new());
+ let writer = WriterTask::new(Arc::clone(&committer), store, rx, handle);
+ (writer, committer, tx, manager)
+ }
+
+ fn batch(rows: i64) -> FlushBatch {
+ FlushBatch {
+ persons: (0..rows)
+ .map(|id| Person {
+ id,
+ team_id: 1,
+ version: 1,
+ ..Default::default()
+ })
+ .collect(),
+ offsets: HashMap::from([(0, rows - 1)]),
+ oldest_message_ts_ms: None,
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn saturation_rounds_beyond_the_strike_limit_do_not_halt() {
+ // More saturation rounds than MAX_CONSECUTIVE_FAILURES, then success:
+ // the batch must complete and commit instead of halting the writer.
+ let sat = Some(WriteErrorKind::Saturation);
+ let (mut writer, committer, _tx, _manager) = scripted_writer(vec![sat, sat, sat, sat]);
+
+ let flow = writer.process_batch(batch(3)).await;
+
+ assert!(matches!(flow, ControlFlow::Continue(())));
+ assert_eq!(committer.commits.lock().unwrap().len(), 1);
+ assert_eq!(writer.consecutive_failures, 0);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn transient_rounds_still_halt_at_the_strike_limit() {
+ let err = Some(WriteErrorKind::Transient);
+ let (mut writer, committer, _tx, _manager) = scripted_writer(vec![err, err, err]);
+
+ let flow = writer.process_batch(batch(3)).await;
+
+ assert!(matches!(flow, ControlFlow::Break(())));
+ assert!(committer.commits.lock().unwrap().is_empty());
+ }
+
#[test]
fn backoff_doubles_each_failure() {
assert_eq!(backoff_duration(1), Duration::from_secs(1));
diff --git a/rust/personhog-writer/tests/common/mod.rs b/rust/personhog-writer/tests/common/mod.rs
index 0aa9fd9ea889..cf70c26b91c2 100644
--- a/rust/personhog-writer/tests/common/mod.rs
+++ b/rust/personhog-writer/tests/common/mod.rs
@@ -3,6 +3,7 @@
// would otherwise fire `dead_code` per-binary; suppress at the module level.
#![allow(dead_code)]
+use std::sync::Arc;
use std::time::Duration;
use common_kafka::kafka_producer::KafkaContext;
@@ -28,6 +29,11 @@ pub fn test_store_config() -> StoreConfig {
}
}
+/// Upsert permit budget large enough to never constrain a test.
+pub fn test_permits() -> Arc<tokio::sync::Semaphore> {
+ Arc::new(tokio::sync::Semaphore::new(64))
+}
+
/// Create a mock Kafka cluster with the personhog_updates topic.
pub async fn create_mock_kafka() -> (
MockCluster<'static, DefaultProducerContext>,
diff --git a/rust/personhog-writer/tests/integration.rs b/rust/personhog-writer/tests/integration.rs
index ccc9910e8251..ba1f942fde76 100644
--- a/rust/personhog-writer/tests/integration.rs
+++ b/rust/personhog-writer/tests/integration.rs
@@ -34,6 +34,7 @@ async fn writer_upserts_person_to_pg() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
let person = make_person(team_id as i64, 1, 1);
@@ -66,6 +67,7 @@ async fn writer_projects_death_documents_as_tombstones() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
let fetch_row = |pool: sqlx::PgPool| async move {
@@ -127,6 +129,7 @@ async fn writer_version_guard_skips_stale_updates() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
// Write version 5
@@ -167,6 +170,7 @@ async fn writer_merges_meta_and_last_seen_instead_of_assigning() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
let fetch = |pool: sqlx::PgPool| async move {
@@ -257,6 +261,7 @@ async fn writer_upsert_batch_multiple_persons() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
let persons: Vec<Person> = (1..=10)
.map(|i| make_person(team_id as i64, i, 1))
@@ -287,6 +292,7 @@ async fn writer_surfaces_invalid_uuids_as_violations_never_silent_skips() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
let valid_person = make_person(team_id as i64, 1, 1);
@@ -301,12 +307,14 @@ async fn writer_surfaces_invalid_uuids_as_violations_never_silent_skips() {
.await;
let BatchOutcome::Partial {
transient,
+ saturated,
data_failed,
} = outcome
else {
panic!("a chunk with an unbindable row must be data-failed");
};
assert!(transient.is_empty());
+ assert!(saturated.is_empty());
assert_eq!(data_failed.len(), 3);
// The per-row pass isolates the poison row as a violation; the valid
@@ -368,6 +376,7 @@ async fn consumer_flushes_on_buffer_size_threshold() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), writer, flush_rx, writer_handle);
tokio::spawn(async move { writer_task.run().await });
@@ -462,6 +471,7 @@ async fn consumer_flushes_on_timer() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), writer, flush_rx, writer_handle);
tokio::spawn(async move { writer_task.run().await });
@@ -556,6 +566,7 @@ async fn consumer_deduplicates_multiple_updates_for_same_person() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), writer, flush_rx, writer_handle);
tokio::spawn(async move { writer_task.run().await });
@@ -748,6 +759,100 @@ async fn multi_lane_consumer_routes_partitions_and_flushes_independently() {
assert_eq!(ids1, vec![4, 5, 6]);
}
+/// Flushes drain whole partitions up to the flush size, so a batch's
+/// committed offsets must cover exactly the partitions of the persons it
+/// carries — never a partition whose persons are still buffered. Asserted
+/// on the lane channel directly across however many capped batches the
+/// consumer emits; arrival interleaving decides the exact split.
+#[tokio::test]
+async fn capped_drains_commit_only_the_partitions_they_carry() {
+ let (mock_cluster, producer) = common::create_mock_kafka_with_partitions(2).await;
+ let team_id: i64 = 99_061;
+
+ let (tx, mut rx) = mpsc::channel::<FlushBatch>(2);
+
+ let client_config = ClientConfig::new()
+ .set("bootstrap.servers", mock_cluster.bootstrap_servers())
+ .set("group.id", "test-capped-drain")
+ .set("auto.offset.reset", "earliest")
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .clone();
+ let kafka_consumer = Arc::new(PersonConsumer::new(&client_config, TOPIC.to_string()).unwrap());
+
+ let mut manager = lifecycle::Manager::builder("test")
+ .with_trap_signals(false)
+ .build();
+ let consumer_handle = manager.register(
+ "consumer",
+ lifecycle::ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(5)),
+ );
+ let _monitor = manager.monitor_background();
+
+ // Person ids encode their partition: 1..=3 on partition 0, 4..=6 on
+ // partition 1, so each flushed person maps back to a partition.
+ for (partition, id) in [(0, 1), (0, 2), (0, 3), (1, 4), (1, 5), (1, 6)] {
+ let person = make_person(team_id, id, 1);
+ let payload = person.encode_to_vec();
+ let key = format!("{team_id}:{id}");
+ let record = FutureRecord::to(TOPIC)
+ .partition(partition)
+ .key(&key)
+ .payload(&payload);
+ producer
+ .send_result(record)
+ .unwrap()
+ .await
+ .unwrap()
+ .unwrap();
+ }
+
+ // Flush size 3 caps each drain below the 6 buffered persons; the short
+ // timer sweeps up any tail the size trigger leaves behind.
+ let consumer_task = ConsumerTask::new(
+ kafka_consumer,
+ vec![tx],
+ 100,
+ Duration::from_secs(2),
+ 3,
+ consumer_handle,
+ );
+ tokio::spawn(async move { consumer_task.run().await });
+
+ let mut seen_persons = 0;
+ let mut batches = 0;
+ let mut max_offset_seen: HashMap<i32, i64> = HashMap::new();
+ while seen_persons < 6 {
+ let batch = tokio::time::timeout(Duration::from_secs(15), rx.recv())
+ .await
+ .expect("expected another capped batch")
+ .expect("consumer channel should be open");
+
+ let partitions_in_batch: std::collections::HashSet<i32> = batch
+ .persons
+ .iter()
+ .map(|p| if p.id <= 3 { 0 } else { 1 })
+ .collect();
+ let committed: std::collections::HashSet<i32> = batch.offsets.keys().copied().collect();
+ assert_eq!(
+ committed, partitions_in_batch,
+ "a batch's offsets must cover exactly the partitions it drained"
+ );
+
+ for (partition, offset) in &batch.offsets {
+ let entry = max_offset_seen.entry(*partition).or_insert(-1);
+ *entry = (*entry).max(*offset);
+ }
+ seen_persons += batch.persons.len();
+ batches += 1;
+ }
+
+ assert!(batches >= 2, "a capped drain must split 6 rows at cap 3");
+ // Three messages per partition, offsets 0..=2, all eventually committed.
+ assert_eq!(max_offset_seen[&0], 2);
+ assert_eq!(max_offset_seen[&1], 2);
+}
+
// ============================================================
// Writer task: signals completion through channel
// ============================================================
@@ -777,6 +882,7 @@ async fn writer_processes_batch_from_channel() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), writer, flush_rx, writer_handle);
tokio::spawn(async move { writer_task.run().await });
@@ -889,6 +995,7 @@ async fn writer_crashes_after_exhausting_transient_retries() {
chunk_size: 10,
row_fallback_concurrency: 4,
},
+ common::test_permits(),
);
let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);
@@ -941,6 +1048,7 @@ async fn writer_recovers_on_transient_retry() {
chunk_size: 10,
row_fallback_concurrency: 4,
},
+ common::test_permits(),
);
let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);
@@ -997,6 +1105,7 @@ async fn writer_falls_back_to_per_row_on_data_error() {
chunk_size: 10,
row_fallback_concurrency: 4,
},
+ common::test_permits(),
);
let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);
@@ -1061,6 +1170,7 @@ async fn unapplyable_batch_halts_the_writer_before_any_later_batch() {
chunk_size: 10,
row_fallback_concurrency: 4,
},
+ common::test_permits(),
);
let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);
@@ -1110,6 +1220,7 @@ async fn properties_size_violation_errors_and_writes_nothing() {
let store = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
// Would have been trimmable under the old semantics: protected email
@@ -1197,6 +1308,7 @@ async fn e2e_produce_to_kafka_and_verify_pg_write() {
let writer = PersonWriteStore::new(
PgStore::new(pool.clone(), TARGET_TABLE.to_string()),
common::test_store_config(),
+ common::test_permits(),
);
let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), writer, flush_rx, writer_handle);
tokio::spawn(async move { writer_task.run().await });