Skip to content

: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.

fix(data-warehouse): bound in-process retries on Postgres recovery conflicts (#64080)

Daniel RCdbfe641b4e62
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index b99a8ec5910d..3b5d247a1b78 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -87,19 +87,14 @@ SYSTEM_POSTGRES_SCHEMAS = ["information_schema", "pg_catalog", "pg_toast"]
# default statement_timeout on the source role.
SYNC_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 mins
-# Statement timeout scoped to the schema-discovery metadata query in `_get_table`.
-# `information_schema.columns` computes `numeric_precision`/`numeric_scale` via the per-column
-# `_pg_numeric_*` SQL functions, which can be slow on large catalogs. The setup connection has no
-# statement_timeout we control until `postgres_source` sets one *after* `_get_table` returns, so
-# the query would otherwise inherit whatever (possibly very short) default the source role/server
-# imposes and get cancelled mid-discovery. Scope a generous-but-bounded budget so a too-short
-# default can't kill it.
METADATA_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 mins
-# How many times the metadata-gathering phase reconnects and retries when a hot-standby
-# recovery conflict terminates the setup connection. Past this the conflict is treated as
-# sustained and surfaced as the non-retryable "successive SerializationFailure errors" abort.
+# In-process retries for a recovery conflict before the abort (non-retryable, see source.py). The
+# read path counts these only once the chunk has shrunk to the floor.
_MAX_SETUP_RECOVERY_CONFLICT_RETRIES = 10
+_MAX_READ_RECOVERY_CONFLICT_RETRIES = 10
+# A shorter query holds its snapshot for less time, lowering the odds the replica cancels it.
+_MIN_RECOVERY_CONFLICT_CHUNK_SIZE = 100
# Bounded in-process retries for a transient connection drop hit *during* the setup metadata
# probes (not just the initial connect). Mirrors `_connect_with_dropped_retry`'s default; past
@@ -280,6 +275,23 @@ def _connect_with_dropped_retry(
time.sleep(min(2 * attempt, 30))
+def _next_recovery_conflict_chunk_size(chunk_size: int, successive_errors: int) -> int:
+ # Only shrink on a sustained conflict — successive_errors resets on a yielded chunk.
+ if successive_errors >= 5 and chunk_size > _MIN_RECOVERY_CONFLICT_CHUNK_SIZE:
+ return max(int(chunk_size / 1.5), _MIN_RECOVERY_CONFLICT_CHUNK_SIZE)
+ return chunk_size
+
+
+def _recovery_conflict_abort_error(retries: int) -> Exception:
+ # Non-retryable (see source.py): once in-process retries are exhausted the conflict is sustained,
+ # and a whole-activity retry just re-reads from offset 0 into the same wall.
+ return Exception(
+ f"Read replica kept canceling reads due to conflict with recovery after {retries} retries. "
+ f"Increase max_standby_streaming_delay or enable hot_standby_feedback on the replica, or sync "
+ f"from the primary database instead of the read replica."
+ )
+
+
def _statement_timeout_as_non_retryable(
error: BaseException,
*,
@@ -2380,9 +2392,7 @@ def postgres_source(
_safe_close_connection(connection)
setup_recovery_conflicts += 1
if setup_recovery_conflicts >= _MAX_SETUP_RECOVERY_CONFLICT_RETRIES:
- raise Exception(
- f"Hit {setup_recovery_conflicts} successive SerializationFailure errors. Aborting."
- ) from e
+ raise _recovery_conflict_abort_error(setup_recovery_conflicts) from e
logger.debug(
f"SerializationFailure during table setup ({e}). Reconnecting and retrying "
f"(attempt {setup_recovery_conflicts}/{_MAX_SETUP_RECOVERY_CONFLICT_RETRIES})"
@@ -2501,6 +2511,7 @@ def postgres_source(
successive_errors = 0
successive_conn_errors = 0
+ floor_retries = 0
connection = _connect_with_dropped_retry(get_connection, logger)
# Autocommit so each LIMIT/OFFSET query runs as its own statement
# and no transaction stays open across the slow delta-merge that
@@ -2542,28 +2553,27 @@ def postgres_source(
successive_errors = 0
successive_conn_errors = 0
+ floor_retries = 0
except psycopg.errors.SerializationFailure as e:
if "due to conflict with recovery" not in "".join(e.args):
raise
- # This error happens when the read replica is out of sync with the primary
logger.debug(f"SerializationFailure error: {e}. Retrying chunk at offset {offset}")
successive_errors += 1
- if successive_errors >= 30:
- # The connection should be closed here, but want to double check to make sure
- _safe_close_connection(connection)
-
- raise Exception(
- f"Hit {successive_errors} successive SerializationFailure errors. Aborting."
- ) from e
- elif successive_errors >= 5:
- chunk_size = max(int(chunk_size / 1.5), 100)
+ # Shrink toward the floor first; only once stuck at the floor do we count down to
+ # the abort.
+ reduced_chunk_size = _next_recovery_conflict_chunk_size(chunk_size, successive_errors)
+ if reduced_chunk_size < chunk_size:
+ chunk_size = reduced_chunk_size
logger.debug(f"Reducing chunk size to {chunk_size} to reduce load on read replica")
- time.sleep(2 * successive_errors)
- else:
- # Linear backoff on successive errors to make sure we give the read replica time to catch up
- time.sleep(2 * successive_errors)
+ floor_retries = 0
+ elif chunk_size <= _MIN_RECOVERY_CONFLICT_CHUNK_SIZE:
+ floor_retries += 1
+ if floor_retries >= _MAX_READ_RECOVERY_CONFLICT_RETRIES:
+ _safe_close_connection(connection)
+ raise _recovery_conflict_abort_error(floor_retries) from e
+ time.sleep(min(2 * successive_errors, 30))
except psycopg.errors.QueryCanceled as e:
# A chunk hit the 10-min statement_timeout. QueryCanceled
# subclasses OperationalError, so this clause must precede the
diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.py
index 5661b6b030aa..6390232c93b8 100644
--- a/posthog/temporal/data_imports/sources/postgres/source.py
+++ b/posthog/temporal/data_imports/sources/postgres/source.py
@@ -270,15 +270,6 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
"SSLRequiredError": None,
"SSL/TLS connection is required": None,
"Could not establish session to SSH gateway": None,
- # Surfaced by a connection pooler (e.g. PgBouncer) as a psycopg ProtocolViolation when
- # the pooler has *repeatedly* failed to log in to the backend database within its
- # server_login_retry window (full message: "server login has been failing, cached
- # error: <reason> (server_login_retry)"). By the time this is returned the backend is in
- # a sustained failure state — unreachable, refusing connections, or rejecting the
- # pooler's credentials — so it is not a one-off transient blip; retrying the whole sync
- # just hits the same wall. Matches the stable pooler signature; the cached <reason>
- # ("connect timeout", etc.) and the trailing "(server_login_retry)" suffix vary and are
- # excluded.
"server login has been failing": (
"Your database's connection pooler (for example PgBouncer) reported that it has "
'repeatedly failed to connect to the backend database ("server login has been '
@@ -286,28 +277,17 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
"the pooler's credentials for the database are wrong. Check that the database is "
"running and reachable from your pooler, then re-enable the sync."
),
- # Serverless Postgres providers (e.g. Neon) suspend a project's compute once it exhausts
- # the plan's compute-time quota, and the connection attempt fails at handshake with
- # "Your account or project has exceeded the compute time quota. Upgrade your plan to
- # increase limits." The compute stays suspended until the customer upgrades their plan or
- # the quota resets at the next billing period, so retrying the activity just re-hits the
- # same wall. Match the stable provider message and exclude the volatile host/IP/port.
"exceeded the compute time quota": (
"Your database provider has suspended the database because the account or project "
'exceeded its compute-time quota ("exceeded the compute time quota"). PostHog can\'t '
"connect until the database is available again. Upgrade your provider's plan or wait "
"for the quota to reset, then re-enable the sync."
),
- # `offset_chunking` retries a Postgres standby recovery conflict ("canceling statement
- # due to conflict with recovery") 30 times in-process with backoff + chunk-size
- # reduction before raising this. The conflict comes from the customer's read replica
- # applying WAL that removes row versions our long-running read still needs
- # (max_standby_streaming_delay exceeded). Once those in-process retries are exhausted the
- # condition is sustained, not a transient blip — retrying the whole activity just
- # re-reads from offset 0 into the same wall, so stop and surface an actionable message.
- # Matched substring excludes the volatile retry count and is distinct from the
- # connection-dropped abort ("successive connection-dropped errors"), which stays retryable.
- "successive SerializationFailure errors. Aborting.": (
+ # A single recovery conflict ("conflict with recovery") is transient and retried in-process,
+ # so it stays retryable. This abort is only raised once those retries are exhausted — by then
+ # the condition is sustained and a whole-activity retry just re-reads from offset 0 into the
+ # same wall, so it's non-retryable. Substring excludes the volatile retry count.
+ "kept canceling reads due to conflict with recovery": (
"PostHog repeatedly hit Postgres recovery conflicts while reading from your read replica "
'("canceling statement due to conflict with recovery"). This happens when the replica must '
"apply changes from the primary that remove rows the sync is still reading. Increase "
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 5612d5520ac0..29cfe3adee50 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -42,6 +42,7 @@ from posthog.temporal.data_imports.sources.postgres.partitioned_tables import (
from posthog.temporal.data_imports.sources.postgres.postgres import (
_MAX_SETUP_CONNECTION_DROPPED_RETRIES,
_MAX_SETUP_RECOVERY_CONFLICT_RETRIES,
+ _MIN_RECOVERY_CONFLICT_CHUNK_SIZE,
FORCE_UTF8_CLIENT_ENCODING,
METADATA_STATEMENT_TIMEOUT_MS,
SSL_REQUIRED_AFTER_DATE,
@@ -74,8 +75,10 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (
_is_partitioned_table,
_is_read_replica,
_is_unsupported_function_error,
+ _next_recovery_conflict_chunk_size,
_normalize_function_names,
_raise_if_setup_connection_broken,
+ _recovery_conflict_abort_error,
_rls_active_from_conn,
_role_subject_to_rls,
_statement_timeout_as_non_retryable,
@@ -411,17 +414,11 @@ class TestPostgresSourceNonRetryableErrors:
is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())
assert is_non_retryable, f"Non-integer incremental cursor error should be non-retryable: {error_msg}"
- @pytest.mark.parametrize(
- "error_msg",
- [
- "Hit 30 successive SerializationFailure errors. Aborting.",
- "Exception: Hit 30 successive SerializationFailure errors. Aborting.",
- ],
- )
- def test_exhausted_recovery_conflict_retries_are_non_retryable(self, source, error_msg):
+ def test_exhausted_recovery_conflict_retries_are_non_retryable(self, source):
+ error_msg = str(_recovery_conflict_abort_error(10))
non_retryable = source.get_non_retryable_errors()
is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())
- assert is_non_retryable, f"Exhausted recovery-conflict error should be non-retryable: {error_msg}"
+ assert is_non_retryable, f"Exhausted recovery-conflict abort should be non-retryable: {error_msg}"
@pytest.mark.parametrize(
"error_msg",
@@ -545,8 +542,10 @@ class TestPostgresSourceSetupRecoveryConflictRetry:
with pytest.raises(Exception) as exc_info:
self._call_postgres_source()
- # Exhausting the in-process retries surfaces the message wired into NonRetryableErrors.
- assert "successive SerializationFailure errors. Aborting." in str(exc_info.value)
+ message = str(exc_info.value)
+ assert "conflict with recovery" in message and "max_standby_streaming_delay" in message
+ non_retryable = PostgresSource().get_non_retryable_errors()
+ assert any(pattern in message for pattern in non_retryable.keys())
# Each retry reconnects, so connect is called once per attempt.
assert connect_mock.call_count == _MAX_SETUP_RECOVERY_CONFLICT_RETRIES
@@ -772,6 +771,43 @@ class TestConnectWithDroppedRetry:
assert connect.call_count == 3
+class TestNextRecoveryConflictChunkSize:
+ @pytest.mark.parametrize(
+ "chunk_size,successive_errors,expected",
+ [
+ # Grace period — don't shrink on a one-off blip.
+ (20_000, 1, 20_000),
+ (20_000, 4, 20_000),
+ # Sustained conflict → reduce.
+ (20_000, 5, int(20_000 / 1.5)),
+ # Never drops below the floor.
+ (120, 5, _MIN_RECOVERY_CONFLICT_CHUNK_SIZE),
+ (_MIN_RECOVERY_CONFLICT_CHUNK_SIZE, 5, _MIN_RECOVERY_CONFLICT_CHUNK_SIZE),
+ ],
+ )
+ def test_chunk_size_reduction(self, chunk_size, successive_errors, expected):
+ assert _next_recovery_conflict_chunk_size(chunk_size, successive_errors) == expected
+
+ def test_converges_to_floor(self):
+ chunk_size = 20_000
+ for _ in range(50):
+ chunk_size = _next_recovery_conflict_chunk_size(chunk_size, 5)
+ assert chunk_size == _MIN_RECOVERY_CONFLICT_CHUNK_SIZE
+
+
+class TestRecoveryConflictAbortError:
+ def test_message_is_actionable(self):
+ message = str(_recovery_conflict_abort_error(10))
+ assert "conflict with recovery" in message
+ assert "max_standby_streaming_delay" in message
+ assert "hot_standby_feedback" in message
+
+ def test_message_is_non_retryable(self):
+ message = str(_recovery_conflict_abort_error(10))
+ non_retryable = PostgresSource().get_non_retryable_errors()
+ assert any(pattern in message for pattern in non_retryable.keys())
+
+
# Redshift (and other Postgres-wire engines) report `client_encoding` as the legacy alias
# `UNICODE`, which psycopg3 can't decode — it raises `NotSupportedError: codec not available in
# Python: 'UNICODE'`. We pin the client encoding to UTF8 on connect to avoid the crash.