:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(postgres): retry connection-limit errors in-process on connect (#64631)
Tom Owerse8a58ed95fe6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.pyindex 92bfe41dcb9e..87731a875587 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py@@ -198,6 +198,22 @@ _CONNECTION_DROPPED_ERROR_SUBSTRINGS = (# XX000 internal errors (data corruption, etc.) carry a different code and stay non-recoverable._POOLER_CONNECTION_DROPPED_ERROR_SUBSTRINGS = ("edbhandlerexited",)+# Connect-time capacity errors: the source refuses a *new* connection because it has hit a+# connection limit, not because anything is misconfigured. PostgreSQL raises "sorry, too many+# clients already" once max_connections is reached, "remaining connection slots are reserved for+# roles with the SUPERUSER attribute" once only the superuser_reserved_connections slots remain,+# and "too many connections for role" once a role's own CONNECTION LIMIT is hit. All three are+# transient capacity conditions on the customer's database — a slot frees the moment another+# connection closes — so a fresh connect after a short backoff usually succeeds. Retried in-process+# on the read/sync connect path (see `_is_dropped_or_connect_timeout` / `_connect_with_dropped_retry`);+# kept retryable and intentionally NOT added to `get_non_retryable_errors` for the same reason as+# pooler saturation (see source.py).+_CONNECTION_LIMIT_ERROR_SUBSTRINGS = (+ "sorry, too many clients already",+ "remaining connection slots are reserved",+ "too many connections for role",+)+# Exception types that can carry a connection-dropped error. ProtocolViolation is# PgBouncer's synthetic error packet; OperationalError is libpq detecting the dead# socket. IdleInTransactionSessionTimeout (SQLSTATE 25P03) is what Postgres raises@@ -256,19 +272,38 @@ def _is_connection_dropped_error(error: BaseException) -> bool:return False+def _is_connection_limit_error(error: BaseException) -> bool:+ """True if the source refused a new connection because it's at a connection limit.++ Distinct from `_is_connection_dropped_error`: the connection was never established, so this is+ only meaningful on the connect path (`_connect_with_dropped_retry`), not for mid-stream fetch+ failures on an already-open connection.+ """+ if not isinstance(error, psycopg.OperationalError):+ return False+ message = " ".join(str(arg) for arg in error.args).lower()+ return any(substring in message for substring in _CONNECTION_LIMIT_ERROR_SUBSTRINGS)++def _is_dropped_or_connect_timeout(error: BaseException) -> bool:"""Transient connect-path failures the import/read reconnect recovers from in process.- Either a mid-stream drop (`_is_connection_dropped_error`) or a connect-time timeout. psycopg- raises `ConnectionTimeout` ("connection timeout expired") only while *establishing* a connection,- never mid-query, so on the import/read path it's transient: the source was reachable moments- earlier in the same sync, and the reconnect just needs retrying. Used by the read/sync connect- retry (`_connect_with_dropped_retry`) and the `offset_chunking` reconnect. The user-facing- validation path (`get_schemas`, via `_retry_on_connection_dropped` directly) deliberately keeps- failing fast on the same timeout, where it usually means an unreachable host / unconfigured- firewall (see `PostgresErrors` and `get_non_retryable_errors`).+ A mid-stream drop (`_is_connection_dropped_error`), a connect-time timeout, or a connect-time+ connection-limit refusal (`_is_connection_limit_error`). psycopg raises `ConnectionTimeout`+ ("connection timeout expired") only while *establishing* a connection, never mid-query, so on the+ import/read path it's transient: the source was reachable moments earlier in the same sync, and+ the reconnect just needs retrying. Connection-limit refusals ("sorry, too many clients already",+ etc.) are likewise transient — a slot frees the moment another connection closes. Used by the+ read/sync connect retry (`_connect_with_dropped_retry`) and the `offset_chunking` reconnect. The+ user-facing validation path (`get_schemas`, via `_retry_on_connection_dropped` directly)+ deliberately keeps failing fast on the same connect-time conditions, where a timeout usually means+ an unreachable host / unconfigured firewall (see `PostgresErrors` and `get_non_retryable_errors`)."""- return _is_connection_dropped_error(error) or isinstance(error, psycopg.errors.ConnectionTimeout)+ return (+ _is_connection_dropped_error(error)+ or _is_connection_limit_error(error)+ or isinstance(error, psycopg.errors.ConnectionTimeout)+ )def _raise_if_setup_connection_broken(connection: psycopg.Connection) -> None:@@ -305,8 +340,9 @@ def _retry_on_connection_dropped(`is_retryable` decides which errors are transient; it defaults to `_is_connection_dropped_error`(mid-stream drops only). The read/sync connect path widens it to also retry connect-time timeouts- (see `_connect_with_dropped_retry`). Permanent errors (auth failures, SSL-required) are re-raised- immediately because neither predicate matches them.+ and connection-limit refusals (see `_connect_with_dropped_retry` / `_is_dropped_or_connect_timeout`).+ Permanent errors (auth failures, SSL-required) are re-raised immediately because no predicate+ matches them."""attempt = 0while True:@@ -333,10 +369,11 @@ def _connect_with_dropped_retry(The streaming recovery path (offset chunking) is reached precisely because thesource just dropped our connection (idle cull, failover, mid-stream SSL EOF), sothe very reconnect that bootstraps the recovery can itself hit a still-recovering- source and fail with another connection-dropped error — or time out establishing the- socket. Without this, that transient failure escapes the recovery loop and fails the- whole sync. Retry both transient classes with bounded backoff; permanent errors (auth- failures, SSL-required) are re-raised immediately because neither predicate matches them.+ source and fail with another connection-dropped error — time out establishing the+ socket, or refuse the reconnect with a connection-limit error while still saturated.+ Without this, that transient failure escapes the recovery loop and fails the whole sync.+ Retry all transient classes with bounded backoff; permanent errors (auth failures,+ SSL-required) are re-raised immediately because no transient predicate matches them."""return _retry_on_connection_dropped(connect, logger, max_attempts=max_attempts, is_retryable=_is_dropped_or_connect_timeoutdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.pyindex d3b3fc0ad175..3326286afec2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py@@ -85,6 +85,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p_get_table_chunk_size,_has_duplicate_primary_keys,_is_connection_dropped_error,+ _is_connection_limit_error,_is_dropped_or_connect_timeout,_is_invalid_ssl_negotiation_response,_is_options_startup_param_unsupported,@@ -293,6 +294,10 @@ class TestPostgresSourceNonRetryableErrors:'OperationalError: connection failed: connection to server at "44.216.29.125", port 5432 failed: FATAL: (EMAXCONNSESSION) max clients reached in session mode - max clients are limited to pool_size: 15','OperationalError: connection failed: connection to server at "10.0.0.1", port 5432 failed: FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute','OperationalError: connection failed: connection to server at "10.0.0.1", port 5432 failed: FATAL: too many connections for role "user"',+ # Server-wide max_connections reached. Transient capacity on the customer's DB — a slot+ # frees as soon as another connection closes — so it's retried in-process on connect and+ # must stay out of NonRetryableErrors.+ 'OperationalError: connection failed: connection to server at "142.93.153.201", port 25060 failed: FATAL: sorry, too many clients already',# Mid-stream SSL/connection drops during schema discovery — the pooler culled an idle# connection or the socket died. A fresh attempt reconnects, so these must stay retryable."consuming input failed: SSL connection has been closed unexpectedly",@@ -1009,6 +1014,43 @@ class TestDroppedOrConnectTimeout:assert _is_dropped_or_connect_timeout(error) is False+class TestIsConnectionLimitError:+ @pytest.mark.parametrize(+ "error",+ [+ psycopg.OperationalError(+ 'connection failed: connection to server at "10.0.0.1", port 5432 failed: '+ "FATAL: sorry, too many clients already"+ ),+ psycopg.OperationalError(+ 'connection failed: connection to server at "10.0.0.1", port 5432 failed: '+ "FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute"+ ),+ psycopg.OperationalError(+ 'connection failed: connection to server at "10.0.0.1", port 5432 failed: '+ 'FATAL: too many connections for role "reader"'+ ),+ ],+ )+ def test_connection_limit_errors_are_detected(self, error):+ assert _is_connection_limit_error(error) is True++ @pytest.mark.parametrize(+ "error",+ [+ # A connection that was established then dropped is a different class — not a limit.+ psycopg.OperationalError("server closed the connection unexpectedly"),+ psycopg.OperationalError(+ 'connection to server at "10.0.0.1" failed: FATAL: password authentication failed'+ ),+ psycopg.errors.QueryCanceled("statement timeout"),+ ValueError("sorry, too many clients already"),+ ],+ )+ def test_unrelated_errors_are_not_detected(self, error):+ assert _is_connection_limit_error(error) is False++class TestRaiseIfSetupConnectionBroken:"""A connection dropped mid-discovery must surface as a retryable error, not the masked`ProgrammingError: Explicit commit() forbidden within a Transaction context` that psycopg's@@ -1076,6 +1118,31 @@ class TestConnectWithDroppedRetry:assert result is good_connassert connect.call_count == 2+ def test_retries_connection_limit_error_then_succeeds(self, logger):+ good_conn = mock.MagicMock()+ connect = mock.MagicMock(+ side_effect=[+ # The source is momentarily at its connection limit; slots free up by a+ # later attempt, so the reconnect succeeds rather than failing the whole sync.+ # Two consecutive refusals lock in that the loop keeps retrying past one attempt.+ psycopg.OperationalError(+ 'connection failed: connection to server at "10.0.0.1", port 5432 failed: '+ "FATAL: sorry, too many clients already"+ ),+ psycopg.OperationalError(+ 'connection failed: connection to server at "10.0.0.1", port 5432 failed: '+ "FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute"+ ),+ good_conn,+ ]+ )++ with patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.time.sleep"):+ result = _connect_with_dropped_retry(connect, logger, max_attempts=5)++ assert result is good_conn+ assert connect.call_count == 3+def test_permanent_error_is_not_retried(self, logger):connect = mock.MagicMock(side_effect=psycopg.OperationalError(