Generated banner for Instrument Metrics
Generated logo for Instrument Metrics

Instrument Metrics

PostHogOfficialCreated by PostHog

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • Low risk

From the author

Add PostHog metric capture to track counters, gauges, and histograms. Use after implementing features or reviewing PRs to ensure key operations are measured, or when asked to add metrics, counters, or track a value over time. Also handles mirroring existing Prometheus/StatsD/OpenTelemetry metrics into PostHog and initial OTLP exporter setup.
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to instrumenting applications with PostHog metrics. It supports various platforms including Web, Node.js, Python, and Kubernetes, and offers a path for integrating existing OpenTelemetry setups. The skill emphasizes non-intrusive instrumentation, advising developers to add PostHog calls alongside existing metrics rather than replacing them. It includes guidance on selecting appropriate metric types, maintaining low cardinality for performance, and configuring environment variables securely.

What it does

  • Detects existing metrics instrumentation and platform-specific requirements.
  • Implements PostHog metric capture for counters, gauges, and histograms.
  • Mirrors existing Prometheus, StatsD, or OpenTelemetry metrics into PostHog.
  • Configures OTLP exporters for applications already using OpenTelemetry.
  • Provides guidance on setting up necessary environment variables for authentication.
  • Ensures metrics are correctly flushed in short-lived processes.

When to use it

  • After implementing new features that require performance or usage tracking.
  • When asked to add specific counters or gauges to an existing codebase.
  • When you need to track values over time, such as queue depths or API durations.
  • When migrating or mirroring existing metrics from other providers into PostHog.
  • When you need to set up initial OTLP exporter configurations.

Advantages

  • Non-destructive: adds metrics alongside existing instrumentation without restructuring code.
  • Flexible: supports native SDKs and standard OpenTelemetry protocols.
  • Performance-conscious: provides clear rules on maintaining low cardinality to prevent series explosion.
  • Secure: mandates the use of environment variables for sensitive configuration keys.
  • Robust: includes error handling guidelines to ensure metrics collection does not break application boot.

Usage examples

“Add a counter to track the number of successful user signups in my Python application.”
The agent will analyze the Python environment, identify the appropriate PostHog SDK or OTLP setup, and insert a counter increment call at the successful signup logic point.
“Mirror my existing Prometheus metrics into PostHog.”
The agent will identify the existing OTLP exporter or Prometheus client, configure the endpoint to point to PostHog, and ensure the project token is correctly set via environment variables.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/posthog/instrument-metrics/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip instrument-metrics.zip -d .agents/skills

Documentation by PostHog

Add PostHog metric capture

Use this skill to add PostHog metric capture (counters, gauges, and histograms) for new or changed code. Use it after implementing features or reviewing PRs to ensure key operations are measured, when the user asks to add metrics or counters, or to mirror existing metrics instrumentation into PostHog. Supports any platform or language.

Supported platforms: Web (JavaScript), Node.js, Python via the posthog.metrics SDK API, Kubernetes via the metrics agent, and any language via OpenTelemetry (OTLP).

Instructions

Follow these steps IN ORDER:

STEP 1: Analyze the codebase and detect the platform.

  • Detect the language, framework, and existing metrics setup.

  • Look for dependency files and project files (package.json, requirements.txt, pyproject.toml, go.mod, pom.xml, etc.).

  • Look for existing metrics instrumentation: Prometheus clients (prom-client, prometheus_client), StatsD/Datadog clients, OpenTelemetry meters, or an OpenTelemetry Collector config.

  • Check whether a PostHog SDK (posthog-js, posthog-node, posthog-python) is already installed.

STEP 2: Choose the capture path.

  • If a PostHog SDK is installed (or the platform supports one), use the posthog.metrics API — no OpenTelemetry packages needed. Read the matching platform reference now.

  • If the codebase already exports OpenTelemetry metrics, point the existing OTLP metrics exporter (or Collector) at PostHog instead — read the "Other Languages" reference. No application code changes needed beyond exporter config.

  • If neither applies, use the "Other Languages" reference as a fallback — it covers the generic OpenTelemetry approach.

STEP 3: Instrument alongside existing metrics.

  • Where the codebase already records a metric (a Prometheus counter, a StatsD call, an OTel instrument), add the PostHog call next to the existing one, reusing the same metric name and attributes. Do NOT remove or restructure the existing instrumentation.

  • Do not alter the fundamental architecture of existing files. Make additions minimal and targeted.

  • You must read a file immediately before attempting to write it.

STEP 4: Add new metrics where they belong.

  • Where the user asked for new metrics, or key operations have no coverage, add PostHog metric calls at the sites they belong: count successes and failures of critical flows, time external calls and jobs with histograms, gauge queue depths and pool sizes.

  • Pick the right type: counters for things that only go up, gauges for values that go up and down, histograms for distributions like durations. Set an explicit unit on histograms (ms, bytes).

  • Use stable, descriptive, dot-separated names (jobs.processed, api.request.duration) and set a service name so systems stay easy to tell apart.

STEP 5: Keep cardinality low.

  • Attributes like route, status, plan, or queue are good; user IDs, session IDs, request IDs, and timestamps are not. Every unique attribute combination creates a new series.

  • If something needs per-user or per-request detail, that's a job for PostHog logs or traces, not metrics.

STEP 6: Set up environment variables. (Skip if the PostHog SDK is already configured — posthog.metrics reuses the SDK's existing project token.)

  • 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-get tool to retrieve the project's api_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.

  • For the PostHog host URL: check the projects-get MCP response for a region field — US maps to https://us.i.posthog.com, EU maps to https://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 metrics endpoint, use https://us.i.posthog.com/i/v1/metrics (US) or https://eu.i.posthog.com/i/v1/metrics (EU), matching the region determined above, with the project token as an Authorization: Bearer header.

  • 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 7: Verify metrics arrive.

  • For short-lived processes (scripts, cron jobs, serverless), flush before exit (posthog.metrics.flush(), or the OTel provider's forceFlush()/shutdown()).

  • Open Metrics in the PostHog sidebar and pick the metric from the name picker; data points should appear within a minute of sending.

Reference files

  • references/javascript.md - JavaScript (web) metrics installation

  • references/nodejs.md - Node.js metrics installation

  • references/python.md - Python metrics installation

  • references/kubernetes.md - Kubernetes metrics installation

  • references/other.md - Other languages metrics installation

  • references/start-here.md - Getting started with metrics

  • references/basics.md - Why you need metrics

  • references/architecture.md - How metrics works

  • references/COMMANDMENTS.md - Framework-specific rules the integration must follow

Each platform reference contains specific SDK setup, OTLP configuration, and integration patterns. Find the one matching the user's stack.

Key principles

  • Environment variables: Always use environment variables for PostHog keys and OpenTelemetry endpoints. Never hardcode them.

  • Minimal changes: Add PostHog metric capture alongside existing metrics. Don't replace or restructure existing instrumentation.

  • Prefer the SDK: When a PostHog SDK is present, posthog.metrics needs no new packages and no extra authentication. Reserve OTLP setup for codebases already invested in OpenTelemetry or languages without SDK support.

  • Low cardinality: Every unique attribute combination creates a new series. Attach bounded dimensions like route, status, or plan — never user IDs, session IDs, or request IDs.

Files

references/architecture.md

AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt

How metrics works

Canonical URL: https://posthog.com/docs/metrics/architecture

Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use https://eu.posthog.com instead of https://app.posthog.com (app host for links).

On this page

  • Ingestion

  • The series model

  • Metric types and temporality

  • Querying

  • Anomaly detection and samples

  • Storage and SQL access

  • What the alpha means here

  • Next steps

Note: Metrics is in open alpha. Any team can turn it on — open Metrics and select Enable metrics in the onboarding view. The details on this page describe current behavior and may change before general availability.

This page explains what happens to a metric between your application and a chart: how ingestion works, what a series is, how aggregations are computed, and where the data lives. You don't need any of this to use metrics, but it helps when you're deciding what to instrument or debugging why a chart looks the way it does.

Ingestion

Metrics arrive over the OpenTelemetry Protocol (OTLP) via HTTP at /i/v1/metrics, as JSON or protobuf, authenticated with your project token. PostHog accepts the standard OTLP metrics model, so anything that can export OTLP (an OpenTelemetry SDK, a Collector, or the posthog.metrics API in posthog-js, which speaks OTLP under the hood) can send metrics without PostHog specific packages.

Each incoming data point carries a metric name, a metric type, a value (or histogram buckets), a timestamp, resource attributes describing the sender (service name, host), and data point attributes describing the measurement (route, status). Ingestion validates the payload, applies your project's quota, and writes data points to a columnar time series store.

Not every metric arrives over OTLP. A log-based metric is generated at ingestion from your logs: log lines matching a rule are tallied as they arrive and emitted as a metric into the same store, so it shows up in the metrics viewer like any instrumented metric.

The series model

A series is one stream of values identified by the combination of:

  • the metric name

  • the metric type (gauge, sum, histogram, exponential_histogram, or summary)

  • the service name

  • the full set of attribute key/value pairs

Record http.requests.total with route=/api/checkout and status=200, then again with status=500, and you have two series. Group a chart by status and each series becomes its own line.

This is why attribute cardinality matters. Ten routes times five status codes is fifty series: cheap, useful, chartable. A user ID attribute with a million values is a million series: expensive, and no chart with a million lines answers a question. Keep attributes to dimensions with a bounded set of values, and reach for logs or traces when you need per user or per request detail.

Metric types and temporality

Counters are where most charting mistakes happen, so PostHog handles their sharp edges for you:

  • Cumulative counters (the OpenTelemetry default) report an ever growing total since process start. The absolute value is meaningless for charting; what matters is how much it grew in each time bucket. The rate and increase aggregations compute per series differences, so a counter reported by twenty processes is twenty series diffed independently and then summed.

  • Counter resets happen when a process restarts and its total drops back toward zero. rate and increase detect resets the same way Prometheus does, so a restart never shows up as a huge negative spike.

  • Delta counters report only what happened since the last export. PostHog reads the temporality that your SDK declares and sums deltas as they are, without differencing.

  • Histograms arrive as bucket counts with bucket boundaries. Percentile aggregations combine the buckets across the query window and interpolate the requested quantile, which is how p95 works without storing every raw observation.

  • Gauges are stored as reported and aggregate naturally with avg, sum, or percentiles.

If an aggregate overflows what a float can represent, the affected time bucket is returned as an explicit null gap rather than an infinity or a silently wrong number.

Querying

Queries resolve over a shared time grid. PostHog picks a bucket size automatically so a chart has roughly sixty points across the selected range, from one second buckets for short windows up to daily and weekly buckets for long ones, and you can pin the interval explicitly through the API. Every series in a response shares the same grid, which is what makes cross series math line up.

Filters match attribute values with equality, negation, or regular expressions, and can target resource attributes, data point attributes, or both. Group by splits the result into one series per attribute value, keeping the largest series when there are too many to chart.

Through the query API you can also combine multiple metrics with a formula, for example an error ratio computed as errors / requests, evaluated server side on the shared grid.

Anomaly detection and samples

Two more things sit between storage and the chart:

  • Anomaly detection. When you chart a metric, PostHog compares the most recent slice of the window against a baseline and, if they differ statistically, finds the onset and ranks which label values drove the move. That powers the anomaly badge and biggest-movers panel in the viewer.

  • Raw samples. Alongside the aggregated series, PostHog keeps the individual emissions. The Samples view in the viewer reads these to show the exact data points behind a chart, and to link each one to the trace it was recorded in when trace context is present.

Storage and SQL access

Metrics are stored in a columnar time series table and exposed to SQL as posthog.metrics, scoped to your project like every other PostHog table. The SQL tab in the metrics viewer is a full escape hatch: anything the chart controls can't express, you can write directly, and join against the rest of your PostHog data.

What the alpha means here

While metrics is in open alpha, ingestion details and limits may still change, and metrics data is kept for 30 days. The OTLP endpoint, the series model, and the aggregation semantics described above are the stable core the product is built on.

Next steps

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 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-metrics · 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-metrics.zip