Shrinking the Synapse database with state compression

State compression can reduce the growth of the state_groups_state table on a PostgreSQL-backed Synapse server, but the gain depends on your rooms, your schedule and your backups. This page explains how to decide, run and verify it.

On this page

Synapse state compression: when the database needs it

State compression with synapse_auto_compressor rewrites stored room state to reduce the space that the state_groups_state table takes in PostgreSQL. It suits teams that have already measured where their database growth comes from and found that room state, not message content or media, is the main contributor. Synapse records a state group whenever room state changes, and in busy or heavily federated rooms those rows accumulate quickly. The compressor works on the existing rows, grouping and storing state more efficiently so that later reads need fewer rows. Before scheduling anything, check the table sizes in your own database, look at which rooms carry the most state, and confirm that the growth is not coming from media or event history instead.

Teams usually reach for the compressor after the database keeps growing even though they have already tuned retention and media cleanup, or after a large room or a backfill has added far more state than normal traffic would explain. It complements history purges and media cleanup rather than replacing them: purging removes old events and media that you no longer need, while compression changes how the remaining state is stored. Running compression on a database that still holds data you intend to delete wastes effort, so sequence the work with your retention decisions. Treat the specifics of the tool, including its command options, supported database versions, resource needs and how it handles rooms, as release-dependent. Confirm them in the Synapse documentation for the release you run, starting with the Synapse documentation, and test on a restored copy of your database before running it in production.

Compressor settings and the room situations they fit

This table compares the main choices an operator makes before running the compressor: which rooms to target, how much work each pass does, how often to run, which database role to use, and whether to rehearse on a copy. Read each row against your own room list and server load, then check the exact option names in the Synapse release notes for the version you run, since flag names and defaults change between releases.

DecisionChoice to considerTrade-offWhen it fits
Which rooms to targetLargest rooms first, using a size report from your databaseBiggest savings come early, but these rooms often hold the most state to rewriteDisk is nearly full and a few rooms dominate state_groups_state growth
Which rooms to targetEvery room, in one sweepLongest total run and the most database work at onceYou have a maintenance window and a tested backup
How much work per passSmall batches of rooms per runSlower overall progress, but each run ends predictably and locks lessThe live server serves busy users during the day
How much work per passLarger batches in a quiet windowFinishes sooner, but load and lock contention rise while it runsTraffic is low at night and you have watched a test batch
How often to runScheduled runs at a fixed intervalSteady, low impact, but growth between runs is only trimmed laterState grows steadily and you want a routine task
How often to runOne catch-up run after a known spikeLess routine work, but it follows a backfill or large join rather than a timetableA federated room backfilled a large history or joined a very large room
Database role and connectionA dedicated database user with the minimum rights the tool documentsMore setup, but a mistake is limited to the rights grantedProduction, where the Synapse credentials should not be reused
Database role and connectionReusing the Synapse application accountLess setup, but the tool gets rights it does not needOnly on throwaway test environments
Run against a copy firstRestore a recent backup to a separate PostgreSQL instance and run thereExtra storage and time, but you see the size change and any errors without risk to live dataAny first run, and any run after a Synapse or PostgreSQL upgrade
Run against a copy firstRun directly on production after a verified backupFastest path, but failures land on the live homeserverOnly when you have already rehearsed the same version and the same room set

How state groups grow on PostgreSQL

A state group in Synapse is a stored snapshot of the current state of a room at a particular point in its history, such as who is joined, the room's name, its power levels and its encryption settings. Synapse does not store a full copy of that state for every event. Instead it records a state group for events where the state changed and keeps the rows for each group in the state_groups_state table in PostgreSQL. Every time the state of a room changes, for example when someone joins, leaves, is invited or banned, or when an admin edits a setting, Synapse may create another group. In a busy room with many membership changes, the table therefore grows with the number of state transitions multiplied by the size of the room's state, which is why large, active rooms dominate the table.

Growth in state_groups_state is not always a sign of a fault. Rooms with thousands of members, rooms that many servers join, and rooms that were backfilled from federation (where Synapse fetches earlier history from other servers after joining) can each carry a large number of state groups. Backfilling is often the surprise: a server that has just joined a busy public room may take on a long chain of historic state that it must keep to validate events. Before you act, check which rooms account for the rows, how many members they have and whether the growth follows normal activity or a sudden spike. Confirm with your own database statistics rather than assuming a single room is the cause, and record the baseline so later runs can be compared.

Deleting data does not shrink PostgreSQL files on its own. Removing old rows leaves free space inside the table files, so the disk usage you see may stay high after a purge or compression run until maintenance reclaims it. Plan that step as a separate task and keep it out of the compression discussion. The sibling guidance on purging room history and running VACUUM covers how to reclaim that space and how to schedule the downtime it can require, so read it before you decide how much free space to expect. Note the free space you need for maintenance before you start, because the work itself needs room to write new data.

Every compressor run starts from a verified backup and a rehearsal

The diagram follows room state from Synapse into PostgreSQL, then shows the order operators should follow before touching the live database. A verified backup comes first, and a test run on a restored copy checks the result. Only after that does a scheduled run work against the live database. The last step is to compare table size and confirm Synapse still behaves normally, because a smaller table alone does not prove the run was safe.

Order of operations for compressing state in a live Synapse database.

Setting up state compression safely, step by step

This sequence takes a Synapse operator from version checks and measurement through a verified backup, a rehearsal on a restored copy, and a scheduled compressor run on the live server with monitoring in place.

  1. Confirm Synapse and PostgreSQL versions

    The operator checks the running Synapse release and PostgreSQL major version against the upgrade notes for every release between the current version and the target, and confirms the platform floors those notes list, including the PostgreSQL 14 minimum for Synapse 1.143.0 and later. Confirm that the PostgreSQL major version is still within its supported window on the published versioning policy. Record both versions in the change ticket. The step is done when every floor is met or an upgrade is scheduled first, and the operator has read the notes for each intermediate release.

  2. Measure state group size and find large rooms

    Using PostgreSQL, the operator records the on-disk size of the state_groups_state table and its indexes, along with the total database size, and then queries which rooms have the most state group rows. The team should note the row counts and the top rooms, and whether growth comes from a few rooms or many. Capture the output as a baseline so the post-run comparison has something to measure against. The step is done when the baseline file lists table size, index size, total database size, and the top rooms by row count, dated and stored with the change record.

  3. Take and verify a PostgreSQL backup

    The operator takes a fresh logical or physical backup of the Synapse database, following the team's documented procedure, and keeps the Synapse configuration and signing key alongside it. A backup is only useful if it restores, so the operator checks that the archive is readable, that the file or dump completes without errors, and that its size and checksum are recorded. The step is done when the backup exists in a location separate from the production host and a checksum is stored with the change record.

  4. Restore to a non-production host

    The operator restores the verified backup to a separate PostgreSQL instance and a Synapse configuration that does not connect to live users or federation traffic. Running the restored copy with federation disabled or firewalled prevents it from sending events to other servers. The step is done when the restored Synapse starts cleanly against the copy, the database answers queries, and the team confirms the restore matches the baseline row counts from the measurement step.

  5. Run the compressor on the restored copy

    On the non-production host, the operator installs synapse_auto_compressor and runs it against the restored database, starting with the largest rooms identified earlier. The operator records how long each run takes, the CPU, memory and disk use observed on the host, and any errors or warnings in the log. Repeat runs on a small sample before a full pass, so the team learns the resource profile. The step is done when the run finishes or stops with a logged reason, and the resource observations are written down.

  6. Compare table size and Synapse behavior

    After the rehearsal, the operator repeats the size queries and compares table size, index size and total database size with the baseline. The team also starts the restored Synapse, checks that rooms load and that sync and message send work in test rooms, and confirms that state resolution in compressed rooms behaves as before. Expect the saving to differ by room, so the team should judge it by its own measurements. The step is done when the before and after numbers are recorded side by side and any behavioral issue is either resolved or documented as a blocker.

  7. Schedule runs on the live server

    The operator schedules the compressor on the production server only after the rehearsal is accepted, choosing a low-traffic window agreed with the people who handle user impact. Runs should be chunked or limited to the rooms the rehearsal covered, with a monitored log file that is watched during and after each run. The team should keep the verified backup available until the post-run checks pass. The step is done when the schedule, the log location, the alert on errors, and the rollback decision point are written into the runbook and a first supervised run completes.

  8. Check live results and record the outcome

    After each scheduled run, the operator reviews the monitored log, repeats the size queries, and checks Synapse health in the usual way, including message delivery and federation to a test partner. The operator keeps the before and after measurements in the record and sets the next run based on what the numbers show. The step is done when the post-run size, error count and health checks are recorded and the team has agreed whether to continue, adjust the schedule or stop.

What drives the compressor's resource needs and run time

The compressor's footprint depends on how much state the database already holds, how the rooms got that way, and what else the host and database are doing during the run. Measure these before the first run, then get the provider to confirm the window, resources and rollback plan in writing.

Database size and state group count

The size of state_groups_state and the number of state groups set the amount of work the compressor must read and rewrite. Before the first run, query the size of the state_groups_state table and the total database size, and record the count of state groups. Growth over months matters more than a single snapshot, so track it over time. Ask the provider to confirm, in writing, how they estimate run time from these figures and which measurements they need from you before quoting a window.

Room size and backfill history

Large rooms with long federation histories produce the most state groups, and backfilled history adds state that was never compressed when it arrived. Identify the largest rooms by state group count before scheduling, and note any rooms that joined a large federated network or pulled in long backfills. Ask the provider how they handle rooms that dominate the work, whether they run them in a separate pass, and what output they will report per room.

CPU and memory on the compressor host

The compressor runs as a separate process that reads and writes large volumes of state data, so its CPU and memory use competes with Synapse on a shared host. Record the host's core count, available memory and current load at the time you plan to run it. Keep the compressor on a host or container with its own limits where possible. Ask the provider to state the minimum CPU and memory they expect for your database size and whether they will test on a copy first.

Disk I/O and free space during the run

Compression writes new state group rows while old ones are still present, so the database needs free space for the rewrite and the storage needs headroom for write load. Check free disk space on the PostgreSQL volume, the write latency during normal traffic, and the space that a previous purge or VACUUM has already returned. Ask the provider to confirm the worst-case extra space they plan for, how they monitor it during the run and when they will stop the job if space falls below a threshold.

Connection limits and PgBouncer pooling

The compressor opens its own database connections alongside Synapse's connection pool, so a busy server can hit the PostgreSQL connection limit during the run. Record the configured max_connections value, the number of connections Synapse uses under load, and whether PgBouncer sits in front of the database. If the compressor connects through PgBouncer, confirm how transaction pooling affects its session behavior. Ask the provider to confirm which connection path they will use and the connection count they expect.

PgBouncer docs

Competing traffic during the window

Compression competes with normal Synapse traffic for database time, so the run window should avoid peak messaging, federation catch-up and scheduled jobs such as media or history purges. Review your usage pattern for the last several weeks to find the quietest period, and check that no other maintenance job overlaps it. Ask the provider to confirm how they will pause the compressor if user-facing latency rises, and who on your side can approve that pause.

What to expect from large, backfilled and quiet rooms

Large public rooms with long histories usually hold the most rows in state_groups_state, so they are where the compressor has the most to work with. The largest reduction tends to appear where membership and state change often and many stored snapshots are nearly identical. Savings are smaller where room state is stable and changes slowly, even when the room is big.

  • Membership churn: Rooms where many users join and leave create many similar state snapshots, which is the pattern compression is designed to reduce.
  • Long first runs: A long history takes more time to process, so schedule the first pass in a quiet window and expect it to be the heaviest run.
  • Active rooms: Rooms with constant new events keep writing state while the compressor works, so watch database load and lock waits during the run.
  • Modest gains on stable state: A large room with little state change may shrink only a little, so check the row count before assuming a large saving.
  • Long logs: Progress output for big rooms can be extensive, so decide where logs go and who reviews them before the first run.

Before setting expectations, measure the row count and table size for your largest rooms on a restored copy of your database.

Protecting data and service during compression runs

State compression rewrites rows in one of the largest tables in a Synapse database, so the risk sits in the data itself and in the service people use while the run is active. The cards below cover the controls to set before the first run, the access the compressor should hold, and the records to keep afterward.

Verify backups before the first run

Take a fresh PostgreSQL backup and confirm it restores into a separate database before the compressor touches state_groups_state. Point-in-time recovery, using the base backup and WAL archiving described in the PostgreSQL continuous archiving docs, lets you return to a moment just before a bad run. Record the restore time you measured, because that is the realistic recovery window to tell stakeholders. Check the restored copy by starting Synapse against it in a test environment.

PITR docs

Grant a narrowly scoped database role

Create a dedicated PostgreSQL role for the compressor instead of reusing the Synapse application role or a superuser. Give it only the table access the compressor needs, and confirm the exact required permissions with the Synapse documentation for your release before you grant anything. Keep the role's password in your secrets store, and remove the role once the compression project is closed so credentials do not linger.

Keep logs and credentials private

The compressor writes progress output and connects with database credentials, so its log file and config can expose both. Store the config file with restricted file permissions, send logs to a directory that only the operator team can read, and avoid pasting either into tickets, chat rooms or shared documents. Review the log after each run for database hostnames or room identifiers you would not want widely visible, and redact before sharing.

Plan for downtime and degraded service

Confirm with the Synapse upgrade and configuration notes whether your release needs the homeserver stopped during a run, or whether the database can keep serving traffic while compression works. Large rooms can slow the database for the whole homeserver, so schedule runs in a low-traffic window and agree on a user-facing message in advance. Decide who can stop a run early and what state the database must be in when you do.

Watch for errors that halt a run

A run that stops partway through can leave you with partly compressed state, so capture the exit status of every scheduled execution and alert on failure. Watch PostgreSQL logs for lock waits, disk space warnings and connection limits during the run, and check free space on the volume holding the database before each start. Treat a failed run as an incident: confirm the database is healthy and decide whether to resume or restore before the next scheduled attempt.

Document each run for change control

Record the date, the target database, the room list or scope used, the backup identifier, the role used, the start and end times, and the result. Attach the before and after table sizes so reviewers can see what changed. Route the record through your change management process so auditors and internal reviewers can trace who approved the work and what evidence supports it, and keep the entry with your backup records.

Limits to confirm before you schedule runs

Start by confirming the versions in your own environment, because the compressor only helps if the rest of the stack is supported. Check which Synapse release you run and which PostgreSQL major version sits underneath it. The Synapse upgrade notes set a floor: releases 1.143.0 and later require PostgreSQL 14 or newer, and PostgreSQL 14 itself reaches end of support on November 12, 2026, so a cluster that is close to that date needs a plan before any compression work begins. Then confirm that the synapse_auto_compressor you install comes from the same release line as your homeserver. Run it against a database that does not match the Synapse schema and the results cannot be trusted. Record both versions in your change ticket so the run can be reproduced or rolled back against known software.

Next, confirm whether the live database can tolerate a long, write-heavy job. The compressor reads and rewrites state_groups_state in batches while Synapse keeps serving clients, so you need to know the disk headroom for new rows and WAL, the load your primary already carries, and the window your operations team will accept. Ask for the size of state_groups_state and the total database size from a staging restore rather than from production guesses. Savings also depend on your room mix: large, long-lived, busy rooms and rooms that were backfilled from federation usually hold the most redundant state, while a small or quiet server may gain little. Estimate the benefit from a test copy before you commit the change window, and decide in advance what result would make the work not worth repeating.

Treat the backup as the first deliverable, not a side task. Rolling back Synapse is not always simple, because the upgrade notes warn that database schema changes between releases can make a downgrade difficult, and the compressor rewrites the state data the server depends on. Take a consistent PostgreSQL dump, save the Synapse configuration and signing key, and prove that the dump restores into a separate PostgreSQL instance on the same major version and that Synapse starts against it. A backup that has never been restored tells you little about whether you can recover. Keep that restored copy until you have watched the production server through several days of normal traffic after the run.

Questions teams ask before running state compression

What does state compression cost, and what drives the effort up?

The cost is mostly staff time, plus a test environment and backup storage. Your team or a partner spends time on discovery (measuring the size of state_groups_state, finding the largest rooms and checking the Synapse version), on a rehearsal against a restored copy of the database, on the production run and on post-run checks. Effort rises with the number of large or heavily backfilled rooms, the size of the database, how much the restore copy must mirror production, and whether the run happens during a maintenance window that someone must coordinate. Recurring costs are smaller: scheduled runs need monitoring and occasional review. Ask any quote to list discovery, rehearsal, production run, backup and restore testing, monitoring and handover as separate line items, and to state which parts are one-time and which recur.

How long does a state compression run take?

Duration depends on the size and shape of your state data, not on a single fixed number. The main factors are how many rows sit in state_groups_state, how many rooms have long histories or were backfilled from federation, the PostgreSQL hardware and I/O capacity, and whether the compressor runs while the homeserver is busy. Rooms with many state changes take longer to process than small quiet rooms. Because the work is incremental and can be stopped and resumed, many teams run it in short sessions rather than one long outage. Do not plan from anyone's generic estimate. Measure a restored copy of your own database first, record how long a representative set of rooms takes, and scale the schedule from that measurement.

What must our team provide before a partner starts?

A partner needs access and information that only your organization holds. Provide a current Synapse version and the PostgreSQL version it runs on, read access to the database through an account you approve, a recent backup or the ability to take one, a copy of the homeserver configuration with secrets removed, and a test environment with enough disk to hold a restored copy of production. You also need a named owner who can approve the production window, a contact for incidents, and a decision on which rooms may be touched. Confirm with your Synapse release notes which versions the compressor supports, because the upstream project documents its own requirements. Missing items usually show up as delays, so list them in the written scope before work begins.

Can our own team run synapse_auto_compressor without outside help?

Yes, if your team has PostgreSQL administration skills, can work with Synapse configuration and can run a restore test. The tool is documented upstream, so an internal team can schedule runs, watch the database and adjust settings. The risk lies in skipping the rehearsal, running without a verified backup, or treating the first large room as typical. Teams that do it alone should still measure growth before and after, keep a written rollback plan and assign someone to review the logs each run. A partner adds value mainly when the team lacks database experience, needs a documented change record for auditors, or wants the work done inside a fixed scope with a known end point.

How do we know state compression worked?

Measure before and after, using the same method both times. Record the total size of the database and the size of state_groups_state, the row counts for the largest rooms, and the homeserver response behavior for a set of routine client actions. Compare these figures after each scheduled run. Expect the physical size to change only if the freed space is reclaimed, so pair the compressor with an understanding of VACUUM behavior before judging the result. Also confirm that the homeserver still starts cleanly, that rooms load correctly, that encrypted rooms still decrypt for members and that the logs show no new errors. Write these checks into the acceptance criteria so the result is recorded, not argued about.

Does state compression replace purging room history?

No. State compression and history purging solve different problems. State compression reorganizes how Synapse stores room state groups so that the state_groups_state table grows more slowly and can shrink in parts, while the events themselves stay in place. Purging history removes old events from a room and is a data-retention decision that deletes messages. Compression never removes user content, so it does not meet a retention or erasure obligation. Many operators run both: compression to reduce storage overhead and purging only after a documented policy and approval. Decide the retention policy first, then choose the technical measures, and record each decision separately in your change log.

What should we back up before running the compressor?

Take a consistent PostgreSQL backup and confirm it restores before any production run. Also save the homeserver configuration, the signing key and the media store, because a database restore alone does not recover everything Synapse needs. Store the backup outside the database host, record its time and checksum, and test a restore into a separate environment. Backup storage is a recurring cost tied to database size and retention period, so ask any quote to state how many copies are kept and for how long. Point-in-time recovery requires continuous WAL archiving, which PostgreSQL documents in its continuous archiving guidance, so confirm whether your environment already has it before relying on it.

How DeployOpen scopes and delivers state compression

DeployOpen plans and runs state compression for Synapse as part of a self-hosted Matrix deployment in infrastructure you control. The work starts with a written scope that covers your PostgreSQL版本 and database size, the rooms driving growth, and a tested backup before any compressor run.

How we scope

  • Written scope lists the Synapse and PostgreSQL versions, the database size and the state_groups_state growth to be addressed.
  • Scope records which rooms are large or heavily backfilled, and which of them need a separate review before compression.
  • Scope sets the maintenance window, the compressor schedule and the resource limits agreed with your database owners.

How we build

  • We confirm a verified backup of the Synapse database and configuration exists and can be restored before the first run.
  • We configure synapse_auto_compressor against a staging copy, measure table growth and record how long each run takes.
  • We move the schedule to production only after the staging results match the agreed scope and your database team signs off.

How we hand over

  • Handover documents the compressor settings, the schedule, the commands used and the expected pattern of database size changes.
  • Runbooks explain how to pause the job, read its output, and recover from an interrupted run or a failed backup check.
  • We walk your operations team through the monitoring checks that show whether compression is keeping pace with new state.

How we support

  • Fixed-scope engagements have written deliverables and timelines agreed before work starts.
  • Ongoing support, Synapse upgrades and continuous testing are available as a retainer, which covers schedule reviews after major room activity.
  • Ask any quote to itemize the staging work, production runs, documentation and any retainer, so you can compare it with your own team's effort.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.