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

Add a timeout that aborts any Postgres statement taking more than 1 hour. #15853

Merged
merged 2 commits into from
Jul 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/15853.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add a timeout that aborts any Postgres statement taking more than 1 hour.
13 changes: 13 additions & 0 deletions synapse/storage/engines/postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ def _disable_bytes_adapter(_: bytes) -> NoReturn:

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

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

# Abort really long-running statements and turn them into errors.
if self.statement_timeout is not None:
cursor.execute("SET statement_timeout TO ?", (self.statement_timeout,))

cursor.close()
db_conn.commit()

Expand Down