: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
chore(docs): document personhog vs clickhouse person data access (#92002)
Nick Best07fd1e03707a
diff --git a/AGENTS.md b/AGENTS.mdindex a5118924dee2..ff511901105c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -196,6 +196,7 @@ See [.agents/security.md](.agents/security.md) for security guidelines — least- **PostHog event capture in Celery tasks:** Do not use `posthoganalytics.capture()` in Celery tasks — events are silently lost. Use `ph_scoped_capture` from `posthog.ph_client` instead (see its docstring for why and usage).- **Django admin `ForeignKey` fields need explicit widget config.** When adding a `ForeignKey`/`OneToOneField` to a model that's exposed in Django admin (including via inlines attached to a _related_ admin), list the new field in `autocomplete_fields`, `raw_id_fields`, or `readonly_fields` on **every** admin class that renders the model — otherwise the default `<select>` widget loads the entire target table per row on each change-page render. Prefer declaring the config on a shared base inline so per-parent variants (e.g., subclasses differentiated by `fk_name`) inherit it automatically.- **Use personhog client for all person/group data access — do not query persons DB tables via the Django ORM or raw SQL.** The `posthog/personhog_client/` gRPC client is the required interface for reading and writing person-related data. This applies to the following tables: `posthog_person`, `posthog_persondistinctid`, `posthog_cohortpeople`, `posthog_group`, `posthog_grouptypemapping`, and related override tables (`posthog_personoverride`, `posthog_pendingpersonoverride`, `posthog_flatpersonoverride`, `posthog_featureflaghashkeyoverride`, `posthog_personlessdistinctid`, `posthog_personoverridemapping`). Use the helpers in `posthog/models/person/util.py` (e.g. `get_person_by_uuid`, `get_persons_by_distinct_ids`, `get_person_by_distinct_id`) and `posthog/models/group_type_mapping.py` (`get_group_types_for_project`) — these already route through personhog with ORM fallback via `_personhog_routed()`. When adding new person/group data access, follow the same `_personhog_routed()` pattern: provide a `personhog_fn` using `get_personhog_client()` and an `orm_fn` fallback. Never add new direct ORM queries like `Person.objects.filter(...)` or `PersonDistinctId.objects.filter(...)` — use the existing routed helpers or create new ones following the established pattern. See `posthog/personhog_client/README.md` for client details and `posthog/personhog_client/client.py` for the full RPC interface.+- **Personhog is for identity questions only; person properties and bulk person reads come from ClickHouse.** Use personhog for resolving distinct IDs to persons, point lookups by person id/UUID, and lifecycle writes. Use ClickHouse (HogQL over the `persons` table, `ActorsQueryRunner`) for loading person properties, hydrating lists of persons, and searching/filtering persons. Avoid reading the `properties` field from personhog where possible — the API will eventually stop surfacing it to users; single-person point lookups that need properties are exempt only while no ClickHouse primitive covers them, and never in bulk. See [docs/internal/person-data-access.md](docs/internal/person-data-access.md).- **PostHog does not enable `ATOMIC_REQUESTS` — there is no implicit per-request transaction.** Each database operation runs in autocommit mode unless explicitly wrapped. Use `with transaction.atomic():` around the specific writes that must succeed or fail together. Do not wrap an entire view method atomically — keep the block as narrow as possible around the related writes. Avoid performing irreversible side effects (sending emails, calling external APIs, enqueuing Celery tasks) inside an atomic block: if the transaction rolls back, those side effects have already happened. Schedule such side effects after the commit, or use `transaction.on_commit()` for Celery task dispatch.- **Object storage is SeaweedFS — do not add new MinIO dependencies.** Both S3-compatible stores in the dev/CI stack are SeaweedFS: the `objectstorage` service (S3 API on `:19000`) backs general object storage (`OBJECT_STORAGE_*` settings — exports, media uploads, error-tracking source maps, query cache, tasks), and the `seaweedfs` service (S3 API on `:8333`) backs session replay v2 (`SESSION_RECORDING_V2_S3_*` settings). MinIO now survives only as migration tooling: `docker-compose.hobby.yml` keeps it as a source for `bin/migrate-storage-hobby`, and `bin/upgrade-objectstorage` starts a throwaway MinIO to salvage objects off the pre-swap volume. Outside that, don't add docker-compose services, scripts, tests, or docs that stand up a `minio/minio` container. Code that talks to object storage should go through the existing `OBJECT_STORAGE_*` / `SESSION_RECORDING_V2_S3_*` config and a standard S3 client rather than hardcoding an endpoint — that keeps backends swappable. Note the `objectstorage` service registers its credentials at runtime via a bootstrap loop and returns `InvalidAccessKeyId` until that completes, so anything depending on it must wait for its readiness sentinel rather than just for the container to start.- **Temporal activity payloads have a ~2 MiB hard limit — pass large data by reference, not by value.** Activity inputs and outputs are serialized across a gRPC boundary that Temporal caps at ~2 MiB per payload (the server rejects larger payloads via `blobSizeLimitError`). As a conservative field-level rule, if a field could exceed ~256 KB once serialized (serialized query results, exported file contents, LLM context, rendered HTML, image bytes, unbounded `list[dict[str, Any]]`), write it to Postgres / S3 / object storage from _inside_ the activity and return only the reference (row ID, S3 key). The workflow already has access to any row ID created earlier in the same run; it does not need the content to flow back through. Shuttling large data through the workflow on the way to persistence is a foreseeable failure mode that produces `PayloadSizeError` (`TMPRL1103`) the moment the underlying data crosses the limit.diff --git a/docs/internal/person-data-access.md b/docs/internal/person-data-access.mdnew file mode 100644index 000000000000..e9676ef69bc4--- /dev/null+++ b/docs/internal/person-data-access.md@@ -0,0 +1,64 @@+# Person data access: personhog vs ClickHouse++Django has two ways to read person information, and they are not interchangeable.+This doc says which source to use for what, and why.+It applies to all new code; some existing paths predate these rules and are noted as legacy below.++## The rules++**Use the personhog API for identity questions only:**++- Resolving distinct IDs to persons (`get_person_by_distinct_id`, `get_persons_by_distinct_ids`).+- Point lookups of a single person, or a small known set, by id or UUID (`get_person_by_uuid`, `get_person_by_id`, `validate_person_uuids_exist`).+- Person lifecycle writes: deletes, splits, cohort membership, hash key overrides.++**Use ClickHouse for everything property-shaped or bulk-shaped:**++- Loading person properties, whether for one person or many.+- Bulk lookups: hydrating a list of persons for display or export.+- Searching, filtering, and sorting persons (by property, cohort, or anything else).++The ClickHouse entry points are HogQL queries over the `persons` table and `ActorsQueryRunner` (`posthog/hogql_queries/actors_query_runner.py`).+Do not query ClickHouse person tables with raw SQL; go through HogQL.++**Avoid reading `properties` from personhog wherever possible.**+The long-term direction is for the personhog API to not surface the properties field to users at all.+If your code needs a person's properties, get them from ClickHouse, even when you already have the person's identity from personhog.++The current exemption: there is no sanctioned primitive yet for "look up one person and get its properties" from ClickHouse, so some existing paths read properties off a personhog point lookup (for example the person detail endpoint, flag test evaluation, and single-person reads in conversations and replay).+These are tolerated until that primitive exists, but do not extend the pattern to bulk reads, and prefer the ClickHouse route when one is available for your case (see `build_person_properties_at_time` in `posthog/models/person/point_in_time_properties.py` for an example of identity-from-personhog, properties-from-ClickHouse).++## Why the split++Personhog is the source of truth for identity: which person a distinct ID maps to right now, whether a person exists, and which distinct IDs belong to it.+It is Postgres-backed and read-after-write consistent, which is what identity decisions need.+But it serves point lookups over gRPC, so hauling large property JSON blobs through it is expensive and does not scale to bulk reads.++ClickHouse is the analytical store.+It is built for scanning, filtering, and returning many rows with their properties in one query, and every insight already reads persons from it.+Its person data lands asynchronously, so it can lag ingestion by a short window — acceptable for displaying and searching properties, not acceptable for deciding who a distinct ID belongs to.++So the split follows the shape of the question:++| Question | Source |+| -------------------------------------------------- | ---------- |+| Which person is this distinct ID? | personhog |+| Does this person UUID exist? What are its IDs? | personhog |+| What are this person's properties? | ClickHouse |+| Which persons match this filter/search? | ClickHouse |+| Give me these 500 persons with their properties | ClickHouse |+| Delete/split this person, change cohort membership | personhog |++## Legacy paths++Some code still hydrates person properties through personhog and is migrating toward ClickHouse:++- `PersonStrategy.get_actors` (`posthog/hogql_queries/actor_strategies.py`) fetches properties via personhog after ClickHouse has selected the actor UUIDs.+- `get_serialized_people` (`posthog/queries/actor_base_query.py`), used by the persons list API.++Do not copy these patterns into new code: bulk hydration of persons with properties always belongs in ClickHouse.++## Related docs++- [`posthog/personhog_client/README.md`](../../posthog/personhog_client/README.md) — client usage, routed helpers, testing with the fake client.+- Direct ORM or raw SQL access to person tables is banned entirely; the personhog client README lists the covered tables.diff --git a/posthog/personhog_client/README.md b/posthog/personhog_client/README.mdindex 99b4fd97622c..24158d4caa40 100644--- a/posthog/personhog_client/README.md+++ b/posthog/personhog_client/README.md@@ -13,6 +13,17 @@ Routed helpers that handle the gRPC call and metrics already exist inWhen no existing helper covers your needs, follow the `_personhog_routed()` pattern in `posthog/models/person/util.py`.personhog is the sole read path — there is no ORM fallback.+## Scope: identity questions only++Personhog is for **identity resolution and point lookups**: resolving a distinct ID to a person, checking a person exists, fetching a single person (or a small known set) by id or UUID, and lifecycle writes (deletes, splits, cohort membership).++It is **not** for property-shaped or bulk-shaped reads.+Loading person properties, hydrating lists of persons, and searching or filtering persons all belong in ClickHouse (HogQL over the `persons` table, `ActorsQueryRunner`).+Avoid reading the `properties` field from personhog where possible — the long-term direction is for the API to not surface it to users at all.+Single-person point lookups that need properties are currently exempt where no ClickHouse primitive exists for them; do not extend that to bulk reads.++See [docs/internal/person-data-access.md](/docs/internal/person-data-access.md) for the full guidelines and rationale.+## Database tablesThe following tables are managed by personhog.