Skip to content

feat(metrics): record requests and httpx durations as a histogram - #967

Closed
pauldambra wants to merge 1 commit into
mainfrom
posthog/network-metrics
Closed

pauldambra wants to merge 1 commit into
mainfrom
posthog/network-metrics

Conversation

@pauldambra

Copy link
Copy Markdown
Member

🤖 This description was written by an agent on Paul's behalf.

💡 Motivation and Context

posthog-js can now record a duration histogram for every fetch and XMLHttpRequest the page makes (metrics.network, PostHog/posthog-js#4918). Python services have no equivalent, so a Django app that wants timings for the HTTP calls it makes has to wrap each call by hand.

This adds the same option to the Python SDK:

posthog.setup(metrics={"network": True})
# or
Client("phc_...", metrics={"network": {"name": ..., "attributes": ...}})

When set, the SDK wraps requests.Session.send and, when httpx is installed, httpx.Client.send and httpx.AsyncClient.send. Every HTTP or HTTPS request is recorded as the http.client.request.duration histogram (unit ms) with method, host, templated path and status_class attributes. name accepts a string or a function of the request (return None to skip it). attributes accepts a function of the request and response whose result is merged over the defaults.

Design points, kept the same as posthog-js where they apply:

  • The wrappers only observe. They call the original with the same arguments, return its result or re-raise its error, and a failure inside recording is logged once and never reaches the caller.
  • The SDK marks its own requests sessions and its async httpx client, so PostHog's own uploads (including the metrics flush) are never recorded.
  • requests sends each redirect hop through Session.send again. A context variable folds those into the outer request, so a redirected call is recorded once with its final status.
  • The wrappers install when the client is built and are removed on shutdown(). If another wrapper was layered on top of ours and it cannot be spliced out, ours stays in place as a pass-through.
  • path replaces all-digit and uuid-like segments with :id. Ids with a prefix or suffix (order-123, 38217.pdf) are kept, so return your own path from attributes for those routes.

Nothing Django-specific is needed: the middleware already uses the global or configured client, so setting metrics={"network": True} on that client times every outbound call a view makes.

This is a public API addition (metrics["network"]). The shape copies the agreed posthog-js option rather than a new design, but per CONTRIBUTING it should still get a maintainer nod before merge.

💚 How did you test it?

  • New posthog/test/test_network_metrics.py (37 tests, parametrized where the cases are a table): default attributes, status classes, failures recorded as missing and re-raised, redirects recorded once, non-HTTP schemes skipped, the SDK's own sessions skipped, httpx sync and async, name and attributes config, invalid config warning and falling back to defaults, install on construction and removal on shutdown, layered wrapper pass-through, module-level posthog.setup().
  • uv run ruff format --check ., uv run ruff check ., mypy with the baseline filter, python -W error -c "import posthog", make public_api_check, and the full suite (2795 passed, 15 skipped).

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file (added .sampo/changesets/network-metrics.md by hand, minor)

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Written with PostHog Desktop (Claude Code). Paul asked for the Python SDK equivalent of the posthog-js network metrics wrapper. Decisions: patch Session.send rather than HTTPAdapter.send so plain requests.get() and non-https mounts are covered; mark the SDK's own sessions instead of matching PostHog hosts by URL, as posthog-js ended up doing; use a context variable rather than a depth counter so the redirect guard works for both threads and asyncio tasks; keep the new module's helpers private so the only new public surface is the network option and the default metric name.


Created with PostHog Desktop

Add the `network` option to the `metrics` client config. When set, the
SDK wraps `requests.Session.send` and, when httpx is installed,
`httpx.Client.send` and `httpx.AsyncClient.send`, and records
`http.client.request.duration` with `method`, `host`, templated `path`
and `status_class` attributes. `name` accepts a string or a function,
`attributes` accepts a function. The wrappers only observe: they call
the original with the same arguments, return its result or re-raise its
error, and never let a recording failure reach the caller. Each redirect
hop that `requests` sends is folded into the outer request. The SDK's
own sessions are marked so PostHog's uploads are not recorded, and the
wrappers are removed on `shutdown()`.

This mirrors `metrics.network` in posthog-js.

Generated-By: PostHog Desktop
Task-Id: 7cbd4d4f-b9f1-4246-ba2a-dbe574f78b08
@github-actions

github-actions Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-17 14:24:01 UTC
Duration: 256054ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 514ms
Endpoint And Method.Does Not Use Legacy Endpoints 509ms
Required Headers.Has Authorization Bearer Header 508ms
Required Headers.Has Content Type Json 508ms
Required Headers.Has Posthog Sdk Info Format 509ms
Required Headers.Has Posthog Attempt Header 508ms
Required Headers.Has Posthog Request Id 509ms
Required Headers.Has Posthog Request Timestamp 508ms
Required Headers.Has User Agent 508ms
Body Format.Body Has Created At And Batch 509ms
Body Format.No Api Key In Body 509ms
Body Format.No Sent At In Body 508ms
Event Format.Event Has Required Root Fields 509ms
Event Format.Event Uuid Is Valid 509ms
Event Format.Event Timestamp Is Rfc3339 508ms
Event Format.Distinct Id Is String 508ms
Event Format.Distinct Id At Root Not Properties 509ms
Event Format.Custom Properties Preserved 508ms
Event Format.Set Properties Preserved 508ms
Event Format.Set Once Properties Preserved 509ms
Event Format.Groups Properties Preserved 509ms
Event Format.Sdk Generates Uuid If Not Provided 508ms
Event Format.Event Has Required Root Fields Batch 511ms
Event Format.Event Uuid Is Valid Batch 511ms
Event Format.Event Timestamp Is Rfc3339 Batch 511ms
Event Format.Distinct Id Is String Batch 510ms
Event Format.Distinct Id At Root Not Properties Batch 511ms
Event Format.Custom Properties Preserved Batch 511ms
Event Format.Set Properties Preserved Batch 511ms
Event Format.Set Once Properties Preserved Batch 511ms
Event Format.Groups Properties Preserved Batch 511ms
Event Format.Sdk Generates Uuid If Not Provided Batch 511ms
Batch Behavior.Multiple Events In Single Batch 514ms
Batch Behavior.Batch Envelope Smoke 512ms
Batch Behavior.Flush With No Events Sends Nothing 505ms
Batch Behavior.Flush At Triggers Batch 1009ms
Batch Behavior.Created At Reflects Batch Creation Time 509ms
Deduplication.Generates Unique Uuids 514ms
Deduplication.Different Events Same Content Different Uuids 511ms
Deduplication.Preserves Uuid On Retry 6512ms
Deduplication.Preserves Timestamp On Retry 6513ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6520ms
Deduplication.No Duplicate Events In Batch 514ms
Header Behavior On Retry.Attempt Header Starts At One 508ms
Header Behavior On Retry.Attempt Header Increments On Retry 13525ms
Header Behavior On Retry.Request Id Preserved On Retry 6514ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3017ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6518ms
Response Format Validation.Success Response Has Uuid Keyed Results 508ms
Response Format Validation.Success Response Has Ok For Each Event 511ms
Response Format Validation.Success No Retry After When All Ok 510ms
Response Format Validation.Success Retry After Present When Retry Events 1513ms
Response Format Validation.Success No Retry After When Drop Only 511ms
Response Format Validation.Response Echoes Request Id 508ms
Retry Behavior.Retries On 408 6516ms
Retry Behavior.Retries On 500 6518ms
Retry Behavior.Retries On 503 8520ms
Retry Behavior.Retries On 504 6517ms
Retry Behavior.Retryable Errors Have Retry After 3514ms
Retry Behavior.Respects Retry After On Retryable Error 11521ms
Retry Behavior.Does Not Retry On 400 2510ms
Retry Behavior.Does Not Retry On 401 2512ms
Retry Behavior.Does Not Retry On 402 2512ms
Retry Behavior.Does Not Retry On 413 2511ms
Retry Behavior.Does Not Retry On 415 2510ms
Retry Behavior.Non Retryable Errors Have No Retry After 2511ms
Retry Behavior.Implements Backoff 22532ms
Retry Behavior.Max Retries Respected 22523ms
Partial Batch Handling.Handles 200 Full Success 2511ms
Partial Batch Handling.Handles 200 With All Ok 3515ms
Partial Batch Handling.Does Not Retry Dropped Events 3511ms
Partial Batch Handling.Does Not Retry Limited Events 3513ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6519ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6518ms
Partial Batch Handling.Retries Only Retry Events From Partial 6517ms
Partial Batch Handling.Partial Retry Preserves Uuids 6518ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6518ms
Partial Batch Handling.Partial Retry Request Id Preserved 6515ms
Partial Batch Handling.Respects Retry After On Partial 8517ms
Partial Batch Handling.Unknown Result Treated As Terminal 3512ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3514ms
Compression.Sends Gzip Content Encoding 509ms
Compression.No Content Encoding When Disabled 508ms
Compression.Compressed Body Is Decompressible 508ms
Error Handling.Does Not Retry On Unknown 4Xx 2511ms
Event Options.Cookieless Mode Override 509ms
Event Options.Disable Skew Correction Override 508ms
Event Options.Process Person Profile Override 508ms
Event Options.Product Tour Id Override 509ms
Event Options.Unset Options Omitted 508ms
Event Options.Options Override In Batch 510ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 509ms
Geoip And Historical Migration.Historical Migration Set In Body 508ms
Geoip And Historical Migration.Historical Migration Absent By Default 508ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 9ms
Request Payload.Flags Request Uses V2 Query Param 8ms
Request Payload.Flags Request Hits Flags Path Not Decide 7ms
Request Payload.Flags Request Omits Authorization Header 7ms
Request Payload.Token In Flags Body Matches Init 7ms
Request Payload.Groups Round Trip 7ms
Request Payload.Groups Default To Empty Object 7ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 7ms
Request Payload.Disable Geoip Omitted Defaults To False 8ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 7ms
Request Lifecycle.No Flags Request On Init Alone 2ms
Request Lifecycle.No Flags Request On Normal Capture 508ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 11ms
Request Lifecycle.Mock Response Value Is Returned To Caller 7ms
Retry Behavior.Retries Flags On 502 311ms
Retry Behavior.Retries Flags On 504 311ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 509ms

@pauldambra pauldambra added reviewhog stamphog Request stamphog review labels Sep 17, 2026
@pauldambra

Copy link
Copy Markdown
Member Author

🤖 Closed by an agent on Paul's behalf. We decided this duplicates what OpenTelemetry instrumentation already provides for server-side HTTP clients, and PostHog accepts OTLP metrics directly. Closing rather than merging.

@pauldambra pauldambra closed this Sep 17, 2026
@pauldambra
pauldambra deleted the posthog/network-metrics branch September 17, 2026 15:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

reviewhog stamphog Request stamphog review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant