Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 53aa26e

Browse files
authored
Add a timeout that aborts any Postgres statement taking more than 1 hour. (#15853)
* Add a timeout to Postgres statements * Newsfile Signed-off-by: Olivier Wilkinson (reivilibre) <oliverw@matrix.org> --------- Signed-off-by: Olivier Wilkinson (reivilibre) <oliverw@matrix.org>
1 parent a587de9 commit 53aa26e

2 files changed

Lines changed: 14 additions & 0 deletions

File tree

changelog.d/15853.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add a timeout that aborts any Postgres statement taking more than 1 hour.

synapse/storage/engines/postgres.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,15 @@ def _disable_bytes_adapter(_: bytes) -> NoReturn:
4545

4646
psycopg2.extensions.register_adapter(bytes, _disable_bytes_adapter)
4747
self.synchronous_commit: bool = database_config.get("synchronous_commit", True)
48+
# Set the statement timeout to 1 hour by default.
49+
# Any query taking more than 1 hour should probably be considered a bug;
50+
# most of the time this is a sign that work needs to be split up or that
51+
# some degenerate query plan has been created and the client has probably
52+
# timed out/walked off anyway.
53+
# This is in milliseconds.
54+
self.statement_timeout: Optional[int] = database_config.get(
55+
"statement_timeout", 60 * 60 * 1000
56+
)
4857
self._version: Optional[int] = None # unknown as yet
4958

5059
self.isolation_level_map: Mapping[int, int] = {
@@ -157,6 +166,10 @@ def on_new_connection(self, db_conn: "LoggingDatabaseConnection") -> None:
157166
if not self.synchronous_commit:
158167
cursor.execute("SET synchronous_commit TO OFF")
159168

169+
# Abort really long-running statements and turn them into errors.
170+
if self.statement_timeout is not None:
171+
cursor.execute("SET statement_timeout TO ?", (self.statement_timeout,))
172+
160173
cursor.close()
161174
db_conn.commit()
162175

0 commit comments

Comments
 (0)