PostHog Python SDK migration guides
Migrating from posthog 7.x to 8.0
posthog 8.0 sends every event through capture v1 and removes the legacy capture path. Most apps upgrade without code changes. Read the checklist first, then the sections that apply to you.
For the changes every capture v1 SDK shares, such as event options, limits and per-event results, see Upgrading to capture v1 SDKs.
Checklist
You need to change code if your app does any of these:
- passes
ClientorAsyncPosthogconstructor arguments by position afterhost - calls
posthog.request.postorposthog.request.flagswith positional arguments afterpathorhost - sets
$exception_levelor another reserved exception property incapture_exception(properties=...) - sets
capture_mode,POSTHOG_CAPTURE_MODEorgzip - imports
CaptureMode,posthog.capture_mode,CaptureV1Error,posthog.capture_v1,request.batch_post,EVENTS_ENDPOINTorAI_EVENTS_ENDPOINT - sends events to a self-hosted PostHog that does not serve the capture v1 endpoints
- sends events through a proxy that redirects capture requests to another host
- reuses one event
uuidfor more than one event - sets
$process_person_profileto turn person processing on for events without a distinct ID - passes strings such as
"true"for$cookieless_mode,$ignore_sent_ator$process_person_profile - expects
super_propertiesto override properties passed to a single call, including$setand$groups - sets
$is_server,$geoip_disableor a system property such as$osand expects the SDK's value to win - tests the AI integrations with a mock client and asserts on
capture - passes its own client object to the AI integrations
- sets
$libor$lib_version, or filters on$lib = "posthog-python-mcp" - passes a personal API key (
phx_...) as the project API key - reads event content from the SDK's debug log
- calls
alias()without adistinct_idand relies on the context distinct ID - runs the Django, Flask or ASGI integration on 7.68 to 7.70 without tracing headers turned on (they are now read by default)
Endpoints
| Method | Endpoint |
|---|---|
capture, set, set_once, alias, group_identify, capture_exception | /i/v1/analytics/events |
capture_ai, capture_ai_immediate, and the AI wrapper integrations | /i/v1/ai/events |
OpenTelemetry (posthog.ai.otel) | /i/v0/ai/otel, unchanged |
If you send events to a self-hosted PostHog, check that it serves both endpoints before you upgrade. An endpoint that is not served drops every event sent to it.
If you send events through your own reverse proxy, update it before you upgrade:
- Forward
/i/v1/analytics/eventsand/i/v1/ai/eventsto PostHog. - Pass
Authorization(the project token, sent asBearer <token>), everyPostHog-*header,Content-Type,Content-EncodingandUser-Agentthrough unchanged. PostHog answers401withoutAuthorizationand400without the others, and the batch fails. - Accept request bodies up to 20 MB. AI requests are often larger than 1 MB, the default limit in nginx and ingress-nginx. A
413from the proxy fails the batch.
PostHog's managed reverse proxy already does this. See the proxy guides.
The SDK follows a 307 or 308 redirect only to the origin of host (same scheme, host and port), at most 5 times.
Any other redirect fails the batch and reaches on_error.
In 7.x the sync client followed redirects to any origin.
If a proxy redirects capture requests to another host, point host at the final host.
SDK identity
PostHog sets $lib and $lib_version on every event from the PostHog-Sdk-Info request header, which is always posthog-python/<version>.
The SDK removes $lib and $lib_version from the properties it sends.
A value you set in a call, in super_properties or in before_send does not reach PostHog.
MCP instrumentation no longer relabels the client.
In 7.x, posthog.mcp.instrument() and PostHogMCP set the client's identity to posthog-python-mcp.
With the default client, or any client the app also used, every event and feature flag request from the app then reported posthog-python-mcp, not only the MCP events.
In 8.0, MCP events report posthog-python like all other events.
To find MCP traffic, filter on the $mcp_* events and properties instead of $lib.
Removed options and APIs
| Removed | Use instead |
|---|---|
capture_mode, CaptureMode, POSTHOG_CAPTURE_MODE | Nothing. Capture v1 is the only path. Setting posthog.capture_mode on the module has no effect. |
gzip=True | capture_compression=CaptureCompression.GZIP. The default is no compression. POSTHOG_CAPTURE_COMPRESSION still works. |
CaptureV1Error (from posthog.capture_v1 import CaptureV1Error) | CaptureError (from posthog import CaptureError). There is no alias. |
posthog.capture_v1 | posthog.capture_event and posthog.capture_send |
request.batch_post, async_batch_post, EVENTS_ENDPOINT, AI_EVENTS_ENDPOINT | Nothing. Send events through a client. |
The gzip parameter of request.post and request.flags | Nothing. The parameters after path in post and after host in flags are keyword-only, so a 7.x call that passes them by position raises TypeError. A gzip= keyword raises no error: it is sent as a field in the request body. |
The backoff dependency | Add it to your own requirements if your code imports it. |
The posthoganalytics package has the same changes. For example, import CaptureError from posthoganalytics.
Constructor arguments after host are keyword-only:
Errors and on_error
Capture v1 returns a result for every event, even when the request succeeds.
An event can be dropped inside a 2xx response, for example when it is over a product quota.
8.0 reports those events as failures.
When the whole request is over the billing limit, capture returns a 402 with no per-event results instead.
- Every capture failure is a
CaptureError, a subclass ofAPIError. It has these fields:status: the HTTP status, or0when the request never got a response. With0,__cause__holds the network error. In 7.x,on_errorreceived the rawrequestsexception.endpoint,request_idandattemptsdrops:(uuid, details)pairs for the events capture dropped in a 2xx responseretry_exhausted: the uuids still waiting for a retry after the last attemptevent_results: aCaptureEventResult(result, details)for each uuid that got a result in a 2xx response, fromposthog.capture_send. An event missing from it never got a result.verdict_summary(): counts such asdrop/llm_events_over_quota=1, retry/not_persisted=1
on_error(error, batch)receives every failure, including insync_modeand fromAsyncPosthog.capture_immediate.- With
on_errorset, the SDK logs nothing for a failed batch. - Without
on_error, the SDK logs one line per failed batch, for example2 event(s) not persisted by /i/v1/analytics/events: .... The line never contains event content or the server's response text. After a 2xx response it also counts the lost events by PostHog's reason, for exampledrop/event_too_big=1. - The 7.x lines
error uploading: ...,async capture upload failed (...)andImmediate async capture failed (...)are gone. Insync_mode, a failed request no longer logs the 7.xError in capture: ...line, or the same line for another method. Update any log-based alerts that match these lines. - In
sync_mode, a failedcapture()callson_errorand returnsNone. Withdebug=Trueit callson_errorand then re-raises the error. - In
sync_mode, a failed request is retried like a background batch, in the calling thread. With the defaultmax_retriesof 3, a call makes up to 4 attempts, and each attempt can take up totimeout(capture_ai_timeoutfor AI events). With the defaults, an analytics event whose requests keep timing out blocks the call for about a minute. 7.x made one attempt. - If a capture inside
on_errorfails, the SDK logs the failure and does not callon_erroragain. - The SDK retries
404,408,429,500,502,503and504responses and network errors. Other error statuses fail the batch at once, including the other 5xx codes. 7.x retried429and every 5xx, but not404. Capture itself does not return429; a proxy in front of it can. A404that lasts through every attempt can mean the PostHog deployment has no capture v1 route, for example an older self-hosted install. - Each attempt makes one connection try. 7.x also retried a failed connection up to twice inside each attempt, so a capture request could block for up to three times the
timeoutper attempt. - Retries start at 100 ms and double each attempt, up to 30 seconds. Each wait varies randomly by up to 25%, so many clients do not retry at the same moment. A
Retry-Afterheader sets a minimum wait, up to 30 seconds. TheConsumerdefault is 3 retries, down from 10. In 7.x the first retry waited up to 1 second. - The SDK's own log lines no longer contain event content: the debug line for a queued event names the event and the lane, and the invalid timestamp warning no longer includes the value. When your
before_sendhook raises, the error line names the event and the exception type, not the exception message, which can hold the data the hook was removing. The traceback is logged at debug level. To inspect events, usebefore_send. - A personal API key (
phx_...) passed as the project API key disables the client and logs one error, as an empty key does. Capture rejects personal API keys, and the SDK no longer sends one with every request.
Invalid events
Capture rejects a whole batch when one event cannot be parsed. 8.0 drops only the invalid event, so the rest of the batch is delivered.
- An event whose name is missing,
None, empty or not a string is dropped. The SDK logs one warning per reason per process. 7.x sent it. - An event whose
before_sendhook setsdistinct_idtoNoneor a non-string is dropped, with one warning per reason per process. The SDK does not convert the hook's value or make up an ID. 7.x sent it, and capture would reject the whole batch. - PostHog drops an event whose name is over 200 UTF-8 bytes (
event_name_too_long), andon_errorreports it. 7.x sent events to legacy capture, which had no event name limit. - A
NaNor infinitefloatvalue is sent asnull, as in 7.75 and later, and the event is kept. Earlier 7.x versions sent invalid JSON, which made capture reject the whole batch. ANaNvalue in$setsets that person property tonull. - An event that cannot be serialized to JSON, for example one with a circular reference, is dropped and logged. As in 7.x, a circular reference logs
Error in capture: maximum recursion depth exceededwith a long traceback. - A property or option key that JSON cannot represent, such as a tuple, is dropped without a log, and the rest of the event is sent. 7.x dropped the event.
int, finitefloat,boolandNonekeys are still converted to strings. ANaNor infinitefloatkey still drops the event.
Event uuids
- Each event needs its own uuid. Capture keeps the first event for each uuid in a request and drops the later copies.
on_errorreports each dropped copy inCaptureError.dropsas(uuid, "duplicate_event_uuid"). 7.x sent every copy. Older PostHog versions reject the whole batch with a 400duplicate_event_uuidinstead. - The SDK accepts a uuid with hyphens, 32 hex digits,
{...}braces or aurn:uuid:prefix, in any case. It sends the lowercase hyphenated form and returns that form fromcapture. - Any other value is replaced with a generated uuid, and the SDK logs one warning that names the rule, not the value. An empty string counts as unset, so the SDK generates a uuid without a warning. This applies to
AsyncPosthogtoo. - Generated uuids are UUIDv7.
Session and window IDs
Capture v1 sends $session_id and $window_id as top-level event fields, not as properties.
The SDK moves them out of properties for you.
- A string is sent as given, including
"". Nonecounts as unset and is removed.- Any other value is removed and not sent, because capture would reject the whole batch. 7.x sent it as a property. The SDK logs a warning for each one, with the key and the value's type but not the value.
Identity and request context
- An empty or whitespace-only
distinct_idcounts as missing, so the event gets a generated personless distinct ID. 7.x sent a whitespace-only ID, and capture dropped the event. - Generated personless distinct IDs are UUIDv7. 7.x generated UUIDv4.
group_identifyuses thedistinct_idyou pass, then the context distinct ID, then$<group_type>_<group_key>. 7.x fell back to a random ID, which created a new person on every call. If$<group_type>_<group_key>is over 200 bytes, passdistinct_id: PostHog drops an event whose distinct ID is over 200 bytes.- PostHog drops an event whose
distinct_idis over 200 UTF-8 bytes (distinct_id_too_large), andon_errorreports it. 7.x sent events to legacy capture, which shortened the ID to 200 characters and kept the event. group_identifyno longer adds the context session ID. A session takes the person of its latest event, and this event's distinct ID is not the session's user.alias()needs an explicitdistinct_id. It no longer falls back to the context distinct ID, which can come from a request header the client controls. Without one, the call is dropped with a warning.- Context tags and context options now apply to
aliasandgroup_identify, below the call's own values, as they do forcapture. - Person processing turned off in the context, with
set_context_option("process_person_profile", False)or a$process_person_profiletag, or insuper_options, now applies to$create_aliasand$groupidentifyevents too. A$process_person_profile: Falseinsuper_propertiesalready did this in 7.x. PostHog drops these events when person processing is off, with an ingestion warning. Capture accepts them, soon_errordoes not report the drop. To keep them, turn person processing off per call instead.
Tracing headers
The Django, Flask and ASGI integrations read the X-PostHog-Distinct-Id and X-PostHog-Session-Id headers by default, as in 7.71 and later.
The headers only fill a missing distinct ID or session ID, and any client can set them, so never use them for authentication.
- To turn this off, set
POSTHOG_MW_CAPTURE_TRACING_HEADERS = Falsein Django, or passcapture_tracing_headers=Falseto the Flask or ASGI integration. - The 7.68
trust_tracing_headersandPOSTHOG_MW_TRUST_TRACING_HEADERSnames still work, but are deprecated. - If you upgrade from 7.68, 7.69 or 7.70 and never turned these headers on, they are now read.
Exceptions
capture_exceptiontakes alevel=argument onClient,AsyncPosthogand the module. It sets$exception_level, for example"warning"or"fatal". The default is"error", and an unknown value counts as unset.capture_exceptionignores reserved exception properties inproperties, such as$exception_list,$exception_leveland$exception_source. In 7.x they overrode the SDK's values, with aDeprecationWarning. Uselevel=instead of$exception_level.AsyncPosthog.capture_exceptionnow sends$exception_level.AsyncPosthog.capture_exceptionnow adds$trace_idand$span_idfrom the active OpenTelemetry span, likeClient.capture_exception. In 7.x it added them only withcapture_trace_context=True.
Event options
Capture v1 sends processing options in an options object, next to properties.
-
capture,capture_ai,set,set_once,alias,group_identifyandcapture_exceptiontake anoptionsargument:Python -
super_options, a newClient,AsyncPosthogand module setting, sets options on every event, likesuper_properties. -
set_context_option(key, value)sets an option for the current context, liketag().get_context_options()returns the options of the current context. Both exist onClientand as module functions.AsyncPosthoghas no context methods, like it has notag(), so call the module functions. They apply to every client in the context. -
Context tags and options reach
capture,capture_ai,capture_exception,aliasandgroup_identify. Context options also reachsetandset_once.super_propertiesandsuper_optionsreach every method. -
Options are sent as given. PostHog validates them. It drops an event with an option value it cannot read, such as a list for
cookieless_mode, asinvalid_options, andon_errorreports it. -
An
optionsvalue that is not a dict is logged as an error and ignored. The event is still sent. -
The legacy option properties, the
$-prefixed properties legacy capture reads as settings, still work. They fill the matching option only when it is unset, and the SDK always removes them fromproperties. Their values are no longer converted, so passTrueorFalse, not"true".Legacy option property Option $cookieless_modecookieless_mode$ignore_sent_atdisable_skew_correction$product_tour_idproduct_tour_id$process_person_profileprocess_person_profile -
An option set at any layer wins over its legacy property set at any layer. For example,
super_options={"cookieless_mode": True}wins over an event's$cookieless_mode: False. When you move a default to options, move the per-event overrides of that key to options too. -
A
Noneoption counts as unset, so a later step can fill it.
Values apply in this order. Steps 2 to 4 fill only the options and properties that the steps before them left unset:
- the
optionsandpropertiesof the call, then the call'sdisable_geoipargument, which fills$geoip_disable - context options and tags
super_optionsandsuper_properties- values the SDK sets:
$is_serverfromis_server,$geoip_disablefrom the client'sdisable_geoipsetting, system properties such as$osand$python_version, the$feature/<key>and$active_feature_flagsproperties fromflagsorsend_feature_flags,$trace_idand$span_idfrom the active OpenTelemetry span (incaptureandcapture_aionly withcapture_trace_context=True, and always incapture_exception),options.process_person_profile = falsefor events without a distinct ID, and$release_idfromPOSTHOG_RELEASE_ID before_send, which sees the result of steps 1 to 4 and can change or remove any of it- legacy properties, which fill unset options and are then removed
A property set to None counts as set, so no later step fills it.
$set, $set_once, $groups and $group_set fill one level deep.
When the call and a later step both set one of them to a dict, the later step adds only the keys the call left out.
For example, super_properties={"$set": {"plan": "free", "source": "web"}} and a call with properties={"$set": {"plan": "pro"}} send {"plan": "pro", "source": "web"}.
These changes follow from this order:
- Properties passed to a call now override
super_properties.super_propertiescan no longer change$libor$lib_version. - A
$is_server,$geoip_disableor system property such as$osthat you set in a call or a context tag now wins over the SDK's value. In 7.x the SDK overwrote it.super_propertieswin over the SDK's value too, sosuper_properties={"$geoip_disable": False}turns GeoIP lookup on for events, even withdisable_geoip=True. - Feature flag properties from
flagsorsend_feature_flagsstill lose to the same key in the call'sproperties, a context tag orsuper_properties, as in 7.x. - A
$trace_idor$span_idin a context tag orsuper_propertiesnow replaces the active OpenTelemetry span's IDs. In 7.x the span's IDs beat context tags. Setting either key in the call'sproperties, a context tag orsuper_propertiesstops the SDK adding both. In 7.x the SDK still added the other key. - A
disable_geoipargument to a call belongs to that event, so it wins over context tags andsuper_properties. A$geoip_disablein the call's ownpropertiesstill wins over it.disable_geoip=Falsenow sends$geoip_disable: false. In 7.x it sent no$geoip_disableproperty. - The
groupsargument merges into a$groupsproperty of the call, and wins key by key. In 7.x it replaced the property. MCP events merge their identity's groups into a custom$groupsproperty the same way. - A
$set,$set_once,$groupsor$group_setinsuper_propertiesno longer replaces the whole value of the call. The two merge, and the call wins key by key. - An event without a distinct ID gets
options.process_person_profile = false. A$process_person_profile: trueproperty no longer turns person processing back on. Set the option instead. - Review your
before_sendhooks for the new event shape. To change an option, editoptions: a legacy property thatbefore_sendadds does not replace an option that is already set. A hook that returns a new dict must copyoptions, or the event is sent without them. That includes theprocess_person_profile = falsethe SDK sets for an event without a distinct ID, so PostHog would create a person for its generated ID. - When the server enables minimal
$feature_flag_calledevents, those events now keep$window_idand the legacy option properties, so their options still apply.
AI capture
capture_aiand the AI wrapper integrations send to/i/v1/ai/events. The AI endpoint accepts events up to 8 MiB.- Send
$ai_events withcapture_ai.capture()sends every event to/i/v1/analytics/events, including$ai_events, which PostHog accepts there for now. capture_aisends any event name to the AI endpoint. PostHog drops an event whose name does not start with$ai_asmisrouted_event, andon_errorreports it. The SDK writes only a debug log.- The OpenTelemetry integration (
PostHogSpanProcessor,PostHogTraceExporter) is unchanged: it still exports spans over OTLP to/i/v0/ai/otel. enable_full_ai_capturenow controls only content: string truncation and media redaction. It no longer chooses the endpoint._use_ai_laneand_enable_multimodal_capturestill work as aliases.- The AI integrations call your client's
capture_ai, and nevercapture. A custom client object must implementcapture_aiand accept itsoptionskeyword argument. If the client has nocapture_ai, the wrapper, callback handler or tracing processor logs one error when you create it and captures no AI events; provider calls still work. Before, such a client gotcapturecalls. - Tests that pass a
Mockclient to an AI integration must assert onmock.capture_ai, notmock.capture. - When an AI integration or MCP falls back to a trace, run or session ID, it turns person processing off with a per-event option. This is the only option the integrations pass. It wins over
super_options, context options and a$process_person_profile: trueproperty.before_sendcan still change it. - An empty or whitespace-only distinct ID passed to an AI integration, such as
posthog_distinct_id="", counts as missing, so the integration falls back the same way and turns person processing off. In 7.x, an empty ID gave non-streaming wrapper calls a random personless ID. Streaming calls, embeddings and LangChain used the trace or run ID with person processing on. OpenAI Agents already treated an empty ID as missing. Every integration sent a whitespace-only ID as given, with person processing on. - The AI integrations have no
optionsargument. To set options on their events, useset_context_option,super_options, or a legacy property such as$cookieless_modeinposthog_properties. - MCP's
PostHogCaptureEventhas anoptionskey. - New
ClientandAsyncPosthogarguments for the AI lane:capture_ai_compression: default none.POSTHOG_CAPTURE_COMPRESSIONdoes not apply to it.capture_ai_max_queue_size: default 1000capture_ai_timeout: default 30 secondscapture_ai_max_event_bytes: default 8 MiB plus 64 KiB. You can only lower it.
- The AI lane does not use
max_queue_size,timeoutorcapture_compression. An invalidcapture_ai_*value raisesValueErrorwhen you create the client. - The module-level client has no AI lane settings. To change them, create a
Client. AsyncPosthoghascapture_aiandcapture_ai_immediate.AsyncPosthogsends events withrequestsin a worker thread. It useshttpxonly for feature flags and remote config.AsyncPosthogacceptsprivacy_modeandenable_full_ai_capture, with the same meaning as onClient. An AI integration given anAsyncPosthogclient used to always truncate and redact media.
Batching and size limits
- An analytics event over 10 MiB is dropped and logged, because no capture request can carry it. 7.x dropped events over 900 KiB. Capture drops an event over its own per-event limit and reports it in
CaptureError.dropsasevent_too_big. - An AI event over
capture_ai_max_event_bytesis dropped and logged. - A batch stops before an event that would take it past 5 MiB. A larger event is sent alone.
flush()andshutdown()drain the analytics and AI queues at the same time.
OpenFeature provider
openfeature-provider-posthog 0.2.0 works with posthog 7.x and 8.x.
Older provider versions require posthog below 8.0, so upgrade the provider before or with posthog.





