How does TrimStats keep multi-step funnels and weekly retention cohorts fast at millions of events on ClickHouse?
TrimStats aligns its ClickHouse MergeTree sorting key (site_id, toDate(timestamp), event_type, visitor_id, timestamp) directly with funnel and cohort predicates, evaluates 2 to 8 step funnels in a single scan with native windowFunnel(), computes weekly cohorts without JOINs using arrayJoin(groupUniqArray(toMonday(timestamp))) and uniqCombined64, and coalesces concurrent reads behind Valkey single-flight caching (30s funnels, 300s cohorts).
- Leading MergeTree ORDER BY with (site_id, toDate(timestamp), event_type, visitor_id, timestamp) lets ClickHouse prune partitions and granules before windowFunnel() runs.
- Avoiding SQL self-joins in retention cohorts by pairing toMonday(min(timestamp)) with arrayJoin(groupUniqArray(...)) cuts RAM pressure dramatically.
- Using uniqCombined64 instead of exact uniqExact bounds HyperLogLog/adaptive cardinality memory across high-traffic sites while keeping sub-1% accuracy.
- Wrapping ClickHouse queries with Valkey single-flight coalescing (cachedQuery) prevents dashboard reloads from triggering duplicate heavy scans.
Why row-oriented analytics databases stall on funnels and cohorts
Anyone who has tried computing a 5-step conversion funnel or an 8-week retention matrix on PostgreSQL or MySQL hits the same wall around a few million events. Counting pageviews is easy; evaluating ordered per-visitor event sequences across rolling windows requires either recursive CTEs, expensive multi-way self-joins, or brittle nightly batch jobs (like Matomo's core:archive cron).
When we built TrimStats on Hetzner in Nuremberg, Germany, we wanted real-time funnels, cohorts, visitor timelines, and revenue attribution without nightly ETL lag or enterprise RAM bills. Four deliberate ClickHouse + Valkey engineering decisions carry the entire workload cleanly.
Columnar single-pass scans plus Valkey caching keep Behavior views snappy
Illustrative p95 query response time (ms) across 5M monthly events comparing relational self-joins vs TrimStats ClickHouse + Valkey
Aligning MergeTree ordering, materialized rollups, bloom filters, and Valkey single-flight caching keeps dashboard latency predictable at scale.
Methodology: Illustrative engineering latency model comparing row-store self-join scans against TrimStats ClickHouse AggregatingMergeTree rollups, single-pass windowFunnel/cohorts, and Valkey cachedQuery.
View chart data table
| Label | TrimStats (ClickHouse cold scan) | TrimStats (Valkey warm hit) | Naive Row-Store Self-Join |
|---|---|---|---|
| Overview (hourly_stats) | 24 ms | 4 ms | 680 ms |
| 5-Step Funnel | 145 ms | 5 ms | 3,400 ms |
| 8-Week Cohorts | 210 ms | 5 ms | 4,800 ms |
| Visitor Timeline | 38 ms | 6 ms | 920 ms |
1. Designing the events MergeTree key around real query shapes
ClickHouse performance lives or dies by how closely your MergeTree primary sorting key matches production WHERE and GROUP BY patterns. Inside packages/db/clickhouse/0001_initial.sql, our unified analytics.events table uses this exact layout:
CREATE TABLE IF NOT EXISTS analytics.events (
site_id UUID,
timestamp DateTime64(3, 'UTC'),
event_type LowCardinality(String),
event_name LowCardinality(String),
identity_mode Enum8('cookieless' = 1, 'first_party' = 2, 'identified' = 3),
visitor_id UInt64,
session_id UUID,
external_user_id String DEFAULT '',
pathname String,
...
INDEX idx_visitor_id visitor_id TYPE bloom_filter(0.01) GRANULARITY 4,
INDEX idx_external_user_id external_user_id TYPE bloom_filter(0.01) GRANULARITY 4
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(timestamp)
ORDER BY (site_id, toDate(timestamp), event_type, visitor_id, timestamp)
TTL toDateTime(timestamp) + INTERVAL 730 DAY
SETTINGS index_granularity = 8192;
Every column position earns its keep:
PARTITION BY toYYYYMM(timestamp)lets 7-day and 30-day queries discard older monthly partitions instantly and makesTTLexpiration an inexpensive partition drop.site_idfirst isolates every customer workspace into contiguous disk ranges, guaranteeing strict multi-tenant efficiency before a single row is decompressed.toDate(timestamp)+event_typenext prunes irrelevant days and skipsleave,scroll,rage_click, anddead_clickrows completely when a funnel only cares aboutevent_type IN ('pageview', 'custom').visitor_id, timestampat the tail clusters each visitor's chronological stream locally on disk, givingwindowFunnel()high cache locality duringGROUP BY visitor_id.- Two
bloom_filter(0.01) GRANULARITY 4skipping indexes accelerate point lookups for individual visitor timelines and 90-day Stripe/Paddle/Polar revenue webhook attribution joins without bloating the primary sorting key.
Each predicate in TrimStats MergeTree key slices away unused event granules
Illustrative percentage of raw events scanned during a 30-day funnel query on a multi-tenant node
Putting site_id, toDate(timestamp), and event_type at the front of ORDER BY guarantees tenant isolation and sparse-index pruning on every query.
Methodology: Granule pruning progression derived from packages/db/clickhouse/0001_initial.sql MergeTree DDL (PARTITION BY toYYYYMM(timestamp), ORDER BY (site_id, toDate(timestamp), event_type, visitor_id, timestamp)).
View chart data table
| Label | Remaining rows scanned |
|---|---|
| 1. Full cluster table | 100% |
| 2. PARTITION BY toYYYYMM | ~16% |
| 3. site_id prefix filter | ~2.4% |
| 4. toDate + event_type filter | ~0.9% |
2. Single-scan windowFunnel() with zero SQL interpolation
Inside apps/collector/src/routes/phase3.ts, TrimStats evaluates 2 to 8 ordered steps inside one grouped pass over analytics.events. Instead of returning raw per-visitor rows to Node.js, the outer query collapses max_step (1..N) into a tiny histogram of at most 8 rows (SELECT max_step, count() AS visitors), which computeFunnelResults() accumulates into step totals and drop-off percentages in microseconds.
Every match rule is validated via Zod (funnelEvalQuerySchema) and converted by buildWindowFunnelSpec() into strictly parameterized ClickHouse bindings ({step_0:String}), supporting exact paths (pathname = {step_i:String}), trailing-wildcard prefixes (startsWith(pathname, {step_i:String})), and custom events (event_name = {step_i:String}) with zero SQL injection surface.


3. Single-pass weekly retention cohorts without a single JOIN
Most SQL tutorials write retention cohorts by computing a first_seen CTE per user and joining it back against the entire events table. On 50 million rows, that join spills memory fast.
In apps/collector/src/routes/phase3.ts, we eliminate the JOIN completely using ClickHouse array aggregation inside one GROUP BY visitor_id scan:
SELECT
toString(cw) AS cohort_week,
dateDiff('week', cw, active_week) AS week_offset,
uniqCombined64(visitor_id) AS visitors
FROM (
SELECT
visitor_id,
toMonday(min(timestamp)) AS cw,
arrayJoin(groupUniqArray(toMonday(timestamp))) AS active_week
FROM events
WHERE site_id = {site_id:UUID}
AND event_type = 'pageview'
AND identity_mode IN ('first_party', 'identified')
AND timestamp >= toMonday(now()) - INTERVAL {weeks:UInt32} WEEK
GROUP BY visitor_id
)
WHERE week_offset >= 0 AND week_offset < {weeks:UInt32}
GROUP BY cw, week_offset
ORDER BY cohort_week DESC, week_offset ASC
Because weeks is bounded between 2 and 12, groupUniqArray(toMonday(timestamp)) stores at most 12 distinct Monday dates per visitor. arrayJoin() fans out only those tiny week offsets, and uniqCombined64(visitor_id) counts retained users per cell with bounded memory rather than unbounded uniqExact hash tables.


4. Valkey single-flight coalescing (cachedQuery) for shared dashboards
Fast SQL still gets hammered when a founder shares a live /share/sh_... dashboard on Hacker News or ten agency teammates open the same report at 9:00 AM Monday. Every Behavior endpoint wraps ClickHouse execution in cachedQuery(redis, key, ttlSeconds, fetcher):
- TTL matched to workload freshness: Saved funnels cache for
30seconds (qcache:funnel:{siteId}:{hash}), while 2 to 12 week retention cohorts cache for300seconds (qcache:cohorts:{siteId}:{weeks}). - In-process single-flight coalescing: Concurrent cold cache misses on the exact same key share one in-flight ClickHouse promise instead of firing duplicate scans.
- Zero stale-cache confusion: Switching date ranges, step definitions, or
windowSecondschanges the deterministic cache key hash immediately so edits reflect live data on the very next click.
5. Matching write batching and rollups to ClickHouse MergeTree physics
Fast read SQL collapses quickly if your ingestion layer inserts one beacon per ClickHouse HTTP request. ClickHouse creates a new immutable data part on disk for every INSERT, so high-frequency single-row writes trigger background merge storms and Too many parts errors.
TrimStats pairs its query layer with two operational safeguards in apps/collector:
- Bounded micro-batching (
EventBatcher): Incoming/v1/collectbeacons buffer in memory and flush in bulk JSONEachRow batches when either the row threshold or flush timer fires, with bounded queue caps and retry requeueing if ClickHouse restarts momentarily. - Pre-aggregated hourly rollups vs raw event reads: Dashboard Overview trendlines and top breakdowns read
analytics.hourly_stats(AggregatingMergeTreepopulated byhourly_stats_mvusinguniqCombined64State(visitor_id)andSimpleAggregateFunction(sum, UInt64)), reserving rawanalytics.eventsscans strictly for orderedwindowFunnel()steps, weekly retention cohorts, and individual visitor timelines.
| Query Workload | ClickHouse Table | Aggregation Engine | Cache TTL |
|---|---|---|---|
| Overview trendlines & breakdowns | analytics.hourly_stats | AggregatingMergeTree + uniqCombined64Merge | Real-time / short Valkey TTL |
| Multi-step funnels (2 to 8 steps) | analytics.events | Native windowFunnel() + ORDER BY pruning | 30s Valkey single-flight |
| Weekly retention cohorts (2 to 12w) | analytics.events | arrayJoin(groupUniqArray(...)) + uniqCombined64 | 300s Valkey single-flight |
| Visitor timelines & 90d revenue join | analytics.events | bloom_filter(0.01) skipping index lookup | Scoped per visitor page |
Want to apply this architecture to your own conversion workflow? Read our practical guide on Web Analytics Funnels or inspect how TrimStats compares to PHP/MySQL-based Matomo Analytics.
Frequently asked questions
Why does TrimStats put site_id first in the ClickHouse MergeTree ORDER BY key?
Why did TrimStats replace uniqExact with uniqCombined64 for cohorts and hourly rollups?
How do ClickHouse bloom_filter skipping indexes speed up visitor timelines and revenue webhooks?
How does Valkey single-flight caching prevent thundering herds on shared dashboards?
Why does TrimStats batch incoming beacons instead of inserting every event individually into ClickHouse?
Does ClickHouse sample funnel or cohort results on high-traffic TrimStats plans?
Sources & references
- ClickHouse Docs: MergeTree Primary Keys & Data Skipping IndexesAccessed 2026-11-30
- ClickHouse Docs: windowFunnel & uniqCombined64 FunctionsAccessed 2026-11-30
- TrimStats Funnels & Cohorts Architecture DocsAccessed 2026-11-30
Co-founder of DotCamp LLC in Brooklyn, NY and lead engineer of TrimStats. Ships privacy-first web analytics, ClickHouse pipelines, and WordPress plugins used on 115,000+ active sites.
- • Architect of the TrimStats 1.96 KB gzipped browser tracker, Fastify collector, and ClickHouse MergeTree pipeline
- • Co-founder of DotCamp LLC (est. 2019), creator of Ultimate Blocks (50,000+ installs), WP Table Builder (50,000+ installs), Tableberg, and OptimizeCamp
- • WordPress.org plugin & theme developer since 2016 with 1,200+ community support replies and 5M+ cumulative plugin downloads
Verification standard: Codebase verification: Direct schema and SQL walkthrough from packages/db/clickhouse/0001_initial.sql, 0002_performance.sql, and apps/collector/src/routes/phase3.ts.
Continue reading
Measure traffic, revenue, and UI friction in 1.96 KB gzipped
Cookie-less by default, powered by ClickHouse, and starting at $17/month for 100,000 monthly events with every feature unlocked.