PostgreSQL pg_ivm Review: Real-Time Materialized Views Without Full Refreshes

Database tutorial - IT technology blog
Database tutorial - IT technology blog

Six months ago, our analytics dashboard hit a wall. A standard PostgreSQL materialized view was aggregating daily order totals across 18 million rows. Running REFRESH MATERIALIZED VIEW CONCURRENTLY every five minutes kept the UI mostly current, but each run took 45 seconds, spiked disk I/O, and still left customers looking at stale numbers right after checkout.

We moved that workload to pg_ivm, an open-source PostgreSQL extension for Incremental View Maintenance (IVM). Rather than recomputing the entire view, pg_ivm updates only the rows touched by an INSERT, UPDATE, or DELETE—inside the same transaction. Six months later, dashboard queries still finish in under 4 milliseconds. Our refresh cron jobs are completely gone. Here is how pg_ivm works, where it pays off, and what caught us off guard.

Quick Start: Real-Time Views in 5 Minutes

Testing pg_ivm locally takes a few minutes. You can install it from your OS package manager or compile it directly against PostgreSQL 13 through 17 headers:

git clone https://github.com/sraoss/pg_ivm.git
cd pg_ivm
make
sudo make install

Enable the extension in your target database next:

CREATE EXTENSION pg_ivm;

Now let’s build an orders table and an Incrementally Maintainable Materialized View (IMMV) to track revenue per customer.

CREATE TABLE orders (
    order_id SERIAL PRIMARY KEY,
    customer_id INT NOT NULL,
    amount NUMERIC(10, 2) NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

INSERT INTO orders (customer_id, amount) VALUES
(101, 49.99),
(101, 25.00),
(102, 120.50);

-- Create the incremental materialized view
SELECT pg_ivm.create_immv(
    'customer_revenue',
    'SELECT customer_id, COUNT(*) AS order_count, SUM(amount) AS total_spent
     FROM orders
     GROUP BY customer_id'
);

Insert a new order and query customer_revenue right away—no refresh command needed:

INSERT INTO orders (customer_id, amount) VALUES (101, 30.00);

SELECT * FROM customer_revenue WHERE customer_id = 101;
-- customer_id | order_count | total_spent
-- 101         | 3           | 104.99

The view updates synchronously inside the INSERT transaction. Roll back that transaction, and the view rolls back too.

How pg_ivm Works Internally

Knowing what pg_ivm creates in your schema explains both its speed and its limits. Unlike a native PostgreSQL materialized view, an IMMV is a regular heap table paired with metadata in the pg_ivm_immv catalog.

Triggers, Transition Tables, and Delta Computation

Calling pg_ivm.create_immv() parses your query and attaches statement-level AFTER INSERT, AFTER UPDATE, and AFTER DELETE triggers to every base table it references. Those triggers use PostgreSQL transition tables (REFERENCING OLD TABLE and NEW TABLE) to capture the exact rows modified by your statement.

pg_ivm never scans the full base table on a write. Instead, it evaluates the view query against those small transition tables, builds a delta, and applies it directly to the IMMV.

How Aggregates and Joins Are Maintained

Different SQL operations carry very different maintenance costs:

  • COUNT, SUM, and AVG: These update algebraically. Adding a $10 order adds 10 to total_spent. For AVG, pg_ivm tracks internal sum and count columns (such as __ivm_count__) so it can recalculate averages and delete groups when their count reaches zero.
  • MIN and MAX: Inserts are fast because pg_ivm only compares the new value against the current extreme. Deleting the current minimum or maximum, however, forces a rescan of that group in the base table.
  • INNER JOINs: Deltas from one table join against the current rows of the other. Index your join keys on both sides, or every write will trigger a sequential scan.
  • DISTINCT: Supported by tracking row multiplicity in a hidden internal count column.

Production Patterns That Actually Matter

Treat an IMMV like any other high-traffic table in production—because physically, it is one.

Indexing IMMVs and Using pg_ivm.refresh_immv

You can add B-tree, GIN, or partial indexes directly on an IMMV to tune read queries. By default, pg_ivm also builds a unique index on the GROUP BY or primary key columns so delta updates can locate target rows quickly.

Sometimes you still need to clear an IMMV before a schema migration or force a full rebuild:

-- Clear all rows from the IMMV (similar to WITH NO DATA)
SELECT pg_ivm.refresh_immv('customer_revenue', false);

-- Repopulate the IMMV from scratch
SELECT pg_ivm.refresh_immv('customer_revenue', true);

Batching Bulk Imports to Protect Throughput

Every night, we import partner pricing feeds into a base table linked to two IMMVs. Because pg_ivm relies on statement-level triggers, loading 5,000 rows in one statement is far cheaper than firing 5,000 separate INSERTs. In our benchmarks, batching dropped load time from ~14 seconds to under 180 milliseconds.

We use jsonb_to_recordset to ingest the entire batch in one query. When I need to convert CSV to JSON before testing an import, I use toolcraft.app/en/tools/data/csv-to-json—it runs locally in the browser, so sensitive partner data stays off third-party servers. From there, a single parameterized query handles the insert:

import json
import psycopg

with open("partner_orders.json", "r") as f:
    payload = json.load(f)

query = """
INSERT INTO orders (customer_id, amount)
SELECT customer_id, amount
FROM jsonb_to_recordset(%s::jsonb) AS x(customer_id int, amount numeric);
"""

with psycopg.connect("dbname=app user=postgres") as conn:
    with conn.cursor() as cur:
        cur.execute(query, (json.dumps(payload),))
    conn.commit()

All 5,000 rows land in a single transition table. pg_ivm computes one combined delta and updates both IMMVs in milliseconds.

Four Lessons From 6 Months in Production

Before rolling pg_ivm out to your own cluster, keep these four constraints in mind:

  1. Avoid hot summary rows: A global aggregate (no GROUP BY) or a low-cardinality key like status creates a single bottleneck row. Concurrent writes to the base table will line up waiting for a lock on that exact row, serializing your throughput. Keep grouping keys granular.
  2. Verify SQL support early: pg_ivm does not support LEFT/RIGHT/FULL OUTER JOIN, window functions (OVER (...)), UNION, HAVING, or LIMIT inside the view definition. Queries that depend on outer joins will need a rewrite or a standard materialized view.
  3. Index join and filter columns on base tables: Writing to Table A when it joins Table B triggers a lookup on Table B inside the transaction. Missing indexes turn routine writes into slow locks.
  4. Watch autovacuum on IMMVs: Frequent UPDATEs on summary rows produce dead tuples just like any busy PostgreSQL table. Tune autovacuum settings on small, high-churn IMMVs so bloat does not creep in.

For read-heavy dashboards and live counters where eventual consistency falls short, pg_ivm has held up without a single incident for us. Respect the write-path cost, batch your bulk loads, and keep your grouping keys selective.

Share: