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(persons): parallelize personhog uuid lookups (opt-in) and use it for freeze experiments (#70353)

Marcel Poelkereb43503ca6e4
diff --git a/posthog/models/person/test/test_batched_personhog_helpers.py b/posthog/models/person/test/test_batched_personhog_helpers.py
index d1206e26221c..2566527acaa5 100644
--- a/posthog/models/person/test/test_batched_personhog_helpers.py
+++ b/posthog/models/person/test/test_batched_personhog_helpers.py
@@ -102,6 +102,56 @@ class TestBatchedGetPersonsByUuids(SimpleTestCase):
assert len(result) == 1
assert result[0].uuid == "uuid-1"
+ @patch("posthog.models.person.util.TEST", False)
+ @patch("posthog.models.person.util.PERSONHOG_BATCH_SIZE", 2)
+ def test_parallel_fan_out_returns_all_batches_in_order(self):
+ with fake_personhog_client() as fake:
+ for i in range(9):
+ fake.add_person(team_id=1, person_id=i + 1, uuid=f"uuid-{i}", distinct_ids=[f"d{i}"])
+
+ result = _batched_get_persons_by_uuids(1, [f"uuid-{i}" for i in range(9)], "test", concurrency=4)
+
+ assert [p.uuid for p in result] == [f"uuid-{i}" for i in range(9)]
+ fake.assert_called("get_persons_by_uuids", times=5)
+
+ @patch("posthog.models.person.util.TEST", False)
+ @patch("posthog.models.person.util.PERSONHOG_BATCH_SIZE", 2)
+ def test_parallel_fan_out_propagates_batch_failure(self):
+ # A failing batch must fail the whole call — collecting only the successful futures
+ # would hand callers (e.g. the freeze-exposure guard) a silently partial result.
+ with fake_personhog_client() as fake:
+ for i in range(6):
+ fake.add_person(team_id=1, person_id=i + 1, uuid=f"uuid-{i}", distinct_ids=[f"d{i}"])
+
+ original_get = fake.get_persons_by_uuids
+
+ def fail_second_batch(request):
+ if "uuid-2" in request.uuids:
+ raise RuntimeError("batch failed")
+ return original_get(request)
+
+ with (
+ patch.object(fake, "get_persons_by_uuids", side_effect=fail_second_batch),
+ self.assertRaises(RuntimeError),
+ ):
+ _batched_get_persons_by_uuids(1, [f"uuid-{i}" for i in range(6)], "test", concurrency=4)
+
+ @patch("posthog.models.person.util.TEST", False)
+ @patch("posthog.models.person.util.PERSONHOG_BATCH_SIZE", 2)
+ def test_default_concurrency_stays_sequential(self):
+ # The fan-out is opt-in: without an explicit concurrency, even a multi-batch call must
+ # not spawn threads — most callers are small or background lookups whose load on the
+ # personhog bulk pools must not silently multiply.
+ with fake_personhog_client() as fake:
+ for i in range(6):
+ fake.add_person(team_id=1, person_id=i + 1, uuid=f"uuid-{i}", distinct_ids=[f"d{i}"])
+
+ with patch("posthog.models.person.util.ThreadPoolExecutor") as mock_executor:
+ result = _batched_get_persons_by_uuids(1, [f"uuid-{i}" for i in range(6)], "test")
+
+ assert [p.uuid for p in result] == [f"uuid-{i}" for i in range(6)]
+ mock_executor.assert_not_called()
+
class TestBatchedGetPersonsByDistinctIds(SimpleTestCase):
@parameterized.expand(
diff --git a/posthog/models/person/util.py b/posthog/models/person/util.py
index 28c83b71d79a..3ee73f391594 100644
--- a/posthog/models/person/util.py
+++ b/posthog/models/person/util.py
@@ -2,6 +2,8 @@ from __future__ import annotations
import json
import datetime
+import contextvars
+from concurrent.futures import ThreadPoolExecutor
from typing import TYPE_CHECKING, Optional, Union
from uuid import UUID
from zoneinfo import ZoneInfo
@@ -52,31 +54,73 @@ if TYPE_CHECKING:
_get_client = require_personhog_client
+def _get_persons_for_uuid_batch(
+ client: PersonHogClient,
+ team_id: int,
+ batch: list[str],
+ operation: str,
+ read_options: ReadOptions | None,
+) -> list[person_pb2.Person]:
+ resp = client.get_persons_by_uuids(
+ GetPersonsByUuidsRequest(team_id=team_id, uuids=batch, read_options=read_options)
+ )
+
+ present_persons = [p for p in resp.persons if p.id]
+ batch_valid = [p for p in present_persons if p.team_id == team_id]
+
+ mismatched = len(present_persons) - len(batch_valid)
+ if mismatched:
+ PERSONHOG_TEAM_MISMATCH_TOTAL.labels(operation=operation, client_name=get_client_name()).inc(mismatched)
+ logger.warning("personhog_team_mismatch", operation=operation, team_id=team_id, dropped=mismatched)
+
+ return batch_valid
+
+
def _batched_get_persons_by_uuids(
team_id: int,
uuids: list[str],
operation: str,
read_options: ReadOptions | None = None,
+ concurrency: int = 1,
) -> list[person_pb2.Person]:
- client = _get_client()
- valid_persons: list[person_pb2.Person] = []
- for i in range(0, len(uuids), PERSONHOG_BATCH_SIZE):
- batch = uuids[i : i + PERSONHOG_BATCH_SIZE]
- resp = client.get_persons_by_uuids(
- GetPersonsByUuidsRequest(team_id=team_id, uuids=batch, read_options=read_options)
- )
+ """Fetch persons for the given UUIDs, one RPC per PERSONHOG_BATCH_SIZE batch.
- present_persons = [p for p in resp.persons if p.id]
- batch_valid = [p for p in present_persons if p.team_id == team_id]
-
- mismatched = len(present_persons) - len(batch_valid)
- if mismatched:
- PERSONHOG_TEAM_MISMATCH_TOTAL.labels(operation=operation, client_name=get_client_name()).inc(mismatched)
- logger.warning("personhog_team_mismatch", operation=operation, team_id=team_id, dropped=mismatched)
-
- valid_persons.extend(batch_valid)
+ Sequential by default. Callers with large, latency-sensitive lookups opt into a
+ concurrent fan-out by passing ``concurrency`` — opt-in so the many small/background
+ callers of this helper don't multiply their load on the personhog bulk pools. Keep
+ opted-in values modest: each in-flight RPC can occupy up to 2 connections of a
+ replica's 5-connection bulk Postgres pool.
+ """
+ client = _get_client()
+ batches = [uuids[i : i + PERSONHOG_BATCH_SIZE] for i in range(0, len(uuids), PERSONHOG_BATCH_SIZE)]
+ max_workers = min(len(batches), concurrency)
- return valid_persons
+ if TEST or max_workers <= 1:
+ batch_results = [
+ _get_persons_for_uuid_batch(client, team_id, batch, operation, read_options) for batch in batches
+ ]
+ else:
+ # Fan the batch RPCs out over the shared (HTTP/2-multiplexed) channel. ThreadPoolExecutor
+ # doesn't inherit contextvars, so copy the current context per task to keep the personhog
+ # caller tag and log/query context on each RPC. Results are collected in batch order, and
+ # any batch failure propagates: callers (e.g. the freeze-exposure guard) rely on the result
+ # covering every requested batch, never a silently partial set.
+ with ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="personhog-uuid-batch") as executor:
+ futures = [
+ executor.submit(
+ contextvars.copy_context().run,
+ _get_persons_for_uuid_batch,
+ client,
+ team_id,
+ batch,
+ operation,
+ read_options,
+ )
+ for batch in batches
+ ]
+ batch_results = [future.result() for future in futures]
+
+ return [person for batch_valid in batch_results for person in batch_valid]
def _batched_get_persons_by_distinct_ids(
@@ -490,19 +534,24 @@ def validate_person_uuids_exist(team_id: int, uuids: list[str]) -> list[str]:
)
-def get_person_ids_and_uuids_by_uuids(team_id: int, uuids: list[str]) -> list[tuple[int, str]]:
+def get_person_ids_and_uuids_by_uuids(team_id: int, uuids: list[str], *, concurrency: int = 1) -> list[tuple[int, str]]:
"""Return (person_id, person_uuid) pairs for the given person UUIDs; unknown UUIDs are omitted.
Lightweight variant of ``get_persons_by_uuids`` — uses field masking to skip fetching
properties and other heavy fields, and never fetches distinct IDs. For callers that only
- need to resolve UUIDs to person IDs (e.g. cohort membership writes).
+ need to resolve UUIDs to person IDs (e.g. cohort membership writes). ``concurrency``
+ opts into the concurrent batch fan-out — see ``_batched_get_persons_by_uuids``.
"""
if not uuids:
return []
def personhog_fn() -> list[tuple[int, str]]:
persons = _batched_get_persons_by_uuids(
- team_id, uuids, "get_person_ids_and_uuids_by_uuids", read_options=_UUID_ONLY_READ_OPTIONS
+ team_id,
+ uuids,
+ "get_person_ids_and_uuids_by_uuids",
+ read_options=_UUID_ONLY_READ_OPTIONS,
+ concurrency=concurrency,
)
return [(p.id, p.uuid) for p in persons]
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 806c22a93a0d..3f839cad3473 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -134,6 +134,11 @@ FREEZE_EXPOSURE_MAX_EXPOSED_USERS = 100_000
# silently lose their variant at freeze time. A small unresolvable share is tolerated as
# deletion/merge noise; beyond this share the freeze is rejected as unable to keep its promise.
FREEZE_EXPOSURE_MAX_UNRESOLVED_SHARE = 0.05
+# Concurrent personhog batch lookups while resolving the exposed set. Deliberately modest: each
+# in-flight RPC can occupy up to 2 connections of a replica's 5-connection bulk Postgres pool, so
+# higher values mostly move the queue server-side. Sized like the other request-path fan-outs
+# (e.g. RUN_WIDGETS_QUERY_CONCURRENCY); 1 falls back to fully sequential resolution.
+FREEZE_EXPOSURE_RESOLVE_CONCURRENCY = 4
# Shared by snapshot creation and cleanup: cleanup only touches cohorts carrying this prefix, so a
# cohort id stamped into the (user-editable) flag filters can't point it at an arbitrary cohort.
FREEZE_EXPOSURE_SNAPSHOT_NAME_PREFIX = "Exposure snapshot for experiment "
@@ -2075,7 +2080,12 @@ class ExperimentService:
unchanged from insert-time resolution (their distinct_id no longer resolves to a cohort
member either way), and the cohort stays consistent with the count this guard approved.
"""
- resolved_person_pairs = get_person_ids_and_uuids_by_uuids(self.team.id, person_uuids)
+ # Opt into the concurrent personhog batch fan-out: the exposed set is large (up to
+ # FREEZE_EXPOSURE_MAX_EXPOSED_USERS) and this resolve runs inline in the web request,
+ # so sequential per-batch round trips would dominate the freeze duration.
+ resolved_person_pairs = get_person_ids_and_uuids_by_uuids(
+ self.team.id, person_uuids, concurrency=FREEZE_EXPOSURE_RESOLVE_CONCURRENCY
+ )
unresolved_count = len(person_uuids) - len(resolved_person_pairs)
if unresolved_count == 0:
return resolved_person_pairs
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 8a60d5ae7542..e9d84ec6569a 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -3253,7 +3253,9 @@ class TestExperimentService(APIBaseTest):
# the personless guard doesn't reject these unrelated scenarios.
patch(
"products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",
- new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],
+ new=lambda team_id, uuids, **kwargs: [
+ (index + 1, person_uuid) for index, person_uuid in enumerate(uuids)
+ ],
),
patch(
"products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_id_uuid_pairs_skip_validation",
@@ -3592,7 +3594,7 @@ class TestExperimentService(APIBaseTest):
patch.object(ExperimentService, "_fetch_exposed_person_uuids", return_value=uuids),
patch(
"products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",
- new=lambda team_id, batch: [
+ new=lambda team_id, batch, **kwargs: [
(index + 1, person_uuid) for index, person_uuid in enumerate(batch[unresolved:])
],
),
@@ -3629,7 +3631,9 @@ class TestExperimentService(APIBaseTest):
),
patch(
"products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",
- new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],
+ new=lambda team_id, uuids, **kwargs: [
+ (index + 1, person_uuid) for index, person_uuid in enumerate(uuids)
+ ],
),
patch(
"products.cohorts.backend.models.cohort.Cohort._insert_resolved_batch",
@@ -3743,7 +3747,9 @@ class TestExperimentService(APIBaseTest):
patch.object(ExperimentService, "_fetch_exposed_person_uuids", side_effect=concurrent_change_then_return),
patch(
"products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",
- new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],
+ new=lambda team_id, uuids, **kwargs: [
+ (index + 1, person_uuid) for index, person_uuid in enumerate(uuids)
+ ],
),
patch(
"products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_id_uuid_pairs_skip_validation",
@@ -3781,7 +3787,9 @@ class TestExperimentService(APIBaseTest):
patch.object(ExperimentService, "_fetch_exposed_person_uuids", side_effect=concurrent_edit_then_return),
patch(
"products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",
- new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],
+ new=lambda team_id, uuids, **kwargs: [
+ (index + 1, person_uuid) for index, person_uuid in enumerate(uuids)
+ ],
),
patch(
"products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_id_uuid_pairs_skip_validation",
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 32bf80605425..111a81578bad 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -5529,7 +5529,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
)
@patch(
"products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",
- new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],
+ new=lambda team_id, uuids, **kwargs: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],
)
@patch(
"products.experiments.backend.experiment_service.ExperimentService._fetch_exposed_person_uuids",
@@ -5561,7 +5561,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
)
@patch(
"products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",
- new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],
+ new=lambda team_id, uuids, **kwargs: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],
)
@patch(
"products.experiments.backend.experiment_service.ExperimentService._fetch_exposed_person_uuids",
@@ -5584,7 +5584,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
)
@patch(
"products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",
- new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],
+ new=lambda team_id, uuids, **kwargs: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],
)
@patch(
"products.experiments.backend.experiment_service.ExperimentService._fetch_exposed_person_uuids",