Clean Up Old Synapse Messages and Media Without Losing Data

To remove old Matrix Synapse data safely, treat room history and media as separate jobs. Use the Purge History Admin API for old room events, the media deletion API for local media, and the remote media cache API for downloaded files from other homeservers. For recurring cleanup, configure retention policies for messages and media. Purging database rows does not always shrink the database file on disk immediately.

Choose the cleanup that matches your goal

What is taking space?UseImportant limit
Old messages and other room eventsPurge History Admin API, or automatic message retentionHistory purging is room-specific. Room state is preserved; Synapse keeps at least one message in each room.
Media stored by your homeserverDelete Local Media API, or local media retentionMedia used in profiles and room avatars is protected by default by the date/size endpoint.
Media cached from other homeserversPurge Remote Media API, or remote media retentionIf requested again, Synapse fetches it again from the originating server.

These controls affect Synapse’s own database and media repository. If you use an external media repository, such as Matrix Media Repository, Synapse’s local media deletion endpoint does not remove files stored there. Check that repository’s own documentation and backup policy before deleting data.

Prepare before you purge

  1. Confirm which Synapse instance handles media. In a worker deployment, media cleanup runs on the worker with enable_media_repo: true; this may be the main process. Confirm your routing and configuration before diagnosing a cleanup that appears not to run.
  2. Back up the database and media store. Take a current, restorable backup before an irreversible purge. Record the room ID and cutoff time, and use a server administrator access token. Do not paste the token into a shared shell history or publish it in logs.
  3. Plan the cutoff carefully. Purge endpoints accept timestamps in Unix milliseconds. Use a UTC-derived cutoff and verify the number before sending the request. A cutoff is not a preview: it can permanently remove eligible data.

In the examples below, replace https://matrix.example.com with the client-facing base URL for your homeserver, set a valid room ID, and export an administrator token in ADMIN_TOKEN. Keep the bearer token private.

Remove old message history from one room

The Purge History API removes events older than a specified point from Synapse’s database. It does not redact messages for other servers, and it is not the same as removing a room. By default, Synapse deletes events sent by remote users but keeps local users’ events; set delete_local_events to true only when you intend to remove those too. Room state such as membership and the topic is preserved.

For example, to set a cutoff 180 days before the current time on a Linux host, calculate the timestamp in milliseconds, inspect it, then submit the request for a single room:

export SYNAPSE_URL='https://matrix.example.com'
export ROOM_ID='!roomid:example.com'
export ADMIN_TOKEN='replace-with-a-server-admin-token'
PURGE_BEFORE_MS=$(python3 -c 'import time; print(int((time.time() - 180*86400) * 1000))')
printf 'Cutoff (Unix milliseconds): %s\n' "$PURGE_BEFORE_MS"

curl -sS -X POST "$SYNAPSE_URL/_synapse/admin/v1/purge_history/$ROOM_ID" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H 'Content-Type: application/json' \
  -d "{\"purge_up_to_ts\":$PURGE_BEFORE_MS,\"delete_local_events\":true}"

Omit delete_local_events or set it to false if you want Synapse’s default behavior. If the API returns a purge_id, the purge has started; it has not necessarily finished. Poll the status endpoint until it reports complete or investigate its error if the status is failed:

curl -sS "$SYNAPSE_URL/_synapse/admin/v1/purge_history_status/$PURGE_ID" \
  -H "Authorization: Bearer $ADMIN_TOKEN"

Large purges can take several minutes or longer. During the operation, users may be unable to paginate further back in that room from the point being purged. Synapse keeps at least one message in a room, so this API will not make the room’s timeline entirely empty.

Delete old media and cached remote files

For a one-time cleanup of local media last used before a cutoff, use the current local media endpoint. Its before_ts is a Unix timestamp in milliseconds, and it can also accept size_gt to target files above a byte threshold. The default keeps media still used for profile or room-avatar images; do not set keep_profiles=false unless you intentionally want those files removed.

curl -sS -X POST "$SYNAPSE_URL/_synapse/admin/v1/media/delete?before_ts=$PURGE_BEFORE_MS" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{}'

Review the response’s total and deleted media IDs. The endpoint deletes local originals and thumbnails. Avoid the older path containing /media/<server_name>/delete; the Synapse docs mark that route as deprecated since v1.78.0. The current local media endpoint does not operate on a separate external media repository.

Cached remote media is a separate category. To remove remote media in the cache that was last accessed before the same cutoff, use:

curl -sS -X POST "$SYNAPSE_URL/_synapse/admin/v1/purge_media_cache?before_ts=$PURGE_BEFORE_MS" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{}'

The response reports how many cached items were deleted. If users request those files later, Synapse may download them again from their origin server, so this operation trades local disk use for possible network traffic and retrieval delay.

Set recurring retention instead of repeating manual purges

Synapse message retention is disabled by default. To enforce a server-wide default for rooms without their own retention state, add a policy to the configuration and enable it. This example sets a one-year maximum:

retention:
  enabled: true
  default_policy:
    max_lifetime: 1y

Use the duration units supported by Synapse, such as d for days and y for years. Room administrators and moderators may also set a room’s m.room.retention state event, while server admins can cap permitted maximum lifetimes with allowed_lifetime_min and allowed_lifetime_max. Review your full policy before enabling it: eligible events are permanently removed by background purge jobs. Synapse hides expired events from clients as soon as they expire, but the database purge runs periodically, so rows can remain until a job runs. State events are not covered by message retention.

For media, add media_retention lifetimes, for example:

media_retention:
  local_media_lifetime: 90d
  remote_media_lifetime: 14d

These lifetimes are inactivity periods, not simply an upload-age limit: when a file has been accessed, Synapse uses its last access; for media never accessed, it uses its creation time. Original files and thumbnails are removed. Quarantined media and local media protected from quarantine are not removed by this cleanup. Configure media retention on the process that hosts the media repository, then validate the setting against the configuration manual for the Synapse version you run.

Read the official Purge History API, Media Admin API, Synapse configuration manual, and message retention policy documentation before applying changes. The API behavior described here reflects the official documentation checked on October 10, 2026; confirm endpoints and configuration against your installed release.

Verify storage was reclaimed

  • Poll the history purge status until it says complete; keep the purge ID and response for your maintenance log.
  • Check the local media and remote cache responses for their deleted counts, then inspect Synapse logs and filesystem usage after the cleanup.
  • Do not assume that fewer database rows immediately means a smaller database file. Synapse’s documentation notes that PostgreSQL may reuse freed space without returning it to the operating system. For PostgreSQL, VACUUM FULL can reclaim disk space but requires an exclusive lock; schedule it with downtime/impact in mind and follow the PostgreSQL VACUUM documentation. For SQLite, Synapse’s retention documentation identifies VACUUM as the corresponding operation.
  • Confirm that the expected files or older events are no longer served, and verify that your backup remains available before closing the maintenance task.

Leave a Comment

Clean Up Old Synapse Messages and Media Without Losing Data

Use Synapse’s history and media purge APIs or retention settings to remove stale data safely, then verify completion and disk-space recovery.

Build a Matrix Echo Bot in Python with Simple-Matrix-Bot-Lib

Build a Matrix Echo Bot in Python with Simple-Matrix-Bot-Lib

Install the current library, connect a dedicated Matrix account, and run a small !echo bot with safer credential handling and a clear test.

Connect Matrix to WhatsApp, Telegram, and Discord with Separate Bridges

Connect Matrix to WhatsApp, Telegram, and Discord with Separate Bridges

Set up three mautrix bridges with separate registrations, logins, and tests—and avoid Docker networking, account-policy, and sync surprises.

Reclaim Synapse Media Disk Space Without Breaking Shared Files

Find what is filling Synapse storage, set safe media retention, and purge remote cache without deleting files directly from disk.

Deactivate Inactive Matrix Users Without Deleting Room History

Deactivate Inactive Matrix Users Without Deleting Room History

Review device activity, deactivate confirmed inactive Synapse accounts through the Admin API, and learn what the optional erase flag actually removes.

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.