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(mysql): retry connect timeouts in-process (#64781)

Tom Owersf21a3fb0f297
diff --git a/posthog/temporal/data_imports/sources/mysql/mysql.py b/posthog/temporal/data_imports/sources/mysql/mysql.py
index 012aca0d7670..2d7ff884e7fd 100644
--- a/posthog/temporal/data_imports/sources/mysql/mysql.py
+++ b/posthog/temporal/data_imports/sources/mysql/mysql.py
@@ -96,6 +96,13 @@ _LOST_CONNECTION_DURING_QUERY_CODE = 2013
# resolves it.
_OUT_OF_SORT_MEMORY_CODE = 1038
+# pymysql error code for "Can't connect to MySQL server on '...'" — raised at
+# connect time when the socket connect can't be established. The parenthesised
+# suffix carries the underlying cause (a timeout vs. a refused connection vs. a
+# failed DNS lookup), which is how we tell a transient timeout apart from a hard
+# config error.
+_CANT_CONNECT_CODE = 2003
+
_SYSTEM_SCHEMAS = ("information_schema", "mysql", "performance_schema", "sys")
@@ -331,13 +338,34 @@ def _is_transient_connect_drop(e: BaseException) -> bool:
return False
+def _is_transient_connect_timeout(e: BaseException) -> bool:
+ """Return True if the initial connect timed out — a transient blip.
+
+ A connect that outruns `connect_timeout` surfaces as pymysql 2003
+ ("Can't connect to MySQL server on '...' (timed out)") wrapping the socket
+ `TimeoutError`. Unlike the other 2003 causes — a refused connection or a
+ failed DNS lookup, both deterministic host/port misconfig that stay
+ non-retryable via the "Can't connect to MySQL server on" classifier — a
+ timeout usually means the server was momentarily slow or unreachable (an
+ overloaded server, a cold PlanetScale endpoint, a brief network blip), so a
+ fresh attempt recovers. Match only the "timed out" payload so the persistent
+ failures still surface.
+ """
+ if not isinstance(e, pymysql.err.OperationalError):
+ return False
+ code = e.args[0] if e.args else None
+ if code != _CANT_CONNECT_CODE:
+ return False
+ return "timed out" in " ".join(str(arg) for arg in e.args)
+
+
def _connect_with_transient_retry(kwargs: dict[str, Any]) -> pymysql.Connection:
- """Open a pymysql connection, retrying a transient drop during the handshake.
+ """Open a pymysql connection, retrying a transient drop or timeout on connect.
Mirrors the in-process connect retry the Postgres source uses: a momentary
- drop while establishing the connection recovers on a fresh attempt, so retry
- it here with a bounded backoff instead of failing schema discovery / sync setup
- on the first blip and surfacing it as captured error-tracking noise.
+ drop or timeout while establishing the connection recovers on a fresh attempt,
+ so retry it here with a bounded backoff instead of failing schema discovery /
+ sync setup on the first blip and surfacing it as captured error-tracking noise.
"""
attempt = 0
while True:
@@ -345,10 +373,12 @@ def _connect_with_transient_retry(kwargs: dict[str, Any]) -> pymysql.Connection:
return pymysql.connect(**kwargs)
except pymysql.err.OperationalError as e:
attempt += 1
- if attempt >= _MAX_CONNECT_ATTEMPTS or not _is_transient_connect_drop(e):
+ if attempt >= _MAX_CONNECT_ATTEMPTS or not (
+ _is_transient_connect_drop(e) or _is_transient_connect_timeout(e)
+ ):
raise
structlog.get_logger().warning(
- "Transient MySQL connection drop during connect; retrying",
+ "Transient MySQL connect error (drop or timeout); retrying",
attempt=attempt,
max_attempts=_MAX_CONNECT_ATTEMPTS,
exc_info=e,
diff --git a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
index 9bddf830f13e..84816b8d6cb1 100644
--- a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
+++ b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
@@ -21,6 +21,7 @@ from posthog.temporal.data_imports.sources.mysql.mysql import (
_build_query,
_is_bad_plan_error,
_is_transient_connect_drop,
+ _is_transient_connect_timeout,
_is_transient_tablet_unavailable,
_release_streaming_cursor,
_retry_on_transient_tablet_unavailable,
@@ -890,6 +891,43 @@ class TestIsTransientConnectDrop:
assert not _is_transient_connect_drop(pymysql.err.OperationalError())
+class TestIsTransientConnectTimeout:
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "Can't connect to MySQL server on 'gcp.connect.psdb.cloud' (timed out)",
+ "Can't connect to MySQL server on 'db.example.com' ([Errno 110] Connection timed out)",
+ ],
+ )
+ def test_matches_connect_timeout(self, message):
+ assert _is_transient_connect_timeout(pymysql.err.OperationalError(2003, message))
+
+ @pytest.mark.parametrize(
+ "message",
+ [
+ # Refused connection and failed DNS lookup are also 2003 but deterministic
+ # host/port misconfig — they must stay non-retryable, not be absorbed here.
+ "Can't connect to MySQL server on 'db.example.com' ([Errno 111] Connection refused)",
+ "Can't connect to MySQL server on 'nope.example.com' ([Errno -2] Name or service not known)",
+ ],
+ )
+ def test_does_not_match_non_timeout_connect_errors(self, message):
+ assert not _is_transient_connect_timeout(pymysql.err.OperationalError(2003, message))
+
+ @pytest.mark.parametrize(
+ "code,message",
+ [
+ (2013, "Lost connection to MySQL server during query"),
+ (1045, "Access denied for user"),
+ ],
+ )
+ def test_does_not_match_other_error_codes(self, code, message):
+ assert not _is_transient_connect_timeout(pymysql.err.OperationalError(code, message))
+
+ def test_does_not_match_error_without_args(self):
+ assert not _is_transient_connect_timeout(pymysql.err.OperationalError())
+
+
class TestConnectTransientRetry:
@pytest.mark.parametrize(
"fail_count,expected_sleeps",
@@ -937,6 +975,40 @@ class TestConnectTransientRetry:
assert mock_connect.call_count == 2
sleep.assert_called_once_with(2)
+ def test_retries_connect_timeout_then_succeeds(self, mocker):
+ sleep = mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql.time.sleep")
+ conn = MagicMock()
+ conn.__enter__.return_value = conn
+ mock_connect = mocker.patch(
+ "posthog.temporal.data_imports.sources.mysql.mysql.pymysql.connect",
+ side_effect=[
+ pymysql.err.OperationalError(2003, "Can't connect to MySQL server on 'host' (timed out)"),
+ conn,
+ ],
+ )
+
+ with MySQLImplementation().connect(_make_config()) as yielded:
+ assert yielded is conn
+
+ assert mock_connect.call_count == 2
+ sleep.assert_called_once_with(2)
+
+ def test_does_not_retry_connection_refused(self, mocker):
+ sleep = mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql.time.sleep")
+ mock_connect = mocker.patch(
+ "posthog.temporal.data_imports.sources.mysql.mysql.pymysql.connect",
+ side_effect=pymysql.err.OperationalError(
+ 2003, "Can't connect to MySQL server on 'host' ([Errno 111] Connection refused)"
+ ),
+ )
+
+ with pytest.raises(pymysql.err.OperationalError):
+ with MySQLImplementation().connect(_make_config()):
+ pass
+
+ assert mock_connect.call_count == 1
+ sleep.assert_not_called()
+
def test_gives_up_after_max_attempts(self, mocker):
mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql.time.sleep")
mock_connect = mocker.patch(