Skip to content

Latest commit

 

History

History
619 lines (533 loc) · 29.4 KB

PERFORMANCE.md

File metadata and controls

619 lines (533 loc) · 29.4 KB

Query Shape Notes

Local benchmarks are useful for regression checks, but they are not product capacity claims. The important parts of this bridge are the schema shape, the ClickHouse query shape, and the number of Go-to-ClickHouse interactions. The sidecar does not call ClickHouse prometheusQuery or prometheusQueryRange.

Dataset

The default repeatable regression benchmark runs the Snuffle-native suite:

  • snuffle_metrics: TSBS devops data replayed through Prometheus remote-write into the Snuffle-native metrics schema.
  • snuffle_logs: synthetic log rows inserted into the Snuffle-native logs/log_streams/log_stream_stats schema, then queried through the same Loki-compatible LogQL API.

The PostHog-compatible runs remain available through make perf-test-posthog or explicit PERF_RUNS=posthog_metrics,posthog_logs.

The metrics run uses TSBS devops data in Prometheus remote-write format:

  • generated by tsbs_generate_data --format prometheus --use-case devops
  • default TSBS module: github.com/timescale/tsbs@v0.0.0-20260527045238-8323e59c7402
  • replayed through snuffle's /api/v1/write by cmd/snuffle-tsbs-replay without unmarshalling each TSBS TimeSeries just to marshal it again
  • default scale: 50 hosts
  • default range: 2016-01-01T00:00:00Z to 2016-01-01T01:00:00Z
  • default interval: 15s
  • default rows: about 1.2 million
  • minimum rows for a recorded baseline: PERF_MIN_ROWS=1000000
  • database: snuffle_perf
  • tenant: team_id = 0

The Snuffle logs run uses scripts/seed_logs_snuffle.sql. By default it inserts 1,000,000 rows over a 24-hour window starting at yesterday's UTC midnight. This volume is chosen so the metric/aggregation scenarios exercise the bucket-aggregation pushdown rather than a dataset small enough that a per-row CROSS JOIN against the eval grid would win; raw-log scenarios stay bounded by POSTHOG_LOG_LIMIT. The PostHog logs run uses scripts/seed_logs_posthog.sql when selected.

Repeatable Benchmark Runbook

Use this when changing schema, insert code, query planning, or response materialization. The benchmark is intentionally end-to-end: each named run creates a fresh ClickHouse schema, starts snuffle unless told otherwise, seeds data, then runs the HTTP benchmark profile for that run.

Prerequisites

  • Docker Compose can start the clickhouse service, or ClickHouse is already reachable through CH_ADDR.
  • Go can download and run the pinned TSBS generator module.
  • The machine should be otherwise quiet. A concurrent ClickHouse build, integration test, merge, or large compile can easily move these numbers.
  • The target database is disposable. By default the harness uses CH_DATABASE=snuffle_perf and recreates the selected benchmark tables for each run.

One-Command Run

make perf-test

For PostHog-compatible metrics and logs:

make perf-test-posthog

For a Codex Autoresearch packet focused only on the Snuffle-native metrics schema:

make autoresearch-snuffle-metrics

That target sets PERF_RUNS=snuffle_metrics, uses the TSBS devops metric dataset, keeps comparison state in ignored .perf/, and prints METRIC snuffle_metrics_score=<number>. The score is the geometric mean of TSBS ingest milliseconds per 1,000 rows, metrics-table storage bytes per row, ClickHouse CPU milliseconds per query, and each TSBS query scenario avg_ms; lower is better. Secondary METRIC lines report ingest, query, scenario count, CPU, storage, read volume, and memory dimensions for guardrails. The target defaults to two warmup requests and BRIDGE_BENCHTIME=3x; override AUTORESEARCH_BRIDGE_BENCH_WARMUP or AUTORESEARCH_BRIDGE_BENCHTIME for smoke or final runs.

The first run takes longer because it generates .perf/tsbs-*.prom. Later runs reuse that generated file unless PERF_REGENERATE_DATA=1 is set.

By default the harness runs the selected suite once (PERF_REPEAT=1). Each attempt recreates the relevant schema, reloads the dataset, and reruns the HTTP benchmark profile. After all attempts finish, the reporter selects the slowest candidate for each named run and compares only that candidate against perf-results.json.

The target writes:

  • .perf/tsbs-*.prom: generated TSBS Prometheus remote-write data
  • .perf/<run>/attempt-<n>/tsbs-load.out: raw TSBS replay progress for metrics attempts
  • .perf/<run>/attempt-<n>/tsbs-load-results.json: metrics write/load summary
  • .perf/<run>/attempt-<n>/log-load-results.json: logs seed summary
  • .perf/<run>/attempt-<n>/go-bench.out: raw Go HTTP benchmark output
  • .perf/<run>/attempt-<n>/memory-results.json: Snuffle process RSS samples and ClickHouse query-memory summary for the benchmark window
  • .perf/<run>/attempt-<n>/perf-results.current.json: candidate result for that attempt
  • .perf/<run>/perf-results.current.json: selected slowest candidate, even when slower than the baseline
  • perf-results.json: accepted suite baseline with one entry per run, overwritten per run only when the selected candidate is faster or within configured tolerance

If the selected candidate is slower than perf-results.json, the reporter prints the overall slowdown and the slowest dimensions, then keeps the existing baseline. Set PERF_FAIL_ON_SLOWER=true only when you want slower selected candidates to make the command exit non-zero.

What The Harness Does

  1. Starts ClickHouse with docker compose up -d clickhouse unless PERF_START_CLICKHOUSE=0.
  2. Waits for ClickHouse and creates CH_DATABASE, default snuffle_perf.
  3. Recreates the benchmark schema for the current run: scripts/create_metrics_schema.sql, scripts/create_logs_snuffle_schema.sql, scripts/create_metrics_posthog_schema.sql, or scripts/create_logs_posthog_schema.sql.
  4. Builds cmd/snuffle into .perf/snuffle.
  5. Starts snuffle on SIDECAR_HOST:SIDECAR_PORT, default 127.0.0.1:9091, unless PERF_SNUFFLE_URL points at an already-running server.
  6. For metrics runs, generates the pinned TSBS dataset if missing and replays it through /api/v1/write with cmd/snuffle-tsbs-replay.
  7. For logs runs, inserts synthetic rows with the selected log seed SQL.
  8. Flushes ClickHouse async inserts and waits until the target table reaches the expected row count.
  9. Runs BenchmarkBridgeHTTP with the selected profile while sampling managed Snuffle RSS and collecting matching ClickHouse system.query_log memory.
  10. Builds a candidate result for each attempt.
  11. Selects the slowest candidate for each named run and compares it to that run's entry in perf-results.json.

Comparison Math

The accepted result is a JSON suite file so diffs are easy to review. Each run entry records:

  • ingest rows, duration, and row rate
  • per-scenario HTTP query latency summaries
  • query geomean average latency
  • total average latency across all scenarios
  • Snuffle peak RSS and ClickHouse per-query peak memory summary for the benchmark window

The reporter compares the previous accepted result to the current run with a geomean of these ratios:

  • previous_row_rate / current_row_rate for writes
  • current_avg_ms / previous_avg_ms for each query scenario

Lower is better. A value under 1.0 means the current run is faster overall.

Baseline Discipline

perf-results.json is a suite-only baseline. Each accepted run must have a named entry, and CI treats a missing baseline or missing run as a failure. Local runs update only the named run that was executed, using the slowest candidate from PERF_REPEAT attempts; targeted query experiments should write to an alternate PERF_RESULTS_FILE or avoid updating the baseline.

The normal loop for performance work is:

  1. Run make perf-test on the current accepted code to get a clean comparison point.
  2. Inspect perf-results.json and system.query_log for the slow scenarios and generated ClickHouse SQL.
  3. Probe candidate SQL manually only to decide whether a full benchmark is worth running. Manual probes are not accepted results.
  4. Patch the code or schema.
  5. Run go test ./... for correctness.
  6. Run make perf-test for the acceptance check.
  7. Keep the change only when the full suite improves the baseline or the regression is explicitly accepted by updating perf-results.json.

Iteration Workflow

For schema changes:

  1. Edit the schema under test, usually scripts/create_metrics_posthog_schema.sql, scripts/create_logs_posthog_schema.sql.
  2. Mirror synthetic log seed changes in scripts/seed_logs_posthog.sql when the logs fixture needs to represent the same schema.
  3. Run make perf-test. The harness recreates snuffle_perf, so a schema change always gets a fresh load.
  4. Compare write rate, query geomean, and individual scenario avg_ms in perf-results.json, .perf/<run>/perf-results.current.json, or the per-attempt files under .perf/<run>/attempt-<n>/.
  5. Check ClickHouse storage after the run:
clickhouse-client --database snuffle_perf --query "
  SELECT
    table,
    sum(rows) AS rows,
    formatReadableSize(sum(bytes_on_disk)) AS bytes,
    count() AS parts
  FROM system.parts
  WHERE database = 'snuffle_perf' AND active
  GROUP BY table
  ORDER BY sum(bytes_on_disk) DESC"

For query-planning changes:

  1. Run a full make perf-test for the accepted comparison.
  2. Use system.query_log to identify the actual SQL, read rows, read bytes, marks, and elapsed time for the scenario you touched.
  3. Make the query change.
  4. Run make perf-test again. Avoid judging from one manual SQL probe unless the full HTTP benchmark agrees.

Useful query-log inspection:

clickhouse-client --database snuffle_perf --query "
  SELECT
    query_duration_ms,
    read_rows,
    formatReadableSize(read_bytes) AS read_bytes,
    query
  FROM system.query_log
  WHERE database = 'snuffle_perf'
    AND type = 'QueryFinish'
  ORDER BY event_time_microseconds DESC
  LIMIT 20
  FORMAT Vertical"

For focused query-only experiments against an already loaded database, start snuffle manually and run one or more scenarios directly:

go build -o .perf/snuffle ./cmd/snuffle
CH_DATABASE=snuffle_perf \
CH_SCHEMA_LAYOUT=current \
CH_SAMPLES_TABLE=metrics_samples \
CH_TIMEOUT_SECONDS=120 \
PROMQL_QUERY_TIMEOUT_SECONDS=120 \
REMOTE_WRITE_SAMPLE_INTERVAL=15s \
.perf/snuffle

Then, in another shell:

BRIDGE_BENCH_URL=http://127.0.0.1:9091 \
BRIDGE_BENCH_PROFILE=snuffle_metrics \
BRIDGE_BENCH_SCENARIO=tsbs_topk,tsbs_instant_or_union,tsbs_range_sum_by_region \
BRIDGE_BENCH_CONCURRENCY=10 \
BRIDGE_BENCH_WARMUP=10 \
go test -run '^$' -bench '^BenchmarkBridgeHTTP$' ./internal/perftest \
  -benchtime=50x -timeout=30m

Do not update perf-results.json from focused runs. Use the full target before accepting a change.

Common Knobs

  • PERF_RUNS: comma-separated run list. Default snuffle_metrics,snuffle_logs; available runs are posthog_metrics, snuffle_metrics, posthog_logs, and snuffle_logs.
  • PERF_REPEAT: number of full suite attempts before selecting the slowest candidate for each run. Default 1.
  • TSBS_SCALE: number of hosts. Default 50.
  • TSBS_START, TSBS_END, TSBS_INTERVAL, TSBS_SEED: generated data shape.
  • BRIDGE_BENCH_TSBS_UNION_SELECTORS: host selector count for the tsbs_instant_or_union and tsbs_range_or_union queries. Default 32.
  • BRIDGE_BENCH_TSBS_UNION_RANGE and BRIDGE_BENCH_TSBS_UNION_DIVISOR: range-function window and scalar divisor for tsbs_instant_or_union and tsbs_range_or_union. Defaults 5m and 5.
  • TSBS_WORKERS: concurrent remote-write workers. Default 2.
  • TSBS_BATCH_SIZE: TimeSeries messages per remote-write request. Default 10000.
  • POSTHOG_LOG_ROWS: synthetic logs inserted for each logs run. Default 1000000. Lower it (for example POSTHOG_LOG_ROWS=10000) for a quick local smoke run.
  • POSTHOG_LOG_START, POSTHOG_LOG_RANGE_SECONDS, POSTHOG_LOG_STEP, and POSTHOG_LOG_LIMIT: LogQL benchmark time range and response limits. POSTHOG_LOG_START defaults to yesterday's UTC midnight so schema TTLs do not expire freshly seeded logs.
  • BRIDGE_BENCH_CONCURRENCY: concurrent query requests per scenario. Default 1.
  • BRIDGE_BENCH_WARMUP: warmup requests before timing. Default 0.
  • BRIDGE_BENCHTIME: Go benchmark iteration count. Default 1x.
  • BRIDGE_BENCH_GO_TEST_TIMEOUT: timeout for each Go benchmark profile. Default 60m.
  • BRIDGE_BENCH_SCENARIO: comma-separated scenario filter for focused runs.
  • PERF_MEMORY_SAMPLE_INTERVAL_MS: Snuffle RSS sampling interval during the HTTP benchmark. Default 100.
  • PERF_RESULTS_FILE: alternate baseline path. Useful when testing a risky branch without touching perf-results.json.
  • PERF_COMPARE_TOLERANCE: allowed slower ratio before the reporter treats the run as a regression.
  • PERF_FAIL_ON_SLOWER=true: exit non-zero on slower runs.
  • PERF_REGENERATE_DATA=1: regenerate TSBS data even if .perf/tsbs-*.prom already exists.
  • PERF_SNUFFLE_URL: use an externally running snuffle instead of the harness-managed process.
  • PERF_START_CLICKHOUSE=0: do not start Docker Compose ClickHouse.

Noise Control

  • Run the same candidate at least twice when results are close. A few percent can be scheduler or merge noise.
  • Watch for background ClickHouse merges, compiles, integration tests, or other containers. They can distort both ingest and query latency.
  • If a run starts with an obviously low first write interval but catches up, prefer the final row rate from the JSON over the first progress line.
  • If ClickHouse is still merging after a run, wait or rerun before accepting a close result.
  • Keep the TSBS source settings fixed when comparing code changes. Changing scale, interval, or seed creates a different benchmark.

Recommended Metrics Layout

For unknown incoming labels, the default should not assume hot label names.

metrics_samples

  • columns: timestamp DateTime64(3), id UInt64, value Float64, team_id UInt64, metric_name LowCardinality(String)
  • engine: MergeTree
  • primary order: (team_id, metric_name, id, timestamp)
  • index granularity: 1024 rows. Larger granules measured slightly smaller on disk, but narrow one-series reads scanned 8-16x more rows, so the schema keeps the tighter granularity.
  • keep metric_name in the sample key. A no-metric/no-ZSTD sample table measured worse at 2.7327 bytes/sample and also removed the metric key prefix that exact-metric queries use.
  • all columns are non-null

metrics_series

  • one row per time series
  • columns: team_id, id, metric_name, labels_json String, min_time, max_time
  • primary order: (team_id, metric_name, id)
  • projection: (team_id, id) for fetching metadata after ClickHouse has already found a small set of series, such as topk
  • all columns are non-null

metrics_label_index

  • columns: team_id, metric_name, label_name, label_value LowCardinality(String), id
  • primary order: (team_id, metric_name, label_name, label_value, id)
  • projection: (team_id, label_name, label_value, id, metric_name) for arbitrary label lookup
  • projection: (team_id, id, label_name, metric_name, label_value) for fetching group labels
  • label_value LowCardinality(String) keeps the existing order and projections while reducing local label-index storage from 0.9337 to 0.7651 bytes/sample. Tested label lookups kept the same read row counts and read fewer bytes.
  • used for arbitrary label filtering and label metadata
  • all columns are non-null

labels_json String is useful for compact label storage and returning complete labelsets. Arbitrary label filtering still goes through the inverted index.

Cold-path companion tables:

  • metrics_histograms: native histogram samples as remote-write protobuf blobs keyed by (team_id, id, timestamp) with ReplacingMergeTree(version)
  • metrics_exemplars: exemplar samples keyed by (team_id, id, timestamp)
  • metrics_metadata: latest metadata per metric family

JSON vs Map Findings

The product layout keeps labels in an opaque JSON string for compact storage and response materialization, but does not use ClickHouse JSON functions for filtering or grouping. All arbitrary label predicates and group labels go through metrics_label_index.

Map was larger than JSON on the local 10M-row dataset and did not add a query-planning advantage once the inverted index became the hot path. The bridge therefore avoids Map for labels.

Other Manual Benchmarks

These commands are useful for ad-hoc checks, but make perf-test is the accepted regression benchmark.

To capture a sidecar CPU profile during a replay, start snuffle with SNUFFLE_PPROF=1 and collect:

curl -fsS 'http://127.0.0.1:9091/debug/pprof/profile?seconds=45' \
  -o .perf/snuffle.cpu.pprof
go tool pprof -top .perf/snuffle.cpu.pprof

The range pushdown has its own opt-in benchmark against a local ClickHouse. It seeds 2000 counter series (SNUFFLE_E2E_BENCH_SERIES) at one sample per minute over 24 hours, runs sum(increase(envoy_cluster_upstream_rq[1m])) by (envoy_response_code) at a one minute step through the pushdown and through the Prometheus engine, checks that both agree, and logs the timings:

docker compose up -d clickhouse
SNUFFLE_E2E_BENCH=1 go test -run TestRangePushdownLatency -v ./internal/snuffle/
# Run the same comparison against Snuffle's native schema:
SNUFFLE_E2E_BENCH=1 SNUFFLE_E2E_BENCH_SCHEMA=current \
  go test -run TestRangePushdownLatency -v ./internal/snuffle/

For PostHog, on the two-CPU compose ClickHouse the pushdown answered in about 0.5 s and the engine in about 1.4 s (2.2 s before the packed sample reads). The pushdown parallelises across series in ClickHouse, so it gains more from larger servers than the engine path, whose evaluation runs in one Go goroutine.

For the native schema, a three-run comparison on the same two-CPU setup gave median times of 787 ms for pushdown and 1143 ms for the engine (31% lower). The native path issued one query instead of three and returned 14,400 rows instead of 2,892,000. It scanned approximately twice as many sample rows because the regular and sparse-series branches each read the source. These timings are for the counter benchmark above, not every supported expression.

Compare the generated ClickHouse SQL and system.query_log rows when changing schema or query planning. Focus on read rows, read bytes, marks used, projection selection, number of HTTP requests, and response materialization cost.

Implemented storage optimizations:

  • exact metric/time pruning on series
  • tenant pruning through team_id in every table and query
  • arbitrary positive label matcher pruning through label_index
  • label-index projections for matcher lookup and group-label lookup
  • sample and label posting bitmap materialization is not on the default write path; exact metric active-series checks read the samples table directly
  • exact-metric nested counts read the samples table directly for the query window and join label_index, avoiding stale series bounds and expensive bitmap intersections
  • exact Prometheus matcher semantics are preserved by a final Go-side matcher filter
  • instant aggregates, topk, and nested counts over bare selectors read the lookback window in SQL; samples can arrive outside Snuffle's remote-write timestamp buckets, so no read path depends on REMOTE_WRITE_SAMPLE_INTERVAL
  • range queries of the shape agg by (...) (F(selector[w])) over the PostHog layout run in one ClickHouse query when F is increase, delta, rate, irate, idelta, or a bare selector (SNUFFLE_RANGE_PUSHDOWN). ClickHouse sorts each series into arrays, computes the MetricsQL rollup at every step and aggregates across series, so one row per group and step returns to Go. sum over increase or delta sums the per-sample contributions directly. The pushdown estimates the sample interval once per series over the query range, as VictoriaMetrics does; the engine estimates it per step from the samples inside the step's matrix. The two therefore differ on irregular series and at the first step after a gap longer than the lookback: rate, irate, idelta and bare selectors accept a previous or last sample within the series interval margin, and increase and delta use the previous sample whenever it lies within the lookback of the window start. A selector offset shifts the samples ClickHouse reads for every step. An offset on the aggregate (sum(...) offset 24h, which the MetricsQL rewrite turns into a default_rollup over a subquery) evaluates the aggregate on the epoch-aligned step grid that covers the shifted range, then Go reads the latest grid point within the MetricsQL window before each shifted step, as the engine does for the subquery. Queries the pushdown does not accept (rate without a window, @, without, nested expressions, windows wider than CH_RANGE_PUSHDOWN_MAX_EXPANSION steps, virtual histogram selectors) keep the engine path below
  • native-layout range queries push bare selectors, increase, delta, rate (including implicit windows), irate, idelta, and basic *_over_time functions into one SQL statement. Aggregations, nested counts, scalar arithmetic and plain or unions compose over those results. Selector and aggregate offsets are supported; outer running_sum sums the evaluated points in Go. Unlike the PostHog implementation, the native path calculates the sample interval from the last 20 intervals in each step's matrix, matching the engine for irregular samples. For increase and delta, series without lookback-sized gaps use adjacent-sample contributions; sparse series keep the per-step calculation. A sum can aggregate contributions directly. The statement also checks the series limit and matching native histogram data; histograms retain engine evaluation. Unsupported expressions (including general subqueries, @, vector arithmetic and custom union matching) and windows above the expansion limit use the engine. SQL errors are returned.
  • other range queries and counter rollups use the Prometheus engine: automatic selector windows depend on the sample interval of each series, and counter rollups use MetricsQL calculations. PostHog-layout float samples arrive as one row per series: the first timestamp, the array of timestamp deltas and the array of values (groupArray in ClickHouse instead of an ORDER BY over every sample). Typed arrays compress far better than an opaque RowBinary string: on a 24-hour read of 2.2M samples over 2010 series the delta arrays moved 0.8 MiB with ZSTD and 1.5 MiB with LZ4, where the RowBinary payload moved 6.2 MiB and 12.0 MiB. Float series iterate their samples in place without a copy into the mixed float and histogram point type
  • sample reads use exact selected IDs against a sample table ordered by (team_id, metric_name, id, timestamp) with tighter index granularity
  • PostHog-layout sample reads (float and histogram) select series first and then read (series_fingerprint, timestamp, value) by fingerprint; joining the series table onto the samples scan shipped both label maps on every sample row and made Go map decoding the dominant cost of range queries. Fingerprint sets larger than CH_ID_CHUNK_SIZE are sent as a ClickHouse external table and read with one subquery, because a literal IN (...) list of that size can exceed the server max_query_size
  • virtual histogram discovery reads DISTINCT (series_fingerprint, histogram_bounds) instead of every sample row
  • virtual histogram series reuse their resolved labels within each request, keyed by source fingerprint, suffix, and bucket boundary; later samples append values without repeating label sorting and string formatting
  • exact histogram suffix selectors resolve real metric labels or virtual source labels in one metadata query; a team-wide name check with LIMIT 1 keeps real metrics first, independent of label filters and the query time window, and stops at the first matching series row. Regex selectors retain the general alias lookup path.
  • histogram array reads use a RowBinary payload with checked, reusable typed decoding instead of reflective per-element array scanning
  • exact virtual histogram quantile range queries over sum by (le) of a counter function (rate, irate, increase, delta, idelta) share timestamp and window work across buckets. They read one source at a time and retain only the points of its selector range for each bucket. They use the existing MetricsQL counter and Prometheus quantile calculations. Real metrics, changing bounds, overlapping source labels, and unsupported query shapes use the general engine. SNUFFLE_POSTHOG_COMPACT_HISTOGRAMS=false turns this path off.
  • small selected-ID sample reads preserve metric constraints so ClickHouse can use the sample-table key prefix
  • sample reads use plain MergeTree rows. This removes replacement merge CPU from the hot ingest path; duplicate remote-write retries can produce duplicate float samples.
  • native-histogram reads still dedupe with argMax(histogram, version) because histograms are much colder and stored as protobuf payloads
  • broad latest-sample reads use ClickHouse subqueries instead of oversized IN (...) lists
  • topk/bottomk carries metric names and label JSON through selected_series, avoiding a second series-table lookup for the winning IDs
  • native /query_range selectors and supported aggregates return evaluated step values from ClickHouse, avoiding raw-sample materialization in Go
  • no-op Grafana regexes such as =~".*" do not disable ClickHouse pushdown
  • /series resolves labelsets without reading samples
  • label metadata endpoints push limit into ClickHouse when clients provide it
  • metric metadata is stored separately and never joined into the sample hot path
  • native histograms and exemplars are stored separately from float samples and loaded only when the request path needs them
  • remote write applies the configurable sample interval before insert; this is intentionally Go-side so later tenant-specific intervals do not require table-level ClickHouse expressions
  • remote write preallocates per-request row buffers before translating protobuf timeseries into native ClickHouse columns
  • remote write asks ClickHouse for missing series IDs only, so existing series batches do not stream every known ID back into Go
  • remote write avoids per-series xxhash allocation and avoids recomputing the sample bucket interval for every sample
  • safe instant sum, avg, count, min, max, group, topk, and bottomk push down to ClickHouse
  • safe aggregate-over-range-function shapes such as sum by (...) (rate(selector[5m])) and sum by (...) (irate(selector[5m])) push down to ClickHouse for float samples
  • post-aggregation joins use ANY JOIN only after both sides are one row per series; raw sample joins stay normal joins so ClickHouse does not collapse samples before aggregation
  • aggregate pushdowns can use CH_AGGREGATE_MAX_THREADS to avoid per-query thread over-subscription under concurrent dashboard traffic; range pushdowns and PostHog sample reads use CH_RANGE_QUERY_MAX_THREADS
  • range pushdowns disable short_circuit_function_evaluation: with lazy if branches ClickHouse re-evaluated the per-step expression tree once per branch reference, which multiplied the query time several times over
  • the query log carries clickhouse_ms, eval_ms and encode_ms per request, so the ClickHouse, Go evaluation and JSON encoding shares of a slow query are visible without a profiler
  • the Go ClickHouse client reuses a precomputed endpoint and avoids copying scanner rows before JSON decoding
  • series labels are stored as an opaque JSON string and parsed in Go only when labels must be returned; filtering and grouping use label_index
  • /series can stream prebuilt label JSON for pushdown-safe matchers, avoiding Go map parsing and re-encoding on the hot path

Comparison Summary

Default generated TimeSeries targets are functional but weak for PromQL-style filters because the tags target is ordered mainly by (metric_name, id), and the data target is ordered by (id, timestamp).

The generic inverted-index layout is the right default for arbitrary labels because it avoids making product assumptions about incoming label names.

Gigapipe Comparison

The local /root/git/gigapipe schema uses the same core shape:

  • time_series: date, fingerprint UInt64, labels String, name String, later type UInt8; ReplacingMergeTree, partitioned by date, ordered by fingerprint and later (fingerprint, type).
  • time_series_gin: inverted label index with date, key, val, fingerprint, later type; ordered by (key, val, fingerprint, type). It is populated by a materialized view that expands the serialized label object into key/value rows.
  • samples_v3: raw samples with fingerprint UInt64, timestamp_ns Int64, value Float64, string String, later type; partitioned by day and ordered by configurable SAMPLES_ORDER_RUL, defaulting to timestamp_ns.
  • metrics_15s: downsampled aggregates ordered by (fingerprint, timestamp_ns, type), populated from samples_v3.

Their PromQL path uses the official Prometheus parser/query interfaces in Go, resolves matchers through the inverted label index, fetches labels separately from time_series, and switches to the metrics_15s downsample table when the query step/range allows it.

For our workload, the main schema difference versus Gigapipe is keeping the stored label object as an opaque JSON string while maintaining the separate inverted label index for query planning.