Query Offload
View as MarkdownYour primary database records transactions. As apps and agents read more, the same expensive queries run against it over and over: a page load that joins and aggregates several tables, an API call that assembles a customer record, an agent that retrieves context before it acts. Every read recomputes the result, and the writes that run the business slow down.
Query offload moves those reads to Materialize. Materialize reads the primary’s change stream and keeps the results of each query fresh, updating them incrementally as writes arrive instead of recomputing them on every read. An index holds the results in memory, so a read becomes a point lookup that typically returns in under 10 ms. The app gets fresh results without a cache to invalidate, and the primary goes back to doing writes.
This page walks through the pattern using a project-tracking app whose workspace page lists every project with its task and comment counts.
Get started
Copy this prompt into your coding agent.
Offload read queries from my primary database to Materialize. Fetch https://materialize.com/docs/markdown-docs/fundamentals/architecture-patterns/query-offload/index.md and follow it. Start by asking me which database I use and which queries put the most load on it.
Run the complete example locally with Docker. It lives in the query-offload
directory of the
Materialize reference architectures
repository, and includes Postgres, the Materialize Emulator, an app under
load, and a dashboard at http://localhost:8080 that switches page loads
between Postgres and Materialize.
git clone https://github.com/MaterializeInc/materialize-reference-architectures
cd materialize-reference-architectures/query-offload
docker compose up --build
When to offload a query
Offload a query when:
- It joins or aggregates several tables, so it is expensive to compute.
- It runs far more often than the data it reads changes.
- It filters on a key, such as a workspace, customer, or order ID.
Architecture
- The app writes to the primary database, as before.
- Materialize ingests the changes with change data capture.
- A view defines the expensive query, and an index keeps its results in memory, up to date as changes arrive.
- The app sends the same query to Materialize, which answers it with an index lookup.
Ingest the primary database
Connect Materialize to the database. This example uses a PostgreSQL source. Run ingestion and serving on separate clusters so that page loads never compete with ingestion.
CREATE CLUSTER ingest (SIZE = '100cc');
CREATE CLUSTER serving (SIZE = '100cc');
CREATE SECRET pg_password AS '<password>';
CREATE CONNECTION pg_conn TO POSTGRES (
HOST '<host>', PORT 5432, USER 'materialize',
PASSWORD SECRET pg_password, DATABASE 'tracker'
);
CREATE SOURCE app_db
IN CLUSTER ingest
FROM POSTGRES CONNECTION pg_conn (PUBLICATION 'mz_source');
CREATE TABLE projects FROM SOURCE app_db (REFERENCE public.projects);
CREATE TABLE tasks FROM SOURCE app_db (REFERENCE public.tasks);
CREATE TABLE comments FROM SOURCE app_db (REFERENCE public.comments);
To keep replication off the primary too, connect to a physical replica
instead. This requires PostgreSQL 16 or later. See
CREATE SOURCE: PostgreSQL.
Define the query as a view
Copy the query the app runs into a view, without the parameter. Materialize speaks the PostgreSQL wire protocol and SQL dialect, so most queries move unchanged.
CREATE VIEW workspace_overview AS
SELECT p.workspace_id, p.project_id, p.name AS project_name,
t.open_tasks, t.done_tasks, c.comments, c.last_comment_at
FROM projects p
CROSS JOIN LATERAL (
SELECT count(*) FILTER (WHERE status <> 'done') AS open_tasks,
count(*) FILTER (WHERE status = 'done') AS done_tasks
FROM tasks
WHERE tasks.project_id = p.project_id
) t
CROSS JOIN LATERAL (
SELECT count(*) AS comments, max(comments.created_at) AS last_comment_at
FROM comments
JOIN tasks USING (task_id)
WHERE tasks.project_id = p.project_id
) c;
Index the view on the lookup key
Index the view on the column the app filters on, in the serving cluster. The index computes the results once and updates them incrementally as writes arrive.
CREATE INDEX workspace_overview_idx
IN CLUSTER serving
ON workspace_overview (workspace_id);
Check that the app’s query reads the index directly:
SET cluster = serving;
EXPLAIN SELECT * FROM workspace_overview WHERE workspace_id = 7;
Explained Query (fast path):
→Map/Filter/Project
Project: #0..=#6
→Index Lookup on materialize.public.workspace_overview (using materialize.public.workspace_overview_idx)
Lookup values: (7)
Used Indexes:
- materialize.public.workspace_overview_idx (lookup)
Target cluster: serving
A fast path query returns rows from
the index without running a dataflow. If the plan doesn’t say fast path,
see Optimization: Indexes.
Point the app at Materialize
Send the page query to Materialize instead of the primary. Only the connection
changes. Set the cluster in the connection options, for example
options=-c cluster=serving.
SELECT * FROM workspace_overview WHERE workspace_id = $1;
Roll out one query at a time behind a feature flag, and compare results with the primary before you switch all traffic.
In the reference repo, with Postgres limited to 2 CPUs and 16 concurrent page loads, moving the page to Materialize raised throughput from about 230 to about 1,300 page loads per second, and dropped the median Postgres write latency from about 10 ms to under 2 ms. Your numbers depend on your query and hardware.
Consistency
Every query in Materialize reads all views at one consistent timestamp, so a page never mixes old and new data. See Isolation levels.
Results trail the primary by the time it takes to ingest a change. In the reference repo, a new comment appears in Materialize 1 to 2 seconds after Postgres commits it.
Production considerations
- Size the serving cluster for the index. The index holds every row of the view in memory. Offload queries over the data your app reads, not whole tables.
- Add replicas for availability. A cluster with two replicas keeps serving if one fails. See Clusters.
- Watch hot keys. A lookup returns every row for its key, so a key with many rows, such as one very large workspace, takes longer than the rest. Index on a finer key where the app can use one.
- Keep writes on the primary. Materialize is a read path. The app writes to the system of record, and Materialize picks up the change.
Learn more
- Live context graph: build on the same ingested data as you offload more queries.
- Indexes: how indexes keep results in memory.
- Reaction time, freshness, and query latency: how fresh results are.
- Ingest data from PostgreSQL: set up CDC for your database.