DRYCODEWORKS
← Case studies

ClickHouse Materialized View Memory: ASOF JOIN to Dictionary

Daniel Young
Daniel YoungFounder, DRYCodeWorks

A dictionary cut per-insert materialized view memory by 95% in nonprod. Resident memory stayed flat. Why those metrics answer different questions.

A small gauge whose needle has dropped to near zero beside a large tank whose level has not moved

In nonprod, a dictionary cutover reduced per-insert materialized view memory by 95%. Resident memory stayed flat. The useful lesson is why those observations can both be correct.

We checked MemoryResident around the cutover and saw little change. That metric describes the process’s overall resident footprint, not just the short-lived allocations made by a materialized view.

Both numbers are correct. They answer different questions.

The measured benefit was a roughly 15× reduction in the sum of per-execution peak allocations over time. That is a workload indicator, not a measurement of simultaneous live memory. Concurrency and overlapping allocation lifetimes determine whether transient allocations exhaust headroom.

This post is about the cutover — what we did to the SQL, and why we did it. It is also about the measurement gap we tripped over on the way, which is probably the more reusable lesson.

This is the sequel to a larger move: getting the client's telemetry onto ClickHouse in the first place — 1.3 billion rows off SQL Server, schema and all. If you want that broader context before the deep-dive, start with Migrating 1.3 Billion IoT Rows to ClickHouse Cloud.

The Problem: A Write-Time ASOF JOIN That Multiplied Under Concurrency

The pipeline enriched incoming telemetry with the closest preceding reference observation. An incremental materialized view performed an ASOF LEFT JOIN during ingestion.

Building join state on each execution made the write path expensive under concurrency.

Illustrative ASOF timeline. The records and timestamps are invented, not customer observations.

Swipe sideways to see the whole diagram.

Illustrative closest-preceding-time matchesInvented events at 14:37, 15:22 and 16:45 match reference records at 14:00, 15:00 and 16:00, respectively. The gaps are 37, 22 and 45 minutes.ASOF JOIN: Match Each Event to Its Preceding Reference14:0015:0016:0017:00ReferenceF1F2F3F4EventsT114:37T215:22T316:45T1 + F1 (37min)T2 + F2 (22min)T3 + F3 (45min)

An ASOF join may build right-hand-side state for each execution, depending on the algorithm. Concurrent inserts can therefore hold multiple copies at once.

The fix targeted repeated construction of that state.

The Fix: A range_hashed Dictionary, One Resident Copy

We moved the reference lookup into a range_hashed dictionary and read it with dictGet. This keeps shared lookup state resident rather than rebuilding the same join state for every insert.

range_hashed dictionary: a ClickHouse dictionary type that indexes rows by a key plus a range of values (start and end). dictGet returns the row whose range contains the lookup value. One resident copy, lookups are O(1) on the key + O(log N) on the range.

The dictionary source must resolve reference versions deterministically before constructing lookup intervals. Keep the entity key, interval boundaries and selected value separate in that design.

Resolve versions before lookup. When several published versions describe the same reference instant, choose the version required by the application. Validate that rule independently rather than relying on whichever row happens to survive a merge.

Make interval boundaries explicit. Inclusive range bounds can overlap at adjacent boundaries. Choose the time precision and boundary rule together, then test exact endpoints and missing intervals.

Time-dependent sources need time-dependent refresh. If a dictionary’s source query uses the current time, a data-only invalidation signal can remain unchanged while the intended result changes. Design refresh around both data updates and time advancement.

The materialized view now performs dictionary lookups instead of the repeated ASOF join. The dictionary definition, selected attributes and lookup window are workload-specific, so the production query is not reproduced here.

The cutover reduced per-insert materialized view memory by 95%. Matching behavior needs an independent validation plan, especially when version-selection rules differ between the old and new paths.

That should have been the end of the story.

The Win Wasn't In Resident Memory

We expected a memory improvement and initially checked process resident memory. It stayed essentially flat despite the 95% reduction in per-execution view memory.

That apparent mismatch came from looking at two different layers: process-level resident memory and execution-level peak allocation.

MemoryResident: process RSS as sampled by ClickHouse's async-metric thread on a 1-second interval. The number that answers "how much memory is the cluster currently holding?"

query_views_log.peak_memory_usage: the peak memory recorded for an individual materialized view execution. A sum over a time window compares execution peaks; it does not measure allocation throughput or simultaneous live memory.

The two metrics observe different things. Resident memory includes caches, allocator-retained memory and other long-lived state. A short-lived execution peak can change substantially without moving that baseline.

The sum of execution peaks over a minute also fell by roughly 15× in this optimization. That sum is useful for comparing workload intensity, but it is neither an allocation rate nor concurrent memory usage. Diagnose OOM risk using actual overlap, concurrency and cluster-level pressure as well.

The reusable framing: when you profile memory for a write-time MV in ClickHouse, look at both layers.

  • MemoryResident answers "is the cluster bloated?" — relevant for steady-state sizing, page cache pressure, slow leaks.
  • query_views_log.peak_memory_usage records per-execution view peaks. Compare it across equivalent workloads and correlate with concurrent execution.
  • A write-path optimization can reduce execution peaks without reducing resident memory. Read both layers before drawing a capacity conclusion.

Two Validation Gotchas Worth Stealing

Two validation principles are worth carrying into another rollout.

Device time is not ingestion time. In a synthetic example, an event inserted at 10:00 reports 12:00 on its own clock. A filter on device time would put it on the wrong side of an 11:00 cutover. Those times are invented; they are not observations from this engagement.

Scope cutover verification with a trusted ingestion marker or a stable captured input set. Treat clock-skew checks as a separate data-quality rule.

Post-cutover parity needs an independent reference. A shadow comparison is useful while the two paths implement different logic over the same inputs. Once both execute the same query, agreement can become tautological.

Keep a fixed validation dataset and an independently specified expected result. A lookup repeated against mutable reference state at a later time is not automatically an oracle for the value that should have been materialized earlier.

Plan the post-cutover gate before changing the live path.

What Generalizes

The technical pattern — replacing a write-time ASOF JOIN with a range_hashed dictionary in a high-volume MV — generalizes to any pipeline where you're enriching inserts via a join against a slowly-changing reference table. ClickHouse dictionaries are designed for exactly this shape: one resident copy, O(1) lookup, content that's a function of source data plus (carefully) wall-clock window. If your MV's hot path is a join, it's a candidate.

The measurement framing applies wherever short-lived allocations overlap on a memory-constrained service. Process resident memory, per-execution peaks and concurrent memory pressure answer different questions.

The 95% reduction in per-insert MV memory was real. The more reusable habit is to compare execution-level measurements with cluster pressure and concurrency before declaring a memory problem understood.

The dashboard answers the question you ask it. Ask the right question first.