Migrate the Go SDK from 1.x.x to 2.0.0
The Go SDK 2.x.x sends every event to the capture v1 endpoints, /i/v1/analytics/events and /i/v1/ai/events.
Use the top right copy page button to work through this with your agents.
You don't need to make every change on the day you upgrade your SDK. Required changes fall in these categories:
- Before you upgrade: you should make these changes before you upgrade your SDK to 2.x.x.
- During your upgrade: These are changes that you need to make in the same PR that upgrades your SDK version.
- Follow ups: These are changes that can come in follow up PRs because 2.x.x has limited backward compatibility for methods that are to be deprecated.
Checklist
Read the checklist first, then the sections that apply to you. Many of these changes don't produce a compile error, so check every row even if your code builds unchanged.
Before you upgrade
- You send events through your own reverse proxy or API gateway → Prepare your proxy
- An egress allowlist or WAF rule pins the
/batch/path → Prepare your proxy - A proxy redirects capture requests → Prepare your proxy
- Something inspects, logs, or rewrites the request body to find the API key → Prepare your proxy
- You pass a personal API key (
phx_...) as the project API key → Use a project key - You send event names longer than 200 bytes → Check event names
During your upgrade
- You import
github.com/posthog/posthog-go,posthogmcp,posthogmcpsdk,posthogmcpgo, or theotelbridge → Change the import path - You call
posthog.New→ Handle constructor errors - You compare the text of
ErrSDKDisabled→ Handle constructor errors - You pass a nil
*posthogmcp.Analyticstoposthogmcpsdk, or an empty API key to theotelbridge → Handle constructor errors - You set
Config.CaptureMode,Capture.Library, orException.Library→ Fix removed APIs - You implement the
Clientinterface, for example in a test mock → Fix removed APIs - You compare
AliasorBackoffvalues with==, or use them as map keys → Fix removed APIs - You pass a value that isn't a string to
Groups.Set→ Convert group keys - You rely on the 500000-byte cap on one event → Check config values
- You set a negative timeout, size, or queue value in
Config→ Check config values - You set
Config.Compression, or something in your path expects the?compression=query parameter or thelz64orbase64encodings → Check config values - Your
BeforeSendhook returns a new message → Copy options in BeforeSend - You send an empty or whitespace-only
DistinctIdorAlias→ Fix identity calls - You send
Identify,Alias, orGroupIdentifywithEnqueueWithContext→ Fix identity calls - You set
GroupIdentify.DistinctId→ Fix identity calls - You turn person processing off in
DefaultEventOptions,DefaultEventProperties,RequestContext.Options, orRequestContext.Propertiesand send$identify,$create_alias,$merge_dangerously,$groupidentify,$set, or$set_onceevents → Check identify-style events - Your
BeforeSendhook builds or renames a$identify,$create_alias,$merge_dangerously,$groupidentify,$set, or$set_onceevent → Check identify-style events - You set
Uuidyourself, or reuse oneUuidfor more than one event → Check event IDs - You expect
DefaultEventPropertiesto override an event's properties, including$setand$groups→ Check property precedence - You set
$is_server,$geoip_disable, or a system property such as$os, and expect the SDK's value to win → Check property precedence - Your
BeforeSendhook adds properties to$feature_flag_calledevents → Check property precedence - You set
$trace_idor$span_idand useposthogotel.EnqueueWithContext→ Check property precedence - You set
$libor$lib_versionyourself → Check SDK identity - Your
Callback.Failurecompares errors with==, or expects only failed requests → Update error handling - You alert on SDK log lines, or read messages from the
Verboselog → Update error handling - You set a custom
Config.RetryAfter, or callDefaultBackoff()→ Update error handling - You set
$session_idor$window_idto a value that isn't a string → Check dropped events - You send
$performance_event,float32values, or types with a customMarshalJSON→ Check dropped events - You set an option, or a legacy option property like
$process_person_profile, to a value PostHog can't read, such as"maybe"→ Check dropped events - You read the text of event timestamps → Check timestamps
Follow ups
- You set legacy option properties like
$process_person_profile→ Move to event options - You send
$ai_events withEnqueue→ Send AI events with EnqueueAI - You use
posthogmcp,posthogmcpsdk, orposthogmcpgo→ Add MCP event options
Before you upgrade
Prepare your proxy
2.x.x sends events to these endpoints:
| Method | Endpoint |
|---|---|
Enqueue, EnqueueWithContext | POST /i/v1/analytics/events |
EnqueueAI, EnqueueAIWithContext | /i/v1/ai/events |
1.x.x sent Enqueue and EnqueueWithContext events to POST /batch/.
Check anything that pins the old path: reverse proxies, API gateways, egress allowlists, and WAF rules.
If you send events through your own reverse proxy, update it before you upgrade:
- Forward both routes. Forward
/i/v1/analytics/eventsand/i/v1/ai/eventsto PostHog. - Pass the headers through unchanged. Pass
Authorization, everyPostHog-*header,Content-Type,Content-Encoding, andUser-Agent.Authorizationholds the project API key, sent asBearer <key>. PostHog answers401withoutAuthorizationand400without the others, and the batch fails. - Keep the credentials. If your proxy strips credentials, keep an
Authorizationheader that starts withBearer phc_,Bearer phs_, orBearer phx_. PostHog SDKs send their keys there. Keys created before these prefixes need their exactBearer <key>value allowed too. - 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. - Pass the capture response through. A proxy or gateway that answers the capture path with its own
200body shows up as failures (see Update error handling).
PostHog's managed reverse proxy already does this. See the proxy guides.
The project API key moves from an api_key body field to an Authorization: Bearer <key> header. Update anything that inspected, logged, or rewrote the request body to find the key.
A capture request follows only 307 and 308 redirects, and only to the same scheme, host, and port as Endpoint, at most 5 times. It resends the same body and headers.
Any other redirect fails the batch without a retry. Callback.Failure gets a CaptureRequestError with the redirect's status. If a proxy redirects capture requests to another host, set Endpoint to the final host.
1.x.x followed up to 10 redirects of any kind to any host:
- A
301,302, or303. 1.x.x resent the request as aGETwithout the events. - A
307or308to another host. That host received the events and the API key.
Feature flag requests are unchanged.
Use a project key
A personal API key (phx_...) passed as the project API key gives a disabled client and a nil error, as an empty key does. Both log an error.
A disabled client sends nothing (see Handle constructor errors).
Check event names
PostHog drops an event whose name is longer than 200 bytes and accepts the rest of the batch. The drop reaches Callback.Failure as a *CaptureEventError.
1.x.x sent events to legacy capture, which had no limit on event name length. Check your event names before you upgrade.
During your upgrade
Change the import path
Go requires the major version in the module path:
The package name is still posthog, so only the import line changes:
The other packages move with the core:
| Package | 2.x.x import path |
|---|---|
Subpackages such as posthogmcp | github.com/posthog/posthog-go/v2/posthogmcp |
| The MCP Go SDK adapter | github.com/posthog/posthog-go/posthogmcpsdk/v2 |
| The mcp-go adapter | github.com/posthog/posthog-go/posthogmcpgo/v2 |
The otel bridge | github.com/posthog/posthog-go/otel/v2 |
The MCP Go SDK adapter and the mcp-go adapter are separate modules that move in lockstep with the core.
The otel bridge imports the core SDK, so it also moves in lockstep with the core.
Handle constructor errors
New returns (Client, error), like NewWithConfig. Handle the error before you use or close the client:
Either constructor returns a nil client and an error only for invalid configuration.
An empty project API key still gives a disabled client and a nil error, as in 1.x.x. A personal (phx_...) key does too in 2.x.x. Both log an error.
- What a disabled client does. It sends nothing, and its methods return default values and
ErrSDKDisabled. - The error text. The text of
ErrSDKDisabledisposthog SDK is disabled. If your code compares error strings, useerrors.Is(err, posthog.ErrSDKDisabled)instead. - A disabled client on purpose. Set
Config.Disabledto build one, for example in tests.
Integrations follow the same rule:
posthogmcpsdk.NewMiddlewareandInstrumentno longer panic on a nil*posthogmcp.Analytics. They report one error and install middleware that changes nothing.- The
otelbridge.NewExporterandNewSpanProcessorno longer return an error for an empty or personal API key. They log one error and return an exporter or processor that exports nothing. They still return an error for an invalidWithHost.
Fix removed APIs
2.x.x removes or changes these APIs:
| API | Change |
|---|---|
Config.CaptureMode and the CaptureMode type | Removed |
The CaptureModeLegacy and CaptureModeAnalyticsV1 constants | Removed |
Capture.Library and Exception.Library (added in posthog-go 1.30.0) | Removed |
Client | New EnqueueAI method |
Alias | New EventProperties and Options maps |
Backoff | New function field |
New | Returns (Client, error) |
Groups | A map[string]string |
Capture v1 is the only behavior. If you opted into capture v1, delete the Config.CaptureMode field.
In place of Capture.Library and Exception.Library, set $lib in the event's properties (see Check SDK identity).
The new Client method only affects code that implements the interface, so a hand-written test mock needs the new method. Callers are unaffected.
You can't compare an Alias or a Backoff with == or use it as a map key, so code that does this no longer compiles.
For New, see Handle constructor errors. For Groups, see Convert group keys.
Delete CaptureMode from your config:
If you used CaptureModeAnalyticsV1, the SDK no longer converts option values or silently removes the ones it can't read. PostHog validates them (see Move to event options).
Convert group keys
Groups is map[string]string, and Groups.Set takes a string value. A group key identifies a group, so numbers, maps, and other values no longer compile. This matches GroupIdentify.Key, which was already a string.
Convert a numeric group ID to its decimal string:
1.x.x bucketed a numeric group key for feature flags by its decimal form. A key converted this way keeps every group in the same rollout bucket and variant.
Check config values
Config has three new size and retry fields:
| Field | Default |
|---|---|
MaxBatchBytes | 500000 bytes |
MaxEventBytes | No cap |
MaxRetryBackoff | 30s |
MaxBatchBytes targets the combined serialized size of the events in one request, excluding the request envelope. Its default is the request limit 1.x.x applied internally.
An event larger than MaxBatchBytes is sent in a request of its own.
MaxEventBytes refuses large events locally with ErrMessageTooBig. With it set, Validate, and so NewWithConfig, rejects a MaxBatchBytes below it.
MaxRetryBackoff caps Retry-After and the default exponential backoff (see Update error handling).
There's no per-event size cap by default. 1.x.x had a 500000-byte cap.
Within PostHog's request limits, PostHog drops an oversized event on its own and reports it to Callback. The other events in the request don't fail.
MaxEventBytes and MaxBatchBytes don't apply to EnqueueAI (see Send AI events with EnqueueAI).
Validate rejects a negative BatchUploadTimeout, CaptureAIBatchUploadTimeout, MaxRetryBackoff, MaxEventBytes, MaxBatchBytes, or CaptureAIMaxQueueSize. Only zero selects the default.
The compression settings change in three ways:
- No opt-in.
CompressionZstd,CompressionDeflate, andCompressionBrotlino longer require an opt-in. A config that failedValidate()with"zstd compression requires CaptureModeAnalyticsV1"succeeds. - Encodings.
Content-Encodingmust be one ofgzip,deflate,br, orzstd. The legacylz64andbase64encodings and the?compression=query parameter are gone. - Codec failures. If a configured codec fails at runtime, the SDK still sends the batch, uncompressed.
Copy options in BeforeSend
Review your BeforeSend hooks for the new message shape. Capture v1 reads per-event processing controls from an options object sent next to properties, and every message type has an Options field (see Move to event options).
A hook that returns a new message must copy Options, or the event is sent without them. That includes the SDK's personless default, so PostHog would create a person for the generated ID.
- The personless default. When a
CaptureorExceptionwith a request context has no distinct ID, the SDK generates one and sets the optionprocess_person_profile: false. So it doesn't create a person for every generated ID. - Turn processing back on. A default, request-context, or event option can turn processing back on.
- MCP events.
posthogmcpsets the same option on events without an identity. This covers tool calls and the$mcp_unknown_tool,$mcp_input_required, and$mcp_missing_capabilityevents. - Options in the hook. A
BeforeSendhook can read and changeOptionslikeProperties, andOptionsis never nil inside the hook. To change an option inBeforeSend, set it inOptions. The SDK checks the event name the call sends, so a hook that builds or renames an identify-style event must set the option itself (see Check identify-style events).
Fix identity calls
- Empty IDs. An empty or whitespace-only
DistinctIdcounts as missing. ACaptureorExceptionsent with a request context gets the context's ID or a personless one. 1.x.x sent it, and PostHog dropped the event. - Whitespace-only IDs without a request context.
Enqueuereturns aFieldErrorfor aCaptureorExceptionwhoseDistinctIdis only whitespace. 1.x.x sent these events. - Whitespace-only
IdentifyandAlias. With or without a request context,Enqueuereturns aFieldErrorfor anIdentifyorAliaswhoseDistinctIdis only whitespace. It does the same for anAliaswhoseAliasis only whitespace. 1.x.x sent these events. - Long distinct IDs. PostHog drops an event whose distinct ID is over 200 UTF-8 bytes, with the per-event result
distinct_id_too_large. It reachesCallback.Failureas aCaptureEventError. 1.x.x sent events to legacy capture, which shortened the ID to 200 characters and kept the event. - Group distinct ID.
GroupIdentify.DistinctIdis sent as the event's distinct ID. If it's empty, the SDK uses the request context's distinct ID, then$<type>_<key>. 1.x.x accepted and ignored the field, and sent every$groupidentifyas$<type>_<key>. - Long group IDs. If
$<type>_<key>is over 200 bytes, setDistinctId, or PostHog drops the event. - Request context values.
RequestContext.PropertiesandRequestContext.Optionsapply toIdentify,Alias, andGroupIdentifyevents sent withEnqueueWithContext. In 1.x.x they applied only toCaptureandException. They never set person processing on identify-style events whose distinct ID the SDK didn't generate (see Check identify-style events). - Context session ID. The context's session ID fills
IdentifyandAlias, but neverGroupIdentify. A session's person in PostHog follows the distinct IDs of the session's events. So an event sent under a different distinct ID with the context's session ID can change the person shown for that session. - Context distinct ID. The context's distinct ID never changes an
Identifyor anAlias.
Check identify-style events
Identify-style events are $identify, $create_alias, $merge_dangerously, $groupidentify, $set, and $set_once. They're the events that Identify, Alias, and GroupIdentify send, and a Capture with one of these names.
They exist to create, link, or change a person or group, and with person processing off PostHog drops them or ignores their person update. So they default to process_person_profile: true unless the call itself sets the option or the legacy $process_person_profile property:
- The call's value. The call's value wins over every layer. A
falseinDefaultEventOptions,RequestContext.Options,DefaultEventProperties, orRequestContext.Propertiesdoesn't reach these events, unless the SDK generates the distinct ID (below). - A legacy property on the call. A legacy
$process_person_profilein the call'sProperties(forCapture) orEventPropertiesbecomes the option before the layers fill, and the property is removed. If the call also sets the option, the option wins. nilvalues. Aniloption or legacy property counts as unset.- Generated distinct IDs. A
Capturewhose distinct ID the SDK generates gets notrue. Itsprocess_person_profilecomes from the layers, then the personlessfalse(see Copy options in BeforeSend), unless the call sets the option or the legacy property. - Layered legacy properties.
BeforeSendsees the option without a legacy$process_person_profilefromDefaultEventPropertiesorRequestContext.Properties, so a hook that clearsOptionsdoesn't send afalsefrom a layer. BeforeSend. The hook sees the value and can change it. The SDK checks the event name the call sends, so aBeforeSendhook that builds or renames an identify-style event must set the option itself.- Keeping one personless. To send an identify-style event without person processing, set
process_person_profiletofalseon the message or inBeforeSend, or turn off person processing for the project in PostHog.
Check event IDs
- Generated IDs. The SDK generates UUIDv7 values for event
Uuids, thePostHog-Request-Idheader, and the distinct ID of a personless capture. It falls back to v4 if v7 generation fails. - Your own
Uuid. The SDK normalizes aUuidyou set to the lowercase hyphenated form, so theCallbackmessage carries that form. - Empty values. An empty
Uuidgets a generated one. - Invalid values. The SDK replaces an invalid
Uuidwith a generated one. It logs one warning that doesn't include the value. BeforeSend. The SDK applies this rule beforeBeforeSend, and again to aUuidthatBeforeSendsets.- Duplicates. Each event needs its own uuid. When a request contains the same uuid more than once, capture keeps the first event and drops the later copies. The SDK reports each dropped copy to
Callback.Failureas a*CaptureEventErrorwithResultdropandDetailsduplicate_event_uuid, and never retries it. Older capture versions reject the whole request with a400, which the SDK reports as a*CaptureRequestErrorwithduplicate_event_uuid.
Check property precedence
An event's properties and options come from five steps, in this order. Steps 2 to 4 fill only the properties and options that the steps before them left unset:
- The event's own
PropertiesandOptions. The request context's session ID is part of the event's identity, so it's set as$session_idfirst, unless the event has its own. RequestContext.PropertiesandRequestContext.Options.Config.DefaultEventPropertiesandConfig.DefaultEventOptions.- Values the SDK sets:
$is_server, fromConfig.IsServer$geoip_disable, fromConfig.DisableGeoIP$os,$os_version,$os_distro, and$go_version$liband$lib_version,posthog-goand the SDK version, as a pair (see Check SDK identity)$feature/<key>and$active_feature_flags, from aFlagssnapshot orSendFeatureFlags- The option
process_person_profile: falsefor a personless event (see Copy options in BeforeSend)
BeforeSend, which sees the result of steps 1 to 4 and can change or remove any of it. Its changes are final.
A property key set to nil counts as set, so it keeps the default out. An option that's missing or nil counts as unset, so a nil event option still gets the default.
Steps 2 to 4 don't fill process_person_profile on an identify-style event that already defaulted to true (see Check identify-style events).
$lib and $lib_version follow their own rule. A nil, empty, or non-string $lib counts as unset, and the SDK replaces a $lib_version set without a $lib.
To turn a default option off for one event, set the option to false on the event or in BeforeSend.
$set, $set_once, $groups, and $group_set fill one level deep. When the event and a default both set one of them to a map, the default adds only the keys the event left out.
For example, a default "$set": {"plan": "free", "source": "web"} and an event "$set": {"plan": "pro"} send {"plan": "pro", "source": "web"}. A $set in DefaultEventProperties or the request context sets those person properties on every event it reaches.
These changes follow from this order:
- Default properties.
Config.DefaultEventPropertiesfill only the keys that the event and the request context left unset. In 1.x.x the default value overwrote the event's value, except when the event turned person processing off. - Merged maps. A
$set,$set_once,$groups, or$group_setdefault no longer replaces the event's whole map. In 1.x.x it did. Capture.Groups. It merges into a$groupsmap inPropertiesand wins key by key. In 1.x.x it replaced the map.- Message types.
DefaultEventPropertiesapply toException,Identify,Alias, andGroupIdentifyevents. In 1.x.x they applied only toCapture. A$process_person_profile: falsethere turns person processing off forExceptionevents too, but not for identify-style events (see Check identify-style events). EventProperties. ForIdentify,Alias, andGroupIdentify, the defaults fill the newEventPropertiesfield. It holds the properties of the event itself, separate from the$setor$group_setthatPropertiessends.$setinEventProperties. A$setinIdentify.EventPropertiesor a$group_setinGroupIdentify.EventPropertiesmerges underProperties, which win key by key.Aliascallbacks. TheConfig.Callbackmessage for anAliasdoesn't include itsEventProperties.- SDK values. A
$is_server,$geoip_disable,$lib,$lib_version, or system property that you set wins over the SDK's value. In 1.x.x the SDK overwrote it. - GeoIP. A
DefaultEventPropertiesvalue of$geoip_disable: falseturns GeoIP lookup back on for events, even whenConfig.DisableGeoIPis on. Feature flag requests still followConfig.DisableGeoIP. - Message fields. The
IsServerandDisableGeoIPfields of a message report the values left afterBeforeSend. To change them, set the properties. - Feature flag properties. A
$feature/<key>set in the request context orDefaultEventPropertieswins over the flag value. One set in the event's ownPropertieswins over both. - Feature flag properties and
SendFeatureFlags. The only change from 1.x.x is that a$feature/<key>set on the event or in the request context wins overSendFeatureFlags. AFlagssnapshot already let them win, andDefaultEventPropertiesalready beat the flag values on both paths. - Minimal flag events. The server can turn on a minimal
$feature_flag_calledevent for flags without an experiment. The SDK trims it to its fixed set of properties beforeBeforeSend. The hook sees only that set, and the properties it adds are sent. In 1.x.x the trim ran afterBeforeSendand removed them. - Options on minimal flag events. Minimal
$feature_flag_calledevents keep their options, because the trim removes only properties. In 1.x.x the trim removed these settings, except person processing.
posthogotel.EnqueueWithContext adds the active span's $trace_id and $span_id only when neither the event nor the request context sets either key. In posthog-go 1.37.0 and later 1.x.x releases, each ID filled on its own, so an event that set only $trace_id got the active span's $span_id.
The helper can't see Config.DefaultEventProperties. A $trace_id or $span_id set there doesn't stop the derived pair, which wins over it.
Check SDK identity
Every event carries $lib and $lib_version in its properties. By default they're posthog-go and the SDK version. PostHog stores the values the event is sent with.
You can set them in the event, the request context, or DefaultEventProperties. Like any other property, each one comes from the most specific place that sets it, so set both in the same place.
- No
$lib. If no$libis set to a non-empty string, the SDK sets both and replaces a$lib_versionset on its own. posthog-gowithout a version. If$libisposthog-gowith no version, the SDK adds its version.- Any other
$lib. The SDK doesn't add its version. A$libset alone sends no$lib_version, so set$lib_versionyourself to keep a version on those events. BeforeSend. The hook sees both and can change or remove them.
If an event has no $lib, PostHog sets both from the PostHog-Sdk-Info header, posthog-go/<version>. In 1.x.x the default /batch/ path overwrote a $lib you set.
Capture.Library and Exception.Library are removed. Set $lib in the event's properties instead.
For example, Capture{..., Library: "my-lib"} becomes Capture{..., Properties: posthog.NewProperties().Set("$lib", "my-lib").Set("$lib_version", "1.2.3")}. In 1.x.x, Library still sent the posthog-go version as $lib_version.
posthogmcp events report posthog-go-mcp with the SDK version, unless you set $lib in the ToolCall or EventContext properties or the request context. DefaultEventProperties can't change it, because posthogmcp sets its pair before the defaults fill.
$lib_version reports the SDK version from a Go test binary too. 1.x.x reported 1.0.0 from any test binary, including your application's own.
Update error handling
Capture v1 returns a result for each event, and the client resends only the events the backend asks it to retry. The old endpoint accepted or rejected a whole batch.
Callback changes with it:
- Failures on a
200.Failurecan fire on an HTTP 200, for an individual event the backend dropped while it accepted the rest of the batch. - Unreadable responses. A
2xxwhose body isn't JSON, or whoseresultsis missing,null, or not an object, fails the whole batch. Each event reachesFailurewith a*CaptureRequestErrorand isn't resent. The old endpoint treated any status below 300 as success. - Missing results. An event whose uuid is absent from a valid
resultsobject fires neither callback.
Errors are typed. Check them with errors.As:
Failure also gets local failures, and it can run on the goroutine that called Enqueue:
- Local failures. A local failure, such as an event over
MaxEventBytesor a full batch-submission queue, reachesFailurewrapped in a*CaptureLocalError. In 1.x.x these were the bare sentinel errors, soerr == posthog.ErrMessageTooBigno longer matches. Useerrors.Is(err, posthog.ErrMessageTooBig), which works in both. - A full message queue.
EnqueuereturnsErrQueueFullandFailureisn't called, so check the errorEnqueuereturns. - The lane. The new
Endpointfield on all three error types names the lane: the analytics path or the AI path. - The calling goroutine.
Failurecan run on the goroutine that calledEnqueue. A message that fails JSON serialization is reported beforeEnqueuereturns. This was also true in 1.x.x. - Re-enqueues. Don't re-enqueue the same message from
Failure. It fails again and the calls recurse.
Update log-based alerts for these log lines:
- Without a
Callback. The SDK logs one warning each time a request loses events, never one per event. For example,analytics: 3 event(s) dropped: <cause>; set Config.Callback to inspect failures. - The cause. For a failed request the cause is the error text, which can include PostHog's error description. 1.x.x logged the response body.
- After the last retry. The SDK logs events that still fail after the last retry as an error, with or without a
Callback. For example,analytics: 3 messages dropped after 4 attempts. - Lane names. Capture log lines start with the lane name,
analytics:orcapture-ai:, and some of their text changed from 1.x.x. Verbose. WithVerboseon, 1.x.x logged every queued message in full. 2.x.x logs batch counts and sizes, not the messages.
2.x.x changes which statuses it retries and adds jitter to retry waits:
| Behavior | 1.x.x | 2.x.x |
|---|---|---|
| Statuses retried | Every 5xx, 408, 429, and network errors, but not 404 | 404, 408, 429, 500, 502, 503, 504, and network errors |
| Default retry waits | No jitter | Up to 25% jitter |
In 2.x.x, other 5xx statuses are terminal.
The default waits vary randomly by up to 25% either way, so clients that fail together don't all retry at the same moment.
DefaultBackoff() has the same jitter. In 1.x.x it had none.
Billing limits arrive as a terminal 402.
The SDK honors Retry-After, clamped to the new Config.MaxRetryBackoff. The default is 30s, and it also caps the default exponential backoff. A server Retry-After stays the minimum wait.
A custom Config.RetryAfter is used as given.
Check dropped events
PostHog rejects these events one by one inside an otherwise successful batch. Each one reaches Callback.Failure as a *CaptureEventError:
- Event names longer than 200 bytes (see Check event names)
- Distinct IDs longer than 200 bytes
$performance_event- Properties that aren't a JSON object
- An event option value, or a legacy option property value such as
$process_person_profile: "maybe", that PostHog can't read, whereDetailsisinvalid_options(see Move to event options). 1.x.x sent the legacy property and PostHog ignored the value, except for cookieless mode, where any non-boolean value failed the whole batch.
The SDK sends $session_id and $window_id as top-level fields of the event, because capture reads them there and requires strings. What the SDK sends depends on the value:
| Value | 2.x.x |
|---|---|
| A value whose JSON form is a string | Sent as that string |
nil | Dropped, without a warning |
| Any other value | Dropped, with a warning |
A value whose JSON form is a string is a string, including "", a named string type, or a uuid.UUID.
nil counts as unset. For any other value, the SDK logs a warning for each drop that names the key and the value's type, never the value.
In 1.x.x the SDK sent any value as a property.
Non-finite numbers follow these rules:
float32andfloat64values. A NaN or infinite property value is sent asnulland the event is kept, as in posthog-go 1.36.1 and later.- Structs. A struct value that holds one is sent as
nullas a whole. - Invalid JSON. Each event is checked as JSON before it's queued. A custom
MarshalJSONthat returns invalid JSON fails only its own event, andCallback.Failurereports it.
Check timestamps
The SDK sends the event timestamp, the batch created_at, and the PostHog-Request-Timestamp header in UTC with at least millisecond digits, for example 2025-01-02T03:04:05.000Z.
The SDK keeps finer precision from your Timestamp or the clock, up to nanoseconds.
1.x.x dropped trailing zeros from event timestamps, so a timestamp on a whole second had no fraction.
Follow ups
Move to event options
Capture v1 reads per-event processing controls, such as person profile processing, from an options object sent next to properties. Every message type (Capture, Identify, Alias, GroupIdentify, and Exception) has an Options field, and it works the same with Enqueue and EnqueueAI:
Keys are strings, and values are any JSON-serializable value.
- Sent unchanged. The SDK sends options unchanged, so an option that PostHog adds later needs no SDK upgrade.
- Unknown keys. PostHog validates options. It ignores keys it doesn't know.
- Common forms. PostHog reads common forms of a known key's value. For a boolean, that includes
"yes","off", or0. - Unreadable values. PostHog drops the event if a known key has a value it can't read. That drop reaches
Callback.Failureas a*CaptureEventErrorwhoseDetailsisinvalid_options.
Each option replaces a legacy option property:
| Option | Replaces |
|---|---|
process_person_profile | $process_person_profile |
cookieless_mode | $cookieless_mode |
disable_skew_correction | $ignore_sent_at |
product_tour_id | $product_tour_id |
Legacy option properties still work, but an option overrides its legacy property. Use options.
You can also set options for every event and for a request:
- Every event.
Config.DefaultEventOptionsapplies to everyCapture,Exception,Identify,Alias, andGroupIdentifyevent, likeConfig.DefaultEventProperties. - One request.
RequestContext.Optionsapplies to every event sent withEnqueueWithContextorEnqueueAIWithContext, likeRequestContext.Properties. A child context inherits its parent's options.
The event's Options come first. Before BeforeSend, the SDK fills each option that's still missing or nil, from RequestContext.Options, then DefaultEventOptions, then the SDK's personless default (see Check property precedence). It doesn't fill process_person_profile on an identify-style event that already defaulted to true (see Check identify-style events).
1.x.x sent these settings as properties to the /batch/ endpoint. Two values behave differently as options:
| Value | 2.x.x | 1.x.x |
|---|---|---|
The string "false" for process_person_profile | Person processing off | Ignored |
| A value PostHog can't read | Event dropped as invalid_options | Event kept, value ignored |
PostHog reads common forms of an option's value, so posthog.NewOptions().Set("process_person_profile", "false") turns person processing off. 1.x.x ignored the string "false" for this setting.
A value PostHog can't read is one such as "maybe" for process_person_profile. PostHog drops the event as invalid_options.
1.x.x kept the event and ignored the value, except for cookieless mode, where any non-boolean value failed the whole batch.
Send AI events with EnqueueAI
Send $ai_ events with EnqueueAI or EnqueueAIWithContext. PostHog accepts $ai_ events on the analytics endpoint for now, but this is temporary.
EnqueueAI sends to PostHog's dedicated AI capture endpoint, which accepts much larger events than the analytics endpoint:
- Its own lane.
EnqueueAIruns on its own queue, batching, and retry state, started on first use. - Routing. Routing is by method.
Enqueuenever reroutes an$ai_-prefixed event. - Message types.
EnqueueAIaccepts every message type and does no routing check of its own. Capture decides, and returns a per-event drop for an event the AI endpoint doesn't take. - Flushes.
FlushandFlushWithContextalso wait for the AI lane onceEnqueueAIhas started it.Closedrains both lanes too. - Size limits. The AI lane's size limits are fixed, because they track the endpoint. The SDK refuses an event over 8 MiB plus 64 KiB of envelope headroom locally, and a batch closes at about 5 MiB.
MaxEventBytesandMaxBatchBytesdon't apply to it. - HTTP handlers. Use
EnqueueAIWithContextfrom HTTP handlers, as you wouldEnqueueWithContext. It takes aClientrather than anEnqueueClient, because only a real client has an AI lane.
Tune the AI lane with these Config fields:
| Field | In place of |
|---|---|
CaptureAICompression | Compression |
CaptureAIMaxQueueSize | MaxQueueSize |
CaptureAIBatchUploadTimeout | BatchUploadTimeout |
CaptureAICompression doesn't inherit Compression. AI requests are sent uncompressed unless you set it.
The AI lane doesn't use MaxQueueSize or BatchUploadTimeout.
CaptureAIBatchUploadTimeout is 30s by default, longer than the analytics lane's because AI batches are much larger.
The AI lane shares BatchSize, Interval, MaxRetries, RetryAfter, MaxRetryBackoff, Callback, BeforeSend, HistoricalMigration, DefaultEventProperties, and DefaultEventOptions with the analytics lane.
Add MCP event options
MCP events take options through EventOptions fields and RequestContext.Options:
- Tool calls.
posthogmcp.ToolCallhas a newEventOptionsfield, and tool calls also takeRequestContext.Options. The call's options override the request context's. - Other MCP events. They take the same layers through
EventContext.EventOptions. - Calls without an identity.
posthogmcpsetsprocess_person_profile: falseon a call without an identity, whatever its options say.BeforeSendruns after that and can still change it, and PostHog receives what the hook returns. - Request context values.
posthogmcpevents takeRequestContext.Propertiesunder the call's properties with any client, as in 1.x.x. They takeRequestContext.Optionsunder the call's options in the same way. - Precedence. The call's values win, and the context's values win over
DefaultEventPropertiesandDefaultEventOptions. - Reserved keys.
posthogmcpstill drops the reserved keys, such as$mcp_*,$set, and$session_id, from the context properties and sanitizes their values first.
With posthogmcpsdk, WithEventOptions sets a tool call's EventOptions:
With posthogmcpgo, WithEventOptions works the same way:





