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.

chore(django): limit distinct id fetches (#62829)

Zach Brown3004f9f6d967
diff --git a/posthog/api/person.py b/posthog/api/person.py
index dfd27be7605e..d15ed4d77385 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -1395,7 +1395,8 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
except (ValueError, AttributeError):
raise ValidationError("One or more UUIDs are invalid.")
- persons = get_persons_by_uuids(self.team_id, uuids)
+ # MinimalPersonSerializer only renders 10 distinct_ids, so bound the fetch to match.
+ persons = get_persons_by_uuids(self.team_id, uuids, distinct_id_limit=10)
results: dict[str, Any] = {}
for person in persons:
diff --git a/posthog/models/person/test/test_util_personhog_routing.py b/posthog/models/person/test/test_util_personhog_routing.py
index 118473a7ea7d..5f41ac59e72c 100644
--- a/posthog/models/person/test/test_util_personhog_routing.py
+++ b/posthog/models/person/test/test_util_personhog_routing.py
@@ -324,7 +324,7 @@ class TestGetPersonsByUuidsRouting(SimpleTestCase):
if personhog_data is not None and gate_on:
assert result == personhog_data
- mock_fetch_personhog.assert_called_once_with(team_id, uuids)
+ mock_fetch_personhog.assert_called_once_with(team_id, uuids, distinct_id_limit=None)
mock_objects.db_manager.assert_not_called()
else:
assert result == mock_qs
@@ -809,6 +809,33 @@ class TestFetchPersonsByUuidsViaPersonhog(SimpleTestCase):
assert len(result) == 1
assert result[0].distinct_ids == []
+ def test_distinct_id_limit_zero_skips_fetch(self):
+ with fake_personhog_client() as fake:
+ fake.add_person(
+ team_id=1, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["d1", "d2", "d3"]
+ )
+
+ result = _fetch_persons_by_uuids_via_personhog(
+ team_id=1, uuids=["550e8400-e29b-41d4-a716-446655440042"], distinct_id_limit=0
+ )
+
+ assert len(result) == 1
+ assert result[0].distinct_ids == []
+ fake.assert_called("get_persons_by_uuids")
+ fake.assert_not_called("get_distinct_ids_for_persons")
+
+ def test_distinct_id_limit_bounds_fetch(self):
+ with fake_personhog_client() as fake:
+ fake.add_person(
+ team_id=1, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["d1", "d2", "d3"]
+ )
+
+ result = _fetch_persons_by_uuids_via_personhog(
+ team_id=1, uuids=["550e8400-e29b-41d4-a716-446655440042"], distinct_id_limit=2
+ )
+
+ assert result[0].distinct_ids == ["d1", "d2"]
+
class TestValidateUuidsViaPersonhog(SimpleTestCase):
def test_returns_matching_uuids(self):
diff --git a/posthog/models/person/util.py b/posthog/models/person/util.py
index 1bb098fcd0a0..ac8ccf41fc69 100644
--- a/posthog/models/person/util.py
+++ b/posthog/models/person/util.py
@@ -484,20 +484,34 @@ def get_distinct_ids_for_persons(
)
-def _fetch_persons_by_uuids_via_personhog(team_id: int, uuids: list[str]) -> list[Person]:
+def _fetch_persons_by_uuids_via_personhog(
+ team_id: int, uuids: list[str], *, distinct_id_limit: int | None = None
+) -> list[Person]:
valid_persons = _batched_get_persons_by_uuids(team_id, uuids, "get_persons_by_uuids")
person_ids = [p.id for p in valid_persons]
if not person_ids:
return []
- distinct_ids_by_person = _batched_get_distinct_ids_for_persons(team_id, person_ids)
+ # Callers needing only id/uuid (e.g. cohort membership) pass distinct_id_limit=0 to skip
+ # the per-person distinct-id fetch, which is otherwise unbounded and pulls thousands of
+ # rows for merge-heavy persons.
+ if distinct_id_limit == 0:
+ return [proto_person_to_model(p, distinct_ids=[]) for p in valid_persons]
+
+ distinct_ids_by_person = _batched_get_distinct_ids_for_persons(
+ team_id, person_ids, limit_per_person=distinct_id_limit
+ )
return [proto_person_to_model(p, distinct_ids=distinct_ids_by_person.get(p.id, [])) for p in valid_persons]
-def get_persons_by_uuids(team_id: int, uuids: list[str]) -> QuerySet | list[Person]:
- personhog_fn: Callable[[], QuerySet | list[Person]] = lambda: _fetch_persons_by_uuids_via_personhog(team_id, uuids)
+def get_persons_by_uuids(
+ team_id: int, uuids: list[str], *, distinct_id_limit: int | None = None
+) -> QuerySet | list[Person]:
+ personhog_fn: Callable[[], QuerySet | list[Person]] = lambda: _fetch_persons_by_uuids_via_personhog(
+ team_id, uuids, distinct_id_limit=distinct_id_limit
+ )
orm_fn: Callable[[], QuerySet | list[Person]] = lambda: Person.objects.db_manager(READ_DB_FOR_PERSONS).filter(
team_id=team_id, uuid__in=uuids
)
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index 705dc1027b30..8ee1003e284b 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -676,7 +676,8 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
from products.cohorts.backend.models.util import insert_static_cohort
- persons = get_persons_by_uuids(team_id, batch)
+ # Cohort membership only needs id/uuid, so skip the unbounded per-person distinct-id fetch.
+ persons = get_persons_by_uuids(team_id, batch, distinct_id_limit=0)
if not persons:
return