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(usage-ingestion): stabilize redis counter flushing (#96775)

Ben Whitef57417de1c41
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index b7ec1d79798d..d5a1cc24eb86 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -13922,6 +13922,7 @@ dependencies = [
"health",
"metrics",
"metrics-exporter-prometheus",
+ "metrics-util",
"moka",
"rdkafka",
"redis",
diff --git a/rust/usage-ingestion/Cargo.toml b/rust/usage-ingestion/Cargo.toml
index 7f6b1d20d06c..5f0b40fa22ea 100644
--- a/rust/usage-ingestion/Cargo.toml
+++ b/rust/usage-ingestion/Cargo.toml
@@ -34,6 +34,7 @@ usage-ingestion-proto = { path = "../usage-ingestion-proto" }
uuid = { workspace = true }
[dev-dependencies]
+metrics-util = { workspace = true }
reqwest = { workspace = true }
tokio-stream = { version = "0.1", features = ["net"] }
diff --git a/rust/usage-ingestion/README.md b/rust/usage-ingestion/README.md
index 91417a52b937..902c511ebac4 100644
--- a/rust/usage-ingestion/README.md
+++ b/rust/usage-ingestion/README.md
@@ -35,12 +35,12 @@ development. It uses structured JSON logs otherwise.
Set `USAGE_INGESTION_REDIS_URL` to a dedicated Valkey Cluster endpoint to
enable the lossy hourly and daily counter projection. It is disabled when the
URL is empty, so Kafka and ClickHouse remain the only required dependencies.
-When Valkey is unavailable, the flusher retries every
-`USAGE_INGESTION_REDIS_FLUSH_INTERVAL_SECONDS` (default `15`) and drops the
-unavailable interval's deltas. Counter timestamps are limited to seven days
-behind and 24 hours ahead of the current time. Redis connections and flush
-concurrency default to 16 and can be tuned with
-`USAGE_INGESTION_REDIS_CONNECTIONS` and
+When connection setup fails, the flusher retries every
+`USAGE_INGESTION_REDIS_FLUSH_INTERVAL_SECONDS` (default `15`) and retains up to
+250,000 pending entries until it reconnects. After a write is issued, failed
+deltas are dropped because an I/O error can follow an applied transaction.
+Counter timestamps are limited to seven days behind and 24 hours ahead of the
+current time. Flush concurrency defaults to 16 and can be tuned with
`USAGE_INGESTION_REDIS_FLUSH_CONCURRENCY`.
The projection stores additive deltas, not usage record identities. Retrying
diff --git a/rust/usage-ingestion/src/config.rs b/rust/usage-ingestion/src/config.rs
index a35e4afcfdc9..ea4311ca4a90 100644
--- a/rust/usage-ingestion/src/config.rs
+++ b/rust/usage-ingestion/src/config.rs
@@ -43,8 +43,6 @@ pub struct Config {
pub redis_url: String,
#[envconfig(from = "USAGE_INGESTION_REDIS_FLUSH_INTERVAL_SECONDS", default = "15")]
pub redis_flush_interval_seconds: u64,
- #[envconfig(from = "USAGE_INGESTION_REDIS_CONNECTIONS", default = "16")]
- pub redis_connections: usize,
#[envconfig(from = "USAGE_INGESTION_REDIS_FLUSH_CONCURRENCY", default = "16")]
pub redis_flush_concurrency: usize,
// Overridable so a test environment can use the suffixed topic its Kafka engine table reads.
@@ -72,9 +70,6 @@ impl Config {
"USAGE_INGESTION_REDIS_FLUSH_INTERVAL_SECONDS must be positive".to_string(),
);
}
- if self.redis_connections == 0 {
- return Err("USAGE_INGESTION_REDIS_CONNECTIONS must be positive".to_string());
- }
if self.redis_flush_concurrency == 0 {
return Err("USAGE_INGESTION_REDIS_FLUSH_CONCURRENCY must be positive".to_string());
}
@@ -89,7 +84,6 @@ impl Config {
pub fn redis_counter_config(&self) -> CounterConfig {
CounterConfig {
- connections: self.redis_connections,
flush_concurrency: self.redis_flush_concurrency,
}
}
@@ -143,7 +137,6 @@ mod tests {
max_batch_size: 500,
redis_url: String::new(),
redis_flush_interval_seconds: 15,
- redis_connections: 16,
redis_flush_concurrency: 16,
topic: "clickhouse_billing_usage_records".to_string(),
grpc_max_connection_age_secs: 60,
@@ -192,23 +185,14 @@ mod tests {
#[test]
fn redis_counter_configuration_requires_positive_values() {
- for (config, expected) in [
- (
- Config {
- redis_connections: 0,
- ..config()
- },
- "USAGE_INGESTION_REDIS_CONNECTIONS must be positive",
- ),
- (
- Config {
- redis_flush_concurrency: 0,
- ..config()
- },
- "USAGE_INGESTION_REDIS_FLUSH_CONCURRENCY must be positive",
- ),
- ] {
- assert_eq!(config.validate(), Err(expected.to_string()));
- }
+ let config = Config {
+ redis_flush_concurrency: 0,
+ ..config()
+ };
+
+ assert_eq!(
+ config.validate(),
+ Err("USAGE_INGESTION_REDIS_FLUSH_CONCURRENCY must be positive".to_string())
+ );
}
}
diff --git a/rust/usage-ingestion/src/counters.rs b/rust/usage-ingestion/src/counters.rs
index bc7ac44fb496..00037aae0a76 100644
--- a/rust/usage-ingestion/src/counters.rs
+++ b/rust/usage-ingestion/src/counters.rs
@@ -1,14 +1,12 @@
use std::collections::HashMap;
-use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use chrono::{DateTime, Duration as ChronoDuration, Utc};
use futures::{stream, StreamExt};
-use redis::cluster::ClusterClient;
+use redis::cluster::ClusterClientBuilder;
use redis::cluster_async::ClusterConnection;
-use tokio::sync::Mutex as AsyncMutex;
use tracing::warn;
use uuid::Uuid;
@@ -16,21 +14,21 @@ use crate::record::KafkaBillingUsageRecord;
const HOURLY_TTL_SECONDS: u64 = 25 * 60 * 60;
const DAILY_TTL_SECONDS: u64 = 31 * 24 * 60 * 60;
-const DEFAULT_CONNECTIONS: usize = 16;
const DEFAULT_FLUSH_CONCURRENCY: usize = 16;
+const DEFAULT_MAX_PENDING_ENTRIES: usize = 250_000;
+const REDIS_CONNECTION_TIMEOUT: Duration = Duration::from_secs(5);
+const REDIS_RESPONSE_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_PAST_TIMESTAMP: ChronoDuration = ChronoDuration::days(7);
const MAX_FUTURE_TIMESTAMP: ChronoDuration = ChronoDuration::hours(24);
#[derive(Clone, Copy, Debug)]
pub struct CounterConfig {
- pub connections: usize,
pub flush_concurrency: usize,
}
impl Default for CounterConfig {
fn default() -> Self {
Self {
- connections: DEFAULT_CONNECTIONS,
flush_concurrency: DEFAULT_FLUSH_CONCURRENCY,
}
}
@@ -88,6 +86,7 @@ struct CounterEntry {
pub enum CounterAddError {
TimestampOutOfRange,
Overflow,
+ Capacity,
}
impl CounterAddError {
@@ -95,6 +94,7 @@ impl CounterAddError {
match self {
Self::TimestampOutOfRange => "timestamp_out_of_range",
Self::Overflow => "overflow",
+ Self::Capacity => "capacity",
}
}
}
@@ -106,12 +106,31 @@ pub struct ScopeCounters {
}
/// A process-local, lossy aggregation of Kafka-confirmed usage records.
-#[derive(Default)]
pub struct CounterAccumulator {
- pending: Mutex<HashMap<CounterScope, HashMap<CounterEntry, i64>>>,
+ pending: Mutex<PendingCounters>,
+ max_entries: usize,
+}
+
+#[derive(Default)]
+struct PendingCounters {
+ scopes: HashMap<CounterScope, HashMap<CounterEntry, i64>>,
+ entries: usize,
+}
+
+impl Default for CounterAccumulator {
+ fn default() -> Self {
+ Self::new(DEFAULT_MAX_PENDING_ENTRIES)
+ }
}
impl CounterAccumulator {
+ pub fn new(max_entries: usize) -> Self {
+ Self {
+ pending: Mutex::new(PendingCounters::default()),
+ max_entries,
+ }
+ }
+
pub fn add_record(&self, record: &KafkaBillingUsageRecord) -> Result<(), CounterAddError> {
self.add(
record.team_id,
@@ -143,25 +162,48 @@ impl CounterAccumulator {
CounterScope::Organization(organization_id),
];
let mut pending = self.pending.lock().expect("usage counter mutex poisoned");
+ let new_entries = scopes
+ .iter()
+ .flat_map(|scope| {
+ buckets.iter().filter(|bucket| {
+ !pending.scopes.get(scope).is_some_and(|entries| {
+ entries.contains_key(&CounterEntry {
+ bucket: **bucket,
+ field: field.clone(),
+ })
+ })
+ })
+ })
+ .count();
+ if pending.entries.saturating_add(new_entries) > self.max_entries {
+ return Err(CounterAddError::Capacity);
+ }
let mut rejection = None;
for scope in scopes {
- if let Err(error) =
- add_to_scope(pending.entry(scope).or_default(), buckets, &field, quantity)
- {
+ let entries = pending.scopes.entry(scope).or_default();
+ let before = entries.len();
+ if let Err(error) = add_to_scope(entries, buckets, &field, quantity) {
rejection = Some(error);
}
+ pending.entries += entries.len() - before;
}
rejection.map_or(Ok(()), Err)
}
pub fn drain(&self) -> Vec<ScopeCounters> {
let mut pending = self.pending.lock().expect("usage counter mutex poisoned");
- std::mem::take(&mut *pending)
+ pending.entries = 0;
+ std::mem::take(&mut pending.scopes)
.into_iter()
.map(|(scope, entries)| ScopeCounters { scope, entries })
.collect()
}
+ fn counts(&self) -> (usize, usize) {
+ let pending = self.pending.lock().expect("usage counter mutex poisoned");
+ (pending.scopes.len(), pending.entries)
+ }
+
pub fn scope_count_for_records(records: &[KafkaBillingUsageRecord]) -> usize {
records
.iter()
@@ -186,44 +228,39 @@ pub struct FlushOutcome {
#[async_trait]
pub trait CounterStore: Send + Sync {
- async fn flush_scope(&self, counters: ScopeCounters) -> Result<usize, redis::RedisError>;
+ async fn flush_scope(&self, counters: &ScopeCounters) -> Result<usize, redis::RedisError>;
}
/// Cluster-aware store. Each scope is one transaction, and every key in it has the same hash tag.
pub struct RedisCounterStore {
- connections: Vec<AsyncMutex<ClusterConnection>>,
+ connection: ClusterConnection,
}
impl RedisCounterStore {
- pub async fn connect(url: &str, config: CounterConfig) -> Result<Self, redis::RedisError> {
- let client = ClusterClient::new([url])?;
- let mut connections = Vec::with_capacity(config.connections);
- for _ in 0..config.connections {
- connections.push(AsyncMutex::new(client.get_async_connection().await?));
- }
- Ok(Self { connections })
- }
-
- fn connection(&self, scope: &CounterScope) -> &AsyncMutex<ClusterConnection> {
- let mut hasher = std::collections::hash_map::DefaultHasher::new();
- scope.hash(&mut hasher);
- &self.connections[(hasher.finish() as usize) % self.connections.len()]
+ pub async fn connect(url: &str, _config: CounterConfig) -> Result<Self, redis::RedisError> {
+ let client = ClusterClientBuilder::new([url])
+ .connection_timeout(REDIS_CONNECTION_TIMEOUT)
+ .response_timeout(REDIS_RESPONSE_TIMEOUT)
+ .build()?;
+ Ok(Self {
+ connection: client.get_async_connection().await?,
+ })
}
}
#[async_trait]
impl CounterStore for RedisCounterStore {
- async fn flush_scope(&self, counters: ScopeCounters) -> Result<usize, redis::RedisError> {
+ async fn flush_scope(&self, counters: &ScopeCounters) -> Result<usize, redis::RedisError> {
let entry_count = counters.entries.len();
let mut pipeline = redis::pipe();
pipeline.atomic();
- for (entry, quantity) in counters.entries {
+ for (entry, quantity) in &counters.entries {
let key = counter_key(&counters.scope, entry.bucket);
pipeline
.cmd("HINCRBY")
.arg(&key)
- .arg(entry.field)
- .arg(quantity)
+ .arg(&entry.field)
+ .arg(*quantity)
.ignore()
.cmd("EXPIRE")
.arg(key)
@@ -231,8 +268,8 @@ impl CounterStore for RedisCounterStore {
.arg("NX")
.ignore();
}
- let mut connection = self.connection(&counters.scope).lock().await;
- pipeline.query_async::<()>(&mut *connection).await?;
+ let mut connection = self.connection.clone();
+ pipeline.query_async::<()>(&mut connection).await?;
Ok(entry_count * 2)
}
}
@@ -300,13 +337,13 @@ async fn flush_with_concurrency(
let store = Arc::clone(&store);
async move {
let entries = counters.entries.len();
- match store.flush_scope(counters).await {
+ match store.flush_scope(&counters).await {
Ok(commands) => FlushOutcome {
commands,
..FlushOutcome::default()
},
Err(error) => {
- warn!(%error, dropped_deltas = entries, "usage counter flush failed");
+ warn!(%error, dropped_deltas = entries, "usage counter write outcome is unknown");
FlushOutcome {
dropped: entries,
failed_scopes: 1,
@@ -321,10 +358,11 @@ async fn flush_with_concurrency(
.await;
results
.into_iter()
- .fold(FlushOutcome::default(), |total, next| FlushOutcome {
- commands: total.commands + next.commands,
- dropped: total.dropped + next.dropped,
- failed_scopes: total.failed_scopes + next.failed_scopes,
+ .fold(FlushOutcome::default(), |mut total, next| {
+ total.commands += next.commands;
+ total.dropped += next.dropped;
+ total.failed_scopes += next.failed_scopes;
+ total
})
}
@@ -342,55 +380,96 @@ pub fn spawn_flush_task(
let mut store: Option<Arc<dyn CounterStore>> = None;
loop {
ticker.tick().await;
- let started = Instant::now();
- if store.is_none() {
- match RedisCounterStore::connect(&redis_url, config).await {
- Ok(redis_store) => {
- store = Some(Arc::new(redis_store));
- metrics::gauge!("usage_ingestion_redis_counter_connected").set(1.0);
- }
- Err(error) => {
- let dropped = accumulator
- .drain()
- .iter()
- .map(|scope| scope.entries.len())
- .sum::<usize>();
- tracing::warn!(%error, dropped_deltas = dropped, "usage counter Redis is unavailable");
- metrics::gauge!("usage_ingestion_redis_counter_connected").set(0.0);
- metrics::counter!("usage_ingestion_redis_counter_dropped_deltas_total")
- .increment(dropped as u64);
- metrics::counter!("usage_ingestion_redis_counter_errors_total")
- .increment(1);
- continue;
- }
- }
+ flush_tick(&accumulator, &redis_url, config, &mut store).await;
+ }
+ });
+}
+
+async fn flush_tick(
+ accumulator: &CounterAccumulator,
+ redis_url: &str,
+ config: CounterConfig,
+ store: &mut Option<Arc<dyn CounterStore>>,
+) {
+ let started = Instant::now();
+ if store.is_none() {
+ match RedisCounterStore::connect(redis_url, config).await {
+ Ok(redis_store) => {
+ *store = Some(Arc::new(redis_store));
+ metrics::gauge!("usage_ingestion_redis_counter_connected").set(1.0);
}
- let counters = accumulator.drain();
- metrics::gauge!("usage_ingestion_redis_counter_accumulator_scopes")
- .set(counters.len() as f64);
- let outcome = flush_with_concurrency(
- Arc::clone(store.as_ref().unwrap()),
- counters,
- config.flush_concurrency,
- )
- .await;
- metrics::histogram!("usage_ingestion_redis_counter_flush_seconds")
- .record(started.elapsed().as_secs_f64());
- metrics::counter!("usage_ingestion_redis_counter_commands_flushed_total")
- .increment(outcome.commands as u64);
- metrics::counter!("usage_ingestion_redis_counter_dropped_deltas_total")
- .increment(outcome.dropped as u64);
- if outcome.failed_scopes > 0 {
+ Err(error) => {
+ let (retained_scopes, retained_deltas) = accumulator.counts();
+ tracing::warn!(%error, retained_deltas, "usage counter Redis is unavailable");
+ metrics::gauge!("usage_ingestion_redis_counter_connected").set(0.0);
+ metrics::gauge!("usage_ingestion_redis_counter_accumulator_scopes")
+ .set(retained_scopes as f64);
+ metrics::gauge!("usage_ingestion_redis_counter_accumulator_entries")
+ .set(retained_deltas as f64);
metrics::counter!("usage_ingestion_redis_counter_errors_total").increment(1);
- store = None;
+ return;
}
}
- });
+ }
+ let counters = accumulator.drain();
+ metrics::gauge!("usage_ingestion_redis_counter_accumulator_scopes").set(counters.len() as f64);
+ metrics::gauge!("usage_ingestion_redis_counter_accumulator_entries").set(
+ counters
+ .iter()
+ .map(|counters| counters.entries.len())
+ .sum::<usize>() as f64,
+ );
+ let outcome = flush_with_concurrency(
+ Arc::clone(store.as_ref().unwrap()),
+ counters,
+ config.flush_concurrency,
+ )
+ .await;
+ let (pending_scopes, pending_entries) = accumulator.counts();
+ metrics::gauge!("usage_ingestion_redis_counter_accumulator_scopes").set(pending_scopes as f64);
+ metrics::gauge!("usage_ingestion_redis_counter_accumulator_entries")
+ .set(pending_entries as f64);
+ metrics::histogram!("usage_ingestion_redis_counter_flush_seconds")
+ .record(started.elapsed().as_secs_f64());
+ metrics::counter!("usage_ingestion_redis_counter_commands_flushed_total")
+ .increment(outcome.commands as u64);
+ metrics::counter!("usage_ingestion_redis_counter_dropped_deltas_total")
+ .increment(outcome.dropped as u64);
+ if outcome.failed_scopes > 0 {
+ metrics::gauge!("usage_ingestion_redis_counter_connected").set(0.0);
+ metrics::counter!("usage_ingestion_redis_counter_errors_total").increment(1);
+ *store = None;
+ }
}
#[cfg(test)]
mod tests {
use super::*;
+ use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter};
+
+ struct FailingStore;
+
+ #[async_trait]
+ impl CounterStore for FailingStore {
+ async fn flush_scope(&self, _counters: &ScopeCounters) -> Result<usize, redis::RedisError> {
+ Err(redis::RedisError::from((
+ redis::ErrorKind::IoError,
+ "test write failure",
+ )))
+ }
+ }
+
+ fn gauge(snapshotter: &Snapshotter, name: &str) -> Option<f64> {
+ snapshotter
+ .snapshot()
+ .into_vec()
+ .into_iter()
+ .find(|(key, _, _, _)| key.key().name() == name)
+ .and_then(|(_, _, _, value)| match value {
+ DebugValue::Gauge(value) => Some(value.into_inner()),
+ _ => None,
+ })
+ }
#[test]
fn hashes_stay_with_their_scope_and_accumulator_merges_series() {
@@ -432,7 +511,7 @@ mod tests {
}
#[test]
- fn rejects_out_of_range_timestamps_and_overflowing_deltas() {
+ fn rejects_out_of_range_timestamps_overflow_and_capacity() {
let organization_id = Uuid::nil();
let accumulator = CounterAccumulator::default();
let now = Utc::now();
@@ -467,5 +546,98 @@ mod tests {
overflow.add(43, organization_id, "events", "event", 1, now),
Err(CounterAddError::Overflow)
);
+ let full = CounterAccumulator::new(3);
+ assert_eq!(
+ full.add(44, organization_id, "events", "event", 1, now),
+ Err(CounterAddError::Capacity)
+ );
+ assert!(full.drain().is_empty());
+ }
+
+ #[test]
+ fn connection_failure_retains_pending_deltas() {
+ let recorder = DebuggingRecorder::new();
+ let snapshotter = recorder.snapshotter();
+ let accumulator = CounterAccumulator::default();
+ accumulator
+ .add(42, Uuid::nil(), "events", "event", 1, Utc::now())
+ .unwrap();
+ let mut store = None;
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+
+ metrics::with_local_recorder(&recorder, || {
+ runtime.block_on(flush_tick(
+ &accumulator,
+ "://invalid",
+ CounterConfig::default(),
+ &mut store,
+ ));
+ });
+
+ assert!(store.is_none());
+ assert_eq!(
+ gauge(
+ &snapshotter,
+ "usage_ingestion_redis_counter_accumulator_entries"
+ ),
+ Some(4.0)
+ );
+ let retained = accumulator.drain();
+ assert_eq!(retained.len(), 2);
+ assert_eq!(
+ retained
+ .iter()
+ .map(|counters| counters.entries.len())
+ .sum::<usize>(),
+ 4
+ );
+ }
+
+ #[test]
+ fn write_failure_drops_deltas_and_marks_the_store_disconnected() {
+ let recorder = DebuggingRecorder::new();
+ let snapshotter = recorder.snapshotter();
+ let accumulator = CounterAccumulator::default();
+ accumulator
+ .add(42, Uuid::nil(), "events", "event", 1, Utc::now())
+ .unwrap();
+ let mut store: Option<Arc<dyn CounterStore>> = Some(Arc::new(FailingStore));
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+
+ metrics::with_local_recorder(&recorder, || {
+ runtime.block_on(flush_tick(
+ &accumulator,
+ "unused",
+ CounterConfig::default(),
+ &mut store,
+ ));
+ });
+
+ assert!(store.is_none());
+ assert_eq!(
+ accumulator
+ .drain()
+ .iter()
+ .map(|counters| counters.entries.len())
+ .sum::<usize>(),
+ 0
+ );
+ assert_eq!(
+ gauge(&snapshotter, "usage_ingestion_redis_counter_connected"),
+ Some(0.0)
+ );
+ assert_eq!(
+ gauge(
+ &snapshotter,
+ "usage_ingestion_redis_counter_accumulator_entries"
+ ),
+ Some(0.0)
+ );
}
}