Pruning stale Matrix devices and sessions

Forgotten logins on a self-hosted Matrix server stay valid until something removes them. This page explains how to prune stale devices and sessions on Synapse and MAS, and what each change does to encryption keys and users.

On this page

Why stale Matrix devices and sessions are an attack surface

Every Matrix account on your server can hold logins for devices its owner no longer uses: an old phone that was replaced, a laptop returned to IT, a browser profile on a shared machine, or a bridge session that was set up once and never revisited. Each of those logins is a working credential path into the account. Pruning stale devices and sessions shortens that list, so that only logins people still use can act on their behalf. The work is about limiting what a forgotten login can still do, not about changing how people chat.

In Synapse, a device is a login that an account has registered, identified by a device ID and holding its own access token and, where encryption is in use, its own encryption keys. Under the Matrix Authentication Service, the equivalent is a session, an OAuth 2.0 grant tied to a client and a device, which MAS tracks and can end. The two models differ in where the data lives and which admin interface you use, so confirm the current device and session tooling for your release before you write a cleanup procedure. Teams should act when they retire a device fleet, offboard staff or contractors, rotate credentials after an incident, or notice a growing count of unused devices per account.

Be clear about what this work is not. Pruning does not replace password policy, multi-factor sign-in at your identity provider, or rate limits on login attempts, and it does not remove devices that a user still relies on. Pruning also has a cost: a device that is removed loses access to any encryption keys held only on that device, so the decision needs input from the people who own those conversations. Before you start, ask your provider or internal team to confirm the retention window they want, how users will be told, and which admin calls will be audited.

Pruning options and when each fits

This table compares four ways to remove a device or session from a Matrix account, covering what each removes, who triggers it, and what happens to the device's encryption keys. Read each row against your own policy for forgotten logins and urgent access revocation. The main takeaway is that automatic pruning clears old logins without staff effort, while admin and user actions handle cases where access must end now.

OptionWhat it removes and who triggers itEffect on encryption keysBest fit
delete_stale_devices_after (automatic)Devices with no recent activity, removed by Synapse on its own schedule with no operator actionKeys for removed devices are deleted; messages only that device could decrypt stay unreadable unless backed upFleets with many forgotten logins where losing old device history is an accepted trade-off
Admin device APIs (manual)Named devices or all devices for one user, removed by a server admin on demandSame key removal as automatic pruning, applied immediately to the targeted devicesOffboarding, suspected compromise or a lost device where access must end now
User sign-out from a clientThe current device, removed when the user signs out in Element or another Matrix clientDevice keys are removed at sign-out; confirm the exact behavior for your client versionShared or borrowed computers, and users who want to end their own access
MAS session managementOAuth and compatibility sessions issued through Matrix Authentication Service, ended by users in account settings or by adminsEnding a session ends its device access; confirm in the MAS documentation how device keys are handledDeployments that use MAS for SSO, where sessions are the main control point for sign-out

Setting up a stale device policy safely

This sequence turns a stale device policy into a tested, reversible change. It inventories existing logins, agrees the inactivity window with security and support, proves the setting on a non-production homeserver, and then confirms that production behaves as expected before any user loses a session.

  1. Inventory current devices and sessions

    Using an admin account, list each user's devices through the Synapse admin API so you know how many sessions exist, when each last connected, and which ones carry encryption keys. Record the counts per user, flag service and bridge accounts, and export the list to your change record. Done when you have a baseline you can compare against after the change, and the security team has signed off that the export is stored under your normal access controls.

  2. Agree the inactivity period with stakeholders

    Security, support and the team that runs bridges and bots agree on the inactivity period before anyone edits configuration. Ask security which idle devices they consider acceptable to keep, ask support how often users lose history or keys after a forced logout, and ask bridge owners whether any service sessions would be affected. Write the agreed value and its rationale into the change record. Done when all three groups have approved the value in writing.

  3. Rehearse the setting on a non-production homeserver

    Copy the configuration and a recent sample of accounts to a non-production Synapse instance, set delete_stale_devices_after to the agreed value, and restart it under the same version you run in production. Use test accounts with old sessions, including one with a cross-signed device and one service account, then check which devices remain. Done when the outcome matches the agreed rule and no unexpected account lost access.

  4. Back up and read the upgrade notes

    Read the upgrade notes for the Synapse release you run, and for any release you plan to move to, because they state when a restart is needed and which changes affect rollback. Take a database backup and confirm you can restore it on a separate host. Done when the change record names the release, the restart requirement and the backup location, and the restore has been tested.

  5. Enable the setting in production configuration

    Add delete_stale_devices_after to homeserver.yaml with the value agreed earlier, and keep the file under version control so the change is reviewable. Confirm the key's accepted format in the configuration manual for your release. Done when the diff contains only this change and a second reviewer has approved it. Rollback is the same edit in reverse, applied before restart. Because a removed device may take its only copy of some keys with it, record which accounts depend on keys held on a single device.

  6. Restart the homeserver as the upgrade notes require

    Restart the main process and any workers in the order your release notes and deployment method require, and watch the logs for startup errors such as configuration parse failures. Keep the change window open until each process reports healthy and test accounts can sync. Done when every process runs the new configuration with no startup errors. If a process fails, revert the configuration line from the previous step and restart again.

  7. Verify device listings and logs

    Run the inventory again and compare it with the baseline to confirm which devices were removed and that accounts meant to keep access still have their sessions. Review the logs for pruning activity and for reports of unexpected sign-outs or missing message keys. Done when the comparison matches the agreed rule and support has notes on what users may see. If results are wrong, revert the configuration line and restart, and use the database backup only if the upgrade notes say rollback is not safe.

Security and operational considerations

Pruning removes sessions that nobody is using, but it also changes what attackers can reuse, what auditors can see and what users experience. The cards below cover the risks that connect those effects, from token lifetime and admin access to offboarding and proof that the job actually runs.

Stale tokens stay valid until removed

A device that is no longer in use still holds an access token and, often, a refresh path that works until the server deletes the device. Pruning narrows that window, but it does not start on its own. Check how long stale devices remain valid before the cutoff runs, and whether revoking a session on the server also invalidates its tokens immediately or only at the next sync or refresh. Test this on a non-production account before relying on it.

Protect admin API credentials

Device deletion runs through the Synapse admin API, so whoever holds an admin access token can log out any user's devices. Store that token in a secrets manager, scope automation to the minimum needed, and keep the admin endpoints off public networks. Rotate the token when someone with access leaves the team, and record which job or person made each call.

Synapse configuration manual

Keep audit evidence for removed sessions

Once a stale device is deleted, its record disappears from the device list, which can remove the trail an investigator or compliance reviewer would ask for. Decide what you must retain, such as device ID, user, last-seen time and the reason for removal, and export it before the job deletes anything. Confirm with your compliance owner how long that export must be kept and where it is stored.

Align pruning with SSO and offboarding

If users sign in through an identity provider, disabling an account upstream does not necessarily end its Matrix sessions on its own. Make offboarding deactivate the Matrix account and remove its devices in one workflow, and confirm how your identity setup handles deprovisioning. Pruning covers forgotten logins; it does not replace removing access for people who have left.

Monitor that pruning actually runs

A scheduled pruning job that fails silently leaves stale devices in place while the configuration looks correct. Record each run's start, end, number of devices removed and any errors, and alert when a run is missed or removes an unusual number of devices. Review these figures periodically, since a sudden spike can signal a compromised account or a misconfigured cutoff.

How a device moves from active to removed

The lifecycle starts when a login creates a device, which stays active while the client syncs and sends messages. If no activity happens for the configured period, the server can remove the device automatically when delete_stale_devices_after is set, or an administrator can remove it through the admin device API. Removal invalidates that device's access token, so the client must sign in again, and the encryption keys held only on that device are lost with it. Before enabling pruning, confirm that users have key backups and know which clients they run.

Device lifecycle from login to removal, with the automatic and manual paths.

What pruning does to encryption keys and user experience

Removing a device removes its access to the account, and that access is the point of the exercise. It also changes which encryption keys remain usable on that device. In Matrix, end-to-end encryption keys for a session live on the device that holds them, so a device that is pruned takes its local message keys and cross-signing trust state with it. Messages that were only decryptable on that device may become unreadable for that user, and the stale device's trust status disappears from the account's device list. Before enabling delete_stale_devices_after or running admin device deletions, confirm with your own test accounts exactly what your Synapse version deletes and what it leaves in place, including whether any server-side key backup is affected.

Users who return to the service after a device is removed should expect to sign in again on a new login. Depending on their client and what they had backed up, they may need to verify the new session with another verified device, or restore their message history from server-side key backup using their recovery key or passphrase. Users who never set up key backup or recovery may lose access to older encrypted history. Forgotten devices that remain on the account can also appear as unverified in other clients, which trains users to ignore device warnings. Test how Element and any other clients you support present these states, because the wording and recovery prompts differ between clients.

Communicate the policy before you enable it. Tell users how long an unused session can stay signed in, that a long-unused device may be removed, and how to check their own device list and set up key backup and recovery. Ask your support team to prepare a short recovery procedure for users who report missing history, and set a point at which you will review support volume after the first pruning run. Confirm the exact key-handling behavior with your Synapse version and client mix in a staging environment before the policy reaches production users.

Limits and what to confirm in your environment

Pruning devices changes what users see and what encryption keys survive, so the setting's behavior depends on your Synapse version, your authentication setup and the clients and bots you run. The items below are the checks to make before you enable anything on a production homeserver.

Synapse version and upgrade notes

Confirm that the Synapse release you run supports delete_stale_devices_after and read the upgrade notes for every release between your current version and the target. Behavior around device cleanup can change between releases, so the notes are the authority for your version. The latest release listed on the Synapse GitHub releases page is v1.163.0, but your production version may be older, and the setting must be verified against the version you actually run.

Synapse upgrade notes

Whether MAS changes session removal

If you run Matrix Authentication Service, device and session lifecycle moves out of Synapse's local user store, so the Synapse setting may not describe what MAS does with sessions. Confirm which component owns the session record, how upstream SSO logins create devices, and whether removing a session in MAS also removes the device in Synapse. Test this on a staging homeserver before relying on either control.

MAS upstream identity docs

Bridge and bot device behavior

Bridges and bots log in as devices and may hold long-lived sessions that look stale to a cleanup rule. Before enabling pruning, list every service account and bridge device, confirm how each one re-authenticates, and decide which ones need exemption or a fixed device ID. Pruning a bridge device can break message relay and can leave encrypted rooms without the keys that service needs.

Matrix bridges directory

Admin API endpoints in the deployed version

Device management through the admin API varies by release, so confirm which device and session endpoints your deployed Synapse exposes and what each one returns. Check the endpoint list in the configuration and API documentation for your version, then test listing, deleting and bulk removal against a copy of your data. Restrict these endpoints to private administrative access, since they can end sessions for any user.

Synapse configuration manual

Database and platform floors

Pruning runs as database work, so the PostgreSQL and Python versions your server runs must meet the floors in the upgrade notes for the release you plan to run. Current notes state that Synapse 1.143.0 and later require PostgreSQL 14 or newer, and 1.142.0 and later require Python 3.10 or newer. Also confirm that a tested backup exists, because rolling back after schema changes can be difficult.

Questions teams ask before pruning Matrix devices

What does it cost to prune stale Matrix devices and sessions?

Cost depends on how many Synapse servers you run, how your admin access is controlled, and how much testing your encryption and user support teams need before a change goes live. Pruning itself is a configuration change plus a scheduled cleanup, so most of the cost sits in planning, testing and documenting the policy. Ask for a quote that lists the policy decisions in scope, the environments that will be tested (staging and production), the admin API scripts to be written and reviewed, and the handover material for your operators. Ask whether the quote covers a rollback plan and a post-change check. DeployOpen does not publish prices, and a quote follows from the written scope.

How long does a stale device pruning rollout take?

The duration depends on how many environments you have, how many users and devices you need to review, and whether your identity provider already controls session lifetimes. The main variables are the number of Synapse instances, whether MAS is already in front of login, and how long your change board takes to approve a policy. Confirm with your delivery lead which steps are fixed and which depend on your sign-off, such as agreeing the inactivity window, testing with real users in a pilot group, and checking that bridges and bots keep working. Ask for the timeline as a written plan with named checkpoints.

What does our team need to provide before the work starts?

You need to provide access to your Synapse and MAS configuration, the database and Redis details needed for admin operations, a staging environment that mirrors production, and a named owner who can approve the inactivity window. Your identity team should confirm how logins are created and whether devices are tied to SSO sessions, and your support team should agree on the message users receive when a device is removed. Also provide a list of bridges, bots and service accounts, since these may need overrides or exclusions. Ask the implementer to list each input in the scope document before the start date.

Can our own team prune stale devices without a partner?

Yes, a capable operations team can do this, provided it has admin access to the server and can test changes safely. The Synapse configuration setting delete_stale_devices_after and the admin device APIs are documented, so the work is mostly about deciding the policy, writing scripts that are reviewed, and monitoring the results. Teams usually struggle with the testing and the user communication, not the commands. Be honest about capacity: a partner adds value when you need an independent review, a documented change for auditors, or help covering encryption and bridge edge cases during rollout.

How does pruning affect end-to-end encryption for users?

Removing a device deletes its session and the keys held for it on the server side, so a user may lose the ability to read older encrypted messages on that device if no other device or key backup holds them. Users who sign in again on a new device will need to verify it and restore from key backup. Before you set a short window, confirm with your encryption owner how many users rely on a single device, whether key backup is enabled, and how verification will be explained to users. Document the trade-off so your security and support teams agree on it.

What goes wrong when a stale device policy is too aggressive?

The most common problems are users who are signed out unexpectedly, encrypted history that cannot be read after a device is removed, and bots or bridges that stop working because their sessions are treated as stale. Each of these is avoidable when you test with service accounts and pilot users first. Ask the implementer to show how bridge and bot devices will be excluded or given overrides, and how the team will watch for support tickets after the change. Plan a rollback path, but note that Synapse database changes can make some rollbacks difficult, so test restores in staging.

What should we ask for in a written scope for this work?

Ask for a scope that names the Synapse and MAS versions in use, the policy values agreed for inactivity and device removal, the admin API procedures, the test cases for encryption and bridges, and the monitoring and rollback steps. Request a list of deliverables such as configuration changes, runbooks and a short report for your security team. Also ask what is excluded, for example key backup redesign or client changes, and who signs off each stage. Confirm the upgrade path with your team, since platform floors can affect what is possible on your current database and Python versions.

How DeployOpen scopes and supports device pruning

DeployOpen scopes device pruning as a fixed-scope engagement agreed in writing before work starts. The scope usually moves through four stages: an inventory of the current homeserver, a written retention policy, testing on a non-production Synapse server, and a controlled rollout to production. The inventory records how many devices and sessions exist per user, which clients are in use (including bridges and bots that hold their own device sessions), how the server is deployed, and whether logins go through Synapse directly or through Matrix Authentication Service. Where the homeserver is run through the Element Server Suite, the scope also needs to say which component owns each session. The written scope should name the staging environment, the test accounts, the rollback owner and the people who approve the production change.

Policy design sets the inactivity window and the exceptions. Each organization has to decide how long an unused device may stay logged in, whether service accounts and bridge devices are exempt, and how users are told before a session disappears. DeployOpen tests the chosen delete_stale_devices_after value and the admin device APIs on the staging server, including the effect on users who return after a long absence and on encrypted rooms where a device's keys are no longer available. Ask the provider to show the test cases, the observed behavior for each client you use, and the exact rollback steps for Synapse versions you run. Because the upgrade notes warn that rolling back can be difficult after schema changes, rollback should be planned as a restore from backup, not as a setting change.

Ongoing checks are available as retainers, covering periodic review of device counts, policy drift after upgrades and retesting after client changes. DeployOpen prepares the controls, configuration records, test results and change records that your compliance or security team can review during an internal or external assessment. DeployOpen does not issue audit reports, attestations or certifications. Independent auditors and certification bodies make those determinations, so your scope should state which evidence you need and which assessor will receive it. Confirm during quoting who owns the policy after handover, how often the inventory is refreshed, and what evidence format the assessor accepts.

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.