: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(usage-ingestion): flush usage counters without scripts (#95935)
Ben White3825bceacd68
diff --git a/rust/usage-ingestion/README.md b/rust/usage-ingestion/README.mdindex 50ab22c8e813..91417a52b937 100644--- a/rust/usage-ingestion/README.md+++ b/rust/usage-ingestion/README.md@@ -38,11 +38,10 @@ 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 theunavailable interval's deltas. Counter timestamps are limited to seven days-behind and 24 hours ahead of the current time. Redis connections,-flush concurrency, and the per-scope/bucket series cap default to 16 and can-be tuned with `USAGE_INGESTION_REDIS_CONNECTIONS`,-`USAGE_INGESTION_REDIS_FLUSH_CONCURRENCY`, and-`USAGE_INGESTION_REDIS_MAX_SERIES_PER_BUCKET`.+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+`USAGE_INGESTION_REDIS_FLUSH_CONCURRENCY`.The projection stores additive deltas, not usage record identities. Retryingafter an accepted response or correcting a durable record can thereforediff --git a/rust/usage-ingestion/src/config.rs b/rust/usage-ingestion/src/config.rsindex 4617612ed2c8..a35e4afcfdc9 100644--- a/rust/usage-ingestion/src/config.rs+++ b/rust/usage-ingestion/src/config.rs@@ -47,8 +47,6 @@ pub struct Config {pub redis_connections: usize,#[envconfig(from = "USAGE_INGESTION_REDIS_FLUSH_CONCURRENCY", default = "16")]pub redis_flush_concurrency: usize,- #[envconfig(from = "USAGE_INGESTION_REDIS_MAX_SERIES_PER_BUCKET", default = "16")]- pub redis_max_series_per_bucket: usize,// Overridable so a test environment can use the suffixed topic its Kafka engine table reads.#[envconfig(from = "USAGE_INGESTION_TOPIC",@@ -80,9 +78,6 @@ impl Config {if self.redis_flush_concurrency == 0 {return Err("USAGE_INGESTION_REDIS_FLUSH_CONCURRENCY must be positive".to_string());}- if self.redis_max_series_per_bucket == 0 {- return Err("USAGE_INGESTION_REDIS_MAX_SERIES_PER_BUCKET must be positive".to_string());- }// A few seconds would make every producer spend its time reconnecting.if self.grpc_max_connection_age_secs > 0 && self.grpc_max_connection_age_secs < 10 {return Err(@@ -96,7 +91,6 @@ impl Config {CounterConfig {connections: self.redis_connections,flush_concurrency: self.redis_flush_concurrency,- max_series_per_bucket: self.redis_max_series_per_bucket,}}@@ -151,7 +145,6 @@ mod tests {redis_flush_interval_seconds: 15,redis_connections: 16,redis_flush_concurrency: 16,- redis_max_series_per_bucket: 16,topic: "clickhouse_billing_usage_records".to_string(),grpc_max_connection_age_secs: 60,}@@ -214,13 +207,6 @@ mod tests {},"USAGE_INGESTION_REDIS_FLUSH_CONCURRENCY must be positive",),- (- Config {- redis_max_series_per_bucket: 0,- ..config()- },- "USAGE_INGESTION_REDIS_MAX_SERIES_PER_BUCKET must be positive",- ),] {assert_eq!(config.validate(), Err(expected.to_string()));}diff --git a/rust/usage-ingestion/src/counters.rs b/rust/usage-ingestion/src/counters.rsindex 239214b2491c..767f22ca4dfc 100644--- a/rust/usage-ingestion/src/counters.rs+++ b/rust/usage-ingestion/src/counters.rs@@ -18,24 +18,13 @@ 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_SERIES_PER_BUCKET: usize = 16;const MAX_PAST_TIMESTAMP: ChronoDuration = ChronoDuration::days(7);const MAX_FUTURE_TIMESTAMP: ChronoDuration = ChronoDuration::hours(24);-const INCREMENT_COUNTER: &str = r#"-local exists = redis.call('HEXISTS', KEYS[1], ARGV[1])-if exists == 0 and redis.call('HLEN', KEYS[1]) >= tonumber(ARGV[4]) then- return 0-end-redis.call('HINCRBY', KEYS[1], ARGV[1], ARGV[2])-redis.call('EXPIRE', KEYS[1], ARGV[3], 'NX')-return 1-"#;#[derive(Clone, Copy, Debug)]pub struct CounterConfig {pub connections: usize,pub flush_concurrency: usize,- pub max_series_per_bucket: usize,}impl Default for CounterConfig {@@ -43,7 +32,6 @@ impl Default for CounterConfig {Self {connections: DEFAULT_CONNECTIONS,flush_concurrency: DEFAULT_FLUSH_CONCURRENCY,- max_series_per_bucket: DEFAULT_MAX_SERIES_PER_BUCKET,}}}@@ -99,7 +87,6 @@ struct CounterEntry {#[derive(Debug, PartialEq, Eq)]pub enum CounterAddError {TimestampOutOfRange,- TooManySeries,Overflow,}@@ -107,7 +94,6 @@ impl CounterAddError {pub fn reason(&self) -> &'static str {match self {Self::TimestampOutOfRange => "timestamp_out_of_range",- Self::TooManySeries => "too_many_series",Self::Overflow => "overflow",}}@@ -120,25 +106,12 @@ 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>>>,- max_series_per_bucket: usize,-}--impl Default for CounterAccumulator {- fn default() -> Self {- Self::new(DEFAULT_MAX_SERIES_PER_BUCKET)- }}impl CounterAccumulator {- pub fn new(max_series_per_bucket: usize) -> Self {- Self {- pending: Mutex::default(),- max_series_per_bucket,- }- }-pub fn add_record(&self, record: &KafkaBillingUsageRecord) -> Result<(), CounterAddError> {// TODO: Pass trusted capture time from event-derived producers into `usage_timestamp`.// Batch-flush time rebuckets lagged records into wrong quota windows; customer event timestamps must not be used.@@ -174,15 +147,9 @@ impl CounterAccumulator {let mut pending = self.pending.lock().expect("usage counter mutex poisoned");let mut rejection = None;for scope in scopes {- // An organization aggregates the series of every team below it, so it saturates- // first. Rejecting per scope keeps the team projection alive when it does.- if let Err(error) = add_to_scope(- pending.entry(scope).or_default(),- buckets,- &field,- quantity,- self.max_series_per_bucket,- ) {+ if let Err(error) =+ add_to_scope(pending.entry(scope).or_default(), buckets, &field, quantity)+ {rejection = Some(error);}}@@ -211,18 +178,9 @@ impl CounterAccumulator {}}-/// A flushed scope: commands sent, and deltas the Redis-side series cap refused.-#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]-pub struct ScopeFlush {- pub commands: usize,- pub capped: usize,-}-#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]pub struct FlushOutcome {pub commands: usize,- /// Refused by the series cap, which is the projection working as designed.- pub capped: usize,/// Lost because a scope's transaction failed.pub dropped: usize,pub failed_scopes: usize,@@ -230,13 +188,12 @@ pub struct FlushOutcome {#[async_trait]pub trait CounterStore: Send + Sync {- async fn flush_scope(&self, counters: ScopeCounters) -> Result<ScopeFlush, 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>>,- max_series_per_bucket: usize,}impl RedisCounterStore {@@ -246,10 +203,7 @@ impl RedisCounterStore {for _ in 0..config.connections {connections.push(AsyncMutex::new(client.get_async_connection().await?));}- Ok(Self {- connections,- max_series_per_bucket: config.max_series_per_bucket,- })+ Ok(Self { connections })}fn connection(&self, scope: &CounterScope) -> &AsyncMutex<ClusterConnection> {@@ -261,29 +215,27 @@ impl RedisCounterStore {#[async_trait]impl CounterStore for RedisCounterStore {- async fn flush_scope(&self, counters: ScopeCounters) -> Result<ScopeFlush, 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 {let key = counter_key(&counters.scope, entry.bucket);pipeline- .cmd("EVAL")- .arg(INCREMENT_COUNTER)- .arg(1)+ .cmd("HINCRBY").arg(&key)- .arg(&entry.field)+ .arg(entry.field).arg(quantity)+ .ignore()+ .cmd("EXPIRE")+ .arg(key).arg(entry.bucket.ttl_seconds())- .arg(self.max_series_per_bucket);+ .arg("NX")+ .ignore();}let mut connection = self.connection(&counters.scope).lock().await;- let accepted = pipeline.query_async::<Vec<i64>>(&mut *connection).await?;- let accepted = accepted.into_iter().filter(|result| *result == 1).count();- Ok(ScopeFlush {- commands: accepted * 2,- capped: entry_count - accepted,- })+ pipeline.query_async::<()>(&mut *connection).await?;+ Ok(entry_count * 2)}}@@ -305,7 +257,6 @@ fn add_to_scope(buckets: [Bucket; 2],field: &str,quantity: i64,- max_series_per_bucket: usize,) -> Result<(), CounterAddError> {let mut totals = [0_i64; 2];for (bucket, total) in buckets.into_iter().zip(&mut totals) {@@ -317,17 +268,7 @@ fn add_to_scope(Some(current) => current.checked_add(quantity).ok_or(CounterAddError::Overflow)?,- None => {- if entries- .keys()- .filter(|existing| existing.bucket == bucket)- .count()- >= max_series_per_bucket- {- return Err(CounterAddError::TooManySeries);- }- quantity- }+ None => quantity,};}for (bucket, total) in buckets.into_iter().zip(totals) {@@ -362,9 +303,8 @@ async fn flush_with_concurrency(async move {let entries = counters.entries.len();match store.flush_scope(counters).await {- Ok(flushed) => FlushOutcome {- commands: flushed.commands,- capped: flushed.capped,+ Ok(commands) => FlushOutcome {+ commands,..FlushOutcome::default()},Err(error) => {@@ -385,7 +325,6 @@ async fn flush_with_concurrency(.into_iter().fold(FlushOutcome::default(), |total, next| FlushOutcome {commands: total.commands + next.commands,- capped: total.capped + next.capped,dropped: total.dropped + next.dropped,failed_scopes: total.failed_scopes + next.failed_scopes,})@@ -443,12 +382,6 @@ pub fn spawn_flush_task(.increment(outcome.commands as u64);metrics::counter!("usage_ingestion_redis_counter_dropped_deltas_total").increment(outcome.dropped as u64);- metrics::counter!(- "usage_ingestion_redis_counter_rejected_deltas_total",- "reason" => "too_many_series"- )- .increment(outcome.capped as u64);- // Only a failed transaction means the connection is suspect. A capped series does not.if outcome.failed_scopes > 0 {metrics::counter!("usage_ingestion_redis_counter_errors_total").increment(1);store = None;@@ -494,7 +427,7 @@ mod tests {}#[test]- fn bounds_series_timestamps_and_deltas() {+ fn rejects_out_of_range_timestamps_and_overflowing_deltas() {let organization_id = Uuid::nil();let accumulator = CounterAccumulator::default();let now = Utc::now();@@ -521,23 +454,6 @@ mod tests {),Err(CounterAddError::TimestampOutOfRange));- for index in 0..DEFAULT_MAX_SERIES_PER_BUCKET {- accumulator- .add(- 42,- organization_id,- &format!("events_{index}"),- "event",- 1,- now,- )- .unwrap();- }- assert_eq!(- accumulator.add(42, organization_id, "one_too_many", "event", 1, now),- Err(CounterAddError::TooManySeries)- );-let overflow = CounterAccumulator::default();overflow.add(43, organization_id, "events", "event", i64::MAX, now)@@ -547,35 +463,4 @@ mod tests {Err(CounterAddError::Overflow));}-- #[test]- fn saturated_organization_still_lets_a_team_count() {- let organization_id = Uuid::nil();- let accumulator = CounterAccumulator::default();- let now = Utc::now();- for index in 0..DEFAULT_MAX_SERIES_PER_BUCKET {- accumulator- .add(- index as i64 + 1,- organization_id,- &format!("events_{index}"),- "event",- 1,- now,- )- .unwrap();- }-- assert_eq!(- accumulator.add(99, organization_id, "one_too_many", "event", 7, now),- Err(CounterAddError::TooManySeries)- );- let drained = accumulator.drain();- let team = drained- .iter()- .find(|counters| counters.scope == CounterScope::Team(99))- .expect("the team scope should still hold its own series");- assert_eq!(team.entries.len(), 2);- assert!(team.entries.values().all(|quantity| *quantity == 7));- }}diff --git a/rust/usage-ingestion/src/main.rs b/rust/usage-ingestion/src/main.rsindex 070ecb2a7847..ca9df8e2c9b0 100644--- a/rust/usage-ingestion/src/main.rs+++ b/rust/usage-ingestion/src/main.rs@@ -79,11 +79,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let producer = create_kafka_producer(&kafka_config, producer_liveness).await?;let grpc_max_connection_age = config.grpc_max_connection_age();let redis_counter_config = config.redis_counter_config();- let counters = (!config.redis_url.is_empty()).then(|| {- Arc::new(CounterAccumulator::new(- redis_counter_config.max_series_per_bucket,- ))- });+ let counters = (!config.redis_url.is_empty()).then(|| Arc::new(CounterAccumulator::default()));let service = UsageIngestionService::new(producer,resolver,diff --git a/rust/usage-ingestion/tests/counters.rs b/rust/usage-ingestion/tests/counters.rsindex 1edd0602b84f..dad17c328245 100644--- a/rust/usage-ingestion/tests/counters.rs+++ b/rust/usage-ingestion/tests/counters.rs@@ -18,6 +18,72 @@ fn redis_url() -> String {.unwrap_or_else(|_| "redis://127.0.0.1:6390".to_string())}+async fn store() -> Arc<dyn CounterStore> {+ Arc::new(+ RedisCounterStore::connect(&redis_url(), Default::default())+ .await+ .expect("failed to connect to Valkey Cluster"),+ )+}++/// How many times the node ran one command. `INFO commandstats` reports+/// `cmdstat_multi:calls=12,usec=...`, and an unused command has no line at all.+async fn command_calls(command: &str) -> u64 {+ let client = redis::Client::open(redis_url()).expect("invalid Valkey URL");+ let mut connection = client+ .get_multiplexed_async_connection()+ .await+ .expect("failed to connect to the Valkey node");+ let stats: String = redis::cmd("INFO")+ .arg("commandstats")+ .query_async(&mut connection)+ .await+ .expect("the node did not report its command stats");+ let prefix = format!("cmdstat_{command}:calls=");+ stats+ .lines()+ .find_map(|line| line.trim().strip_prefix(&prefix))+ .map_or(0, |calls| {+ calls+ .split(',')+ .next()+ .and_then(|calls| calls.parse().ok())+ .expect("the node reported an unreadable call count")+ })+}++/// ElastiCache Serverless supports transactions but refuses scripts inside them.+#[tokio::test]+#[ignore = "requires the cluster-enabled Valkey from docker-compose.dev.yml"]+async fn a_flush_uses_a_transaction_without_scripts() {+ let accumulator = CounterAccumulator::default();+ accumulator+ .add(+ 2_000_000 + (Uuid::new_v4().as_u128() % 1_000_000) as i64,+ Uuid::new_v4(),+ "script_free_flush",+ "event",+ 1,+ Utc::now(),+ )+ .expect("test record should enter the counter accumulator");+ let scripts = command_calls("eval").await;+ let transactions = command_calls("multi").await;++ let outcome = flush(store().await, accumulator.drain()).await;++ assert_eq!(outcome.dropped, 0);+ assert_eq!(+ command_calls("eval").await,+ scripts,+ "the flush ran a script, which ElastiCache Serverless refuses inside MULTI"+ );+ assert!(+ command_calls("multi").await > transactions,+ "the flush did not use a transaction"+ );+}+#[tokio::test]#[ignore = "requires the cluster-enabled Valkey from docker-compose.dev.yml"]async fn counters_are_atomic_per_scope_and_do_not_cross_slots() {@@ -41,14 +107,9 @@ async fn counters_are_atomic_per_scope_and_do_not_cross_slots() {.expect("test record should enter the counter accumulator");}- let store: Arc<dyn CounterStore> = Arc::new(- RedisCounterStore::connect(&redis_url(), Default::default())- .await- .expect("failed to connect to Valkey Cluster"),- );+ let store = store().await;let outcome = flush(Arc::clone(&store), accumulator.drain()).await;assert_eq!(outcome.dropped, 0);- assert_eq!(outcome.capped, 0);// 1,024 teams plus one shared organization; hour + day, HINCRBY + EXPIRE NX each.assert_eq!(outcome.commands, (SCOPES as usize + 1) * 4);@@ -122,7 +183,6 @@ async fn counters_are_atomic_per_scope_and_do_not_cross_slots() {.expect("test retry should enter the counter accumulator");let retry_outcome = flush(Arc::clone(&store), retry.drain()).await;assert_eq!(retry_outcome.dropped, 0);- assert_eq!(retry_outcome.capped, 0);let retried_hourly_ttl: i64 = redis::cmd("TTL").arg(&hour_key).query_async(&mut connection)diff --git a/rust/usage-ingestion/tests/load.rs b/rust/usage-ingestion/tests/load.rsindex d1ca3728510b..27f4757b7c18 100644--- a/rust/usage-ingestion/tests/load.rs+++ b/rust/usage-ingestion/tests/load.rs@@ -218,8 +218,7 @@ async fn sustains_thousands_of_concurrent_requests() {let outcome = flush(Arc::clone(&store), accumulator.drain()).await;assert_eq!(- (outcome.dropped, outcome.capped),- (0, 0),+ outcome.dropped, 0,"Valkey dropped counter deltas under request load");assert_eq!(