# Operating Materialize in production
How to run Materialize as a production database: sizing, access, changes, upstream systems, monitoring, and what to have ready when you need help.

> For the complete documentation index, see [llms.txt](https://materialize.com/docs/llms.txt).


This guide covers how to run Materialize as a production database: sizing,
access, changes, upstream systems, monitoring, and what to have ready when you
need help. It applies to every deployment. If you run Materialize yourself,
also see
[Operating self-managed deployments](https://materialize.com/docs/markdown-docs/production-readiness/self-managed-operations/index.md),
which covers the infrastructure underneath. Before go-live, work through the
[production readiness checklist](https://materialize.com/docs/markdown-docs/production-readiness/checklist/index.md) for your
deployment.

For the split of responsibilities between Materialize and your team, see the
customer responsibility model for
[Materialize Cloud](https://materialize.com/docs/markdown-docs/materialize-cloud/customer-responsibilities/index.md) or
[self-managed deployments](https://materialize.com/docs/markdown-docs/self-managed-deployments/customer-responsibilities/index.md).
This guide is the "how" for the customer side of the database
responsibilities.

## 1. Define what "down" means

Decide ahead of time what counts as an outage for each production workload, and
write it down. A target that only lives in someone's head can't be alerted on,
and makes it hard to judge how urgent an issue is.

For each critical object (usually the indexes, materialized views, or sinks
your applications depend on), define:

- **The metric.** Usually freshness, measured as a percentile such as p99 or
  p99.9. For sinks, it may be the delay before data lands downstream. For
  serving clusters, it may also be query latency.
- **The target.** For example, "p99.9 freshness under 10 seconds, measured
  over the last 24 hours."
- **The outage threshold.** How far past the target, for how long, counts as an
  outage rather than a degradation.

Use your thresholds to decide how to contact us:

| What you're seeing | Report it as |
| ------------------ | ------------ |
| Production data is stale or unavailable past your outage threshold, or queries aren't returning | Production outage |
| Freshness or latency is worse than your target, but data is still flowing | High priority ticket |
| A non-production issue, or a question about a trend | Normal ticket |

**Know your baseline.** Measure normal freshness and latency for at least a
week before go-live, including your busiest day. If your normal p99.9 is
already close to your target, small changes can push you over.

## 2. Control what runs on production clusters

A query that does more work than expected can affect everything else on its
cluster: one that scans instead of using an index, runs on the wrong cluster,
holds a transaction open, or returns a huge result. Limit who and what can run
on production clusters, and put limits on the queries that do.

### Access control

- Use [role-based access control](https://materialize.com/docs/markdown-docs/security/index.md) so only the right people and
  services can change or query production.
- **Limit who can create objects on production clusters.** Grant
  `CREATE ON CLUSTER` only to your deploy pipeline or a small group of owners.
- **Limit who can query production clusters.** Grant `USAGE ON CLUSTER` to the
  application service accounts that need it. Give analysts, BI tools, and ad
  hoc users their own cluster.
- **Set a default cluster per role** with
  `ALTER ROLE <role> SET cluster = '<cluster>'`, so people and tools land on
  the right cluster without having to remember.
- **Limit who can resize, drop, or alter** clusters, sources, and sinks.
- **Use separate service accounts** for each application, tool, and agent.
  Shared credentials make it hard to tell who ran what.
- **Harden authentication for people.** Require SSO or MFA where your
  deployment supports it: configure it in the Console on Materialize Cloud, or
  see [single sign-on](https://materialize.com/docs/markdown-docs/self-managed-deployments/sso/index.md) for self-managed.

### Query guardrails

- **Serve queries from indexes.** Point application queries at the cluster that
  holds the indexes they need. A query that can't use an index scans its
  inputs, which can use a lot of CPU and memory on a busy cluster. See
  [Optimization](https://materialize.com/docs/markdown-docs/transform-data/optimization/index.md).
- **Attach a query policy to production clusters.** A
  [query policy](https://materialize.com/docs/markdown-docs/clusters/query-policies/index.md) <a class="private-preview-inline" href="https://materialize.com/preview-terms/">(feature in private preview)</a>

  rejects ad hoc queries that would build temporary dataflows or read from
  object storage on a cluster that serves an application, before they run.
- **Keep transactions short.** Long-running transactions hold back cleanup on
  the clusters they read from, which increases memory use over time. Set
  `idle_in_transaction_session_timeout` on application, BI, and ad hoc roles
  with `ALTER ROLE`, so a stuck client can't hold a transaction open for
  hours. Role settings apply even if a client forgets to set them.
- **Break up large operations.** Large `DELETE` or `INSERT` statements and
  queries that return very large results can overwhelm a cluster. Run them in
  smaller batches.
- **Test generated SQL.** Very large or deeply nested queries, often produced
  by tools or code generators, can be expensive to plan. Test them in staging
  before they run in production.

### System clusters, tools, and agents

- **Be aware of the shared catalog server.** The Console, catalog queries, and
  many tools run on the
  [system catalog server](https://materialize.com/docs/markdown-docs/clusters/system-clusters/index.md), which every user in your
  environment shares. Heavy queries there can slow the Console and catalog
  operations for everyone.
- **Query the documented relations.** For query history, use
  `mz_internal.mz_recent_activity_log` rather than the raw statement-history
  tables, which are much more expensive to query.
- **Give tools and AI agents their own role.** Monitoring tools, BI tools, and
  AI agents that query Materialize should have their own role, and their own
  cluster where possible, with a query policy attached. Review what they run,
  the same way you would review a new application.
- **Be careful with diagnostics on a busy cluster.** `EXPLAIN ANALYZE` and
  introspection queries use the same resources as your production work. If a
  cluster is already saturated, check utilization first, or reproduce the
  problem on a separate cluster.

## 3. Isolate your production environment and change it safely

Problems can follow any change: a new view, a resize, a deploy, a new tool, or
an upgrade. Keep production separate from everything else, and treat changes to
it the way you treat changes to any other production database.

### Isolation

- **Run production in its own environment.** Separate clusters in the same
  environment help, but objects in one environment share the catalog and
  storage, so non-production work can still affect production. Use a separate
  environment for dev, staging, and CI.
- **Keep staging close to production.** Staging should run the same Materialize
  version and a similar data shape and volume, so changes behave the same way
  when they reach production.
- **Name things clearly.** Use prefixes like `prod_` and `stg_` so nobody runs
  a test against production by accident.
- **Clean up what you don't use.** Drop test objects and unused clusters.
  Objects left behind, especially on clusters with no replicas, can hold back
  cleanup on the sources they depend on and cause problems much later.

### Changes

- **Don't create objects on production clusters by hand.** Deploy through
  [dbt](https://materialize.com/docs/markdown-docs/developer-tools/dbt/index.md) or [mz-deploy](https://materialize.com/docs/markdown-docs/developer-tools/mz-deploy/index.md),
  which keep your objects in version control and stage changes for you.
- **Test every new view in staging first**, with realistic data, and check its
  memory, CPU, and freshness impact before it reaches production.
- **Use blue/green deploys** for schema changes to production clusters, so you
  can validate before cutting over. mz-deploy manages this for you. See
  [Updating materialized views](https://materialize.com/docs/markdown-docs/transform-data/updating-materialized-views/index.md).
- **Keep CI out of production.** CI pipelines that create and drop many
  objects, run bulk DDL, or load large files put heavy load on the catalog. Run
  them in their own environment, and batch DDL where you can.
- **Use connection pooling** for applications and tools that open many
  short-lived connections. See
  [Connection pooling](https://materialize.com/docs/markdown-docs/serve-results/connection-pooling/index.md).
- **Keep a change log.** When something breaks, the first question is "what
  changed?" Deploying through dbt or mz-deploy gives you this history for
  objects. Keep a record of resizes, new tools, and upstream changes too.
- **Plan around upgrades.** Know when upgrades happen in your deployment, avoid
  scheduling risky changes at the same time, and make sure production clusters
  are sized for hydration (section 4).
- **Tell us ahead of big events**, like a launch, migration, large backfill, or
  upstream failover test. We can help you plan capacity and watch for issues.

## 4. Right-size your clusters

Size each production cluster for its peak memory use, including when it
rebuilds its state after upgrades, maintenance, resizes, and failures. As a
rule of thumb, a cluster often needs to stay at or below about 60% of its
memory in steady state to have that room, and some workloads need more. For how
to measure peak usage, choose a size, and reduce the memory your workload
needs, see [Size clusters for hydration](https://materialize.com/docs/markdown-docs/clusters/sizing/index.md) and
[Optimize hydration requirements](https://materialize.com/docs/markdown-docs/clusters/optimize-hydration-requirements/index.md).

## 5. Upstream sources and downstream sinks

Materialize is only as healthy as the systems it reads from and writes to. The
teams that own those systems need to know Materialize depends on them, and
which changes can affect it.

### Upstream systems

These upstream events commonly affect Materialize, whatever the source type:

| Upstream event | What can happen in Materialize | What to do |
| -------------- | ------------------------------ | ---------- |
| Failover, promotion, or replacement of the upstream system | Materialize may lose its place in the change stream, and the source can fail or stall | Check the [ingestion guide](https://materialize.com/docs/markdown-docs/ingest-data/index.md) for your source type to see how it handles failover. Test a failover in staging, and plan how you'd recreate the source if needed. |
| Objects or permissions Materialize relies on are dropped or changed | The source can't resume and may get stuck retrying | Document what belongs to Materialize in each upstream system, and make sure nobody changes it without coordinating. |
| Schema changes to data Materialize ingests | The affected table or subsource can stall with an error | Run schema changes through change review, and check your source type's guide for how it handles them. |
| Bulk rewrites, like truncating and reloading data | Ingestion can stall, and fixing it the wrong way can cause incorrect results | [Contact us](https://materialize.com/support/) before doing this to data Materialize ingests. |
| Long-running transactions or locks upstream | New snapshots can hang, and unread changes can build up | Monitor long-running transactions and locks on upstream systems. |
| Adding new tables or a large initial snapshot | The source cluster may need much more memory while it snapshots | Resize the cluster before adding data, watch snapshot progress, then size back down. |

**Back up your source data.** The data of record lives in your upstream
systems, and recovering from some failures means re-ingesting from them. Back
up source data on a regular schedule, verify that the backups are complete,
and store them securely.

### Sinks

- **Give sink clusters enough capacity.** A sink that regularly falls behind
  can block other operations on the Materialize cluster that hosts it, such as
  blue/green deploys. Size that cluster with headroom, the same as any other
  production cluster.
- **Keep downstream systems compatible.** Outages, permission changes, or
  schema changes in the destination can put a sink into a retry loop.
  Coordinate changes with the destination's owners.
- **Watch sink status and lag**, not just source status (section 6).

Give the owners of each upstream and downstream system a short list of the
objects, users, and permissions Materialize relies on, and ask them to loop in
your Materialize owners before any failover test, major upgrade, or schema
change. For source-specific requirements, see [Ingest data](https://materialize.com/docs/markdown-docs/ingest-data/index.md) and
its troubleshooting pages.

## 6. Monitor Materialize

Your team should find out about a production problem before your users do. Use
the Materialize [monitoring and alerting](https://materialize.com/docs/markdown-docs/observability/index.md) docs as your
baseline.

### Connect a monitoring tool

- **Materialize Cloud:** Connect your region to
  [Datadog](https://materialize.com/docs/markdown-docs/observability/cloud/datadog/index.md) or
  [Grafana](https://materialize.com/docs/markdown-docs/observability/cloud/grafana/index.md) using a Prometheus SQL exporter.
- **Self-managed:** Use the bundled monitoring stack or forward metrics to your
  own platform. See
  [Operating self-managed deployments](https://materialize.com/docs/markdown-docs/production-readiness/self-managed-operations/index.md).

**Route alerts to a person.** Send production alerts to whoever is on call. An
alert in a channel nobody watches is the same as no alert.

### Start with these alert thresholds

These come from the recommended thresholds for
[Cloud](https://materialize.com/docs/markdown-docs/observability/cloud/alerting/index.md) and
[self-managed](https://materialize.com/docs/markdown-docs/observability/self-managed/alerting/index.md). Replace the freshness
and latency numbers with your own targets from section 1.

| What to watch | Warning | Alert | Measured over |
| ------------- | ------- | ----- | ------------- |
| Memory per cluster | 80% | 90% | Average over 15 minutes |
| CPU per cluster | 85% | 100% | Average over 15 minutes |
| Source status | Any change | Any change | Last 1 minute |
| Cluster replica status | Any change | Any change | Last 1 minute |
| Freshness (lag behind input) | Over 5 seconds | Over 1 minute | Average over 15 minutes |
| Query latency | Over your target | Over your outage threshold | Average over 15 minutes |

If you collect Prometheus metrics, see
[essential metrics](https://materialize.com/docs/markdown-docs/observability/essential-metrics/index.md) for the ones Materialize
recommends.

### Other checks worth adding

- **Queries on the wrong cluster.** Watch for ad hoc, BI, or agent queries
  hitting production clusters, by `cluster_name` and `application_name`.
- **Clusters with no replicas that still hold objects.** These can hold back
  cleanup on the sources they depend on.
- **Upstream systems.** For every system that feeds Materialize, watch its
  health, how far behind Materialize is reading from it, and how long it
  retains changes Materialize hasn't read yet.
- **Materialize Cloud status.** Subscribe to the
  [status page](https://status.materialize.com/), and mute expected alerts
  during the weekly maintenance window.

## 7. Build resilient applications

Some interruptions are brief and outside your control: an upgrade or
maintenance window, a replica restart, or a short outage in a service
Materialize or your network depends on. Applications that handle these well
often see little or no impact.

- **Retry connections.** Retry failed connections and queries with backoff,
  instead of failing on the first error.
- **Reconnect cleanly.** Expect connections to drop occasionally, and reconnect
  automatically.
- **Pool connections.** Reuse long-lived connections through a
  [connection pool](https://materialize.com/docs/markdown-docs/serve-results/connection-pooling/index.md) rather than opening a
  new connection for every request. Existing connections are often unaffected
  when opening new ones is briefly failing.
- **Make `SUBSCRIBE` clients resumable.** Track the last timestamp a client
  processed, so it can pick up where it left off after a reconnect. See
  [SUBSCRIBE](https://materialize.com/docs/markdown-docs/sql/subscribe/index.md).
- **Set client-side timeouts** that match your latency targets, so a slow query
  fails fast instead of piling up requests.
- **Decide what happens when data is stale.** If freshness passes your outage
  threshold, should your application keep serving, fall back, or show a
  warning? Decide ahead of time.
- **Avoid single points of failure on the path to Materialize.** Check the
  network path between your applications and Materialize for components that
  can take every connection down at once, such as a single proxy or NAT
  gateway, and build in redundancy where you can.
- **Include Materialize in your disaster recovery plan.** Decide how your
  applications behave during an extended outage, and how you would re-ingest
  from your source data backups (section 5) if you had to recreate an
  environment. For what recovery looks like per deployment, see
  [disaster recovery on Cloud](https://materialize.com/docs/markdown-docs/materialize-cloud/disaster-recovery/index.md) and
  [backup and restore for self-managed](https://materialize.com/docs/markdown-docs/self-managed-deployments/backup-and-restore/index.md).

## 8. Be ready to escalate

The fastest investigations are the ones where we have context in the first
message.

### Before an incident

- **Name your contacts.** Who should we talk to during an incident, during
  business hours and after hours? Include at least one person who can approve
  changes, like resizing a cluster.
- **Know who owns what Materialize depends on.** A fix often depends on someone
  who can change an upstream system, a network setting, or an application. Know
  who those people are and how to reach them on a weekend.
- **Make sure you can see your own query history.** Query text and literal
  values may be redacted in what we can see, so we may ask you to pull them
  from `mz_internal.mz_recent_activity_log`.
- **Set a clear `application_name`** for each application, tool, and agent, so
  it's easy to tell what ran which query.
- **Know your data-sharing rules.** If your company restricts sharing logs,
  query text, or screen sharing with vendors, sort out what's allowed before an
  incident.

### When you open a ticket, include:

- Your environment, and the affected clusters and objects
- When it started, with time zone, and whether it's still happening
- What your users are seeing, compared to your targets from section 1
- What changed recently in Materialize, your applications, your tools, or
  upstream
- Any error messages from sources, sinks, or clients
- Anything you've already tried, like resizing a cluster or restarting an
  application, and exactly when
- The application names or sessions involved, if you know them
- Self-managed only: an [mz-debug](https://materialize.com/docs/markdown-docs/developer-tools/mz-debug/self-managed/index.md)
  bundle and any changes since your environment profile (see
  [Operating self-managed deployments](https://materialize.com/docs/markdown-docs/production-readiness/self-managed-operations/index.md))
