Eric Eastwood ba3ab1876a Optimize mark_as_sent_devices_by_remote to do less CPU work on the database (#20120)
### Background

On `matrix.org`, since 2026-08-15, we are seeing the database CPU being
saturated more than usual
([grafana](https://grafana.matrix.org/d/rYdddlPWk/node-exporter?orgId=1&from=2026-08-10T23:23:14.237Z&to=2026-08-17T23:23:14.237Z&timezone=browser&var-DS_PROMETHEUS=default&var-job=machine&var-node=matrix-db-01.matrix.org:9100&var-diskdevices=%5Ba-z%5D%2B%7Cnvme%5B0-9%5D%2Bn%5B0-9%5D%2B&refresh=1m&viewPanel=panel-77))

<img width="919" height="265" alt="CPU of database server"
src="https://github.com/user-attachments/assets/9a43cf3c-bf9a-4ade-b70e-0bf0fb53f0ef"
/>


@reivilibre
[found](https://matrix.to/#/!yHWhpxlXVaLcsgDUKb:matrix.org/$fUMf60IbFocpEuJNbmbEzFiCyKCFnAl4I4XpB27DUQs?via=banzan.uk&via=element.io&via=matrix.org)
`mark_as_sent_devices_by_remote` spiking in the `DB transactions by
total txn time` graph
([grafana](https://grafana.matrix.org/d/000000012/synapse?var-bucket_size=$__auto&orgId=1&from=2026-08-10T22:26:07.336Z&to=2026-08-17T22:26:07.336Z&timezone=browser&var-datasource=default&var-instance=matrix.org&var-job=synapse_federation_sender&var-index=$__all&showCategory=Thresholds&viewPanel=panel-11))

<img width="919" height="269" alt="'mark_as_sent_devices_by_remote'
spiking in the 'DB transactions by total txn time' graph"
src="https://github.com/user-attachments/assets/9336ce29-c045-4940-9c46-9e4906300f2d"
/>

And we indeed see a bunch of time being spent on
`mark_as_sent_devices_by_remote` by looking at `pg_stat_statements`. The
top two queries we're spending CPU on are the `SELECT` and `DELETE`
statements in
[`mark_as_sent_devices_by_remote`](https://github.com/element-hq/synapse/blob/94a5f2afb36a4afdc36813fd1c24b9a1c4aec252/synapse/storage/databases/main/devices.py#L922-L950).


We also did some related work in this area recently with
https://github.com/element-hq/synapse/pull/20098 although it was
tackling a different bottle-neck.


### This PR

This PRs combines the two separate `SELECT` and `DELETE` queries which
touch the same data into one `DELETE ... RETURNING ...` query. this
means we get to save the cost of one of those statements (less CPU on
the database) and fewer statements per transaction (less round-trips)
means connections turn over faster, and can move on to process the next
thing.

This is a micro-optimization I spotted while reading
[`_mark_as_sent_devices_by_remote_txn`](https://github.com/element-hq/synapse/blob/develop/synapse/storage/databases/main/devices.py#L922-L950)
rather than a structural fix. I'm sure there are even better things to
do to where we could even avoid this kind of work altogether but this
seemed like a quick win especially given how much this particular
transaction is saturating the database.

Doing things faster doesn't necessarily mean we solve the
saturated/starved CPU problem but it does mean the same task costs less
CPU.

From the `pg_stat_statements` samples above, we can expect to be up to
~27% more efficient with database CPU on this code path (derived from
the `cpus_busy` numbers above `22.932 / (22.932 + 61.956)`). We're
removing the `SELECT` (`61.956` `cpus_busy`) but I still expect the
`DELETE` (`22.932` `cpus_busy`) to take on a similar cost as I'm sure
it's a warm cache situation between them.
2026-08-18 09:27:50 +01:00
2026-08-11 11:25:53 -05:00
2024-11-20 15:01:56 +00:00
2023-12-13 16:15:22 +00:00
2026-08-11 11:25:53 -05:00
2023-12-13 16:15:22 +00:00

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
.. image:: https://github.com/element-hq/synapse/raw/develop/docs/element_logo_white_bg.svg
   :height: 60px

**Element Synapse - Matrix homeserver implementation**

|support| |development| |documentation| |license| |pypi| |python|

Synapse is an open source `Matrix <https://matrix.org>`__ homeserver
implementation, written and maintained by `Element <https://element.io>`_.
`Matrix <https://github.com/matrix-org>`__ is the open standard for secure and
interoperable real-time communications. You can directly run and manage the
source code in this repository, available under an AGPL license (or
alternatively under a commercial license from Element).

There is no support provided by Element unless you have a subscription from
Element.

🚀 Getting started
==================

This component is developed and maintained by `Element <https://element.io>`_.
It gets shipped as part of the **Element Server Suite (ESS)** which provides the
official means of deployment.

ESS is a Matrix distribution from Element with focus on quality and ease of use.
It ships a full Matrix stack tailored to the respective use case.

There are three editions of ESS:

- `ESS Community <https://github.com/element-hq/ess-helm>`_ - the free Matrix
  distribution from Element tailored to small-/mid-scale, non-commercial
  community use cases
- `ESS Pro <https://element.io/server-suite>`_ - the commercial Matrix
  distribution from Element for professional use
- `ESS TI-M <https://element.io/server-suite/ti-messenger>`_ - a special version
  of ESS Pro focused on the requirements of TI-Messenger Pro and ePA as
  specified by the German National Digital Health Agency Gematik


🛠️ Standalone installation and configuration
============================================

The Synapse documentation describes `options for installing Synapse standalone
<https://element-hq.github.io/synapse/latest/setup/installation.html>`_. See
below for more useful documentation links.

- `Synapse configuration options <https://element-hq.github.io/synapse/latest/usage/configuration/config_documentation.html>`_
- `Synapse configuration for federation <https://element-hq.github.io/synapse/latest/federate.html>`_
- `Using a reverse proxy with Synapse <https://element-hq.github.io/synapse/latest/reverse_proxy.html>`_
- `Upgrading Synapse <https://element-hq.github.io/synapse/develop/upgrade.html>`_


🎯 Troubleshooting and support
==============================

🚀 Professional support
-----------------------

Enterprise quality support for Synapse including SLAs is available as part of an
`Element Server Suite (ESS) <https://element.io/pricing>`_ subscription.

If you are an existing ESS subscriber then you can raise a `support request <https://ems.element.io/support>`_
and access the `Element product documentation <https://docs.element.io>`_.

🤝 Community support
--------------------

The `Admin FAQ <https://element-hq.github.io/synapse/latest/usage/administration/admin_faq.html>`_
includes tips on dealing with some common problems. For more details, see
`Synapse's wider documentation <https://element-hq.github.io/synapse/latest/>`_.

For additional support installing or managing Synapse, please ask in the community
support room |room|_ (from a matrix.org account if necessary). We do not use GitHub
issues for support requests, only for bug reports and feature requests.

.. |room| replace:: ``#synapse:matrix.org``
.. _room: https://matrix.to/#/#synapse:matrix.org

.. |docs| replace:: ``docs``
.. _docs: docs


🛠️ Development
==============

We welcome contributions to Synapse from the community!
The best place to get started is our
`guide for contributors <https://element-hq.github.io/synapse/latest/development/contributing_guide.html>`_.
This is part of our broader `documentation <https://element-hq.github.io/synapse/latest>`_, which includes
information for Synapse developers as well as Synapse administrators.

Developers might be particularly interested in:

* `Synapse's database schema <https://element-hq.github.io/synapse/latest/development/database_schema.html>`_,
* `notes on Synapse's implementation details <https://element-hq.github.io/synapse/latest/development/internal_documentation/index.html>`_, and
* `how we use git <https://element-hq.github.io/synapse/latest/development/git.html>`_.

Alongside all that, join our developer community on Matrix:
`#synapse-dev:matrix.org <https://matrix.to/#/#synapse-dev:matrix.org>`_, featuring real humans!

Copyright and Licensing
=======================

  | Copyright 20142017 OpenMarket Ltd
  | Copyright 2017 Vector Creations Ltd
  | Copyright 20172025 New Vector Ltd
  | Copyright 2025 Element Creations Ltd

This software is dual-licensed by Element Creations Ltd (Element). It can be
used either:

(1) for free under the terms of the GNU Affero General Public License (as
    published by the Free Software Foundation, either version 3 of the License,
    or (at your option) any later version); OR

(2) under the terms of a paid-for Element Commercial License agreement between
    you and Element (the terms of which may vary depending on what you and
    Element have agreed to).

Unless required by applicable law or agreed to in writing, software distributed
under the Licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the Licenses for the
specific language governing permissions and limitations under the Licenses.

Please contact `licensing@element.io <mailto:licensing@element.io>`_ to purchase
an Element commercial license for this software.


.. |support| image:: https://img.shields.io/badge/matrix-community%20support-success
  :alt: (get community support in #synapse:matrix.org)
  :target: https://matrix.to/#/#synapse:matrix.org

.. |development| image:: https://img.shields.io/matrix/synapse-dev:matrix.org?label=development&logo=matrix
  :alt: (discuss development on #synapse-dev:matrix.org)
  :target: https://matrix.to/#/#synapse-dev:matrix.org

.. |documentation| image:: https://img.shields.io/badge/documentation-%E2%9C%93-success
  :alt: (Rendered documentation on GitHub Pages)
  :target: https://element-hq.github.io/synapse/latest/

.. |license| image:: https://img.shields.io/github/license/element-hq/synapse
  :alt: (check license in LICENSE file)
  :target: LICENSE

.. |pypi| image:: https://img.shields.io/pypi/v/matrix-synapse
  :alt: (latest version released on PyPi)
  :target: https://pypi.org/project/matrix-synapse

.. |python| image:: https://img.shields.io/pypi/pyversions/matrix-synapse
  :alt: (supported python versions)
  :target: https://pypi.org/project/matrix-synapse
S
Description
No description provided
Readme
605 MiB
Languages
Python 95.6%
Rust 2.9%
HTML 0.4%
Shell 0.4%
Go 0.2%
Other 0.2%