
Dashboard, aggregate, tối ưu query, materialized viewDashboards, aggregates, query tuning, materialized views
Tám giờ sáng thứ HaiMonday, eight a.m..Đầu tuần, 300 chủ shop trên một nền tảng bán hàng cùng mở dashboard doanh thu, trong khi checkout vẫn nhận 400 đơn mỗi giây. Tài chính còn đang chạy báo cáo 12 tháng theo tỉnh thành.On Monday morning, 300 shop owners on a commerce platform open their revenue dashboards while checkout still takes 400 orders a second. Finance is also running a 12-month report by province.
Hãy theo một chủ shop mở biểu đồ doanh thu lúc 8 giờ sáng thứ Hai, đúng lúc checkout vẫn ghi đơn liên tục vào PostgreSQL primary. Sự kiện order.paid đi qua outbox lên Kafka, Rollup Worker tính lại đúng ngày giờ địa phương bị ảnh hưởng vào revenue_daily, còn ClickHouse nhận cùng luồng để phân tích sâu; Reporting API chỉ đọc rollup sau cache Redis có version. Chạy luồng dashboard trước, rồi bật “Sự kiện tới trễ” và “Báo cáo chậm” để thấy vì sao primary không bao giờ phải gánh báo cáo.Follow a shop owner opening the revenue chart at 8 a.m. on Monday, while checkout keeps writing orders to the PostgreSQL primary. order.paid events go through an outbox to Kafka, the Rollup Worker recomputes exactly the affected local day into revenue_daily, and ClickHouse takes the same stream for deep analysis; the Reporting API only reads rollups behind a versioned Redis cache. Play the dashboard first, then turn on “Late events” and “Slow report” to see why the primary never carries reporting load.
1Quản lý tenant t-17 mở biểu đồ doanh thu 16 ngày đầu tháng 10.A manager of tenant t-17 opens the revenue chart for the first 16 days of October.
GROUP BY trên hàng chục triệu dòng chiếm CPU, I/O và buffer cache của checkout. Tách đường đọc: dashboard đọc bảng rollup, báo cáo ad-hoc chạy trên replica với pool và statement_timeout riêng.A GROUP BY over tens of millions of rows takes CPU, I/O and buffer cache from checkout. Split the read path: dashboards read rollup tables, ad-hoc reports run on a replica with their own pool and statement_timeout.
REFRESH MATERIALIZED VIEW lấy ACCESS EXCLUSIVE lock. Dùng REFRESH … CONCURRENTLY (cần unique index trên view), nhưng nó vẫn tính lại toàn bộ; khi dữ liệu lớn, chuyển sang bảng rollup cập nhật từng ngày bằng upsert.REFRESH MATERIALIZED VIEW takes an ACCESS EXCLUSIVE lock. Use REFRESH … CONCURRENTLY (it needs a unique index on the view), but it still recomputes everything; at scale switch to a rollup table updated per day with upserts.
Cộng dồn gross += total sẽ cộng đôi khi Kafka giao lại. Sự kiện chỉ đánh dấu ngày bẩn; job tính lại cả ngày từ bảng gốc và ghi đè. Ngày cũ hơn 72 giờ đóng sổ, chỉ tính lại khi có lệnh thủ công.A running gross += total double-counts when Kafka redelivers. Events only mark the day dirty; a job recomputes the whole day from the source and overwrites it. Days older than 72 hours are closed and only recomputed on a manual command.
Lưu timestamptz (UTC), gom nhóm theo múi giờ tenant: (paid_at AT TIME ZONE 'Asia/Ho_Chi_Minh')::date. Rollup giờ theo UTC không gộp đúng được cho múi lệch nửa giờ như Asia/Kolkata, nên rollup ngày lưu theo ngày địa phương của từng tenant.Store timestamptz (UTC) and group in the tenant's zone: (paid_at AT TIME ZONE 'Asia/Ho_Chi_Minh')::date. UTC hourly rollups cannot be re-bucketed correctly for half-hour zones such as Asia/Kolkata, so daily rollups are stored per tenant-local day.
Định nghĩa báo cáo là một cây metric, dimension, filter. Visitor duyệt cây và sinh SQL cho PostgreSQL hoặc ClickHouse; Adapter che khác biệt hàm thời gian (date_trunc ⇄ toStartOfDay) giữa hai engine.A report definition is a tree of metrics, dimensions and filters. A Visitor walks it and emits SQL for PostgreSQL or ClickHouse; an Adapter hides the time-function differences (date_trunc ⇄ toStartOfDay) between engines.
Đầu giờ sáng hàng trăm người mở cùng dashboard. Cache Redis TTL 60 s, khoá có version của tenant để vô hiệu hoá khi rollup đổi, single-flight để mỗi khoá chỉ một truy vấn đang chạy.At the start of the day hundreds open the same dashboard. Cache in Redis for 60 s, include the tenant's rollup version in the key to invalidate on change, and use single-flight so each key has one query in flight.
Replay WAL xung đột với truy vấn đang đọc gây lỗi “canceling statement due to conflict with recovery”. Tăng max_standby_streaming_delay trên replica dành cho báo cáo, hoặc bật hot_standby_feedback và chấp nhận bloat trên primary; theo dõi replay_lag.WAL replay conflicting with a running read raises “canceling statement due to conflict with recovery”. Raise max_standby_streaming_delay on a reporting-only replica, or enable hot_standby_feedback and accept some bloat on the primary; watch replay_lag.
| BảngTable | Cột chínhKey columns | Ghi chúNotes |
|---|---|---|
orders | id, tenant_id, status, total, refunded, currency, paid_at timestamptz, created_at | Nguồn sự thật trên primary; index (tenant_id, paid_at) cho việc tính lại một ngàySource of truth on the primary; index (tenant_id, paid_at) serves single-day recomputes |
revenue_daily | tenant_id, day date, orders, gross, refunds, computed_at | PK (tenant_id, day); day là ngày địa phương của tenant; ghi bằng upsertPK (tenant_id, day); day is the tenant-local date; written by upsert |
revenue_hourly | tenant_id, hour_utc timestamptz, orders, gross, refunds | Cho biểu đồ trong ngày; gộp lên ngày chỉ đúng với múi giờ lệch tròn giờFor intraday charts; rolling up to days is only correct for whole-hour offsets |
rollup_dirty | tenant_id, day, marked_at | PK (tenant_id, day); job lấy bằng FOR UPDATE SKIP LOCKED rồi xoá sau khi tính lạiPK (tenant_id, day); the job takes rows with FOR UPDATE SKIP LOCKED and deletes them after recomputing |
order_events (ClickHouse) | order_id, tenant_id, event_time DateTime64, category, province, amount, version | ReplacingMergeTree(version), PARTITION BY toYYYYMM(event_time), ORDER BY (tenant_id, event_time, order_id)ReplacingMergeTree(version), PARTITION BY toYYYYMM(event_time), ORDER BY (tenant_id, event_time, order_id) |
RevenueRollup.java là hộp Rollup Worker ở sơ đồ: onOrderEvent đánh dấu ngày bẩn từ Kafka, recomputeDirtyDays tính lại từng ngày theo múi giờ tenant rồi upsert vào hộp Rollup tables. RevenueReport trong revenue_report.go là hộp Reporting API: đọc rollup trên replica, cache Redis có version và single-flight.RevenueRollup.java is the Rollup Worker box in the diagram: onOrderEvent marks dirty days from Kafka and recomputeDirtyDays recomputes each day in the tenant's time zone, upserting into the Rollup tables box. RevenueReport in revenue_report.go is the Reporting API box: it reads rollups on the replica behind a versioned Redis cache with single-flight.
package com.example.report;
import java.time.LocalDate;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class RevenueRollup {
private final JdbcTemplate jdbc;
private final DirtyDayRepository dirty;
private final ApplicationEventPublisher events;
private static final String RECOMPUTE_DAY = """
INSERT INTO revenue_daily (tenant_id, day, orders, gross, refunds, computed_at)
SELECT o.tenant_id, ?::date, count(*), sum(o.total), sum(o.refunded), now()
FROM orders o JOIN tenant t ON t.id = o.tenant_id
WHERE o.tenant_id = ? AND o.status IN ('PAID', 'REFUNDED')
AND o.paid_at >= (?::date)::timestamp AT TIME ZONE t.timezone
AND o.paid_at < (?::date + 1)::timestamp AT TIME ZONE t.timezone
GROUP BY o.tenant_id
ON CONFLICT (tenant_id, day) DO UPDATE
SET orders = EXCLUDED.orders, gross = EXCLUDED.gross,
refunds = EXCLUDED.refunds, computed_at = EXCLUDED.computed_at
""";
@KafkaListener(topics = {"order.paid", "order.refunded"}, groupId = "revenue-rollup")
public void onOrderEvent(OrderEvent e) {
LocalDate day = e.paidAt().atZone(e.tenantZone()).toLocalDate();
dirty.mark(e.tenantId(), day); // INSERT … ON CONFLICT DO NOTHING
}
@Scheduled(fixedDelay = 30_000)
@Transactional
public void recomputeDirtyDays() {
for (DirtyDay d : dirty.lockBatch(50)) { // FOR UPDATE SKIP LOCKED
jdbc.update(RECOMPUTE_DAY, d.day(), d.tenantId(), d.day(), d.day());
dirty.delete(d);
events.publishEvent(new RollupChanged(d.tenantId(), d.day()));
}
}
}package main
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"golang.org/x/sync/singleflight"
)
type RevenueReport struct {
replica *pgxpool.Pool // reporting pool on the read replica
cache *redis.Client
group singleflight.Group
}
func (r *RevenueReport) Daily(ctx context.Context, q RevenueQuery) ([]DayRow, error) {
ver, _ := r.cache.Get(ctx, "report:ver:"+q.TenantID).Result()
key := fmt.Sprintf("report:rev:%s:%s:%s:v%s", q.TenantID, q.From, q.To, ver)
if b, err := r.cache.Get(ctx, key).Bytes(); err == nil {
var rows []DayRow
return rows, json.Unmarshal(b, &rows)
}
v, err, _ := r.group.Do(key, func() (any, error) {
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
rows, err := r.load(ctx, q)
if err != nil {
return nil, err
}
if b, err := json.Marshal(rows); err == nil {
r.cache.Set(ctx, key, b, 60*time.Second)
}
return rows, nil
})
if err != nil {
return nil, err
}
return v.([]DayRow), nil
}
func (r *RevenueReport) load(ctx context.Context, q RevenueQuery) ([]DayRow, error) {
rows, err := r.replica.Query(ctx, `
SELECT day, orders, gross, refunds
FROM revenue_daily
WHERE tenant_id = $1 AND day BETWEEN $2 AND $3
ORDER BY day`, q.TenantID, q.From, q.To)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, pgx.RowToStructByName[DayRow])
}| Rollup PostgreSQL + replicaPostgreSQL rollups + replica | ClickHouse nạp từ sự kiệnClickHouse fed by events | |
|---|---|---|
| Hợp vớiGood for | Bộ chỉ số cố định, vài dashboard, đội nhỏA fixed set of metrics, a few dashboards, a small team | Phân tích ad-hoc, nhiều chiều, hàng tỷ dòngAd-hoc analysis, many dimensions, billions of rows |
| Tốc độ aggregateAggregate speed | Nhanh khi đọc rollup, chậm khi quét bảng gốcFast on rollups, slow on raw scans | Lưu theo cột, nén tốt, quét trăm triệu dòng trong vài giâyColumnar and compressed, scans hundreds of millions of rows in seconds |
| Sửa và xoáUpdates and deletes | Upsert và transaction bình thườngOrdinary upserts and transactions | Gần như chỉ thêm; sửa qua ReplacingMergeTree, kết quả đúng sau merge hoặc FINALMostly append-only; updates via ReplacingMergeTree, exact after merges or with FINAL |
| Chọn khiPick it when | Muốn ít hệ thống, số khớp tuyệt đối với DBYou want few systems and figures that match the DB exactly | Báo cáo đa chiều thay đổi thường xuyên, dữ liệu vượt sức replicaMulti-dimensional reports change often and data outgrows a replica |
Worker chạy UPDATE total = total + amount sẽ cộng hai lần khi Kafka giao lại sự kiện sau rebalance, và không bao giờ tự sửa được. Chỉ đánh dấu ngày bẩn rồi tính lại cả ngày từ bảng nguồn bằng upsert, nên chạy lại bao nhiêu lần cũng ra cùng kết quả. Thêm job đối soát hằng đêm so revenue_daily với SUM trên replica và cảnh báo khi lệch quá 0,01%.A worker running UPDATE total = total + amount double-counts when Kafka redelivers after a rebalance, and never heals itself. Only mark the day dirty and recompute it from the source tables with an upsert, so any number of reruns gives the same result. Add a nightly reconciliation comparing revenue_daily with SUM on the replica and alert above 0.01% drift.
date_trunc('day', paid_at) trên cột timestamptz cắt theo múi giờ của session, thường là UTC, nên đơn từ 0:00 tới 7:00 giờ Việt Nam rơi vào ngày hôm trước. Lưu timezone theo tenant và tính khoảng [00:00, 24:00) địa phương rồi đổi sang UTC trước khi truy vấn. Viết test với đơn lúc 23:58 và 00:02 cho tenant ở Asia/Ho_Chi_Minh.date_trunc('day', paid_at) on a timestamptz column truncates in the session time zone, usually UTC, so orders between 0:00 and 7:00 Vietnam time land on the previous day. Store a time zone per tenant, compute the local [00:00, 24:00) range and convert it to UTC before querying. Test with orders at 23:58 and 00:02 for a tenant in Asia/Ho_Chi_Minh.
Chuyển báo cáo sang replica mà không giới hạn thì mười truy vấn 30 giây có thể làm replica trễ vài phút và dashboard đọc số cũ. Dùng pool riêng tối đa 4 kết nối, statement_timeout 120 giây và theo dõi replay_lag. Báo cáo chạy lặp lại hằng ngày nên chuyển sang ClickHouse hoặc rollup theo tháng.Moving reports to a replica without limits lets ten 30-second queries push replica lag to minutes, so dashboards read stale numbers. Use a dedicated pool of at most 4 connections, statement_timeout 120 seconds, and watch replay_lag. Reports that run every day belong in ClickHouse or a monthly rollup.
300 chủ shop mở dashboard lúc 8 giờ, khoá TTL 60 giây hết hạn cùng lúc và hàng trăm request cùng đổ xuống DB. Dùng single-flight theo khoá cache, cộng jitter 10-20% vào TTL và trả số cũ trong lúc làm mới nền. Theo dõi tỉ lệ hit và số truy vấn rollup mỗi giây sau mỗi lần INCR version.300 shop owners open dashboards at 8 a.m., 60-second TTL keys expire together and hundreds of requests hit the database at once. Use single-flight per cache key, add 10-20% jitter to the TTL and serve the stale value while refreshing in the background. Watch the hit rate and rollup queries per second after each version INCR.
Mỗi pattern mở bài học tương ứng trong menu Pattern.Each one opens its lesson in the Patterns menu.
Ngay lập tức: chuyển truy vấn sang replica với statement_timeout. Sau đó: EXPLAIN (ANALYZE, BUFFERS) để thêm index phù hợp. Lâu dài: bảng rollup theo ngày cập nhật tăng dần, cache trước API; nếu báo cáo đa chiều nhiều lên thì đưa sự kiện sang ClickHouse.Right away: move the query to a replica with a statement_timeout. Next: EXPLAIN (ANALYZE, BUFFERS) and add the right index. Longer term: an incrementally updated daily rollup with a cache in front; if multi-dimensional reports grow, stream events into ClickHouse.
Kafka giao ít nhất một lần nên sẽ cộng đôi; hoàn tiền, huỷ đơn cũng phải trừ đúng. Đánh dấu ngày bẩn rồi tính lại cả ngày từ bảng gốc là idempotent và tự sửa được mọi sai lệch trước đó.Kafka delivers at least once, so you will double-count, and refunds and cancellations must subtract correctly. Marking the day dirty and recomputing it from the source is idempotent and repairs any earlier drift.
Mỗi tenant lấy khoảng [00:00, 24:00) theo múi giờ của mình đổi sang UTC: Việt Nam là 14/10 17:00Z tới 15/10 17:00Z, Ấn Độ là 14/10 18:30Z tới 15/10 18:30Z. Vì vậy rollup ngày lưu theo ngày địa phương, không gộp từ rollup giờ UTC.Each tenant takes its local [00:00, 24:00) and converts it to UTC: Vietnam is 14 Oct 17:00Z to 15 Oct 17:00Z, India is 14 Oct 18:30Z to 15 Oct 18:30Z. That is why daily rollups are stored per local day and not summed from UTC hourly rollups.
Materialized view hợp khi dữ liệu vừa và refresh định kỳ là đủ; dùng REFRESH CONCURRENTLY với unique index để không chặn người đọc. Khi dữ liệu lớn hoặc cần tính lại từng phần (một ngày, một tenant), bảng rollup với upsert rẻ hơn nhiều vì không tính lại toàn bộ.A materialized view suits moderate data where a periodic refresh is enough; use REFRESH CONCURRENTLY with a unique index so readers are not blocked. With large data or partial recomputes (one day, one tenant), a rollup table with upserts is far cheaper because nothing is recomputed in full.
Phím 1–4 để chọn đáp án, Enter để kiểm tra.Press 1–4 to choose an answer, Enter to check.
Ôn tập ngắt quãng (spaced repetition): thẻ được lặp lại sau 1 → 3 → 7 → 14 → 30 ngày để củng cố trí nhớ dài hạn.Spaced repetition: cards are repeated after 1 → 3 → 7 → 14 → 30 days to build long-term memory.