AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured approach to implementing distributed tracing with PostHog. By leveraging the OpenTelemetry standard, it enables developers to track requests across services, databases, and background jobs. The process covers detection of the existing stack, configuration of OTLP exporters, and strategic placement of spans to identify performance bottlenecks and cross-service failures without requiring a proprietary PostHog SDK.
What it does
- Analyzes existing codebase to detect language, framework, and current tracing setup.
- Configures OpenTelemetry SDKs and OTLP HTTP exporters to send trace data to PostHog.
- Implements auto-instrumentation for common frameworks and libraries.
- Guides the manual addition of spans for background jobs and complex internal logic.
- Links trace spans to specific users and sessions for enhanced observability.
- Ensures proper flushing of trace data in serverless and short-lived environments.
When to use it
- After implementing new features or reviewing pull requests to ensure proper observability.
- When you need to diagnose latency issues or request flow problems across distributed services.
- When tasked with adding tracing or spans to an existing application.
- When migrating or pointing existing OpenTelemetry tracing configurations to PostHog.
Advantages
- Uses industry-standard OpenTelemetry, avoiding vendor lock-in.
- Provides deep visibility into request latency and service-to-service communication.
- Supports a wide range of languages including Node.js, Python, Go, Java, .NET, PHP, and Ruby.
- Enables correlation between backend traces and frontend user sessions.
- Minimal impact on existing architecture through non-intrusive instrumentation.
Usage examples
- “Add PostHog distributed tracing to my Python FastAPI application.”
- The agent will analyze your project, install the necessary OpenTelemetry distro, configure the OTLP exporter to point to PostHog, and provide instructions for starting the app with the instrumentation wrapper.
- “My Next.js app is slow. How can I see where the time is going?”
- The agent will guide you through setting up OpenTelemetry in your Next.js project, specifically using the instrumentation.ts file to capture request entry points and outbound calls.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/posthog/instrument-tracing/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip instrument-tracing.zip -d .agents/skills
Documentation by PostHog
Add PostHog distributed tracing
Use this skill to add PostHog distributed tracing for new or changed code. Use it after implementing features or reviewing PRs to ensure request entry points, outbound calls, and background jobs produce spans, when the user asks to add tracing or spans, or to point existing OpenTelemetry tracing at PostHog. Supports any platform or language.
Supported platforms: Node.js, Next.js, Python (including Django, FastAPI, and Flask), Go, Java, .NET, PHP, Ruby, and any language via OpenTelemetry (OTLP).
PostHog tracing uses the standard OpenTelemetry SDK and an OTLP HTTP trace exporter. It does not need a PostHog SDK.
Instructions
Follow these steps IN ORDER:
STEP 1: Analyze the codebase and detect the platform.
Detect the language, framework, and existing tracing setup.
Look for dependency files and project files (package.json, requirements.txt, pyproject.toml, go.mod, pom.xml, build.gradle, *.csproj, Gemfile, composer.json, etc.).
Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb, poetry.lock, uv.lock, go.sum, Gemfile.lock, composer.lock, etc.) to determine the package manager.
Look for existing tracing: an OpenTelemetry tracer provider, an
instrumentation.tsfile, anopentelemetry-instrumentlaunch command, an OpenTelemetry Collector config, a Java agent flag, or another vendor's tracing agent.Check whether a PostHog SDK (posthog-js, posthog-node, posthog-python) is already installed. You need this only for STEP 6.
STEP 2: Choose the capture path.
If the codebase already exports OpenTelemetry traces, point the existing OTLP trace exporter (or Collector) at PostHog. Reuse the existing tracer provider. If it exports to another tracing backend, ask the user before you add PostHog as a second destination.
Otherwise, add the OpenTelemetry SDK with an OTLP HTTP trace exporter and auto-instrumentation. Auto-instrumentation creates spans for HTTP servers, frameworks, and database drivers without code changes.
Read the platform reference that matches the detected stack now. Use its "With OpenTelemetry" section. If no reference matches, use the general installation reference.
STEP 3: Install dependencies. (Skip if the codebase already exports OpenTelemetry traces.)
Install the OpenTelemetry SDK, the OTLP HTTP/protobuf trace exporter, and the auto-instrumentation for the detected stack:
Node.js and Next.js: the packages from the platform reference, plus
@opentelemetry/auto-instrumentations-node.Python:
opentelemetry-distroandopentelemetry-exporter-otlp-proto-http, then runopentelemetry-bootstrap -a install. It installs the instrumentation packages for the libraries the app already uses. Do not installopentelemetry-instrumentation-all.Go: the packages from the platform reference, plus the contrib instrumentation for each library, such as
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.Java: the zero-code
opentelemetry-javaagent.jar. It needs no dependency changes..NET:
OpenTelemetry,OpenTelemetry.Exporter.OpenTelemetryProtocol, andOpenTelemetry.Extensions.Hosting, plusOpenTelemetry.Instrumentation.AspNetCoreandOpenTelemetry.Instrumentation.Http.PHP: the packages from the platform reference. For auto-instrumentation, the
opentelemetryPHP extension (from PECL) and theopen-telemetry/opentelemetry-auto-*package for the framework, such asopen-telemetry/opentelemetry-auto-slim.Ruby:
opentelemetry-sdk,opentelemetry-exporter-otlp, andopentelemetry-instrumentation-all, enabled withc.use_all.
Do not manually edit dependency files — use the package manager's install command.
STEP 4: Configure the OTLP trace exporter.
Send spans over OTLP HTTP/protobuf to
/i/v1/traceson the PostHog host, with the project token in anAuthorization: Bearerheader. Do not use/i/v0/ai/otel. That endpoint accepts only LLM spans.With environment variables, set the full path in
OTEL_EXPORTER_OTLP_TRACES_ENDPOINTand the header inOTEL_EXPORTER_OTLP_TRACES_HEADERS(Authorization=Bearer <token>). Do not set the baseOTEL_EXPORTER_OTLP_ENDPOINTfor PostHog. It appends its own/v1/tracespath.Set
OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobufwhere the SDK or agent defaults to gRPC. This applies to the Java agent, .NET, and Python withopentelemetry-distro.Python with
opentelemetry-distro: start the app withopentelemetry-instrument(for example,opentelemetry-instrument python app.py). It builds the tracer provider from the environment variables, so do not also build a provider in code. The distro also turns on OTLP metric and log export. SetOTEL_METRICS_EXPORTER=noneandOTEL_LOGS_EXPORTER=noneunless the app already sends those signals somewhere.Set a service name (
service.name, orOTEL_SERVICE_NAME) so spans are easy to find in the Tracing UI.Start the provider before the application loads its frameworks, so auto-instrumentation can patch them. In Next.js, register the provider in
instrumentation.tsbehind theNEXT_RUNTIME === 'nodejs'check.Follow the platform-specific reference for the exact configuration.
You must read a file immediately before attempting to write it.
STEP 5: Add spans where they belong.
Auto-instrumentation covers request entry points and most outbound calls. Add manual spans with the OpenTelemetry tracer API only where it has no coverage: background job handlers, queue consumers, and slow internal steps the user cares about.
Use low-cardinality span names like
GET /users/:id, notGET /users/123. Put variable values in attributes.Pass the W3C
traceparentheader on calls between services, so spans from each service join one trace.Do not alter the fundamental architecture of existing files. Make additions minimal and targeted.
STEP 6: Link spans to people and sessions. (Optional.)
A span joins a person and a Session Replay recording through the
posthogDistinctIdandsessionIdspan attributes.If the app uses posthog-js, enable
tracing_headersfor your API hosts. The browser then sendsX-POSTHOG-DISTINCT-IDandX-POSTHOG-SESSION-IDheaders on each request.With OpenTelemetry only, copy these values onto spans yourself. In the request handler or a middleware, read the two headers and set them as the
posthogDistinctIdandsessionIdattributes on the active request span. Skip a header that is missing or empty.If the app already uses the PostHog SDK, it can add these attributes for you. Do not install the PostHog SDK only for this step.
Python: add
PostHogContextSpanProcessorfromposthog.integrations.otelto the tracer provider. It copies the distinct ID and session ID from the active PostHog context onto each new span. Django's contexts middleware reads the headers and sets that context.Node.js and Python: spans created with the PostHog SDK span API (
posthog.withSpan,posthog.start_span) inside a PostHog request context get these attributes automatically. This needsposthog-node5.52.0 or later, orposthog7.58.0 or later, with thetracesoption set. These spans go through the PostHog SDK, not the OpenTelemetry provider. Use this only for apps that do not run OpenTelemetry.
STEP 7: Set up environment variables.
Check if the project already has PostHog environment variables configured (e.g. in
.env,.env.local, or framework-specific env files). If valid values already exist, skip this step.If the PostHog project token is missing, use the PostHog MCP server's
projects-gettool to retrieve the project'sapi_token. If multiple projects are returned, ask the user which project to use. If the MCP server is not connected or not authenticated, ask the user for their PostHog project token instead.Use the project token (it starts with
phc_). Do not use a personal API key (it starts withphx_).For the PostHog host URL: check the
projects-getMCP response for aregionfield —USmaps tohttps://us.i.posthog.com,EUmaps tohttps://eu.i.posthog.com. If the region is not available from the MCP response or from existing project configuration, ask the user: "Are you on PostHog US Cloud or EU Cloud?" Do not assume US Cloud.For the OTLP traces endpoint, use
https://us.i.posthog.com/i/v1/traces(US) orhttps://eu.i.posthog.com/i/v1/traces(EU), matching the region determined above, with the project token as anAuthorization: Bearerheader.Write these values to the appropriate env file using the framework's naming convention.
Reference these environment variables in code instead of hardcoding them.
STEP 8: Flush spans in short-lived processes.
The batch processor exports spans on an interval. A script, cron job, or serverless function can stop before the batch is sent.
On Vercel and other serverless platforms, call the provider's
forceFlush()before the function returns. In Next.js 15.1 and later, call it insideafter()fromnext/server.On AWS Lambda, call
forceFlush()at the end of each invocation. Do not callshutdown()there, because the runtime reuses the container. Callshutdown()only when the process exits.
STEP 9: Verify spans arrive.
Run the application and trigger the instrumented code.
Open Tracing in the PostHog sidebar and filter by the service name. Spans should appear within a minute of sending.
If no spans appear, check the endpoint path, the
Bearertoken, the exporter protocol, and the flush step.
Reference files
references/nodejs.md- Node.js tracing installationreferences/nextjs.md- Next.js tracing installationreferences/python.md- Python tracing installationreferences/go.md- Go tracing installationreferences/java.md- Java tracing installationreferences/dotnet.md- .net tracing installationreferences/php.md- Php tracing installationreferences/ruby.md- Ruby tracing installationreferences/installation.md- Install tracingreferences/start-here.md- Getting started with distributed tracingreferences/basics.md- Why you need distributed tracingreferences/COMMANDMENTS.md- Framework-specific rules the integration must follow
Each platform reference contains specific OpenTelemetry setup, OTLP configuration, and integration patterns. Find the one matching the user's stack.
Key principles
OpenTelemetry first: PostHog traces use the OpenTelemetry protocol. Use the OpenTelemetry SDK with auto-instrumentation, and reuse an existing tracer provider when there is one. The PostHog SDK is optional.
Environment variables: Always use environment variables for PostHog keys and OpenTelemetry endpoints. Never hardcode them.
Minimal changes: Add PostHog trace export alongside existing code. Don't replace or restructure existing tracing.
Boundaries, not every function: A few spans at request entry, outbound calls, and background jobs are better than a span around every function.
No secrets in attributes: Never put tokens, passwords, or other secrets in span names or attributes.
Files
- ATTRIBUTION.mdAdded by AutoGineer940 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md11.4 KiB
- references/COMMANDMENTS.md1.5 KiB
- references/basics.md6.8 KiB
- references/dotnet.md6.1 KiB
- references/go.md6.9 KiB
- references/installation.md2.5 KiB
- references/java.md5.5 KiB
- references/nextjs.md7.8 KiB
- references/nodejs.md12.1 KiB
- references/php.md6.7 KiB
- references/python.md11.3 KiB
- references/ruby.md3.9 KiB
- references/start-here.md3.9 KiB
references/basics.md
AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
Why you need distributed tracing
Canonical URL: https://posthog.com/docs/distributed-tracing/basics
On this page
What is a trace?
What tracing shows you that nothing else does
When tracing saves you
What good tracing looks like
How PostHog makes tracing useful
Next steps
Tracing follows a single request as it travels through your application – across the functions, services, databases, and APIs it touches along the way. Where Logs record what happened at each point, a trace shows you the whole path: what called what, in what order, and how long each step took.
This page covers what a trace is, what it shows you that nothing else does, and when it saves you hours of debugging.
What is a trace?
A trace is the complete journey of one request through your system. It's made up of spans – each span is a single unit of work, like an incoming HTTP request, a database query, or a call to a third-party API.
Spans nest into a tree. The incoming request is the root span, and everything it triggers becomes a child span underneath it. Each span records:
A name and service - what ran, and where
A start time and duration - when it happened, and how long it took
A status - whether it succeeded or failed
Attributes - any context you attach, like a user ID or a query parameter
Because every span in a request shares the same trace_id, you can reconstruct the request as a waterfall and see exactly where the time went and where things broke.
What tracing shows you that nothing else does
Each PostHog product answers a different question about your application:
| Product | What it tells you | Example |
|---|---|---|
| Product Analytics | What users did | "User clicked checkout" |
| Logs | What happened at each point | "Inventory service returned 200 with 0 items" |
| Error Tracking | What broke | "TypeError: cannot read property 'price' of undefined" |
| Distributed tracing | How the request flowed and where time went | "Checkout took 3.2s, and 2.8s of it was spent waiting on the inventory service" |
Errors tell you something broke. Logs tell you what happened at one point. Tracing tells you how the pieces connected, and where the time and failures actually came from – across every service a request touched.
In a single process, you can often guess. Once a request fans out across services, queues, and third-party APIs, guessing stops working. Tracing replaces the guesswork with a map.
When tracing saves you
A request is slow, but you don't know which part
Without tracing, "the checkout endpoint is slow" sends you back to the code to add timers by hand.
With tracing, you open the trace and read the waterfall top to bottom. The handler is fast and the payment call is fast, but one span sits at 2.8 seconds because the inventory service runs a separate database query for every item in the cart instead of one query for the whole cart. You found the N+1 in seconds.
A failure crosses service boundaries
A user hits an error on the frontend, but the root cause is three services deep. The error surfaces in one place and originates somewhere else entirely.
With tracing, you follow the trace_id from the failed request down through each service it called, and land on the span that actually failed: a downstream auth service returning 401 because a token expired mid-request.
Latency only happens sometimes
The endpoint is usually fast, but your p99 is terrible and you can't reproduce it. Averages hide the problem.
With tracing, you filter to the slow traces and compare them against the fast ones. The slow traces all share one span: a cache miss that falls through to a cold database query. Now you know what to fix.
Async and background work disappears
A request kicks off a queue job that runs later. There's no single stack trace that spans the gap between them.
With tracing, context propagates across the boundary, so the job's spans attach to the trace that started them. You see the whole flow, even when it crosses processes and time.
What good tracing looks like
Useful tracing is about instrumenting the right boundaries, not every line of code.
Trace the boundaries – Wrap incoming requests, outgoing calls, and database queries. These are where time is spent and where things fail.
Give spans descriptive names –
GET /api/checkoutanddb.query load_carttell you what ran at a glance.handlerandquerydon't.Add business context as attributes – Attach the user ID, the plan, and the Feature Flag variant. When a trace is slow, you want to know who it was slow for.
Propagate context across services – Pass trace context with every outgoing call so spans from different services join the same trace. This is what makes tracing distributed.
How PostHog makes tracing useful
No vendor lock-in - PostHog ingests traces over OpenTelemetry (OTLP). Use standard OTel libraries in any language, with no proprietary SDK. If you already export traces, point them at PostHog and you're done.
Built on the same pipeline as Logs - Tracing uses the same OpenTelemetry-based ingestion as Logs, so a single OTel setup covers both. When inspecting a span, the Logs tab shows correlated logs scoped to that span or the whole trace, and you can deep-link into the full Logs product with filters pre-applied.
One platform, not another vendor - Your traces live in the same PostHog project as Session Replay, Error Tracking, and Product Analytics, so you have one less observability tool to run and pay for.
One meter with Logs - Tracing and Logs bill together on a single ingestion meter with a monthly free tier. See Tracing pricing.
Next steps
Get started - Install an OpenTelemetry exporter and send your first spans
Logs - Capture what happened at each point, using the same OpenTelemetry setup
Error Tracking - Turn failures into issues you can assign and resolve
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs an API key, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- PostHog
- Publisher
- PostHog (Official)
- Source
- PostHog/skills · skills/omnibus/instrument-tracing · commit a5d30e7
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by PostHog.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download instrument-tracing.zip