Video in progress
Dashboard queries are slow because of heavy JOINs. How do you choose between denormalization, a materialized view, or a separate read model?
If the data being a few minutes stale is fine, REFRESH MATERIALIZED VIEW CONCURRENTLY. If you need real-time, a denormalized table updated by a trigger or the application, or a read model built from events. With each option you're choosing between consistency and the cost of writes.
📖 Answer
First I check: is the query really slow because of the JOIN, or because an index is missing? In many cases the right composite index and a well-written query make denormalization unnecessary.
If it's still needed:
A materialized view
CREATE MATERIALIZED VIEW sales_daily AS
SELECT shop_id, date_trunc('day', created_at) AS day, sum(total) AS revenue
FROM orders GROUP BY 1, 2;
CREATE UNIQUE INDEX ON sales_daily (shop_id, day); -- required for CONCURRENTLY
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;
Simple and reliable. But every refresh recomputes the whole query: PostgreSQL has no incremental refresh. If the base table is big, a refresh every 5 minutes is a constant load on the database.
A denormalized table (updated by a trigger or the application) is real-time, but every write becomes more expensive, and a hot row problem can appear on one row (say, the daily total). Triggers are hidden logic, and a new developer doesn't see them.
A read model through events (CQRS) can live between services, even in another database. It's the most flexible, but it needs eventual consistency and a rebuild mechanism.
My decision table is: "how much staleness can we take?" and "how large is the write volume?". Minutes and moderate writes: an MV. Seconds and small writes: a trigger/table. Across services or heavy writes: a read model. In every case I don't change the source: denormalization is a cache, and it must always be possible to recompute it.
Sign up to mark studied questions and save your progress.