: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
chore(flags): split the sweep cap and threshold per cache (#104236)
James Gille2f09f636126
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.mdindex 2f2742e73a46..ae9ff843e1cc 100644--- a/docs/internal/feature-flags/hypercache-system.md+++ b/docs/internal/feature-flags/hypercache-system.md@@ -497,11 +497,12 @@ The Rust service only operates when `FLAGS_REDIS_URL` is configured. All cache uCache freshness is maintained through scheduled Celery tasks.-| Task | Schedule | Purpose |-| -------------------------------------------- | ---------------- | ---------------------------------------------------- |-| `refresh_expiring_flags_cache_entries` | Hourly at :15 | Refresh caches with TTL < 24h before they expire |-| `cleanup_stale_flags_expiry_tracking_task` | Daily at 3:15 AM | Remove expired team entries from tracking sorted set |-| `verify_and_fix_flag_definitions_cache_task` | Hourly at :50 | Verify flag definitions cache against database |+| Task | Schedule | Purpose |+| ------------------------------------------------- | ---------------- | ---------------------------------------------------- |+| `refresh_expiring_flags_cache_entries` | Hourly at :15 | Refresh caches with TTL < 24h before they expire |+| `cleanup_stale_flags_expiry_tracking_task` | Daily at 3:15 AM | Remove expired team entries from tracking sorted set |+| `refresh_expiring_flag_definitions_cache_entries` | Hourly at :35 | Refresh flag definitions caches before they expire |+| `verify_and_fix_flag_definitions_cache_task` | Hourly at :50 | Verify flag definitions cache against database |### Refresh task@@ -597,11 +598,17 @@ FLAGS_REDIS_URL=redis://flags-redis:6379FLAGS_CACHE_TTL=604800 # 7 days (default)FLAGS_CACHE_MISS_TTL=86400 # 1 day (default)-# Scheduled task settings+# Scheduled task settings for the flags cache sweepFLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS=24 # Refresh caches expiring within 24hFLAGS_CACHE_REFRESH_LIMIT=5000 # Max teams per refresh runFLAGS_CACHE_VERIFICATION_GRACE_PERIOD_MINUTES=5 # Skip recently updated flags+# Scheduled task settings for the flag definitions cache sweep.+# Each one defaults to the resolved flags value above, so both sweeps move together.+# Uncomment one to move this sweep alone.+# FLAG_DEFINITIONS_CACHE_REFRESH_TTL_THRESHOLD_HOURS=12+# FLAG_DEFINITIONS_CACHE_REFRESH_LIMIT=2000+# For S3 fallbackOBJECT_STORAGE_ENABLED=trueAWS_S3_BUCKET_NAME=posthog-cachediff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex 5c220183836b..e123023a7c9d 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -67,18 +67,32 @@ FEATURE_FLAG_LAST_CALLED_AT_SYNC_QUERY_TIMEOUT_SECONDS: int = max(get_from_env("FEATURE_FLAG_LAST_CALLED_AT_SYNC_QUERY_TIMEOUT_SECONDS", 120, type_cast=int),)-# Feature flag cache refresh settings+# Refresh sweep settings for the `flags` cache; `flag_definitions` has its own pair below.FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS: int = get_from_env("FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS", 24, type_cast=int)-# Maximum number of teams to refresh per cache refresh run to prevent memory spikes.+# Maximum number of teams the `flags` sweep takes per run. A routed team counts when its+# Kafka message is produced, so a routed run caps messages and not finished rebuilds.# With ~200k teams, 5000 is a starting point that processes all teams across ~40 runs.# Run `python manage.py analyze_flags_cache_sizes` to measure actual memory usage.# Based on typical flag data, 5000 teams ≈ 10-100 MB depending on flag complexity.# See cache_expiry_manager.py for implementation details.FLAGS_CACHE_REFRESH_LIMIT: int = get_from_env("FLAGS_CACHE_REFRESH_LIMIT", 5000, type_cast=int)+# Refresh sweep settings for the `flag_definitions` cache, which binds no `route_refresh_fn`+# and so always builds inline and always caps finished rebuilds. Each defaults to the+# `flags` value, which means raising the `flags` setting still raises this sweep until an+# operator pins these.+FLAG_DEFINITIONS_CACHE_REFRESH_TTL_THRESHOLD_HOURS: int = get_from_env(+ "FLAG_DEFINITIONS_CACHE_REFRESH_TTL_THRESHOLD_HOURS",+ FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS,+ type_cast=int,+)+FLAG_DEFINITIONS_CACHE_REFRESH_LIMIT: int = get_from_env(+ "FLAG_DEFINITIONS_CACHE_REFRESH_LIMIT", FLAGS_CACHE_REFRESH_LIMIT, type_cast=int+)+# Pacing for the teams the refresh sweep routes to the Kafka cache builder instead of# building itself. The builder drains a batch sequentially, so a whole run produced at# once sits in front of the flag edits raised after it and delays their rebuilds. Thediff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.pyindex ebbb46339bab..188f7f1dfd9e 100644--- a/products/feature_flags/backend/tasks.py+++ b/products/feature_flags/backend/tasks.py@@ -467,7 +467,7 @@ def refresh_expiring_flag_definitions_cache_entries(self: PushGatewayTask) -> No"""Periodic task to refresh the flag definitions cache before entries expire.- Runs hourly and refreshes caches with TTL < 24 hours to prevent cache misses.+ Runs hourly and refreshes caches inside the TTL threshold to prevent cache misses.Note: Most cache updates happen via Django signals when flags change.This job just prevents expiration-related cache misses.@@ -489,14 +489,14 @@ def refresh_expiring_flag_definitions_cache_entries(self: PushGatewayTask) -> Nostart_time = time.time()logger.info("Starting flag definitions cache sync",- ttl_threshold_hours=settings.FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS,- limit=settings.FLAGS_CACHE_REFRESH_LIMIT,+ ttl_threshold_hours=settings.FLAG_DEFINITIONS_CACHE_REFRESH_TTL_THRESHOLD_HOURS,+ limit=settings.FLAG_DEFINITIONS_CACHE_REFRESH_LIMIT,)counts = refresh_expiring_caches(config=FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,- ttl_threshold_hours=settings.FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS,- limit=settings.FLAGS_CACHE_REFRESH_LIMIT,+ ttl_threshold_hours=settings.FLAG_DEFINITIONS_CACHE_REFRESH_TTL_THRESHOLD_HOURS,+ limit=settings.FLAG_DEFINITIONS_CACHE_REFRESH_LIMIT,)successful_gauge.set(counts.successful)diff --git a/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py b/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.pyindex 1b06a512cfbb..d28b94eb13ba 100644--- a/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py+++ b/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py@@ -1,6 +1,7 @@from unittest.mock import MagicMock, patch-from django.test import TestCase+from django.conf import settings+from django.test import TestCase, override_settingsfrom posthog.storage.cache_expiry_manager import CacheRefreshCountsfrom posthog.tasks.test.utils import PushGatewayTaskTestMixin@@ -9,6 +10,7 @@ from products.feature_flags.backend.local_evaluation import FLAG_DEFINITIONS_HYPfrom products.feature_flags.backend.tasks import (cleanup_stale_flag_definitions_expiry_tracking_task,refresh_expiring_flag_definitions_cache_entries,+ refresh_expiring_flags_cache_entries,)@@ -20,11 +22,50 @@ class TestRefreshExpiringFlagDefinitionsCacheEntries(PushGatewayTaskTestMixin, Trefresh_expiring_flag_definitions_cache_entries()- mock_refresh.assert_called_once()+ mock_refresh.assert_called_once_with(+ config=FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,+ ttl_threshold_hours=settings.FLAG_DEFINITIONS_CACHE_REFRESH_TTL_THRESHOLD_HOURS,+ limit=settings.FLAG_DEFINITIONS_CACHE_REFRESH_LIMIT,+ )+ assert settings.FLAG_DEFINITIONS_CACHE_REFRESH_LIMIT == settings.FLAGS_CACHE_REFRESH_LIMIT+ assert (+ settings.FLAG_DEFINITIONS_CACHE_REFRESH_TTL_THRESHOLD_HOURS+ == settings.FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS+ )assert self.registry.get_sample_value("posthog_flag_definitions_cache_refresh_successful_count") == 5assert self.registry.get_sample_value("posthog_flag_definitions_cache_refresh_failed_count") == 0mock_stats.assert_called_once_with(FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG)+ @override_settings(+ FLAG_DEFINITIONS_CACHE_REFRESH_LIMIT=7,+ FLAG_DEFINITIONS_CACHE_REFRESH_TTL_THRESHOLD_HOURS=3,+ FLAGS_REDIS_URL="redis://localhost:6379",+ )+ @patch("products.feature_flags.backend.tasks.get_cache_stats", return_value={})+ @patch("products.feature_flags.backend.tasks.refresh_expiring_flags_caches")+ @patch("products.feature_flags.backend.tasks.get_cache_stats_generic", return_value={})+ @patch("posthog.storage.cache_expiry_manager.refresh_expiring_caches")+ def test_definitions_settings_leave_the_flags_sweep_alone(+ self,+ mock_definitions_refresh: MagicMock,+ mock_definitions_stats: MagicMock,+ mock_flags_refresh: MagicMock,+ mock_flags_stats: MagicMock,+ ) -> None:+ mock_definitions_refresh.return_value = CacheRefreshCounts(successful=1, failed=0)+ mock_flags_refresh.return_value = CacheRefreshCounts(successful=1, failed=0)++ refresh_expiring_flag_definitions_cache_entries()+ refresh_expiring_flags_cache_entries()++ assert mock_definitions_refresh.call_args.kwargs["limit"] == 7+ assert mock_definitions_refresh.call_args.kwargs["ttl_threshold_hours"] == 3+ assert mock_flags_refresh.call_args.kwargs["limit"] == settings.FLAGS_CACHE_REFRESH_LIMIT+ assert (+ mock_flags_refresh.call_args.kwargs["ttl_threshold_hours"]+ == settings.FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS+ )+@patch("posthog.storage.cache_expiry_manager.refresh_expiring_caches")def test_propagates_error(self, mock_refresh: MagicMock) -> None:mock_refresh.side_effect = Exception("refresh failed")