Dynamic PricingClickHouse Workshops

02 Ingest sales and accelerate queries

Ingest live sales, inspect operational CDC, and measure materialized-view query performance.

Your computer
macOS terminal: Run workshop commands in Terminal using zsh or bash.

Outcome

Build incremental aggregates, verify they preserve sales facts, and measure their performance while transactions continue to arrive.

Starting point

Complete Module 01. Keep the live writer stopped until step 4.

Understand source and branch

Follow three example sales rows through the system. In a real retailer, the primary sales stream would contain selling transactions from tills and online orders. Here, the writer generates that workload so you can practice safely. It can also generate an additional what-if stream to test keeping an old price. All rows in this workshop are synthetic.

The diagram previews a price change from SGD 8 to SGD 6 later in the workshop. For the same store and product, it follows one historical row, one new primary-sale row, and one unchanged-price comparison row.

Historical applied sales of SGD 16, live applied sales of SGD 6, and live comparison sales of SGD 8 enter retail_sales. Backfill and materialized views populate minute aggregates while keeping source and branch separate. Chain queries include only applied rows, totaling SGD 22. A separate receipt-scoped query compares the two live paths, SGD 6 versus SGD 8.

Follow the arrows:

  1. Data arrives. S3 history enters through Module 01's load and registration. The writer inserts new sales directly into ClickHouse. After price approval in Module 04, it also generates unchanged-price rows for that store/SKU, with a separate simulated stock balance.
  2. ClickHouse stores the rows together. Each row gets two labels: source answers “history or live?”; branch answers “primary sales or the extra what-if?”. applied is the primary path, using the original price before approval and the approved price afterward. comparison is the what-if path keeping the previous price.
  3. ClickHouse aggregates without mixing the paths. Historical backfill and the two materialized views populate store/SKU/minute and district/SKU/minute tables. Their grouping keys include both source and branch, so each combination retains separate aggregate states.
  4. Queries choose the relevant rows. Chain totals merge only branch = 'applied': SGD 16 + SGD 6 = SGD 22 in the example. Filtering source = 'history' selects the SGD 16 history; source = 'live' selects the SGD 6 primary live sale. The extra SGD 8 what-if sale is excluded.
  5. The later outcome chart asks a different question. It reads raw sales and CDC evidence for one approval receipt and compares the two live paths separately: SGD 6 versus SGD 8 for these example rows. It does not add them to chain revenue. Later observations can have different numbers of units sold in each path.

The first query below uses source = 'history' AND branch = 'applied' to measure the original historical dataset. Keep the same labels when you run its aggregate equivalent. You do not need to create a comparison branch in this module; the writer adds it after a later approval.

Actions

1. Measure a raw sales query

Run this SQL. Record its result, elapsed time, and rows read.

SELECT district_id, sku, sum(quantity) AS units,
 sum(receipts_minor) AS receipts_minor, uniqExact(transaction_id) AS transactions
FROM pricing.retail_sales
WHERE district_id = 1 AND source = 'history' AND branch = 'applied'
GROUP BY district_id, sku ORDER BY district_id, sku;

Pre-aggregate repeated questions

An incremental materialized view runs its SELECT on each new insert block and writes partial aggregate states to a separate target table. Repeated queries combine those states instead of grouping the original transaction lines again.

Two inserted blocks become partial aggregate states through a materialized view. Raw and aggregate queries both return four units, SGD 32, and three distinct transactions. Existing history follows a separate backfill path.

Read the example: Transaction A has two different sale lines, one in each block. sumMerge adds the unit states: 2 + 2 = 4. uniqExactMerge combines the ID sets {A, B} and {A, C} into three distinct transactions. Adding the two per-block distinct counts would incorrectly give four.

Here, the aggregate query combines two partial states instead of reading four sale lines. Pre-aggregation adds insert work and storage. Compare rows read and elapsed time in step 3; fewer rows do not guarantee a faster exact-distinct query.

2. Create and backfill the aggregate tables

Run each SQL statement separately in SQL console. Keep the live writer stopped until step 4.

2.1. Create the district aggregate table

Create the empty target table for district/SKU/minute aggregate states.

CREATE TABLE pricing.retail_district_minute (
 district_id UInt16,  sku UInt32, run_id UUID,
 branch LowCardinality(String), source LowCardinality(String), minute DateTime('UTC'),
 units_state AggregateFunction(sum, Int64), sold_units_state AggregateFunction(sum, Int64), receipts_state AggregateFunction(sum, Int64),
 cost_state AggregateFunction(sum, Int64), rows_state AggregateFunction(count),
 transactions_state AggregateFunction(uniqExact, UUID), sequence_state AggregateFunction(max, UInt64)
) ENGINE = AggregatingMergeTree PARTITION BY toYYYYMM(minute)
ORDER BY (district_id,  sku, run_id, branch, source, minute);

2.2. Backfill district history

Populate the district aggregate table from the sales history you loaded in Module 01.

Allow about 2–3 minutes for the backfill

The following INSERT ... SELECT reads the 100-million-line history and writes district-minute aggregate states. Wait for it to finish before creating the materialized view. Duration varies with your service size and load.

INSERT INTO pricing.retail_district_minute
SELECT district_id, sku, run_id, branch, source, toStartOfMinute(event_time) AS minute,
 sumState(toInt64(quantity)) AS units_state,
 sumState(toInt64(greatest(quantity, 0))) AS sold_units_state,
 sumState(receipts_minor) AS receipts_state, sumState(sold_cost_minor) AS cost_state,
 countState() AS rows_state, uniqExactState(transaction_id) AS transactions_state,
 maxState(sequence) AS sequence_state
FROM pricing.retail_sales
GROUP BY district_id, sku, run_id, branch, source, minute
SETTINGS max_threads=1, max_bytes_before_external_group_by=1000000000,
 max_block_size=8192, max_insert_block_size=8192,
 min_insert_block_size_rows=8192, min_insert_block_size_bytes=1000000,
 aggregation_memory_efficient_merge_threads=1;

The backfill uses one query thread and spills intermediate aggregation data to disk after about 1 GB. These settings bound memory use while grouping the full history; small insert blocks also bound buffering of aggregate states. The aggregate values remain exact.

2.3. Create the district materialized view

Create the view that sends aggregate states from new sales inserts to the district table.

CREATE MATERIALIZED VIEW pricing.retail_district_minute_mv TO pricing.retail_district_minute
AS SELECT district_id, sku, run_id, branch, source, toStartOfMinute(event_time) AS minute,
 sumState(toInt64(quantity)) AS units_state,
 sumState(toInt64(greatest(quantity, 0))) AS sold_units_state,
 sumState(receipts_minor) AS receipts_state, sumState(sold_cost_minor) AS cost_state,
 countState() AS rows_state, uniqExactState(transaction_id) AS transactions_state,
 maxState(sequence) AS sequence_state
FROM pricing.retail_sales
GROUP BY district_id, sku, run_id, branch, source, minute;

2.4. Create the store aggregate table

Create a second target table that keeps store-level detail for pricing queries.

CREATE TABLE pricing.retail_sales_minute (
 district_id UInt16, store_id UInt16, sku UInt32, run_id UUID,
 branch LowCardinality(String), source LowCardinality(String), minute DateTime('UTC'),
 units_state AggregateFunction(sum, Int64), sold_units_state AggregateFunction(sum, Int64), receipts_state AggregateFunction(sum, Int64),
 cost_state AggregateFunction(sum, Int64), rows_state AggregateFunction(count),
 transactions_state AggregateFunction(uniqExact, UUID), sequence_state AggregateFunction(max, UInt64)
) ENGINE = AggregatingMergeTree PARTITION BY toYYYYMM(minute)
ORDER BY (district_id, store_id, sku, run_id, branch, source, minute);

2.5. Backfill store history

Populate the store aggregate table from the same history.

Allow about 5–6 minutes for the store backfill

The following INSERT ... SELECT reads the 100-million-line history and writes store-level minute aggregate states. Wait for it to finish before creating the materialized view in step 2.6. Duration varies with your service size and load.

INSERT INTO pricing.retail_sales_minute
SELECT district_id, store_id, sku, run_id, branch, source, toStartOfMinute(event_time) AS minute,
 sumState(toInt64(quantity)) AS units_state,
 sumState(toInt64(greatest(quantity, 0))) AS sold_units_state,
 sumState(receipts_minor) AS receipts_state, sumState(sold_cost_minor) AS cost_state,
 countState() AS rows_state, uniqExactState(transaction_id) AS transactions_state,
 maxState(sequence) AS sequence_state
FROM pricing.retail_sales
GROUP BY district_id, store_id, sku, run_id, branch, source, minute
SETTINGS max_threads=1, max_bytes_before_external_group_by=1000000000,
 max_block_size=8192, max_insert_block_size=8192,
 min_insert_block_size_rows=8192, min_insert_block_size_bytes=1000000,
 aggregation_memory_efficient_merge_threads=1;

2.6. Create the store materialized view

Create the view that maintains store-level aggregate states as new sales arrive.

CREATE MATERIALIZED VIEW pricing.retail_sales_minute_mv TO pricing.retail_sales_minute
AS SELECT district_id, store_id, sku, run_id, branch, source, toStartOfMinute(event_time) AS minute,
 sumState(toInt64(quantity)) AS units_state,
 sumState(toInt64(greatest(quantity, 0))) AS sold_units_state,
 sumState(receipts_minor) AS receipts_state, sumState(sold_cost_minor) AS cost_state,
 countState() AS rows_state, uniqExactState(transaction_id) AS transactions_state,
 maxState(sequence) AS sequence_state
FROM pricing.retail_sales
GROUP BY district_id, store_id, sku, run_id, branch, source, minute;

2.7. Register and verify the aggregates

In your terminal, from the workshop directory, run:

.venv/bin/workshop retail-register-rollup

This performs a quick metadata check: both tables must have the expected columns, types, engine, sort key, and partition key, and both must contain data. It then attaches the canonical insert views and enables the opportunity queries. Progress messages identify each stage.

It does not rescan the historical sales, compare every aggregate group, or backfill again. A populated table alone does not prove the backfill is complete or numerically correct; Step 3 checks a representative result with SQL. Keep the writer stopped until registration finishes.

Why backfill comes first

An incremental materialized view sees new inserts; it does not automatically process rows already in its source. With the writer stopped, backfill once, then attach the view before starting sales. This avoids both gaps and double counting.

3. Verify the same result through aggregate states

SELECT district_id, sku, sumMerge(units_state) AS units,
 sumMerge(receipts_state) AS receipts_minor,
 uniqExactMerge(transactions_state) AS transactions
FROM pricing.retail_district_minute
WHERE district_id = 1 AND source = 'history' AND branch = 'applied'
GROUP BY district_id, sku ORDER BY district_id, sku;

Compare all three measures with step 1. They must match. Step 5 measures the performance of units, revenue, and gross profit separately from exact distinct transaction counting.

Open Overview in the workbench. The query evidence now identifies a Minute aggregate query. The chart and district cards describe the last 24 hours of historical business time; the live rate remains zero until you start the writer.

Cloud-connected workbench showing historical chain receipts, district totals, a zero live rate, and minute aggregate query evidence

This example uses the 100-million-line dataset. Its client duration is one observation, not a performance guarantee; collect your own repeated measurements in step 5.

4. Start batched sales and inspect operational CDC

In a second terminal, from the same workshop directory, run:

docker compose --env-file app/.env.workshop -f app/docker-compose.workshop.yml -f app/docker-compose.cloud.yml run --build --rm writer python retail_writer.py --transactions-per-minute 10000 --burst-transactions-per-minute 100000 --burst-minutes 2 --minutes 180

Leave this terminal running through the remaining exercises. The writer targets 100,000 transactions per minute for the first two business minutes, then automatically switches to 10,000 per minute for the rest of its three-business-hour run. The short burst demonstrates ingestion; the continuing feed preserves stock for pricing. A sales_rate_changed message identifies each target rate. Restarting the same command resumes the business clock and does not repeat a completed burst.

The writer sends up to 10,000 sales lines per batch, with at most 10 seconds of business time per batch. It also completes each minute boundary so the analytics can use whole windows. It reports the actual delivered rate; the requested rate is a target. Open Overview and observe the live rate and newest business time.

The query below keeps the applied branch for primary chain totals. Before price approval, no comparison rows are expected in the new run.

Run in SQL console:

SELECT source, count() AS lines, uniqExact(transaction_id) AS transactions,
 max(event_time) AS latest_business_time
FROM pricing.retail_sales
WHERE event_time >= toDateTime('2026-01-30 02:00:00', 'UTC')
 AND branch = 'applied'
GROUP BY source;

SELECT run_id, sequence, status, logical_end, event_count
FROM pricing.retail_batches_cdc FINAL
WHERE _peerdb_is_deleted = 0
ORDER BY sequence DESC LIMIT 5;

Two ingestion paths, one analytical question

High-volume sales arrive in direct ClickHouse batches. Operational inventory, prices, policies, run metadata, batch acknowledgements, and receipts arrive from managed Postgres through ClickPipes. An acknowledged batch and matching event count let the queries choose a complete boundary. A source write and a visible CDC record can arrive at different times.

5. Compare raw sales with materialized-view aggregates

Answer the same question with less work

How many units, how much revenue, and how much gross profit did each district generate? Run this question against individual sales lines, then against the minute aggregates. Compare identical answers, rows read, and elapsed time in SQL console.

Keep the sales writer from step 4 running. Both queries below use the fixed historical dataset (source = 'history'), so new sales do not change their answers during the comparison. ClickHouse continues ingesting live sales and maintaining the materialized views while you query.

5.1. Query the raw sales

Run this in ClickHouse Cloud SQL console. It calculates district totals from the 100-million-line sales history.

SELECT
    district_id,
    sum(quantity) AS units,
    sum(receipts_minor) / 100 AS revenue_sgd,
    (sum(receipts_minor) - sum(sold_cost_minor)) / 100 AS gross_profit_sgd
FROM pricing.retail_sales
WHERE source = 'history' AND branch = 'applied'
GROUP BY district_id
ORDER BY district_id
SETTINGS use_query_cache = 0;

Check the result table. In the query statistics, note elapsed time, rows read, and bytes read.

5.2. Query the minute aggregates

Run the equivalent question against the target table maintained by the materialized view:

SELECT
    district_id,
    sumMerge(units_state) AS units,
    sumMerge(receipts_state) / 100 AS revenue_sgd,
    (sumMerge(receipts_state) - sumMerge(cost_state)) / 100 AS gross_profit_sgd
FROM pricing.retail_district_minute
WHERE source = 'history' AND branch = 'applied'
GROUP BY district_id
ORDER BY district_id
SETTINGS use_query_cache = 0;

Verify that all 20 district rows match the raw query: units, revenue, and gross profit. Record the same query statistics.

Why the materialized view helps

The raw query adds values from individual sales lines. The aggregate table stores partial sums from your historical backfill and the materialized view's processing of new inserts. sumMerge combines those smaller states into district totals. ClickHouse reads fewer rows and avoids repeating the original aggregation work.

5.3. Repeat and compare

Treat the first execution of each query as a warm-up. Then run each query three more times, alternating raw and aggregate. Record the middle elapsed time of the three measurements and the rows and bytes read.

QueryMiddle elapsed timeRows readBytes read
Raw salesYour measurementYour measurementYour measurement
Minute aggregatesYour measurementYour measurementYour measurement

Both queries disable the query-result cache. Storage caches remain available to both approaches. Expect the aggregate query to read substantially less data; measure the latency improvement on your own service.

Calculate raw elapsed time ÷ aggregate elapsed time. A value of 4 means the aggregate query was four times faster in your measurements. Explain the result using both elapsed time and read volume.

This comparison focuses on sums. Exact distinct transaction counts from steps 1 and 3 require merging sets of transaction identities, which can have a different performance profile.

6. Check the continuing sales stream

In the writer terminal, confirm that the latest sales_rate_changed message shows "target_transactions_per_minute": 10000 once business time reaches 02:02 UTC. The switch happens automatically; leave the writer running. Overview shows the actual delivered rate, which can differ from the target.

The continuous feed covers the workshop's ready-to-eat product category. Individual products can sell out, but the bounded burst leaves inventory across the chain for the pricing exercises.

Start a fresh live scenario for another workshop run

Stop the writer with Ctrl+C and wait for its container to exit. Then, from the workshop directory, run:

.venv/bin/workshop retail-initialize --new-run

This creates a new run at 02:00 UTC with opening stock, prices, and policies. The 100-million-line history, aggregate tables, and previous runs remain available. Restart the writer with the command in step 4. Reload the workbench and select Start learner session. Wait for new completed sales batches to reach ClickHouse, then follow Module 03 to simulate the slowdown and find a pricing opportunity.

A fresh run begins a new pricing exercise. Select a new product comparison and approval; earlier receipts belong to the previous run.

Verify

Explain why an incremental materialized view needs a historical backfill. Compare the raw and aggregate query results, elapsed time, rows read, and bytes read. Describe how direct sales ingestion and operational CDC contribute different data.

Next: Find opportunities and compare prices.

このページの内容

Track your progress?

Optional. We email a link to confirm your address; progress records once you open it.

Please use your work email address, not a personal one.

By continuing you accept the Terms.

JA