Skip to content
Shortcut: /, ⌘K or Ctrl+K

Connect an analytics collector

Read number engagement, connection and call metrics with Prometheus or OpenTelemetry.

View as Markdown

Send engagement, connection, response and call measurements to your telemetry backend. A collector pulls the metrics from Polymorfa once a minute, then exports them through OTLP over HTTP.

Before you start#

  • Enable Analytics for your team.
  • Create a project token with sessions:read, or a team key with the same scope for all projects. Client tokens cannot read analytics metrics.
  • Install an OpenTelemetry Collector distribution that includes the Prometheus receiver and OTLP HTTP exporter. The Contrib distribution includes both. Check its available components with otelcol-contrib components.
  • Obtain your telemetry backend's OTLP HTTP base URL and authorization header. This credential is separate from your Polymorfa API key.

Connect OpenTelemetry#

  1. Copy the configuration for your scope

    In Analytics, choose a project in the Console header, then use All Numbers to select one number or keep the combined view. Open … → Connect a collector.

    Choose a Rolling window of 1, 24 or 168 hours. Turn on Include message and audience breakdowns if you need those dimensions. Select Copy configuration and save the YAML as collector.yaml. It contains your selected scope and the API address for your Console environment. The collector window is independent of the page's calendar dates.

  2. Provide the credentials and destination

    Mount a file containing only your Polymorfa API key at /run/secrets/polymorfa_key. The user running the collector needs read access to that file. Keep the key out of collector.yaml.

    Set these environment variables in the collector's service or container:

    VariableValue
    OTLP_ENDPOINTYour backend's OTLP HTTP base URL, such as https://telemetry.example.com:4318
    OTLP_AUTHORIZATIONThe complete header value your backend requires, such as Bearer YOUR_BACKEND_TOKEN

    The exporter appends /v1/metrics to OTLP_ENDPOINT. If your provider gives you a complete metrics URL, replace endpoint with metrics_endpoint in the YAML instead. For a backend without authentication, remove the headers block and omit OTLP_AUTHORIZATION.

  3. Validate and start the collector

    Run these commands with the same environment and file mounts as the collector service:

    Shell
    otelcol-contrib validate --config=collector.yaml
    otelcol-contrib --config=collector.yaml

    The generated configuration names the HTTP exporter otlphttp. If your distribution lists otlp_http instead, use that name in both exporters and service.pipelines.metrics.exporters. An unknown-component error means the distribution lacks a required component or uses a different component name.

    Configure one collector instance per scrape job. Multiple instances pulling the same scope send duplicate observations to your backend.

  4. Check the first measurements

    After the first minute, look for polymorfa_analytics_enabled in your backend. A value of 1 confirms the export read enabled Analytics. Check polymorfa_analytics_window_end_timestamp_seconds for the measurement boundary and polymorfa_analytics_generated_timestamp_seconds for the scrape time.

    The receiver also reports Prometheus scrape health through up for the polymorfa_analytics job. A value of 0 indicates a failed scrape; check the collector's logs. Export errors after a successful scrape point to your backend URL, authorization or connectivity. Missing business metrics after a successful scrape mean their measurements are absent, not zero.

Example configuration#

This example reads every number in one project. Replace PROJECT_ID, provide the key file and environment variables above, then validate it with your collector. Use the Console-generated configuration to include a number filter or team scope.

collector.yaml
receivers:
  prometheus:
    config:
      scrape_configs:
        - job_name: polymorfa_analytics
          scrape_interval: 60s
          scrape_timeout: 20s
          scheme: https
          metrics_path: /platform/projects/PROJECT_ID/analytics/metrics
          authorization:
            type: Bearer
            credentials_file: /run/secrets/polymorfa_key
          params:
            windowHours: ["24"]
            format: [prometheus]
            segments: ["false"]
          static_configs:
            - targets: ["api.polymorfa.com"]
exporters:
  otlphttp:
    endpoint: ${env:OTLP_ENDPOINT}
    headers:
      Authorization: ${env:OTLP_AUTHORIZATION}
service:
  pipelines:
    metrics:
      receivers: [prometheus]
      exporters: [otlphttp]

Use Prometheus directly#

Copy the job under receivers.prometheus.config.scrape_configs into the scrape_configs list in your Prometheus configuration. Mount the same key file. The exporters and service sections belong to OpenTelemetry and are omitted from the Prometheus configuration.

Use format: [openmetrics] to request OpenMetrics text 1.0 instead of Prometheus text 0.0.4. The response includes its Content-Type and required ending marker. format selects the representation.

Choose your scope and window#

ParameterMeaning
projectIdSelect one project on API Export team analytics metrics. A project token always reads its own project.
sessionIdSelect a number by its record UUID, within your authorized project or team.
windowHours1–168 completed UTC hours; default 24. The window ends at the most recent hour boundary.
segmentstrue adds metadata breakdowns; default false.
formatprometheus for text 0.0.4 or openmetrics for text 1.0.

To read the metrics text from your own code:

API

cURL
curl --get "$POLYMORFA_API_URL/platform/analytics/metrics" \
  --header "Authorization: Bearer $POLYMORFA_API_KEY" \
  --data-urlencode "projectId=$PROJECT_ID" \
  --data-urlencode "windowHours=24" \
  --data-urlencode "format=openmetrics"
TypeScript
const metrics = await platform.analytics.metrics({
  projectId: "22222222-2222-4222-8222-222222222222",
  windowHours: 24,
  segments: true,
  format: "openmetrics",
});

console.log(metrics.data, metrics.metadata.status);

TypeScript:

data holds the metrics text and metadata the HTTP details. Team and project clients both support it, with the same number filter.

Use a separate scrape job name for each scope/window you collect. All number samples carry project_id and number_id. Scope-wide samples carry scope and project_id; API request counts remain team/project-wide when selecting a number. Names, phone numbers, contacts, message bodies and call participants are absent.

The window uses complete hours so message buckets and call windows align. Connection status describes the number at read time. Response queues and phone activity have their own observation timestamps; they can be older than a scrape. For exact historical ranges and time comparisons, use the JSON Analytics API.

What you receive#

Every metric name starts with polymorfa_analytics_.

Metric familyWhat it measures
enabled, window_start_timestamp_seconds, window_end_timestamp_seconds, generated_timestamp_secondsOpt-in state, measurement window and scrape generation time.
numbers, connected, message_measured, message_observed_hours, message_last_observed_timestamp_secondsNumber coverage, live connection state and latest message observation. Measured hours are not uptime.
requests, request_failures, request_error_ratioAPI/MCP request count, failure count and failure ratio.
messages, send_failure_ratio, business_response_secondsSend attempts, successful sends, send failures, direct incoming messages, business replies and response delay.
conversations, engagement_ratio, customer_response_secondsCompleted 24-hour direct-chat cohort counts, delivery/read/reply ratios and customer reply delay. outcome="completed" supplies the ratio denominator.
engagement_complete, segments_complete, dropped_observationsCompleteness of observed buckets and dropped-data counts. Completeness does not prove continuous observation across the whole window.
online_seconds, connection_eventsAdvertised online presence time, disconnects, connection failures, stream errors and keepalive timeouts. Online presence time is not connection uptime.
customer_activity_observed, customer_presence_signalsObserved online/offline/typing signals from enabled presence subscriptions. Signals do not count unique people or their online duration.
phone_interval_average_seconds, phone_interval_secondsCompleted observed phone activity spans and quiet gaps. The kind label separates activity and quiet; these are not phone online/offline durations.
account_activity_observed, account_activity, account_response_seconds, primary_phone_last_timestamp_secondsPhone and other-device activity, replies and response timing. Phone active periods are not power cycles.
awaiting_reply, oldest_awaiting_reply_seconds, queue_observed_timestamp_seconds, queue_completeLatest measured reply queue, age at observation and coverage.
calls, call_starts, short_answered_calls, video_calls, call_answer_eligible, call_answer_ratioCalls by direction/outcome, the answer-rate denominator and answer ratio. Still-ringing calls are excluded from that denominator. Short answered calls have less than 10 measured connected seconds.
call_talk_seconds, call_talk_measured, call_talk_duration_seconds, call_pickup_measured, call_pickup_delay_secondsMeasured connected time and per-number mean/median/p95 timings.
call_quality_measured, call_jitter_seconds, call_rtt_seconds, call_packets_lost, call_packet_loss_ratio, call_reconnectsQuality-report coverage and reported audio/connection measurements. Media and app reports stay separate.
missed_call_follow_up, missed_call_follow_up_ratio, missed_call_follow_up_delay_secondsAn answered outgoing call to the same peer within 24 hours after a missed incoming call. Completed eligible windows, returned calls, pending windows and unknown contacts stay separate.
multi_participant_calls, call_diagnosticsCounts of calls with multiple participants and bounded end-reason, app-error and transport categories.
segment_observations, segment_ratio, segment_customer_response_secondsOptional message type, text-length, send-origin, calling-code and customer-device breakdowns.

Query gauges correctly#

These are windowed gauges, including the count metrics. Repeated scrapes observe overlapping windows. Do not use rate() or increase(), or add up samples over time to count events.

For a fleet read ratio, divide the summed read count by the summed completed conversation count, filtering to complete engagement coverage:

promql
sum(
  polymorfa_analytics_conversations{outcome="read"}
  and on(job, instance, project_id, number_id)
  (polymorfa_analytics_engagement_complete == 1)
)
/
sum(
  polymorfa_analytics_conversations{outcome="completed"}
  and on(job, instance, project_id, number_id)
  (polymorfa_analytics_engagement_complete == 1)
)

Read receipts are observed reads, not app opens. Metadata categories group the first successful message in a conversation; calling-code and device shares count conversations, not unique customers or physical locations. Compare within one dimension; adding different dimensions counts the same activity repeatedly.

All durations use seconds and all ratios use 0–1. Missing measurements and null ratios are omitted. A reported zero is a measured value, not a substitute for missing data. Call counts can be zero when no retained, attributable calls exist. Never sum or average per-number percentiles to produce a fleet percentile.

Disable or troubleshoot#

Disabling Analytics stops business exports. Successful scrapes then contain only enabled=0 and window/generation timestamps. It does not delete data already sent to your telemetry backend, or change Calls retention.

A missing scope or client token returns 403. An inaccessible project or number returns 404. Invalid filters return 400. An analytics query timeout returns 503 without partial metrics; shorten the window or retry later. Authentication, credential revocation and API rate limits also apply to scrapes. Failed scrapes return an API error response; they never substitute a zero-filled measurement.

See the team export reference and project export reference.

Send hourly JSON snapshots#

See Drains for the shared configuration and delivery controls.

For a custom ingestion endpoint, open Project Settings → Drains → Add drain → Analytics. A team owner or admin selects all numbers in that project or one number, a 1-, 24- or 168-hour rolling window, and a public HTTPS destination. The Analytics drains action in Analytics opens the same flow with the selected number.

Analytics must be enabled for the team before you enable an analytics drain. New snapshots are prepared hourly for the most recent completed UTC hour. Each delivered record contains one number's aggregate analytics:

FieldMeaning
idStable record identity for the drain revision, hour and number
typeanalytics.window
projectId, numberIdProject and Number record UUIDs
period.start, period.endWindow boundaries in Unix milliseconds
windowHoursSelected rolling window: 1, 24 or 168
generatedAtSnapshot preparation time in Unix milliseconds
dataThe number's metrics from the JSON Analytics API, including engagement, metadata breakdowns, calls, connection and activity observations

The HTTPS POST uses the drain envelope, signatures, retries and deduplication headers. Its body is Polymorfa JSON, so the destination needs a receiver for this schema. Use the Prometheus receiver above when collecting OTLP metrics.

Rolling windows overlap. Treat each snapshot as a window observation; adding successive 24-hour snapshots double-counts activity. Log sampling rules do not sample these aggregates. Pausing stops new snapshots and delivery claims; resuming sends eligible queued records and prepares the latest window without backfilling every skipped hour.

Disabling Analytics deletes queued analytics snapshots and stops new collection. An in-flight delivery can finish. Data already accepted by your endpoint follows your own retention policy. Re-enabling starts a new consent period; old queued snapshots cannot return.

Phone intervals and NDJSON#

The metrics export includes phone_interval_average_seconds{kind="activity|quiet"} and phone_interval_seconds{kind="activity|quiet"}. The account_activity gauge includes completed_phone_activity_periods and phone_quiet_gaps sample counts. These are rolling-window gauges for completed observed activity spans and gaps, not counters or phone online/offline measurements. An absent sample leaves the average absent. Use the measurement definitions when comparing intervals.

Analytics drains accept JSON or NDJSON. NDJSON posts one newline-terminated {version, deliveryId, record} envelope using application/x-ndjson. JSON keeps its {version, deliveryId, records} envelope. The generated signing secret and signature verification apply to both; verify the exact bytes, including NDJSON's trailing newline.

Estimated platforms and owned-device coverage#

The windowed device gauges include:

GaugeMeaning
polymorfa_analytics_device_platforms_measuredWhether client-family observations exist in the selected window
polymorfa_analytics_device_platforms_completeWhether all retained buckets have complete coverage
polymorfa_analytics_device_platform_messagesObserved direct messages, labeled by direction (customer or account) and estimated platform
polymorfa_analytics_device_platform_sharePlatform share; omitted for incomplete coverage
polymorfa_analytics_owned_device_list_currentWhether the latest full owned-device list has no later observed change
polymorfa_analytics_owned_devicesCount in the latest full list; omitted when stale or unobserved
polymorfa_analytics_owned_device_list_observed_timestamp_secondsLast full-list observation time

These values are gauges for the rolling window, not cumulative counters. Do not apply a counter rate() to message counts. Labels never include recipient identifiers or individual device indexes. Prefix-based platforms are estimates, and Unknown remains a category. Use scoped JSON or an analytics drain for joint conversation rows and individual owned-device observations; the collector does not expand the joint rows into high-cardinality metric labels.

Recipient activity gauges#

With segments=true, measured recipient activity adds these rolling-window gauges:

MetricMeaning
polymorfa_analytics_recipient_activity_measuredRecipient observations exist in retained buckets
polymorfa_analytics_recipient_activity_completeEvery retained bucket has complete recipient coverage
polymorfa_analytics_recipient_signalsIncoming, delivery, read, online, offline and typing counts, separated by signal
polymorfa_analytics_recipient_last_signal_timestamp_secondsLatest observed signal time
polymorfa_analytics_recipient_quiet_gapsCompleted gaps of at least 15 minutes between signals from the same device
polymorfa_analytics_recipient_quiet_gap_secondsSum of those completed gaps; not offline time

Signal and timing gauges add recipient_country, recipient_device_count and device_source labels to the number/project scope. Hours with the same dimensions are combined into one sample per scrape. Country/count categories include Unknown. Presence does not identify a primary or linked device. The two coverage gauges remain available when segments=false.

Counts include multiple device receipts for one message. These values are gauges, not counters: do not use rate() or increase(). Use scoped JSON or a JSON/NDJSON analytics drain for hourly rows. Delivery does not establish a read, and quiet gaps do not establish offline time. See measurement definitions.

See also#