Skip to content
MSO CloudDocumentation

Runbook: observability (web + worker)

On this page

On-call reference for the metrics the platform exposes, the three alarms the watchdog service evaluates and emails, and the health/readiness contract. Scope: the web, worker and watchdog services in docker-compose.prod.yml.

1. Endpoints#

Endpoint Service Gate Answers
GET /api/health web public (proxy allow-list) Liveness only. 200 whenever the Node process serves HTTP. Touches no dependency. Used by the compose healthcheck and the Traefik upstream check.
GET /api/ready web compose network only (isInternalOnlyRequest) Readiness. SELECT 1 on Postgres plus a Redis PING, each with a 2s deadline. 200 {"status":"ready"} or 503 {"status":"not_ready","checks":{...}}.
GET /api/metrics web compose network and Authorization: Bearer $METRICS_TOKEN Prometheus text (version=0.0.4). 404 when METRICS_TOKEN is unset or the request crossed the edge.
GET /live, /ready, /metrics worker private listener on WORKER_METRICS_PORT (9464), no host port published Worker liveness, readiness (startup, Redis, Postgres, DB role, workers, outbox, metrics) and Prometheus text.

Contract rules:

  • /api/health never learns about a dependency. The web container carries autoheal=true, so a failing healthcheck restarts it; a Postgres blip must not recycle the web tier at the moment Postgres can least afford reconnects.
  • /api/ready is the endpoint that tells an operator whether the process can serve work. Nothing restarts on its answer.
  • Neither observability endpoint is reachable from the internet. /api/metrics carries org ids as labels and every tRPC procedure path; a request that crossed Traefik or Cloudflare gets a 404 identical to an unconfigured deployment.

Scrape from inside the compose network:

# `msocloud-web-prod` is the web service's NETWORK ALIAS, not a container
# name (rolling deploys create `msocloudnet-web-<N>`); resolve the live one.
WEB="$(docker ps --format '{{.Names}}' | grep -m1 msocloudnet-web)"
docker exec "$WEB" \
  curl -sS -H "Authorization: Bearer $METRICS_TOKEN" http://127.0.0.1:3000/api/metrics | head -40
docker exec "$WEB" curl -sS -i http://127.0.0.1:3000/api/ready
docker exec msocloud-worker-prod curl -sS http://127.0.0.1:9464/metrics | head -40

2. What each metric means#

Web (yng_web_*)

Metric Type Meaning
yng_web_up gauge 1 while the process serves metrics.
yng_web_trpc_calls_total{procedure,type,outcome} counter Completed tRPC calls. outcome is ok or the tRPC error code (UNKNOWN for an error that is not a TRPCError).
yng_web_trpc_duration_seconds{procedure} histogram End-to-end call duration, rate-limit preflight and RLS transaction included. Buckets 10ms to 30s.
yng_web_db_pool_max gauge DB_POOL_MAX in force (25 in production).
PLATFORM_ALERT_EMAILS watchdog BOOTSTRAP_ADMIN_EMAIL
WATCHDOG_INTERVAL_MS watchdog 60000
WATCHDOG_PROBE_TIMEOUT_MS watchdog 5000
yng_web_db_pool_in_use gauge RLS transactions holding a pooled connection right now. Every RLS-scoped resolver holds one for its whole lifetime.
yng_web_db_pool_waiting gauge RLS transactions waiting for a connection. Above zero means the pool is exhausted.
yng_web_db_pool_peak_in_use gauge High-water mark since boot, so a burst between scrapes is not missed.
yng_web_llm_tokens_total{org,purpose,direction} counter LLM tokens charged by the web process. A signal, not the budget: the refusal lives in @yng/ai against ai_usage_log.
yng_web_llm_calls_total{org,purpose} counter Billed LLM calls by the web process.
yng_web_process_resident_memory_bytes, ..._heap_used_bytes, ..._uptime_seconds gauge Process footprint. RSS that never returns between scrapes is the first sign of an unbounded frame pinned in a cache.
yng_web_metric_source_up{source} gauge 0 when a registered metric source threw on this scrape. The scrape still succeeds.

Cardinality is bounded: org and purpose labels collapse into __over_limit__ past their ceiling. The total stays correct; only the breakdown stops.

Cache families (from apps/web/src/server/cache-stats.ts, the one registry every cache reports through):

Metric Type Meaning
yng_web_cache_events_total{cache,event} counter event is hit, miss, evict or refused. evict is a drop to stay inside a bound, never an expiry.
yng_web_cache_entries{cache} gauge Entries currently retained.
yng_web_cache_bytes{cache} gauge Approximate retained bytes — a structural estimate, not a heap measurement. Read the TREND, never the absolute value.

How to read them: a rising evict next to a low hit is a bound that is too small; a rising evict next to a high hit is a healthy cache. A rising refused is the one to act on — it counts values too large to retain, i.e. a caller resolving an unbounded frame. A cache whose module has not been loaded in this process emits no series at all; an absent series is honest, a zero would read as "never hit".

Worker (yng_worker_*, yng_redis_*, yng_eventbus_*)

Metric Type Meaning
yng_worker_ready, yng_worker_dependency_up{dependency} gauge Readiness overall and per dependency.
yng_worker_jobs_total{queue,status} counter Jobs processed since boot. Queue-level: a scheduled tick counts as one completed however many tenants failed inside it.
yng_worker_scheduled_org_outcomes_total{job,status} counter PER-ORG outcomes inside a scheduled fan-out. This is the counter that distinguishes "the tick ran" from "the tick worked". status is ok or failed.
yng_worker_queue_depth{queue,state} gauge Waiting / active / delayed / failed per BullMQ queue.
yng_worker_dlq_open gauge Unresolved sync_dead_letters rows across all queues.
yng_worker_outbox_pending, ..._oldest_age_seconds gauge Committed job hand-offs not yet published to BullMQ.
yng_redis_memory_bytes{kind="used"|"peak"|"max"} gauge Redis used_memory, used_memory_peak and the configured maxmemory.
yng_redis_evicted_keys_total counter Keys Redis evicted. Must stay 0 under noeviction; nonzero means the policy was changed and BullMQ keys can now be discarded.
yng_eventbus_stream_entries{topic} gauge Stream entries per topic, summed over every org partition.
yng_eventbus_stream_entries_total gauge Entries across every topic and org.
yng_eventbus_stream_budget_entries gauge The global budget from packages/eventbus/src/budget.ts (default 250,000 entries, about 250 MB at 1 KB per entry).
yng_eventbus_stream_scan_complete gauge 0 when the key scan hit its cap, i.e. the totals above are a lower bound.
yng_redis_probe_up, yng_eventbus_stream_probe_up, yng_worker_queue_probe_up{queue}, yng_worker_dlq_probe_up gauge 0 when that probe failed or timed out. A missing number is reported, never guessed.

3. The three alarms#

A. Redis memory

  • Fire at yng_redis_memory_bytes{kind="used"} / yng_redis_memory_bytes{kind="max"} > 0.70 for 10 minutes.
  • Also fire on increase(yng_redis_evicted_keys_total[1h]) > 0 — under noeviction this can only mean the policy changed.
  • Why it is an action, not a notification. One Redis carries BullMQ, the eventbus streams, the rate limiter and sessions at --maxmemory 512mb --maxmemory-policy noeviction. The ceiling is a cliff: at maxmemory every write is refused at once, so ingest, AI generation and cache invalidation stop together.
  • Triage. Read yng_eventbus_stream_entries_total against yng_eventbus_stream_budget_entries and yng_worker_queue_depth{state="failed"} (BullMQ retains 5,000 failed jobs per queue). Streams over budget point at a topic with an unusually busy org; a large failed set points at a queue that needs draining.
  • Do not change the eviction policy. An evicted BullMQ key is a silently lost job.

B. DB pool saturation

  • Fire at yng_web_db_pool_waiting > 0 for 5 minutes, or yng_web_db_pool_in_use / yng_web_db_pool_max > 0.80 for 10 minutes.
  • Why. DB_POOL_MAX is 25 for the whole web tier, and every RLS-scoped resolver holds one pooled connection for its entire lifetime. A deck with 40+ widgets has no per-request concurrency limiter, so a burst can exhaust the pool for every tenant at once.
  • Triage. yng_web_trpc_duration_seconds by procedure names the slow resolver. SET LOCAL statement_timeout (60s, RLS_TX_TIMEOUT_MS) means a runaway transaction self-aborts rather than holding a connection forever, so sustained saturation is volume, not a stuck query. Raising DB_POOL_MAX needs Postgres max_connections headroom checked first.

C. tRPC error rate

  • Fire at sum(rate(yng_web_trpc_calls_total{outcome=~"INTERNAL_SERVER_ERROR|UNKNOWN"}[5m])) / sum(rate(yng_web_trpc_calls_total[5m])) > 0.02 for 10 minutes.
  • Exclude expected refusals. FORBIDDEN, UNAUTHORIZED, BAD_REQUEST, NOT_FOUND and TOO_MANY_REQUESTS are the application working. Only INTERNAL_SERVER_ERROR and UNKNOWN are incidents.
  • Triage. The procedure label points at the router; the structured request log (component: "trpc", one line per failing call with orgId, procedure, durationMs, errorCode) carries the identity. Inputs are never logged.

The watchdog evaluates A, B, C and hard-down

No Prometheus or Alertmanager runs here. The watchdog compose service (apps/worker/src/watchdog/main.ts, the worker image with its own command) evaluates the rules above and emails an operator. It is out of band on purpose: any check that is a BullMQ job or goes through the notification outbox stops exactly when Redis refuses writes, Postgres is down or the worker has crashed. The watchdog holds no database credential, no BullMQ connection and has no depends_on; scripts/verify-prod-compose.mjs fails if that changes.

Every for window and threshold is the number printed in A, B and C above. The only rule this section adds:

Alarm Rule Source
A. memory used / max > 0.70 for 10 min (skipped when maxmemory is 0, i.e. unlimited) A
A. evictions evicted_keys increased within the last 1 h A
B. waiting yng_web_db_pool_waiting > 0 for 5 min B
B. utilisation in_use / max > 0.80 for 10 min B
C. error rate INTERNAL_SERVER_ERROR + UNKNOWN over all calls > 2 % across the last 5 min of scrapes, for 10 min C
hard-down: web / worker / Redis web /api/ready, worker /ready not 200, or Redis INFO failing, on 3 consecutive failed probes mechanical choice (below)

Mechanics the rules above do not state:

  • Probe every 60 s (WATCHDOG_INTERVAL_MS), each probe with a 5 s timeout (WATCHDOG_PROBE_TIMEOUT_MS); a timeout is a failed probe. "3 consecutive failed probes at 60 s" is the mechanical choice that makes hard-down fire after about 3 minutes of continuous failure: it is not tuned to an incident. A rolling deploy that keeps the worker unready for 3 minutes therefore opens and later resolves worker_down.
  • A for window starts at the first probe over the threshold and is cleared by any probe under it. C needs about 15 minutes of history (5 min rate window, then the 10 min window).
  • C is computed from successive /api/metrics scrapes, not Prometheus rate(). An interval where any counter went down (web restart, or the two replicas of a rolling deploy answering alternately) is discarded. No traffic in the window is "not firing", as in Prometheus.
  • No reading means no verdict: a pending window starts over, and an incident that is already open stays open until a reading shows it cleared. Hard-down never lacks a reading.
  • An incident resolves on the first probe that no longer breaches. The for window protects against a flapping reopen, and the 6 h reminder cap against repeated mail.
  • Incident state is in memory. A watchdog restart forgets open incidents and an eviction that happened before the restart; the first probe after it re-opens any alarm still breaching once its window elapses.
  • B and C need METRICS_TOKEN. While METRICS_TOKEN is unset (or /api/metrics answers 404/401, or does not answer), the watchdog logs watchdog_metrics_unavailable once per change and does not evaluate B or C. That is never an incident; the hard-down rules read /api/ready and Redis INFO and do not depend on it. watchdog_metrics_available is logged when the scrape recovers.

Email, to PLATFORM_ALERT_EMAILS (comma list, default BOOTSTRAP_ADMIN_EMAIL; an entry that is not an address is ignored, and with no recipient the watchdog logs watchdog_no_recipient once and keeps probing):

  • Open: when an alarm fires. Reminder: at most every 6 hours while it stays open. Resolved: once, when it clears; nothing is sent for an incident that cleared before its open mail was delivered.
  • Plain text plus simple HTML, Vietnamese. It carries the alarm name, the value against the threshold, since when (giờ Việt Nam), how long, and this runbook as the triage pointer. It never carries a token, an org id or an address. The copy is inline in apps/worker/src/watchdog/mail.ts: @yng/i18n is a tenant-UI catalogue, not an operator channel.
  • Providers, first success wins per recipient: Cloudflare Email Service (REST), then Resend. Cloudflare is skipped unless CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_EMAIL_API_TOKEN and a from address (PLATFORM_ALERT_FROM, else RESEND_FROM) are all set; Resend is skipped unless RESEND_API_KEY and RESEND_FROM are set. A 200 from Cloudflare that lists a recipient under permanent bounces or suppressed recipients counts as a failure for that recipient, who then goes to Resend. A 4xx other than 408/429 is permanent, 429/5xx/timeout transient; Cloudflare 403 code 10208 (recipient_plan_restricted) is permanent with its own token.
  • If every provider fails, the watchdog logs watchdog_email_failed with the mail kind, the alarm and the failure tokens (never an address) and retries the identical message on the next probe. A Resend retry reuses its Idempotency-Key (watchdog:<alarm>:<since>:<kind>:<recipient hash>; reminders carry a sequence number so a second reminder is not deduplicated). Cloudflare has no idempotency key, so a retry after a lost response can deliver twice. A mail that still has not reached every recipient after 30 attempts (about 30 minutes) is given up with watchdog_email_abandoned, so one address that never accepts cannot block that alarm's later mail.

Verify (production):

docker logs msocloud-watchdog-prod --tail 20          # watchdog_started: recipients, cloudflare, resend
docker inspect -f '{{.State.Health.Status}}' msocloud-watchdog-prod
docker exec msocloud-watchdog-prod node --import tsx/esm apps/worker/src/watchdog/main.ts --send-test

--send-test sends one email through the real providers and exits 0 only when every recipient was delivered (watchdog_test_sent).

Activate Cloudflare Email Service (Resend already delivers with the existing RESEND_* variables, so the watchdog mails without these steps):

  1. In the Cloudflare dashboard, Email Service > Email Sending, onboard a sending subdomain on msocloud.net and add the DNS records it lists.
  2. Create an API token with the permission "Email Sending Write" and copy the account id.
  3. On the Workers Free plan Cloudflare sends only to verified destination addresses; verify every address in PLATFORM_ALERT_EMAILS first (otherwise recipient_plan_restricted, and Resend carries the mail).
  4. Set CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_EMAIL_API_TOKEN and PLATFORM_ALERT_FROM (an address on the onboarded subdomain) in .env.prod, run the deploy, then --send-test.

Open gap: if the whole host is down, so is the watchdog; nothing on the host can report that. It needs a probe outside the host (an external uptime check on the public URL), which does not exist yet.

Companion signal, not a separate alarm

yng_worker_scheduled_org_outcomes_total{status="failed"} rising while yng_worker_jobs_total{queue="scheduled",status="completed"} also rises is the shape of a fan-out where the tick succeeds and the tenants do not. Every such failure also writes one sync_dead_letters row per org, which the existing unresolved-dead-letter alert already covers, and a later success for that org resolves it.

4. Redis ceiling: the headroom rule#

  • The rule is used_memory under 70% of maxmemory. Alarm A above enforces it.
  • The configured ceiling is 512mb. The redis container's memory limit is 2g, so there is physical room to raise it to 1536mb without touching anything else.
  • Raising the ceiling is an operator decision and is recorded here before it ships. A bigger ceiling on one shared instance postpones the cliff without splitting the workloads sharing it; the alternative is separating the cache/stream database from the queue database, which changes the failure mode rather than deferring it. No decision has been recorded yet, so the ceiling stays 512mb.
  • scripts/audit/redis-memory-budget.py (in audit:all) asserts the ceiling and the noeviction policy in both docker-compose.prod.yml and docker-compose.prod.yml.example, that this runbook names the configured ceiling, and that the metric families the alarms read still exist.

5. Configuration#

Variable Service Default Effect
METRICS_TOKEN web unset Unset: /api/metrics 404s and the web tier exposes nothing. Set: bearer required, on top of the compose-network origin check. Generate with openssl rand -hex 32.
WORKER_METRICS_PORT worker 9464 Private listener port. No host port is published.
EVENTBUS_STREAM_BUDGET_ENTRIES worker 250000 Global eventbus entry budget the gauge reports against. Raise only together with the Redis ceiling.
DB_POOL_MAX web, worker web 25, worker 20 (WORKER_DB_POOL_MAX) Pool ceiling the saturation alarm reads (the alarm is on the web pool).

Adding METRICS_TOKEN to .env.prod and restarting web and watchdog is the whole enablement step; B and C stay unevaluated until then. Both compose files already pass the variable through to both services.