feat(metrics): module counters for rate limits, cache, IdP, M-Pesa, check-ins and DB errors (#60) #170

Merged
amiryahaya merged 3 commits from feat/api-counters-60 into main 2026-11-06 12:18:22 +01:00
Owner

Step 2b of #60 (docs/05-observability.md): counters inside the API and worker, so the dashboards can show where a slowdown or a money problem is.

What is counted (only when KWS_METRICS_ADDR is set)

Metric Where Labels
kws_rate_limited_total API class: every 429 the limiter writes (not the auth_fail 429, which auth writes)
kws_cache_requests_total, kws_cache_version_poll_failures_total API result = hit / miss
kws_auth_idp_unavailable_total API none: every 503 because the IdP could not be reached
kws_mpesa_callback_total API outcome: settled, replay, refund_due, no_payment, no_attempt, unverified, invalid, too_large, error
kws_mpesa_push_total worker outcome: accepted, rejected, maybe_sent, not_sent
kws_checkin_total API action, result (ok or the fixed refusal code)
kws_db_errors_total API and worker kind: timeout, lock_wait, deadlock, serialization

How it is built

  • Modules never import Prometheus. Each takes an optional plain callback, and nil counts nothing:
    • Limiter.OnDenied
    • Cache.Observe
    • auth.WithUnavailableHook
    • CallbackHandler.OnOutcome
    • checkin.Handler.OnScan
    • StkHandler's count
  • metrics hands out each callback, or nil when metrics are off. The fixed label values start at 0, so an alert on > 0 has a series to watch.
  • Database errors are counted by a pgx QueryTracer and BatchTracer, set through postgres.Config.Tracer. That means every query is seen once, and so is every failed batch (the seat locks and checkout run as batches).
    • A cancelled request also gets 57014 from the server. It is not counted as a timeout.
    • Constraint errors such as 23505 are not counted, because idempotency relies on them.
  • NewAPIHandler, registerJobs and mpesa.StkHandler each take one more argument; tests pass nil.
  • The labels contain no ids. The app-level test fails if a uuid reaches the output.

Also fixed

TestABrokenSnapshotKeepsTheLastGoodValuesAndIsCounted (from PR 165) failed about 2 times in 15. Prometheus collects metrics in parallel, so the snapshot error counter could be read before the failure in the same scrape was counted. The business collector now emits the counter itself, after it reads. It passed 30 of 30 under -race.

Deviations from doc 05 (in ADR 0036)

  • Renamed:
    • kws_db_errors_total, with no conn kind (pool waits are already in kws_db_pool_*)
    • kws_auth_idp_unavailable_total
    • the push outcome not_sent
  • Not built yet: the M-Pesa push-to-callback histogram, the cache bypass result, and the doc 05 §4.2 sales, payments and email counters.
  • Gate-scan results are not preset at 0; each one appears on its first scan.

Checks

  • make cover: 91.5 % total (minimum 80 %). Touched packages:
    • metrics 97.7 %
    • cache 100 %
    • ratelimit 100 %
    • checkin 97.0 %
    • auth 96.4 %
    • payments/mpesa 91.7 %
  • make lint: 0 issues. The touched packages pass under -race.
  • Dual-pass review:
    • ponytail-review: no must-fix items.
    • Correctness review: found the batch tracer gap, which is now fixed and tested.
    • The fix diff was re-checked.

Not done: alert rules, dashboards and the monitoring Compose files (steps 3 to 6 of doc 05).

🤖 Generated with Claude Code

Step 2b of #60 (docs/05-observability.md): counters inside the API and worker, so the dashboards can show where a slowdown or a money problem is. ## What is counted (only when `KWS_METRICS_ADDR` is set) | Metric | Where | Labels | |---|---|---| | `kws_rate_limited_total` | API | `class`: every 429 the limiter writes (not the `auth_fail` 429, which `auth` writes) | | `kws_cache_requests_total`, `kws_cache_version_poll_failures_total` | API | `result` = `hit` / `miss` | | `kws_auth_idp_unavailable_total` | API | none: every 503 because the IdP could not be reached | | `kws_mpesa_callback_total` | API | `outcome`: `settled`, `replay`, `refund_due`, `no_payment`, `no_attempt`, `unverified`, `invalid`, `too_large`, `error` | | `kws_mpesa_push_total` | worker | `outcome`: `accepted`, `rejected`, `maybe_sent`, `not_sent` | | `kws_checkin_total` | API | `action`, `result` (`ok` or the fixed refusal code) | | `kws_db_errors_total` | API and worker | `kind`: `timeout`, `lock_wait`, `deadlock`, `serialization` | ## How it is built - Modules never import Prometheus. Each takes an optional plain callback, and nil counts nothing: - `Limiter.OnDenied` - `Cache.Observe` - `auth.WithUnavailableHook` - `CallbackHandler.OnOutcome` - `checkin.Handler.OnScan` - `StkHandler`'s `count` - `metrics` hands out each callback, or nil when metrics are off. The fixed label values start at 0, so an alert on `> 0` has a series to watch. - Database errors are counted by a pgx `QueryTracer` and `BatchTracer`, set through `postgres.Config.Tracer`. That means every query is seen once, and so is every failed batch (the seat locks and checkout run as batches). - A cancelled request also gets 57014 from the server. It is not counted as a timeout. - Constraint errors such as 23505 are not counted, because idempotency relies on them. - `NewAPIHandler`, `registerJobs` and `mpesa.StkHandler` each take one more argument; tests pass nil. - The labels contain no ids. The app-level test fails if a uuid reaches the output. ## Also fixed `TestABrokenSnapshotKeepsTheLastGoodValuesAndIsCounted` (from PR 165) failed about 2 times in 15. Prometheus collects metrics in parallel, so the snapshot error counter could be read before the failure in the same scrape was counted. The business collector now emits the counter itself, after it reads. It passed 30 of 30 under `-race`. ## Deviations from doc 05 (in ADR 0036) - Renamed: - `kws_db_errors_total`, with no `conn` kind (pool waits are already in `kws_db_pool_*`) - `kws_auth_idp_unavailable_total` - the push outcome `not_sent` - Not built yet: the M-Pesa push-to-callback histogram, the cache `bypass` result, and the doc 05 §4.2 sales, payments and email counters. - Gate-scan results are not preset at 0; each one appears on its first scan. ## Checks - `make cover`: **91.5 %** total (minimum 80 %). Touched packages: - metrics 97.7 % - cache 100 % - ratelimit 100 % - checkin 97.0 % - auth 96.4 % - payments/mpesa 91.7 % - `make lint`: 0 issues. The touched packages pass under `-race`. - Dual-pass review: - ponytail-review: no must-fix items. - Correctness review: found the batch tracer gap, which is now fixed and tested. - The fix diff was re-checked. Not done: alert rules, dashboards and the monitoring Compose files (steps 3 to 6 of doc 05). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Step 2b of docs/05-observability.md. Modules take optional plain callbacks (nil counts nothing) and the
metrics package hands them out with their fixed label values preset at 0; DB errors are counted by the
pool's pgx query tracer in both the API and the worker. ADR 0036 lists the names and the deviations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fix(metrics): count batch lock waits, deterministic snapshot error count, review fixes (#60)
Some checks failed
ci / changes (pull_request) Successful in 29s
ci / clients (pull_request) Has been skipped
ci / web-ticket (pull_request) Has been skipped
ci / web-admin (pull_request) Has been skipped
ci / web-partner (pull_request) Has been skipped
ci / mobile-ticket (pull_request) Has been skipped
ci / api (pull_request) Failing after 16m29s
ci / ci-gate (pull_request) Failing after 3s
d7319e53ee
Seat locks and checkout run as pgx batches, which report to a BatchTracer: count a failed batch once at
its end. The worker's snapshot error counter is now emitted by the business collector after its read, so
a failure is in the same scrape (the existing test was flaky with collectors running in parallel). A
code error without a code reports "error"; the callback test hook is safe for parallel callbacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test(metrics): freeze the limiter clock in the wiring test (#60)
All checks were successful
ci / changes (pull_request) Successful in 15s
ci / clients (pull_request) Has been skipped
ci / web-ticket (pull_request) Has been skipped
ci / web-admin (pull_request) Has been skipped
ci / web-partner (pull_request) Has been skipped
ci / mobile-ticket (pull_request) Has been skipped
ci / api (pull_request) Successful in 14m50s
ci / ci-gate (pull_request) Successful in 4s
5cda25a836
On a slow runner the real clock refilled the default bucket before the burst was spent, so no 429 came.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
primatekuntech/kws!170
No description provided.