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(query-performance): chart preaggregation table growth over time (#75894)

Juraj Majerik801dfa4bd67e
diff --git a/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsx b/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsx
index 89e13ed7f8cd..108a5c9bb792 100644
--- a/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsx
+++ b/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsx
@@ -1,7 +1,9 @@
import { useActions, useValues } from 'kea'
import { LemonButton } from '@posthog/lemon-ui'
+import { TimeSeriesBarChart } from '@posthog/quill-charts'
+import { useChartTheme } from 'lib/charts/hooks'
import { dayjs } from 'lib/dayjs'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
@@ -9,7 +11,14 @@ import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
import { humanFriendlyLargeNumber, humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'
-import { CachePartitionRow, CacheTableStats, queryPerformanceLogic } from './queryPerformanceLogic'
+import { CacheGrowthResponse, CachePartitionRow, CacheTableStats, queryPerformanceLogic } from './queryPerformanceLogic'
+
+const GROWTH_RANGE_OPTIONS = [
+ { label: '48h', hours: 48 },
+ { label: '7d', hours: 168 },
+ { label: '14d', hours: 336 },
+ { label: '21d', hours: 504 },
+]
// Partitions are keyed by toYYYYMMDD(expires_at), so a partition id is the day its rows expire.
const partitionToISO = (partition: string): string =>
@@ -31,16 +40,50 @@ function ttlStatus(partition: string): { label: string; type: LemonTagType } {
return { label: `Drops in ${days}d`, type: 'muted' }
}
+// "experiment_exposures_preaggregated" -> "exposures" — the key the backend uses for growth series
+// (it comes from the experiment_precompute_table query tag on build INSERTs).
+const growthKey = (table: string): string => table.replace(/^experiment_/, '').replace(/_preaggregated$/, '')
+
// "experiment_exposures_preaggregated" -> "Exposures", "experiment_metric_events_preaggregated" -> "Metric events"
function tableLabel(table: string): string {
- const short = table
- .replace(/^experiment_/, '')
- .replace(/_preaggregated$/, '')
- .replace(/_/g, ' ')
+ const short = growthKey(table).replace(/_/g, ' ')
return short.charAt(0).toUpperCase() + short.slice(1)
}
-function TableCard({ table }: { table: CacheTableStats }): JSX.Element {
+function GrowthChart({
+ title,
+ growth,
+ data,
+ formatValue,
+}: {
+ title: string
+ growth: CacheGrowthResponse
+ data: number[]
+ formatValue?: (value: number) => string
+}): JSX.Element {
+ const theme = useChartTheme()
+ return (
+ <div>
+ <div className="text-xs text-muted mb-1">{title}</div>
+ {/* Flex column: the chart root is `flex-1` and only gets height from a flex parent. */}
+ <div className="h-32 flex flex-col">
+ <TimeSeriesBarChart
+ series={[{ key: 'value', label: title, data }]}
+ labels={growth.buckets}
+ theme={theme}
+ config={{
+ xAxis: { timezone: 'UTC', interval: growth.interval },
+ yAxis: formatValue ? { tickFormatter: formatValue } : { format: 'short' },
+ tooltip: formatValue ? { valueFormatter: formatValue } : undefined,
+ showGrid: true,
+ }}
+ />
+ </div>
+ </div>
+ )
+}
+
+function TableCard({ table, growth }: { table: CacheTableStats; growth: CacheGrowthResponse | null }): JSX.Element {
if (table.unavailable) {
return (
<LemonCard hoverEffect={false} className="flex-1 min-w-72">
@@ -50,6 +93,8 @@ function TableCard({ table }: { table: CacheTableStats }): JSX.Element {
</LemonCard>
)
}
+ const series = growth?.tables[growthKey(table.table)]
+ const per = growth?.interval === 'hour' ? 'per hour' : 'per day'
return (
<LemonCard hoverEffect={false} className="flex-1 min-w-72">
<div className="font-mono text-xs text-muted">{table.table}</div>
@@ -66,13 +111,30 @@ function TableCard({ table }: { table: CacheTableStats }): JSX.Element {
)}`
: 'No active parts'}
</div>
+ {growth && series ? (
+ <div className="flex flex-col gap-3 mt-3">
+ <GrowthChart title={`Rows written ${per}`} growth={growth} data={series.written_rows} />
+ <GrowthChart
+ title={`Data written ${per} (uncompressed)`}
+ growth={growth}
+ data={series.written_bytes}
+ formatValue={humanizeBytes}
+ />
+ </div>
+ ) : (
+ <div className="flex flex-col gap-3 mt-3">
+ <LemonSkeleton className="h-32 w-full" />
+ <LemonSkeleton className="h-32 w-full" />
+ </div>
+ )}
</LemonCard>
)
}
export function CacheHealth(): JSX.Element {
- const { cacheHealth, cacheHealthLoading, cachePartitionRows } = useValues(queryPerformanceLogic)
- const { loadCacheHealth } = useActions(queryPerformanceLogic)
+ const { cacheHealth, cacheHealthLoading, cachePartitionRows, cacheGrowth, cacheGrowthHoursBack } =
+ useValues(queryPerformanceLogic)
+ const { loadCacheHealth, loadCacheGrowth, setCacheGrowthHoursBack } = useActions(queryPerformanceLogic)
const tables = cacheHealth?.tables ?? []
@@ -123,17 +185,32 @@ export function CacheHealth(): JSX.Element {
<>
<div className="flex items-center justify-between gap-2 mb-2">
<p className="text-muted text-sm mb-0">
- Physical footprint of the experiment preaggregation tables (active parts across all shards, from
- ClickHouse system.parts).
+ Physical footprint of the experiment preaggregation tables (totals from ClickHouse system.parts,
+ growth from the archived build inserts).
</p>
- <LemonButton
- type="secondary"
- size="small"
- onClick={() => loadCacheHealth()}
- disabledReason={cacheHealthLoading ? 'Loading...' : undefined}
- >
- Refresh
- </LemonButton>
+ <div className="flex items-center gap-2">
+ {GROWTH_RANGE_OPTIONS.map(({ label, hours }) => (
+ <LemonButton
+ key={hours}
+ type={cacheGrowthHoursBack === hours ? 'primary' : 'tertiary'}
+ size="small"
+ onClick={() => setCacheGrowthHoursBack(hours)}
+ >
+ {label}
+ </LemonButton>
+ ))}
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => {
+ loadCacheHealth()
+ loadCacheGrowth()
+ }}
+ disabledReason={cacheHealthLoading ? 'Loading...' : undefined}
+ >
+ Refresh
+ </LemonButton>
+ </div>
</div>
<div className="flex flex-wrap gap-4 mb-4">
{!cacheHealth && cacheHealthLoading
@@ -145,7 +222,7 @@ export function CacheHealth(): JSX.Element {
<LemonSkeleton className="h-3 w-1/3 mt-1" />
</LemonCard>
))
- : tables.map((table) => <TableCard key={table.table} table={table} />)}
+ : tables.map((table) => <TableCard key={table.table} table={table} growth={cacheGrowth} />)}
</div>
<h3>Partition breakdown by expiry day</h3>
<LemonTable
diff --git a/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts b/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts
index 355952db0865..6b547e6c27e2 100644
--- a/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts
+++ b/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts
@@ -87,6 +87,19 @@ export interface PrecomputeTimeseriesResponse {
}
}
+export interface CacheGrowthTableSeries {
+ written_rows: number[]
+ written_bytes: number[] // uncompressed INSERT accounting, reads higher than compressed bytes_on_disk
+}
+
+export interface CacheGrowthResponse {
+ hours: number
+ interval: 'hour' | 'day'
+ buckets: string[] // ISO timestamps; all arrays below align to this axis (zero-filled)
+ // Keyed by the experiment_precompute_table tag: "exposures" and "metric_events" (always both present)
+ tables: Record<string, CacheGrowthTableSeries>
+}
+
export interface CachePartitionStats {
partition: string // YYYYMMDD — the expiry day of the partition (tables partition by toYYYYMMDD(expires_at))
rows: number
@@ -156,6 +169,9 @@ export interface SlowestQuery {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface queryPerformanceLogicValues {
+ cacheGrowth: CacheGrowthResponse | null
+ cacheGrowthHoursBack: number
+ cacheGrowthLoading: boolean
cacheHealth: CacheHealthResponse | null
cacheHealthLoading: boolean
cachePartitionRows: CachePartitionRow[]
@@ -180,6 +196,21 @@ export interface queryPerformanceLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface queryPerformanceLogicActions {
+ loadCacheGrowth: () => any
+ loadCacheGrowthFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadCacheGrowthSuccess: (
+ cacheGrowth: CacheGrowthResponse | null,
+ payload?: any
+ ) => {
+ cacheGrowth: CacheGrowthResponse | null
+ payload?: any
+ }
loadCacheHealth: () => any
loadCacheHealthFailure: (
error: string,
@@ -255,6 +286,9 @@ export interface queryPerformanceLogicActions {
slowestQueries: SlowestQuery[]
payload?: any
}
+ setCacheGrowthHoursBack: (hours: number) => {
+ hours: number
+ }
setExceptionCodeFilter: (exceptionCode: string) => {
exceptionCode: string
}
@@ -338,6 +372,7 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([
setExperimentsTab: (tab: ExperimentsTab) => ({ tab }),
setOverviewHoursBack: (hours: number) => ({ hours }),
setTimeseriesHoursBack: (hours: number) => ({ hours }),
+ setCacheGrowthHoursBack: (hours: number) => ({ hours }),
}),
reducers({
search: [
@@ -394,6 +429,12 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([
setTimeseriesHoursBack: (_, { hours }) => hours,
},
],
+ cacheGrowthHoursBack: [
+ 336,
+ {
+ setCacheGrowthHoursBack: (_, { hours }) => hours,
+ },
+ ],
}),
loaders(({ values }) => ({
precomputationTeams: [
@@ -429,6 +470,14 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([
},
},
],
+ cacheGrowth: [
+ null as CacheGrowthResponse | null,
+ {
+ loadCacheGrowth: async () => {
+ return await api.get(`api/debug_ch_queries/cache_growth/?hours=${values.cacheGrowthHoursBack}`)
+ },
+ },
+ ],
precomputeOverview: [
null as PrecomputeOverviewResponse | null,
{
@@ -521,12 +570,16 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([
setTimeseriesHoursBack: () => {
actions.loadPrecomputeTimeseries()
},
+ setCacheGrowthHoursBack: () => {
+ actions.loadCacheGrowth()
+ },
})),
afterMount(({ actions }) => {
if (userLogic.findMounted()?.values.user?.is_staff) {
actions.loadPrecomputationTeams()
actions.loadSlowestQueries()
actions.loadCacheHealth()
+ actions.loadCacheGrowth()
actions.loadPrecomputeOverview()
actions.loadPrecomputeTimeseries()
}
diff --git a/posthog/api/debug_ch_queries.py b/posthog/api/debug_ch_queries.py
index 4f62bb7470a9..f8ecf99f8f9f 100644
--- a/posthog/api/debug_ch_queries.py
+++ b/posthog/api/debug_ch_queries.py
@@ -162,6 +162,33 @@ def _cache_table_stats() -> list[dict]:
return list(stats.values())
+def _bucket_axis(hours: int) -> tuple[str, str, list[str], dict[str, int]]:
+ """Zero-fillable time axis for the timeseries endpoints: hourly buckets up to 48h, daily beyond.
+
+ Returns the ClickHouse bucketing function, the interval name, the bucket keys (ISO strings in
+ explicit UTC, matching what the SQL's formatDateTime emits — so no assumption about the
+ ClickHouse server timezone or driver naive/aware behavior is needed), and a key→index lookup.
+ """
+ bucket_fn = "toStartOfHour" if hours <= 48 else "toStartOfDay"
+ bucket_delta = timedelta(hours=1) if hours <= 48 else timedelta(days=1)
+ interval = "hour" if hours <= 48 else "day"
+
+ window_start = datetime.now(UTC) - timedelta(hours=hours)
+ if interval == "hour":
+ first_bucket = window_start.replace(minute=0, second=0, microsecond=0)
+ else:
+ first_bucket = window_start.replace(hour=0, minute=0, second=0, microsecond=0)
+ buckets: list[datetime] = []
+ cursor = first_bucket
+ end = datetime.now(UTC)
+ while cursor <= end:
+ buckets.append(cursor)
+ cursor += bucket_delta
+ bucket_keys = [b.strftime("%Y-%m-%dT%H:%M:%SZ") for b in buckets]
+ index_by_bucket = {key: i for i, key in enumerate(bucket_keys)}
+ return bucket_fn, interval, bucket_keys, index_by_bucket
+
+
@extend_schema(exclude=True)
class DebugCHQueries(viewsets.ViewSet):
"""
@@ -976,9 +1003,7 @@ class DebugCHQueries(viewsets.ViewSet):
raise exceptions.ValidationError("hours must be an integer.")
hours = max(1, min(hours, 504)) # clamp to 1h–21d
- bucket_fn = "toStartOfHour" if hours <= 48 else "toStartOfDay"
- bucket_delta = timedelta(hours=1) if hours <= 48 else timedelta(days=1)
- interval = "hour" if hours <= 48 else "day"
+ bucket_fn, interval, bucket_keys, index_by_bucket = _bucket_axis(hours)
params: dict = {
"hours": hours,
@@ -1035,23 +1060,7 @@ class DebugCHQueries(viewsets.ViewSet):
reads_response = sync_execute(reads_sql, params)
builds_response = sync_execute(builds_sql, params)
- # Zero-filled bucket axis from window start to now (UTC, matching toStartOfHour/Day above).
- window_start = datetime.now(UTC) - timedelta(hours=hours)
- if interval == "hour":
- first_bucket = window_start.replace(minute=0, second=0, microsecond=0)
- else:
- first_bucket = window_start.replace(hour=0, minute=0, second=0, microsecond=0)
- buckets: list[datetime] = []
- cursor = first_bucket
- end = datetime.now(UTC)
- while cursor <= end:
- buckets.append(cursor)
- cursor += bucket_delta
- # Buckets are matched as ISO strings: the SQL formats them in explicit UTC, so no
- # assumption about the ClickHouse server timezone or driver naive/aware behavior is needed.
- bucket_keys = [b.strftime("%Y-%m-%dT%H:%M:%SZ") for b in buckets]
- index_by_bucket = {key: i for i, key in enumerate(bucket_keys)}
- n = len(buckets)
+ n = len(bucket_keys)
reads = [0] * n
precomputed_reads = [0] * n
@@ -1098,3 +1107,77 @@ class DebugCHQueries(viewsets.ViewSet):
tag_queries(product=Product.INTERNAL, feature=Feature.DEBUG_QUERY)
return Response({"tables": _cache_table_stats()})
+
+ # Keys match the experiment_precompute_table tag on build INSERTs; both are always present in
+ # the response so the charts render a (zero) series even for a table with no builds in window.
+ _CACHE_GROWTH_TABLES = ("exposures", "metric_events")
+
+ @action(detail=False, methods=["GET"], url_path="cache_growth", required_scopes=["query_performance:read"])
+ def cache_growth(self, request):
+ """Bucketed written rows/bytes per preaggregation table, from the tagged build INSERTs in
+ query_log_archive — the growth-over-time companion to cache_health's point-in-time snapshot.
+
+ written_bytes is ClickHouse's uncompressed INSERT accounting, so it will read higher than
+ the compressed bytes_on_disk in cache_health. Window capped at 21 days (archive retention).
+ """
+ if not request.user.is_staff:
+ raise exceptions.PermissionDenied("Only staff users can view cache growth.")
+
+ tag_queries(product=Product.INTERNAL, feature=Feature.DEBUG_QUERY)
+
+ try:
+ hours = int(request.query_params.get("hours", 336))
+ except (TypeError, ValueError):
+ raise exceptions.ValidationError("hours must be an integer.")
+ hours = max(1, min(hours, 504)) # clamp to 1h–21d
+
+ bucket_fn, interval, bucket_keys, index_by_bucket = _bucket_axis(hours)
+
+ params: dict = {
+ "hours": hours,
+ "not_query": "%request:_api_debug_ch_queries_%",
+ }
+ # Failed builds are excluded: their written_rows is unreliable and their (retried) work
+ # would double-count against the successful build that actually populated the table.
+ # nosemgrep: clickhouse-fstring-param-audit - bucket_fn is one of two hardcoded function names
+ growth_sql = f"""
+ SELECT
+ formatDateTime({bucket_fn}(event_time, 'UTC'), '%%Y-%%m-%%dT%%H:%%i:%%SZ', 'UTC') AS bucket,
+ ifNull(toString(log_comment.experiment_precompute_table), '') AS build_table,
+ sum(written_rows) AS written_rows,
+ sum(written_bytes) AS written_bytes
+ FROM query_log_archive
+ WHERE
+ event_date >= toDate(now() - INTERVAL %(hours)s HOUR)
+ AND event_time > now() - INTERVAL %(hours)s HOUR
+ AND lc_product = 'experiments'
+ AND toString(log_comment.experiment_query_surface) = 'precompute_build'
+ AND is_initial_query
+ AND toInt8(type) > 1
+ AND exception_code = 0
+ AND query NOT LIKE %(not_query)s
+ GROUP BY bucket, build_table
+ SETTINGS skip_unavailable_shards=1
+ """
+ response = sync_execute(growth_sql, params)
+
+ n = len(bucket_keys)
+ tables: dict[str, dict[str, list[int]]] = {
+ table: {"written_rows": [0] * n, "written_bytes": [0] * n} for table in self._CACHE_GROWTH_TABLES
+ }
+ for bucket, build_table, written_rows, written_bytes in response:
+ i = index_by_bucket.get(bucket)
+ entry = tables.get(build_table)
+ if i is None or entry is None:
+ continue
+ entry["written_rows"][i] += written_rows
+ entry["written_bytes"][i] += written_bytes
+
+ return Response(
+ {
+ "hours": hours,
+ "interval": interval,
+ "buckets": bucket_keys,
+ "tables": tables,
+ }
+ )
diff --git a/posthog/api/test/test_debug_ch_queries.py b/posthog/api/test/test_debug_ch_queries.py
index 931ddc24b290..3cc5a47eba9f 100644
--- a/posthog/api/test/test_debug_ch_queries.py
+++ b/posthog/api/test/test_debug_ch_queries.py
@@ -1,3 +1,5 @@
+from datetime import UTC, datetime
+
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -123,6 +125,29 @@ class TestDebugCHQuery(APIBaseTest):
)
self.assertEqual(resp.status_code, HTTP_403_FORBIDDEN)
+ def test_cache_growth_series_are_preseeded_and_bucket_aligned(self):
+ # The charts index series arrays by bucket position, so a table with no builds in the
+ # window must still return zero-filled arrays, and returned rows must land in the bucket
+ # matching their ISO key — not be appended positionally.
+ self.user.is_staff = True
+ self.user.save()
+ bucket = datetime.now(UTC).strftime("%Y-%m-%dT00:00:00Z")
+
+ with patch(
+ "posthog.api.debug_ch_queries.sync_execute",
+ return_value=[(bucket, "exposures", 10, 100)],
+ ):
+ resp = self.client.get("/api/debug_ch_queries/cache_growth/?hours=336")
+
+ self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)
+ data = resp.json()
+ i = data["buckets"].index(bucket)
+ for table in ("exposures", "metric_events"):
+ self.assertEqual(len(data["tables"][table]["written_rows"]), len(data["buckets"]))
+ self.assertEqual(data["tables"]["exposures"]["written_rows"][i], 10)
+ self.assertEqual(data["tables"]["exposures"]["written_bytes"][i], 100)
+ self.assertEqual(sum(data["tables"]["metric_events"]["written_rows"]), 0)
+
@patch("posthog.api.debug_ch_queries.sync_execute", return_value=[])
def test_slowest_queries_pat_with_scope_and_staff_allowed(self, _mock_execute):
self.user.is_staff = True