: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(data-warehouse): retry transient DB pool timeout when checking webhook status (#66898)
Tom Owers0f7b6ad1e93e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.pyindex 4f621b493d62..f77d42ab71a5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.py@@ -5,9 +5,10 @@ import functoolsimport contextlibimport pytest-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, call, patchfrom django.conf import settings+from django.db import OperationalErrorfrom django.test import override_settingsimport orjson@@ -16,7 +17,15 @@ import aioboto3import pyarrow.parquet as pqfrom parameterized import parameterized-from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import (+ WebhookSourceManager,+ _db_read_with_retry,+)++_CLOSE_CONNECTIONS_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3.close_old_connections"+)+_SLEEP_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3.time.sleep"def _table_to_parquet_bytes(table: pa.Table) -> bytes:@@ -341,6 +350,47 @@ class TestWebhookSourceManager:assert tables == []+class TestDbReadWithRetry:+ def test_rides_out_pool_wait_timeout_then_succeeds(self):+ sentinel = object()+ fn = MagicMock(+ side_effect=[+ OperationalError("query_wait_timeout"),+ OperationalError("query_wait_timeout"),+ sentinel,+ ]+ )++ with patch(_CLOSE_CONNECTIONS_PATH) as close, patch(_SLEEP_PATH) as sleep:+ result = _db_read_with_retry(fn)++ assert result is sentinel+ assert fn.call_count == 3+ # Connections evicted before every attempt, including the two that failed.+ assert close.call_count == 3+ # Backoff grows per `min(2 * attempt, 30)`: 2s after the 1st failure, 4s after the 2nd.+ assert sleep.call_args_list == [call(2), call(4)]++ def test_reraises_after_exhausting_attempts(self):+ fn = MagicMock(side_effect=OperationalError("query_wait_timeout"))++ with patch(_CLOSE_CONNECTIONS_PATH), patch(_SLEEP_PATH):+ with pytest.raises(OperationalError):+ _db_read_with_retry(fn)++ assert fn.call_count == 4++ def test_non_operational_error_propagates_without_retry(self):+ fn = MagicMock(side_effect=ValueError("not a connection problem"))++ with patch(_CLOSE_CONNECTIONS_PATH), patch(_SLEEP_PATH) as sleep:+ with pytest.raises(ValueError):+ _db_read_with_retry(fn)++ assert fn.call_count == 1+ sleep.assert_not_called()++# -- Integration tests using MinIO --diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.pyindex 086dd6f8ec86..cb6a06e45861 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py@@ -1,9 +1,11 @@from __future__ import annotations+import timefrom collections.abc import AsyncGenerator, Callable-from typing import Optional+from typing import Optional, TypeVarfrom django.conf import settings+from django.db import OperationalError, close_old_connectionsimport orjsonimport pyarrow as pa@@ -17,6 +19,35 @@ from products.data_warehouse.backend.facade.api import aget_s3_clientfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list+T = TypeVar("T")++_MAX_DB_READ_ATTEMPTS = 4+++def _db_read_with_retry(fn: Callable[[], T]) -> T:+ """Run an idempotent main-DB read, retrying a transient connection failure with backoff.++ Temporal activities run in a long-lived worker that never goes through Django's request+ cycle, so a pooled Postgres connection can be closed server-side while it sits idle, or the+ connection pooler can reject the query with a wait timeout when the pool is saturated. Both+ surface as a transient ``OperationalError`` and both clear once a healthy connection is used.+ ``close_old_connections()`` evicts connections already known to be stale (and, after a failed+ query marks one unusable, drops it), so each attempt runs on a fresh connection; the short+ backoff also gives a saturated pool time to drain rather than retrying straight back into the+ same wait timeout. Must run inside the ``database_sync_to_async_pool`` thread so the eviction+ targets the same connection the query uses. ``DoesNotExist`` and other errors propagate.+ """+ attempt = 0+ while True:+ close_old_connections()+ try:+ return fn()+ except OperationalError:+ attempt += 1+ if attempt >= _MAX_DB_READ_ATTEMPTS:+ raise+ time.sleep(min(2 * attempt, 30))+class WebhookSourceManager:_inputs: SourceInputs@@ -36,8 +67,8 @@ class WebhookSourceManager:from products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema- schema = await database_sync_to_async_pool(ExternalDataSchema.objects.get)(- id=self._inputs.schema_id, team_id=self._inputs.team_id+ schema = await database_sync_to_async_pool(_db_read_with_retry)(+ lambda: ExternalDataSchema.objects.get(id=self._inputs.schema_id, team_id=self._inputs.team_id))if (@@ -50,15 +81,15 @@ class WebhookSourceManager:)return False- has_webhook_function = await database_sync_to_async_pool(- HogFunction.objects.filter(+ has_webhook_function = await database_sync_to_async_pool(_db_read_with_retry)(+ lambda: HogFunction.objects.filter(inputs__source_id__value=self._inputs.source_id,team_id=self._inputs.team_id,type="warehouse_source_webhook",enabled=True,deleted=False,- ).exists- )()+ ).exists()+ )return has_webhook_function