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.

perf(organization): cache member_count per-org (#57608)

Paul D'Ambrad4b85414601d
diff --git a/posthog/api/organization.py b/posthog/api/organization.py
index 7a74f50b8e54..80c7f5f53599 100644
--- a/posthog/api/organization.py
+++ b/posthog/api/organization.py
@@ -134,11 +134,10 @@ def _bump_org_serializer_cache_version(organization_id: str) -> None:
CacheField = Literal["teams", "projects"]
+OrgCacheField = Literal["member_count"]
-def _cached_per_user_org(field: CacheField, user_id: int, organization_id: str, fetcher: Callable[[], Any]) -> Any:
- version = _org_serializer_cache_version(organization_id)
- cache_key = f"org_serializer:{field}:{organization_id}:v{version}:{user_id}"
+def _cached_org_serializer_field(cache_key: str, fetcher: Callable[[], Any]) -> Any:
cached = get_safe_cache(cache_key)
if cached is not None:
return cached
@@ -147,6 +146,30 @@ def _cached_per_user_org(field: CacheField, user_id: int, organization_id: str,
return result
+def _cached_per_user_org(field: CacheField, user_id: int, organization_id: str, fetcher: Callable[[], Any]) -> Any:
+ version = _org_serializer_cache_version(organization_id)
+ cache_key = f"org_serializer:{field}:{organization_id}:v{version}:{user_id}"
+ return _cached_org_serializer_field(cache_key, fetcher)
+
+
+def _fetch_member_count(organization: Organization) -> int:
+ # The cache version is bumped on OrganizationMembership signals (see _INVALIDATION_SOURCES
+ # below), so add/remove of members invalidates immediately. User.is_active flips and email
+ # changes to/from INTERNAL_BOT_EMAIL_SUFFIX do NOT invalidate via signals — they rely on
+ # ORG_SERIALIZER_CACHE_TTL_SECONDS (1h) as the staleness bound.
+ return (
+ OrganizationMembership.objects.exclude(user__email__endswith=INTERNAL_BOT_EMAIL_SUFFIX)
+ .filter(user__is_active=True, organization=organization)
+ .count()
+ )
+
+
+def _cached_per_org(field: OrgCacheField, organization_id: str, fetcher: Callable[[], Any]) -> Any:
+ version = _org_serializer_cache_version(organization_id)
+ cache_key = f"org_serializer:{field}:{organization_id}:v{version}"
+ return _cached_org_serializer_field(cache_key, fetcher)
+
+
def _resolve_cached_user_id(serializer_context: dict[str, Any]) -> int | None:
request = serializer_context.get("request")
if request is None:
@@ -389,15 +412,8 @@ class OrganizationSerializer(
@extend_schema_field(serializers.IntegerField())
@tracer.start_as_current_span("organization_serializer.member_count")
- def get_member_count(self, organization: Organization):
- return (
- OrganizationMembership.objects.exclude(user__email__endswith=INTERNAL_BOT_EMAIL_SUFFIX)
- .filter(
- user__is_active=True,
- )
- .filter(organization=organization)
- .count()
- )
+ def get_member_count(self, organization: Organization) -> int:
+ return _cached_per_org("member_count", str(organization.id), lambda: _fetch_member_count(organization))
@tracer.start_as_current_span("organization_serializer.to_representation")
def to_representation(self, instance):
diff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.py
index 00bfc7deae2e..4f81b107a54f 100644
--- a/posthog/api/test/test_organization.py
+++ b/posthog/api/test/test_organization.py
@@ -15,7 +15,7 @@ from rest_framework import status
from rest_framework.test import APIRequestFactory
from posthog.api.oauth.test_dcr import generate_rsa_key
-from posthog.api.organization import OrganizationSerializer, _org_serializer_cache_version
+from posthog.api.organization import OrganizationSerializer, _fetch_member_count, _org_serializer_cache_version
from posthog.models import FeatureFlag, Organization, OrganizationMembership, Team
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.personal_api_key import PersonalAPIKey
@@ -787,6 +787,46 @@ class TestOrganizationSerializer(APIBaseTest):
serializer.get_teams(self.organization)
assert spy.call_count == 2
+ def test_get_member_count_caches_per_org(self):
+ serializer = OrganizationSerializer(self.organization, context=self.context)
+ with patch("posthog.api.organization._fetch_member_count", wraps=_fetch_member_count) as spy:
+ first = serializer.get_member_count(self.organization)
+ second = serializer.get_member_count(self.organization)
+ assert spy.call_count == 1
+ assert first == second == 1
+
+ @parameterized.expand(
+ [
+ (
+ "membership_create",
+ lambda self: self._create_user("[email protected]"),
+ 3,
+ ),
+ (
+ "membership_delete",
+ lambda self: OrganizationMembership.objects.filter(user=self._seeded_user).delete(),
+ 1,
+ ),
+ ]
+ )
+ def test_get_member_count_invalidates_on_membership_change(self, _name, mutate, expected_after):
+ # Seed a second member so the delete path has something to remove and the
+ # baseline count is the same for both parameter cases.
+ self._seeded_user = self._create_user("[email protected]")
+ cache.clear()
+ baseline = OrganizationSerializer(self.organization, context=self.context).get_member_count(self.organization)
+ assert baseline == 2
+
+ with self.captureOnCommitCallbacks(execute=True):
+ mutate(self)
+
+ with patch("posthog.api.organization._fetch_member_count", wraps=_fetch_member_count) as spy:
+ after = OrganizationSerializer(
+ self.organization, context=self._fresh_context_for(self.user)
+ ).get_member_count(self.organization)
+ assert spy.call_count == 1
+ assert after == expected_after
+
class TestOrganizationRbacMigrations(APIBaseTest):
def setUp(self):