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(usage): add the usage-ingestion grpc service (#86962)

Ben Whitea2dd19715228
diff --git a/.github/rust-images.yml b/.github/rust-images.yml
index cffc76b6760d..024280d49eb4 100644
--- a/.github/rust-images.yml
+++ b/.github/rust-images.yml
@@ -129,3 +129,7 @@
- image: hypercache-server
dockerfile: ./rust/Dockerfile
project: plc74nsj8z
+
+- image: usage-ingestion
+ dockerfile: ./rust/Dockerfile
+ project: g9w71772m7
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 012b1fd45ccd..0a5e5f768204 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -182,6 +182,8 @@ jobs:
"property-vals-rs": 70,
"replay-anonymizer-node": 5,
"serve-metrics": 5,
+ "usage-ingestion": 70,
+ "usage-ingestion-proto": 5,
}
# Filter to only affected crates when selective builds are active.
@@ -498,6 +500,16 @@ jobs:
if [ "$pkg" = "cymbal" ]; then
run_nextest cymbal-ignored -p cymbal -E 'test(rate_limiting)' --run-ignored only --test-threads=1
fi
+ # usage-ingestion's e2e tests are #[ignore]'d (they need Kafka and ClickHouse).
+ # This job has both, on the suffixed schema `setup_test_environment` created.
+ # Single-threaded so the load test's throughput measurement stays clean. The
+ # Cargo.toml guard keeps this a no-op on branches predating the crate.
+ if [ "$pkg" = "usage-ingestion" ] && [ -f usage-ingestion/Cargo.toml ]; then
+ USAGE_INGESTION_E2E_CLICKHOUSE_DATABASE=posthog_test \
+ USAGE_INGESTION_E2E_TOPIC=clickhouse_billing_usage_records_test \
+ USAGE_INGESTION_E2E_LOAD_REQUESTS=2000 \
+ run_nextest usage-ingestion-ignored -p usage-ingestion --run-ignored only --test-threads=1
+ fi
echo "::endgroup::"
done
diff --git a/.github/workflows/rust-docker-build.yml b/.github/workflows/rust-docker-build.yml
index 9103d2b7a913..0b45de935ecd 100644
--- a/.github/workflows/rust-docker-build.yml
+++ b/.github/workflows/rust-docker-build.yml
@@ -207,6 +207,9 @@ jobs:
- release: hypercache-server
digest_key: hypercache-server
values_key: image
+ - release: usage-ingestion
+ digest_key: usage-ingestion
+ values_key: image
steps:
- name: check if image was built
id: check
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index da9fc2220b1d..5d1b2bdaefbc 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -404,6 +404,16 @@ procs:
layer: Ingestion pipeline
tech: Rust
+ usage-ingestion:
+ shell: |-
+ bin/wait-for-docker && \
+ bin/start-rust-service usage-ingestion
+ capability: event_ingestion
+ ready_pattern: 'Starting usage-ingestion gRPC service'
+ groups:
+ layer: Ingestion pipeline
+ tech: Rust
+
batch-import-worker:
shell: |-
bin/wait-for-docker && \
diff --git a/bin/start-rust-service b/bin/start-rust-service
index 4482c586cbfe..2a9d8fbf4e6c 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -246,6 +246,14 @@ case "$RS_SVC" in
export DEBUG=1
;;
+ usage-ingestion)
+ export RUST_LOG=debug,rdkafka=warn
+ export RUST_BACKTRACE=1
+ export USAGE_INGESTION_DATABASE_URL="${USAGE_INGESTION_DATABASE_URL:-$DEFAULT_PG}"
+ export KAFKA_HOSTS="$DEFAULT_KAFKA"
+ export DEBUG=1
+ ;;
+
batch-import-worker)
SQLX_QUERY_LEVEL=${SQLX_QUERY_LEVEL:-warn}
export RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL,rdkafka=warn
diff --git a/docker-compose.base.yml b/docker-compose.base.yml
index e501f3893097..8458fffdc0d2 100644
--- a/docker-compose.base.yml
+++ b/docker-compose.base.yml
@@ -494,6 +494,24 @@ services:
COOKIELESS_REDIS_HOST: redis7
COOKIELESS_REDIS_PORT: 6379
+ usage-ingestion:
+ image: ghcr.io/posthog/posthog/usage-ingestion:master
+ build:
+ context: rust/
+ args:
+ BIN: usage-ingestion
+ restart: on-failure
+ healthcheck:
+ test: ['CMD', 'curl', '-f', 'http://localhost:7144/_readiness']
+ interval: 5s
+ timeout: 5s
+ retries: 12
+ start_period: 10s
+ environment:
+ USAGE_INGESTION_DATABASE_URL: 'postgres://posthog:posthog@db:5432/posthog'
+ KAFKA_HOSTS: 'kafka:9092'
+ RUST_LOG: 'info'
+
personhog-replica:
image: ghcr.io/posthog/posthog/personhog-replica:master
build:
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index b71e7b96ca81..fa15402743af 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -695,6 +695,22 @@ services:
REDIS_COMPRESSION_ENABLED: 'true'
INTERNAL_REQUEST_TOKEN: 'dev-internal-token'
+ usage-ingestion:
+ extends:
+ file: docker-compose.base.yml
+ service: usage-ingestion
+ ports:
+ - '7143:7143'
+ - '7144:7144'
+ depends_on:
+ db:
+ condition: service_healthy
+ kafka:
+ condition: service_healthy
+ # Keeps a bare `up` from building an image that is not published yet.
+ profiles:
+ - ingestion
+
# Temporal containers
elasticsearch:
extends:
diff --git a/proto/usage_ingestion/v1/service.proto b/proto/usage_ingestion/v1/service.proto
new file mode 100644
index 000000000000..5c1d4b6287e0
--- /dev/null
+++ b/proto/usage_ingestion/v1/service.proto
@@ -0,0 +1,47 @@
+syntax = "proto3";
+
+package usage_ingestion.v1;
+
+// UsageIngestion accepts usage records for durable analytics. Producers must reuse
+// record_id when retrying a record. The service preserves the producer's timestamp and
+// assigns insertion time when it publishes.
+//
+// IngestBillingUsage carries tenant-billable usage: exact, idempotent, retained
+// indefinitely. Cost and resource metering is a separate RPC and table.
+service UsageIngestion {
+ rpc IngestBillingUsage(IngestBillingUsageRequest) returns (IngestBillingUsageResponse);
+}
+
+// Fields 1-5 are the record's identity, in the order the storage sorting key uses them:
+// (team_id, toDate(timestamp), producer_id, usage_key, record_id). A retry reuses all five
+// and collapses to one row. Correcting a quantity means re-sending the same identity, and
+// the last send wins.
+message BillingUsageRecord {
+ // The service owns organization attribution: it resolves the organization from team_id,
+ // so producers cannot supply one.
+ int64 team_id = 1;
+
+ // Stamp this from the producer's own clock when it emits, never from a customer payload.
+ // It is part of the identity, so a value a customer controls would let them decide
+ // whether their own records deduplicate.
+ int64 timestamp_ms = 2;
+
+ string producer_id = 3;
+ string usage_key = 4;
+ string record_id = 5;
+
+ int64 quantity = 6;
+ string unit = 7;
+}
+
+message IngestBillingUsageRequest {
+ repeated BillingUsageRecord records = 1;
+}
+
+message IngestBillingUsageResponse {
+ // The service validates a whole batch before producing, so validation failures accept no
+ // records. The RPC waits for Kafka delivery confirmation, so callers must use it off their
+ // request-critical path. A retry after an unavailable response is safe because record_id is
+ // the deduplication identity, including when Kafka delivered only part of the batch.
+ repeated string accepted_record_ids = 1;
+}
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 98f84b5ff96a..f939222d9c84 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -13323,6 +13323,45 @@ version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
+[[package]]
+name = "usage-ingestion"
+version = "0.1.0"
+dependencies = [
+ "async-trait",
+ "axum 0.7.9",
+ "chrono",
+ "common-database",
+ "common-kafka",
+ "common-liveness",
+ "envconfig",
+ "health",
+ "metrics",
+ "metrics-exporter-prometheus",
+ "moka",
+ "rdkafka",
+ "reqwest 0.12.28",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.18",
+ "tokio",
+ "tokio-stream",
+ "tonic 0.12.3",
+ "tracing",
+ "tracing-subscriber",
+ "usage-ingestion-proto",
+ "uuid",
+]
+
+[[package]]
+name = "usage-ingestion-proto"
+version = "0.1.0"
+dependencies = [
+ "prost 0.13.5",
+ "tonic 0.12.3",
+ "tonic-build 0.12.3",
+]
+
[[package]]
name = "utf8-zero"
version = "0.8.1"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 4a9795adac8c..f6c1a33ee5b4 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -43,6 +43,8 @@ members = [
"replay-anonymizer-node",
"cymbal",
"cymbal-proto",
+ "usage-ingestion-proto",
+ "usage-ingestion",
"embedding-worker",
"common/geoip",
"common/hogvm",
diff --git a/rust/affected-services/determinator-rules.toml b/rust/affected-services/determinator-rules.toml
index b2b8a90aa70c..d1d52f2b562e 100644
--- a/rust/affected-services/determinator-rules.toml
+++ b/rust/affected-services/determinator-rules.toml
@@ -39,6 +39,7 @@ mark-changed = [
"cymbal-proto",
"ingestion-worker-proto",
"prometheus-rw-proto",
+ "usage-ingestion-proto",
]
# Hypercache contract: Python serializer changes may break Rust deserialization.
diff --git a/rust/usage-ingestion-proto/Cargo.toml b/rust/usage-ingestion-proto/Cargo.toml
new file mode 100644
index 000000000000..5fe63c1edde1
--- /dev/null
+++ b/rust/usage-ingestion-proto/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "usage-ingestion-proto"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[dependencies]
+prost = { workspace = true }
+tonic = { workspace = true }
+
+[build-dependencies]
+tonic-build = { workspace = true }
+
+[package.metadata.cargo-shear]
+ignored = ["prost"]
+
+[lints]
+workspace = true
diff --git a/rust/usage-ingestion-proto/build.rs b/rust/usage-ingestion-proto/build.rs
new file mode 100644
index 000000000000..199a02f007c6
--- /dev/null
+++ b/rust/usage-ingestion-proto/build.rs
@@ -0,0 +1,12 @@
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let proto_root = std::env::var("PROTO_ROOT").unwrap_or_else(|_| "../../proto".to_string());
+
+ tonic_build::configure()
+ .build_server(true)
+ .build_client(true)
+ .compile_protos(
+ &[format!("{proto_root}/usage_ingestion/v1/service.proto")],
+ &[proto_root],
+ )?;
+ Ok(())
+}
diff --git a/rust/usage-ingestion-proto/src/lib.rs b/rust/usage-ingestion-proto/src/lib.rs
new file mode 100644
index 000000000000..89be149a9541
--- /dev/null
+++ b/rust/usage-ingestion-proto/src/lib.rs
@@ -0,0 +1,5 @@
+pub mod usage_ingestion {
+ pub mod v1 {
+ tonic::include_proto!("usage_ingestion.v1");
+ }
+}
diff --git a/rust/usage-ingestion-proto/tests/contract.rs b/rust/usage-ingestion-proto/tests/contract.rs
new file mode 100644
index 000000000000..1606c7e2b112
--- /dev/null
+++ b/rust/usage-ingestion-proto/tests/contract.rs
@@ -0,0 +1,25 @@
+use prost::Message;
+use usage_ingestion_proto::usage_ingestion::v1::{BillingUsageRecord, IngestBillingUsageRequest};
+
+#[test]
+fn usage_record_round_trips_every_field() {
+ let request = IngestBillingUsageRequest {
+ records: vec![BillingUsageRecord {
+ record_id: "018f7c8e-4c08-7c5e-9bc0-15c9f5cc9f42".to_string(),
+ producer_id: "feature-flags".to_string(),
+ team_id: 42,
+ usage_key: "feature_flag_requests".to_string(),
+ unit: "request".to_string(),
+ quantity: 10,
+ timestamp_ms: 1_700_000_000_000,
+ }],
+ };
+
+ let decoded = IngestBillingUsageRequest::decode(request.encode_to_vec().as_slice()).unwrap();
+ let record = decoded.records.first().unwrap();
+
+ assert_eq!(record.team_id, 42);
+ assert_eq!(record.timestamp_ms, 1_700_000_000_000);
+ assert_eq!(record.record_id, "018f7c8e-4c08-7c5e-9bc0-15c9f5cc9f42");
+ assert_eq!(record.quantity, 10);
+}
diff --git a/rust/usage-ingestion/Cargo.toml b/rust/usage-ingestion/Cargo.toml
new file mode 100644
index 000000000000..c9325b82efb7
--- /dev/null
+++ b/rust/usage-ingestion/Cargo.toml
@@ -0,0 +1,36 @@
+[package]
+name = "usage-ingestion"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[dependencies]
+async-trait = { workspace = true }
+axum = { workspace = true }
+chrono = { workspace = true }
+common-database = { path = "../common/database" }
+common-kafka = { path = "../common/kafka" }
+common-liveness = { path = "../common/liveness" }
+envconfig = { workspace = true }
+health = { path = "../common/health" }
+metrics = { workspace = true }
+metrics-exporter-prometheus = { workspace = true }
+moka = { workspace = true }
+rdkafka = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true }
+thiserror = { workspace = true }
+tokio = { workspace = true }
+tonic = { workspace = true }
+tracing = { workspace = true }
+tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
+usage-ingestion-proto = { path = "../usage-ingestion-proto" }
+uuid = { workspace = true }
+
+[dev-dependencies]
+reqwest = { workspace = true }
+tokio-stream = { version = "0.1", features = ["net"] }
+
+[lints]
+workspace = true
diff --git a/rust/usage-ingestion/README.md b/rust/usage-ingestion/README.md
new file mode 100644
index 000000000000..ad6d8d4943f2
--- /dev/null
+++ b/rust/usage-ingestion/README.md
@@ -0,0 +1,128 @@
+# Usage ingestion service
+
+`usage-ingestion` is the internal gRPC gateway for durable usage records. It
+validates records, resolves an omitted organization ID from core PostgreSQL,
+caches successful lookups in memory for five minutes, and publishes
+JSONEachRow messages to `clickhouse_billing_usage_records`.
+
+The service is the shared gateway for every usage stream; `IngestBillingUsage`
+is the tenant-billing stream, which is exact, idempotent, and retained
+indefinitely. Cost and resource metering gets its own RPC, topic, and table
+rather than sharing these — see `.context/usage-ingestion-implementation-plan.md`.
+
+The RPC acknowledges only after Kafka confirms every record. Producers must call
+it asynchronously, outside request-critical paths, and retry an unavailable response
+with the same record identity and event timestamp.
+The service validates the complete batch before producing, so validation failure accepts
+no records. Kafka may have delivered part of a batch before an unavailable response, but
+retrying the complete batch is safe because records are idempotent.
+
+Run it in the local Docker stack with:
+
+```sh
+docker compose -f docker-compose.dev.yml up usage-ingestion
+```
+
+The gRPC endpoint listens on port 7143 and metrics/readiness on port 7144.
+PostgreSQL is the source of truth. The service retains successful team-to-
+organization lookups in its process-local cache for five minutes.
+
+When `DEBUG` is set, the service writes readable, colorized logs for local
+development. It uses structured JSON logs otherwise.
+
+## Where it runs
+
+| Resource | Placement |
+| --- | --- |
+| Kafka cluster | `warpstream-shared` |
+| Topic | `clickhouse_billing_usage_records`, 8 partitions, 7-day retention |
+| ClickHouse Kafka table and MV | `NodeRole.INGESTION_SMALL` |
+| ClickHouse storage and read tables | `NodeRole.DATA` |
+| Reachability | in-cluster only; no external proxy and no request authentication |
+| Owning team | `team-ingestion` |
+
+`warpstream-shared` carries the low-volume topics that do not justify a cluster
+of their own, which is what usage records are.
+The alternative was `warpstream-ingestion`, where `usage_report_events_preagg`
+lives, but that cluster carries the event hot path.
+Usage records come from a standalone gateway rather than the event pipeline, so
+putting them there would couple billing data to the noisiest cluster for no gain.
+The producer and the ClickHouse Kafka engine table must name the same cluster:
+the table takes it from `CLICKHOUSE_KAFKA_WARPSTREAM_SHARED_NAMED_COLLECTION`,
+and the service takes its topic from `USAGE_INGESTION_TOPIC`.
+
+The endpoint relies on an in-cluster network boundary while it is being validated.
+Before it is exposed beyond trusted callers, it must authenticate the calling service.
+
+Partition count can be raised later without risk, which is not true of an
+ordered stream.
+ClickHouse deduplicates by record identity and picks a winner by
+`event_timestamp`, so a key that moves to a different partition after a
+repartition cannot change the result.
+
+## End-to-end tests
+
+Both tests run the service in-process and need the local dev stack for Kafka and
+ClickHouse (with migration `0303_billing_usage_records` applied), so both are
+`#[ignore]`d by default.
+`ci-rust.yml` runs them with `--run-ignored only` against the Django test
+schema, so they gate PRs that touch this crate.
+
+| Env var | Default |
+| --- | --- |
+| `USAGE_INGESTION_E2E_KAFKA_HOSTS` | `localhost:9092` |
+| `USAGE_INGESTION_E2E_CLICKHOUSE_URL` | `http://localhost:8123` |
+| `USAGE_INGESTION_E2E_CLICKHOUSE_DATABASE` | `posthog` (CI: `posthog_test`) |
+| `USAGE_INGESTION_E2E_TOPIC` | `clickhouse_billing_usage_records` (CI: `clickhouse_billing_usage_records_test`) |
+
+A Django test environment suffixes both the ClickHouse database and the Kafka
+topic, which is why the last two exist.
+The service reads the same topic from `USAGE_INGESTION_TOPIC`.
+
+```sh
+flox activate -- bash -c 'cd rust && cargo test -p usage-ingestion -- --ignored --nocapture'
+```
+
+`tests/e2e.rs` checks that a retry with the original event timestamp collapses
+to one canonical row. A correction must use a new version, and any correction
+that moves event time becomes a distinct billable row.
+
+### Load test
+
+`tests/load.rs` fires thousands of concurrent single-record requests across
+varied teams, organizations, usage keys and modes, a tenth of them retries of an
+earlier record shuffled so they can arrive before the original.
+
+```sh
+flox activate -- bash -c 'cd rust && cargo test -p usage-ingestion --test load -- --ignored --nocapture'
+```
+
+It asserts that every request succeeds, that concurrent throughput is at least
+5x the sequential baseline measured on the same machine, and that ClickHouse
+ends with exactly one row per record with every retry winning on event
+timestamp.
+The throughput floor is deliberately loose: it exists to catch a lock or single
+worker serializing the request path, not to pin a number to a laptop.
+
+The printed percentiles are the other half of the point.
+Raise the load to find where a machine stops scaling:
+
+| Env var | Default | |
+| --- | --- | --- |
+| `USAGE_INGESTION_E2E_LOAD_REQUESTS` | 5000 | total requests, 10% of them retries |
+| `USAGE_INGESTION_E2E_LOAD_CONCURRENCY` | 128 | requests in flight |
+| `USAGE_INGESTION_E2E_LOAD_CHANNELS` | 8 | gRPC connections the load spreads over |
+
+On an M-series laptop against the dev stack, p50 stays pinned to the Kafka
+producer's 20ms linger until concurrency passes 512, measured at 20000 requests:
+
+| Concurrency | Throughput | p50 | p99 |
+| --- | --- | --- | --- |
+| 32 | 1.4k req/s | 23ms | 30ms |
+| 256 | 9.6k req/s | 26ms | 40ms |
+| 512 | 18.8k req/s | 26ms | 45ms |
+| 1024 | 22.7k req/s | 43ms | 71ms |
+
+A large run leaves its rows in `posthog.sharded_billing_usage_records`; every query
+filters on a per-run record ID prefix, so runs never interfere, but
+`TRUNCATE TABLE posthog.sharded_billing_usage_records` clears a dev instance.
diff --git a/rust/usage-ingestion/src/config.rs b/rust/usage-ingestion/src/config.rs
new file mode 100644
index 000000000000..0d45c6ef40b6
--- /dev/null
+++ b/rust/usage-ingestion/src/config.rs
@@ -0,0 +1,32 @@
+use envconfig::Envconfig;
+
+#[derive(Envconfig, Clone)]
+pub struct Config {
+ #[envconfig(from = "USAGE_INGESTION_GRPC_ADDRESS", default = "0.0.0.0:7143")]
+ pub grpc_address: String,
+ #[envconfig(from = "USAGE_INGESTION_METRICS_ADDRESS", default = "0.0.0.0:7144")]
+ pub metrics_address: String,
+ #[envconfig(from = "USAGE_INGESTION_DATABASE_URL")]
+ pub database_url: String,
+ #[envconfig(from = "KAFKA_HOSTS", default = "localhost:9092")]
+ pub kafka_hosts: String,
+ #[envconfig(from = "KAFKA_TLS", default = "false")]
+ pub kafka_tls: bool,
+ #[envconfig(from = "USAGE_INGESTION_MAX_BATCH_SIZE", default = "500")]
+ pub max_batch_size: usize,
+ // Overridable so a test environment can use the suffixed topic its Kafka engine table reads.
+ #[envconfig(
+ from = "USAGE_INGESTION_TOPIC",
+ default = "clickhouse_billing_usage_records"
+ )]
+ pub topic: String,
+}
+
+impl Config {
+ pub fn validate(&self) -> Result<(), String> {
+ if self.max_batch_size == 0 || self.max_batch_size > 5_000 {
+ return Err("USAGE_INGESTION_MAX_BATCH_SIZE must be between 1 and 5000".to_string());
+ }
+ Ok(())
+ }
+}
diff --git a/rust/usage-ingestion/src/lib.rs b/rust/usage-ingestion/src/lib.rs
new file mode 100644
index 000000000000..c94d23269d43
--- /dev/null
+++ b/rust/usage-ingestion/src/lib.rs
@@ -0,0 +1,4 @@
+pub mod config;
+pub mod record;
+pub mod resolver;
+pub mod service;
diff --git a/rust/usage-ingestion/src/main.rs b/rust/usage-ingestion/src/main.rs
new file mode 100644
index 000000000000..435727732208
--- /dev/null
+++ b/rust/usage-ingestion/src/main.rs
@@ -0,0 +1,118 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use axum::{routing::get, Router};
+use common_database::{get_pool_with_config, PoolConfig};
+use common_kafka::config::KafkaConfig;
+use common_kafka::kafka_producer::create_kafka_producer;
+use envconfig::Envconfig;
+use health::HealthRegistry;
+use metrics_exporter_prometheus::PrometheusBuilder;
+use tonic::transport::Server;
+use tracing::level_filters::LevelFilter;
+use tracing_subscriber::fmt::format::FmtSpan;
+use tracing_subscriber::layer::SubscriberExt;
+use tracing_subscriber::util::SubscriberInitExt;
+use tracing_subscriber::{EnvFilter, Layer};
+use usage_ingestion::config::Config;
+use usage_ingestion::resolver::PostgresOrganizationResolver;
+use usage_ingestion::service::UsageIngestionService;
+use usage_ingestion_proto::usage_ingestion::v1::usage_ingestion_server::UsageIngestionServer;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let log_layer = {
+ let base = tracing_subscriber::fmt::layer()
+ .with_target(true)
+ .with_thread_ids(true)
+ .with_level(true);
+
+ if std::env::var_os("DEBUG").is_some() {
+ base.with_span_events(
+ FmtSpan::NEW | FmtSpan::CLOSE | FmtSpan::ENTER | FmtSpan::EXIT | FmtSpan::ACTIVE,
+ )
+ .with_ansi(true)
+ .boxed()
+ } else {
+ base.json()
+ .flatten_event(true)
+ .with_span_list(true)
+ .with_current_span(true)
+ .boxed()
+ }
+ };
+
+ tracing_subscriber::registry()
+ .with(log_layer)
+ .with(
+ EnvFilter::builder()
+ .with_default_directive(LevelFilter::INFO.into())
+ .from_env_lossy(),
+ )
+ .init();
+
+ let config = Config::init_from_env()?;
+ config.validate()?;
+
+ let database = get_pool_with_config(
+ &config.database_url,
+ PoolConfig {
+ max_connections: 10,
+ pool_name: Some("usage-ingestion".to_string()),
+ ..Default::default()
+ },
+ )?;
+ let resolver = Arc::new(PostgresOrganizationResolver::new(database));
+
+ let kafka_config = KafkaConfig {
+ kafka_hosts: config.kafka_hosts,
+ kafka_tls: config.kafka_tls,
+ kafka_client_id: "usage-ingestion".to_string(),
+ ..Default::default()
+ };
+ let health = Arc::new(HealthRegistry::new("usage-ingestion"));
+ let producer_liveness = health
+ .register("kafka_producer".to_string(), Duration::from_secs(30))
+ .await;
+ let producer = create_kafka_producer(&kafka_config, producer_liveness).await?;
+ let service = UsageIngestionService::new(
+ producer,
+ resolver,
+ config.max_batch_size,
+ config.topic.clone(),
+ );
+
+ let metrics_handle = PrometheusBuilder::new().install_recorder()?;
+ let metrics_address = config.metrics_address.clone();
+ let health_for_routes = health.clone();
+ tokio::spawn(async move {
+ let router = Router::new()
+ .route(
+ "/_readiness",
+ get(move || {
+ let health = health_for_routes.clone();
+ async move { health.get_status() }
+ }),
+ )
+ .route("/_liveness", get(|| async { "ok" }))
+ .route(
+ "/metrics",
+ get(move || std::future::ready(metrics_handle.render())),
+ );
+ let listener = tokio::net::TcpListener::bind(metrics_address)
+ .await
+ .expect("failed to bind usage-ingestion metrics listener");
+ axum::serve(listener, router)
+ .await
+ .expect("usage-ingestion metrics server failed");
+ });
+
+ tracing::info!(address = %config.grpc_address, "Starting usage-ingestion gRPC service");
+ // This listener is limited to trusted in-cluster callers. Add authenticated caller identity
+ // before exposing it beyond that boundary because records affect tenant billing.
+ Server::builder()
+ .add_service(UsageIngestionServer::new(service))
+ .serve(config.grpc_address.parse()?)
+ .await?;
+ Ok(())
+}
diff --git a/rust/usage-ingestion/src/record.rs b/rust/usage-ingestion/src/record.rs
new file mode 100644
index 000000000000..bd72cc8bbd2b
--- /dev/null
+++ b/rust/usage-ingestion/src/record.rs
@@ -0,0 +1,91 @@
+use std::ops::Range;
+
+use chrono::{DateTime, Datelike, SecondsFormat, Utc};
+use serde::Serialize;
+use thiserror::Error;
+use usage_ingestion_proto::usage_ingestion::v1::BillingUsageRecord;
+use uuid::Uuid;
+
+const CLICKHOUSE_DATETIME64_YEARS: Range<i32> = 1900..2300;
+/// A record_id may have to mirror a whole dedup identity: the analytics producers compose
+/// theirs from the events table's sorting key, whose event name and distinct_id are each
+/// capped at 200. Rejecting one would drop the record and under-bill.
+const MAX_IDENTIFIER_LENGTH: usize = 512;
+
+#[derive(Debug, Error, PartialEq, Eq)]
+pub enum ValidationError {
+ #[error("{0} must not be empty")]
+ Empty(&'static str),
+ #[error("{0} exceeds the maximum length")]
+ TooLong(&'static str),
+ #[error("team_id must be positive")]
+ InvalidTeamId,
+ #[error("quantity must be positive")]
+ InvalidQuantity,
+ #[error("timestamp_ms must be milliseconds since the epoch, between years 1900 and 2300")]
+ InvalidTimestamp,
+}
+
+#[derive(Debug, Serialize)]
+pub struct KafkaBillingUsageRecord {
+ pub schema_version: u8,
+ pub record_id: String,
+ pub producer_id: String,
+ pub team_id: i64,
+ pub organization_id: Uuid,
+ pub usage_key: String,
+ pub unit: String,
+ pub quantity: i64,
+ pub timestamp: String,
+ pub inserted_at: String,
+}
+
+impl KafkaBillingUsageRecord {
+ pub fn from_proto(
+ record: BillingUsageRecord,
+ organization_id: Uuid,
+ inserted_at: DateTime<Utc>,
+ ) -> Result<Self, ValidationError> {
+ validate_identifier("record_id", &record.record_id)?;
+ validate_identifier("producer_id", &record.producer_id)?;
+ validate_identifier("usage_key", &record.usage_key)?;
+ validate_identifier("unit", &record.unit)?;
+ if record.team_id <= 0 {
+ return Err(ValidationError::InvalidTeamId);
+ }
+ // Every record is a delta, so nothing meaningful is zero. A snapshot producer would
+ // need this exemption back alongside the mode column.
+ if record.quantity <= 0 {
+ return Err(ValidationError::InvalidQuantity);
+ }
+
+ // This protects the Kafka engine rather than defining a billing-time policy. Tighten the
+ // accepted range when producers have an explicit backfill and future-skew contract.
+ let timestamp = DateTime::from_timestamp_millis(record.timestamp_ms)
+ .filter(|value| CLICKHOUSE_DATETIME64_YEARS.contains(&value.year()))
+ .ok_or(ValidationError::InvalidTimestamp)?;
+
+ Ok(Self {
+ schema_version: 1,
+ record_id: record.record_id,
+ producer_id: record.producer_id,
+ team_id: record.team_id,
+ organization_id,
+ usage_key: record.usage_key,
+ unit: record.unit,
+ quantity: record.quantity,
+ timestamp: timestamp.to_rfc3339_opts(SecondsFormat::Millis, true),
+ inserted_at: inserted_at.to_rfc3339_opts(SecondsFormat::Millis, true),
+ })
+ }
+}
+
+fn validate_identifier(field: &'static str, value: &str) -> Result<(), ValidationError> {
+ if value.is_empty() {
+ return Err(ValidationError::Empty(field));
+ }
+ if value.len() > MAX_IDENTIFIER_LENGTH {
+ return Err(ValidationError::TooLong(field));
+ }
+ Ok(())
+}
diff --git a/rust/usage-ingestion/src/resolver.rs b/rust/usage-ingestion/src/resolver.rs
new file mode 100644
index 000000000000..e307555cd876
--- /dev/null
+++ b/rust/usage-ingestion/src/resolver.rs
@@ -0,0 +1,65 @@
+use std::time::Duration;
+
+use async_trait::async_trait;
+use moka::future::Cache;
+use sqlx::PgPool;
+use thiserror::Error;
+use uuid::Uuid;
+
+#[derive(Debug, Error)]
+pub enum ResolveError {
+ #[error("team ID is outside the supported range")]
+ InvalidTeamId,
+ #[error("team has no organization")]
+ Missing,
+ #[error("database lookup failed: {0}")]
+ Database(#[from] sqlx::Error),
+}
+
+#[async_trait]
+pub trait OrganizationResolver: Send + Sync {
+ async fn resolve(&self, team_id: i64) -> Result<Uuid, ResolveError>;
+}
+
+pub struct PostgresOrganizationResolver {
+ cache: Cache<i64, Option<Uuid>>,
+ database: PgPool,
+}
+
+impl PostgresOrganizationResolver {
+ pub fn new(database: PgPool) -> Self {
+ Self {
+ cache: Cache::builder()
+ .time_to_live(Duration::from_secs(5 * 60))
+ .build(),
+ database,
+ }
+ }
+}
+
+#[async_trait]
+impl OrganizationResolver for PostgresOrganizationResolver {
+ async fn resolve(&self, team_id: i64) -> Result<Uuid, ResolveError> {
+ if team_id <= 0 {
+ return Err(ResolveError::InvalidTeamId);
+ }
+ if let Some(organization_id) = self.cache.get(&team_id).await {
+ metrics::counter!("usage_ingestion_organization_resolver_cache_lookups_total", "result" => "hit")
+ .increment(1);
+ return organization_id.ok_or(ResolveError::Missing);
+ }
+ metrics::counter!("usage_ingestion_organization_resolver_cache_lookups_total", "result" => "miss")
+ .increment(1);
+
+ // A short TTL bounds stale attribution after a project moves organizations while avoiding
+ // a PostgreSQL lookup for every invalid or repeated record.
+ let organization_id = sqlx::query_scalar::<_, Uuid>(
+ "SELECT organization_id FROM posthog_team WHERE id = $1 AND organization_id IS NOT NULL",
+ )
+ .bind(team_id)
+ .fetch_optional(&self.database)
+ .await?;
+ self.cache.insert(team_id, organization_id).await;
+ organization_id.ok_or(ResolveError::Missing)
+ }
+}
diff --git a/rust/usage-ingestion/src/service.rs b/rust/usage-ingestion/src/service.rs
new file mode 100644
index 000000000000..69bb0debe4c4
--- /dev/null
+++ b/rust/usage-ingestion/src/service.rs
@@ -0,0 +1,205 @@
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Instant;
+
+use chrono::Utc;
+use common_kafka::kafka_producer::{
+ send_keyed_payloads_to_kafka_with_encoding, EnvelopeEncoding, KafkaContext,
+};
+use rdkafka::producer::FutureProducer;
+use tonic::{Request, Response, Status};
+use usage_ingestion_proto::usage_ingestion::v1::{
+ usage_ingestion_server::UsageIngestion, BillingUsageRecord, IngestBillingUsageRequest,
+ IngestBillingUsageResponse,
+};
+use uuid::Uuid;
+
+use crate::record::KafkaBillingUsageRecord;
+use crate::resolver::{OrganizationResolver, ResolveError};
+
+pub struct UsageIngestionService {
+ producer: FutureProducer<KafkaContext>,
+ resolver: Arc<dyn OrganizationResolver>,
+ max_batch_size: usize,
+ topic: String,
+}
+
+impl UsageIngestionService {
+ pub fn new(
+ producer: FutureProducer<KafkaContext>,
+ resolver: Arc<dyn OrganizationResolver>,
+ max_batch_size: usize,
+ topic: String,
+ ) -> Self {
+ Self {
+ producer,
+ resolver,
+ max_batch_size,
+ topic,
+ }
+ }
+
+ async fn prepare(
+ &self,
+ record: BillingUsageRecord,
+ resolved: &mut HashMap<i64, Uuid>,
+ ) -> Result<KafkaBillingUsageRecord, Status> {
+ if record.team_id <= 0 || record.team_id > i64::from(i32::MAX) {
+ return Err(Status::invalid_argument(
+ "team_id must be a positive 32-bit integer",
+ ));
+ }
+ let organization_id = match resolved.get(&record.team_id) {
+ Some(value) => *value,
+ None => {
+ let value = self
+ .resolver
+ .resolve(record.team_id)
+ .await
+ .map_err(resolve_status)?;
+ resolved.insert(record.team_id, value);
+ value
+ }
+ };
+
+ KafkaBillingUsageRecord::from_proto(record, organization_id, Utc::now())
+ .map_err(|error| Status::invalid_argument(error.to_string()))
+ }
+}
+
+#[tonic::async_trait]
+impl UsageIngestion for UsageIngestionService {
+ async fn ingest_billing_usage(
+ &self,
+ request: Request<IngestBillingUsageRequest>,
+ ) -> Result<Response<IngestBillingUsageResponse>, Status> {
+ let records = request.into_inner().records;
+ if records.is_empty() {
+ return Err(Status::invalid_argument("records must not be empty"));
+ }
+ if records.len() > self.max_batch_size {
+ return Err(Status::invalid_argument(
+ "records exceeds the configured batch limit",
+ ));
+ }
+
+ // One resolver call per distinct team, not per record: a full batch from one
+ // team would otherwise be 500 Redis reads and 500 queries on a cold cache.
+ let mut resolved = HashMap::new();
+ let mut prepared = Vec::with_capacity(records.len());
+ for record in records {
+ prepared.push(self.prepare(record, &mut resolved).await?);
+ }
+ let accepted_record_ids = prepared
+ .iter()
+ .map(|record| record.record_id.clone())
+ .collect::<Vec<_>>();
+ let payloads = prepared.into_iter().map(|record| {
+ let key = Some(record.team_id.to_string());
+ serde_json::to_vec(&record)
+ .map(|payload| (key, payload))
+ .map_err(|error| {
+ Status::internal(format!("failed to encode usage record: {error}"))
+ })
+ });
+ let payloads = payloads.collect::<Result<Vec<_>, _>>()?;
+ let producer_started_at = Instant::now();
+ let results = send_keyed_payloads_to_kafka_with_encoding(
+ &self.producer,
+ &self.topic,
+ EnvelopeEncoding::None,
+ payloads,
+ )
+ .await;
+ metrics::histogram!("usage_ingestion_kafka_delivery_seconds")
+ .record(producer_started_at.elapsed().as_secs_f64());
+ if results.iter().any(Result::is_err) {
+ return Err(Status::unavailable(
+ "Kafka did not confirm every usage record; retry with the same record IDs",
+ ));
+ }
+
+ Ok(Response::new(IngestBillingUsageResponse {
+ accepted_record_ids,
+ }))
+ }
+}
+
+fn resolve_status(error: ResolveError) -> Status {
+ match error {
+ ResolveError::InvalidTeamId => {
+ Status::invalid_argument("team_id must be a positive 32-bit integer")
+ }
+ ResolveError::Missing => Status::not_found("team organization mapping was not found"),
+ ResolveError::Database(error) => {
+ Status::unavailable(format!("team organization lookup failed: {error}"))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use async_trait::async_trait;
+ use common_liveness::SyncLivenessReporter;
+ use rdkafka::ClientConfig;
+
+ use super::*;
+
+ const TEAM_ORGANIZATION: &str = "018f7c8e-4c08-7c5e-9bc0-15c9f5cc9f42";
+
+ #[derive(Clone, Copy)]
+ struct AlwaysHealthy;
+
+ impl SyncLivenessReporter for AlwaysHealthy {
+ fn report_healthy(&self) {}
+ fn report_unhealthy(&self) {}
+ }
+
+ struct FixedResolver;
+
+ #[async_trait]
+ impl OrganizationResolver for FixedResolver {
+ async fn resolve(&self, _team_id: i64) -> Result<Uuid, ResolveError> {
+ Ok(Uuid::parse_str(TEAM_ORGANIZATION).unwrap())
+ }
+ }
+
+ fn service() -> UsageIngestionService {
+ // prepare() never produces, so the producer only has to exist.
+ let producer = ClientConfig::new()
+ .set("bootstrap.servers", "localhost:9092")
+ .create_with_context(KafkaContext::new(AlwaysHealthy))
+ .expect("failed to build the test producer");
+ UsageIngestionService::new(
+ producer,
+ Arc::new(FixedResolver),
+ 500,
+ "test-topic".to_string(),
+ )
+ }
+
+ fn record() -> BillingUsageRecord {
+ BillingUsageRecord {
+ record_id: "018f7c8e-4c08-7c5e-9bc0-15c9f5cc9f44".to_string(),
+ producer_id: "feature-flags".to_string(),
+ team_id: 42,
+ usage_key: "feature_flag_requests".to_string(),
+ unit: "request".to_string(),
+ quantity: 10,
+ timestamp_ms: 1_718_409_600_000,
+ }
+ }
+
+ #[tokio::test]
+ async fn the_resolved_organization_is_stamped_on_the_record() {
+ let prepared = service()
+ .prepare(record(), &mut HashMap::new())
+ .await
+ .expect("the record should be accepted");
+
+ assert_eq!(
+ prepared.organization_id,
+ Uuid::parse_str(TEAM_ORGANIZATION).unwrap()
+ );
+ }
+}
diff --git a/rust/usage-ingestion/tests/common/mod.rs b/rust/usage-ingestion/tests/common/mod.rs
new file mode 100644
index 000000000000..c74867b0ec1a
--- /dev/null
+++ b/rust/usage-ingestion/tests/common/mod.rs
@@ -0,0 +1,154 @@
+//! Shared harness for the opt-in end-to-end tests.
+
+// Each test binary compiles this module separately, so helpers only one uses look dead.
+#![allow(dead_code)]
+
+use std::net::SocketAddr;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use common_kafka::config::KafkaConfig;
+use common_kafka::kafka_producer::create_kafka_producer;
+use common_liveness::SyncLivenessReporter;
+use tokio::net::TcpListener;
+use tokio::sync::oneshot;
+use tokio::task::JoinHandle;
+use tokio_stream::wrappers::TcpListenerStream;
+use tonic::transport::{Channel, Server};
+use usage_ingestion::resolver::{OrganizationResolver, ResolveError};
+use usage_ingestion::service::UsageIngestionService;
+use usage_ingestion_proto::usage_ingestion::v1::usage_ingestion_client::UsageIngestionClient;
+use usage_ingestion_proto::usage_ingestion::v1::usage_ingestion_server::UsageIngestionServer;
+use uuid::Uuid;
+
+/// A Django test environment suffixes both the database and the topic, so CI overrides both.
+pub fn table() -> String {
+ format!(
+ "{}.sharded_billing_usage_records",
+ env_or("USAGE_INGESTION_E2E_CLICKHOUSE_DATABASE", "posthog")
+ )
+}
+
+pub fn topic() -> String {
+ env_or(
+ "USAGE_INGESTION_E2E_TOPIC",
+ "clickhouse_billing_usage_records",
+ )
+}
+
+#[derive(Clone)]
+struct TestLiveness;
+
+impl SyncLivenessReporter for TestLiveness {
+ fn report_healthy(&self) {}
+
+ fn report_unhealthy(&self) {}
+}
+
+/// The service resolves every organization itself, so these tests stand in for the
+/// HyperCache/PostgreSQL lookup rather than seeding a team row.
+struct FixedResolver(Uuid);
+
+#[async_trait]
+impl OrganizationResolver for FixedResolver {
+ async fn resolve(&self, _team_id: i64) -> Result<Uuid, ResolveError> {
+ Ok(self.0)
+ }
+}
+
+pub fn env_or(key: &str, default: &str) -> String {
+ std::env::var(key).unwrap_or_else(|_| default.to_string())
+}
+
+pub fn env_usize(key: &str, default: usize) -> usize {
+ std::env::var(key)
+ .ok()
+ .map(|value| {
+ value
+ .parse()
+ .unwrap_or_else(|_| panic!("{key} must be a positive integer, got {value:?}"))
+ })
+ .unwrap_or(default)
+}
+
+pub fn kafka_hosts() -> String {
+ env_or("USAGE_INGESTION_E2E_KAFKA_HOSTS", "localhost:9092")
+}
+
+pub fn clickhouse_url() -> String {
+ env_or(
+ "USAGE_INGESTION_E2E_CLICKHOUSE_URL",
+ "http://localhost:8123",
+ )
+}
+
+pub async fn clickhouse(client: &reqwest::Client, url: &str, query: &str) -> String {
+ let response = client
+ .post(url)
+ .body(query.to_string())
+ .send()
+ .await
+ .expect("ClickHouse request failed");
+ let status = response.status();
+ let body = response.text().await.expect("ClickHouse body was not text");
+ assert!(status.is_success(), "{query}\n-> {status}: {body}");
+ body
+}
+
+pub struct Service {
+ pub address: SocketAddr,
+ shutdown: oneshot::Sender<()>,
+ handle: JoinHandle<()>,
+}
+
+impl Service {
+ pub async fn start(max_batch_size: usize, organization_id: Uuid) -> Self {
+ let producer = create_kafka_producer(
+ &KafkaConfig {
+ kafka_hosts: kafka_hosts(),
+ kafka_tls: false,
+ kafka_client_id: "usage-ingestion-e2e".to_string(),
+ ..Default::default()
+ },
+ TestLiveness,
+ )
+ .await
+ .expect("failed to create the Kafka producer");
+ let service = UsageIngestionService::new(
+ producer,
+ Arc::new(FixedResolver(organization_id)),
+ max_batch_size,
+ topic(),
+ );
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let (shutdown, shutdown_signal) = oneshot::channel::<()>();
+ let handle = tokio::spawn(async move {
+ Server::builder()
+ .add_service(UsageIngestionServer::new(service))
+ .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async {
+ let _ = shutdown_signal.await;
+ })
+ .await
+ .expect("the gRPC server failed");
+ });
+
+ Self {
+ address,
+ shutdown,
+ handle,
+ }
+ }
+
+ pub async fn client(&self) -> UsageIngestionClient<Channel> {
+ UsageIngestionClient::connect(format!("http://{}", self.address))
+ .await
+ .expect("failed to connect to the in-process gRPC server")
+ }
+
+ pub async fn stop(self) {
+ let _ = self.shutdown.send(());
+ self.handle.await.unwrap();
+ }
+}
diff --git a/rust/usage-ingestion/tests/e2e.rs b/rust/usage-ingestion/tests/e2e.rs
new file mode 100644
index 000000000000..5847bd528aa7
--- /dev/null
+++ b/rust/usage-ingestion/tests/e2e.rs
@@ -0,0 +1,96 @@
+//! End-to-end check that a retried usage record collapses to one canonical row.
+
+mod common;
+
+use std::time::{Duration, Instant};
+
+use common::{clickhouse, clickhouse_url, table, Service};
+use usage_ingestion_proto::usage_ingestion::v1::{BillingUsageRecord, IngestBillingUsageRequest};
+use uuid::Uuid;
+
+/// Fixed so both rows land in one monthly partition, the scope ReplacingMergeTree collapses within.
+const FIRST_EVENT_TIMESTAMP_MS: i64 = 1_718_409_600_000; // 2024-06-15T00:00:00Z
+
+fn record(record_id: &str, timestamp_ms: i64) -> BillingUsageRecord {
+ BillingUsageRecord {
+ record_id: record_id.to_string(),
+ producer_id: "usage-ingestion-e2e".to_string(),
+ team_id: 1,
+ usage_key: "e2e_records".to_string(),
+ unit: "record".to_string(),
+ quantity: 1,
+ timestamp_ms,
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires a local Kafka and ClickHouse with migration 0303; run with --ignored"]
+async fn retried_record_with_original_timestamp_deduplicates() {
+ let clickhouse_url = clickhouse_url();
+ let table = table();
+ let organization_id = Uuid::new_v4();
+ let service = Service::start(500, organization_id).await;
+ let mut client = service.client().await;
+
+ let record_id = Uuid::new_v4().to_string();
+ client
+ .ingest_billing_usage(IngestBillingUsageRequest {
+ records: vec![record(&record_id, FIRST_EVENT_TIMESTAMP_MS)],
+ })
+ .await
+ .expect("the first ingest failed");
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ client
+ .ingest_billing_usage(IngestBillingUsageRequest {
+ records: vec![record(&record_id, FIRST_EVENT_TIMESTAMP_MS)],
+ })
+ .await
+ .expect("the retried ingest failed");
+
+ let http = reqwest::Client::new();
+ // Wait for the original record: each retry preserves the event timestamp.
+ let arrival_query = format!(
+ "SELECT count() FROM {table} WHERE record_id = '{record_id}' AND timestamp = toDateTime64('2024-06-15 00:00:00', 6, 'UTC')"
+ );
+ let deadline = Instant::now() + Duration::from_secs(120);
+ loop {
+ if clickhouse(&http, &clickhouse_url, &arrival_query)
+ .await
+ .trim()
+ == "1"
+ {
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "the retried record never reached ClickHouse"
+ );
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+
+ clickhouse(
+ &http,
+ &clickhouse_url,
+ &format!("OPTIMIZE TABLE {table} FINAL"),
+ )
+ .await;
+ // No FINAL: after OPTIMIZE the stored rows themselves must be collapsed.
+ let canonical = clickhouse(
+ &http,
+ &clickhouse_url,
+ &format!(
+ "SELECT toString(timestamp) FROM {table} WHERE record_id = '{record_id}' FORMAT TSV"
+ ),
+ )
+ .await;
+ let canonical: Vec<&str> = canonical.lines().collect();
+
+ assert_eq!(
+ canonical.len(),
+ 1,
+ "expected one canonical row: {canonical:?}"
+ );
+ assert_eq!(canonical[0], "2024-06-15 00:00:00.000000");
+
+ service.stop().await;
+}
diff --git a/rust/usage-ingestion/tests/load.rs b/rust/usage-ingestion/tests/load.rs
new file mode 100644
index 000000000000..6f0d7d5eaec8
--- /dev/null
+++ b/rust/usage-ingestion/tests/load.rs
@@ -0,0 +1,222 @@
+//! Load check: thousands of concurrent requests over varied data, a tenth of them retries.
+//!
+//! The printed percentiles matter as much as the assertions. Raise the request count with
+//! `--nocapture` to find where a machine stops scaling. See the crate README.
+
+mod common;
+
+use std::collections::hash_map::DefaultHasher;
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use common::{clickhouse, clickhouse_url, env_usize, table, Service};
+use tokio::sync::Semaphore;
+use usage_ingestion_proto::usage_ingestion::v1::{BillingUsageRecord, IngestBillingUsageRequest};
+use uuid::Uuid;
+
+/// Midnight UTC, so the whole run shares one `toDate(timestamp)` and one monthly partition.
+const BASE_TIMESTAMP_MS: i64 = 1_718_409_600_000; // 2024-06-15T00:00:00Z
+/// An hour after the original: a different `timestamp` but the same day, which is the window
+/// the sorting key deduplicates within. Producers stamp flush time, so a retry does move it.
+const RETRY_OFFSET_MS: i64 = 3_600_000;
+
+const BASELINE_REQUESTS: usize = 32;
+/// Sequential latency is dominated by the producer's 20ms linger, so there is a lot of
+/// headroom for concurrency to reclaim. Real runs clear 100x; serialization lands under 2x.
+const MIN_THROUGHPUT_SPEEDUP: f64 = 5.0;
+
+const USAGE_KEYS: [(&str, &str); 4] = [
+ ("events_captured", "event"),
+ ("flag_requests", "request"),
+ ("recordings_ingested", "recording"),
+ ("queries_executed", "query"),
+];
+
+/// A retry reuses the sorting key `(team_id, toDate(timestamp), producer_id, usage_key,
+/// record_id)` while moving `timestamp` within the day. Narrowing the key's date to the exact
+/// timestamp makes this test fail with double the rows.
+fn record(run: &str, index: usize, retry: bool) -> BillingUsageRecord {
+ let (usage_key, unit) = USAGE_KEYS[index % USAGE_KEYS.len()];
+ let event_offset_ms = (index % 60_000) as i64;
+ BillingUsageRecord {
+ record_id: format!("{run}:{index}"),
+ producer_id: "usage-ingestion-load".to_string(),
+ team_id: 1 + (index % 8) as i64,
+ usage_key: usage_key.to_string(),
+ unit: unit.to_string(),
+ quantity: 1 + (index % 100) as i64,
+ timestamp_ms: BASE_TIMESTAMP_MS + event_offset_ms + if retry { RETRY_OFFSET_MS } else { 0 },
+ }
+}
+
+fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
+ let index = ((sorted.len() as f64 * fraction) as usize).min(sorted.len() - 1);
+ sorted[index]
+}
+
+#[tokio::test(flavor = "multi_thread")]
+#[ignore = "load test: needs a local Kafka and ClickHouse with migration 0303; run with --ignored --nocapture"]
+async fn sustains_thousands_of_concurrent_requests() {
+ let requests = env_usize("USAGE_INGESTION_E2E_LOAD_REQUESTS", 5_000);
+ let concurrency = env_usize("USAGE_INGESTION_E2E_LOAD_CONCURRENCY", 128);
+ let channels = env_usize("USAGE_INGESTION_E2E_LOAD_CHANNELS", 8);
+ assert!(requests >= 100 && concurrency >= 1 && channels >= 1);
+
+ let retries = requests / 10;
+ let unique = requests - retries;
+ let run = Uuid::new_v4().to_string();
+
+ let clickhouse_url = clickhouse_url();
+ let table = table();
+ let service = Service::start(500, Uuid::new_v4()).await;
+
+ // Measured here, not hardcoded, so the throughput assertion is not a hardware guess.
+ let mut baseline_client = service.client().await;
+ let mut baseline_latencies = Vec::with_capacity(BASELINE_REQUESTS);
+ let baseline_started = Instant::now();
+ for index in unique..unique + BASELINE_REQUESTS {
+ let started = Instant::now();
+ baseline_client
+ .ingest_billing_usage(IngestBillingUsageRequest {
+ records: vec![record(&run, index, false)],
+ })
+ .await
+ .expect("a baseline ingest failed");
+ baseline_latencies.push(started.elapsed());
+ }
+ let baseline_throughput = BASELINE_REQUESTS as f64 / baseline_started.elapsed().as_secs_f64();
+ baseline_latencies.sort();
+
+ let mut plan: Vec<BillingUsageRecord> = (0..unique)
+ .map(|index| record(&run, index, false))
+ .chain((0..retries).map(|index| record(&run, index, true)))
+ .collect();
+ // Arrival order must not match event order: a retry landing before its original still has
+ // to collapse to one row.
+ plan.sort_by_key(|record| {
+ let mut hasher = DefaultHasher::new();
+ (&record.record_id, record.timestamp_ms).hash(&mut hasher);
+ hasher.finish()
+ });
+
+ let mut clients = Vec::with_capacity(channels);
+ for _ in 0..channels {
+ clients.push(service.client().await);
+ }
+ let permits = Arc::new(Semaphore::new(concurrency));
+ let load_started = Instant::now();
+ let tasks: Vec<_> = plan
+ .into_iter()
+ .enumerate()
+ .map(|(slot, record)| {
+ let mut client = clients[slot % channels].clone();
+ let permits = permits.clone();
+ tokio::spawn(async move {
+ let _permit = permits.acquire().await.unwrap();
+ let started = Instant::now();
+ let result = client
+ .ingest_billing_usage(IngestBillingUsageRequest {
+ records: vec![record],
+ })
+ .await;
+ (started.elapsed(), result.err())
+ })
+ })
+ .collect();
+
+ let mut latencies = Vec::with_capacity(requests);
+ let mut failures = Vec::new();
+ for task in tasks {
+ let (latency, error) = task.await.expect("an ingest task panicked");
+ latencies.push(latency);
+ if let Some(error) = error {
+ failures.push(error);
+ }
+ }
+ let elapsed = load_started.elapsed();
+ let throughput = requests as f64 / elapsed.as_secs_f64();
+ latencies.sort();
+
+ println!(
+ "sequential baseline: {} requests, p50 {:?}, {:.0} req/s",
+ BASELINE_REQUESTS,
+ percentile(&baseline_latencies, 0.50),
+ baseline_throughput,
+ );
+ println!(
+ "concurrent load: {requests} requests ({retries} retries) at concurrency {concurrency} over {channels} channels in {elapsed:?}, {throughput:.0} req/s ({:.1}x baseline)",
+ throughput / baseline_throughput,
+ );
+ println!(
+ "latency: p50 {:?}, p95 {:?}, p99 {:?}, max {:?}",
+ percentile(&latencies, 0.50),
+ percentile(&latencies, 0.95),
+ percentile(&latencies, 0.99),
+ latencies.last().unwrap(),
+ );
+
+ assert!(
+ failures.is_empty(),
+ "{} of {requests} requests failed, first: {:?}",
+ failures.len(),
+ failures[0]
+ );
+ assert!(
+ throughput >= baseline_throughput * MIN_THROUGHPUT_SPEEDUP,
+ "concurrency bought only {:.1}x the sequential throughput; the request path is serializing",
+ throughput / baseline_throughput,
+ );
+
+ let http = reqwest::Client::new();
+ let expected_rows = unique + BASELINE_REQUESTS;
+ let arrival_query =
+ format!("SELECT uniqExact(record_id) FROM {table} WHERE startsWith(record_id, '{run}:')");
+ let deadline = Instant::now() + Duration::from_secs(300);
+ loop {
+ let arrived = clickhouse(&http, &clickhouse_url, &arrival_query)
+ .await
+ .trim()
+ .to_string();
+ if arrived == expected_rows.to_string() {
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "only {arrived} of {expected_rows} distinct records reached ClickHouse"
+ );
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+
+ clickhouse(
+ &http,
+ &clickhouse_url,
+ &format!("OPTIMIZE TABLE {table} FINAL"),
+ )
+ .await;
+ // No FINAL in the read: after the merge the stored rows themselves must be collapsed. This
+ // merge covers every row the run inserted rather than the handful the e2e test writes, so
+ // poll instead of assuming OPTIMIZE returned with all parts already merged.
+ //
+ // Which of the two survives is not asserted: `ver` is inserted_at, so the copy that
+ // arrived second wins, and arrival order here is deliberately shuffled.
+ let collapse_query =
+ format!("SELECT count() FROM {table} WHERE startsWith(record_id, '{run}:') FORMAT TSV");
+ let collapse_deadline = Instant::now() + Duration::from_secs(60);
+ loop {
+ let stored = clickhouse(&http, &clickhouse_url, &collapse_query)
+ .await
+ .trim()
+ .to_string();
+ if stored == expected_rows.to_string() {
+ break;
+ }
+ assert!(
+ Instant::now() < collapse_deadline,
+ "{retries} retries did not collapse: {stored} rows, expected {expected_rows}"
+ );
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+
+ service.stop().await;
+}
diff --git a/rust/usage-ingestion/tests/record.rs b/rust/usage-ingestion/tests/record.rs
new file mode 100644
index 000000000000..7329bf2f10b5
--- /dev/null
+++ b/rust/usage-ingestion/tests/record.rs
@@ -0,0 +1,78 @@
+use chrono::Utc;
+use usage_ingestion::record::{KafkaBillingUsageRecord, ValidationError};
+use usage_ingestion_proto::usage_ingestion::v1::BillingUsageRecord;
+use uuid::Uuid;
+
+fn record() -> BillingUsageRecord {
+ BillingUsageRecord {
+ record_id: "record-1".to_string(),
+ producer_id: "feature-flags".to_string(),
+ team_id: 42,
+ usage_key: "feature_flag_requests".to_string(),
+ unit: "request".to_string(),
+ quantity: 2,
+ timestamp_ms: 1_700_000_000_000,
+ }
+}
+
+#[test]
+fn converts_a_valid_record_to_clickhouse_json_shape() {
+ let organization_id = Uuid::new_v4();
+ let result =
+ KafkaBillingUsageRecord::from_proto(record(), organization_id, Utc::now()).unwrap();
+
+ assert_eq!(result.organization_id, organization_id);
+ assert_eq!(result.timestamp, "2023-11-14T22:13:20.000Z");
+}
+
+/// A producer sending microseconds or nanoseconds would otherwise serialize a year
+/// ClickHouse cannot parse, stalling the Kafka engine table on that row.
+#[test]
+fn rejects_timestamps_outside_the_clickhouse_range() {
+ for timestamp_ms in [
+ 1_700_000_000_000_000, // microseconds
+ 1_700_000_000_000_000_000, // nanoseconds
+ -2_208_988_800_001, // just before 1900
+ 10_413_792_000_000, // 2300
+ ] {
+ let mut invalid = record();
+ invalid.timestamp_ms = timestamp_ms;
+
+ assert_eq!(
+ KafkaBillingUsageRecord::from_proto(invalid, Uuid::new_v4(), Utc::now()).unwrap_err(),
+ ValidationError::InvalidTimestamp,
+ "{timestamp_ms} should be rejected"
+ );
+ }
+}
+
+/// Every record is a delta, so a zero or negative quantity bills nothing and means nothing.
+#[test]
+fn rejects_quantities_that_are_not_positive() {
+ for quantity in [0, -1] {
+ let mut invalid = record();
+ invalid.quantity = quantity;
+
+ assert_eq!(
+ KafkaBillingUsageRecord::from_proto(invalid, Uuid::new_v4(), Utc::now()).unwrap_err(),
+ ValidationError::InvalidQuantity,
+ "quantity {quantity} should be rejected"
+ );
+ }
+}
+
+/// The analytics producers compose a record_id from the events table's dedup identity, whose
+/// event name and distinct_id are each capped at 200. Lowering this bound would reject those
+/// records, and a rejected record is usage nobody is billed for.
+#[test]
+fn accepts_a_record_id_long_enough_for_a_composed_identity() {
+ for (length, expected) in [
+ (512, Ok(())),
+ (513, Err(ValidationError::TooLong("record_id"))),
+ ] {
+ let mut candidate = record();
+ candidate.record_id = "r".repeat(length);
+ let result = KafkaBillingUsageRecord::from_proto(candidate, Uuid::new_v4(), Utc::now());
+ assert_eq!(result.map(|_| ()), expected, "record_id of {length} bytes");
+ }
+}
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devenv.py b/tools/hogli-commands/hogli_commands/tests/test_devenv.py
index 046a4cb47e04..97e774f5dfec 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devenv.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devenv.py
@@ -925,6 +925,7 @@ class TestMprocsGeneratorRegression:
assert "capture" in resolved.units
assert "capture" in config.procs
+ assert "usage-ingestion" in config.procs
assert "feature-flags" in config.procs
assert "property-defs-rs" in config.procs
assert "docker-compose" in config.procs