Reduce PostgreSQL Memory Pressure in Matrix Synapse

If PostgreSQL is consuming more memory than expected for Matrix Synapse, first determine whether memory is in shared buffers, active query work, autovacuum, or a large number of connections. Then tune one source at a time and measure again. Synapse’s own Python workers also use substantial memory, so confirm the PostgreSQL processes or database container are the source before changing database settings.

Understand what “high memory” means

PostgreSQL uses shared memory for its cache, private memory for each server connection and query, and operating-system page cache. On Linux, memory shown as “used” can include reclaimable filesystem cache; that number alone does not prove the database is under pressure. Look for sustained low available memory, swap activity, out-of-memory events, or a container approaching its memory limit. Compare those signals with Synapse and PostgreSQL process metrics.

A PostgreSQL backend is a server process handling a client connection. Synapse’s database connection pool can open several backends per process, and Synapse workers each have their own pool. Increasing worker count or pool size can therefore increase concurrent database work and memory demand. Action: inventory Synapse processes, worker count, pool settings, PostgreSQL connections, and the host or container memory limit before adjusting PostgreSQL.

Find the main source before tuning

Connect to the Synapse database as an administrator and inspect the settings that control memory and connections:

SHOW shared_buffers;
SHOW work_mem;
SHOW maintenance_work_mem;
SHOW autovacuum_work_mem;
SHOW max_connections;

shared_buffers is PostgreSQL’s shared cache and is allocated when the server starts. work_mem is a per-query-operation budget for sorts and hash tables, not a per-server cap; one query may use several such operations, and many connections can execute them at once. Maintenance and autovacuum memory can also multiply when several maintenance workers run. Action: compare configured values with available RAM, concurrency, and the number of Synapse connections, rather than assuming the largest setting is best.

Use this query to see how many client sessions are connected and whether they are active or idle:

SELECT application_name, state, count(*)
FROM pg_stat_activity
GROUP BY application_name, state
ORDER BY count(*) DESC;

Where supported by your deployment, inspect the PostgreSQL container’s memory limit and use its metrics or the host’s process and cgroup metrics. Summing resident memory across PostgreSQL processes can overcount shared pages. Action: use the container or host’s total memory accounting to verify pressure, then use connection and query statistics to identify a likely contributor.

Choose changes based on the evidence

If query memory spikes during busy periods

Review work_mem first. A high value can consume substantial memory when concurrent queries perform multiple sorts or hash operations. Reduce it cautiously if measurements show query concurrency is multiplying memory use; the trade-off is that large operations may spill to temporary files and run more slowly. Avoid copying generic values from a different server because Synapse workload and PostgreSQL version matter.

PostgreSQL documentation describes shared_buffers as the main shared cache and gives about 25% of RAM as a reasonable starting point only for a dedicated database server with at least 1 GB of RAM. It also notes that allocating more than 40% is unlikely to help most workloads because PostgreSQL relies on the operating-system cache too. Action: use those figures as context, not a target for a shared Synapse host; if shared buffers already take a large portion of total memory, evaluate a lower value during a planned restart.

If connection count is the main pressure

Review Synapse’s database.args.cp_min and cp_max values in homeserver.yaml and in worker configuration files. The Synapse PostgreSQL guide shows these settings as the minimum and maximum connection-pool size. When there are many workers, each with a pool, the total possible connections can be much larger than the value in one file. Lowering cp_max can limit concurrent database backends and their memory footprint, but too small a pool can make requests wait for a connection.

database:
  name: psycopg2
  args:
    user: synapse_user
    password: "use-a-secret-store-or-protected-config"
    dbname: synapse
    host: 127.0.0.1
    port: 5432
    cp_min: 2
    cp_max: 5

The values above are illustrative only; they are not a universal recommendation. Count pools across the main process and every worker, and leave headroom for administration, migrations, monitoring, and other clients. PostgreSQL allocates some resources based on max_connections, so raising that limit “just in case” can increase baseline memory pressure. Action: cap Synapse pools to a level your measured concurrency needs and ensure PostgreSQL’s connection limit has room for all services plus administrative access.

If maintenance or autovacuum coincides with spikes

PostgreSQL may allocate maintenance memory for vacuum and index work. Autovacuum memory can be allocated per autovacuum worker, so a large setting combined with several workers can raise peak usage. Do not disable autovacuum to reduce memory: it performs necessary table maintenance. Action: inspect logs and activity during the spike, then adjust maintenance_work_mem or autovacuum_work_mem only if those operations are confirmed contributors.

Apply changes and verify the result

Back up the PostgreSQL configuration and Synapse configuration first. Change one variable or pool limit at a time, preserve existing credentials securely, and use the configuration path appropriate to your package or container. Some PostgreSQL parameters, including shared_buffers and max_connections, require a server restart; reloadable settings can be applied with PostgreSQL’s supported reload mechanism. Check the setting context before assuming a reload applied it.

After the change, monitor peak memory, swap and out-of-memory events, active connections, query latency, temporary file activity, and Synapse request delays over a representative busy period. The change is useful if it reduces memory pressure without causing sustained connection waits, slower queries, or a growing request backlog. If Synapse is the process consuming RAM rather than PostgreSQL, tune Synapse cache behavior and worker count separately; PostgreSQL settings will not fix memory held by Python workers.

Do not set work_mem equal to the whole server’s RAM, raise max_connections without calculating pool totals, or disable autovacuum as a blanket fix. If memory remains high, capture metrics during the peak and review the actual running queries and connection sources before adding hardware or making broad configuration changes.

Official references

Leave a Comment

Reduce PostgreSQL Memory Pressure in Matrix Synapse

Find whether PostgreSQL memory comes from query work, shared buffers, connections, or maintenance, then make targeted Synapse-safe changes.

Why Matrix Synapse Room Joins Are Slow—and What to Check

Why Matrix Synapse Room Joins Are Slow—and What to Check

Trace slow Matrix room joins to one remote homeserver, federation backoff, local database load, or an outbound sender queue before changing Synapse settings.

Close Matrix Sign-Ups or Require Invite Tokens on Synapse

Stop open account creation on a self-hosted Synapse server, or keep sign-ups invite-only with limited-use registration tokens.

Element Session Identity Warning: Verify Your Login Safely

Clear Element's unverified-session warning using a trusted device or recovery key, with checks that protect your encrypted chat history.

Stop ownCloud File Lock Timeouts with the Right Backend

Distinguish database lock contention from expired WebDAV locks, then choose and configure the right ownCloud 10 fix.

What to Check When ownCloud Web Opens to a Blank Page

What to Check When ownCloud Web Opens to a Blank Page

Trace a blank ownCloud Web screen to browser cache, missing web assets, service errors, or reverse-proxy URL settings with targeted checks.

Clear the ownCloud PHP Memory Warning in the Correct Runtime

Set ownCloud’s web PHP memory limit, restart the matching service, and verify the active value without confusing it with CLI settings or upload limits.

Troubleshoot ownCloud 10 MySQL Connection Failures

Find out whether MySQL, PHP, socket settings, or database permissions are blocking ownCloud 10, then verify a safe fix.

Set a Firm Expiration Limit for ownCloud Public Links

Set a Firm Expiration Limit for ownCloud Public Links

Make public link expiration mandatory in ownCloud Classic, set a maximum lifetime, and check existing shares that may need separate cleanup.

Add TOTP Two-Factor Login to ownCloud Infinite Scale with Keycloak

Add TOTP Two-Factor Login to ownCloud Infinite Scale with Keycloak

Enable TOTP through Keycloak, enroll users safely, and understand when Infinite Scale’s route-level MFA settings apply.