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.

feat(personhog): pool warming and offset-query kafka clients (#75145)

Zach Brown423950a6aa7b
diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rs
index 841a65b74279..f2f870788f97 100644
--- a/rust/personhog-leader/src/coordination/mod.rs
+++ b/rust/personhog-leader/src/coordination/mod.rs
@@ -8,7 +8,7 @@ use tracing::info;
use crate::cache::{DirtyIndex, PartitionedCache};
use crate::inflight::InflightTracker;
-use crate::warming::{warm_from_kafka, WarmingConfig};
+use crate::warming::{warm_from_kafka, WarmClientPools, WarmingConfig};
const DRAIN_POLL_INTERVAL: Duration = Duration::from_millis(50);
@@ -45,6 +45,7 @@ pub struct LeaderHandoffHandler {
inflight: Arc<InflightTracker>,
dirty_index: Arc<DirtyIndex>,
warming: WarmingConfig,
+ pools: Arc<WarmClientPools>,
}
impl LeaderHandoffHandler {
@@ -53,12 +54,14 @@ impl LeaderHandoffHandler {
inflight: Arc<InflightTracker>,
dirty_index: Arc<DirtyIndex>,
warming: WarmingConfig,
+ pools: Arc<WarmClientPools>,
) -> Self {
Self {
cache,
inflight,
dirty_index,
warming,
+ pools,
}
}
@@ -85,7 +88,14 @@ impl HandoffHandler for LeaderHandoffHandler {
async fn warm_partition(&self, partition: u32) -> Result<()> {
info!(partition, "warming partition cache from kafka");
- warm_from_kafka(&self.warming, &self.cache, &self.dirty_index, partition).await?;
+ warm_from_kafka(
+ &self.warming,
+ &self.pools,
+ &self.cache,
+ &self.dirty_index,
+ partition,
+ )
+ .await?;
// This pod may still carry a fence from a previous ownership of
// the partition (a drain whose handoff never completed); taking
// ownership through a fresh warm re-admits writes.
@@ -145,6 +155,7 @@ mod tests {
kafka_producer_acks: None,
kafka_producer_retries: None,
};
+ let pools = Arc::new(WarmClientPools::new(&kafka, "test", "personhog-writer"));
LeaderHandoffHandler::new(
Arc::new(PartitionedCache::new(100)),
Arc::new(InflightTracker::new()),
@@ -164,6 +175,7 @@ mod tests {
max_backoff: Duration::from_secs(5),
},
},
+ pools,
)
}
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 58caa5b7506e..660217fa7d83 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -3,7 +3,6 @@ use std::time::Duration;
use assignment_coordination::store::{EtcdStore, StoreConfig};
use axum::{routing::get, Router};
-use common_kafka::config::KafkaConfig;
use common_kafka::kafka_producer::create_kafka_producer;
use common_metrics::setup_metrics_routes;
use dashmap::DashMap;
@@ -31,7 +30,7 @@ use personhog_leader::pg::{validate_table_name, PgFallback};
use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
use personhog_leader::service::{sweep_idle_locks, PersonHogLeaderService, PropertySizeLimits};
use personhog_leader::warming::{
- fetch_writer_committed_offsets, WarmingConfig, WarmingRetryPolicy,
+ fetch_writer_committed_offsets, WarmClientPools, WarmingConfig, WarmingRetryPolicy,
};
use personhog_leader::warnings::WarningsProducer;
@@ -219,6 +218,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
warnings.clone(),
);
+ let warm_pools = Arc::new(WarmClientPools::new(
+ &config.kafka,
+ &config.pod_name,
+ &config.writer_consumer_group,
+ ));
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
@@ -242,24 +246,38 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
max_backoff: Duration::from_millis(config.warm_retry_max_backoff_ms),
},
},
+ Arc::clone(&warm_pools),
);
let advertise_address =
personhog_leader::config::derive_advertise_address(&config.grpc_address, &config.pod_ip)
.expect("Invalid advertise address configuration");
tracing::info!(%advertise_address, "advertising gRPC address for routing");
- let pod = PodHandle::new(
- store,
- PodConfig {
- pod_name: config.pod_name.clone(),
- lease_ttl: config.lease_ttl,
- heartbeat_interval: config.heartbeat_interval(),
- advertise_address: Some(advertise_address),
- ..Default::default()
- },
- Arc::new(handler),
- None,
- );
+ let pod_config = PodConfig {
+ pod_name: config.pod_name.clone(),
+ lease_ttl: config.lease_ttl,
+ heartbeat_interval: config.heartbeat_interval(),
+ advertise_address: Some(advertise_address),
+ ..Default::default()
+ };
+
+ // Open connections up front: warms cluster in deploy bursts, and a
+ // cold pool would make every burst's first operations pay the client
+ // setup the pool exists to amortize. Sized from the pod's actual
+ // configured warm concurrency — the bound the semaphore enforces —
+ // so the pool and the concurrency limit cannot drift apart; the
+ // offsets pool also serves the dirty-index prune tick. Best-effort:
+ // a failure only defers the cost.
+ {
+ let pools = Arc::clone(&warm_pools);
+ let warm_slots = pod_config.warm_concurrency;
+ tokio::spawn(async move {
+ pools.offsets.warm_up(2).await;
+ pools.warming.warm_up(warm_slots).await;
+ });
+ }
+
+ let pod = PodHandle::new(store, pod_config, Arc::new(handler), None);
tokio::spawn(async move {
let _guard = coordination_handle.process_scope();
@@ -282,9 +300,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::spawn(run_dirty_index_prune_loop(
Arc::clone(&dirty_index),
- config.kafka.clone(),
+ Arc::clone(&warm_pools),
config.kafka_person_state_topic.clone(),
- config.writer_consumer_group.clone(),
Duration::from_secs(config.warm_committed_offsets_timeout_secs),
Duration::from_secs(config.dirty_index_prune_interval_secs.max(1)),
));
@@ -372,13 +389,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// Periodically drop dirty-index marks the writer has applied to PG, and
/// export the dirty-count and writer-lag gauges as a side effect. One
-/// batched OffsetFetch covers every partition with marks, so each tick
-/// costs a single short-lived consumer.
+/// batched OffsetFetch covers every partition with marks, on a pooled
+/// client — each tick reuses the connection instead of rebuilding one.
async fn run_dirty_index_prune_loop(
dirty_index: Arc<DirtyIndex>,
- kafka: KafkaConfig,
+ pools: Arc<WarmClientPools>,
topic: String,
- writer_group: String,
offsets_timeout: Duration,
prune_interval: Duration,
) {
@@ -396,8 +412,7 @@ async fn run_dirty_index_prune_loop(
continue;
}
let committed_offsets = match fetch_writer_committed_offsets(
- &kafka,
- &writer_group,
+ &pools.offsets,
&topic,
&partitions,
offsets_timeout,
diff --git a/rust/personhog-leader/src/warming.rs b/rust/personhog-leader/src/warming.rs
index 38bbc9c609dc..5a11ffd03640 100644
--- a/rust/personhog-leader/src/warming.rs
+++ b/rust/personhog-leader/src/warming.rs
@@ -1,5 +1,6 @@
use std::collections::HashMap;
-use std::sync::Arc;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex as StdMutex};
use std::time::{Duration, Instant};
use common_kafka::config::KafkaConfig;
@@ -134,18 +135,143 @@ pub(crate) fn make_consumer(
cfg.create()
}
+/// A checkout stack of assign-only Kafka clients sharing one group id.
+/// Clients are checked out for the duration of one operation, returned on
+/// success, and dropped on error — a client that just failed is never
+/// reused, so error hygiene is structural. None of these clients ever
+/// joins the group protocol (no subscribe), so the group id is broker
+/// bookkeeping, not membership: pooling clients in the writer's group
+/// cannot affect the writer's rebalancing.
+///
+/// The pool exists because client construction is the dominant cost of
+/// the operations it serves: a fresh consumer pays connection setup,
+/// metadata, and coordinator discovery before its one round-trip. Warms
+/// paid that twice per partition; the dirty-index prune paid it every
+/// tick.
+pub struct ConsumerPool {
+ kafka: KafkaConfig,
+ group_id: String,
+ /// Metric label; also names the pool in logs.
+ label: &'static str,
+ stack: StdMutex<Vec<StreamConsumer>>,
+ created: AtomicU64,
+}
+
+impl ConsumerPool {
+ pub fn new(kafka: KafkaConfig, group_id: String, label: &'static str) -> Self {
+ Self {
+ kafka,
+ group_id,
+ label,
+ stack: StdMutex::new(Vec::new()),
+ created: AtomicU64::new(0),
+ }
+ }
+
+ /// Pop a pooled client or create a fresh one.
+ pub fn checkout(&self) -> CoordResult<StreamConsumer> {
+ if let Some(consumer) = self.stack.lock().unwrap().pop() {
+ return Ok(consumer);
+ }
+ self.created.fetch_add(1, Ordering::Relaxed);
+ counter!(
+ "personhog_leader_warm_clients_created_total",
+ "pool" => self.label
+ )
+ .increment(1);
+ make_consumer(&self.kafka, &self.group_id)
+ .map_err(|e| CoordError::invalid_state(format!("create {} client: {e}", self.label)))
+ }
+
+ /// Return a client after a successful operation. The assignment is
+ /// cleared so the next checkout starts from a clean slate; clearing
+ /// an unassigned client is a harmless no-op. A client whose
+ /// assignment cannot be cleared is dropped instead of pooled — the
+ /// pool's contract is that doubtful clients are never reused — with
+ /// the failure logged so a systematic cleanup problem surfaces as a
+ /// visible signal rather than silent churn.
+ pub fn give_back(&self, consumer: StreamConsumer) {
+ if let Err(e) = consumer.unassign() {
+ tracing::warn!(
+ pool = self.label,
+ error = %e,
+ "unassign failed; dropping client instead of pooling it"
+ );
+ return;
+ }
+ self.stack.lock().unwrap().push(consumer);
+ }
+
+ /// Total clients ever created — flat across operations when reuse
+ /// works; grows per operation when it does not.
+ pub fn created_count(&self) -> u64 {
+ self.created.load(Ordering::Relaxed)
+ }
+
+ /// Eagerly create `n` clients and open their broker connections
+ /// (rdkafka connects lazily, so creation alone leaves cold sockets).
+ /// Best-effort: warms cluster in deploy bursts, and a failure here
+ /// only means the first operations pay the setup they would have
+ /// paid anyway.
+ pub async fn warm_up(&self, n: usize) {
+ // Hold every connected client outside the pool until the end:
+ // returning them as we go would make the next checkout pop the
+ // client we just returned, connecting one client n times and
+ // leaving the other n-1 slots to be built cold on the hot path.
+ let mut connected = Vec::with_capacity(n);
+ for _ in 0..n {
+ let Ok(consumer) = self.checkout() else {
+ break;
+ };
+ let timeout = Duration::from_secs(5);
+ let outcome = tokio::task::spawn_blocking(move || {
+ let ok = consumer.fetch_metadata(None, timeout).is_ok();
+ (consumer, ok)
+ })
+ .await;
+ match outcome {
+ Ok((consumer, true)) => connected.push(consumer),
+ _ => break,
+ }
+ }
+ for consumer in connected {
+ self.give_back(consumer);
+ }
+ }
+}
+
+/// The two client pools the warm path and the dirty-index prune share.
+/// Separate pools because a client's group id is fixed at construction:
+/// offset queries must carry the writer's group id to OffsetFetch its
+/// committed offsets, while warming consumers carry their own.
+pub struct WarmClientPools {
+ pub offsets: ConsumerPool,
+ pub warming: ConsumerPool,
+}
+
+impl WarmClientPools {
+ pub fn new(kafka: &KafkaConfig, pod_name: &str, writer_group: &str) -> Self {
+ Self {
+ offsets: ConsumerPool::new(kafka.clone(), writer_group.to_string(), "offsets"),
+ warming: ConsumerPool::new(
+ kafka.clone(),
+ format!("personhog-leader-warm-{pod_name}"),
+ "warming",
+ ),
+ }
+ }
+}
+
/// Query the writer consumer group's committed offset for a partition.
/// Returns `None` if the writer has no commit yet for the partition
/// (typical for a freshly-created topic).
async fn fetch_writer_committed_offset(
- kafka: &KafkaConfig,
- writer_group: &str,
+ pool: &ConsumerPool,
topic: &str,
partition: u32,
timeout: Duration,
) -> CoordResult<Option<i64>> {
- let offsets =
- fetch_writer_committed_offsets(kafka, writer_group, topic, &[partition], timeout).await?;
+ let offsets = fetch_writer_committed_offsets(pool, topic, &[partition], timeout).await?;
Ok(offsets.get(&partition).copied())
}
@@ -160,8 +286,7 @@ async fn fetch_writer_committed_offset(
/// and parks the calling thread for up to `timeout`. We run it on the
/// blocking pool so a slow broker can't stall the tokio runtime.
pub async fn fetch_writer_committed_offsets(
- kafka: &KafkaConfig,
- writer_group: &str,
+ pool: &ConsumerPool,
topic: &str,
partitions: &[u32],
timeout: Duration,
@@ -169,33 +294,37 @@ pub async fn fetch_writer_committed_offsets(
if partitions.is_empty() {
return Ok(HashMap::new());
}
- let kafka = kafka.clone();
- let writer_group = writer_group.to_string();
+ let consumer = pool.checkout()?;
let topic = topic.to_string();
let partitions = partitions.to_vec();
- tokio::task::spawn_blocking(move || {
- let consumer = make_consumer(&kafka, &writer_group)
- .map_err(|e| CoordError::invalid_state(format!("create offset query consumer: {e}")))?;
+ let (consumer, result) = tokio::task::spawn_blocking(move || {
let mut tpl = TopicPartitionList::new();
for partition in &partitions {
tpl.add_partition(&topic, *partition as i32);
}
- let committed = consumer
+ let result = consumer
.committed_offsets(tpl, timeout)
- .map_err(|e| CoordError::invalid_state(format!("committed_offsets for group: {e}")))?;
- let mut offsets = HashMap::new();
- for partition in partitions {
- if let Some(Offset::Offset(offset)) = committed
- .find_partition(&topic, partition as i32)
- .map(|tp| tp.offset())
- {
- offsets.insert(partition, offset);
- }
- }
- Ok(offsets)
+ .map_err(|e| CoordError::invalid_state(format!("committed_offsets for group: {e}")))
+ .map(|committed| {
+ let mut offsets = HashMap::new();
+ for partition in partitions {
+ if let Some(Offset::Offset(offset)) = committed
+ .find_partition(&topic, partition as i32)
+ .map(|tp| tp.offset())
+ {
+ offsets.insert(partition, offset);
+ }
+ }
+ offsets
+ });
+ (consumer, result)
})
.await
- .map_err(|e| CoordError::invalid_state(format!("offset query join: {e}")))?
+ .map_err(|e| CoordError::invalid_state(format!("offset query join: {e}")))?;
+ if result.is_ok() {
+ pool.give_back(consumer);
+ }
+ result
}
/// Decide where to start consuming for a partition.
@@ -236,6 +365,7 @@ fn resolve_start_offset(committed: Option<i64>, earliest: i64, lookback: i64) ->
/// racing producers.
pub async fn warm_from_kafka(
cfg: &WarmingConfig,
+ pools: &WarmClientPools,
cache: &PartitionedCache,
dirty_index: &DirtyIndex,
partition: u32,
@@ -250,8 +380,7 @@ pub async fn warm_from_kafka(
// consumer group.
let committed_offset = with_warm_retry("committed_offset", partition, cfg.retry, || async {
fetch_writer_committed_offset(
- &cfg.kafka,
- &cfg.writer_consumer_group,
+ &pools.offsets,
&cfg.topic,
partition,
cfg.committed_offsets_timeout,
@@ -260,14 +389,9 @@ pub async fn warm_from_kafka(
})
.await?;
- let warming_group = format!(
- "personhog-leader-warm-{pod}-p{partition}",
- pod = cfg.pod_name
- );
- let consumer = Arc::new(
- make_consumer(&cfg.kafka, &warming_group)
- .map_err(|e| CoordError::invalid_state(format!("create warming consumer: {e}")))?,
- );
+ // Arc because the watermark retry closure needs its own handle for
+ // the blocking pool; sole ownership returns once the retries finish.
+ let consumer = Arc::new(pools.warming.checkout()?);
// `fetch_watermarks` is synchronous in rdkafka and may block for the
// full timeout. Run it on the blocking pool so retries don't park the
@@ -427,6 +551,13 @@ pub async fn warm_from_kafka(
histogram!("personhog_leader_warm_duration_ms").record(elapsed.as_secs_f64() * 1000.0);
counter!("personhog_leader_warmed_messages_total").increment(count);
+ // Every error path above dropped the consumer instead of returning
+ // it — a client that just failed is not pool material. Failing to
+ // unwrap the Arc would only mean the same disposition.
+ if let Ok(consumer) = Arc::try_unwrap(consumer) {
+ pools.warming.give_back(consumer);
+ }
+
Ok(())
}
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index 60fc421e4c0c..4c7ebca109b1 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -31,6 +31,7 @@ use personhog_leader::inflight::InflightTracker;
use personhog_leader::pg::PgFallback;
use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};
+use personhog_leader::warming::WarmClientPools;
use personhog_leader::warnings::WarningsProducer;
use personhog_proto::personhog::leader::v1::person_hog_leader_client::PersonHogLeaderClient;
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;
@@ -343,11 +344,18 @@ pub async fn start_leader_pod(
let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
// Recovery must read the broker the service produces to.
let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let warming = test_warming_config(name, &mock_cluster.bootstrap_servers());
+ let pools = Arc::new(WarmClientPools::new(
+ &warming.kafka,
+ name,
+ &warming.writer_consumer_group,
+ ));
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
Arc::clone(&dirty_index),
- test_warming_config(name, &mock_cluster.bootstrap_servers()),
+ warming,
+ pools,
);
let pod = PodHandle::new(
store,
@@ -416,11 +424,18 @@ pub async fn start_leader_pod_with_lease_ttl(
let inflight = Arc::new(InflightTracker::new());
let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let warming = test_warming_config(name, &mock_cluster.bootstrap_servers());
+ let pools = Arc::new(WarmClientPools::new(
+ &warming.kafka,
+ name,
+ &warming.writer_consumer_group,
+ ));
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
Arc::clone(&dirty_index),
- test_warming_config(name, &mock_cluster.bootstrap_servers()),
+ warming,
+ pools,
);
let pod = PodHandle::new(
store,
diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rs
index 55fc0c049dff..d9efc0785384 100644
--- a/rust/personhog-leader/tests/integration.rs
+++ b/rust/personhog-leader/tests/integration.rs
@@ -24,6 +24,7 @@ use personhog_leader::cache::{
use personhog_leader::coordination::LeaderHandoffHandler;
use personhog_leader::inflight::InflightTracker;
use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};
+use personhog_leader::warming::WarmClientPools;
use personhog_leader::warnings::WarningsProducer;
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;
use personhog_proto::personhog::types::v1::{
@@ -433,11 +434,18 @@ async fn writes_fenced_after_drain_reads_still_served() {
);
// The handler shares the cache, inflight tracker, dirty index, and
// recovery pool with the service, exactly as main.rs wires them.
+ let warming = test_warming_config("fence-pod", KAFKA_BOOTSTRAP);
+ let pools = Arc::new(WarmClientPools::new(
+ &warming.kafka,
+ "fence-pod",
+ &warming.writer_consumer_group,
+ ));
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
Arc::clone(&dirty_index),
- test_warming_config("fence-pod", KAFKA_BOOTSTRAP),
+ warming,
+ pools,
);
cache.create_partition(0);
@@ -542,11 +550,18 @@ async fn drain_fences_before_waiting_on_inflight() {
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
);
+ let warming = test_warming_config("fence-race-pod", KAFKA_BOOTSTRAP);
+ let pools = Arc::new(WarmClientPools::new(
+ &warming.kafka,
+ "fence-race-pod",
+ &warming.writer_consumer_group,
+ ));
let handler = Arc::new(LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
Arc::clone(&dirty_index),
- test_warming_config("fence-race-pod", KAFKA_BOOTSTRAP),
+ warming,
+ pools,
));
cache.create_partition(0);
diff --git a/rust/personhog-leader/tests/warming_integration.rs b/rust/personhog-leader/tests/warming_integration.rs
index bf35543e1173..b2cd66891432 100644
--- a/rust/personhog-leader/tests/warming_integration.rs
+++ b/rust/personhog-leader/tests/warming_integration.rs
@@ -9,7 +9,7 @@ use std::time::Duration;
use common::{create_test_kafka, test_warming_config, CHANGELOG_TOPIC, NUM_PARTITIONS};
use personhog_leader::cache::{CacheLookup, DirtyIndex, PartitionedCache, PersonCacheKey};
-use personhog_leader::warming::{warm_from_kafka, WarmingConfig};
+use personhog_leader::warming::{warm_from_kafka, WarmClientPools, WarmingConfig};
use personhog_proto::personhog::types::v1::Person;
use prost::Message as ProtoMessage;
use rdkafka::config::ClientConfig;
@@ -82,8 +82,10 @@ async fn produce_garbage_to_partition(
fn warming_config_for(
pod_name: &str,
cluster: &MockCluster<'static, DefaultProducerContext>,
-) -> WarmingConfig {
- test_warming_config(pod_name, &cluster.bootstrap_servers())
+) -> (WarmingConfig, WarmClientPools) {
+ let cfg = test_warming_config(pod_name, &cluster.bootstrap_servers());
+ let pools = WarmClientPools::new(&cfg.kafka, pod_name, &cfg.writer_consumer_group);
+ (cfg, pools)
}
/// Happy path: produce N messages to a partition, warm, assert every
@@ -101,9 +103,9 @@ async fn warming_populates_cache_from_kafka() {
}
let cache = PartitionedCache::new(100);
- let cfg = warming_config_for("warmer-0", &cluster);
+ let (cfg, pools) = warming_config_for("warmer-0", &cluster);
- warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0)
+ warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("warming should succeed");
@@ -133,9 +135,9 @@ async fn warming_handles_empty_partition() {
let (cluster, _producer) = create_test_kafka().await;
let cache = PartitionedCache::new(100);
- let cfg = warming_config_for("warmer-empty", &cluster);
+ let (cfg, pools) = warming_config_for("warmer-empty", &cluster);
- warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0)
+ warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("warming an empty partition should succeed");
@@ -165,9 +167,9 @@ async fn warming_only_populates_target_partition() {
produce_person_to_partition(&producer, 1, &make_person(1, 200)).await;
let cache = PartitionedCache::new(100);
- let cfg = warming_config_for("warmer-iso", &cluster);
+ let (cfg, pools) = warming_config_for("warmer-iso", &cluster);
- warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0)
+ warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("warming partition 0 should succeed");
@@ -201,9 +203,9 @@ async fn warming_fails_loudly_on_decode_error_and_leaves_cache_clean() {
produce_garbage_to_partition(&producer, 0).await;
let cache = PartitionedCache::new(100);
- let cfg = warming_config_for("warmer-decode", &cluster);
+ let (cfg, pools) = warming_config_for("warmer-decode", &cluster);
- let result = warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0).await;
+ let result = warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0).await;
assert!(
result.is_err(),
"a malformed message must fail the entire warm"
@@ -230,10 +232,10 @@ async fn warming_works_across_all_partitions() {
}
let cache = Arc::new(PartitionedCache::new(100));
- let cfg = warming_config_for("warmer-all", &cluster);
+ let (cfg, pools) = warming_config_for("warmer-all", &cluster);
for partition in 0..NUM_PARTITIONS {
- warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), partition)
+ warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), partition)
.await
.unwrap_or_else(|e| panic!("warming partition {partition} failed: {e}"));
}
@@ -298,13 +300,13 @@ async fn warming_starts_from_writer_committed_offset() {
commit_writer_offset_at(&cluster, "personhog-writer", 0, 5);
let cache = PartitionedCache::new(100);
- let mut cfg = warming_config_for("warmer-committed", &cluster);
+ let (mut cfg, pools) = warming_config_for("warmer-committed", &cluster);
// Set lookback to 0 so the start offset is exactly the committed
// value; otherwise it would rewind further and include earlier
// records, defeating the point of this assertion.
cfg.lookback_offsets = 0;
- warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0)
+ warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("warming should succeed");
@@ -365,9 +367,9 @@ async fn warming_fails_loudly_on_properties_json_error() {
produce_person_to_partition(&producer, 0, &bad).await;
let cache = PartitionedCache::new(100);
- let cfg = warming_config_for("warmer-bad-props", &cluster);
+ let (cfg, pools) = warming_config_for("warmer-bad-props", &cluster);
- let result = warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0).await;
+ let result = warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0).await;
assert!(
result.is_err(),
"invalid JSON in properties must fail the entire warm"
@@ -407,9 +409,9 @@ async fn warming_preserves_last_write_for_same_key() {
}
let cache = PartitionedCache::new(100);
- let cfg = warming_config_for("warmer-lww", &cluster);
+ let (cfg, pools) = warming_config_for("warmer-lww", &cluster);
- warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0)
+ warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("warming should succeed");
@@ -451,12 +453,12 @@ async fn warming_seeds_dirty_index_only_at_or_past_the_committed_offset() {
let cache = PartitionedCache::new(100);
let dirty_index = DirtyIndex::new(1_000_000);
- let mut cfg = warming_config_for("warmer-seed-committed", &cluster);
+ let (mut cfg, pools) = warming_config_for("warmer-seed-committed", &cluster);
// Rewind the warm range below the committed offset so it spans the
// boundary and both seeding arms are exercised.
cfg.lookback_offsets = 8;
- warm_from_kafka(&cfg, &cache, &dirty_index, 0)
+ warm_from_kafka(&cfg, &pools, &cache, &dirty_index, 0)
.await
.expect("warming should succeed");
@@ -498,9 +500,9 @@ async fn warming_seeds_dirty_index_when_writer_has_no_commits() {
let cache = PartitionedCache::new(100);
let dirty_index = DirtyIndex::new(1_000_000);
- let cfg = warming_config_for("warmer-seed", &cluster);
+ let (cfg, pools) = warming_config_for("warmer-seed", &cluster);
- warm_from_kafka(&cfg, &cache, &dirty_index, 0)
+ warm_from_kafka(&cfg, &pools, &cache, &dirty_index, 0)
.await
.expect("warming should succeed");
@@ -512,3 +514,56 @@ async fn warming_seeds_dirty_index_when_writer_has_no_commits() {
// Marks carry the record offsets: 3 records at offsets 0..=2.
assert_eq!(dirty_index.max_offset(0), Some(2));
}
+
+/// Sequential warms reuse pooled clients instead of rebuilding them:
+/// client construction (connection, metadata, coordinator discovery) is
+/// the dominant cost of a warm, so the pool's whole purpose is that the
+/// created-count stays at pool size while operations keep flowing.
+#[tokio::test]
+async fn sequential_warms_reuse_pooled_clients() {
+ let (cluster, producer) = create_test_kafka().await;
+
+ for person_id in 1..=3 {
+ let person = make_person(1, person_id);
+ produce_person_to_partition(&producer, 0, &person).await;
+ produce_person_to_partition(&producer, 1, &person).await;
+ }
+
+ let cache = PartitionedCache::new(100);
+ let (cfg, pools) = warming_config_for("warmer-pool", &cluster);
+
+ for partition in [0u32, 1, 0, 1] {
+ warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), partition)
+ .await
+ .expect("warming should succeed");
+ }
+
+ assert_eq!(
+ pools.warming.created_count(),
+ 1,
+ "four sequential warms must reuse one pooled warming consumer"
+ );
+ assert_eq!(
+ pools.offsets.created_count(),
+ 1,
+ "four offset queries must reuse one pooled offsets client"
+ );
+}
+
+/// Prewarming must fill every slot with a distinct connected client —
+/// returning clients to the pool mid-loop would hand the same one back
+/// to each iteration, leaving all but one slot to be built cold on the
+/// handoff path.
+#[tokio::test]
+async fn warm_up_fills_every_slot() {
+ let (cluster, _producer) = create_test_kafka().await;
+ let (_cfg, pools) = warming_config_for("warmer-prewarm", &cluster);
+
+ pools.warming.warm_up(3).await;
+
+ assert_eq!(
+ pools.warming.created_count(),
+ 3,
+ "prewarming three slots must create three distinct clients"
+ );
+}