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(flags): retry the last_called_at sync on Redis errors (#102050)

posthog[bot]be9c0eebbad5
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index 099785d57591..94df81ea697a 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -16,6 +16,7 @@ from celery import shared_task
from clickhouse_driver.errors import UnknownPacketFromServerError
from prometheus_client import Counter, Gauge
from redis import Redis
+from redis.exceptions import RedisError
from rest_framework.exceptions import APIException
from structlog import get_logger
@@ -34,6 +35,7 @@ from posthog.redis import get_client
from posthog.scoping_audit import skip_team_scope_audit
from posthog.settings import CLICKHOUSE_CLUSTER
from posthog.tasks.utils import CeleryQueue, PushGatewayTask
+from posthog.utils import safe_cache_delete
logger = get_logger(__name__)
@@ -1255,7 +1257,10 @@ def _queue_delete_team_recordings(team_ids: list[int], deleted_by: str) -> None:
queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,
# sync_execute wraps TOO_MANY_SIMULTANEOUS_QUERIES/CANNOT_SCHEDULE_TASK into
# ClickHouseAtCapacity, which CH_TRANSIENT_ERRORS includes.
- autoretry_for=FEATURE_FLAG_SYNC_TRANSIENT_ERRORS,
+ # The lock and the checkpoint live in Redis. A retry resumes from the unmoved checkpoint within
+ # minutes instead of at the next scheduled run. django-redis re-raises the redis-py error that
+ # ConnectionInterrupted wraps. RedisError therefore also covers the cache calls on the lock.
+ autoretry_for=(*FEATURE_FLAG_SYNC_TRANSIENT_ERRORS, RedisError),
retry_backoff=30,
retry_backoff_max=120,
max_retries=3,
@@ -1334,24 +1339,20 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:
try:
redis_client = get_client()
- # Get last sync timestamp from Redis or use lookback
- try:
- last_sync_str = redis_client.get(FEATURE_FLAG_LAST_CALLED_SYNC_KEY)
- if last_sync_str:
+ # Get last sync timestamp from Redis or use lookback. A Redis error on this read propagates so
+ # that Celery retries the run. The lookback fallback would rescan up to
+ # FEATURE_FLAG_LAST_CALLED_AT_SYNC_MAX_LOOKBACK_HOURS of chunks that the checkpoint already covers.
+ last_sync_str = redis_client.get(FEATURE_FLAG_LAST_CALLED_SYNC_KEY)
+ last_sync_timestamp = timezone.now() - timedelta(days=settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_LOOKBACK_DAYS)
+ if last_sync_str:
+ try:
parsed_timestamp = datetime.fromisoformat(last_sync_str.decode())
# Ensure timezone-aware to avoid comparison issues with timezone.now()
last_sync_timestamp = (
parsed_timestamp if parsed_timestamp.tzinfo else timezone.make_aware(parsed_timestamp)
)
- else:
- last_sync_timestamp = timezone.now() - timedelta(
- days=settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_LOOKBACK_DAYS
- )
- except Exception as e:
- logger.warning("Failed to get or parse last sync timestamp", error=str(e))
- last_sync_timestamp = timezone.now() - timedelta(
- days=settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_LOOKBACK_DAYS
- )
+ except ValueError as e:
+ logger.warning("Failed to parse last sync timestamp", error=str(e))
# Cap lookback to prevent excessive scanning when checkpoint is stale/missing.
# Capture now once to avoid drift between max_lookback and current_sync_timestamp.
@@ -1637,8 +1638,9 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:
if not run_failed and (self.request.retries or 0) > 0:
FEATURE_FLAG_LAST_CALLED_AT_SYNC_RETRY_RECOVERY_COUNTER.inc()
- # Always release the lock
- cache.delete(LOCK_KEY)
+ # Always release the lock. A failed delete must not replace the exception that the try block
+ # raised. The lock expires on its own after LOCK_TIMEOUT.
+ safe_cache_delete(LOCK_KEY)
@shared_task(ignore_result=True, time_limit=7200)
diff --git a/products/feature_flags/backend/test/test_feature_flag_sync.py b/products/feature_flags/backend/test/test_feature_flag_sync.py
index afbab864ed8c..da76f017e72d 100644
--- a/products/feature_flags/backend/test/test_feature_flag_sync.py
+++ b/products/feature_flags/backend/test/test_feature_flag_sync.py
@@ -11,6 +11,7 @@ from django.utils import timezone as tz
from clickhouse_driver.errors import UnknownPacketFromServerError
from parameterized import parameterized
from prometheus_client import REGISTRY
+from redis.exceptions import ConnectionError as RedisConnectionError
from posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorTooManyBytes, CHQueryErrorUnknownTable
from posthog.exceptions import ClickHouseAtCapacity
@@ -24,7 +25,8 @@ def mock_redis_client() -> Mock:
mock = Mock()
mock.storage = {}
mock.get = lambda k: mock.storage.get(k)
- mock.set = lambda k, v: mock.storage.update({k: v}) or None
+ # redis-py encodes a str value on write, so the real client stores and returns bytes
+ mock.set = lambda k, v: mock.storage.update({k: v.encode() if isinstance(v, str) else v}) or None
return mock
@@ -239,13 +241,13 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
@time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
- def test_redis_error_falls_back_to_lookback_days(
+ def test_unparseable_checkpoint_falls_back_to_lookback_days(
self, mock_get_client: MagicMock, mock_sync_execute: MagicMock
) -> None:
- """When checkpoint cannot be retrieved, fall back to lookback_days"""
+ """When the stored checkpoint cannot be parsed, fall back to lookback_days"""
redis_mock = mock_redis_client()
- # Make redis.get() raise an exception
- redis_mock.get = Mock(side_effect=Exception("Redis error"))
+ # A malformed stored value, not a transport failure: those have to raise and retry instead
+ redis_mock.storage["posthog:feature_flag_last_called_sync:last_timestamp"] = b"not-a-timestamp"
mock_get_client.return_value = redis_mock
mock_sync_execute.return_value = []
@@ -260,6 +262,26 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
assert last_sync.month == 6
assert last_sync.day == 14
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
+ @patch("posthog.clickhouse.client.sync_execute")
+ @patch("posthog.tasks.tasks.get_client")
+ def test_checkpoint_read_transport_error_raises_and_keeps_checkpoint(
+ self, mock_get_client: MagicMock, mock_sync_execute: MagicMock
+ ) -> None:
+ redis_mock = mock_redis_client()
+ checkpoint_key = "posthog:feature_flag_last_called_sync:last_timestamp"
+ checkpoint_time = tz.make_aware(datetime(2024, 6, 13, 12, 0, 0))
+ redis_mock.storage[checkpoint_key] = checkpoint_time.isoformat().encode()
+ redis_mock.get = Mock(side_effect=RedisConnectionError("redis is down"))
+ mock_get_client.return_value = redis_mock
+ mock_sync_execute.return_value = []
+
+ with self.assertRaises(RedisConnectionError):
+ sync_feature_flag_last_called()
+
+ mock_sync_execute.assert_not_called()
+ assert redis_mock.storage[checkpoint_key] == checkpoint_time.isoformat().encode()
+
@time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.tasks.tasks.get_client")
def test_concurrent_execution_prevented(self, mock_get_client: MagicMock) -> None:
@@ -307,6 +329,19 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
# Lock should be deleted
assert cache.get(lock_key) is None
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
+ @patch("posthog.clickhouse.client.sync_execute")
+ @patch("posthog.tasks.tasks.get_client")
+ def test_failed_lock_release_does_not_mask_original_error(
+ self, mock_get_client: MagicMock, mock_sync_execute: MagicMock
+ ) -> None:
+ mock_get_client.return_value = mock_redis_client()
+ mock_sync_execute.side_effect = ClickHouseAtCapacity()
+
+ with patch("django.core.cache.cache.delete", side_effect=RedisConnectionError("redis is down")):
+ with self.assertRaises(ClickHouseAtCapacity):
+ sync_feature_flag_last_called()
+
@time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
@@ -355,8 +390,8 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
checkpoint_key = "posthog:feature_flag_last_called_sync:last_timestamp"
stored_timestamp = redis_mock.storage.get(checkpoint_key)
assert stored_timestamp is not None
- assert "2024-06-15" in stored_timestamp
- assert "2024-06-15T11:59:00" in stored_timestamp
+ assert b"2024-06-15" in stored_timestamp
+ assert b"2024-06-15T11:59:00" in stored_timestamp
@time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@@ -490,7 +525,7 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
# Checkpoint stops at the end of the first chunk, so the unread window from 11:50
# onwards is retried next run rather than skipped
stored = redis_mock.storage.get(checkpoint_key)
- assert stored == tz.make_aware(datetime(2024, 6, 15, 11, 50, 0)).isoformat()
+ assert stored == tz.make_aware(datetime(2024, 6, 15, 11, 50, 0)).isoformat().encode()
@time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@@ -635,14 +670,13 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
# Checkpoint should still be updated
stored = redis_mock.storage.get(checkpoint_key)
assert stored is not None
- assert "2024-06-15T11:59:00" in stored
+ assert b"2024-06-15T11:59:00" in stored
# Flag should remain unchanged
self.flag1.refresh_from_db()
assert self.flag1.last_called_at is None
def test_autoretry_for_membership(self) -> None:
- """CHQueryErrorTooManyBytes should not be in the autoretry_for tuple"""
autoretry_for = sync_feature_flag_last_called.autoretry_for
assert CHQueryErrorTooManyBytes not in autoretry_for
# Transient errors should still be retried
@@ -651,6 +685,9 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
# sync_execute wraps capacity errors (code 202) into ClickHouseAtCapacity,
# so the wrapped form must be retryable too
assert ClickHouseAtCapacity in autoretry_for
+ # The lock and the checkpoint live in Redis. Celery retries the run on a Redis error instead of
+ # waiting for the next scheduled run
+ assert issubclass(RedisConnectionError, autoretry_for)
# A desynced pooled socket is retryable for this task, which only reads from ClickHouse,
# but it has to stay out of the shared tuple: the driver can raise it after the server ran
# the query, so a write caller retrying it would land the write twice
@@ -699,7 +736,8 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
def test_run_that_completes_on_a_retry_is_counted(
self, mock_get_client: MagicMock, mock_sync_execute: MagicMock
) -> None:
- mock_get_client.return_value = mock_redis_client()
+ redis_mock = mock_redis_client()
+ mock_get_client.return_value = redis_mock
mock_sync_execute.return_value = []
recoveries_metric = "posthog_feature_flag_last_called_at_sync_retry_recoveries_total"
recoveries_before = REGISTRY.get_sample_value(recoveries_metric) or 0.0
@@ -719,6 +757,9 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
assert (REGISTRY.get_sample_value(recoveries_metric) or 0.0) == recoveries_before + 1
cache.clear()
+ # The run before moved the checkpoint to the frozen now. Without a reset, this run has no chunk
+ # to query and never reaches the error
+ redis_mock.storage.clear()
mock_sync_execute.side_effect = CHQueryErrorUnknownTable("boom")
sync_feature_flag_last_called.push_request(retries=1)
try: