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(warehouse_sources): retry resumable state writes after a Redis failover (#96397)

Tom Owersc6ebc3da16b5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
index a97c8cefba4a..32cd3d5472ee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
@@ -1,14 +1,14 @@
import json
import dataclasses
-from collections.abc import Callable
+import collections.abc
from contextlib import contextmanager
from typing import Generic
from django.conf import settings
+import redis
import orjson
-from redis import Redis
-from redis.exceptions import ReadOnlyError
+import redis.exceptions as redis_exceptions
from structlog.types import FilteringBoundLogger
from posthog.redis import get_client
@@ -84,26 +84,30 @@ class ResumableSourceManager(Generic[ResumableData]):
self._logger.debug(f"Dropping unknown resumable state fields. key={self._key}, fields={unknown}")
return self._data_class(**{name: value for name, value in parsed_data.items() if name in known})
- def _write_with_readonly_retry(self, client: Redis, write: Callable[[], object]) -> None:
- """Retry a write once after `ReadOnlyError`.
+ def _write_with_stale_replica_retry(self, client: redis.Redis, write: collections.abc.Callable[[], None]) -> None:
+ """Run a Redis write, retrying once if the connection now points at a demoted replica.
- A connection held open across a Redis failover keeps talking to what is now a demoted
- replica, so a write on it fails until the client reconnects — the same stale-connection
- failure mode Postgres writes hit after a failover (see `is_stale_connection_read_only_error`).
- Disconnecting the pool forces the retry onto a fresh connection to the current primary.
+ `get_client` caches one connection pool for the lifetime of the worker process. A Redis
+ failover can promote a different node to primary while this pool still holds a connection
+ to the now-demoted node, so every write on it fails with ``ReadOnlyError`` until the pool
+ is forced to reconnect. Disconnecting and retrying once means a passing failover costs at
+ most one failed write instead of every write for the rest of the worker's life.
"""
try:
write()
- except ReadOnlyError:
+ except redis_exceptions.ReadOnlyError:
client.connection_pool.disconnect()
write()
def save_state(self, data: ResumableData) -> None:
- with self._get_redis() as redis:
+ with self._get_redis() as redis_client:
json_data = self._dump_json(data)
self._logger.debug(f"Saving resumable source state. key={self._key}, data={json_data}")
- self._write_with_readonly_retry(redis, lambda: redis.set(self._key, json_data, ex=60 * 60 * 24))
+ self._write_with_stale_replica_retry(
+ redis_client,
+ lambda: redis_client.set(self._key, json_data, ex=60 * 60 * 24), # 24 hours expiration
+ )
def clear_state(self) -> None:
"""Drop any saved resume state so a subsequent attempt starts from scratch.
@@ -111,9 +115,9 @@ class ResumableSourceManager(Generic[ResumableData]):
Called once a source has walked its data to completion: leaving the final checkpoint in
place would let a later attempt resume mid-stream instead of restarting cleanly.
"""
- with self._get_redis() as redis:
+ with self._get_redis() as redis_client:
self._logger.debug(f"Clearing resumable source state. key={self._key}")
- self._write_with_readonly_retry(redis, lambda: redis.delete(self._key))
+ self._write_with_stale_replica_retry(redis_client, lambda: redis_client.delete(self._key))
def can_resume(self) -> bool:
with self._get_redis() as redis:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py
index 1cfe4d8b3c24..7c1e34913787 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py
@@ -1,7 +1,7 @@
import pytest
from unittest.mock import MagicMock, patch
-from redis.exceptions import ReadOnlyError
+import redis.exceptions as redis_exceptions
from posthog.dataclasses import frozen
@@ -25,26 +25,30 @@ class TestResumableSourceManager:
assert state == _SweepPosition(cursor="cus_1")
- def test_save_state_retries_once_after_stale_connection_read_only_error(self):
+ def test_clear_state_retries_once_after_a_stale_replica_write(self):
manager = ResumableSourceManager[_SweepPosition](MagicMock(team_id=1, job_id="job-1"), _SweepPosition)
redis = MagicMock()
- redis.set.side_effect = [ReadOnlyError("You can't write against a read only replica."), None]
+ redis.delete.side_effect = [
+ redis_exceptions.ReadOnlyError("You can't write against a read only replica."),
+ None,
+ ]
with patch.object(ResumableSourceManager, "_get_redis") as get_redis:
get_redis.return_value.__enter__.return_value = redis
- manager.save_state(_SweepPosition(cursor="cus_1"))
+ manager.clear_state()
- assert redis.set.call_count == 2
redis.connection_pool.disconnect.assert_called_once()
+ assert redis.delete.call_count == 2
- def test_save_state_raises_when_retry_also_hits_read_only_error(self):
+ def test_clear_state_raises_when_the_retry_also_hits_a_stale_replica(self):
manager = ResumableSourceManager[_SweepPosition](MagicMock(team_id=1, job_id="job-1"), _SweepPosition)
redis = MagicMock()
- redis.set.side_effect = ReadOnlyError("You can't write against a read only replica.")
+ redis.delete.side_effect = redis_exceptions.ReadOnlyError("You can't write against a read only replica.")
with patch.object(ResumableSourceManager, "_get_redis") as get_redis:
get_redis.return_value.__enter__.return_value = redis
- with pytest.raises(ReadOnlyError):
- manager.save_state(_SweepPosition(cursor="cus_1"))
+ with pytest.raises(redis_exceptions.ReadOnlyError):
+ manager.clear_state()
- assert redis.set.call_count == 2
+ redis.connection_pool.disconnect.assert_called_once()
+ assert redis.delete.call_count == 2