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(org-cache): clear the org serializer cache on organization saves (#125733)

Paul D'Ambra5dc908455fff
diff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.py
index b163a8fb7a6b..b83221748a02 100644
--- a/posthog/api/test/test_organization.py
+++ b/posthog/api/test/test_organization.py
@@ -1130,6 +1130,10 @@ class TestOrganizationSerializer(APIBaseTest):
"organization_membership",
lambda self: self._create_user("[email protected]"),
),
+ (
+ "organization",
+ lambda self: self.organization.save(),
+ ),
]
)
def test_rbac_change_invalidates_org_cache(self, _name, mutate):
diff --git a/posthog/caching/cache_version.py b/posthog/caching/cache_version.py
new file mode 100644
index 000000000000..280ae8b1f1c4
--- /dev/null
+++ b/posthog/caching/cache_version.py
@@ -0,0 +1,37 @@
+"""
+A version number in the cache that a cached value puts in its key. A write bumps the version, so readers
+build a new value and the old entries expire on their own TTL.
+"""
+
+from django.core.cache import cache
+
+from posthog.utils import get_safe_cache
+
+
+def read_cache_version(key: str, timeout: int) -> int:
+ raw = get_safe_cache(key)
+ if raw is None:
+ try:
+ cache.add(key, 0, timeout=timeout)
+ except Exception:
+ pass
+ return 0
+ try:
+ return int(raw)
+ except (TypeError, ValueError):
+ return 0
+
+
+def bump_cache_version(key: str, timeout: int) -> None:
+ try:
+ cache.incr(key)
+ # incr keeps the old expiry. If the key expired, the version would start again at 0 and could
+ # match entries that are still cached.
+ cache.touch(key, timeout=timeout)
+ except ValueError:
+ try:
+ cache.add(key, 1, timeout=timeout)
+ except Exception:
+ pass
+ except Exception:
+ pass
diff --git a/posthog/caching/organization_serializer_cache.py b/posthog/caching/organization_serializer_cache.py
index 564a425497b8..7d93869b50b2 100644
--- a/posthog/caching/organization_serializer_cache.py
+++ b/posthog/caching/organization_serializer_cache.py
@@ -11,15 +11,14 @@ no longer triggers at setup.
from collections.abc import Callable
from typing import Any
-from django.core.cache import cache
from django.db import transaction
from django.db.models import Model
from django.db.models.signals import post_delete, post_save
-from posthog.models.organization import OrganizationMembership
+from posthog.caching.cache_version import bump_cache_version, read_cache_version
+from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.project import Project
from posthog.models.team import Team
-from posthog.utils import get_safe_cache
from products.access_control.backend.models.access_control import AccessControl
from products.access_control.backend.models.role import RoleMembership
@@ -36,31 +35,11 @@ def _org_serializer_version_key(organization_id: str) -> str:
def _org_serializer_cache_version(organization_id: str) -> int:
- key = _org_serializer_version_key(organization_id)
- raw = get_safe_cache(key)
- if raw is None:
- try:
- cache.add(key, 0, timeout=ORG_SERIALIZER_VERSION_TTL_SECONDS)
- except Exception:
- pass
- return 0
- try:
- return int(raw)
- except (TypeError, ValueError):
- return 0
+ return read_cache_version(_org_serializer_version_key(organization_id), ORG_SERIALIZER_VERSION_TTL_SECONDS)
def _bump_org_serializer_cache_version(organization_id: str) -> None:
- key = _org_serializer_version_key(organization_id)
- try:
- cache.incr(key)
- except ValueError:
- try:
- cache.add(key, 1, timeout=ORG_SERIALIZER_VERSION_TTL_SECONDS)
- except Exception:
- pass
- except Exception:
- pass
+ bump_cache_version(_org_serializer_version_key(organization_id), ORG_SERIALIZER_VERSION_TTL_SECONDS)
def _instance_org_id(instance: Any) -> str | None:
@@ -94,6 +73,7 @@ def _access_control_to_org_id(instance: Any) -> str | None:
_INVALIDATION_SOURCES: list[tuple[type[Model], Callable[[Any], str | None]]] = [
+ (Organization, lambda instance: str(instance.pk)),
(Team, _instance_org_id),
(Project, _instance_org_id),
(OrganizationMembership, _instance_org_id),
diff --git a/posthog/caching/test/test_cache_version.py b/posthog/caching/test/test_cache_version.py
new file mode 100644
index 000000000000..f6177f28345a
--- /dev/null
+++ b/posthog/caching/test/test_cache_version.py
@@ -0,0 +1,26 @@
+from datetime import UTC, datetime, timedelta
+
+import time_machine
+
+from django.core.cache import cache
+from django.test import SimpleTestCase, override_settings
+
+from posthog.caching.cache_version import bump_cache_version, read_cache_version
+
+KEY = "test_cache_version"
+TIMEOUT = 24 * 60 * 60
+
+
+@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})
+class TestCacheVersion(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+
+ def test_bump_keeps_the_version_alive_past_the_first_timeout(self) -> None:
+ with time_machine.travel(datetime(2026, 1, 1, tzinfo=UTC), tick=False) as traveller:
+ read_cache_version(KEY, TIMEOUT)
+ traveller.shift(timedelta(hours=23))
+ bump_cache_version(KEY, TIMEOUT)
+ traveller.shift(timedelta(hours=2))
+
+ assert read_cache_version(KEY, TIMEOUT) == 1