Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(billing): keep real-time usage reads inside the memory limit (#93134)

Ben Whitedea3f1bec9b1
diff --git a/docs/internal/usage-record-producers.md b/docs/internal/usage-record-producers.md
index ec8c6461faef..02f8f2fc9b77 100644
--- a/docs/internal/usage-record-producers.md
+++ b/docs/internal/usage-record-producers.md
@@ -22,10 +22,16 @@ The cost is that deduplication is scoped to a UTC day, so a reprocess that cross
`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.
-Read with `argMax(quantity, timestamp)` grouped by the sort key. HogQL rejects `FINAL` outright, so this is the only correct shape there.
+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 |
diff --git a/frontend/src/scenes/real-time-usage/realTimeUsageLogic.test.ts b/frontend/src/scenes/real-time-usage/realTimeUsageLogic.test.ts
index eea0663368e0..794177060b1f 100644
--- a/frontend/src/scenes/real-time-usage/realTimeUsageLogic.test.ts
+++ b/frontend/src/scenes/real-time-usage/realTimeUsageLogic.test.ts
@@ -37,13 +37,11 @@ describe('real-time usage logic', () => {
[
{
project: { id: 1, name: 'First project' },
- rows: response([['ingestion', 'events', 'events', 2]]),
- timeSeries: response([[bucket, 'ingestion: events (events)', 2]]),
+ usage: response([[bucket, 'ingestion', 'events', 'events', 2]]),
},
{
project: { id: 2, name: 'Second project' },
- rows: response([['ingestion', 'events', 'events', 3]]),
- timeSeries: response([[bucket, 'ingestion: events (events)', 3]]),
+ usage: response([[bucket, 'ingestion', 'events', 'events', 3]]),
},
],
'1d',
diff --git a/frontend/src/scenes/real-time-usage/realTimeUsageLogic.ts b/frontend/src/scenes/real-time-usage/realTimeUsageLogic.ts
index 70399d87b519..5a0dfb35f3e7 100644
--- a/frontend/src/scenes/real-time-usage/realTimeUsageLogic.ts
+++ b/frontend/src/scenes/real-time-usage/realTimeUsageLogic.ts
@@ -30,8 +30,7 @@ type RealTimeUsageData = {
type ProjectUsageData = {
project: { id: number; name: string }
- rows: HogQLQueryResponse
- timeSeries: HogQLQueryResponse
+ usage: HogQLQueryResponse
}
const RANGE_INTERVALS: Record<UsageRange, string> = {
@@ -46,7 +45,7 @@ const RANGE_SECONDS: Record<UsageRange, number> = {
'30d': 30 * 24 * 60 * 60,
}
-const PROJECT_QUERY_CONCURRENCY = 5
+const PROJECT_QUERY_CONCURRENCY = 10
// Buckets are cut by integer arithmetic on the Unix timestamp rather than by dateTrunc, so a bucket
// is the same absolute instant for every project and for the browser. dateTrunc cuts on the team's
@@ -100,18 +99,16 @@ function bucketStarts(range: UsageRange, granularity: UsageGranularity): number[
return Array.from({ length: count }, (_, index) => end - (count - 1 - index) * step)
}
-function usageQuery(range: UsageRange, granularity: UsageGranularity, timeSeries: boolean): string {
+// Collapsing an un-merged resend needs a group by record_id, which is unique per row, so the
+// aggregation holds one state per row and exceeds ClickHouse's per-query memory limit. This page
+// reports usage as it arrives rather than the billed number, so a plain sum is close enough.
+// One query serves both the chart and the table, because the table is this result summed over its
+// buckets.
+function usageQuery(range: UsageRange, granularity: UsageGranularity): string {
const interval = RANGE_INTERVALS[range]
const step = GRANULARITY_SECONDS[granularity]
- const bucket = `intDiv(toUnixTimestamp(recorded_at), ${step}) * ${step}`
- // Grouped by the table's sorting key so un-merged duplicates of one record collapse instead
- // of summing. HogQL rejects FINAL, and timestamp is monotonic per resend, so argMax on it
- // picks the same row a merge would keep.
- const canonicalRecords = `SELECT producer_id, usage_key, unit, record_id, argMax(quantity, timestamp) AS quantity, max(timestamp) AS recorded_at FROM posthog.billing_usage_records WHERE timestamp >= now() - INTERVAL ${interval} GROUP BY toDate(timestamp), producer_id, usage_key, unit, record_id`
- return timeSeries
- ? `SELECT ${bucket} AS bucket, concat(producer_id, ': ', usage_key, ' (', unit, ')') AS series, sum(quantity) AS quantity FROM (${canonicalRecords}) GROUP BY bucket, series ORDER BY bucket, series`
- : `SELECT producer_id, usage_key, unit, sum(quantity) AS quantity FROM (${canonicalRecords}) GROUP BY producer_id, usage_key, unit ORDER BY quantity DESC, producer_id, usage_key`
+ return `SELECT intDiv(toUnixTimestamp(timestamp), ${step}) * ${step} AS bucket, producer_id, usage_key, unit, sum(quantity) AS quantity FROM posthog.billing_usage_records WHERE timestamp >= now() - INTERVAL ${interval} GROUP BY bucket, producer_id, usage_key, unit`
}
async function queryUsage(teamId: number, query: string): Promise<HogQLQueryResponse> {
@@ -137,26 +134,25 @@ export function parseUsageData(
const series = new Map<string, Map<number, number>>()
for (const response of responses) {
- for (const [producerId, usageKey, unit, quantity] of response.rows.results ?? []) {
- const key = `${breakdownByProject ? `${response.project.id}:` : ''}${producerId}:${usageKey}:${unit}`
- const current = rows.get(key)
- rows.set(key, {
+ for (const [bucket, producerId, usageKey, unit, quantity] of response.usage.results ?? []) {
+ const meter = `${producerId}: ${usageKey} (${unit})`
+ const amount = Number(quantity)
+
+ const rowKey = `${breakdownByProject ? `${response.project.id}:` : ''}${producerId}:${usageKey}:${unit}`
+ const current = rows.get(rowKey)
+ rows.set(rowKey, {
projectName: breakdownByProject ? response.project.name : undefined,
producerId: String(producerId),
usageKey: String(usageKey),
unit: String(unit),
- quantity: (current?.quantity ?? 0) + Number(quantity),
+ quantity: (current?.quantity ?? 0) + amount,
})
- }
- for (const [bucket, seriesName, quantity] of response.timeSeries.results ?? []) {
+ const seriesKey = breakdownByProject ? `${response.project.id}:${response.project.name}: ${meter}` : meter
+ const values = series.get(seriesKey) ?? new Map<number, number>()
const bucketStart = Number(bucket)
- const key = breakdownByProject
- ? `${response.project.id}:${response.project.name}: ${seriesName}`
- : String(seriesName)
- const values = series.get(key) ?? new Map<number, number>()
- values.set(bucketStart, (values.get(bucketStart) ?? 0) + Number(quantity))
- series.set(key, values)
+ values.set(bucketStart, (values.get(bucketStart) ?? 0) + amount)
+ series.set(seriesKey, values)
}
}
@@ -228,8 +224,7 @@ export const realTimeUsageLogic = kea<realTimeUsageLogicType>([
null as RealTimeUsageData | null,
{
loadUsageData: async (): Promise<RealTimeUsageData> => {
- const rowsQuery = usageQuery(values.usageRange, values.usageGranularity, false)
- const timeSeriesQuery = usageQuery(values.usageRange, values.usageGranularity, true)
+ const query = usageQuery(values.usageRange, values.usageGranularity)
const teams = values.currentOrganization?.teams ?? []
const selectedTeams = values.selectedProjectIds.length
? teams.filter((team) => values.selectedProjectIds.includes(team.id))
@@ -243,8 +238,7 @@ export const realTimeUsageLogic = kea<realTimeUsageLogicType>([
projectQueryConcurrency.run({
fn: async () => ({
project: { id: team.id, name: team.name },
- rows: await queryUsage(team.id, rowsQuery),
- timeSeries: await queryUsage(team.id, timeSeriesQuery),
+ usage: await queryUsage(team.id, query),
}),
})
)
diff --git a/posthog/hogql/database/schema/billing_usage_records.py b/posthog/hogql/database/schema/billing_usage_records.py
index f70fd2196144..25dae0f49ebb 100644
--- a/posthog/hogql/database/schema/billing_usage_records.py
+++ b/posthog/hogql/database/schema/billing_usage_records.py
@@ -20,9 +20,12 @@ class BillingUsageRecordsTable(Table):
visible only in the project that produced them.
Rows deduplicate on ``(team_id, toDate(timestamp), producer_id, usage_key, record_id)``, and
- the collapse only happens on merge. Read with ``argMax(quantity, timestamp)`` grouped by that
- key; a plain ``sum(quantity)`` counts duplicates that have not merged yet, and HogQL rejects
- ``FINAL``.
+ the collapse only happens on merge. ``argMax(quantity, timestamp)`` grouped by that key is the
+ exact read, because HogQL rejects ``FINAL``, but ``record_id`` is unique per row, so that
+ grouping holds one aggregation state per row and exceeds the per-query memory limit over any
+ real range. A plain ``sum(quantity)`` counts un-merged duplicates instead, which overstates a
+ total by a fraction of a percent. Prefer the plain sum unless the read is both scoped to a
+ small range and required to be exact.
"""
description: str = "Durable product-usage records emitted by event ingestion, CDP, and feature flags."