Skip to content

Observability ​

Metrics ​

Checkgate exposes Prometheus/OpenMetrics metrics at GET /metrics on a separate listener, off by default:

bash
METRICS_ADDR=0.0.0.0:9464   # or 127.0.0.1:9464 for a local agent

The metrics port is never served on the public port (PORT). Bind it to a private interface, or keep it unpublished (Docker) / reachable only inside the cluster (Kubernetes), and scrape it from there. Metrics carry no secrets, but they do describe traffic and capacity.

yaml
# Prometheus
scrape_configs:
  - job_name: checkgate
    static_configs: [{ targets: ["checkgate:9464"] }]
yaml
# Kubernetes: container port + PodMonitor/ServiceMonitor, or annotations
ports:
  - { name: http, containerPort: 3000 }
  - { name: metrics, containerPort: 9464 }
env:
  - { name: METRICS_ADDR, value: "0.0.0.0:9464" }

Labels are fixed, low-cardinality sets: route templates (/api/environments/{env_id}/flags/{key}, never a raw path), status classes (2xx…5xx) and small enums. Flag keys, environment ids, SDK keys, users, addresses and connection ids never appear in metrics. Every enumerated series exists from start-up at 0, so rate() and alerts work before the first event. Recording is lock-free on the request path.

The instrumentation uses prometheus-client, whose data model is OpenMetrics; an OpenTelemetry collector can scrape the same endpoint (Prometheus receiver) to forward metrics to any OTel backend.

Reference ​

MetricTypeMeaning
checkgate_http_requests_total{method,route,status_class}counterRequests handled. Unmatched paths (dashboard files) use route="static".
checkgate_http_request_duration_seconds{method,route}histogramTime to the response head. For /stream that is the bootstrap, not the stream's lifetime.
checkgate_flag_updates_totalcounterChange events this instance published (or tried to).
checkgate_flag_update_publish_failures_totalcounterEvents Redis did not accept after a retry. Delivered locally; other instances recover by resync.
checkgate_flag_updates_received_totalcounterEvents received from the Redis subscription (from every instance, including this one).
checkgate_flag_publish_duration_secondshistogramTime to publish one event, retry included.
checkgate_redis_connectedgauge1 while the subscription is up and answering pings.
checkgate_redis_reconnections_total{reason}counterSubscription losses: closed, ping_timeout, connect_failed.
checkgate_resync_requests_total{trigger}counterTimes clients were told to re-bootstrap: subscriber_reconnect, remote, reconciliation, environment_removed, segment_read_failed (a committed change could not be expanded with its segments, so its environment re-bootstraps instead), key_revoked (an SDK key was revoked, so its environment's open streams close and reconnect).
checkgate_resync_failures_totalcounterFailed attempts to broadcast a RESYNC through Redis.
checkgate_resync_pendinggauge1 while a RESYNC broadcast is waiting for Redis.
checkgate_sync_reconciliations_total{outcome}counterReconciliation passes, success/failure.
checkgate_sync_reconcile_duration_secondshistogramDuration of one pass.
checkgate_sync_divergences_totalcounterEnvironments found with committed changes never relayed — lost notifications.
checkgate_sync_tracked_flagsgaugeEntries in the reconciliation index.
checkgate_sse_connections_totalcounterStreams opened.
checkgate_sse_rejections_total{reason}counterStreams refused: capacity, bootstrap_busy, bootstrap_error, draining.
checkgate_sse_disconnects_total{reason}counterStreams ended: client, lagged, resync, shutdown.
checkgate_sse_lagged_messages_totalcounterEvents skipped by clients that fell behind (each such client is disconnected).
checkgate_sse_active_connectionsgaugeOpen streams on this instance.
checkgate_sse_bootstrap_duration_secondshistogramBootstrap read time, including waiting for a slot.
checkgate_snapshot_query_duration_secondshistogram/flags/snapshot read time, including waiting for a slot.
checkgate_snapshot_requests_totalcounter/flags/snapshot requests (SDK poll fallback), by outcome (ok, busy, error) and format (v2, legacy).
checkgate_playground_evaluations_totalcounterEvaluation playground requests, by outcome (ok, not_found, invalid, error).
checkgate_db_pool_connections / _idle_connections / _max_connectionsgaugePostgreSQL pool.
checkgate_database_upgauge1 if the last database check (readiness or reconciliation) succeeded.
checkgate_readygauge1 while ready (not draining).
checkgate_analytics_rows_total{table,outcome}counterImpression (table="impressions") and event (events) rows sent for ingestion: accepted (stored), invalid (skipped inside an accepted batch: empty or over-long key), quota (in a batch refused by the per-key quota), batch_too_large (in a batch of more than 500).
checkgate_ingest_quota_rejections_total{limit}counterIngest requests refused with 429 by the per-key quota, by the budget that refused them: requests or rows.
checkgate_ingest_quota_local_decisions_totalcounterQuota decisions this instance made alone because Redis did not answer (the budget is then per instance).
checkgate_analytics_cleanup_runs_total{outcome}counterRetention passes this instance ran: success/failure. Passes skipped because another instance holds the lock, or because one ran within the interval, are not counted.
checkgate_analytics_cleanup_deleted_rows_total{table}counterExpired rows deleted by this instance's passes.
checkgate_analytics_cleanup_duration_secondshistogramDuration of one retention pass (buckets 10 ms to 44 min).
checkgate_analytics_cleanup_last_success_timestamp_secondsgaugeUnix time this instance last completed a pass; 0 if it never has (with several instances, take the max across them).
checkgate_build_info{version}infoBuild version.
process_cpu_seconds_totalcounterCPU time (user + system) of the server process. Linux only.
process_resident_memory_bytes / process_virtual_memory_bytesgaugeResident and virtual memory. Linux only.
process_open_fds / process_threadsgaugeOpen file descriptors (each SSE stream holds one) and OS threads. Linux only.
process_start_time_secondsgaugeProcess start time, Unix epoch. Linux only.

The process_* metrics use the standard names of every Prometheus client library, so existing dashboards work. They are read from /proc/self only when /metrics is scraped (no background sampling) and are absent on non-Linux hosts. No metric carries a user key, attribute value, SDK key or flag key as a label: every label is from a fixed set (route templates, reasons, outcomes).

Reading the signals ​

SituationWhat you see
Healthyredis_connected=1, database_up=1, ready=1; sync_divergences_total flat; flag_update_publish_failures_total flat; sse_disconnects_total{reason="lagged"} near 0.
Redis unavailableredis_connected=0; redis_reconnections_total{reason="connect_failed"} rising; flag_update_publish_failures_total rising on writes; resync_pending=1; /health/ready reports degraded (still 200 unless READY_REQUIRES_REDIS=true).
Redis connection silently deadredis_reconnections_total{reason="ping_timeout"} increments, then resync_requests_total{trigger="subscriber_reconnect"}.
Database unavailabledatabase_up=0; sync_reconciliations_total{outcome="failure"} rising; 5xx on API routes; sse_rejections_total{reason="bootstrap_error"}; /health/ready 503.
Growing SSE loadsse_active_connections rising toward SSE_MAX_CONNECTIONS; then sse_rejections_total{reason="capacity"}.
Reconnect wave / slow databasesse_bootstrap_duration_seconds p95 rising; sse_rejections_total{reason="bootstrap_busy"}; db_pool_idle_connections at 0.
Lagging clientssse_disconnects_total{reason="lagged"} and sse_lagged_messages_total rising.
SDKs falling back to pollingsnapshot_requests_total{outcome="ok"} rising while sse_active_connections drops: something between SDKs and the server (a proxy, a firewall) keeps streams from being established. SDKs poll only after 3 consecutive failed stream attempts (pollFallbackThreshold); a stream that connects and later drops is reconnected instead. The Node.js and Python SDKs' getHealth().polling confirms it.
Lost notifications repairedsync_divergences_total and resync_requests_total{trigger="reconciliation"} increment, with a WARN log naming the environment.
Analytics quota reachedingest_quota_rejections_total rising and analytics_rows_total{outcome="quota"} growing; SDKs drop those batches (flags unaffected). Raise RATE_LIMIT_INGEST_ROWS_PER_MINUTE if the traffic is legitimate.
Quota backend downingest_quota_local_decisions_total rising (with redis_connected=0): each instance enforces the quota alone until Redis answers.
Retention not runningmax(checkgate_analytics_cleanup_last_success_timestamp_seconds) older than a few intervals, or analytics_cleanup_runs_total{outcome="failure"} rising with an ERROR log "Analytics retention pass failed".
Persistent publish errorsflag_update_publish_failures_total rising while redis_connected=1: the publisher connection (not the subscriber) is failing — check Redis maxclients, ACLs, network policy.

Suggested alerts ​

yaml
groups:
  - name: checkgate
    rules:
      - alert: CheckgateRedisDisconnected
        expr: max_over_time(checkgate_redis_connected[5m]) == 0
        for: 5m
      - alert: CheckgateDatabaseDown
        expr: checkgate_database_up == 0
        for: 2m
      - alert: CheckgateLostNotifications
        # Occasional repairs are the system working; a steady rate means events
        # are being lost (publisher crashes, Redis trouble).
        expr: increase(checkgate_sync_divergences_total[1h]) > 3
      - alert: CheckgatePublishFailures
        expr: increase(checkgate_flag_update_publish_failures_total[10m]) > 0
      - alert: CheckgateSseNearCapacity
        expr: checkgate_sse_active_connections > 0.8 * 10000   # your SSE_MAX_CONNECTIONS
      - alert: CheckgateSlowBootstrap
        expr: histogram_quantile(0.95, rate(checkgate_sse_bootstrap_duration_seconds_bucket[5m])) > 1
        for: 10m
      - alert: CheckgateAnalyticsRetentionStalled
        # Default interval is one hour; allow a few missed passes. Leave this
        # out if ANALYTICS_RETENTION_DAYS=0 (no passes run).
        expr: time() - max(checkgate_analytics_cleanup_last_success_timestamp_seconds) > 4 * 3600
        for: 15m
      - alert: CheckgateIngestQuotaRejecting
        expr: increase(checkgate_ingest_quota_rejections_total[15m]) > 0

Analytics ingestion and retention ​

Ingestion volume is rate(checkgate_analytics_rows_total{outcome="accepted"}[5m]) (rows per second, by table). Rows refused by the per-key quota appear under outcome="quota"; a steady stream of them from one deployment either means an SDK key is being abused or that the quota is set below the real traffic (the server logs each refusal as Ingest quota exceeded, with the credential's numeric id but never its value). Per-address limit refusals of ingest requests are checkgate_http_requests_total{route="/api/environments/{env_id}/impressions",status_class="4xx"}.

Each completed retention pass is logged at INFO as Analytics retention pass complete, with deleted_impressions, deleted_events, batches and elapsed_ms; one pass at most per ANALYTICS_RETENTION_INTERVAL_SECS runs across all instances, on whichever instance checks first. A table's size in steady state is about its accepted-row rate × the retention period; the SQL in Self-Hosting → Analytics retention shows the current size and the rows kept for running experiments.

Health endpoints ​

EndpointPurposeFails when
GET /health/liveLivenessNever while the process serves requests. A dependency outage never fails it, so it cannot cause restart loops.
GET /health/readyReadiness — route traffic here?Draining for shutdown; PostgreSQL does not answer SELECT 1 within 2 s; Redis subscription down only if READY_REQUIRES_REDIS=true.
GET /healthLegacy, unchanged (OK)Same as liveness.

/health/ready answers JSON:

json
{ "status": "ready", "checks": { "database": "ok", "redis": "ok" } }

status is ready, degraded (Redis down, still serving: writes commit and reach this instance's clients; other instances recover by reconciliation), unavailable (503) or draining (503). None of the health endpoints is rate limited.

Why Redis does not fail readiness by default: PostgreSQL is authoritative, and every read path (bootstrap, snapshot, REST) works without Redis. Taking every instance out of rotation during a Redis outage would turn a propagation delay into a full outage. Set READY_REQUIRES_REDIS=true if you prefer to drain an instance whose own path to Redis is broken while others remain healthy.

Logs ​

Logs are JSON lines on stdout (RUST_LOG sets the level). Stable messages and fields for operations:

EventLevelFields
Redis subscriber: listeningINFOchannel
Redis subscriber: connection lost — reconnectingWARNreason
Redis subscriber: ping unanswered / ping failedWARNtimeout / error
Redis subscriber: resubscribed — resyncing local SSE clientsWARN
Redis publish failed — delivered locally, other instances will resyncWARNoperation, error
Redis reachable again — resync broadcast sentINFO
Committed flag changes were never relayed to this instance — resyncing the environment's clientsWARNenvironment_id, flags, sample_keys
Sync reconciliation failed — will retryWARNerror
Could not read segments to expand a committed flag change — resyncing this environment's clients instead of publishing itWARNoperation, env_id, error
SSE client connectedINFOconnection_id, environment_id, sdk_key_name, bootstrap_flags, bootstrap_ms, client_ip
SSE client disconnectedINFOconnection_id, reason
SSE client lagged — closing connection to trigger reconnectWARNmissed_messages
SSE connection refused — instance at SSE_MAX_CONNECTIONSWARN
Shutdown requested / Draining: … / Server shut down gracefullyINFOsignal, drain_delay, grace_period, open_streams, elapsed_ms
Scheduler: …INFO/ERRORid, key, error

SDK keys, session cookies, personal access tokens, setup tokens, user attributes and connection-string passwords are never logged (connection strings are not logged at all; the image's entrypoint logs them redacted).

Released under the Apache License 2.0.