PostHog Rust SDK 1.x
Getting started
The Rust SDK runs on your server.
To send your first event, add posthog and tokio, create a client with your project token from your project settings, and call capture.
A background worker sends queued events, so call shutdown before your process exits, or the last events are lost.
Install
Initialize and capture
Create a client with your project API key, capture an event, then shut down so queued events are sent. Without the default async-client feature, client is synchronous and the calls below drop .await.
capture queues the event and returns at once. Call shutdown before the process exits.
Read SDK logs
The SDK logs through tracing under the posthog target. Add a subscriber to your application to see the logs.
This example needs the env-filter feature of tracing-subscriber. Add tracing-subscriber = { version = "0.3", features = ["env-filter"] } to your dependencies.
Set RUST_LOG to choose the level.
Use posthog=warn for warnings and errors only. Use posthog=trace for detailed local evaluation and cache logs.
Setup
posthog::client
Construct an async PostHog client from an API key or ClientOptions.
Parameters
options: Either a project API key (for example"phc_...") or a configuredClientOptionsvalue.
Returns
A Client that performs capture and feature flag requests asynchronously.
Remarks
This constructor is available with the default async-client feature and
must be awaited. Passing a blank API key creates a disabled client.
If the HTTP client cannot be built, logs a warning and creates a disabled
client instead.
posthog::init_global
Initialize the global client singleton.
Use the crate-level init_global re-export when you don't need more than
one client instance and don't need to change client options at runtime.
With the error-tracking feature (on by default) and
ErrorTrackingOptions::capture_panics enabled (opt-in; off by default),
this also installs a process-wide panic hook that captures panics as
$exception events through the global client.
Parameters
options: Project API key orClientOptionsused to construct the global client.
Errors
Returns Error::AlreadyInitialized if called more than once.
Capture
Client::capture
Capture the provided event, sending it to PostHog.
Parameters
event: Event name, distinct ID, properties, timestamp, groups, and optional feature flag state to send.
Remarks
Fire-and-forget: the event is handed to the background worker, which batches, sends, and retries it. Returns once the event is queued — not once it is delivered, and delivery failures are not surfaced to the caller. Disabled clients and a full queue drop the event (the latter with a single warning).
Use Client::capture_ai for LLM analytics events ($ai_generation,
$ai_span, …): capture never reroutes by event name. The analytics
endpoint still accepts AI events for now, but large ones need capture_ai.
Client::capture_batch
Capture a collection of events.
Parameters
events: Events to send in the batch.historical_migration: Set totrueto route events to the historical ingestion topic, bypassing the main pipeline.
Remarks
Fire-and-forget, like Client::capture. The batch is enqueued per event
rather than atomically, so if the bounded queue fills partway through, the
remaining events are dropped (with the usual single full-queue warning).
Client::capture_immediate
Capture a single event and await confirmation that the request completed.
The immediate-delivery counterpart to Client::capture. This is a
convenience wrapper over Client::capture_batch_immediate with a
one-event batch; see it for full semantics.
Client::capture_batch_immediate
Capture a batch of events and await confirmation that the request
completed, returning a CaptureSummary describing the outcome.
The immediate-delivery counterpart to Client::capture_batch. Prefer
the fire-and-forget Client::capture/Client::capture_batch for
normal analytics; reach for this only when the caller must know the batch
persisted before advancing its own durable state.
Parameters
events: Events to send in a single request.historical_migration: Route events to the historical ingestion topic.
Behavior
Sends inline (bypassing the background worker) and retries transient
failures per the client's retry configuration. A returned Ok can still
report unpersisted events — inspect
CaptureSummary::all_persisted. Does NOT fire on_error hooks: the
returned Result is the delivery signal. Disabled clients and an empty
(or fully before_send-filtered) batch return a default CaptureSummary.
Errors
Returns Error when the request is rejected with a terminal status or
the retry budget is exhausted without a successful response.
Event::new
Create a new identified Event. Unless you have a distinct ID you can
associate with a user, you probably want to use Event::new_anon
instead.
Parameters
event: Event name, such as"user_signed_up".distinct_id: Stable user or account identifier. For backend events, use the same distinct ID your frontend passes toposthog.identify(). An empty or whitespace-only ID counts as missing: the event becomes anonymous, as fromEvent::new_anon.
Event::new_anon
Create a new anonymous event.
See https://posthog.com/docs/data/anonymous-vs-identified-events#how-to-capture-anonymous-events.
Parameters
event: Event name.
Remarks
Generates a random distinct ID and sets the process_person_profile
option to false so PostHog does not create a person profile for the
event. To process one anyway, set the option to true with
Event::insert_option. A null or removed option counts as unset,
so the SDK sets false again before before_send.
posthog::capture
Capture the provided event using the global client.
Remarks
Fire-and-forget, like Client::capture. No-op if init_global has not
run.
Alias
Client::alias
Merge two distinct IDs onto the same person by sending a $create_alias
event.
Parameters
previous_id: ID already known to PostHog, such as an anonymous ID.distinct_id: ID it should be merged into, such as a logged-in user ID.
Remarks
Fire-and-forget, like Client::capture. A blank ID on either side
cannot describe a merge, so the event is dropped with a warning rather
than sent.
The event sends process_person_profile: true, so a request context
cannot turn person processing off for it. To set options on it, build it
with Event::alias and capture it.
Examples
Capture AI
Client::capture_ai
Capture an AI (LLM analytics) event, sending it to PostHog's AI ingestion endpoint.
Parameters
event: The AI event ($ai_generation,$ai_span,$ai_trace,$ai_embedding, …) with its$ai_*properties.
Remarks
Fire-and-forget, like Client::capture, on a separate lane: its own
background worker, queue (capture_ai_max_queue_size), retry state, and
endpoint, so a multi-MB AI event can never delay or displace analytics
events. The lane batches by size (about 5 MiB per request), compresses
bodies per capture_ai_compression (unset sends them raw; zstd is
recommended), and drops an event locally — with a warning naming only
the event and its byte size — when its serialized properties exceed
8 MiB, the backend's per-event ceiling. The worker starts on the first
call.
The SDK does not inspect the event name. The backend accepts only its
AI event names on this endpoint and reports anything else as a per-event
drop, which reaches an on_error hook (see
CaptureFailure::endpoint_kind) or, with no
hook, one aggregate warning per batch.
Client::capture_ai_batch
Capture a batch of AI events on the AI lane.
Parameters
events: AI events to send.
Remarks
Fire-and-forget, like Client::capture_ai. Events are enqueued per
event, so if the bounded queue fills partway through, the remaining
events are dropped (with the usual single full-queue warning). The lane
splits the batch into requests of about 5 MiB each.
Client::capture_ai_immediate
Capture a single AI event and await confirmation that the request completed.
The immediate-delivery counterpart to Client::capture_ai. This is a
convenience wrapper over Client::capture_ai_batch_immediate with a
one-event batch; see it for full semantics.
Client::capture_ai_batch_immediate
Capture a batch of AI events and await confirmation that every request
completed, returning a CaptureSummary describing the outcome.
The immediate-delivery counterpart to Client::capture_ai_batch.
Parameters
events: AI events to send.
Behavior
Like Client::capture_batch_immediate, but on the AI endpoint with
capture_ai_compression, and the batch is split into requests of about 5 MiB
each, sent in order. Each request retries transient failures and
per-event retry verdicts per the client's retry configuration; the
summary merges every request's verdicts. An event whose serialized
properties are over 8 MiB is not sent, as the backend would refuse it.
It gets a local drop verdict with details ai_event_too_big in the
summary, and counts in CaptureSummary::submitted and
CaptureSummary::not_persisted.
Errors
Returns Error as soon as one request is rejected with a terminal
status or exhausts its retry budget; requests sent before it may already
have persisted. An Err therefore means "not confirmed", not "nothing
was stored".
posthog::capture_ai
Capture the provided AI event using the global client.
Remarks
Fire-and-forget, like Client::capture_ai. No-op if init_global has
not run.
Capture exception
Client::capture_exception
Capture a Rust error personlessly, sending it to PostHog Error Tracking.
The error's type, message, and full source() chain are sent as
$exception_list, with a stacktrace of the capture site attached to
the first entry (see ErrorTrackingOptions::capture_stacktrace).
Accepts any std::error::Error, including &dyn Error. A
Box<dyn Error> does not implement Error itself, so pass the
dereferenced trait object: capture_exception(&*boxed).
To associate the exception with a person or attach custom properties,
groups, a fingerprint, or a severity level, use
Client::capture_exception_with.
Examples
Client::capture_exception_with
Capture a Rust error with optional context, sending it to PostHog Error Tracking.
Set CaptureExceptionOptions::distinct_id to associate the exception
with a person; without it the exception is captured personlessly.
Examples
posthog::capture_exception
Capture a Rust error personlessly using the global client.
posthog::capture_exception_with
Capture a Rust error with optional context using the global client.
Emails
Client::emails
Transactional email: send email from templates made in PostHog or from content your code rendered, and read the status of each email sent.
Send a CodeEmail or a
TemplateEmail with Emails::send, and read
its status with Emails::get. Needs secret_key set to a Project
Secret API Key with the transactional_email:write scope, and
app_host when host isn't PostHog Cloud. See Emails for setup,
attachments and retries.
Needs posthog 1.0.0 or later, or posthog-rs 0.31.0 or later.
Use 1.1.2 or later of either: earlier releases call the
/api/projects/@current/messaging/ routes, which PostHog is removing.
Emails
Transactional email on a Client: sends email from
templates made in PostHog or from content your code rendered, and reads the
status of each email it sent. Get it with
Client::emails.
Setup
- Create a project secret API key (
phs_...) with the "Send transactional email" preset (transactional_email:write) in your project settings, and set it as the client'ssecret_key. Addtransactional_email:readtoo if you read email statuses with a key that can't send. Keys made withhog_flow:writestill work. The project API key (phc_...) captures events but can't send email. - On PostHog Cloud, set
hostto your region, such ashttps://eu.i.posthog.com, and the client sends email to that region's app host. For any otherhost, such as a reverse proxy, setapp_hostto your PostHog app host: the proxy must not receive the secret key. The client also sends the secret key tohostwhenenable_local_evaluationloads flag definitions and when you callget_remote_config_payload. When that proxy must not see the key, send email from its own client whosehostis PostHog's, and leavesecret_keyoff the proxy client. From 1.1.2, email goes to/api/messaging/on the app host, which a self-hosted PostHog serves from its 2026-11-18 version. - To send a template made in PostHog, open it under Workflows, make it transactional and copy its ID.
A result means PostHog queued the email. Delivery happens later: read it
with Emails::get.
Copies and attachments
A CodeEmail takes cc, bcc and files: add each
with cc, bcc and
attachment. PostHog takes at most 10
addresses in each of cc and bcc. An email carries at most 10 files and
40 MB after Base64 encoding, which leaves about 29 MB for the files. The
40 MB counts the bodies and the subject too, and the HTML twice when the
email has no text, because PostHog then sends text it derives from the HTML.
The client checks both before it sends anything, and refuses the send with
too_many_attachments or message_too_large.
A template made in PostHog sets its own recipients and content, so a
TemplateEmail takes none of them.
The client sends files in two steps. It asks PostHog which files it lacks,
naming each by its SHA-256 and size, and uploads those straight to
PostHog's file store, without your secret key. A file this project sent
before isn't uploaded again. Once every upload succeeded, it sends the email
naming each file by its SHA-256. If the file store refuses an upload, the
send fails with attachment_upload_failed and the store's answer in
why, and no email is sent. A PostHog without
the upload route, a project with sending email from code off, or an
app_host that isn't PostHog's answers the upload request with 404: the
send fails with PostHog's answer, such as not_found, on attachments,
and no email is sent. Allow your app to reach the file store's host as
well as your PostHog app host.
Uploads go only over https: when PostHog names a file store URL that isn't
https, the send fails with api_error on that attachment before any
upload, and no email is sent. Fix the file store's URL. Only an app_host that is itself plain
http, such as a PostHog on your own machine, lets files upload over plain
http. Uploads go through a client the SDK builds, even when you supply
your own HTTP client, so your client's default headers never reach the
file store. That client follows no redirect, so a file never moves to
another host, trusts the system's root certificates, and takes its proxy
from the environment, such as HTTPS_PROXY. None of your client's own
settings apply to uploads: a root certificate, TLS option or proxy set in
code doesn't reach them.
Timeouts and retries
Each request times out after email_request_timeout_seconds, 15 by
default. A request retries network errors, rate limits other than
quota_limited, a send still in flight and an unavailable service
email_request_max_retries times, 2 by default. Retry n, counting from
0, waits about 2^n seconds, at most 30, so 1 and then 2 seconds by
default, or the server's Retry-After when that is longer. A Retry-After over 30 seconds fails at
once. An upload also retries the file store's 500, 502 and 504. An
upload gets one more second for each 128 KiB of its file, so a
29 MB file has about 4 minutes. Every attempt of a send carries the same
idempotency key, so a retry never sends twice. When a job runner already retries the send, set
max_retries(0) on it and pass an idempotency key that names the email.
PostHog keeps an idempotency key for 7 days, so finish every retry within
7 days. A status read retries the same errors, but never not_found.
Moving from another email provider
Set migrated_from, such as "resend", on the client, so PostHog knows
where your sends came from.
Emails::send
Queues one email, from a template made in PostHog or from content your code rendered.
Ok means PostHog queued the email, not that it was delivered. Network
errors, rate limits other than quota_limited, a send with the same
idempotency key still in flight and an unavailable service are retried with the same idempotency
key, up to the email's max_retries or the client's
email_request_max_retries. The result's id is the message ID that
get takes.
A CodeEmail with attachments first asks PostHog
which files it lacks, uploads those straight to PostHog's file store,
then sends the email naming each file by its SHA-256.
Errors
Returns an EmailError when an argument check fails, the client is
disabled, shut down or has no secret_key, the file store refused an
upload (attachment_upload_failed), or PostHog did not queue the
email. Branch on EmailError::code, never on the message.
Examples
Emails::get
Reads the status of an email that send queued, for 30
days after the send. A key with only transactional_email:read can read
statuses but not send. The EmailStatus holds an
EmailDeliveryStatus, and its as_str()
gives the status as PostHog sends it.
Errors
Returns an EmailError when message_id is not a message ID, the
client can't reach PostHog, or PostHog answered with an error. The code
is not_found when no email of this project has the ID, when the email
is older than 30 days, or for a few seconds after the send. The client
doesn't retry not_found: right after a send, wait a few seconds and
call again before you treat the email as missing.
CodeEmail
One email whose content your code rendered, such as React Email output, named by a key. PostHog sends it as is.
It needs new, and html, text
or both. Every other method is optional. Without text, PostHog derives
it from the html. To send a React email, render it to HTML in your app
and pass the HTML.
Needs posthog 1.0.0 or later, or posthog-rs 0.31.0 or later.
Use 1.1.2 or later of either: earlier releases call the
/api/projects/@current/messaging/ routes, which PostHog is removing. On
posthog-rs, sensitive and
tracking need 0.32.0, and cc,
bcc and attachment need 0.33.0.
CodeEmail::new
An email to one recipient address, with a subject.
template_key names the email, such as "password-reset", so its
metrics, logs and status group under it in PostHog. It takes letters,
digits, hyphens and underscores, at most 400.
CodeEmail::html
The HTML body.
CodeEmail::text
The plain-text body.
CodeEmail::from
A verified sender, such as "Acme <security@example.com>". Without
it, PostHog uses the project's default sender.
CodeEmail::reply_to
Adds a reply-to address. Call it again to add more.
CodeEmail::cc
Adds an address that gets a visible copy. Call it again to add more,
at most 10. Each is a bare address, such as "finance@example.com",
with no name.
Needs posthog 1.0.0 or later, or posthog-rs 0.33.0 or later.
CodeEmail::bcc
Adds an address that gets a copy the other recipients never see. Call it again to add more, at most 10. Each is a bare address, with no name.
Needs posthog 1.0.0 or later, or posthog-rs 0.33.0 or later.
CodeEmail::attachment
Adds a file to the email. Call it again to add more, at most 10 files
and 40 MB for the whole email after Base64 encoding, which leaves about
29 MB for the files. The 40 MB counts the bodies too, and the HTML twice
without text, because PostHog derives the text from it. PostHog refuses a file type that mailbox providers
block, such as .exe.
Needs posthog 1.0.0 or later, or posthog-rs 0.33.0 or later.
CodeEmail::header
Adds a header to the email itself, not to the request to PostHog. Call
it again to add more. A name you set twice, with the same
capitalization, keeps the last value. Names that differ only in case,
such as X-Note and x-note, are two headers, and PostHog refuses the
send with invalid_header.
PostHog takes at most 8 headers: In-Reply-To, References,
List-Unsubscribe, List-Unsubscribe-Post, List-Id and any X-
header, except X-PostHog- and X-SES- headers. A value is at most 870
ASCII characters with no line breaks. Only an X- header takes
non-ASCII text, up to 200 UTF-8 bytes. A header PostHog sets itself,
such as List-Unsubscribe on marketing email, keeps PostHog's value.
PostHog checks the headers, not the client, and refuses the send with
invalid_header.
A TemplateEmail takes no headers. PostHog's test sender refuses a
send with headers with sandbox_fields_unsupported.
Needs posthog or posthog-rs 1.15.0 or later.
CodeEmail::tag
Adds a tag that PostHog puts on the email's events as $email_tags, so
you can break them down by it, such as by properties.$email_tags.plan.
Call it again to add more. A name you set twice keeps the last value.
The $workflows_email_sent, delivered, opened, clicked and bounced
events carry the tags. PostHog takes at most 10 tags. A name is 1 to 64
letters, digits, _ and -, and starts with a letter or digit. A value
is 1 to 256 of the same characters. PostHog checks the tags, not the
client, and refuses the send with invalid_tag.
A TemplateEmail takes no tags. PostHog's test sender refuses a send
with tags with sandbox_fields_unsupported.
Needs posthog or posthog-rs 1.15.0 or later.
CodeEmail::sensitive
Whether the email carries a login link, a reset token or a code. PostHog keeps a sensitive email's links unchanged, leaves its subject off engagement events and keeps its content out of logs.
Without it, the email takes the setting of the saved template whose
key is the email's template_key, or is sensitive when no template has
that key.
Needs posthog 1.0.0 or later, or posthog-rs 0.32.0 or later.
CodeEmail::tracking
What PostHog tracks for this email: EmailTracking::On,
EmailTracking::Off, or EmailTrackingOptions to set each kind on
its own. Takes a bool too.
Without it, PostHog counts opens, captures engagement events, and
rewrites links to count clicks only when the email isn't
sensitive.
Needs posthog 1.0.0 or later, or posthog-rs 0.32.0 or later.
CodeEmail::capture_engagement
Whether PostHog captures the email's engagement events (sent,
delivered, opened, clicked, bounced) as events of the recipient.
Defaults to true. A project whose admin turned engagement capture off
captures nothing, whatever the send asks. PostHog refuses a send that
sets both this and tracking.
CodeEmail::category
Deprecated: email sent from code is transactional only. A send that
sets a category fails before any request with an
EmailErrorKind::ValidationError
whose code is invalid_form and whose field is category, and sends
nothing. The SDK never sends the category to PostHog. Send marketing
email through a PostHog workflow, where opt-outs apply.
CodeEmail::distinct_id
The recipient's distinct ID in your product. The email's events go to this person. Without it, they go to a person whose distinct ID is the email address.
CodeEmail::idempotency_key
1 to 255 visible ASCII characters.
A send with a key that PostHog already accepted queues nothing and
returns the first send's result. The same key for another email returns
idempotency_key_reused. Without a key, the client makes a UUID that
covers its own retries of this call. Pass a key derived from what the
email is for, such as password-reset:user_123:<request id>, to cover
retries outside this call too. PostHog keeps a key for 7 days after it
queues the email, so a retry after that can send the email twice.
CodeEmail::max_retries
Overrides the client's email_request_max_retries for this send. 0
turns retries off.
TemplateEmail
One email from an email template made transactional in PostHog, sent by the template's ID.
The template sets its own sender, subject and content. Only
new is required. Needs posthog 1.0.0 or later, or
posthog-rs 0.31.0 or later.
Use 1.1.2 or later of either: earlier releases call the
/api/projects/@current/messaging/ routes, which PostHog is removing.
TemplateEmail::new
An email to one recipient address from the template with this UUID.
TemplateEmail::template_data
Values for the template's {{ variables.* }} placeholders, as a JSON
object. Sent as message_data.
TemplateEmail::distinct_id
The recipient's distinct ID in your product. The email's events go to this person. Without it, they go to a person whose distinct ID is the email address.
TemplateEmail::idempotency_key
1 to 255 visible ASCII characters. See CodeEmail::idempotency_key.
TemplateEmail::max_retries
Overrides the client's email_request_max_retries for this send. 0
turns retries off.
SendEmail
Variants
Template(TemplateEmail)- A template made transactional in PostHog.Code(CodeEmail)- Content your code rendered.
An email for Emails::send: a template made in
PostHog, or content your code rendered.
SendEmailResult
Fields
id: String- The queued email's message ID.replayed: bool- True when PostHog had already accepted this idempotency key and returned the first send's result.warnings: Vec<EmailWarning>- Warnings PostHog returned with the email. The client also logs each one.
The queued email.
A result means PostHog queued the email, not that it was delivered. Read
its delivery status with Emails::get.
EmailStatus
Fields
id: String- The message ID thatsendreturned.status: EmailDeliveryStatus- What happened to the email.created_at: chrono::DateTime<chrono::Utc>- When PostHog queued the email.status_at: chrono::DateTime<chrono::Utc>- When the email reached its current status.reason: Option<String>- Why a failed email was not sent, such asprovider_errororrecipient_suppressed, or the bounce type of a bounced email:hard,softorunknown.Noneotherwise.
The status of an email that Emails::send queued.
EmailDeliveryStatus
Variants
Queued- The email waits to go out.Sent- PostHog handed the email to the email provider.Failed- The email was not sent, and the status'sreasonsays why.Delivered- The recipient's mail server accepted the email.Bounced- The recipient's mail provider reported a bounce after delivery.Complained- The recipient marked the email as spam.Other(String)- A status this SDK version doesn't know, as PostHog sent it.
What happened to an email. Later SDK versions can know statuses that this
one passes through as Other.
EmailDeliveryStatus::as_str
The status as PostHog sends it, such as "delivered".
EmailWarning
Fields
code: String- The warning's stable code.message: String- What the warning is about, in words.fix: Option<String>- How to fix it, when PostHog said.
A warning PostHog returned with a queued email.
EmailError
PostHog did not queue the email or read its status, or the client could not tell whether it did.
Branch on code, PostHog's stable error code such as
quota_limited, or on kind, a coarse category. The message
never holds the secret key or the request body.
EmailError::kind
The coarse category of the failure.
EmailError::code
PostHog's error code, such as quota_limited or recipient_suppressed,
or an SDK code, such as network_error, missing_secret_key or
invalid_template_id.
EmailError::message
What went wrong, in words.
EmailError::status
The HTTP status, when PostHog answered, or the file store's status for
attachment_upload_failed.
EmailError::why
Why PostHog refused the request, when it said.
EmailError::fix
How to fix the request, when PostHog or the SDK said.
EmailError::docs_url
A link to the docs for this error, when PostHog gave one.
EmailError::field
The request field the error is about, such as to, when one is known.
EmailError::retry_after
How long PostHog asked the client to wait before it sends again, from
the Retry-After header of a 429 or 503.
EmailErrorKind
Variants
ValidationError- The send was malformed: a local argument check failed, such astoo_many_attachmentsormessage_too_large, or PostHog answered400, a409withtemplate_outdated, or a422other than a reused idempotency key.MissingApiKey- The client has no secret key, or PostHog answered401.InvalidPermission- PostHog answered403: the secret key lacks the scope.NotFound- PostHog answered404: no such template or email in this project, or, for a send with files, no upload route.ConcurrentIdempotentRequests- PostHog answered409: a send with the same idempotency key is still in flight.InvalidIdempotentRequest- PostHog answered422withidempotency_key_reused: the key was already used for a different email.RateLimitExceeded- PostHog answered429: too many requests.MonthlyQuotaExceeded- PostHog answered429withquota_limited: the monthly quota is spent.ServiceUnavailable- PostHog answered503, the file store answered500,502,503or504to an upload, or the request failed on the network.ApplicationError- Anything else.
A coarse category of an EmailError, for code that branches on the kind
of failure rather than on the exact code.
EmailErrorKind::as_str
The kind's name, such as "validation_error", as every PostHog SDK
spells it.
EmailAttachment
A file sent with a CodeEmail.
PostHog can't fetch a file from a path or URL: read the file and pass its
bytes. Before the send, the client uploads each file PostHog doesn't have
yet straight to PostHog's file store, then sends the email naming each file
by its SHA-256. Its Debug output never shows the content.
EmailAttachment::new
A file from its bytes, with the name the recipient sees, such as
"invoice.pdf". The client hashes the bytes here, once.
EmailAttachment::content_type
The MIME type, such as "application/pdf". Without it, the type
follows from the file name.
EmailAttachment::content_id
Shows the file inline: the HTML references it as cid:<content_id>,
such as <img src="cid:logo"> for "logo".
EmailTracking
Variants
On- Tracks opens and clicks and captures engagement events. Use it only when the email's links are safe to send through a redirect.Off- Turns off every kind of tracking, including kinds PostHog adds later. PostHog then can't count the email's opens and clicks, and captures no engagement events.Custom(EmailTrackingOptions)- Sets each kind of tracking on its own.
What PostHog tracks for a CodeEmail. A bool or an
EmailTrackingOptions converts into it.
EmailTrackingOptions
Each kind of tracking of a CodeEmail, on or off. A kind you don't set
keeps its default.
EmailTrackingOptions::new
Every kind at its default.
EmailTrackingOptions::opens
Whether PostHog adds its open pixel to count opens. Defaults to true.
With opens off, PostHog counts no clicks, and refuses clicks on.
EmailTrackingOptions::clicks
Whether PostHog rewrites the email's links to count clicks. Defaults to
true when the email isn't sensitive and
false when it is. Turn it on only when the links are safe to send
through a redirect, so not for a login or password reset link. A link with a
data-ph-no-track attribute is never rewritten.
EmailTrackingOptions::engagement
Whether PostHog captures the email's engagement events, such as opens
and clicks, as events of the recipient. Defaults to true.
Flush
Client::flush
Flush queued events, returning once the worker has attempted delivery of everything queued before this call. Transient failures are kept for retry (the call still returns without error). A no-op for disabled clients.
posthog::flush
Flush the global client's queued events, awaiting the worker's next delivery
attempt. No-op if init_global has not run.
capture only enqueues, and the global client lives in a static whose
Drop never runs at process exit, so call this (or shutdown) before
exiting to avoid losing buffered events.
Get feature flag payload
FeatureFlagEvaluations::get_flag_payload
Return the JSON payload associated with key, if any.
Remarks
This call does not count as an access and does not fire any event, matching the behavior documented for server-side SDKs.
Flag evaluation through /flags does not return a remote config flag that
has an encrypted payload. Read it with
Client::get_remote_config_payload.
Get feature flag result
FeatureFlagEvaluations::get_flag
Look up the value of key.
Returns
Nonewhen the flag is not in the snapshot,Some(FlagValue::Boolean(false))when disabled,Some(FlagValue::String(variant))for a multivariate match,Some(FlagValue::Boolean(true))when enabled with no variant.
Records the access and fires (deduplicated) $feature_flag_called.
Evaluate flags
Client::evaluate_flags_with_context
Uses this context's identity and pins defaults for later flag access events.
Client::evaluate_flags
Evaluate feature flags for distinct_id, returning a
FeatureFlagEvaluations snapshot.
Each is_enabled / get_flag call on the returned snapshot fires a
dedup-aware $feature_flag_called event with full metadata, and the
snapshot can be passed to [Event::with_flags] so a downstream
Client::capture inherits $feature/<key> and $active_feature_flags
without an extra /flags request.
Parameters
distinct_id: User distinct ID. Empty values return an empty snapshot.options: Optional groups, properties, device ID, GeoIP override, local-only mode, and flag-key filtering.
Errors
Returns Error::Connection or Error::Serialization when remote
evaluation is required and the /flags request fails when local
evaluation produced no value and left no flag unresolved.
When local evaluation produced values or left flags unresolved, a failed
/flags request returns the snapshot instead, so the values and
FeatureFlagEvaluations::unresolved_flags can be read. The snapshot's
$feature_flag_called events report the failure. To observe the failed
request itself, register a hook with
ClientOptionsBuilder::on_error,
which receives it as PostHogError::FeatureFlags.
Returns Error::InvalidArgument when a known-absent key list in
options has more than 1000 keys.
Get remote config payload
Client::get_remote_config_payload
Fetch the payload of a remote config flag by key, with no distinct ID.
Use this method, not Client::evaluate_flags with
FeatureFlagEvaluations::get_flag_payload, for a remote config flag, and
always when the payload is encrypted: flag evaluation through /flags does
not return a remote config flag that has an encrypted payload. The method
needs secret_key. A personal API key (phx_...) returns an encrypted
payload decrypted, and a project secret API key (phs_...) returns it
redacted.
Remote config flags serve one payload to everyone. This method reads it
from the PostHog API, so it works without local evaluation and sends no
$feature_flag_called event.
Parameters
flag_key: Key of the remote config flag. The SDK percent-encodes it as one URL path segment.
Returns
The payload as JSON. PostHog stores the payload as a JSON string, so the
SDK parses a string value a second time. A string that is not JSON is
returned as Value::String. Returns Ok(None) when PostHog answers with an
empty body, which means the flag has no payload. Returns Ok(None) without
a request when the client is disabled.
Errors
Returns Error::Unauthorized when secret_key is missing, or PostHog
answers 401. Returns Error::Connection for a request failure, a timeout
(feature_flags_request_timeout_seconds), or a status the SDK has no
specific error for, such as 404. Returns Error::RateLimit,
Error::BadRequest or Error::ServerError for 429, 400 or 413, and 5xx.
Returns Error::BadRequest for an empty, . or .. flag key. Returns
Error::Serialization when the body is not empty and is not JSON. The request is not
retried and does not call the on_error hooks.
Group identify
Client::group_identify
Create or update a group and set its properties by sending a $groupidentify
event.
See https://posthog.com/docs/product-analytics/group-analytics#set-group-properties.
Parameters
group_type: Group type, such as"company","project", or"organization".group_key: Unique identifier for the group, such as an ID in your database.properties: Any serializable object or JSON map representing group properties.
Remarks
Fire-and-forget, like Client::capture, for a blank group_type or
group_key: the event is dropped with a warning rather than sent.
The event sends process_person_profile: true, so a request context
cannot turn person processing off for it. To set options on it, build it
with Event::group_identify and capture it.
The event's distinct id is the request context's distinct id when one is
set, else $<group_type>_<group_key>. The context session id is never added.
Errors
Returns Error::Serialization if properties fails to serialize to
JSON, or if it does not serialize to a JSON object (PostHog requires
$group_set to be an object).
Examples
Is feature enabled
FeatureFlagEvaluations::is_enabled
Whether key is enabled. Records the access and fires (deduplicated)
$feature_flag_called.
Returns
true for enabled boolean flags or matched multivariate variants, and
false for disabled or missing flags.
Reload feature flags
Client::reload_feature_flags
Fetches local feature flag definitions now and returns once they are in use, so the next local evaluation sees them. The background poller keeps its own schedule.
Errors
Returns Error::InvalidArgument when local evaluation is not
configured (enable_local_evaluation with a secret_key), and
Error::Connection or Error::Serialization when the request fails
or its response cannot be parsed.
Shutdown
Client::shutdown
Flush, stop the background worker, and join it. Idempotent: subsequent
calls are no-ops. Also stops the local evaluation poller at its next
tick. After shutdown, capture drops events and
emails refuses requests with client_closed. Email
requests already in flight, retries included, get until
shutdown_timeout_ms from the start of shutdown to finish. When called
from a transport callback, queues shutdown without waiting for email
requests or joining the current worker thread.
In a web server, call this after the server future resolves, such as
after HttpServer::run().await (actix) or axum::serve(..).await
(axum) returns.
posthog::shutdown
Flush and stop the global client's background worker. Idempotent; no-op if
init_global has not run.
Local feature flag evaluator
Client::evaluate_feature_flag_locally
Evaluate a supplied feature flag definition locally.
groups and group_properties are only consulted when the flag (or one
of its conditions) targets a group; pass empty maps for person flags.
Parameters
flag: Feature flag definition to evaluate.distinct_id: User distinct ID.person_properties: Person properties available to release conditions.groups: Group keys for group-targeted flags.group_properties: Group properties for group-targeted release conditions.
Errors
Returns Error::InconclusiveMatch when the flag cannot be evaluated
locally with the supplied context.
SDK utils
posthog::DEFAULT_HOST
Default host (US by default)
posthog::EU_INGESTION_ENDPOINT
EU ingestion endpoint
posthog::US_INGESTION_ENDPOINT
US ingestion endpoint
posthog::match_feature_flag
Evaluate a feature flag definition against person and optional group context.
Parameters
flag: Feature flag definition to evaluate.distinct_id: Distinct ID used for person bucketing.person_properties: Person properties available to release conditions.groups: Group keys for group-targeted flags, keyed by group type.group_properties: Group properties for group-targeted flags.group_type_mapping: Mapping from PostHog group type index to group type name.
Returns
The matched flag value: Boolean(false) for inactive or unmatched flags,
Boolean(true) for matched boolean flags, or String(variant) for matched
multivariate flags.
A hand-built FeatureFlag can't express a condition with an explicit
person aggregation (JSON null under a group flag) or a group filter's own
group_type_index, so a condition without its own aggregation uses the
flag's and group filters read the condition's group type. Definitions
loaded by LocalEvaluator follow the flags service
for both.
Errors
Returns InconclusiveMatchError when required properties are missing or an
operator cannot be evaluated locally.
posthog::match_feature_flag_with_context
Match a feature flag with full context (cohorts, other flags).
This version supports cohort membership checks and flag dependency checks.
person_properties carries person-level property values; group-level
properties are looked up from ctx.group_properties when a condition (or
the flag itself) targets a group via aggregation_group_type_index.
A hand-built FeatureFlag can't express a condition with an explicit
person aggregation (JSON null under a group flag) or a group filter's own
group_type_index, so a condition without its own aggregation uses the
flag's and group filters read the condition's group type. Definitions
loaded by LocalEvaluator follow the flags service
for both.
Errors
Returns InconclusiveMatchError when local evaluation cannot determine a
result with the provided context.
posthog::match_property_with_context
Match a property with additional context for cohorts and flag dependencies.
Use this when evaluating local feature flag conditions that can reference
cohort membership (type = "cohort") or another feature flag
(type = "flag").
Errors
Returns InconclusiveMatchError when the property, cohort, or dependent
flag cannot be evaluated from the supplied context.
posthog::disable_global
Prevent the global client from being initialized.
Remarks
This does not prevent use of a global client that was already initialized.
posthog::global_is_disabled
Return true if global client initialization has been disabled.
Remarks
A disabled global client can still be used if it was initialized before it was disabled.
EndpointManager
EndpointManager
Manages PostHog API endpoints and host configuration.
This low-level helper normalizes app hosts such as
https://us.posthog.com to ingestion hosts such as
US_INGESTION_ENDPOINT.
EndpointManager::new
Create a new endpoint manager for host.
host may be an app host (for example https://eu.posthog.com), an
ingestion host, or a custom reverse-proxy host.
EndpointManager::determine_server_host
Determine the ingestion host used for API calls.
Maps PostHog app hosts to their ingestion equivalents and removes a trailing slash. Custom hosts are returned unchanged except for the trailing slash.
EndpointManager::base_host
Get the normalized base host URL used for API calls.
EndpointManager::raw_host
Get the raw host as provided by the user.
EndpointManager::build_url
Build a full URL for a given SDK endpoint.
EndpointManager::build_custom_url
Build a URL with a custom path relative to the base host.
The path may be passed with or without a leading /.
EndpointManager::build_local_eval_url
Build the local evaluation definitions URL with a project token.
The token is included as a query parameter, so avoid logging this URL in production diagnostics.
EndpointManager::api_host
Get the base host for API operations without a trailing slash or path.
FeatureFlagEvaluations
FeatureFlagEvaluations
A snapshot of evaluated feature flags for one distinct_id.
Returned by Client::evaluate_flags. Reading
flags via [is_enabled] or [get_flag] both records the access (so it can be
later attached to a capture event) and emits a deduplicated
$feature_flag_called event. [get_flag_payload] is intentionally event-free.
FeatureFlagEvaluations::keys
All flag keys present in this snapshot.
FeatureFlagEvaluations::unresolved_flags
Flags that have a loaded local definition but no value, each with the reason local evaluation couldn't resolve it.
A flag is listed when it was in the requested keys (or every loaded
flag, without EvaluateFlagsOptions::flag_keys), local evaluation was
inconclusive, and no remote /flags value filled the gap, for example
with EvaluateFlagsOptions::only_evaluate_locally. A key without a
local definition is never listed.
Listed flags are not in keys and don't change any
accessor's result. Reading one with is_enabled or
get_flag reports local_evaluation_inconclusive
instead of flag_missing.
Reading this map makes no request, doesn't count as an access and fires
no event. Snapshots returned by only and
only_accessed have no entries.
FeatureFlagEvaluations::only_accessed
A clone of the snapshot containing only flags whose values were read via
is_enabled or get_flag before
this call.
Order-dependent: if nothing has been accessed yet, the returned snapshot is empty. Pre-access the flags you want to attach before calling this.
FeatureFlagEvaluations::only
A clone of the snapshot containing only the listed keys (preserving
records). Unknown keys are dropped and surfaced via a single warning.
Use this before Event::with_flags to limit
the $feature/<key> properties attached to a captured event.
FlagPoller
FlagPoller
Synchronous poller for feature flag definitions.
Runs a background thread that periodically fetches flag definitions from
the PostHog API and updates the shared cache. Use this for blocking/sync
applications. With the async-client feature enabled, use
AsyncFlagPoller for async applications instead.
FlagPoller::new
Create a synchronous flag definition poller.
If the HTTP client cannot be built, logs a warning and leaves polling
disabled. Self::load_flags then returns Error::Connection.
Parameters
config: Credentials, host, polling interval, and request timeout.cache: Shared cache updated by the poller.
FlagPoller::start
Start the polling thread.
Performs an initial synchronous load, then refreshes definitions in the
background until FlagPoller::stop is called or the poller is dropped.
FlagPoller::load_flags
Load flags synchronously and update the cache once.
Errors
Returns Error::Connection for request failures or non-success HTTP
statuses, and Error::Serialization when the response cannot be
parsed.
FlagPoller::stop
Stop the polling thread and wait for it to exit.
LocalEvaluator
LocalEvaluator
Evaluates feature flags using locally cached definitions.
The evaluator reads from a FlagCache to determine flag values without
making network requests. Supports cohort membership checks and flag
dependencies through the evaluation context.
LocalEvaluator::new
Create an evaluator backed by a shared FlagCache.
LocalEvaluator::cache
Access the underlying flag cache (e.g. to read group type mappings).
LocalEvaluator::evaluate_flag
Evaluate a feature flag locally with full context support.
Supports cohort membership checks, flag dependency evaluation, and
group / mixed-targeting flags. groups and group_properties are
only consulted when the flag (or one of its conditions) targets a
group via aggregation_group_type_index; pass empty maps for
person-targeted flags.
The flag's definition metadata applies too, including its experiment
holdout. A flag that buckets on a device ID hashes the $device_id
person property; pass a device ID explicitly with
EvaluateFlagsOptions::device_id.
Returns
Ok(Some(value)) when the flag is present and evaluated,
Ok(None) when the flag is absent from the cache.
Errors
Returns InconclusiveMatchError when required properties, cohorts, or
dependent flags are unavailable locally, or when a device-bucketed flag
or a holdout needs a device ID or group key that wasn't passed.
LocalEvaluator::evaluate_flag_simple
Evaluate a feature flag locally without cohort or flag dependency support.
Use this when you know the flag doesn't have cohort or flag dependency conditions.
Returns
Ok(Some(value)) when the flag is present and evaluated,
Ok(None) when the flag is absent from the cache.
Errors
Returns InconclusiveMatchError when required properties are
unavailable locally.
LocalEvaluator::evaluate_all_flags
Get all flags and evaluate them with full context support.
The returned map is keyed by feature flag key. Each value can be an inconclusive error if that particular flag could not be evaluated from the supplied context.
Types
RequestContext
Analytics defaults for one request. Header identity is not proof of authentication.
RequestContext::new
RequestContext::distinct_id
RequestContext::session_id
RequestContext::property
RequestContext::option
Sets a capture option on every event in this context. An option the event sets wins,
and a null value sets nothing. A process_person_profile option does not set
process_person_profile on an identify-style event, such as $identify or
$create_alias, whose distinct ID the SDK did not generate; see
RequestContext::apply_to_event.
RequestContext::get_distinct_id
RequestContext::get_session_id
RequestContext::current
Returns a snapshot. Spawned tasks must receive and scope an explicit clone.
RequestContext::scope
Context exists only while the future is polled, including error and cancellation paths.
RequestContext::event
Without identity, this uses the SDK's ordinary personless event behavior.
RequestContext::apply_to_event
Pins these defaults before delivery. Explicit event identity, properties and options win.
An identify-style event, such as $identify or $create_alias, first gets
process_person_profile from its own option or $process_person_profile property,
else true unless the SDK generated its distinct ID, so the context cannot turn
person processing off for it.
RequestContext::exception_options
BeforeSendHook
Hook that can modify or discard events before they are sent.
Hooks run before serialization. Return Some(event) to continue sending the
event, or None to drop it.
Hook panics are caught and cause the current event to be dropped. If a hook keeps mutable state, a panic can leave that state partially updated; the SDK recovers the hook mutex and subsequent events continue through the same hook.
BeforeSendHook::new
Create a new before-send hook.
CaptureCompression
Variants
GzipDeflateBrZstd
Request-body compression algorithm for the capture pipelines.
When set on ClientOptions, capture requests are compressed and the
matching Content-Encoding header is sent. The variant string matches the
HTTP Content-Encoding token the server expects. All four variants are
accepted by the capture endpoint.
CaptureSummary
The outcome of an immediate capture ([Client::capture_immediate] /
[Client::capture_batch_immediate]), returned once the SDK has a terminal
result for the batch — the request succeeded, or the retry budget was spent
(which is an Err instead).
A returned CaptureSummary means the capture request itself succeeded (HTTP
2xx). The backend reports a per-event verdict, so a 2xx can still leave
some events unpersisted (drop/retry) — check
all_persisted / not_persisted
before treating the batch as fully durable.
#[non_exhaustive]: fields are read through accessors so more can be added
without breaking callers.
CaptureSummary::submitted
Number of events that reached a verdict (after before_send filtering):
the events sent on the wire, plus any AI event the SDK did not send
because it was over the size limit. Such an event has a local drop
verdict in event_results.
CaptureSummary::not_persisted
Number of submitted events the backend did not persist.
submitted minus the events with an ok/warning verdict, so it counts
both drop/retry verdicts and any submitted event the backend omitted
from its response, including copies dropped as duplicates.
CaptureSummary::all_persisted
Whether every submitted event was persisted (not_persisted() == 0).
Note this is vacuously true when nothing was sent (submitted() == 0),
which is what a disabled client or a fully before_send-filtered batch
returns. Callers that advance durable state on the strength of an immediate
delivery (e.g. committing an upstream offset) must therefore also check
submitted() against the number of events they intended to send — do not
gate durability on all_persisted() alone.
CaptureSummary::event_results
Per-event server verdicts. Includes persisted
(ok/warning) and unpersisted (drop/retry) verdicts; filter by
EventStatus to isolate failures. May omit events
the backend did not report on — see not_persisted.
An entry's duplicates_dropped counts
lost copies that shared its uuid; they have no entry of their own.
ClientOptions
Configuration options for the PostHog client.
Use ClientOptionsBuilder to construct options with custom settings, or
create options directly from a project API key with
ClientOptions::from("your-api-key").
Example
ClientOptions::is_disabled
Check whether the client is disabled.
A client is disabled when configured with disabled(true), when the
project API key is missing or blank after trimming, or when it is a
personal API key (phx_...), which PostHog never accepts for capture.
ClientOptionsBuilder
Builder for ClientOptions.
ClientOptionsBuilder::host
Host URL for the PostHog API. Defaults to the US ingestion endpoint.
App hosts such as https://eu.posthog.com are normalized to ingestion
hosts before requests are sent.
ClientOptionsBuilder::api_key
PostHog project API key (project token). If missing or blank, the client is disabled.
ClientOptionsBuilder::http_client
Optional async HTTP client for immediate capture, flags, and local evaluation.
Defaults to an SDK-created client. Clones share the supplied connection pool.
The SDK still applies request_timeout_seconds to capture and local
evaluation, and feature_flags_request_timeout_seconds to remote flags.
These options replace the supplied client's request timeout, even when the
client's timeout is shorter. Background capture uses blocking_http_client;
see its documentation for the limits of shutdown_timeout_ms.
Only supply clients whose default headers and cookies are safe to send to
PostHog. Do not share clients carrying credentials for unrelated services;
the SDK cannot inspect or filter those defaults. The SDK keeps the
supplied client's redirect policy; the capture and /flags clients it
builds follow only 307 and 308 redirects to the same scheme, host and port.
Email attachments upload to PostHog's file store through a client the SDK
builds, so these defaults never reach it. Nor do the supplied client's root
certificates, TLS options or proxy: that client trusts the system's roots
and takes its proxy from the environment, such as HTTPS_PROXY.
ClientOptionsBuilder::blocking_http_client
Optional blocking HTTP client for blocking requests and background capture.
Defaults to SDK-created clients. Clones share the supplied connection pool.
The SDK still applies request_timeout_seconds to capture and local
evaluation, and feature_flags_request_timeout_seconds to remote flags.
These options replace the supplied client's request timeout, even when the
client's timeout is shorter.
shutdown_timeout_ms bounds shutdown draining and caps requests started
during that drain at the remaining deadline. It does not interrupt work
already underway. An in-flight request can delay shutdown() or Drop
until request_timeout_seconds expires; an automatic multi-batch flush
already underway can delay teardown by several request timeouts.
It is not a hard limit on the total time spent waiting for the worker.
Only supply clients whose default headers and cookies are safe to send to
PostHog. Do not share clients carrying credentials for unrelated services;
the SDK cannot inspect or filter those defaults. The SDK keeps the
supplied client's redirect policy; the capture and /flags clients it
builds follow only 307 and 308 redirects to the same scheme, host and port.
Email attachments upload to PostHog's file store through a client the SDK
builds, so these defaults never reach it. Nor do the supplied client's root
certificates, TLS options or proxy: that client trusts the system's roots
and takes its proxy from the environment, such as HTTPS_PROXY.
Create and finally drop application-owned blocking clients, including handles held in options and builders, outside async runtimes. SDK shutdown does not invalidate application-held clones. Both setters require a compatible reqwest version (currently 0.13).
ClientOptionsBuilder::request_timeout_seconds
Per-request timeout in seconds for capture, batch, and local evaluation
definition requests. Defaults to 30.
Also applies to custom HTTP clients, replacing their request timeout even
when that timeout is shorter. Remote flags use feature_flags_request_timeout_seconds.
ClientOptionsBuilder::secret_key
Secret key used for local feature flag evaluation and remote config.
Accepts either a Personal API Key (phx_...) or a Project Secret API
Key (phs_...). Required when enable_local_evaluation is true.
Client::emails needs a Project Secret API Key with the
transactional_email:write scope to send email, or
transactional_email:read to read an email's status. The client also
sends this key to host when enable_local_evaluation loads flag
definitions and when you call Client::get_remote_config_payload.
When host is a proxy that must not see the key, send email from its
own client whose host is PostHog's, and leave secret_key off the
proxy client.
ClientOptionsBuilder::app_host
Your PostHog app host, such as https://posthog.example.com, for
Client::emails. Needed only when host is not PostHog Cloud, such
as a reverse proxy: email requests carry the secret key, so they never
go to a custom host. Without it, a PostHog Cloud host such as
https://eu.i.posthog.com sends email to its region's app host, and
any other host fails each email request with missing_app_host.
From 1.1.2, email requests go to /api/messaging/ on this host. A
self-hosted PostHog serves it from its 2026-11-18 version, and an older
one answers 404.
ClientOptionsBuilder::email_request_timeout_seconds
Per-request timeout in seconds for Client::emails. Defaults to 15.
Also applies to custom HTTP clients, replacing their request timeout.
ClientOptionsBuilder::email_request_max_retries
Maximum number of retries of an email request after a network error,
a rate limit other than quota_limited, a send with the same
idempotency key in flight, or an unavailable service. Defaults to 2.
Retry n, counting from 0, waits about 2^n seconds, at most 30, so
1 and then 2 seconds by default, or the server's Retry-After when
that is longer. A Retry-After over 30 seconds fails at once.
Set to 0 when a job runner already retries the send. A send can
override it with max_retries.
ClientOptionsBuilder::migrated_from
The email provider your sends moved from, such as "resend", sent with
each email request so PostHog knows where your sends came from.
ClientOptionsBuilder::enable_local_evaluation
Enable local evaluation of feature flags using a background definitions poller.
ClientOptionsBuilder::poll_interval_seconds
Interval for polling flag definitions, in seconds. Defaults to 30.
ClientOptionsBuilder::disabled
Disable tracking and remote flag requests. Useful for development and tests.
ClientOptionsBuilder::disable_geoip
Disable automatic GeoIP enrichment for capture and flag requests.
ClientOptionsBuilder::is_server
Whether events originate from a server-side runtime. Defaults to true,
which stamps $is_server: true so PostHog won't attribute the host OS to
the user. Set false for client/CLI use (the property is then omitted).
ClientOptionsBuilder::feature_flags_request_timeout_seconds
Per-request timeout in seconds for remote /flags requests. Defaults to 3.
Also applies to custom HTTP clients, replacing their request timeout even
when that timeout is shorter. Capture and local-evaluation polling use
request_timeout_seconds.
ClientOptionsBuilder::feature_flags_request_max_retries
Maximum number of retries after a transient remote /flags failure
(transport error or HTTP 502/504). Defaults to 1. Set to 0 to
disable retries.
ClientOptionsBuilder::error_tracking
Error tracking stacktrace and frame classification options
ClientOptionsBuilder::local_evaluation_only
When true, never fall back to the remote API for flag evaluation. If local
evaluation is inconclusive (flag not cached or missing properties), the SDK
returns Ok(None) instead of making a network call. Only meaningful when
enable_local_evaluation is also true.
ClientOptionsBuilder::max_capture_attempts
Maximum number of attempts for capture requests (default: 4).
Includes the initial attempt, so 4 means 1 initial + 3 retries.
ClientOptionsBuilder::retry_initial_backoff_ms
Initial capture retry backoff duration in milliseconds (default: 100).
Remote /flags retries use their own fixed backoff.
ClientOptionsBuilder::retry_max_backoff_ms
Maximum capture retry backoff duration in milliseconds (default: 30000)
ClientOptionsBuilder::flush_at
Number of buffered events that triggers an automatic flush (default: 100).
ClientOptionsBuilder::max_batch_size
Maximum number of events sent in a single batch request (default: 100). A flush of more than this many events is split into multiple requests.
ClientOptionsBuilder::flush_interval_ms
Interval between automatic time-based flushes, in milliseconds (default: 5000).
ClientOptionsBuilder::max_queue_size
Maximum number of events buffered before new events are dropped (default: 10000). A single warning is logged while the queue is full.
ClientOptionsBuilder::shutdown_timeout_ms
Maximum time shutdown() and Drop spend draining buffered and
retrying events before abandoning the rest, in milliseconds (default:
30000). This bounds the drain itself, including any delivery the drain
starts. It does not bound work already underway: each background
worker (analytics, and the AI lane once used) performs one blocking send
at a time, so an automatic flush or drain in progress when shutdown is
requested runs to completion first — up to request_timeout_seconds
per in-flight batch, including with a custom blocking client, so a large
auto-drain can delay teardown by several request timeouts. The lanes
drain concurrently, so the budget is shared, not doubled. flush() is
unaffected.
ClientOptionsBuilder::capture_compression
Optional request-body compression. When None (default), bodies are
sent uncompressed. The capture endpoint supports all variants.
ClientOptionsBuilder::capture_ai_compression
Compression for capture_ai* bodies; unset (default) sends them
uncompressed. Prefer Zstd: AI events are large JSON.
ClientOptionsBuilder::capture_ai_max_queue_size
Maximum capture_ai* events buffered before new ones are dropped
(default: 1000). Lower than max_queue_size because AI events can be
multi-MB; a single warning is logged while the queue is full.
ClientOptionsBuilder::before_send
Add a hook that can modify or discard events before they are sent.
Hooks should avoid panicking. Panics are caught and drop the current event, but any mutable state captured by the hook may be left partially updated and will be reused on subsequent calls.
ClientOptionsBuilder::on_error
Add a hook for terminal network failures and storage errors.
The hook receives a PostHogError once per terminal capture failure,
failed remote /flags request, or failed local-evaluation poll. With
persistent delivery, it also receives storage read, write, and removal
errors. A failed write drops that event (reported once per run of
failures). A record that cannot be read is dropped and its file
deleted. An event whose record could not be removed after it left the
queue (delivered, reported lost, evicted, or unreadable) can come back
after a restart, as can an event in flight at shutdown.
Multiple hooks fire in registration order.
Observability only — never emit from the hook
The hook MUST NOT call back into the SDK (capture/capture_batch/
capture_exception, flush, or shutdown): emitting an event while
handling a capture failure forms an amplification loop. The hook is
Fn + Send + Sync and invoked without holding any SDK lock, so it may
run concurrently on multiple threads and must be internally thread-safe.
Keep it cheap and non-blocking; capture and storage callbacks run on the
background transport thread. Panics are caught and ignored.
Registering a hook silences the default WARN for terminal capture
reject/exhaustion, serialization failures, and worker storage errors (the
caller now owns those signals). Shutdown-timeout, queue-full, and
before_send drops, and retryable failures that shutdown stops from being
retried, keep their WARN logs and do not fire the hook. A batch that
has used all max_capture_attempts still fires it. Stateful delivery
has no attempt limit, so its retryable failures never fire it.
The existing /flags and poller WARN logs are unaffected.
ClientOptionsBuilder::build
Build sanitized ClientOptions.
Missing, whitespace-only and personal (phx_...) API keys are allowed and
disable the client with one error log, so SDK initialization remains
infallible and never sends a key PostHog would reject.
Errors
Returns ClientOptionsBuilderError if a required builder value is
invalid according to the generated builder.
ClientOptionsBuilderError
Variants
UninitializedField(&'static str)- Uninitialized fieldValidationError(::derive_builder::export::core::string::String)- Custom validation error
Error type for ClientOptionsBuilder
CaptureFailure
Details of a terminal capture batch failure.
Fields are read through accessors; the struct is #[non_exhaustive].
Does not fire for shutdown-timeout, queue-full, before_send, or local
oversize-AI-event drops — those are not delivery failures.
CaptureFailure::endpoint_kind
The capture endpoint the failed batch targeted: Endpoint::Capture
for capture/capture_batch, Endpoint::CaptureAi for
capture_ai/capture_ai_batch. Lets one hook tell the lanes apart.
FlagsFailure::endpoint is the request URL instead.
CaptureFailure::error
The batch-level cause: a permanent reject, exhausted transport/HTTP retries, or a serialization failure.
None when the request succeeded (2xx) but individual events were
rejected or exhausted finite retries. With persistent delivery, permanent
failures can be reported while retryable events remain queued; None
does not mean the original batch has finished. Inspect
event_results.
CaptureFailure::status
The HTTP status of the final attempt, or None when no response was
received (a transport error or a serialization failure before sending).
CaptureFailure::attempt
The failing attempt number (equals the configured maximum on exhaustion).
CaptureFailure::event_count
Number of events this failure dropped (lost).
Counts only undelivered events (retry/drop). With finite retries this
includes losses finalized on earlier attempts. Persistent delivery counts
only permanent losses in this callback, not retained retryable events or
losses reported by earlier callbacks. This can be smaller than
event_results.len(), which also reports persisted
ok/warning verdicts; filter by status before treating an entry as lost.
It also counts each copy capture dropped because an earlier event in the
same request had its uuid, as reported by an entry's
duplicates_dropped.
CaptureFailure::historical_migration
Whether the batch was a historical-migration batch.
CaptureFailure::request_id
The capture posthog-request-id of the final attempt, when one was
sent. None for a serialization failure where no request reached the
wire.
CaptureFailure::event_results
Per-event server verdicts for the capture batch.
Maps event UUID to its EventResult. Includes persisted (ok/warning)
as well as lost (retry/drop) verdicts, so this map can be larger than
event_count; filter by
EventStatus to isolate the failures.
With finite retries, includes all verdicts the batch collected: complete
when error is None, or possibly partial on a batch-level
failure. With persistent delivery, a callback can report permanent failures
before the batch finishes. Retained retryable events are absent from this
map, and later callbacks can omit verdicts reported by earlier callbacks.
An entry's duplicates_dropped counts
lost copies that shared its uuid; they have no entry of their own.
CaptureFailure::verdict_summary
One line with every drop and retry reason in the batch and its count, drops first
and most frequent first, for example drop/invalid_options=2, retry/not_persisted=1,
or an empty string when nothing was lost. Dropped duplicate copies show as
drop/duplicate_event_uuid.
Reasons come from the server, so the summary strips control characters and line
separators, cuts each reason to 64 characters, and shows a missing one as unspecified.
CaptureFailure::error_response
The structured error body returned by the capture backend on a
non-2xx response (error, error_description, error_uri), when the
body parsed as one. None for a transport error, a 2xx, or an
unrecognizable body — the raw body remains available via
error.
FlagsFailure
Details of a failed remote /flags request.
Fields are read through accessors; the struct is #[non_exhaustive].
FlagsFailure::error
The cause of the failure (Error::Connection for transport or
non-success status, Error::Serialization for an unparseable body).
FlagsFailure::endpoint
The /flags endpoint URL the request targeted.
FlagsFailure::distinct_id
The distinct_id the request was evaluating flags for, when known.
FlagsFailure::status
The HTTP status, or None when no response was received (a transport
error or an exhausted transient-retry budget).
FlagsFailure::body
The response body, when one was read (present on a non-success status).
LocalEvaluationFailure
Details of a failed local-evaluation definitions poll.
Fields are read through accessors; the struct is #[non_exhaustive].
Credentials (the personal API key) are never surfaced here.
LocalEvaluationFailure::error
The cause of the failure (Error::Connection for transport or
non-success status, Error::Serialization for an unparseable body).
LocalEvaluationFailure::status
The HTTP status, or None when no response was received (a transport
error).
PostHogError
Variants
Capture(CaptureFailure<'a>)- A capture batch the SDK gave up delivering (permanent reject, exhausted retries, serialization failure) or — on the V1 pipeline — a2xxwhose per-event verdicts left events unpersisted after the retry budget.FeatureFlags(FlagsFailure<'a>)- A remote/flagsrequest that failed (transport error, non-success status, or an unparseable response body).LocalEvaluation(LocalEvaluationFailure<'a>)- A background local-evaluation definitions poll that failed (transport error, non-success status, or an unparseable response body). The SDK keeps serving the previously cached definitions.Storage(StorageFailure<'a>)- A persistence operation failed. For queued events, a failed write or read loses that event. For client state, the in-memory state remains usable, and what could not be persisted may be lost when the process exits.Initialization(InitializationFailure)- A stateful client could not be enabled. The returned client is disabled.RemoteConfig(RemoteConfigFailure)- A stateful remote-configuration request failed. Cached settings remain usable.Replay(ReplayFailure)- A screenshot failed encoding, validation or terminal delivery.
A delivery, feature flag, local evaluation, remote configuration, storage,
or initialization failure, passed by reference to each registered on_error
hook.
#[non_exhaustive]: new variants may be added as more surfaces gain hook
coverage, so a match must include a wildcard arm.
StorageError
An immutable snapshot of an I/O or decoding error. It preserves the error kind, OS code and display message without retaining a backend's mutable source.
StorageError::kind
The classification of the original I/O error.
StorageError::raw_os_error
The OS error code, when the original error supplied one.
StorageFailure
Details of a storage failure. The callback runs on the thread performing storage I/O, not on an ordinary capture caller.
For client state, a failed write does not roll back the in-memory state. For queued events, a failed write leaves no record and the event is dropped. An event whose record could not be removed after it left the queue (delivered, reported lost, evicted, or unreadable) can come back after a restart, as can an event in flight at shutdown.
StorageFailure::operation
The operation that failed.
StorageFailure::error
An immutable diagnostic for the I/O or decoding error. The message may contain paths or other application context supplied by the backend.
StorageOperation
Variants
Open- Opening or acquiring exclusive ownership of a store.Read- Reading or decoding persisted data.Write- Writing or replacing persisted data.Remove- Removing a persisted record.
The persistence operation that failed.
Endpoint
Variants
Capture- Analytics event capture endpoint (capture,capture_batch, and their immediate variants).CaptureAi- AI event capture endpoint (capture_ai,capture_ai_batch, and their immediate variants). A separate lane with its own size limits.Flags- Feature flags endpointLocalEvaluation- Local evaluation endpoint
API endpoints used by the SDK for different operations.
#[non_exhaustive]: new endpoints can be added without breaking callers.
Endpoint::path
Get the URL path for this endpoint.
Error
Variants
Connection(String)- Network or HTTP error when communicating with PostHog APISerialization(String)- Error serializing or deserializing JSON dataAlreadyInitialized- Global client was already initialized viainit_globalNotInitialized- Global client was not initialized before usePanicHookAlreadyInstalled- Panic autocapture hook was already installedInvalidTimestamp(String)- Timestamp could not be parsed or is invalidInvalidArgument(String)- An argument was invalid, such as a blank IDInconclusiveMatch(String)- Flag evaluation was inconclusive (e.g., missing required properties, unknown operator)RateLimit- HTTP 429 — the server is rate limiting requestsBadRequest(String)- HTTP 400 or 413 — the request was malformed or too largeServerError { .. }- HTTP 5xx — the server encountered an errorUnauthorized- HTTP 401 — invalid or missing Bearer tokenBillingLimitExceeded(String)- HTTP 402 — billing quota exceeded (non-retryable)Email(emails::EmailError)- A transactional email request failed; seeEmailError.
Errors that can occur when using the PostHog client.
CaptureExceptionOptions
Optional context for capture_exception_with: person identity, custom
properties, capture options, groups, trace context, and exception
fingerprint/level.
All fields are optional. An empty options set (new() / Default)
captures the exception personlessly with no extra context. With the
trace-context provider configured on ErrorTrackingOptions, its trace
and span IDs are attached automatically; values set here take precedence.
A $trace_id or $span_id set with CaptureExceptionOptions::property
also wins: the provider's IDs are then not added at all.
Examples
CaptureExceptionOptions::new
Create an empty options set: personless, no extra context.
CaptureExceptionOptions::distinct_id
Associate the exception with a person.
CaptureExceptionOptions::property
Add a custom property to the exception event.
CaptureExceptionOptions::option
Set a capture option on the exception event; see Event::insert_option.
CaptureExceptionOptions::group
Capture the exception as a group event.
Adding a group does not change person processing. An exception without
a distinct ID is personless, and PostHog attaches groups for group
analytics only to events that process person profiles. Set
option("process_person_profile", true) to count it for its groups.
CaptureExceptionOptions::trace_context
Associate the exception with a span in a distributed trace.
The IDs are accepted together so an exception can never combine a trace
ID and span ID from different contexts. This pair overrides any context
returned by the client's trace-context provider, and any $trace_id or
$span_id set with CaptureExceptionOptions::property.
CaptureExceptionOptions::fingerprint
Set a custom exception fingerprint.
CaptureExceptionOptions::level
Set the exception severity level. Defaults to "error".
ErrorTrackingOptions
Client-level Error Tracking configuration, applied to every exception the
client captures. Set it via ErrorTrackingOptionsBuilder on
ClientOptions::error_tracking.
Examples
ErrorTrackingOptionsBuilder
Builder for ErrorTrackingOptions.
ErrorTrackingOptionsBuilder::capture_stacktrace
Capture a stack trace at the capture_exception call site and attach
it to the first entry of $exception_list (default: true).
The trace shows where the error was captured, not where it was
created — a bubbled-up Err value carries no stack of its own. The
error type/message chain in $exception_list is always sent regardless
of this setting. Disabling it skips the stack walk and per-frame symbol
resolution entirely, which can matter when capturing handled errors in
high-volume paths.
ErrorTrackingOptionsBuilder::in_app_include_paths
Treat only frames matching one of these patterns as in-app. Patterns
are substring matches against a frame's file path and function
symbol, so both path fragments ("/service/") and crate prefixes
("my_service::") work. When empty, built-in defaults apply: frames
from the cargo registry, the standard library, and vendored/target
paths are library frames, everything else is in-app.
ErrorTrackingOptionsBuilder::in_app_exclude_paths
Always mark matching frames as not in-app, taking precedence over
includes and defaults. Same matching rules as in_app_include_paths
— e.g. "other_crate::" excludes every frame of that crate.
ErrorTrackingOptionsBuilder::capture_panics
When true, crate::init_global installs a process-wide panic hook
that captures panics as $exception events through the global client.
Defaults to false — panic autocapture is opt-in.
Only the global client installs a hook: a panic hook is process-global
(std::panic::set_hook), so it pairs with the process-global client, and
there is intentionally no per-Client panic API for now.
ErrorTrackingOptionsBuilder::build
Builds a new ErrorTrackingOptions.
Errors
If a required field has not been initialized.
ErrorTrackingOptionsBuilder::trace_context_provider
Set a callback that returns the distributed trace context active at an exception's capture site.
The callback runs synchronously during capture_exception. It must be
fast, non-blocking, and must not call back into the PostHog SDK. Panics
are caught and cause trace context to be omitted from that exception.
The callback is skipped for an exception that sets a $trace_id or
$span_id property or an explicit
CaptureExceptionOptions::trace_context.
ErrorTrackingOptionsBuilderError
Variants
UninitializedField(&'static str)- Uninitialized fieldValidationError(::derive_builder::export::core::string::String)- Custom validation error
Error type for ErrorTrackingOptionsBuilder
TraceContext
An atomic trace/span identifier pair used to correlate an exception with distributed traces and logs.
TraceContext::new
Create a trace context from its trace and span identifiers.
Event
An Event represents an interaction a user has with your app or
website. Examples include button clicks, pageviews, query completions, and signups.
See the PostHog documentation
for a detailed explanation of PostHog Events.
Event::insert_prop
Add a property to the event.
Parameters
key: Property name.prop: Any value that can be serialized to JSON.
Errors
Returns Error::Serialization if prop cannot be serialized.
Event::remove_prop
Remove a property from the event and return its previous value, if any.
Event::insert_option
Set a capture option that tells PostHog how to process the event, such
as "process_person_profile".
Parameters
key: Option name.value: Any value that can be serialized to JSON.
Errors
Returns Error::Serialization if value cannot be serialized.
Remarks
Sent unchecked: PostHog ignores unknown keys and drops the event if a known key has an unusable value. Legacy option properties still work, but an option overrides its legacy property. Use options.
Event::remove_option
Remove a capture option from the event and return its previous value, if any.
Event::add_group
Capture this as a group event.
See https://posthog.com/docs/product-analytics/group-analytics#link-events-to-groups.
Parameters
group_name: Group type, such as"company".group_id: Stable identifier for the group.
Remarks
Adding a group does not change person processing. PostHog attaches
groups for group analytics only to events that process person profiles,
so an event from Event::new_anon needs
insert_option("process_person_profile", true) to count for its groups.
Event::set_timestamp
Set the event timestamp, for events that happened in the past.
Parameters
timestamp: Timestamp to send with the event. UTC input is preferred; non-UTC input is converted to the equivalent UTC instant before serialization.
Errors
Never returns an error; PostHog clamps timestamps far in the future.
The Result stays so existing callers keep compiling.
Event::alias
Build the $create_alias event that crate::Client::alias sends, so you
can set options on it before you capture it.
Parameters
previous_id: ID already known to PostHog, such as an anonymous ID.distinct_id: ID it should be merged into, such as a logged-in user ID.
Returns
The event, attributed to previous_id, which is also mirrored into
properties.distinct_id alongside the merge target in properties.alias.
Errors
Returns Error::InvalidArgument when either ID is blank, because a merge
needs both sides.
Remarks
The SDK sends process_person_profile: true on this event unless you set
the option, so a request context cannot turn person processing off for it.
Examples
Event::group_identify
Build the $groupidentify event that crate::Client::group_identify
sends, so you can set options on it before you capture it.
Parameters
group_type: Group type, such as"company".group_key: Unique identifier for the group, such as an ID in your database.properties: Any serializable object or JSON map of group properties.
Returns
The event, with $group_type, $group_key, and $group_set in its
properties. Its distinct ID is the request context's distinct ID when one
is set, else $<group_type>_<group_key>.
Errors
Returns Error::InvalidArgument when group_type or group_key is
blank. Returns Error::Serialization if properties fails to serialize
to JSON, or if it does not serialize to a JSON object. PostHog requires
$group_set to be an object and silently drops the event otherwise.
Remarks
The SDK sends process_person_profile: true on this event unless you set
the option, so a request context cannot turn person processing off for it.
Examples
Event::set_uuid
Override the auto-generated UUID for this event.
Useful for deduplication when re-importing historical data. Every
capture of an event with this uuid sends the same uuid. When one request
contains a uuid twice, PostHog keeps the first event and drops the later
copies, which the SDK reports with the reason duplicate_event_uuid.
Event::with_flags
Attach the flag state captured by a FeatureFlagEvaluations snapshot
to this event.
Adds $feature/<key> for every evaluated flag plus a sorted
$active_feature_flags list of enabled keys, mirroring what
send_feature_flags would otherwise fetch — but without making an
extra /flags request.
A property already on the event keeps its value, so the caller can
override a $feature/<key> or $active_feature_flags value whether it
is set before or after this call.
Returns
Returns self so calls can be chained before capture.
Event::event_name
Return the event name.
Event::distinct_id
Return the event distinct ID.
Event::properties
Return the event properties.
Event::options
Return the event's capture options, as set by Event::insert_option.
CaptureErrorResponse
Fields
error: Stringerror_description: Option<String>error_uri: Option<String>
CaptureResponse
Fields
results: std::collections::HashMap<uuid::Uuid, EventResult>
EventResult
Fields
result: EventStatusdetails: Option<String>duplicates_dropped: Option<u32>- Number of later copies of this uuid in the same request that capture dropped.resultanddetailsdescribe the first copy, which capture kept; each dropped copy is lost with the reasonduplicate_event_uuid.
EventStatus
Variants
OkDropWarningRetryUnknown
Only Retry is resent; all other variants are terminal.
Unknown (#[serde(other)]) is a forward-compat catch-all that deserializes
unrecognised statuses as terminal rather than failing the parse.
EvaluateFlagsOptions
Fields
groups: Option<std::collections::HashMap<String, String>>- Group keys for group-targeted feature flags, keyed by group type (for example{ "company": "company_123" }). These groups are also attached to$feature_flag_calledevents emitted by the returned snapshot.person_properties: Option<std::collections::HashMap<String, serde_json::Value>>- Person properties used by remote or local flag evaluation. Provide any properties referenced by release conditions when using local evaluation.group_properties: Option<std::collections::HashMap<String, std::collections::HashMap<String, serde_json::Value>>>- Group properties used by group-targeted or mixed-targeting flags, keyed first by group type and then by property name.person_property_keys_known_absent: Option<Vec<String>>- Person property keys known to be absent for this evaluation. Local evaluation treats a listed key as absent even whenperson_propertiesholds a value for it:is_not_setand the negated operators (is_not,not_icontains,not_starts_with,not_ends_with,not_regex) match, and every other supported operator doesn't. The condition value isn't parsed, so an invalid regex, number, version or date gives the same result as a valid one. Operators this SDK doesn't support and a missing or null condition value stay inconclusive, except foris_setandis_not_set. Listed keys resolvetype: "person"filters and person cohort leaves, including in conditions aggregated on a group;person_metadataand other filter types never resolve from the list. Keys starting with__posthog_person_metadata__are ignored locally. The list is also sent asperson_property_keys_known_absentwhen the/flagsrequest is made.group_property_keys_known_absent: Option<std::collections::HashMap<String, Vec<String>>>- Group property keys known to be absent for this evaluation, keyed by group type. Keys listed for one group type only resolvetype: "group"filters whosegroup_type_indexnames that group type, whatever the condition aggregates on, never cohort filters or any other filter type. Otherwise these followperson_property_keys_known_absent, including the limit of 1000 keys per group type. Sent asgroup_property_keys_known_absentwhen the/flagsrequest is made.only_evaluate_locally: bool- Whentrue, skip the remote/flagsrequest and return only locally evaluated results. If local evaluation is not configured, the snapshot is empty.disable_geoip: Option<bool>- Per-call override for GeoIP behavior on/flagsand$feature_flag_calledrequests.Noneuses the client-level setting.flag_keys: Option<Vec<String>>- Optional list of flag keys. When provided, only these flags are evaluated — the underlying/flagsrequest asks the server for just this subset, which makes the response smaller and the request cheaper. An explicitly empty list returns an empty snapshot without local or remote evaluation;Noneevaluates all flags.device_id: Option<String>- Device ID for flags that bucket on the device instead of the distinct ID. WhenNoneor empty, local evaluation reads a non-empty string$device_idperson property instead. Only an explicit value is sent to/flags, as the top-leveldevice_id.
Optional inputs for Client::evaluate_flags.
This struct is non-exhaustive so more options can be added in minor releases.
Create it with Default and then set the fields you need.
CohortDefinition
Fields
id: String- Unique identifier for the cohort.properties: serde_json::Value- Properties can be either: - A JSON object with "type" and "values" for complex property groups - Or a directVec<Property>for simple cases
Definition of a cohort for local evaluation
CohortDefinition::new
Create a new cohort definition with a simple property list.
Parameters
id: Cohort identifier.properties: Property filters that define cohort membership.
CohortDefinition::parse_properties
Parse the properties from the JSON structure.
PostHog cohort properties come in format:
{"type": "AND", "values": [{"type": "property", "key": "...", "value": "...", "operator": "..."}]}.
EvaluationContext
Fields
cohorts: &'a std::collections::HashMap<String, CohortDefinition>- Cohort definitions available to local evaluation, keyed by cohort ID.flags: &'a std::collections::HashMap<String, FeatureFlag>- Feature flag definitions available to evaluate flag dependencies, keyed by flag key.distinct_id: &'a str- Distinct ID used for person-targeted flag bucketing.groups: &'a std::collections::HashMap<String, String>- Group keys for group-targeted flags, keyed by group type.group_properties: &'a std::collections::HashMap<String, std::collections::HashMap<String, serde_json::Value>>- Group properties for group-targeted flags, keyed by group type and then property name.group_type_mapping: &'a std::collections::HashMap<String, String>- Mapping from PostHog group type index to group type name.property_matching_version: i64- Matching semantics pinned to the definitions snapshot. Exactly2uses explicit equality;1(and other versions) uses legacy boolean coercion.
Context for evaluating properties that may depend on cohorts or other flags.
groups, group_properties, and group_type_mapping are used to resolve
group-targeted and mixed-targeting flags. A group condition (one whose
aggregation_group_type_index is set, either at the flag or condition level)
is bucketed on the group key and matched against group properties looked up
via the group type mapping.
FeatureFlag
Fields
key: String- Unique identifier for the flag (e.g., "new-checkout-flow")active: bool- Whether the flag is currently active. Inactive flags always return false.filters: FeatureFlagFilters- Targeting rules and rollout configurationhas_experiment: Option<bool>- Whether the flag is linked to an experiment, as reported by the local-evaluation definitions endpoint. Tri-state:Some(true)/Some(false)when the server reports it,Nonewhen it does not (older server). Drives the$feature_flag_has_experimentproperty and event minimization.
A feature flag definition from PostHog.
Contains all the information needed to evaluate whether a flag should be enabled for a given user, including targeting rules and rollout percentages.
FeatureFlagCondition
Fields
properties: Vec<Property>- Property filters that must all match (AND logic)rollout_percentage: Option<f64>- Percentage of matching users who should see this flag (0-100)variant: Option<String>- Specific variant to serve for this condition (for variant overrides)aggregation_group_type_index: Option<i32>- Optional per-condition aggregation override used by mixed-targeting flags. When set, this condition targets the specified group type instead of the flag-level aggregation.Nonemeans person targeting under a mixed flag.
A single condition group within a feature flag's targeting rules.
All properties within a condition must match (AND logic), and the user must fall within the rollout percentage to be included.
FeatureFlagFilters
Fields
groups: Vec<FeatureFlagCondition>- List of condition groups (evaluated with OR logic between groups)multivariate: Option<MultivariateFilter>- Multivariate configuration for A/B tests with multiple variantspayloads: std::collections::HashMap<String, serde_json::Value>- JSON payloads associated with flag variantsaggregation_group_type_index: Option<i32>- Group type index this flag targets at the flag level.Nonemeans person targeting (or mixed, when individual conditions set their own).early_exit: bool- Whentrue, local evaluation stops and returns a definitive disabled result as soon as a condition group's property filters match (or it has no property filters) but the rollout percentage excludes the user, instead of falling through to later condition groups. Defaults tofalse, which preserves the legacy fall-through behavior.
Targeting rules and configuration for a feature flag.
FeatureFlagsResponse
Variants
V2 { .. }- v2 API format from/flags/?v=2endpointLegacy { .. }- Legacy format from older decide endpoint
Response from the PostHog feature flags API.
Supports both the v2 API format (with detailed flag information) and the legacy format (simple flag values and payloads).
FeatureFlagsResponse::normalize
Convert the response to normalized flag values and payloads.
Returns
A tuple of (feature_flags, feature_flag_payloads), each keyed by flag
key.
FlagDetail
Fields
key: String- The feature flag keyenabled: bool- Whether the flag is enabled for this uservariant: Option<String>- The variant key if this is a multivariate flagreason: Option<FlagReason>- Reason explaining why the flag evaluated to this valuemetadata: Option<FlagMetadata>- Additional metadata about the flag
Detailed information about a feature flag evaluation result.
Returned by the /flags/?v=2 endpoint with extended information about why a
flag evaluated to a particular value.
FlagMetadata
Fields
id: u64- Unique identifier for this flagversion: u32- Version number of the flag definitiondescription: Option<String>- Optional description of what this flag controlspayload: Option<serde_json::Value>- Optional JSON payload associated with the flaghas_experiment: Option<bool>- Whether the flag is linked to an experiment. Tri-state:Some(true)/Some(false)when the/flags?v=2metadata reports it,Nonewhen it is absent (older server or degraded response). Drives the$feature_flag_has_experimentproperty and event minimization.
Metadata about a feature flag from the PostHog server.
FlagReason
Fields
code: String- Reason code (e.g., "condition_match", "out_of_rollout_bound")condition_index: Option<usize>- Index of the condition that matched (if applicable)description: Option<String>- Human-readable description of the reason
Explains why a feature flag evaluated to a particular value.
FlagValue
Variants
Boolean(bool)- Flag is either enabled (true) or disabled (false)String(String)- Flag returns a specific variant key (e.g., "control", "test", "variant-a")
The value of a feature flag evaluation.
Feature flags can return either a boolean (enabled/disabled) or a string (for multivariate flags where users are assigned to different variants).
InconclusiveMatchError
Fields
message: String- Human-readable description of why evaluation was inconclusive
Error returned when a feature flag cannot be evaluated locally.
This typically occurs when:
- Required person/group properties are missing
- A cohort referenced by the flag is not in the local cache
- A dependent flag is not available locally
- An unknown operator is encountered
InconclusiveMatchError::new
Create an inconclusive-match error with a human-readable message.
MultivariateFilter
Fields
variants: Vec<MultivariateVariant>- List of variants with their rollout percentages
Configuration for multivariate (A/B/n) feature flags.
MultivariateVariant
Fields
key: String- Unique key for this variant (e.g., "control", "test", "variant-a")rollout_percentage: f64- Percentage of users who should see this variant (0-100)
A single variant in a multivariate feature flag.
Property
Fields
key: String- The property key to match (e.g., "email", "country"). For a flag dependency (type = "flag"), the key of the referenced flag.value: serde_json::Value- The value to compare against. The presence operators ("is_set"and"is_not_set") never read it, and the API may omit it for them; it then deserializes as JSON null.operator: String- Comparison operator. Supported property operators include"exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex","gt","gte","lt","lte","is_set","is_not_set","is_date_before","is_date_after", and the"semver_*"operators used by PostHog version targeting.property_type: Option<String>- Property type. UseSome("cohort")for cohort membership checks andSome("flag")with the"flag_evaluates_to"operator for flag dependency checks.
A property filter used in feature flag targeting.
Supports various operators for matching user properties against expected values.
UnresolvedFlagReason
Variants
ExperienceContinuity- The flag has experience continuity enabled, which local evaluation never resolves.UnsupportedDefinition- The definition uses something the local evaluator does not support, such as a static cohort, an unknown operator or filter type, a malformed value, or a dependency with no loaded definition.UnresolvedDependency- A flag the definition depends on was unresolved.MissingContext- The call did not pass a property, group property or device ID the flag needs, or a group key its holdout needs, or passed it in a form the evaluator cannot use.
Why local evaluation left a flag without a value.
Reported by
FeatureFlagEvaluations::unresolved_flags.
UnresolvedFlagReason::as_str
The reason's wire name, such as "unsupported_definition".
Cohort
Fields
properties: serde_json::Value- The raw cohort property group exactly as returned by the API, e.g.{"type": "AND", "values": [{"key": "email", "value": "...", ...}]}.valuesentries may be leaf property filters or nested property groups.
A cohort definition for local evaluation.
Cohorts are groups of users defined by property filters, used for targeting feature flags to specific user segments.
The /flags/definitions/?send_cohorts endpoint maps each cohort ID
straight to its property group, {"type": "AND"|"OR", "values": [...]},
with no wrapping id/name fields — so this type is transparent over the
raw property group and the owning ID is the map key in
LocalEvaluationResponse::cohorts.
The backend dependency loader can serialize cohort references that form a cycle across map entries. Serde preserves those references as-is; cohort evaluation must track active IDs before following them recursively to avoid a stack overflow.
FlagCache
Thread-safe cache for feature flag definitions.
Stores feature flags, group type mappings, and cohort definitions that have been fetched from the PostHog API. The cache is shared between the poller (which updates it) and the evaluator (which reads from it).
FlagCache::new
Create an empty shared flag cache.
FlagCache::update
Replace cached flags, group type mappings, and cohorts from a local evaluation API response.
FlagCache::minimal_flag_called_events
Whether the most recent definitions poll enabled minimal
$feature_flag_called events. false until definitions load, so a
missing signal always yields full events.
FlagCache::get_flag
Return a cached feature flag by key.
LocalEvaluator also uses parts of the definition that are not
on FeatureFlag: early-access enrollment, experience continuity,
device ID bucketing and the experiment holdout.
FlagCache::get_all_flags
Return all cached feature flag definitions.
FlagCache::get_cohort
Return a cached cohort by ID.
FlagCache::get_all_cohorts
Return all cached cohorts, keyed by cohort ID.
FlagCache::get_cohort_definitions
Get all cohorts as CohortDefinitions for evaluation context
FlagCache::get_flags_map
Get all flags as a HashMap for evaluation context
FlagCache::get_group_type_mapping
Get the group type mapping (group type index → group type name).
FlagCache::clear
Remove all cached flags, group type mappings, and cohorts.
LocalEvaluationConfig
Fields
secret_key: String- Secret key for authentication.project_api_key: String- Project API key to identify which project's flags to fetchapi_host: String- PostHog API host URL (for example,https://us.i.posthog.com). Usehttps://eu.i.posthog.comfor EU-hosted projects.poll_interval: std::time::Duration- How often to poll for updated flag definitionsrequest_timeout: std::time::Duration- Timeout for API requests
Configuration for local flag evaluation.
Specifies the credentials and settings needed to fetch feature flag definitions from the PostHog API for local evaluation.
LocalEvaluationResponse
Fields
flags: Vec<feature_flags::FeatureFlag>- List of feature flag definitionsgroup_type_mapping: std::collections::HashMap<String, String>- Mapping from group type keys to their display namescohorts: std::collections::HashMap<String, Cohort>- Cohort definitions for evaluating cohort membershipminimal_flag_called_events: bool- Server-controlled gate: whentrue,$feature_flag_calledevents for non-experiment flags evaluated from these definitions are minimized to a strict property allowlist. Absent fails safe tofalse(full event).property_matching_version: i64- Property equality semantics for this snapshot. Exactly2selects explicit matching; absent metadata and other versions use legacy matching.
Response from the PostHog local evaluation API.
Contains feature flag definitions, group type mappings, and cohort definitions that can be cached locally for flag evaluation without server round-trips.
LocalEvaluationResponse::new
Create a local-evaluation response from feature flag definitions.
Group mappings, cohorts, and minimized flag-called events default to empty or disabled and can be assigned through their public fields.
AsyncFlagPoller
Asynchronous poller for feature flag definitions.
Runs a tokio task that periodically fetches flag definitions from the
PostHog API and updates the shared cache. Use this for async applications.
For blocking/sync applications, use FlagPoller instead.
AsyncFlagPoller::new
Create an asynchronous flag definition poller.
If the HTTP client cannot be built, logs a warning and leaves polling
disabled. Self::load_flags then returns Error::Connection.
Parameters
config: Credentials, host, polling interval, and request timeout.cache: Shared cache updated by the poller.
AsyncFlagPoller::start
Start the polling task.
Performs an initial async load, then refreshes definitions in the
background until AsyncFlagPoller::stop is called or the poller is
dropped.
AsyncFlagPoller::load_flags
Load flags asynchronously and update the cache once.
Errors
Returns Error::Connection for request failures or non-success HTTP
statuses, and Error::Serialization when the response cannot be
parsed.
AsyncFlagPoller::stop
AsyncFlagPoller::is_running
Check if the poller currently has a running background task.
PostHogReqwestClient
An opt-in application HTTP client that sends analytics context to exact allowed hosts.
This client disables automatic redirects and returns redirect responses to the caller. Reqwest otherwise forwards custom headers across redirects, which can expose analytics IDs. Configure a separate client for requests that need automatic redirects.
The supplied builder retains its other settings. Do not set PostHog tracing headers as client default headers: those defaults belong to the application and can apply to any host. This client does not change the SDK's event ingestion transport.
PostHogReqwestClient::new
Builds a dedicated client with automatic redirects disabled.
Hosts are trimmed and compared without case sensitivity. Each entry must be a hostname without a scheme, port, path, or wildcard. An empty list disables header injection.
PostHogReqwestClient::client
Use this client to build requests, then pass them to Self::execute.
Calling reqwest's send or execute directly does not inject context.
PostHogReqwestClient::execute
Sends a request with the context active when this future is first polled.
Build the request with Self::client to retain its client configuration.
On allowed hosts, current values replace stale tracing headers. Missing values and
values that cannot form valid HTTP headers are omitted. Other hosts are unchanged.
Spawned tasks can use an explicit RequestContext::scope to carry context.





