Skip to content

Commit

Permalink
Speed up e2e device keys queries for bot accounts (#16841)
Browse files Browse the repository at this point in the history
This helps with bot accounts with lots of non-e2e devices.

The change is basically to change the order of the join for the case of
using `INNER JOIN`
  • Loading branch information
erikjohnston authored Jan 23, 2024
1 parent 23740ea commit c925b45
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
1 change: 1 addition & 0 deletions changelog.d/16841.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Speed up e2e device keys queries for bot accounts.
29 changes: 18 additions & 11 deletions synapse/storage/databases/main/end_to_end_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,17 +408,24 @@ async def _get_e2e_device_keys(
def get_e2e_device_keys_txn(
txn: LoggingTransaction, query_clause: str, query_params: list
) -> None:
sql = (
"SELECT user_id, device_id, "
" d.display_name, "
" k.key_json"
" FROM devices d"
" %s JOIN e2e_device_keys_json k USING (user_id, device_id)"
" WHERE %s AND NOT d.hidden"
) % (
"LEFT" if include_all_devices else "INNER",
query_clause,
)
if include_all_devices:
sql = f"""
SELECT user_id, device_id, d.display_name, k.key_json
FROM devices d
LEFT JOIN e2e_device_keys_json k USING (user_id, device_id)
WHERE {query_clause} AND NOT d.hidden
"""
else:
# We swap around `e2e_device_keys_json` and `devices`, as we
# want Postgres to query `e2e_device_keys_json` first as it will
# have fewer rows in it. This helps *a lot* with accounts with
# lots of non-e2e devices (such as bots).
sql = f"""
SELECT user_id, device_id, d.display_name, k.key_json
FROM e2e_device_keys_json k
INNER JOIN devices d USING (user_id, device_id)
WHERE {query_clause} AND NOT d.hidden
"""

txn.execute(sql, query_params)

Expand Down

0 comments on commit c925b45

Please sign in to comment.