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-ingestion): add Valkey usage counters (#93142)

Ben Whitebba5328360ad
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index fa15402743af..af88df61dcf1 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -191,7 +191,7 @@ services:
# CDP Redis defaults to 127.0.0.1 — must point to the Docker service
CDP_REDIS_HOST: redis7
CDP_VALKEY_HOST: valkey-cluster
- CDP_VALKEY_PORT: 6379
+ CDP_VALKEY_PORT: 6390
# Encryption keys default is only set when NODE_ENV=dev, but the image uses production
ENCRYPTION_SALT_KEYS: '00beef0000beef0000beef0000beef00'
# PersonHog is required for CDP — point at the local gRPC router
@@ -428,21 +428,26 @@ services:
image: valkey/valkey:8.1-alpine
restart: on-failure
ports:
- - '127.0.0.1:6390:6379'
+ - '127.0.0.1:6390:6390'
command:
- /bin/sh
- -ec
- |
- valkey-server --cluster-enabled yes --cluster-config-file /tmp/nodes.conf --cluster-node-timeout 5000 &
+ # 6390 inside the container as well as on the host, so the port CLUSTER SLOTS
+ # announces is right for both. It announces no address, which every cluster
+ # client reads as "the one you reached me on", so a host client stays on
+ # 127.0.0.1 and a container client stays on valkey-cluster. Announcing an
+ # address instead would name one of those two and break the other.
+ valkey-server --port 6390 --cluster-enabled yes --cluster-config-file /tmp/nodes.conf --cluster-node-timeout 5000 &
pid=$$!
- until valkey-cli ping >/dev/null 2>&1; do sleep 0.1; done
- valkey-cli cluster addslots $$(seq 0 16383)
+ until valkey-cli -p 6390 ping >/dev/null 2>&1; do sleep 0.1; done
+ valkey-cli -p 6390 cluster addslots $$(seq 0 16383)
wait $$pid
healthcheck:
test:
[
'CMD-SHELL',
- 'valkey-cli cluster info | grep -q cluster_state:ok && test "$$(valkey-cli cluster info | sed -n "s/cluster_slots_assigned://p" | tr -d "\r")" = 16384',
+ 'valkey-cli -p 6390 cluster info | grep -q cluster_state:ok && test "$$(valkey-cli -p 6390 cluster info | sed -n "s/cluster_slots_assigned://p" | tr -d "\r")" = 16384',
]
interval: 2s
timeout: 3s
@@ -707,6 +712,10 @@ services:
condition: service_healthy
kafka:
condition: service_healthy
+ valkey-cluster:
+ condition: service_healthy
+ environment:
+ USAGE_INGESTION_REDIS_URL: 'redis://valkey-cluster:6390'
# Keeps a bare `up` from building an image that is not published yet.
profiles:
- ingestion
diff --git a/docs/internal/usage-record-producers.md b/docs/internal/usage-record-producers.md
deleted file mode 100644
index 02f8f2fc9b77..000000000000
--- a/docs/internal/usage-record-producers.md
+++ /dev/null
@@ -1,259 +0,0 @@
-# Where billing usage records come from
-
-Every producer of `billing_usage_records` and the exact point in its flow where usage is counted.
-The rule that shapes all of them: **count after the last step that can drop the thing being billed, and before the row is written.**
-
-## Reading the tables
-
-`ReplacingMergeTree(inserted_at)` sorts by `(team_id, toDate(timestamp), producer_id, usage_key, record_id)`.
-Two records sharing those five collapse to one — they do not add, and the later send wins.
-So a producer's `record_id` has to be a stable identity for the billed thing: the same work replayed must produce the same ID, and different work must never share one.
-
-What it protects against is our own duplication, not a sender's.
-If someone sends the same thing twice we ingest it twice and bill it twice, which is correct.
-The identity exists so our retries and reprocessing of one ingested thing collapse to one row.
-`usage_key` is in the key, so a `record_id` does not repeat it.
-CDP is the one producer that still prefixes, because its three call sites share one `usage_key` and the prefix is what separates them.
-
-`timestamp` is in the sort key as a date, because every billing read filters a time range and a date in the key prunes where a skip index only skips granules.
-Every producer stamps it from its own clock when it flushes, never from anything a customer sends — a customer-controlled value would decide whether their own records deduplicate.
-The cost is that deduplication is scoped to a UTC day, so a reprocess that crosses midnight leaves two rows.
-
-`inserted_at` is the engine's version column but is deliberately absent from the HogQL schema.
-`timestamp` is monotonic per resend, so `argMax(quantity, timestamp)` reads what a merge would keep, and one time column cannot be confused for the other.
-
-A read that must be exact uses `argMax(quantity, timestamp)` grouped by the sort key. HogQL rejects `FINAL` outright, so this is the only exact shape there.
-The collapse happens on merge, so a plain `sum(quantity)` counts every un-merged duplicate.
-Measured locally: two identical batches landing in separate parts read as 6 rows summing 18 without `FINAL`, and 3 rows summing 9 with it.
-
-That shape does not scale, so do not reach for it by default.
-`record_id` is unique per row, so grouping by the sort key holds one aggregation state per row, and the query exceeds ClickHouse's per-query memory limit.
-A plain `sum(quantity)` stays inside the limit and overstates a total by a fraction of a percent, because a resend is rare.
-So a monitoring or in-product read sums raw rows and says it is not the billed number.
-Reserve the exact shape for a read that is scoped tightly enough to afford it.
-
-| producer_id | usage_key | unit | record_id | deployment |
-| ------------------- | ----------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------- |
-| `ingestion` | `events`, `ai_events` | events | `{day}:{sha256 of event, distinct_id, uuid}` | ingestion consumers, ingestion API |
-| `ai-ingestion` | `ai_events` | events | `{day}:{sha256 of event, distinct_id, uuid}` | AI ingestion consumer |
-| `error-tracking` | `exceptions` | events | `{day}:{sha256 of event, distinct_id, uuid}` | error tracking server |
-| `cdp` | `cdp_billable_invocations` | invocations | `event:{eventUuid}` / `flow:{invocationId}:{actionStepCount}:{kind}` / `webhook:{invocationId}` | CDP consumers |
-| `feature-flags` | `feature_flag_requests`, `feature_flag_local_evaluation_requests` | requests | fresh UUIDv7 per flush | feature flags service |
-| `ingestion` | `survey_responses` | events | `{day}:{sha256 of event, distinct_id, uuid}` | ingestion consumers, ingestion API |
-| `warehouse-sources` | `warehouse_rows_synced` | rows | the ExternalDataJob ID | warehouse sources worker |
-| `batch-exports` | `batch_export_rows` | rows | the BatchExportRun ID | batch exports worker |
-| `replay-vision` | `replay_vision_credits` | credits | the observation ID | replay vision worker |
-| `logs` | `logs_bytes`, `logs_records` | bytes, records | fresh UUIDv7 per flush | logs ingestion server |
-| `apm-traces` | `apm_traces_bytes`, `apm_traces_spans` | bytes, records | fresh UUIDv7 per flush | traces ingestion server |
-| `session-replay` | `session_replay_recordings`, `mobile_replay_recordings` | recordings | the session ID | session replay consumer |
-| `ingestion` | `enhanced_person_events` | events | `{day}:{sha256 of event, distinct_id, uuid}` | ingestion consumers, ingestion API |
-
-APM names its producer and meters for the signal they carry, not for the product, so metrics get their own names alongside traces rather than inheriting a bare `apm_` prefix that already means spans.
-
-Every producer reads the same four env vars, and each one is its own deployment, so one name still rolls out per producer from that service's own config.
-
-| Env var | Default | Meaning |
-| ------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------ |
-| `USAGE_INGESTION_REPORT_TEAMS` | `''` | `''` reports nothing, `*` every team, `1,2` those teams. |
-| `USAGE_INGESTION_ADDR` | `''` outside dev | `host:port` of the gateway. Empty also reports nothing. |
-| `USAGE_INGESTION_TLS` | `false` | Plaintext in-cluster. The flags service refuses `true` at startup, because its tonic build has no TLS. |
-| `USAGE_INGESTION_TIMEOUT_MS` | `5000` | Per attempt, not per batch. The flags sender retries a transient failure three times. |
-
-Empty is the default everywhere, so nothing reports until it is set.
-There is deliberately no percentage option: sampling a share of a team's events would bill that team a fraction of what it used.
-
-Every record carries quantity 1 and names one billed thing, so the aggregate lives in ClickHouse rather than in the producer.
-A producer that sees the same identity twice sends one record, because two records sharing an identity collapse rather than add.
-
-Three producers break that shape: feature flags, logs and APM send per-flush aggregates rather than one record per billed thing.
-They have no identity to reproduce, so each flush mints a fresh UUIDv7.
-That makes them retry-safe but not replay-safe, and it is deliberate: the quantity is a delta over a window, so a replayed flush is new usage rather than the same usage seen twice.
-Deriving those IDs from a clock instead would let two pods flushing one team in the same millisecond collapse into one row and drop a real quantity.
-Note the existing nightly report reaches the same totals additively — `app_metrics2` is an `AggregatingMergeTree` summing `count` per hour — so it has no identity to collide in the first place.
-
-## Analytics ingestion
-
-```mermaid
-flowchart TD
- K[events_plugin_ingestion] --> DENY[deny $exception, heatmap, client warning]
- DENY --> RESTRICT[token restrictions: drop / force overflow]
- RESTRICT --> RL[rate limit to overflow]
- RL --> PARSE[parse message]
- PARSE --> TEAM[resolve team]
- TEAM --> HIST[validate historical migration]
- HIST --> FILTERS[customer event filters]
- FILTERS --> COOKIELESS[cookieless processing]
- COOKIELESS --> DROPOLD[drop old events]
- DROPOLD --> TRANSFORM[hog transformations]
- TRANSFORM --> PERSONS[person processing]
- PERSONS --> PREPARE[prepare event]
- PREPARE --> GROUPS[process groups]
- GROUPS --> COUNT[**count usage**]
- COUNT --> CREATE[create event]
- CREATE --> EMIT[emit to clickhouse_events_json]
-
- DENY -.dropped.-> X[not counted]
- RESTRICT -.dropped.-> X
- RL -.redirected.-> OF[overflow topic, counted on the overflow lane]
- PARSE -.dlq.-> X
- TEAM -.dlq.-> X
- HIST -.dropped.-> X
- FILTERS -.dropped.-> X
- DROPOLD -.dropped.-> X
- TRANSFORM -.dropped.-> X
-```
-
-Counting sits between group processing and event creation, the last point where the event still carries its own team, name and Kafka message.
-Everything that can drop an event runs upstream of it.
-
-`resolveAnalyticsUsageKey` decides the key from the event name, so an event is billed under the product that owns it wherever it turns up.
-A known AI event that reaches this lane is billed as `ai_events`, not as a standard event, and the non-billable names (`$feature_flag_called`, `$experiment_exposure`, survey events, `$exception`, conversations widget events) return no key at all.
-That list mirrors `BILLABLE_EVENT_EXCLUDED_EVENTS` in `posthog/tasks/usage_report.py`; the two have to agree or the same team is billed differently by the two systems.
-The AI check matches the exact names in `AI_EVENT_TYPES` rather than the `$ai_` prefix, for the same reason: the report excludes the exact `AIEventType` values, so an unknown `$ai_something` is a standard billable event on both sides.
-
-Overflow is not a drop. A redirected event is consumed again on the overflow lane, whose consumer reports under its own topic and partition, so it is counted exactly once.
-
-### Why the identity is `{day}:{sha256 of event, distinct_id, uuid}`
-
-The first version of this keyed a record on the batch's consumed offset range and carried the batch's count.
-That is not replay-safe: Kafka does not promise the same batch boundaries twice, so a replay produces different IDs and the totals add.
-Measured before the change: 6 events read as batches of 3 produced `0-2:events`; the same events re-read as one batch produced `0-8:events`, a new ID overlapping the first, and the total doubled.
-
-The event's own identity has none of that. It travels inside the event and does not depend on how a consumer batched.
-Measured after the change: the same events re-consumed by a fresh consumer group with a different batch size wrote 6 raw rows where `FINAL` still reads 3 — the replay landed and deduplicated instead of billing twice.
-
-The UUID alone is not that identity. `sharded_events` is itself a `ReplacingMergeTree` sorted by `(team_id, toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid))`, so two events sharing a UUID but differing in day, name or distinct ID are separate rows there.
-The nightly report counts them separately too — `get_teams_with_billable_event_count_in_period` counts `distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)` — so keying on the UUID alone would have collapsed rows the report bills for.
-The `record_id` therefore carries that whole tuple minus the team the billing sorting key already holds. The timestamp is UTC-normalized upstream, so its first ten characters are the day `toDate` resolves.
-The tuple is hashed rather than joined, because event names and distinct IDs are client-supplied and together exceed the 512-byte identifier the service accepts. One oversized record makes the service reject the whole request, dropping every record batched with it.
-
-The cost is one record per event rather than one per batch. Records are still batched into requests of up to `USAGE_INGESTION_MAX_BATCH_SIZE`, so the request count is a function of batch size, not event count.
-
-### The one case that over-counts
-
-Counting happens before the Kafka produce, and the produce is not awaited.
-An event that fails to emit with `message_size_too_large` is counted but never lands in `clickhouse_events_json`.
-Moving the count onto the acknowledgement does not work: it resolves after the batch's flush step, so the count would land in a cleared accumulator.
-Emission retries five times, so the residue is bounded by that one non-retried failure, which also raises an ingestion warning.
-
-## AI ingestion
-
-Same shape, on its own lane. The allow step DLQs anything that is not an AI event, so every event that reaches the counting step is billable and the resolver returns `ai_events` unconditionally.
-
-AI events are double-written to `clickhouse_events_json` and `clickhouse_ai_events_json`. Counting runs before the split, so the double write bills once.
-
-## Error tracking
-
-```mermaid
-flowchart TD
- K[exceptions_ingestion] --> RESTRICT[token restrictions]
- RESTRICT --> RL[rate limit to overflow]
- RL --> PARSE[parse message]
- PARSE --> TEAM[resolve team]
- TEAM --> COOKIELESS[cookieless processing]
- COOKIELESS --> CYMBAL[cymbal: symbolication, fingerprint, issue link]
- CYMBAL --> PERSON[fetch person]
- PERSON --> TRANSFORM[hog transformations]
- TRANSFORM --> PREPARE[prepare event]
- PREPARE --> GROUPS[process groups]
- GROUPS --> COUNT[**count usage**]
- COUNT --> CREATE[create event]
- CREATE --> EMIT[emit to clickhouse_events_json]
-
- CYMBAL -.suppressed.-> X[not counted]
- RESTRICT -.dropped.-> X
- PARSE -.dlq.-> X
-```
-
-Cymbal is the Rust symbolication service, and it suppresses exceptions — a suppressed exception is dropped from the pipeline.
-Counting runs after it, so a suppressed exception is never billed.
-Cymbal runs before enrichment for an unrelated reason (it only needs the raw exception, so suppressing early saves the enrichment work), which happens to put every one of its drops upstream of the counting step.
-
-## CDP
-
-CDP reports through `CdpUsageReporterService`, which owns its own batching and flush timer.
-It is deliberately not derived from the `billable_invocation` app metric: the app metrics could be deleted without touching billing.
-Three call sites report, each next to the app metric it is independent of:
-
-| Site | When | record_id |
-| --------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------- |
-| `hog-function-invocation-pipeline.service.ts` | an event triggers at least one destination | `event:{eventUuid}` |
-| `hogflows/actions/hog_function.ts` | a workflow function action executed and was not skipped | `flow:{invocationId}:{actionStepCount}:{kind}` |
-| `cdp-source-webhooks.consumer.ts` | a webhook produced a workflow trigger | `webhook:{invocationId}` |
-
-The event-triggered site bills once per triggering event, not per destination, matching the existing app metric.
-The workflow site keys on `actionStepCount` so a cyclotron retry of the same step reuses the ID and deduplicates, while a loop that revisits the same action gets a new one and bills again.
-
-The webhook site mints its `invocationId` when it receives the request, which is what we want: ten webhooks carrying one sender-side ID are ten things we ingested and ten things we bill.
-The ID only has to survive our own retry of that one receipt, which it does.
-The three CDP sites share one `usage_key`, which is why they are the only producer that still prefixes its `record_id`.
-
-The reporter flushes on a timer rather than at a consumer batch boundary, and `CdpBaseConsumer.stop()` flushes it, so a graceful deploy loses nothing.
-An ungraceful exit can still lose up to one interval of records per pod.
-
-## Feature flags
-
-The billing aggregator already counts requests in memory per `(team, request_type, library, bucket)` and flushes them to Redis on a tick.
-Usage records are emitted from inside that flush, once a chunk has been credited to Redis, so a Redis retry cannot bill twice and the two stores can only disagree by a failed usage request.
-
-`record_id` is a fresh UUIDv7 per emission rather than something derived from the aggregation key.
-The key is not a stable identity for a delta: a Redis outage rebuckets and merges requeued entries, so the same key legitimately carries different quantities across flushes.
-ID reuse is therefore scoped to the retry the gRPC client performs on one request. This is the one producer whose records are aggregates rather than one per billed thing.
-
-Sends go through a bounded queue drained by one owned task, and `shutdown` closes the queue and awaits it within the aggregator's flush timeout, so a deploy does not lose records Redis just credited.
-A full queue drops and counts the drop rather than growing; Redis still holds the authoritative count.
-
-The two billable request types get their own usage keys, because the report prices them apart: `billable_feature_flag_requests_count_in_period` is `decide + local_evaluation * 10`.
-The producer reports what happened and leaves the weighting downstream, so a decide request lands under `feature_flag_requests` and a local evaluation under `feature_flag_local_evaluation_requests`, both at their raw counts.
-Remote config requests are telemetry and bill on neither side.
-
-## Trying it locally
-
-The service's compose entry sits behind the `ingestion` profile and builds from source, so run it from cargo instead:
-
-```sh
-docker compose -f docker-compose.dev.yml up -d db redis7 kafka clickhouse
-DEBUG=1 python manage.py migrate_clickhouse
-cd rust && USAGE_INGESTION_DATABASE_URL=postgres://posthog:posthog@localhost:5432/posthog \
- cargo run -p usage-ingestion
-```
-
-Then point a producer at it and turn its team matcher on:
-
-```sh
-USAGE_INGESTION_ADDR=localhost:7143 USAGE_INGESTION_REPORT_TEAMS='*' ./bin/start
-USAGE_INGESTION_ADDR=localhost:7143 USAGE_INGESTION_REPORT_TEAMS='*' cargo run -p feature-flags
-```
-
-Records land within one flush interval:
-
-```sql
-SELECT producer_id, usage_key, sum(quantity), count()
-FROM billing_usage_records GROUP BY 1, 2 ORDER BY 1, 2
-```
-
-Local development exposes `billing_usage_records` for every organization. Set
-`BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS` to a comma-separated list of organization UUIDs in other deployments.
-Configure that environment variable before enabling the real-time usage feature flag. The table stays hidden for every
-other organization.
-
-## What is not reported yet
-
-All current collectors mirror usage into usage-ingestion. Existing billing still reads the nightly usage report.
-
-## Where a collector still disagrees with the report
-
-Each row is a case where the two systems would bill the same team differently, so they have to be closed before billing reads these records.
-
-| usage_key | the report counts | the collector counts | effect |
-| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ----------------------------------------------- |
-| `survey_responses` | one response per `$survey_submission_id` per survey, and nothing for a survey attached to a product tour | every `survey sent` event | over-bills repeat submissions and product tours |
-| `warehouse_rows_synced` | nothing for a source created within seven days of the period end, and nothing at all during the warehouse free period | every completed billable job | over-bills a source's first week |
-| `feature_flag_local_evaluation_requests` | every local evaluation request | only the ones the Rust service answers | Django's own endpoint writes no record |
-
-The flags row is about routing, not counting.
-The Rust service records both billable request types - `Decide` from the decide handler, `FlagDefinitions` from the local-evaluation handler - and each has its own usage key.
-Django still serves `/api/feature_flag/local_evaluation` too, and that path increments the report's counter without writing a usage record, so whatever Contour routes there is uncollected.
-
-Session replay is the closest of the ones that were closed: the collector bills a new session under `session_replay_recordings` only when it is not mobile, and under `mobile_replay_recordings` only for the four SDKs the report bills.
-It still bills a recording the report would later drop for `is_deleted`, because deletion happens after the session is counted.
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 3448d5e0269c..d8718ce6abbd 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -13888,11 +13888,13 @@ dependencies = [
"common-kafka",
"common-liveness",
"envconfig",
+ "futures",
"health",
"metrics",
"metrics-exporter-prometheus",
"moka",
"rdkafka",
+ "redis",
"reqwest 0.12.28",
"serde",
"serde_json",
diff --git a/rust/usage-ingestion/Cargo.toml b/rust/usage-ingestion/Cargo.toml
index 751b189c4fc9..5d7a25742664 100644
--- a/rust/usage-ingestion/Cargo.toml
+++ b/rust/usage-ingestion/Cargo.toml
@@ -8,6 +8,7 @@ publish = false
async-trait = { workspace = true }
axum = { workspace = true }
chrono = { workspace = true }
+futures = { workspace = true }
common-database = { path = "../common/database" }
common-grpc = { path = "../common/grpc" }
common-kafka = { path = "../common/kafka" }
@@ -18,6 +19,7 @@ metrics = { workspace = true }
metrics-exporter-prometheus = { workspace = true }
moka = { workspace = true }
rdkafka = { workspace = true }
+redis = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/rust/usage-ingestion/README.md b/rust/usage-ingestion/README.md
index 958321f31e5f..3016253b31e9 100644
--- a/rust/usage-ingestion/README.md
+++ b/rust/usage-ingestion/README.md
@@ -30,6 +30,38 @@ 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.
+## Redis usage counters
+
+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,
+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`.
+
+The projection stores additive deltas, not usage record identities. Retrying
+after an accepted response or correcting a durable record can therefore
+increment its Valkey total again. ClickHouse remains the authoritative billing
+source, so do not use this projection for exact billing decisions.
+
+The dev stack runs the cluster on 6390 from both sides, so a host client uses
+`redis://127.0.0.1:6390` and the service container uses
+`redis://valkey-cluster:6390`. Start it and run its integration test with:
+
+```sh
+docker compose -f docker-compose.dev.yml up -d valkey-cluster
+flox activate -- bash -c 'cd rust && cargo test -p usage-ingestion --test counters -- --ignored --nocapture'
+```
+
+The test writes 1,024 independent team scopes plus one organization scope,
+checks the hour and day keys share a cluster slot, and proves cluster routing
+still rejects an intentionally cross-slot transaction.
+
## Where it runs
| Resource | Placement |
@@ -115,7 +147,10 @@ flox activate -- bash -c 'cd rust && cargo test -p usage-ingestion --test load -
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.
+timestamp. It also flushes the accepted requests to Valkey Cluster, then
+checks the 27 hourly/daily hashes stay at four fields each and within a
+64-byte–1-KiB per-key memory budget. Add a counter series only with an
+intentional budget adjustment.
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.
@@ -124,7 +159,7 @@ 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_REQUESTS` | 5000 | total requests, 10% of them retries, minimum 320 |
| `USAGE_INGESTION_E2E_LOAD_CONCURRENCY` | 128 | requests in flight |
| `USAGE_INGESTION_E2E_LOAD_CHANNELS` | 8 | gRPC connections the load spreads over |
@@ -141,3 +176,177 @@ producer's 20ms linger until concurrency passes 512, measured at 20000 requests:
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.
+
+## Usage producers
+
+Every producer of `billing_usage_records` counts after the last step that can
+drop the billed thing, and before the row is written.
+
+### Record identity and exact reads
+
+`ReplacingMergeTree(inserted_at)` sorts by `(team_id, toDate(timestamp),
+producer_id, usage_key, record_id)`. Records sharing those fields collapse to
+one, with the later send winning. A producer's `record_id` must therefore be a
+stable identity for one billed thing: retries and reprocessing reuse it, while
+different work never does.
+
+This protects against our duplication, not a sender's. If a customer sends the
+same thing twice, we ingest and bill it twice. `usage_key` is already in the
+key, so `record_id` does not repeat it; CDP prefixes its IDs only because its
+three call sites share one `usage_key`.
+
+`timestamp` is in the sort key as a date because billing reads filter time
+ranges. Every producer stamps it from its own clock when it flushes, never from
+a customer-controlled value. Deduplication is consequently scoped to a UTC
+day, so a reprocess that crosses midnight leaves two rows.
+
+`inserted_at` is the engine version column but is absent from the HogQL schema.
+`timestamp` is monotonic per resend, so an exact, tightly-scoped read groups by
+the sorting key and uses `argMax(quantity, timestamp)`. A plain `sum(quantity)`
+can count unmerged duplicates and is suitable only for an approximate read.
+
+| producer_id | usage_key | unit | record_id | deployment |
+| --- | --- | --- | --- | --- |
+| `ingestion` | `events`, `ai_events` | events | `{day}:{sha256 of event, distinct_id, uuid}` | ingestion consumers, ingestion API |
+| `ai-ingestion` | `ai_events` | events | `{day}:{sha256 of event, distinct_id, uuid}` | AI ingestion consumer |
+| `error-tracking` | `exceptions` | events | `{day}:{sha256 of event, distinct_id, uuid}` | error tracking server |
+| `cdp` | `cdp_billable_invocations` | invocations | `event:{eventUuid}` / `flow:{invocationId}:{actionStepCount}:{kind}` / `webhook:{invocationId}` | CDP consumers |
+| `feature-flags` | `feature_flag_requests`, `feature_flag_local_evaluation_requests` | requests | fresh UUIDv7 per flush | feature flags service |
+| `ingestion` | `survey_responses` | events | `{day}:{sha256 of event, distinct_id, uuid}` | ingestion consumers, ingestion API |
+| `warehouse-sources` | `warehouse_rows_synced` | rows | the ExternalDataJob ID | warehouse sources worker |
+| `batch-exports` | `batch_export_rows` | rows | the BatchExportRun ID | batch exports worker |
+| `replay-vision` | `replay_vision_credits` | credits | the observation ID | replay vision worker |
+| `logs` | `logs_bytes`, `logs_records` | bytes, records | fresh UUIDv7 per flush | logs ingestion server |
+| `apm-traces` | `apm_traces_bytes`, `apm_traces_spans` | bytes, records | fresh UUIDv7 per flush | traces ingestion server |
+| `session-replay` | `session_replay_recordings`, `mobile_replay_recordings` | recordings | the session ID | session replay consumer |
+| `ingestion` | `enhanced_person_events` | events | `{day}:{sha256 of event, distinct_id, uuid}` | ingestion consumers, ingestion API |
+
+Every producer reads the following environment variables. Since every producer
+is its own deployment, the same name rolls out per producer from that service's
+configuration.
+
+| Env var | Default | Meaning |
+| --- | --- | --- |
+| `USAGE_INGESTION_REPORT_TEAMS` | `''` | `''` reports nothing, `*` every team, `1,2` those teams. |
+| `USAGE_INGESTION_ADDR` | `''` outside dev | Gateway `host:port`. Empty also reports nothing. |
+| `USAGE_INGESTION_TLS` | `false` | Plaintext in-cluster. Feature flags rejects `true` because its tonic build has no TLS. |
+| `USAGE_INGESTION_TIMEOUT_MS` | `5000` | Per attempt, not per batch. Feature flags retries transient failure three times. |
+
+There is deliberately no percentage option: sampling a share of a team's
+events would bill that team a fraction of its usage.
+
+### Aggregate producers
+
+Most records carry quantity 1 and name one billed thing, so their aggregate
+lives in ClickHouse rather than in the producer. Feature flags, logs, and APM
+instead send per-flush aggregates. They have no replayable item identity, so
+each flush mints a fresh UUIDv7. This is retry-safe but not replay-safe: a
+replayed delta is new usage. Deriving IDs from a clock could collapse two pods'
+real flushes.
+
+### Analytics ingestion
+
+Analytics usage is counted after group processing and before event creation.
+That is the last point where the event has its team, name, and Kafka message;
+all drop paths are upstream. `resolveAnalyticsUsageKey` selects the product key
+from the event name. The non-billable names return no key, and the list mirrors
+`BILLABLE_EVENT_EXCLUDED_EVENTS` in `posthog/tasks/usage_report.py` so the
+collector and nightly report agree.
+
+Overflow is not a drop: the overflow consumer reports on its own topic and
+partition, so a redirected event is counted once.
+
+The identity is `{day}:{sha256 of event, distinct_id, uuid}` rather than a
+consumer offset range because Kafka does not preserve batch boundaries on
+replay. The event identity travels with the event and matches the tuple the
+nightly report counts. It is hashed because customer-supplied event names and
+distinct IDs could otherwise exceed the service's 512-byte identifier limit.
+
+Counting is before Kafka produce, which is not awaited. An event that fails to
+emit with `message_size_too_large` is counted but never lands in
+`clickhouse_events_json`; moving the count to the acknowledgement would miss it
+after the accumulator clears. Five emit retries bound this residue to the one
+non-retried failure, which also raises an ingestion warning.
+
+### AI ingestion and error tracking
+
+AI ingestion has its own lane. Its allow step DLQs non-AI events, so every
+event reaching its counter is billable as `ai_events`. It writes to both
+`clickhouse_events_json` and `clickhouse_ai_events_json`; counting before that
+split bills once.
+
+Error tracking counts after Cymbal, the Rust symbolication service. Cymbal can
+suppress an exception, so a suppressed exception is never billed. Token
+restriction and parse failures are likewise upstream of the counter.
+
+### CDP
+
+`CdpUsageReporterService` owns CDP batching and its flush timer independently
+of the `billable_invocation` app metric. It reports when an event triggers at
+least one destination (`event:{eventUuid}`), when a non-skipped workflow action
+executes (`flow:{invocationId}:{actionStepCount}:{kind}`), and when a webhook
+creates a workflow trigger (`webhook:{invocationId}`). The action step count
+deduplicates a retry but bills a loop revisit. `CdpBaseConsumer.stop()` flushes
+the reporter, so a graceful deploy loses nothing; an ungraceful exit can lose
+one interval per pod.
+
+### Feature flags
+
+The feature-flags billing aggregator counts requests in memory per `(team,
+request_type, library, bucket)` and flushes to Redis on a tick. It emits usage
+records after a chunk is credited to Redis, so a Redis retry cannot bill twice.
+A bounded queue drained by one owned task sends records; shutdown closes and
+awaits it within the aggregator flush timeout. A full queue drops and counts
+the drop rather than growing, while Redis retains the authoritative count.
+
+The raw `feature_flag_requests` and
+`feature_flag_local_evaluation_requests` keys stay separate because the report
+prices them differently. Remote-config requests bill on neither side.
+
+### Trying it locally
+
+The compose entry sits behind the `ingestion` profile and builds from source,
+so run it from Cargo instead:
+
+```sh
+docker compose -f docker-compose.dev.yml up -d db redis7 kafka clickhouse
+DEBUG=1 python manage.py migrate_clickhouse
+cd rust && USAGE_INGESTION_DATABASE_URL=postgres://posthog:posthog@localhost:5432/posthog \\
+ cargo run -p usage-ingestion
+```
+
+Then point a producer at it and turn on its team matcher:
+
+```sh
+USAGE_INGESTION_ADDR=localhost:7143 USAGE_INGESTION_REPORT_TEAMS='*' ./bin/start
+USAGE_INGESTION_ADDR=localhost:7143 USAGE_INGESTION_REPORT_TEAMS='*' cargo run -p feature-flags
+```
+
+Records land within one flush interval:
+
+```sql
+SELECT producer_id, usage_key, sum(quantity), count()
+FROM billing_usage_records GROUP BY 1, 2 ORDER BY 1, 2
+```
+
+Local development exposes `billing_usage_records` for every organization. Set
+`BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS` to a comma-separated list of
+organization UUIDs in other deployments before enabling the real-time usage
+feature flag; the table stays hidden for every other organization.
+
+### Coverage gaps
+
+All current collectors mirror usage into `usage-ingestion`. Existing billing
+still reads the nightly usage report.
+
+| usage_key | the report counts | the collector counts | effect |
+| --- | --- | --- | --- |
+| `survey_responses` | one response per `$survey_submission_id` per survey, excluding product-tour surveys | every `survey sent` event | over-bills repeat submissions and product tours |
+| `warehouse_rows_synced` | nothing for a source created within seven days of the period end or during the warehouse free period | every completed billable job | over-bills a source's first week |
+| `feature_flag_local_evaluation_requests` | every local evaluation request | only ones served by the Rust service | Django's endpoint writes no record |
+
+The feature-flags gap is routing, not counting: the Rust service records both
+billable request types, but Django still serves
+`/api/feature_flag/local_evaluation` and increments the report counter without
+writing a usage record. Session replay is also counted before later deletion,
+so it can bill a recording the report subsequently drops as `is_deleted`.
diff --git a/rust/usage-ingestion/src/config.rs b/rust/usage-ingestion/src/config.rs
index 92fa4e739574..4617612ed2c8 100644
--- a/rust/usage-ingestion/src/config.rs
+++ b/rust/usage-ingestion/src/config.rs
@@ -3,6 +3,8 @@ use std::time::Duration;
use common_kafka::config::KafkaConfig;
use envconfig::Envconfig;
+use crate::counters::CounterConfig;
+
/// WarpStream's recommended librdkafka producer settings.
/// <https://docs.warpstream.com/warpstream/kafka/configure-kafka-client/tuning-for-performance>
const BATCH_SIZE: u32 = 16_000_000;
@@ -36,6 +38,17 @@ pub struct Config {
pub kafka_producer_linger_ms: u32,
#[envconfig(from = "USAGE_INGESTION_MAX_BATCH_SIZE", default = "500")]
pub max_batch_size: usize,
+ /// Empty keeps the Redis projection disabled, which is the safe default for existing deployments.
+ #[envconfig(from = "USAGE_INGESTION_REDIS_URL", default = "")]
+ 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,
+ #[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",
@@ -56,6 +69,20 @@ impl Config {
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());
}
+ if self.redis_flush_interval_seconds == 0 {
+ return Err(
+ "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());
+ }
+ 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(
@@ -65,6 +92,14 @@ impl Config {
Ok(())
}
+ pub fn redis_counter_config(&self) -> CounterConfig {
+ CounterConfig {
+ connections: self.redis_connections,
+ flush_concurrency: self.redis_flush_concurrency,
+ max_series_per_bucket: self.redis_max_series_per_bucket,
+ }
+ }
+
pub fn grpc_max_connection_age(&self) -> Option<Duration> {
if self.grpc_max_connection_age_secs == 0 {
None
@@ -112,6 +147,11 @@ mod tests {
kafka_compression_codec: "lz4".to_string(),
kafka_producer_linger_ms: 100,
max_batch_size: 500,
+ redis_url: String::new(),
+ 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,
}
@@ -156,4 +196,33 @@ mod tests {
assert_eq!(kafka.kafka_compression_codec, "none");
assert_eq!(kafka.kafka_producer_linger_ms, 5);
}
+
+ #[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",
+ ),
+ (
+ 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.rs
new file mode 100644
index 000000000000..2d064efcd4f1
--- /dev/null
+++ b/rust/usage-ingestion/src/counters.rs
@@ -0,0 +1,578 @@
+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_async::ClusterConnection;
+use tokio::sync::Mutex as AsyncMutex;
+use tracing::warn;
+use uuid::Uuid;
+
+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_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 {
+ fn default() -> Self {
+ Self {
+ connections: DEFAULT_CONNECTIONS,
+ flush_concurrency: DEFAULT_FLUSH_CONCURRENCY,
+ max_series_per_bucket: DEFAULT_MAX_SERIES_PER_BUCKET,
+ }
+ }
+}
+
+#[derive(Clone, Debug, Eq, Hash, PartialEq)]
+pub enum CounterScope {
+ Team(i64),
+ Organization(Uuid),
+}
+
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
+pub enum Bucket {
+ Hour(i64),
+ Day(i64),
+}
+
+impl Bucket {
+ fn from_timestamp(timestamp: DateTime<Utc>) -> [Self; 2] {
+ let seconds = timestamp.timestamp();
+ [
+ Self::Hour(seconds.div_euclid(60 * 60)),
+ Self::Day(seconds.div_euclid(24 * 60 * 60)),
+ ]
+ }
+
+ fn suffix(self) -> &'static str {
+ match self {
+ Self::Hour(_) => "h",
+ Self::Day(_) => "d",
+ }
+ }
+
+ fn index(self) -> i64 {
+ match self {
+ Self::Hour(index) | Self::Day(index) => index,
+ }
+ }
+
+ fn ttl_seconds(self) -> u64 {
+ match self {
+ Self::Hour(_) => HOURLY_TTL_SECONDS,
+ Self::Day(_) => DAILY_TTL_SECONDS,
+ }
+ }
+}
+
+#[derive(Clone, Debug, Eq, Hash, PartialEq)]
+struct CounterEntry {
+ bucket: Bucket,
+ field: String,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub enum CounterAddError {
+ TimestampOutOfRange,
+ TooManySeries,
+ Overflow,
+}
+
+impl CounterAddError {
+ pub fn reason(&self) -> &'static str {
+ match self {
+ Self::TimestampOutOfRange => "timestamp_out_of_range",
+ Self::TooManySeries => "too_many_series",
+ Self::Overflow => "overflow",
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct ScopeCounters {
+ scope: CounterScope,
+ entries: HashMap<CounterEntry, i64>,
+}
+
+/// A process-local, lossy aggregation of Kafka-confirmed usage records.
+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.
+ self.add(
+ record.team_id,
+ record.organization_id,
+ &record.usage_key,
+ &record.unit,
+ record.quantity,
+ record.usage_timestamp,
+ )
+ }
+
+ pub fn add(
+ &self,
+ team_id: i64,
+ organization_id: Uuid,
+ usage_key: &str,
+ unit: &str,
+ quantity: i64,
+ timestamp: DateTime<Utc>,
+ ) -> Result<(), CounterAddError> {
+ let now = Utc::now();
+ if timestamp < now - MAX_PAST_TIMESTAMP || timestamp > now + MAX_FUTURE_TIMESTAMP {
+ return Err(CounterAddError::TimestampOutOfRange);
+ }
+ let field = usage_field(usage_key, unit);
+ let buckets = Bucket::from_timestamp(timestamp);
+ let scopes = [
+ CounterScope::Team(team_id),
+ CounterScope::Organization(organization_id),
+ ];
+ 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,
+ ) {
+ rejection = Some(error);
+ }
+ }
+ 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)
+ .into_iter()
+ .map(|(scope, entries)| ScopeCounters { scope, entries })
+ .collect()
+ }
+
+ pub fn scope_count_for_records(records: &[KafkaBillingUsageRecord]) -> usize {
+ records
+ .iter()
+ .flat_map(|record| {
+ [
+ CounterScope::Team(record.team_id),
+ CounterScope::Organization(record.organization_id),
+ ]
+ })
+ .collect::<std::collections::HashSet<_>>()
+ .len()
+ }
+}
+
+/// 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,
+}
+
+#[async_trait]
+pub trait CounterStore: Send + Sync {
+ async fn flush_scope(&self, counters: ScopeCounters) -> Result<ScopeFlush, 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 {
+ 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,
+ max_series_per_bucket: config.max_series_per_bucket,
+ })
+ }
+
+ 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()]
+ }
+}
+
+#[async_trait]
+impl CounterStore for RedisCounterStore {
+ async fn flush_scope(&self, counters: ScopeCounters) -> Result<ScopeFlush, 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)
+ .arg(&key)
+ .arg(&entry.field)
+ .arg(quantity)
+ .arg(entry.bucket.ttl_seconds())
+ .arg(self.max_series_per_bucket);
+ }
+ 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,
+ })
+ }
+}
+
+pub fn counter_key(scope: &CounterScope, bucket: Bucket) -> String {
+ let scope = match scope {
+ CounterScope::Team(team_id) => format!("team:{team_id}"),
+ CounterScope::Organization(organization_id) => format!("org:{organization_id}"),
+ };
+ format!(
+ "usage:v1:{{{scope}}}:{}:{}",
+ bucket.suffix(),
+ bucket.index()
+ )
+}
+
+/// Both buckets of one scope move together, so a rejected series leaves the scope untouched.
+fn add_to_scope(
+ entries: &mut HashMap<CounterEntry, i64>,
+ 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) {
+ let entry = CounterEntry {
+ bucket,
+ field: field.to_string(),
+ };
+ *total = match entries.get(&entry) {
+ 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
+ }
+ };
+ }
+ for (bucket, total) in buckets.into_iter().zip(totals) {
+ entries.insert(
+ CounterEntry {
+ bucket,
+ field: field.to_string(),
+ },
+ total,
+ );
+ }
+ Ok(())
+}
+
+fn usage_field(usage_key: &str, unit: &str) -> String {
+ // The length prefix keeps the pair unambiguous even if a producer uses a delimiter in a name.
+ format!("{}:{usage_key}{unit}", usage_key.len())
+}
+
+pub async fn flush(store: Arc<dyn CounterStore>, counters: Vec<ScopeCounters>) -> FlushOutcome {
+ flush_with_concurrency(store, counters, DEFAULT_FLUSH_CONCURRENCY).await
+}
+
+async fn flush_with_concurrency(
+ store: Arc<dyn CounterStore>,
+ counters: Vec<ScopeCounters>,
+ flush_concurrency: usize,
+) -> FlushOutcome {
+ let results = stream::iter(counters)
+ .map(|counters| {
+ let store = Arc::clone(&store);
+ async move {
+ let entries = counters.entries.len();
+ match store.flush_scope(counters).await {
+ Ok(flushed) => FlushOutcome {
+ commands: flushed.commands,
+ capped: flushed.capped,
+ ..FlushOutcome::default()
+ },
+ Err(error) => {
+ warn!(%error, dropped_deltas = entries, "usage counter flush failed");
+ FlushOutcome {
+ dropped: entries,
+ failed_scopes: 1,
+ ..FlushOutcome::default()
+ }
+ }
+ }
+ }
+ })
+ .buffer_unordered(flush_concurrency)
+ .collect::<Vec<_>>()
+ .await;
+ results
+ .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,
+ })
+}
+
+pub fn spawn_flush_task(
+ accumulator: Arc<CounterAccumulator>,
+ redis_url: String,
+ interval: Duration,
+ config: CounterConfig,
+) {
+ tokio::spawn(async move {
+ let mut ticker = tokio::time::interval(interval);
+ 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;
+ }
+ }
+ }
+ 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);
+ 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;
+ }
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hashes_stay_with_their_scope_and_accumulator_merges_series() {
+ let organization_id = Uuid::nil();
+ let accumulator = CounterAccumulator::default();
+ let timestamp = Utc::now();
+ accumulator
+ .add(42, organization_id, "events", "event", 2, timestamp)
+ .unwrap();
+ accumulator
+ .add(42, organization_id, "events", "event", 3, timestamp)
+ .unwrap();
+ accumulator
+ .add(43, organization_id, "events", "event", 1, timestamp)
+ .unwrap();
+
+ let drained = accumulator.drain();
+ assert_eq!(drained.len(), 3);
+ assert!(accumulator.drain().is_empty());
+ let team = drained
+ .iter()
+ .find(|counters| counters.scope == CounterScope::Team(42))
+ .unwrap();
+ assert_eq!(team.entries.len(), 2);
+ assert!(team.entries.values().all(|quantity| *quantity == 5));
+ assert_eq!(
+ counter_key(&CounterScope::Team(42), Bucket::Hour(477_336)),
+ "usage:v1:{team:42}:h:477336"
+ );
+ assert!(counter_key(&CounterScope::Team(42), Bucket::Hour(477_336)).contains("{team:42}"));
+ assert!(counter_key(&CounterScope::Team(42), Bucket::Day(19_889)).contains("{team:42}"));
+ }
+
+ #[test]
+ fn bounds_series_timestamps_and_deltas() {
+ let organization_id = Uuid::nil();
+ let accumulator = CounterAccumulator::default();
+ let now = Utc::now();
+
+ assert_eq!(
+ accumulator.add(
+ 42,
+ organization_id,
+ "events",
+ "event",
+ 1,
+ now - ChronoDuration::days(8),
+ ),
+ Err(CounterAddError::TimestampOutOfRange)
+ );
+ assert_eq!(
+ accumulator.add(
+ 42,
+ organization_id,
+ "events",
+ "event",
+ 1,
+ now + ChronoDuration::hours(25),
+ ),
+ 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)
+ .unwrap();
+ assert_eq!(
+ overflow.add(43, organization_id, "events", "event", 1, now),
+ 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/lib.rs b/rust/usage-ingestion/src/lib.rs
index c94d23269d43..3ff66c142742 100644
--- a/rust/usage-ingestion/src/lib.rs
+++ b/rust/usage-ingestion/src/lib.rs
@@ -1,4 +1,5 @@
pub mod config;
+pub mod counters;
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
index ab49c975400a..f1d206f5a81e 100644
--- a/rust/usage-ingestion/src/main.rs
+++ b/rust/usage-ingestion/src/main.rs
@@ -15,6 +15,7 @@ use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, Layer};
use usage_ingestion::config::Config;
+use usage_ingestion::counters::{spawn_flush_task, CounterAccumulator};
use usage_ingestion::resolver::PostgresOrganizationResolver;
use usage_ingestion::service::UsageIngestionService;
use usage_ingestion_proto::usage_ingestion::v1::usage_ingestion_server::UsageIngestionServer;
@@ -70,11 +71,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.register("kafka_producer".to_string(), Duration::from_secs(30))
.await;
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 service = UsageIngestionService::new(
producer,
resolver,
config.max_batch_size,
config.topic.clone(),
+ counters.as_ref().map(Arc::clone),
);
// Buckets only for the shared gRPC histogram, so it renders the same way personhog's does
@@ -89,6 +98,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
GRPC_DURATION_BUCKETS_MS,
)?
.install_recorder()?;
+ if let Some(accumulator) = counters {
+ spawn_flush_task(
+ accumulator,
+ config.redis_url,
+ Duration::from_secs(config.redis_flush_interval_seconds),
+ redis_counter_config,
+ );
+ }
let metrics_address = config.metrics_address.clone();
let health_for_routes = health.clone();
tokio::spawn(async move {
@@ -121,7 +138,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// ponytail: tonic 0.12 adds no jitter here. Move to client-side round-robin if the
// synchronized reconnect shows up as a latency sawtooth.
let mut builder = Server::builder();
- if let Some(age) = config.grpc_max_connection_age() {
+ if let Some(age) = grpc_max_connection_age {
builder = builder.max_connection_age(age);
}
builder
diff --git a/rust/usage-ingestion/src/record.rs b/rust/usage-ingestion/src/record.rs
index bd72cc8bbd2b..7d794c1bf01e 100644
--- a/rust/usage-ingestion/src/record.rs
+++ b/rust/usage-ingestion/src/record.rs
@@ -38,6 +38,8 @@ pub struct KafkaBillingUsageRecord {
pub quantity: i64,
pub timestamp: String,
pub inserted_at: String,
+ #[serde(skip)]
+ pub usage_timestamp: DateTime<Utc>,
}
impl KafkaBillingUsageRecord {
@@ -76,6 +78,7 @@ impl KafkaBillingUsageRecord {
quantity: record.quantity,
timestamp: timestamp.to_rfc3339_opts(SecondsFormat::Millis, true),
inserted_at: inserted_at.to_rfc3339_opts(SecondsFormat::Millis, true),
+ usage_timestamp: timestamp,
})
}
}
diff --git a/rust/usage-ingestion/src/service.rs b/rust/usage-ingestion/src/service.rs
index 68573fd9dceb..f19cca101d3b 100644
--- a/rust/usage-ingestion/src/service.rs
+++ b/rust/usage-ingestion/src/service.rs
@@ -14,6 +14,7 @@ use usage_ingestion_proto::usage_ingestion::v1::{
};
use uuid::Uuid;
+use crate::counters::CounterAccumulator;
use crate::record::KafkaBillingUsageRecord;
use crate::resolver::{OrganizationResolver, ResolveError};
@@ -22,6 +23,7 @@ pub struct UsageIngestionService {
resolver: Arc<dyn OrganizationResolver>,
max_batch_size: usize,
topic: String,
+ counters: Option<Arc<CounterAccumulator>>,
}
impl UsageIngestionService {
@@ -30,12 +32,14 @@ impl UsageIngestionService {
resolver: Arc<dyn OrganizationResolver>,
max_batch_size: usize,
topic: String,
+ counters: Option<Arc<CounterAccumulator>>,
) -> Self {
Self {
producer,
resolver,
max_batch_size,
topic,
+ counters,
}
}
@@ -151,8 +155,8 @@ impl UsageIngestion for UsageIngestionService {
.map(|record| record.record_id.clone())
.collect::<Vec<_>>();
// No key: nothing downstream reads per-team order, and a team key crowds one partition.
- let payloads = prepared.into_iter().map(|record| {
- serde_json::to_vec(&record)
+ let payloads = prepared.iter().map(|record| {
+ serde_json::to_vec(record)
.map(|payload| (None, payload))
.map_err(|error| {
Status::internal(format!("failed to encode usage record: {error}"))
@@ -175,6 +179,21 @@ impl UsageIngestion for UsageIngestionService {
));
}
+ if let Some(counters) = &self.counters {
+ metrics::histogram!("usage_ingestion_distinct_scopes_per_request")
+ .record(CounterAccumulator::scope_count_for_records(&prepared) as f64);
+ for record in &prepared {
+ if let Err(error) = counters.add_record(record) {
+ metrics::counter!(
+ "usage_ingestion_redis_counter_rejected_deltas_total",
+ "reason" => error.reason()
+ )
+ .increment(1);
+ metrics::counter!("usage_ingestion_redis_counter_errors_total").increment(1);
+ }
+ }
+ }
+
Ok(Response::new(IngestBillingUsageResponse {
accepted_record_ids,
}))
@@ -254,7 +273,7 @@ mod tests {
.set("bootstrap.servers", "localhost:9092")
.create_with_context(KafkaContext::new(AlwaysHealthy))
.expect("failed to build the test producer");
- UsageIngestionService::new(producer, resolver, 500, "test-topic".to_string())
+ UsageIngestionService::new(producer, resolver, 500, "test-topic".to_string(), None)
}
fn service() -> UsageIngestionService {
diff --git a/rust/usage-ingestion/tests/common/mod.rs b/rust/usage-ingestion/tests/common/mod.rs
index c74867b0ec1a..3a22d65b5764 100644
--- a/rust/usage-ingestion/tests/common/mod.rs
+++ b/rust/usage-ingestion/tests/common/mod.rs
@@ -15,6 +15,7 @@ use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use tokio_stream::wrappers::TcpListenerStream;
use tonic::transport::{Channel, Server};
+use usage_ingestion::counters::CounterAccumulator;
use usage_ingestion::resolver::{OrganizationResolver, ResolveError};
use usage_ingestion::service::UsageIngestionService;
use usage_ingestion_proto::usage_ingestion::v1::usage_ingestion_client::UsageIngestionClient;
@@ -102,7 +103,11 @@ pub struct Service {
}
impl Service {
- pub async fn start(max_batch_size: usize, organization_id: Uuid) -> Self {
+ pub async fn start(
+ max_batch_size: usize,
+ organization_id: Uuid,
+ counters: Option<Arc<CounterAccumulator>>,
+ ) -> Self {
let producer = create_kafka_producer(
&KafkaConfig {
kafka_hosts: kafka_hosts(),
@@ -119,6 +124,7 @@ impl Service {
Arc::new(FixedResolver(organization_id)),
max_batch_size,
topic(),
+ counters,
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
diff --git a/rust/usage-ingestion/tests/counters.rs b/rust/usage-ingestion/tests/counters.rs
new file mode 100644
index 000000000000..1edd0602b84f
--- /dev/null
+++ b/rust/usage-ingestion/tests/counters.rs
@@ -0,0 +1,164 @@
+//! Cluster-backed counter checks. Start the dev Valkey cluster first:
+//! `docker compose -f docker-compose.dev.yml up -d valkey-cluster`.
+
+use std::sync::Arc;
+
+use chrono::Utc;
+use redis::cluster::ClusterClient;
+use redis::AsyncCommands;
+use usage_ingestion::counters::{
+ counter_key, flush, Bucket, CounterAccumulator, CounterScope, CounterStore, RedisCounterStore,
+};
+use uuid::Uuid;
+
+const SCOPES: i64 = 1_024;
+
+fn redis_url() -> String {
+ std::env::var("USAGE_INGESTION_REDIS_URL")
+ .unwrap_or_else(|_| "redis://127.0.0.1:6390".to_string())
+}
+
+#[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() {
+ let timestamp = Utc::now();
+ let organization_id = Uuid::new_v4();
+ let usage_key = format!("integration_events_{}", Uuid::new_v4());
+ let field = format!("{}:{usage_key}event", usage_key.len());
+ let first_team_id = 1_000_000 + (Uuid::new_v4().as_u128() % 1_000_000) as i64;
+ let accumulator = CounterAccumulator::default();
+ for offset in 0..SCOPES {
+ let team_id = first_team_id + offset;
+ accumulator
+ .add(
+ team_id,
+ organization_id,
+ &usage_key,
+ "event",
+ offset + 1,
+ timestamp,
+ )
+ .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 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);
+
+ let client = ClusterClient::new([redis_url()]).expect("invalid Valkey Cluster URL");
+ let mut connection = client
+ .get_async_connection()
+ .await
+ .expect("failed to connect to Valkey Cluster");
+ let team_scope = CounterScope::Team(first_team_id + SCOPES - 1);
+ let hour_key = counter_key(
+ &team_scope,
+ Bucket::Hour(timestamp.timestamp().div_euclid(3600)),
+ );
+ let day_key = counter_key(
+ &team_scope,
+ Bucket::Day(timestamp.timestamp().div_euclid(86400)),
+ );
+ let hour_slot: u16 = redis::cmd("CLUSTER")
+ .arg("KEYSLOT")
+ .arg(&hour_key)
+ .query_async(&mut connection)
+ .await
+ .expect("cluster did not report the hourly key slot");
+ let day_slot: u16 = redis::cmd("CLUSTER")
+ .arg("KEYSLOT")
+ .arg(&day_key)
+ .query_async(&mut connection)
+ .await
+ .expect("cluster did not report the daily key slot");
+ assert_eq!(
+ hour_slot, day_slot,
+ "one scope must stay in one cluster slot"
+ );
+ let other_slot: u16 = redis::cmd("CLUSTER")
+ .arg("KEYSLOT")
+ .arg(counter_key(
+ &CounterScope::Team(first_team_id),
+ Bucket::Hour(timestamp.timestamp().div_euclid(3600)),
+ ))
+ .query_async(&mut connection)
+ .await
+ .expect("cluster did not report another team key slot");
+ assert_ne!(
+ hour_slot, other_slot,
+ "independent teams should shard separately"
+ );
+
+ let quantity: i64 = connection
+ .hget(&hour_key, field)
+ .await
+ .expect("the hourly counter was not written");
+ assert_eq!(quantity, SCOPES);
+ let hourly_ttl: i64 = redis::cmd("TTL")
+ .arg(&hour_key)
+ .query_async(&mut connection)
+ .await
+ .expect("failed to read the hourly TTL");
+ assert!((25 * 60 * 60 - 3..=25 * 60 * 60).contains(&hourly_ttl));
+
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
+ let retry = CounterAccumulator::default();
+ retry
+ .add(
+ first_team_id + SCOPES - 1,
+ organization_id,
+ "ttl_does_not_refresh",
+ "event",
+ 1,
+ timestamp,
+ )
+ .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)
+ .await
+ .expect("failed to read the hourly TTL after a retry");
+ assert!(
+ retried_hourly_ttl < hourly_ttl,
+ "the hourly TTL was refreshed"
+ );
+ let daily_ttl: i64 = redis::cmd("TTL")
+ .arg(&day_key)
+ .query_async(&mut connection)
+ .await
+ .expect("failed to read the daily TTL");
+ assert!((31 * 24 * 60 * 60 - 3..=31 * 24 * 60 * 60).contains(&daily_ttl));
+
+ // The cluster client or server rejects this transaction. The successful writes above
+ // therefore prove the production pipeline is not combining different scope hash tags.
+ let error = redis::pipe()
+ .atomic()
+ .cmd("HINCRBY")
+ .arg("usage:v1:{scope-a}:h:1")
+ .arg("field")
+ .arg(1)
+ .ignore()
+ .cmd("HINCRBY")
+ .arg("usage:v1:{scope-b}:h:1")
+ .arg("field")
+ .arg(1)
+ .ignore()
+ .query_async::<()>(&mut connection)
+ .await
+ .expect_err("Valkey Cluster should reject a cross-slot transaction");
+ let error = error.to_string();
+ assert!(
+ error.to_ascii_lowercase().contains("crossslot") || error.contains("same slot"),
+ "unexpected cross-slot error: {error}"
+ );
+}
diff --git a/rust/usage-ingestion/tests/e2e.rs b/rust/usage-ingestion/tests/e2e.rs
index 5847bd528aa7..f904b8aac1d1 100644
--- a/rust/usage-ingestion/tests/e2e.rs
+++ b/rust/usage-ingestion/tests/e2e.rs
@@ -29,7 +29,7 @@ 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 service = Service::start(500, organization_id, None).await;
let mut client = service.client().await;
let record_id = Uuid::new_v4().to_string();
diff --git a/rust/usage-ingestion/tests/load.rs b/rust/usage-ingestion/tests/load.rs
index 6f0d7d5eaec8..d1ca3728510b 100644
--- a/rust/usage-ingestion/tests/load.rs
+++ b/rust/usage-ingestion/tests/load.rs
@@ -10,13 +10,26 @@ use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::time::{Duration, Instant};
+use chrono::{DateTime, Utc};
use common::{clickhouse, clickhouse_url, env_usize, table, Service};
+use redis::cluster::ClusterClient;
+use redis::AsyncCommands;
use tokio::sync::Semaphore;
+use usage_ingestion::counters::{
+ counter_key, flush, Bucket, CounterAccumulator, CounterScope, CounterStore, RedisCounterStore,
+};
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
+fn base_timestamp_ms() -> i64 {
+ Utc::now()
+ .date_naive()
+ .and_hms_opt(0, 0, 0)
+ .unwrap()
+ .and_utc()
+ .timestamp_millis()
+}
/// 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;
@@ -25,6 +38,15 @@ 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 TEAMS: usize = 8;
+const BUCKETS_PER_SCOPE: usize = 3;
+const MIN_BYTES_PER_COUNTER_KEY: usize = 64;
+// This is the Redis budget for one hourly or daily hash with the four usage fields below.
+// Raise it deliberately when adding counter series, rather than letting per-request data grow it.
+const MAX_BYTES_PER_COUNTER_KEY: usize = 1024;
+/// Only a tenth of the requests are retries, and they alone fill the retry hour bucket. It
+/// needs every team and usage key for the counter assertions to hold.
+const MIN_REQUESTS: usize = TEAMS * USAGE_KEYS.len() * 10;
const USAGE_KEYS: [(&str, &str); 4] = [
("events_captured", "event"),
@@ -36,20 +58,31 @@ const USAGE_KEYS: [(&str, &str); 4] = [
/// 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()];
+fn record(
+ run: &str,
+ index: usize,
+ retry: bool,
+ first_team_id: i64,
+ base_timestamp_ms: i64,
+) -> BillingUsageRecord {
+ let (usage_key, unit) = USAGE_KEYS[(index / TEAMS) % 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,
+ team_id: first_team_id + (index % TEAMS) 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 },
+ timestamp_ms: base_timestamp_ms + event_offset_ms + if retry { RETRY_OFFSET_MS } else { 0 },
}
}
+fn redis_url() -> String {
+ std::env::var("USAGE_INGESTION_REDIS_URL")
+ .unwrap_or_else(|_| "redis://127.0.0.1:6390".to_string())
+}
+
fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
let index = ((sorted.len() as f64 * fraction) as usize).min(sorted.len() - 1);
sorted[index]
@@ -61,15 +94,28 @@ 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);
+ assert!(
+ requests >= MIN_REQUESTS,
+ "USAGE_INGESTION_E2E_LOAD_REQUESTS must be at least {MIN_REQUESTS}"
+ );
+ assert!(concurrency >= 1 && channels >= 1);
let retries = requests / 10;
let unique = requests - retries;
let run = Uuid::new_v4().to_string();
+ let base_timestamp_ms = base_timestamp_ms();
+ let first_team_id = 1 + (Uuid::new_v4().as_u128() % (i32::MAX as u128 - TEAMS as u128)) as i64;
+ let organization_id = Uuid::new_v4();
+ let accumulator = Arc::new(CounterAccumulator::default());
+ let store: Arc<dyn CounterStore> = Arc::new(
+ RedisCounterStore::connect(&redis_url(), Default::default())
+ .await
+ .expect("failed to connect to Valkey Cluster"),
+ );
let clickhouse_url = clickhouse_url();
let table = table();
- let service = Service::start(500, Uuid::new_v4()).await;
+ let service = Service::start(500, organization_id, Some(Arc::clone(&accumulator))).await;
// Measured here, not hardcoded, so the throughput assertion is not a hardware guess.
let mut baseline_client = service.client().await;
@@ -79,7 +125,7 @@ async fn sustains_thousands_of_concurrent_requests() {
let started = Instant::now();
baseline_client
.ingest_billing_usage(IngestBillingUsageRequest {
- records: vec![record(&run, index, false)],
+ records: vec![record(&run, index, false, first_team_id, base_timestamp_ms)],
})
.await
.expect("a baseline ingest failed");
@@ -89,8 +135,10 @@ async fn sustains_thousands_of_concurrent_requests() {
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)))
+ .map(|index| record(&run, index, false, first_team_id, base_timestamp_ms))
+ .chain(
+ (0..retries).map(|index| record(&run, index, true, first_team_id, base_timestamp_ms)),
+ )
.collect();
// Arrival order must not match event order: a retry landing before its original still has
// to collapse to one row.
@@ -168,6 +216,66 @@ async fn sustains_thousands_of_concurrent_requests() {
throughput / baseline_throughput,
);
+ let outcome = flush(Arc::clone(&store), accumulator.drain()).await;
+ assert_eq!(
+ (outcome.dropped, outcome.capped),
+ (0, 0),
+ "Valkey dropped counter deltas under request load"
+ );
+ assert_eq!(
+ outcome.commands,
+ (TEAMS + 1) * USAGE_KEYS.len() * BUCKETS_PER_SCOPE * 2,
+ "the service should aggregate request counters by scope and series"
+ );
+
+ let client = ClusterClient::new([redis_url()]).expect("invalid Valkey Cluster URL");
+ let mut redis = client
+ .get_async_connection()
+ .await
+ .expect("failed to connect to Valkey Cluster");
+ let timestamp = DateTime::<Utc>::from_timestamp_millis(base_timestamp_ms).unwrap();
+ let retry_timestamp =
+ DateTime::<Utc>::from_timestamp_millis(base_timestamp_ms + RETRY_OFFSET_MS).unwrap();
+ let buckets = [
+ Bucket::Hour(timestamp.timestamp().div_euclid(60 * 60)),
+ Bucket::Hour(retry_timestamp.timestamp().div_euclid(60 * 60)),
+ Bucket::Day(timestamp.timestamp().div_euclid(24 * 60 * 60)),
+ ];
+ let scopes = (0..TEAMS)
+ .map(|offset| CounterScope::Team(first_team_id + offset as i64))
+ .chain(std::iter::once(CounterScope::Organization(organization_id)));
+ let mut counter_bytes = 0;
+ for scope in scopes {
+ for bucket in buckets {
+ let key = counter_key(&scope, bucket);
+ let fields: usize = redis
+ .hlen(&key)
+ .await
+ .expect("failed to count counter fields");
+ assert_eq!(
+ fields,
+ USAGE_KEYS.len(),
+ "counter key {key} grew per request"
+ );
+ let bytes: usize = redis::cmd("MEMORY")
+ .arg("USAGE")
+ .arg(&key)
+ .query_async(&mut redis)
+ .await
+ .expect("failed to measure counter key memory");
+ counter_bytes += bytes;
+ }
+ }
+ let counter_keys = (TEAMS + 1) * BUCKETS_PER_SCOPE;
+ assert!(
+ (counter_keys * MIN_BYTES_PER_COUNTER_KEY..=counter_keys * MAX_BYTES_PER_COUNTER_KEY)
+ .contains(&counter_bytes),
+ "counter keyspace used {counter_bytes} bytes across {counter_keys} keys; expected {}..={} bytes",
+ counter_keys * MIN_BYTES_PER_COUNTER_KEY,
+ counter_keys * MAX_BYTES_PER_COUNTER_KEY,
+ );
+ println!("Valkey counter keyspace: {counter_bytes} bytes across {counter_keys} keys");
+
let http = reqwest::Client::new();
let expected_rows = unique + BASELINE_REQUESTS;
let arrival_query =