Observability

Monitor Sockudo connections, subscriptions, publishes, fanout, history, recovery, webhooks, and push notifications.

12 min read
View .mdEdit on GitHub

This page lists the metrics Sockudo exports, what each one tells you, and which conditions are worth paging on. Set it up before production traffic: realtime failures are often silent (a node that stops hearing its peers, a history store that degrades, a webhook queue that backs up) and only metrics make them visible.

Observability is part of the runtime contract. A realtime system should tell operators when it is connected, degraded, delayed, retrying, or dropping work.

Metrics endpoint

Terminal window
curl http://127.0.0.1:9601/metrics

Prometheus metrics are served on the dedicated [metrics] listener (9601 by default), not on the WebSocket and HTTP API port, so you can keep them on a private network.

config.toml
[metrics]
enabled = true
driver = "prometheus"
host = "0.0.0.0"
port = 9601
[metrics.prometheus]
prefix = "sockudo_"

Scrape the endpoint with Prometheus and label metrics by environment, region, node, adapter, and app where possible. Sockudo emits metrics through the metrics-rs recorder and exposes them through the Prometheus exporter by default.

How to read the tables below:

  • Names assume the default sockudo_ prefix. process_* metrics are never prefixed.
  • Most Sockudo metrics carry app_id and port labels; extra labels are listed per metric.
  • A counter only goes up: graph it with rate() or increase(). A gauge is a current value. A histogram exposes _bucket, _sum, and _count series: use histogram_quantile() for latency.
  • Prometheus adds instance and job at scrape time; use instance to compare nodes.

For OTLP export of the same metrics plus traces and logs, see Observability configuration.

TCP metrics exporter

For live debugging or sidecar consumers, Sockudo can also fan out metric events over TCP using metrics-exporter-tcp. This exporter streams protobuf-encoded metric events to connected clients; it is useful for local inspection and custom collectors, but Prometheus scraping should remain the primary production monitoring path.

config.toml
[metrics.tcp_exporter]
enabled = true
host = "127.0.0.1"
port = 5000
buffer_size = 1024

The TCP exporter has bounded buffering by default. When buffers fill, event samples can be dropped to avoid blocking the server, so do not use it as the only source for alerts or SLO dashboards.

Core signals

AreaWatch
Connectionsactive sockets, connection attempts, disconnects, connection errors by type
Subscriptionssubscribe and unsubscribe rates, active channels by type
PublishHTTP calls, idempotency hits, rate-limit rejections
Fanoutbroadcast latency, cross-node request latency, transport reconnects and drops
Recoveryresume successes by source, resume failures by code
Historywrites, write failures, queue depth, degraded and reset-required channels
Webhooksqueue depth and settled outcomes for the webhooks queue
Pushaccepted, dispatched, provider failures, queue age

Connections and traffic

MetricTypeLabelsWhat it tells you
sockudo_connectedgaugeSockets currently connected to this node. Compare across instance to spot imbalance.
sockudo_new_connections_totalcounterConnection attempts. A spike after a deploy is normal reconnect churn.
sockudo_new_disconnections_totalcounterDisconnects. Rising faster than connections means clients are leaving.
sockudo_connection_errors_totalcountererror_typeFailed connections, for example origin_not_allowed.
sockudo_memory_pressure_rejections_totalcounterport onlyNew sockets refused by memory-pressure admission.
sockudo_memory_pressure_sheddinggaugenone1 while the node is shedding new connections.
sockudo_ws_messages_received_total, sockudo_ws_messages_sent_totalcounterapp_id, portMessages received from connections, and application messages addressed to connections. Outbound control frames are counted separately in sockudo_ws_control_frames_total; see WebSocket delivery metrics.
sockudo_socket_received_bytes, sockudo_socket_transmitted_bytescounterWebSocket bandwidth.
sockudo_http_calls_received_totalcounterREST API calls, including publishes.
sockudo_http_received_bytes, sockudo_http_transmitted_bytescounterREST API bandwidth.

Channels and fanout

MetricTypeLabelsWhat it tells you
sockudo_channel_subscriptions_total, sockudo_channel_unsubscriptions_totalcounterchannel_typeSubscription churn by channel type.
sockudo_active_channelsgaugechannel_typeChannels with at least one local subscriber.
sockudo_broadcast_latency_mshistogramchannel_type, recipient_count_bucketEnd-to-end broadcast latency. Your main fanout SLI.
sockudo_horizontal_adapter_resolve_timehistogramTime for peers to answer cross-node requests such as counts and presence.
sockudo_horizontal_adapter_sent_requests, _received_requests, _received_responses, _resolved_promisescounterCross-node request volume.
sockudo_horizontal_adapter_uncomplete_promisescounterrequest_typeCross-node requests not answered by every node. Counts may be partial.
sockudo_horizontal_transport_reconnections_totalcounterdriver onlyAdapter transport reconnects, including failed Redis subscriber PINGs.
sockudo_horizontal_transport_messages_dropped_totalcounterdriver onlyCross-node messages dropped by the transport. Any increase is lost fanout.
sockudo_horizontal_transport_queue_depthgaugedriver onlyTransport backlog.
sockudo_nats_events_totalcounterevent onlyNATS client events such as disconnected and slow_consumer.

Publish controls

MetricTypeLabelsWhat it tells you
sockudo_rate_limit_checks_totalcounterlimiter_type, request_contextRate-limit decisions made.
sockudo_rate_limit_triggered_totalcounterlimiter_type, request_contextRequests rejected by a rate limit.
sockudo_idempotency_publish_totalcounterPublishes that carried an idempotency key.
sockudo_idempotency_duplicates_totalcounterRetries answered from the idempotency cache. A high ratio points at aggressive client retries.
sockudo_ephemeral_messages_totalcounterV2 ephemeral messages delivered.
sockudo_event_filter_suppressed_total, sockudo_echo_suppressed_totalcounterV2 deliveries skipped by event filters or echo control.

History, recovery, and versioned messages

MetricTypeLabelsWhat it tells you
sockudo_history_writes_total, sockudo_history_write_failures_totalcounterDurable history appends and failures. Failures put channels at risk of degrading.
sockudo_history_write_latency_mshistogramDurable write latency.
sockudo_history_queue_depthgaugeHistory writer backlog. Growth means the backend is slower than publish rate.
sockudo_history_retained_messages, sockudo_history_retained_bytesgaugeRetained history volume.
sockudo_history_evictions_total, sockudo_history_evicted_bytes_totalcounterRows removed by retention.
sockudo_history_degraded_channelsgaugeChannels whose durable stream cannot currently prove continuity.
sockudo_history_reset_required_channelsgaugeChannels that need an operator reset before history and recovery resume.
sockudo_history_recovery_success_totalcountersource (hot, cold)Successful resumes, from the hot buffer or durable history.
sockudo_history_recovery_failures_totalcountercodeFailed resumes: position_expired, continuity_unverifiable, stream_reset, persistence_unavailable.
sockudo_versioned_message_mutations_totalcounteraction, resultUpdate, delete, and append attempts and outcomes.
sockudo_versioned_message_retrieval_totalcountersurface, resultLatest-version and version-list reads.
sockudo_versioned_history_substitution_totalcounterresultHistory rows replaced by their latest version.
sockudo_presence_history_*mixedThe same write, retention, queue, degraded, and reset-required signals for presence history.

Annotations and delta compression

MetricTypeLabelsWhat it tells you
sockudo_annotations_published_total, sockudo_annotations_deleted_totalcounterchannel, typeAnnotation create and delete volume.
sockudo_annotation_summary_deliveries_totalcounterchannelSummary messages delivered.
sockudo_annotation_summary_clipped_totalcounterchannel, typeSummaries clipped by size limits.
sockudo_annotation_projection_rebuild_total, _duration_secondscounter, histogramchannelFull projection rebuilds and their cost.
sockudo_delta_compression_bandwidth_saved_bytes, _original_bytescounterchannel_nameBandwidth saved by delta compression.
sockudo_delta_compression_full_messages_total, _delta_messages_totalcounterchannel_nameFull versus delta frames sent.
sockudo_delta_cluster_coordination_backend_upgaugebackend onlyHealth of the delta coordination backend.

Queues, push, and runtime

MetricTypeLabelsWhat it tells you
sockudo_queue_depthgaugebackend, queue, stateJobs by state (ready, active, delayed, dead-letter, completed). Redis-family queue backends.
sockudo_queue_settled_totalcounterbackend, queue, outcomeJob outcomes: completed, retry, dead-letter, panic-or-lease-lost.
sockudo_queue_enqueue_total, sockudo_queue_claimed_totalcounterbackend, queueJobs added and picked up.
sockudo_queue_processing_duration_secondshistogrambackend, queueJob processing time.
sockudo_push_publish_accepted_totalcountersee push docsPush publishes admitted.
sockudo_push_dispatched_total, sockudo_push_provider_failures_totalcountersee push docsProvider sends and failures by provider and failure class.
sockudo_push_queue_oldest_age_secondsgaugesee push docsAge of the oldest push work item; the best push backlog signal.
sockudo_tokio_active_tasks, sockudo_tokio_worker_busy_ratiogaugeworker on busy ratioRuntime saturation. Busy ratio near 1.0 on every worker means the node is CPU bound.
process_resident_memory_bytes, process_open_fdsgaugenoneMemory and file descriptors. Each socket uses a descriptor; compare with process_max_fds.

The full push metric catalog, with labels and push-specific alerts, is in Push operations.

WebSocket delivery metrics

MetricTypeLabelsMeaning
sockudo_ws_messages_sent_totalcounterapp_id, portApplication messages addressed to connections. Each node counts only its own local recipients, so sum across nodes is the cluster delivery total. Control frames are excluded.
sockudo_ws_control_frames_totalcounterapp_id, port, frame_typeControl frames sent through the connection handler. frame_type is one of pong, error, connection_established, ack, auth, cache_miss, delta_negotiation, history, other.
sockudo_ws_message_byteshistogramapp_id, portSerialized size of each published application message, buckets 64 B to 1 MiB.
sockudo_socket_transmitted_bytescounterapp_id, portBytes addressed to connections (message size × recipients).

How these are counted:

  • Deliveries are counted at address time, before the socket write. Delta conflation and tag filtering can still skip individual writes, so the counter can slightly exceed actual writes. This matches Pusher’s addressed-delivery semantics.
  • sockudo_ws_message_bytes is observed once per published message on the origin node, never on receiving nodes or per recipient. It is a per-message size distribution; use sockudo_socket_transmitted_bytes for total bytes. A Prometheus histogram cannot report max.
  • Presence member_added, member_removed and presence_update events are counted on remote nodes but not on the node that handled the join or leave.
  • Server-initiated pusher:ping frames are not counted in sockudo_ws_control_frames_total.
  • A watch on frame_type="other" flags new protocol events that need a named frame_type.

When ably-compat is enabled, two lock-free operator snapshots supplement Prometheus:

  • /operator/stats/ably-runtime reports queued messages/bytes, overflow and continuity loss, total encoded frames, shared data-projection encodes (data_encoded), fanout counts, replay source and recovery backend calls, duplicate suppression, backend/degraded/reset state, expiry, and derived-filter cache pressure. data_encoded excludes ACK, heartbeat, connection, and channel-control frames, so it is the counter used to verify one encode per active data format.
  • /operator/stats/aggregation reports the bounded stats queue capacity, backlog, accepted, flushed, dropped, and failed observations.

These endpoints expose counters only. They never return credentials, device tokens, channel payloads, or raw encrypted values.

AI Transport

AI Transport observability is domain-blind. Sockudo reads only the well-known extras.ai.transport headers and never labels metrics by channel, run ID, message ID, or client ID. Headers are validated once and then passed as a typed borrowed view to metric and webhook classification. Empty run-client-id and step-client-id unknown-owner sentinels remain unchanged on the wire but are treated as absent when deriving an identity.

Metrics exposed at /metrics include:

  • sockudo_ai_runs_started_total
  • sockudo_ai_runs_ended_total{reason}
  • sockudo_ai_cancel_signals_total
  • sockudo_ai_active_streams
  • sockudo_ai_stream_duration_seconds
  • sockudo_ai_stream_bytes_total
  • sockudo_ai_messages_rejected_total{code}
  • sockudo_ai_messages_unparseable_total
  • sockudo_appends_received_total
  • sockudo_appends_delivered_total
  • sockudo_rollup_ratio
  • sockudo_flush_latency
  • sockudo_history_recovery_success_total{source}
  • sockudo_history_recovery_failures_total{code}
  • sockudo_versioned_message_mutations_total{action,result}
  • sockudo_versioned_message_retrieval_total{surface,result}

The four production signals are run outcomes, stream rate, rejects by code, and rollup efficiency. Use docs/public/grafana/ai-transport-observability.json as the starting Grafana dashboard.

sockudo_rollup_ratio is the number of input appends folded into one delivered frame, so higher means rollup is saving more fanout. sockudo_flush_latency is in milliseconds and should stay near the configured rollup window.

Active-stream gauges use exact atomic insertion/removal deltas. Tracker entries that never receive a terminal event expire at the configured AI orphan TTL and decrement the same gauge exactly. AI lifecycle webhooks are awaited into the configured bounded webhook queue, which supplies backpressure and retry handling; Sockudo does not spawn an unbounded Tokio task per event or retain AI events in the optional in-process batching vector.

Dashboard starter panels:

PanelMetric
Active AI streamssockudo_ai_active_streams
Run outcomessockudo_ai_runs_started_total, sockudo_ai_runs_ended_total
Rejects by codesockudo_ai_messages_rejected_total
Rollup efficiencysockudo_appends_received_total vs sockudo_appends_delivered_total, sockudo_rollup_ratio
Rollup latencysockudo_flush_latency
Recovery healthsockudo_history_recovery_success_total, sockudo_history_recovery_failures_total
Durable statesockudo_history_degraded_channels, sockudo_history_reset_required_channels
Push backlogpush queue/status/provider metrics from the push dashboard

For support escalation, capture the channel, wall-clock time window, verified clientId, and first error code before collecting logs. Do not ask customers for provider payloads unless the codec layer explicitly requires them.

Persist completed AI runs

For Ably-style production persistence, persist completed runs from your backend instead of making Sockudo a domain store:

  1. Enable the ai_run_ended webhook for the app.
  2. On reason: "complete", query the history endpoint for the channel around the webhook time.
  3. Select messages with the same extras.ai.transport.run-id.
  4. Store the reduced transcript in your application database.
app.post("/sockudo/webhooks", async (req, res) => {
for (const event of req.body.events) {
if (event.name !== "ai_run_ended" || event.reason !== "complete") continue;
const history = await sockudo.channelHistory(event.channel, {
limit: 1000,
direction: "newest_first",
});
await storeCompletedRun({
runId: event.run_id,
channel: event.channel,
items: history.items.filter((item) => {
return item.message?.extras?.ai?.transport?.["run-id"] === event.run_id;
}),
});
}
res.sendStatus(200);
});

Each history item wraps the delivered message in its message field, so AI Transport headers are at item.message.extras.ai.transport. The page limit is capped by the channel’s history max_page_size; follow next_cursor for long runs. Verify the webhook signature before trusting the event, as described in Webhooks.

Logs

Use structured logs for events that operators need to investigate:

{
"level": "warn",
"target": "sockudo_push",
"app_id": "app-id",
"publish_id": "pub_123",
"provider": "apns",
"error": "BadDeviceToken"
}

Avoid logging secrets, raw auth signatures, provider tokens, or encrypted payloads. Log filters, JSON output, and the data-safety policy are in the logging reference.

Grafana dashboards

Recommended panels:

  • active connections by node
  • connection churn
  • publish rate by app
  • fanout latency histogram
  • subscription auth failure rate
  • recovery success ratio
  • replay buffer pressure
  • queue depth for webhooks and push
  • push provider failure rate by provider
  • APNs, FCM, Web Push latency by outcome
  • AI run outcomes by reason
  • AI stream duration and active streams
  • AI reject codes and unparseable headers
  • AI append rollup efficiency

Alerts

Alert on symptoms operators can act on:

  • readiness failures
  • adapter connection loss
  • rising publish failures
  • high auth rejection rate after deploy
  • recovery success ratio dropping
  • history write failures
  • webhook retry backlog
  • push queue backlog
  • push provider credential failures
  • push delivery status callback failures

Starting rules, to tune against your own baseline:

AlertExpressionWhy it matters
Cross-node fanout lossincrease(sockudo_horizontal_transport_messages_dropped_total[5m]) > 0Subscribers on some nodes missed messages.
Adapter flappingincrease(sockudo_horizontal_transport_reconnections_total[10m]) > 3The adapter link is unstable; expect gaps until it settles.
Durable history degradedmax(sockudo_history_degraded_channels) > 0 for 5mRecovery and history reads on those channels fail closed.
Reset requiredmax(sockudo_history_reset_required_channels) > 0An operator must reset the stream; it will not heal on its own.
History write failuresincrease(sockudo_history_write_failures_total[5m]) > 0The history backend is rejecting writes.
Recovery failure ratiosum(rate(sockudo_history_recovery_failures_total[10m])) / (sum(rate(sockudo_history_recovery_success_total[10m])) + sum(rate(sockudo_history_recovery_failures_total[10m]))) > 0.05Reconnecting clients are falling back to full backfill. Break down by code.
Fanout latencyhistogram_quantile(0.99, sum by (le) (rate(sockudo_broadcast_latency_ms_bucket[5m]))) > 250p99 delivery is slower than your SLO.
Memory sheddingmax(sockudo_memory_pressure_shedding) == 1 for 2mThe node is refusing new connections.
Webhook backlogsockudo_queue_depth{queue="webhooks",state="ready"} above baseline for 10mWebhook consumers are falling behind or failing.
Webhook dead lettersincrease(sockudo_queue_settled_total{queue="webhooks",outcome="dead-letter"}[15m]) > 0Events were given up on after all retries.
Rate limitingsum(rate(sockudo_rate_limit_triggered_total[5m])) by (app_id) well above baselineA client or tenant is being throttled.

Push status workflow

Push publishes are asynchronous. Store the publishId returned by the API when a business workflow needs support visibility.

const response = await sockudo.publishPush({
recipients: [{ type: "channel", channel: "orders" }],
payload: { title: "Order updated", body: "Packed" },
});
console.log(response.publishId);

Then inspect status with a signed request, for example through the server SDK:

const status = await sockudo.getPublishStatus(response.publishId);

This calls GET /apps/{app_id}/push/publish/{publish_id}/status, which requires push admin.

Status records should be retained long enough for customer support and incident review. Retention is push.publish_status_ttl_days (default 30).

Next steps