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-imports): retry writes hitting a stale connection after failover (#88295)

Tom Owersf7d0959ff1ec
diff --git a/posthog/temporal/common/utils.py b/posthog/temporal/common/utils.py
index ef13350b5930..733d40177b0c 100644
--- a/posthog/temporal/common/utils.py
+++ b/posthog/temporal/common/utils.py
@@ -157,16 +157,30 @@ def close_db_connections(fn: Callable[P, T]) -> Callable[P, T]:
return sync_wrapper
+def _is_stale_connection_read_only_error(error: Exception) -> bool:
+ """Whether `error` is a write rejected because the connection outlived a primary failover.
+
+ A connection held open across a Postgres failover/switchover keeps talking to what is now a
+ demoted standby (or a pooler backend still routed there mid-cutover), so any write on it fails
+ with ``cannot execute ... in a read-only transaction`` (``psycopg.errors.ReadOnlySqlTransaction``,
+ surfaced by Django as ``InternalError``). This is the same stale-pooled-connection failure mode
+ ``OperationalError``/``InterfaceError`` already cover, just a different DB-API exception class —
+ closing the connection and retrying reconnects to the current primary.
+ """
+ return isinstance(error, django.db.InternalError) and "read-only transaction" in str(error).lower()
+
+
async def aretry_on_db_connection_drop(operation: Callable[[], Coroutine[Any, Any, T]]) -> T:
- """Run an async DB read, retrying once on a transient connection drop.
+ """Run an async DB operation, retrying once on a transient connection drop.
Long-lived Temporal workers pool their connections through pgbouncer, so a pool
recycle, failover, or deploy can leave a stale pooled connection that raises
- ``OperationalError`` / ``InterfaceError`` the first time it's used. Evict the dead
- connection and retry once, so a transient blip at an activity's early connect-time
- reads succeeds on a fresh connection instead of escaping as error-tracking noise.
- A second failure propagates — that's a genuinely degraded DB, left to the caller's
- retry posture.
+ ``OperationalError`` / ``InterfaceError`` the first time it's used — or, for a write,
+ ``InternalError`` if the stale connection now points at a demoted standby (see
+ ``_is_stale_connection_read_only_error``). Evict the dead connection and retry once, so a
+ transient blip at an activity's early connect-time reads succeeds on a fresh connection
+ instead of escaping as error-tracking noise. A second failure propagates — that's a
+ genuinely degraded DB, left to the caller's retry posture.
Pass a zero-arg callable that *produces* the awaitable (not the awaitable itself),
so the retry can issue a fresh query:
@@ -175,20 +189,27 @@ async def aretry_on_db_connection_drop(operation: Callable[[], Coroutine[Any, An
"""
try:
return await operation()
+ except django.db.InternalError as e:
+ if not _is_stale_connection_read_only_error(e):
+ raise
+ await sync_to_async(_close_db_connections)()
+ return await operation()
except (django.db.OperationalError, django.db.InterfaceError):
await sync_to_async(_close_db_connections)()
return await operation()
def retry_on_db_connection_drop(operation: Callable[[], T]) -> T:
- """Run a sync DB read, retrying once on a transient connection drop.
+ """Run a sync DB operation, retrying once on a transient connection drop.
The sync sibling of ``aretry_on_db_connection_drop``, for activities that run sync
Django ORM code (e.g. under ``@asyncify``). See that function for the full rationale:
a long-lived worker pools connections through pgbouncer, so a pool recycle / failover
/ deploy can leave a stale pooled connection that raises ``OperationalError`` /
- ``InterfaceError`` on first use. Evict the dead connection and retry once; a second
- failure propagates, left to the caller's retry posture.
+ ``InterfaceError`` on first use — or, for a write, ``InternalError`` if the stale
+ connection now points at a demoted standby (see ``_is_stale_connection_read_only_error``).
+ Evict the dead connection and retry once; a second failure propagates, left to the
+ caller's retry posture.
The single retry leans on the activity's outer Temporal retry policy. Code without
one (e.g. a Celery task) needs multi-attempt backoff instead; see
@@ -201,6 +222,11 @@ def retry_on_db_connection_drop(operation: Callable[[], T]) -> T:
"""
try:
return operation()
+ except django.db.InternalError as e:
+ if not _is_stale_connection_read_only_error(e):
+ raise
+ _close_db_connections()
+ return operation()
except (django.db.OperationalError, django.db.InterfaceError):
_close_db_connections()
return operation()
diff --git a/posthog/temporal/tests/common/test_utils.py b/posthog/temporal/tests/common/test_utils.py
index c0758fbb59bd..9e01d56f7072 100644
--- a/posthog/temporal/tests/common/test_utils.py
+++ b/posthog/temporal/tests/common/test_utils.py
@@ -3,7 +3,7 @@ import inspect
import pytest
from unittest.mock import patch
-from django.db import InterfaceError, OperationalError
+from django.db import InterfaceError, InternalError, OperationalError
from posthog.temporal.common.utils import (
close_db_connections,
@@ -201,7 +201,12 @@ CLOSE_DB_CONNECTIONS_TARGET = "posthog.temporal.common.utils._close_db_connectio
@pytest.mark.parametrize(
- "error", [OperationalError("the connection is closed"), InterfaceError("connection already closed")]
+ "error",
+ [
+ OperationalError("the connection is closed"),
+ InterfaceError("connection already closed"),
+ InternalError("cannot execute UPDATE in a read-only transaction"),
+ ],
)
def test_retry_on_db_connection_drop_retries_once_then_succeeds(error):
calls = 0
@@ -221,7 +226,12 @@ def test_retry_on_db_connection_drop_retries_once_then_succeeds(error):
@pytest.mark.parametrize(
- "error", [OperationalError("the connection is closed"), InterfaceError("connection already closed")]
+ "error",
+ [
+ OperationalError("the connection is closed"),
+ InterfaceError("connection already closed"),
+ InternalError("cannot execute UPDATE in a read-only transaction"),
+ ],
)
def test_retry_on_db_connection_drop_raises_after_second_failure(error):
calls = 0
@@ -249,3 +259,17 @@ def test_retry_on_db_connection_drop_does_not_retry_unrelated_errors():
retry_on_db_connection_drop(operation)
assert calls == 1
+
+
+def test_retry_on_db_connection_drop_does_not_retry_unrelated_internal_errors():
+ calls = 0
+
+ def operation():
+ nonlocal calls
+ calls += 1
+ raise InternalError("current transaction is aborted, commands ignored until end of transaction block")
+
+ with pytest.raises(InternalError):
+ retry_on_db_connection_drop(operation)
+
+ assert calls == 1