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 / |
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 / |
web | compose network only (isInternal) |
Readiness. SELECT 1 on Postgres plus a Redis PING, each with a 2s deadline. 200 {"status":"ready"} or 503 {"status":"not_. |
GET / |
web | compose network and Authorization: Bearer $METRICS_ |
Prometheus text (version=0.). 404 when METRICS_ is unset or the request crossed the edge. |
GET /, /, / |
worker | private listener on WORKER_ (9464), no host port published |
Worker liveness, readiness (startup, Redis, Postgres, DB role, workers, outbox, metrics) and Prometheus text. |
Contract rules:
/api/healthnever learns about a dependency. Thewebcontainer carriesautoheal=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/readyis 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/metricscarries 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_ |
gauge | 1 while the process serves metrics. |
yng_ |
counter | Completed tRPC calls. outcome is ok or the tRPC error code (UNKNOWN for an error that is not a TRPCError). |
yng_ |
histogram | End-to-end call duration, rate-limit preflight and RLS transaction included. Buckets 10ms to 30s. |
yng_ |
gauge | DB_ in force (25 in production). |
PLATFORM_ |
watchdog | BOOTSTRAP_ |
WATCHDOG_ |
watchdog | 60000 |
WATCHDOG_ |
watchdog | 5000 |
yng_ |
gauge | RLS transactions holding a pooled connection right now. Every RLS-scoped resolver holds one for its whole lifetime. |
yng_ |
gauge | RLS transactions waiting for a connection. Above zero means the pool is exhausted. |
yng_ |
gauge | High-water mark since boot, so a burst between scrapes is not missed. |
yng_ |
counter | LLM tokens charged by the web process. A signal, not the budget: the refusal lives in @yng/ against ai_. |
yng_ |
counter | Billed LLM calls by the web process. |
yng_, ., . |
gauge | Process footprint. RSS that never returns between scrapes is the first sign of an unbounded frame pinned in a cache. |
yng_ |
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_ |
counter | event is hit, miss, evict or refused. evict is a drop to stay inside a bound, never an expiry. |
yng_ |
gauge | Entries currently retained. |
yng_ |
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_, yng_ |
gauge | Readiness overall and per dependency. |
yng_ |
counter | Jobs processed since boot. Queue-level: a scheduled tick counts as one completed however many tenants failed inside it. |
yng_ |
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_ |
gauge | Waiting / active / delayed / failed per BullMQ queue. |
yng_ |
gauge | Unresolved sync_ rows across all queues. |
yng_, . |
gauge | Committed job hand-offs not yet published to BullMQ. |
yng_ |
gauge | Redis used_, used_ and the configured maxmemory. |
yng_ |
counter | Keys Redis evicted. Must stay 0 under noeviction; nonzero means the policy was changed and BullMQ keys can now be discarded. |
yng_ |
gauge | Stream entries per topic, summed over every org partition. |
yng_ |
gauge | Entries across every topic and org. |
yng_ |
gauge | The global budget from packages/ (default 250,000 entries, about 250 MB at 1 KB per entry). |
yng_ |
gauge | 0 when the key scan hit its cap, i.e. the totals above are a lower bound. |
yng_, yng_, yng_, yng_ |
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.70for 10 minutes. - Also fire on
increase(yng_redis_evicted_keys_total[1h]) > 0— undernoevictionthis 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: atmaxmemoryevery write is refused at once, so ingest, AI generation and cache invalidation stop together. - Triage. Read
yng_eventbus_stream_entries_totalagainstyng_eventbus_stream_budget_entriesandyng_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 > 0for 5 minutes, oryng_web_db_pool_in_use / yng_web_db_pool_max > 0.80for 10 minutes. - Why.
DB_POOL_MAXis 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_secondsby 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. RaisingDB_POOL_MAXneeds Postgresmax_connectionsheadroom 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.02for 10 minutes. - Exclude expected refusals.
FORBIDDEN,UNAUTHORIZED,BAD_REQUEST,NOT_FOUNDandTOO_MANY_REQUESTSare the application working. OnlyINTERNAL_SERVER_ERRORandUNKNOWNare incidents. - Triage. The
procedurelabel points at the router; the structured request log (component: "trpc", one line per failing call withorgId,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_ increased within the last 1 h |
A |
| B. waiting | yng_ > 0 for 5 min |
B |
| B. utilisation | in_ > 0.80 for 10 min |
B |
| C. error rate | INTERNAL_ + UNKNOWN over all calls > 2 % across the last 5 min of scrapes, for 10 min |
C |
| hard-down: web / worker / Redis | web /, worker / 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 resolvesworker_down. - A
forwindow 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/metricsscrapes, not Prometheusrate(). 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
forwindow 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. WhileMETRICS_TOKENis unset (or/api/metricsanswers 404/401, or does not answer), the watchdog logswatchdog_metrics_unavailableonce per change and does not evaluate B or C. That is never an incident; the hard-down rules read/api/readyand RedisINFOand do not depend on it.watchdog_metrics_availableis 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/i18nis 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_TOKENand a from address (PLATFORM_ALERT_FROM, elseRESEND_FROM) are all set; Resend is skipped unlessRESEND_API_KEYandRESEND_FROMare 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; Cloudflare403code10208(recipient_plan_restricted) is permanent with its own token. - If every provider fails, the watchdog logs
watchdog_email_failedwith 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 itsIdempotency-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 withwatchdog_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):
- In the Cloudflare dashboard, Email Service > Email Sending, onboard a sending subdomain on
msocloud.netand add the DNS records it lists. - Create an API token with the permission "Email Sending Write" and copy the account id.
- On the Workers Free plan Cloudflare sends only to verified destination addresses; verify every address in
PLATFORM_ALERT_EMAILSfirst (otherwiserecipient_plan_restricted, and Resend carries the mail). - Set
CLOUDFLARE_ACCOUNT_ID,CLOUDFLARE_EMAIL_API_TOKENandPLATFORM_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_memoryunder 70% ofmaxmemory. Alarm A above enforces it. - The configured ceiling is 512mb. The
rediscontainer'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(inaudit:all) asserts the ceiling and thenoevictionpolicy in bothdocker-compose.prod.ymlanddocker-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_ |
web | unset | Unset: / 404s and the web tier exposes nothing. Set: bearer required, on top of the compose-network origin check. Generate with openssl rand -. |
WORKER_ |
worker | 9464 | Private listener port. No host port is published. |
EVENTBUS_ |
worker | 250000 | Global eventbus entry budget the gauge reports against. Raise only together with the Redis ceiling. |
DB_ |
web, worker | web 25, worker 20 (WORKER_) |
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.