: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
refactor(slack_app): replace Redis user-profile cache with DB TTL (#61565)
Vojta Bartoš9edf9aef4042
diff --git a/products/slack_app/backend/admin.py b/products/slack_app/backend/admin.pyindex 5bc41566ac6b..881651ead4d1 100644--- a/products/slack_app/backend/admin.py+++ b/products/slack_app/backend/admin.py@@ -84,20 +84,22 @@ class SlackUserProfileCacheAdmin(admin.ModelAdmin):"real_name","is_admin","is_owner",+ "refreshed_at","updated_at",)list_filter = ("is_admin","is_owner",+ ("refreshed_at", admin.DateFieldListFilter),("updated_at", admin.DateFieldListFilter),)search_fields = ("slack_user_id", "email", "display_name", "real_name")- readonly_fields = ("id", "created_at", "updated_at")+ readonly_fields = ("id", "created_at", "updated_at", "refreshed_at")autocomplete_fields = ("integration",)- ordering = ("-updated_at",)+ ordering = ("-refreshed_at",)fieldsets = ((None, {"fields": ("id", "integration", "slack_user_id")}),("Profile", {"fields": ("email", "display_name", "real_name", "is_admin", "is_owner")}),- ("Dates", {"fields": ("created_at", "updated_at")}),+ ("Dates", {"fields": ("created_at", "updated_at", "refreshed_at")}),)diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 4a656eb788e9..8f19bdbf3073 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -5,6 +5,7 @@ import uuidimport asyncioimport hashlibfrom dataclasses import dataclass+from datetime import timedeltafrom typing import Any, Literalfrom urllib.parse import urlparse, urlunparse@@ -13,6 +14,7 @@ from django.core import signingfrom django.core.cache import cachefrom django.db.utils import DatabaseErrorfrom django.http import HttpRequest, HttpResponse, JsonResponse+from django.utils import timezonefrom django.views.decorators.csrf import csrf_exemptimport requests@@ -85,7 +87,7 @@ ROUTE_NO_INTEGRATION = "no_integration"PICKER_TOKEN_SALT = "posthog_code_repo_picker"PICKER_TOKEN_MAX_AGE_SECONDS = 900-SLACK_USER_INFO_CACHE_TTL_SECONDS = 600+SLACK_USER_PROFILE_TTL = timedelta(hours=1)_MAX_GITHUB_REPOS = 500REPO_LIST_CACHE_TTL_SECONDS = 300@@ -173,14 +175,6 @@ class RulesCommand:project_team_id: int | None = None-def _slack_user_info_cache_key(integration_id: int, slack_user_id: str) -> str:- return f"posthog_code_slack_user_info:{integration_id}:{slack_user_id}"---def _slack_user_id_by_email_cache_key(integration_id: int, normalized_email: str) -> str:- return f"posthog_code_slack_user_id_by_email:{integration_id}:{normalized_email}"--def _format_slack_user_info_payload(*, email: str | None, display_name: str, real_name: str, is_admin: bool, is_owner: bool) -> dict[str, Any]:@@ -216,7 +210,7 @@ def _get_slack_user_info_from_db(integration: Integration, slack_user_id: str) -except DatabaseError:logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)return None- if not profile:+ if not profile or not profile.refreshed_at or timezone.now() - profile.refreshed_at >= SLACK_USER_PROFILE_TTL:return Nonereturn _format_slack_user_info_payload(@@ -241,6 +235,7 @@ def _persist_slack_user_info(integration: Integration, slack_user_id: str, user_"real_name": profile.get("real_name") or "","is_admin": bool(user.get("is_admin")),"is_owner": bool(user.get("is_owner")),+ "refreshed_at": timezone.now(),},)except DatabaseError:@@ -248,20 +243,13 @@ def _persist_slack_user_info(integration: Integration, slack_user_id: str, user_def _get_slack_user_info(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> dict[str, Any]:- cache_key = _slack_user_info_cache_key(integration.id, slack_user_id)- cached = cache.get(cache_key)- if isinstance(cached, dict):- return cached-cached_db = _get_slack_user_info_from_db(integration, slack_user_id)if isinstance(cached_db, dict):- cache.set(cache_key, cached_db, timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)return cached_dbuser_info = _normalize_slack_response(slack.client.users_info(user=slack_user_id))if user_info:_persist_slack_user_info(integration, slack_user_id, user_info)- cache.set(cache_key, user_info, timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)return user_inforeturn {}@@ -282,7 +270,9 @@ def _get_slack_user_id_by_email_from_db(integration: Integration, normalized_emaexcept DatabaseError:logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)return None- return profile.slack_user_id if profile else None+ if not profile or not profile.refreshed_at or timezone.now() - profile.refreshed_at >= SLACK_USER_PROFILE_TTL:+ return None+ return profile.slack_user_iddef lookup_slack_user_id_by_email(@@ -293,20 +283,14 @@ def lookup_slack_user_id_by_email("""Resolve a Slack user ID from a PostHog user email.Uses ``SlackUserProfileCache`` (populated by ``resolve_slack_user`` and prior lookups),- then ``users.lookupByEmail``. Results are cached per integration + email.+ then ``users.lookupByEmail``."""normalized_email = email.strip().lower()if not normalized_email:return None- cache_key = _slack_user_id_by_email_cache_key(integration.id, normalized_email)- cached = cache.get(cache_key)- if cached is not None:- return cached or None-slack_user_id = _get_slack_user_id_by_email_from_db(integration, normalized_email)if slack_user_id:- cache.set(cache_key, slack_user_id, timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)return slack_user_idtry:@@ -320,29 +304,37 @@ def lookup_slack_user_id_by_email(email=email,error=error_code,)- cache.set(cache_key, "", timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)return Noneif not user_info.get("ok"):- cache.set(cache_key, "", timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)return Noneuser = user_info.get("user")if not isinstance(user, dict) or not user.get("id"):- cache.set(cache_key, "", timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)return Noneslack_user_id = str(user["id"])_persist_slack_user_info(integration, slack_user_id, user_info)- cache.set(- _slack_user_info_cache_key(integration.id, slack_user_id),- user_info,- timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS,- )- cache.set(cache_key, slack_user_id, timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)+ _purge_stale_email_rows(integration, normalized_email, slack_user_id)return slack_user_id+def _purge_stale_email_rows(integration: Integration, normalized_email: str, keep_slack_user_id: str) -> None:+ """Drop rows that share an email with the authoritative Slack user ID we just resolved.++ Without this, an orphan row (same email, older Slack user ID) can outrank the fresh one+ in ``_get_slack_user_id_by_email_from_db`` and trigger a fresh ``users.lookupByEmail`` call+ on every request.+ """+ try:+ SlackUserProfileCache.objects.filter(+ integration_id=integration.id,+ email__iexact=normalized_email,+ ).exclude(slack_user_id=keep_slack_user_id).delete()+ except DatabaseError:+ logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)++QUOTA_EXHAUSTED_MESSAGE = ("Your team has used its monthly PostHog AI credits. ""Top up at https://us.posthog.com/organization/billing to continue."@@ -424,11 +416,6 @@ def resolve_slack_user(fresh_user_info = _normalize_slack_response(slack.client.users_info(user=slack_user_id))if fresh_user_info:_persist_slack_user_info(integration, slack_user_id, fresh_user_info)- cache.set(- _slack_user_info_cache_key(integration.id, slack_user_id),- fresh_user_info,- timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS,- )slack_email = fresh_user_info.get("user", {}).get("profile", {}).get("email")if not slack_email:diff --git a/products/slack_app/backend/migrations/0004_slackuserprofilecache_refreshed_at.py b/products/slack_app/backend/migrations/0004_slackuserprofilecache_refreshed_at.pynew file mode 100644index 000000000000..0b92e620f4ba--- /dev/null+++ b/products/slack_app/backend/migrations/0004_slackuserprofilecache_refreshed_at.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-06-04 09:30++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("slack_app", "0003_slacksettings"),+ ]++ operations = [+ migrations.AddField(+ model_name="slackuserprofilecache",+ name="refreshed_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txtindex 026dc63df81f..579142254ca3 100644--- a/products/slack_app/backend/migrations/max_migration.txt+++ b/products/slack_app/backend/migrations/max_migration.txt@@ -1 +1 @@-0003_slacksettings+0004_slackuserprofilecache_refreshed_atdiff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.pyindex 998663938fe6..ae053bda1436 100644--- a/products/slack_app/backend/models.py+++ b/products/slack_app/backend/models.py@@ -53,6 +53,8 @@ class SlackUserProfileCache(UUIDModel):is_owner = models.BooleanField(default=False, db_default=False)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)+ # Null is treated as stale (rows predating this field).+ refreshed_at = models.DateTimeField(null=True, blank=True)class Meta:constraints = [diff --git a/products/slack_app/backend/tests/test_resolve_slack_user.py b/products/slack_app/backend/tests/test_resolve_slack_user.pyindex 7e1b5247e1ee..42ba2dfbc40e 100644--- a/products/slack_app/backend/tests/test_resolve_slack_user.py+++ b/products/slack_app/backend/tests/test_resolve_slack_user.py@@ -1,21 +1,22 @@+from datetime import timedelta+import pytestfrom unittest.mock import MagicMock, patch-from django.core.cache import cache+from django.utils import timezonefrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from products.slack_app.backend.api import lookup_slack_user_id_by_email, resolve_slack_user+from products.slack_app.backend.api import SLACK_USER_PROFILE_TTL, lookup_slack_user_id_by_email, resolve_slack_userfrom products.slack_app.backend.models import SlackUserProfileCacheclass TestResolveSlackUser:@pytest.fixture(autouse=True)def setup(self, db):- cache.clear()self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")self.user = User.objects.create(email="[email protected]", distinct_id="user-1")@@ -100,6 +101,7 @@ class TestResolveSlackUser:email="[email protected]",display_name="Dev",real_name="Developer",+ refreshed_at=timezone.now(),)slack = SlackIntegration(self.integration)@@ -110,6 +112,46 @@ class TestResolveSlackUser:assert result.slack_email == "[email protected]"mock_client.users_info.assert_not_called()+ @pytest.mark.parametrize(+ "stale_refreshed_at",+ [+ pytest.param(lambda: timezone.now() - SLACK_USER_PROFILE_TTL - timedelta(minutes=1), id="stale_by_ttl"),+ pytest.param(lambda: None, id="null_refreshed_at"),+ ],+ )+ @patch("posthog.models.integration.WebClient")+ def test_refetches_when_profile_is_stale(self, mock_webclient_class, stale_refreshed_at):+ mock_client = MagicMock()+ mock_webclient_class.return_value = mock_client+ mock_client.users_info.return_value = {+ "user": {+ "is_admin": True,+ "is_owner": False,+ "profile": {"email": "[email protected]", "display_name": "Dev (renamed)", "real_name": "Developer"},+ }+ }++ before = timezone.now()+ SlackUserProfileCache.objects.create(+ integration=self.integration,+ slack_user_id="U123",+ email="[email protected]",+ display_name="Dev",+ real_name="Developer",+ refreshed_at=stale_refreshed_at(),+ )++ slack = SlackIntegration(self.integration)+ result = resolve_slack_user(slack, self.integration, "U123", "C001", "1234.5678")++ assert result is not None+ assert result.slack_email == "[email protected]"+ mock_client.users_info.assert_called_once_with(user="U123")+ profile = SlackUserProfileCache.objects.get(integration=self.integration, slack_user_id="U123")+ assert profile.display_name == "Dev (renamed)"+ assert profile.is_admin is True+ assert profile.refreshed_at is not None and profile.refreshed_at >= before+@patch("posthog.models.integration.WebClient")def test_persists_slack_profile_after_lookup(self, mock_webclient_class):mock_client = MagicMock()@@ -141,7 +183,6 @@ class TestResolveSlackUser:class TestLookupSlackUserIdByEmail:@pytest.fixture(autouse=True)def setup(self, db):- cache.clear()self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")self.integration = Integration.objects.create(@@ -160,6 +201,7 @@ class TestLookupSlackUserIdByEmail:integration=self.integration,slack_user_id="U123",email="[email protected]",+ refreshed_at=timezone.now(),)slack = SlackIntegration(self.integration)@@ -186,3 +228,42 @@ class TestLookupSlackUserIdByEmail:assert slack_user_id == "U456"profile = SlackUserProfileCache.objects.get(integration=self.integration, slack_user_id="U456")assert profile.email == "[email protected]"+ assert profile.refreshed_at is not None++ @pytest.mark.parametrize(+ "stale_refreshed_at",+ [+ pytest.param(lambda: timezone.now() - SLACK_USER_PROFILE_TTL - timedelta(minutes=1), id="stale_by_ttl"),+ pytest.param(lambda: None, id="null_refreshed_at"),+ ],+ )+ @patch("posthog.models.integration.WebClient")+ def test_refetches_email_lookup_when_profile_is_stale(self, mock_webclient_class, stale_refreshed_at):+ mock_client = MagicMock()+ mock_webclient_class.return_value = mock_client+ mock_client.users_lookupByEmail.return_value = {+ "ok": True,+ "user": {+ "id": "U999",+ "profile": {"email": "[email protected]", "display_name": "Dev", "real_name": "Developer"},+ },+ }++ before = timezone.now()+ SlackUserProfileCache.objects.create(+ integration=self.integration,+ slack_user_id="U123",+ email="[email protected]",+ refreshed_at=stale_refreshed_at(),+ )++ slack = SlackIntegration(self.integration)+ slack_user_id = lookup_slack_user_id_by_email(slack, self.integration, "[email protected]")++ assert slack_user_id == "U999"+ mock_client.users_lookupByEmail.assert_called_once()+ refreshed_profile = SlackUserProfileCache.objects.get(integration=self.integration, slack_user_id="U999")+ assert refreshed_profile.refreshed_at is not None and refreshed_profile.refreshed_at >= before+ # The orphan row for the previous Slack user ID is purged so subsequent+ # lookups land on the fresh row instead of re-firing the email lookup.+ assert not SlackUserProfileCache.objects.filter(integration=self.integration, slack_user_id="U123").exists()