@luanpdd/kit-mcp 1.8.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +97 -1
  3. package/gates/golden-signals-coverage.md +133 -0
  4. package/gates/obs-agents-mcp-supabase.md +86 -0
  5. package/gates/obs-skills-frontmatter.md +76 -0
  6. package/gates/omm-no-regression.md +83 -0
  7. package/gates/postmortem-template-required.md +127 -0
  8. package/gates/prr-checklist-coverage.md +128 -0
  9. package/gates/skill-must-include.md +21 -19
  10. package/kit/agents/burn-rate-forecaster.md +160 -0
  11. package/kit/agents/golden-signals-instrumenter.md +241 -0
  12. package/kit/agents/incident-investigator.md +245 -0
  13. package/kit/agents/observability-instrumenter.md +200 -0
  14. package/kit/agents/omm-auditor.md +251 -0
  15. package/kit/agents/postmortem-writer.md +282 -0
  16. package/kit/agents/prr-conductor.md +288 -0
  17. package/kit/agents/slo-engineer.md +224 -0
  18. package/kit/agents/supabase-architect.md +62 -0
  19. package/kit/agents/supabase-auth-bootstrapper.md +17 -0
  20. package/kit/agents/supabase-edge-fn-writer.md +124 -0
  21. package/kit/agents/supabase-migration-writer.md +98 -0
  22. package/kit/agents/supabase-realtime-implementer.md +23 -0
  23. package/kit/agents/supabase-rls-writer.md +17 -0
  24. package/kit/agents/supabase-storage-implementer.md +174 -0
  25. package/kit/agents/toil-auditor.md +277 -0
  26. package/kit/commands/auditar-marco.md +102 -1
  27. package/kit/commands/auditar-observabilidade.md +103 -0
  28. package/kit/commands/auditar-toil.md +129 -0
  29. package/kit/commands/burn-rate-status.md +140 -0
  30. package/kit/commands/concluir-marco.md +73 -1
  31. package/kit/commands/definir-slo.md +108 -0
  32. package/kit/commands/discutir-fase.md +26 -0
  33. package/kit/commands/forense.md +83 -1
  34. package/kit/commands/golden-signals.md +142 -0
  35. package/kit/commands/instrumentar-fase.md +200 -0
  36. package/kit/commands/investigar-producao.md +162 -0
  37. package/kit/commands/observabilidade.md +116 -0
  38. package/kit/commands/planejar-fase.md +20 -0
  39. package/kit/commands/postmortem.md +179 -0
  40. package/kit/commands/prr.md +205 -0
  41. package/kit/commands/risk-budget.md +220 -0
  42. package/kit/commands/sre.md +227 -0
  43. package/kit/commands/verificar-trabalho.md +26 -0
  44. package/kit/skills/_shared-observability/glossary.md +396 -0
  45. package/kit/skills/_shared-sre/glossary.md +573 -0
  46. package/kit/skills/blameless-postmortems/SKILL.md +340 -0
  47. package/kit/skills/burn-rate-alerting/SKILL.md +258 -0
  48. package/kit/skills/core-analysis-loop/SKILL.md +352 -0
  49. package/kit/skills/distributed-tracing/SKILL.md +362 -0
  50. package/kit/skills/eliminating-toil/SKILL.md +243 -0
  51. package/kit/skills/event-based-slos/SKILL.md +296 -0
  52. package/kit/skills/four-golden-signals/SKILL.md +297 -0
  53. package/kit/skills/observability-driven-development/SKILL.md +315 -0
  54. package/kit/skills/observability-maturity-model/SKILL.md +222 -0
  55. package/kit/skills/opentelemetry-standard/SKILL.md +351 -0
  56. package/kit/skills/production-readiness-review/SKILL.md +305 -0
  57. package/kit/skills/sre-risk-management/SKILL.md +221 -0
  58. package/kit/skills/structured-events/SKILL.md +265 -0
  59. package/kit/skills/telemetry-pipelines/SKILL.md +259 -0
  60. package/kit/skills/telemetry-sampling/SKILL.md +256 -0
  61. package/package.json +1 -1
@@ -0,0 +1,296 @@
1
+ ---
2
+ name: event-based-slos
3
+ description: Use ao definir SLO — SLI event-based (não time-based), sliding window 30d, decouple what/why. SLO-based alerts substituem thresholds brutos como CPU/memória.
4
+ ---
5
+
6
+ # Observabilidade — Event-Based SLOs
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao definir/avaliar SLOs ou substituir alertas threshold por SLO-based. Trigger phrases:
11
+
12
+ - "definir SLO", "criar SLI"
13
+ - "alertas confiáveis", "alert fatigue"
14
+ - "error budget", "sliding window"
15
+ - "como medir saúde do serviço"
16
+ - "decouple what from why"
17
+
18
+ ## Regras absolutas
19
+
20
+ - **SLI sempre event-based, nunca time-based** — "% de eventos com `result.success=true` em 30d" > "% de janelas de 5min com p99 < 300ms"
21
+ - **Sliding window 30d por default** — fixed window (calendário) gera comportamento perverso (cliente não esquece bug por causa de reset).
22
+ - **Target ≤ 99.95%** — para SLO 99.99%+ você não tem tempo de reagir antes do budget acabar; use métricas/dashboards informativos em vez de SLO.
23
+ - **Decouple "what" do "why"** — SLO alert diz que tem dor (sintoma); investigation descobre porquê (use [`core-analysis-loop`](../skills/core-analysis-loop/SKILL.md)). NUNCA misturar (anti-pattern: "alert se memória > 80% AND p99 > 300ms").
24
+ - **Customer-facing journey, não system metric** — SLI mede o que o cliente sente ("login funcionou em < 800ms"), não estado interno ("threads ativas").
25
+ - **Granular por endpoint/feature** — 1 SLO por jornada crítica do user. Não SLO global "site availability" — específico demais para ser ignorável.
26
+ - **Owner explícito** — cada SLO tem dono nomeado. Sem owner = sem ação = sem valor.
27
+ - **Substituir alertas threshold gradualmente** — após SLO comprovar valor (1+ incident detectado por SLO antes de threshold), DELETAR threshold antigo.
28
+
29
+ ## Risk continuum — SLO target é decisão explícita
30
+
31
+ > Cross-ref canônico: [sre-risk-management](../sre-risk-management/SKILL.md) (cap 3 do livro Google SRE — Embracing Risk).
32
+
33
+ SLO target NÃO é meta arbitrária ("queremos 99.99% porque soa bom"). É uma escolha consciente no **continuum risk × innovation**: cada nove adicional **multiplica custo** mas **divide benefício marginal** percebido pelo cliente.
34
+
35
+ | Target | Tolerância 30d | User-perceptible? | Quando faz sentido |
36
+ |---|---|---|---|
37
+ | 99% | 7.2 h | Sim, notável | Tier free, beta features, internal tools |
38
+ | 99.5% | 3.6 h | Notável em paths críticos | Tier free de produção |
39
+ | 99.9% | 43.2 min | Aceitável para maior parte de UX | Tier paid default |
40
+ | 99.95% | 21.6 min | Quase imperceptível | Tier enterprise / mission-critical |
41
+ | 99.99% | 4.3 min | Imperceptível em smartphone (~99% no canal do user) | Apenas se justificado por user perception (raro) |
42
+
43
+ **Sabedoria 99.99%** — cliente final acessa via smartphone (~99% disponibilidade) com ISP residencial (~99%). Serviço 99.99% **não é distinguível** de 99.999% nesse contexto: ambos parecem "sempre funcionando". Esforço além de 99.95% para serviço user-facing é tipicamente desperdício.
44
+
45
+ **Error budget é o instrumento contábil dessa decisão.** Para SLO 99.9% em 30d com 10M eventos: budget = `0.001 × 10M = 10k bad events`. Esse 10k é orçamento explícito para gastar em deploys arriscados, experimentos, refactors. Quando esgota, releases freezam até regenerar — não como punição, mas como **balanço explícito risk × innovation**.
46
+
47
+ **Diferentes tiers, diferentes targets** — `customer.tier='enterprise'` pode justificar 99.95%; `tier='free'` pode operar em 99.5%. Tratar todos como tier-1 desperdiça budget; tratar todos como tier-3 frustra clientes pagantes. A skill `sre-risk-management` documenta o framework completo de decisão.
48
+
49
+ > Em resumo: a regra `Target ≤ 99.95%` desta skill (acima) é **consequência** do risk continuum, não restrição arbitrária. Para 99.99%+ trate como métrica informativa (dashboard), NÃO como SLO acionável (alerts).
50
+
51
+ ## Patterns canônicos
52
+
53
+ ### Pattern: SLI event-based vs time-based
54
+
55
+ ```sql
56
+ -- PT-BR: BAD — SLI time-based (anti-pattern)
57
+ -- "99% das janelas de 5 min têm p99 < 300ms"
58
+ -- Problema: pre-aggregation perde fidelidade; janela com 1 outlier puxa p99.
59
+
60
+ -- PT-BR: GOOD — SLI event-based
61
+ -- "99.9% dos eventos individuais têm duration < 300ms e result_success = true"
62
+ select
63
+ count(*) filter (where duration_ms < 300 and result_success = true) as good,
64
+ count(*) as total,
65
+ count(*) filter (where duration_ms < 300 and result_success = true)::float / count(*) as compliance
66
+ from observability.events
67
+ where
68
+ event_name = 'http_request'
69
+ and endpoint = '/api/v1/orders'
70
+ and timestamp > now() - interval '30 days';
71
+ ```
72
+
73
+ ### Pattern: SLO definition canônico
74
+
75
+ ```yaml
76
+ # PT-BR: SLO documentado em formato YAML — alimenta agent slo-engineer
77
+ slo:
78
+ name: checkout_success
79
+ description: "Checkout completes successfully within 800ms (customer perception)"
80
+ owner: orders-team@company.com # PT-BR: dono nomeado
81
+
82
+ sli:
83
+ type: event_based # PT-BR: NUNCA time-based
84
+ event_filter:
85
+ service: orders-api
86
+ endpoint: /api/v1/checkout
87
+ http_method: POST
88
+ good_event: # PT-BR: predicate booleano
89
+ result_success: true
90
+ duration_ms: { lt: 800 }
91
+ bad_event: # PT-BR: complemento
92
+ operator: not_good # qualquer evento que não é "good"
93
+
94
+ target: 0.999 # PT-BR: 99.9% — não 99.99%+ por design
95
+ window: 30d_sliding # PT-BR: nunca fixed/calendar
96
+
97
+ alerts: # PT-BR: ver skill burn-rate-alerting
98
+ - name: page_short_term
99
+ lookahead: 4h
100
+ baseline: 1h
101
+ severity: page
102
+ - name: ticket_long_term
103
+ lookahead: 3d
104
+ baseline: 18h
105
+ severity: ticket
106
+ ```
107
+
108
+ ### Pattern: SLI materialized view (Postgres)
109
+
110
+ ```sql
111
+ -- PT-BR: view materializa SLI events para queries baratas
112
+ -- Refresh agendado (pg_cron) ou em tempo real (trigger)
113
+ create materialized view obs.sli_checkout_success as
114
+ select
115
+ date_trunc('minute', timestamp) as bucket,
116
+ count(*) filter (where result_success = true and duration_ms < 800) as good,
117
+ count(*) filter (where not (result_success = true and duration_ms < 800)) as bad,
118
+ count(*) as total
119
+ from observability.events
120
+ where
121
+ service = 'orders-api'
122
+ and endpoint = '/api/v1/checkout'
123
+ and http_method = 'POST'
124
+ and timestamp > now() - interval '35 days' -- 30d + buffer
125
+ group by 1
126
+ with no data;
127
+
128
+ -- PT-BR: índice para queries de burn rate
129
+ create index on obs.sli_checkout_success (bucket);
130
+
131
+ -- PT-BR: refresh schedule via pg_cron — a cada 30s
132
+ select cron.schedule(
133
+ 'refresh_sli_checkout_success',
134
+ '*/30 * * * * *',
135
+ $$ refresh materialized view concurrently obs.sli_checkout_success $$
136
+ );
137
+ ```
138
+
139
+ ### Pattern: SLO compliance query (atual e histórico)
140
+
141
+ ```sql
142
+ -- PT-BR: compliance atual — % good no último 30d
143
+ select
144
+ sum(good)::float / nullif(sum(total), 0) as compliance_30d,
145
+ 0.999 as target,
146
+ case
147
+ when sum(good)::float / nullif(sum(total), 0) >= 0.999 then 'IN_BUDGET'
148
+ else 'OUT_OF_BUDGET'
149
+ end as status
150
+ from obs.sli_checkout_success
151
+ where bucket > now() - interval '30 days';
152
+
153
+ -- PT-BR: error budget remaining
154
+ -- Budget = (1 - target) × total_events
155
+ -- Remaining = budget - bad_events_so_far
156
+ select
157
+ (1 - 0.999) * sum(total) as budget,
158
+ sum(bad) as burned,
159
+ (1 - 0.999) * sum(total) - sum(bad) as remaining,
160
+ 100.0 * (1 - sum(bad) / nullif((1 - 0.999) * sum(total), 0)) as remaining_pct
161
+ from obs.sli_checkout_success
162
+ where bucket > now() - interval '30 days';
163
+ ```
164
+
165
+ ### Pattern: SLO replacing thresholds (case study Honeycomb)
166
+
167
+ ```text
168
+ ANTES (cap 12 do livro):
169
+ - Alert: CPU > 80% (false positive: garbage collector)
170
+ - Alert: memory > 90% (false positive: cache warming)
171
+ - Alert: 5xx > 1% in 5min (false negative: 0.5% por 1h burns 60% do budget)
172
+ - Alert: p99 latency > 500ms in 5min (false positive: 1 spike isolado)
173
+
174
+ DEPOIS:
175
+ - 1 SLO: checkout_success em 30d sliding
176
+ - 1 alert preditivo: burn rate sustained 4h+
177
+ - 1 alert ticket: burn rate sustained 3d+
178
+
179
+ RESULTADO: 60% menos paginations, 100% dos incidents reais detectados.
180
+ ```
181
+
182
+ ### Pattern: customer-facing SLI dimensions
183
+
184
+ | Dimensão | Valor | Por quê SLI deve incluir |
185
+ |---|---|---|
186
+ | `endpoint` | `/api/v1/checkout` | Granular — não SLO global |
187
+ | `customer.tier` | `'enterprise'` | Diferentes targets por tier (Pro = 99.95% vs Free = 99.5%) |
188
+ | `region` | `us-east-1` | Identificar problema regional vs global |
189
+ | `feature_flag.<name>` | `true`/`false` | SLO durante rollout incremental |
190
+ | `tenant_id` | `'acme'` | Big customers podem ter SLOs próprios |
191
+
192
+ ## Anti-patterns
193
+
194
+ ### ANTI: SLO 99.99% ou 99.999%
195
+
196
+ ```text
197
+ ANTI: target 99.99% em SLO de 30d sliding
198
+ - 30d × 24h × 60min × (1-0.9999) = 4.3 minutos de tolerância
199
+ - Sem tempo para reagir antes do budget esgotar
200
+ - Burn rate alerts disparam após o budget acabar (zero-level)
201
+
202
+ CERTO: target ≤ 99.95% para SLO real
203
+ Para 99.99%+, use métricas/dashboards informativos (não alerta)
204
+ ```
205
+
206
+ ### ANTI: SLO global "site up"
207
+
208
+ ```text
209
+ ANTI: 1 SLO "site availability" para tudo
210
+ - Falha em /api/v1/admin não conta para 99% dos clientes
211
+ - Falha em /api/v1/checkout = catastrófico
212
+ - Misturar = alarmes confusos, ações vagas
213
+
214
+ CERTO: 1 SLO por jornada crítica do user
215
+ - checkout_success: 99.9%
216
+ - login_success: 99.95%
217
+ - search_p95_latency: 99% < 200ms
218
+ - admin_panel: SEM SLO (uso baixo, latência aceitável)
219
+ ```
220
+
221
+ ### ANTI: SLO sem owner
222
+
223
+ ```text
224
+ ANTI: SLO definido em retrospectiva, sem dono nomeado
225
+ - Burn alert dispara → ninguém atende → escalation
226
+ - Sem follow-up no fim do mês
227
+
228
+ CERTO: SLO tem owner em arquivo (yaml ou tabela DB)
229
+ owner = team email ou pessoa específica
230
+ Burn alert roteia direto para owner antes de escalation
231
+ ```
232
+
233
+ ### ANTI: SLO == SLA externo
234
+
235
+ ```text
236
+ ANTI: usar SLA do contrato (99.9% uptime) como SLO interno
237
+
238
+ PROBLEMA: 0 margem de segurança. Atinge SLA mínimo no fio = 1 incident e quebra.
239
+
240
+ CERTO: SLO interno mais rígido que SLA externo
241
+ SLA externo: 99.9% (compromisso com cliente)
242
+ SLO interno: 99.95% (margem de 5× para reagir)
243
+ ```
244
+
245
+ ### ANTI: alterar SLI quando burn ocorre
246
+
247
+ ```text
248
+ ANTI: SLO está queimando → "vamos relaxar SLI para reduzir false positives"
249
+ (definir bad_event mais frouxo)
250
+
251
+ PROBLEMA: você está mascarando dor real. Próximo incident similar passa silencioso.
252
+
253
+ CERTO: SLI é compromisso com customer experience. Se está queimando, fixar
254
+ o problema (root cause via core-analysis-loop), não o SLI.
255
+ Se SLI sistematicamente errado (mede coisa errada): substituir, não relaxar.
256
+ ```
257
+
258
+ ### ANTI: fixed window (mensal/calendário)
259
+
260
+ ```text
261
+ ANTI: error budget reseta dia 1 do mês
262
+
263
+ PROBLEMA:
264
+ - "Tivemos outage dia 31, reseta amanhã" — cliente NÃO esquece
265
+ - Pressão para postergar fixes para "depois do reset"
266
+ - Behavioral hazard: deploy arriscado dia 30
267
+
268
+ CERTO: sliding window 30d
269
+ Outage dia 31 fica no budget até dia 30 do mês seguinte (sai gradualmente)
270
+ Sem incentivo perverso, comportamento humano realista
271
+ ```
272
+
273
+ ## Verificação
274
+
275
+ Antes de marcar SLO como produção-pronto:
276
+
277
+ 1. **Owner nomeado** — email/team em `slo.owner`
278
+ 2. **SLI event-based** — pred boolean, não time-bucket
279
+ 3. **Target ≤ 99.95%** — > 99.95% sinaliza informativo, não SLO
280
+ 4. **Window 30d sliding** — não fixed
281
+ 5. **Customer-facing journey** — SLI mede o que o cliente sente
282
+ 6. **Materialized view** existe e é refreshable (pg_cron)
283
+ 7. **Burn alerts** configurados (ver skill `burn-rate-alerting`)
284
+ 8. **Quero SLO ou metric?** — se a resposta é "informativo", crie metric, não SLO
285
+
286
+ ---
287
+
288
+ ## Ver também
289
+
290
+ - `kit/skills/_shared-observability/glossary.md` — termos canônicos SLI/SLO/error budget
291
+ - `kit/skills/structured-events/SKILL.md` — eventos canônicos para alimentar SLI
292
+ - `kit/skills/burn-rate-alerting/SKILL.md` — lookahead/baseline windows
293
+ - `kit/skills/core-analysis-loop/SKILL.md` — investigar quando SLO queima
294
+ - `kit/agents/slo-engineer.md` — gera SLO.md + SQL para materializar SLI
295
+
296
+ *Material-fonte: Observability Engineering (O'Reilly, 2022) — Cap 12: "Using Service-Level Objectives for Reliability".*
@@ -0,0 +1,297 @@
1
+ ---
2
+ name: four-golden-signals
3
+ description: Use ao instrumentar serviço user-facing — Latency + Traffic + Errors + Saturation, percentis (não mean), histogram exponencial, latência success vs error separadas.
4
+ ---
5
+
6
+ # SRE — Four Golden Signals
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao instrumentar Edge Function/serviço/microservice user-facing. Trigger phrases:
11
+
12
+ - "golden signals", "4 sinais dourados"
13
+ - "latency, traffic, errors, saturation"
14
+ - "instrumentar serviço", "métricas mínimas"
15
+ - "p99 latency", "percentis vs mean"
16
+ - "black-box vs white-box monitoring"
17
+ - "Google SRE cap 6"
18
+ - "Latency success vs error"
19
+
20
+ ## Regras absolutas
21
+
22
+ - **4 sinais são universais para serviço user-facing** — Latency + Traffic + Errors + Saturation. Se mede esses 4, captura ~95% da saúde operacional. Outros sinais (CPU, memória, disco I/O) são **causas potenciais**, não sintomas — vão em white-box monitoring secundário.
23
+ - **Latency success vs error sempre separadas** — falhas rápidas (HTTP 500 em 5ms) mascaram latência ruim de successes se misturadas. Sempre `histogram(duration_ms, {result: 'success'})` e `histogram(duration_ms, {result: 'error'})` em séries distintas.
24
+ - **NUNCA mean para latency** — long tail invisível: mean=50ms mas p99=5000ms é UX ruim para 1% dos usuários (tipicamente os mais valiosos: enterprise tier). SEMPRE histogram com percentis.
25
+ - **Histogram com bucketing exponencial** — buckets `[1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000]` ms ou base 1.5/2. Captura long tail sem cardinality explosion.
26
+ - **Errors counter por error.type (não message)** — `error.type` enumerado (5-15 valores: `timeout`, `validation`, `auth`, `rate_limit`, `db`, `provider_down`, ...). `error.message` é alta cardinalidade — não usar como dimension.
27
+ - **Saturation é resource-specific** — não existe métrica genérica de saturação. Para HTTP service: connection pool used %. Para DB: tablespace used %. Para queue: queue depth. Para CPU-bound: load average. Identificar O recurso mais escasso ANTES de instrumentar.
28
+ - **Black-box monitora UX, white-box monitora internals** — black-box (synthetic prober HTTP) detecta "site offline" mesmo se métricas internas estão verdes (corner case clássico). White-box (golden signals) explica "porquê" quando black-box dispara.
29
+ - **Reportar p50, p95, p99, p99.9 — não só p99** — p50 (mediana) é UX típica; p95 é primeiro deslize; p99 é cauda; p99.9 é seu 1 em 1000 que é seu cliente enterprise. Cada percentil conta uma história diferente.
30
+
31
+ ## Patterns canônicos
32
+
33
+ ### Pattern: definição canônica dos 4 signals (tabela)
34
+
35
+ | Signal | Definição | Tipo de instrument | Granularity recomendada |
36
+ |---|---|---|---|
37
+ | **Latency** | Tempo de request bem-sucedido vs falho — SEPARADO | Histogram (ms) com bucketing exponencial | Por endpoint × `result` (success/error) |
38
+ | **Traffic** | Volume de demanda — requests/s, msgs/s, bytes/s | Counter | Por endpoint × method |
39
+ | **Errors** | Taxa de requests que falharam (explícitas: 5xx; implícitas: 200 com payload errado; políticas: > SLO target) | Counter | Por endpoint × `error.type` |
40
+ | **Saturation** | "Quão cheio" o serviço está — % do recurso mais escasso | ObservableGauge (%) | Por resource (connection pool, queue, CPU) |
41
+
42
+ ### Pattern: instrumentação canônica em OTel SDK (TypeScript/Deno)
43
+
44
+ ```ts
45
+ // PT-BR: 4 golden signals em Edge Function — copiar este shape
46
+ import { trace, metrics } from '@opentelemetry/api'
47
+
48
+ const tracer = trace.getTracer('orders-service')
49
+ const meter = metrics.getMeter('orders-service')
50
+
51
+ // PT-BR: 1. LATENCY — histogram bucketed exponencial
52
+ const latencyHistogram = meter.createHistogram('http_request_duration_ms', {
53
+ description: 'Request latency in ms — split by result',
54
+ unit: 'ms',
55
+ advice: { explicitBucketBoundaries: [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000] }
56
+ })
57
+
58
+ // PT-BR: 2. TRAFFIC — counter de requests recebidos
59
+ const trafficCounter = meter.createCounter('http_requests_total', {
60
+ description: 'Total HTTP requests received'
61
+ })
62
+
63
+ // PT-BR: 3. ERRORS — counter por error.type (categoria, não message)
64
+ const errorsCounter = meter.createCounter('http_errors_total', {
65
+ description: 'Total HTTP errors by error.type'
66
+ })
67
+
68
+ // PT-BR: 4. SATURATION — gauge do recurso mais escasso
69
+ const saturationGauge = meter.createObservableGauge('db_connection_pool_used_pct', {
70
+ description: 'DB connection pool utilization %',
71
+ unit: '%'
72
+ })
73
+ saturationGauge.addCallback((result) => {
74
+ // PT-BR: callback executado em scrape — lê estado atual do pool
75
+ result.observe(getConnectionPoolUsedPct(), { resource: 'db_pool', service: 'orders' })
76
+ })
77
+
78
+ export async function placeOrder(req: Request) {
79
+ const startMs = performance.now()
80
+ const dims = { endpoint: '/api/v1/orders', method: 'POST' }
81
+
82
+ // PT-BR: 2. Traffic — incrementar antes de processar
83
+ trafficCounter.add(1, dims)
84
+
85
+ return tracer.startActiveSpan('place_order', async (span) => {
86
+ try {
87
+ const order = await db.insertOrder(req.body)
88
+ // PT-BR: 1. Latency success — só após success confirmar
89
+ const durationMs = performance.now() - startMs
90
+ latencyHistogram.record(durationMs, { ...dims, result: 'success' })
91
+ return order
92
+ } catch (e) {
93
+ // PT-BR: 1. Latency error — separada da success
94
+ const durationMs = performance.now() - startMs
95
+ latencyHistogram.record(durationMs, { ...dims, result: 'error' })
96
+ // PT-BR: 3. Errors — counter por error.type (enum baixa cardinalidade)
97
+ errorsCounter.add(1, { ...dims, error_type: classify(e) })
98
+ throw e
99
+ } finally {
100
+ span.end()
101
+ }
102
+ })
103
+ }
104
+
105
+ // PT-BR: classifier — enum estável de 5-15 valores
106
+ function classify(e: unknown): string {
107
+ if (e instanceof TimeoutError) return 'timeout'
108
+ if (e instanceof ValidationError) return 'validation'
109
+ if (e instanceof AuthError) return 'auth'
110
+ if (e instanceof RateLimitError) return 'rate_limit'
111
+ if (e instanceof DbError) return 'db'
112
+ return 'unknown'
113
+ }
114
+ ```
115
+
116
+ ### Pattern: queries SQL para 4 signals em 1 dashboard
117
+
118
+ ```sql
119
+ -- PT-BR: dashboard único — 4 golden signals últimos 60 minutos, por minuto
120
+ select
121
+ date_trunc('minute', timestamp) as minute,
122
+ -- Traffic
123
+ count(*) as traffic_rpm,
124
+ -- Errors (por error.type)
125
+ count(*) filter (where result_success = false) as errors_total,
126
+ count(*) filter (where error_type = 'timeout') as errors_timeout,
127
+ count(*) filter (where error_type = 'rate_limit') as errors_rate_limit,
128
+ count(*) filter (where error_type = 'db') as errors_db,
129
+ -- Latency p50/p95/p99 — APENAS success
130
+ percentile_cont(0.50) within group (order by duration_ms)
131
+ filter (where result_success = true) as latency_p50_success,
132
+ percentile_cont(0.95) within group (order by duration_ms)
133
+ filter (where result_success = true) as latency_p95_success,
134
+ percentile_cont(0.99) within group (order by duration_ms)
135
+ filter (where result_success = true) as latency_p99_success,
136
+ -- Latency p99 — APENAS error (visibilidade de error path lentidão)
137
+ percentile_cont(0.99) within group (order by duration_ms)
138
+ filter (where result_success = false) as latency_p99_error,
139
+ -- Saturation (gauge max no minuto)
140
+ max(connection_pool_used_pct) as saturation_pool_max
141
+ from observability.events
142
+ where service = 'orders-api' and timestamp > now() - interval '60 minutes'
143
+ group by minute
144
+ order by minute desc;
145
+ ```
146
+
147
+ ### Pattern: black-box probe complementar (synthetic check)
148
+
149
+ ```ts
150
+ // PT-BR: black-box monitoring — chamar serviço como cliente externo
151
+ // Roda em CI ou serviço external (uptimerobot, datadog synthetics)
152
+ async function blackBoxProbe(): Promise<{ ok: boolean; durationMs: number }> {
153
+ const startMs = Date.now()
154
+ const r = await fetch('https://api.example.com/api/v1/orders/probe', {
155
+ method: 'POST',
156
+ body: JSON.stringify({ probe: true, sku: 'TEST-001' }),
157
+ headers: { 'X-Probe': 'true' }
158
+ })
159
+ const durationMs = Date.now() - startMs
160
+ // PT-BR: validar resposta — não basta status 200
161
+ const body = await r.json()
162
+ const ok = r.status === 200 && body.order_id != null && durationMs < 1000
163
+ return { ok, durationMs }
164
+ }
165
+
166
+ // PT-BR: rodar a cada 30s; alerta se 3 consecutivos falham (debounce contra flake)
167
+ ```
168
+
169
+ ### Pattern: saturation por tipo de serviço
170
+
171
+ | Tipo de serviço | Recurso mais escasso | Métrica de saturation |
172
+ |---|---|---|
173
+ | HTTP API stateless | Connection pool DB | `db_connection_pool_used_pct` |
174
+ | API com cache | Memory do cache | `cache_memory_used_pct` |
175
+ | Worker async | Queue depth | `queue_depth_messages` |
176
+ | Edge Function | Concurrency limit Deno | `concurrent_executions_pct` |
177
+ | DB | Tablespace ou WAL | `disk_used_pct`, `wal_lag_bytes` |
178
+ | CPU-bound (encoder, ML) | Load average | `cpu_load_avg_5min` |
179
+ | Network egress | Bandwidth | `egress_bytes_per_sec_pct` |
180
+
181
+ ## Anti-patterns
182
+
183
+ ### ANTI: mean latency
184
+
185
+ ```text
186
+ ANTI: alerta/dashboard com avg(duration_ms) — long tail invisível.
187
+
188
+ PROBLEMA: mean=50ms mas p99=5000ms = UX ruim invisível; cliente enterprise
189
+ (no p99) sofre sem nunca disparar alerta. Mean é puxado para baixo
190
+ por mass de requests rápidos; sinaliza "tudo ok" enquanto 1% dos
191
+ users espera 5s.
192
+
193
+ CERTO: histogram com percentile_cont(0.99); alertar em p99 > target.
194
+ Reportar p50/p95/p99/p99.9 para ver formato da distribuição.
195
+ ```
196
+
197
+ ### ANTI: latência success+error misturadas
198
+
199
+ ```text
200
+ ANTI: histogram(duration_ms) sem dimension result.
201
+
202
+ PROBLEMA: falhas rápidas (HTTP 500 em 5ms quando timeout dispara cedo)
203
+ puxam mean/percentis para baixo; mascaram lentidão real de
204
+ requests bem-sucedidos. Dashboard mostra "p99=80ms" mas
205
+ successes reais são 800ms.
206
+
207
+ CERTO: dimension {result: 'success'} vs {result: 'error'} SEMPRE separadas
208
+ em séries distintas. SLI/SLO computado APENAS sobre success path.
209
+ ```
210
+
211
+ ### ANTI: Errors com error.message como dimension
212
+
213
+ ```text
214
+ ANTI: errorsCounter.add(1, { error_message: e.message })
215
+
216
+ PROBLEMA: cada mensagem única é uma série temporal; cardinality explosion
217
+ (1M+ séries em horas se message contém timestamps/IDs/random);
218
+ time-series DB OOMs ou throttles; queries lentas/impossíveis;
219
+ custo de armazenamento explode.
220
+
221
+ CERTO: enum error.type com 5-15 valores fixos (timeout, validation, auth,
222
+ rate_limit, db, provider_down, unknown); error.message em
223
+ log/span attribute (não métrica) para debug pontual.
224
+ ```
225
+
226
+ ### ANTI: monitoring causes não symptoms
227
+
228
+ ```text
229
+ ANTI: alertar em "CPU > 80% / memory < 10% / threads > N"
230
+
231
+ PROBLEMA: mistura "what" (sintoma user-facing) com "why" (causa interna);
232
+ falsos positivos (cron job legítimo dispara CPU);
233
+ falsos negativos (sistema lento sem CPU alta — saturação em
234
+ connection pool ou rede); on-call paginado por nada e
235
+ incidents reais passam silenciosos.
236
+
237
+ CERTO: alertar em SLO burn rate sobre os 4 signals (event-based,
238
+ customer-impacting); usar CPU/memory como debug context em
239
+ white-box monitoring, não como alert source.
240
+ ```
241
+
242
+ ### ANTI: saturation genérica
243
+
244
+ ```text
245
+ ANTI: copiar pattern de saturation de outro serviço sem identificar o
246
+ gargalo real.
247
+
248
+ PROBLEMA: mede CPU em serviço onde gargalo é connection pool; mede memory
249
+ em serviço CPU-bound; saturation alerta nunca dispara antes do
250
+ incident; quando incident acontece, dashboard mostra "saturação
251
+ OK" e ninguém sabe explicar por quê.
252
+
253
+ CERTO: identificar EXPLICITAMENTE o recurso mais escasso (DB pool? queue
254
+ depth? Deno concurrency? tablespace?) ANTES de instrumentar (ver
255
+ Pattern: saturation por tipo de serviço). Cada serviço tem 1 ou 2
256
+ gargalos reais — instrumentar esses, não copiar template.
257
+ ```
258
+
259
+ ### ANTI: black-box only (sem white-box)
260
+
261
+ ```text
262
+ ANTI: só prober externo (synthetic check), sem instrumentação interna.
263
+
264
+ PROBLEMA: sabe que "site offline" mas não sabe porquê; debug requer SSH
265
+ em prod / log dive sem instrumentation; MTTR cresce horas;
266
+ incidents repetem porque root cause nunca foi capturada.
267
+
268
+ CERTO: black-box detecta UX impact (cliente real não consegue) + white-box
269
+ (4 signals) explica root cause. Os dois juntos: black-box dispara,
270
+ white-box mostra qual signal degradou (latency? errors? saturation?)
271
+ e em qual endpoint.
272
+ ```
273
+
274
+ ## Verificação
275
+
276
+ Antes de marcar instrumentação como production-ready, validar:
277
+
278
+ 1. **Os 4 signals presentes** — Latency (histogram), Traffic (counter), Errors (counter por error.type), Saturation (gauge resource-specific)
279
+ 2. **Latency separada** — `result: 'success'` e `result: 'error'` em séries distintas
280
+ 3. **Histogram com bucketing exponencial** — não fixed buckets lineares
281
+ 4. **error.type é enum (5-15 valores)** — não `error.message` como dimension
282
+ 5. **Saturation tem o recurso certo identificado** — connection pool? queue depth? concurrency? CPU load?
283
+ 6. **Black-box probe complementar** — synthetic check do happy path principal a cada 30s
284
+ 7. **Dashboard de 4 signals** existe e é o **primeiro** lugar de debug em incident
285
+
286
+ ## Ver também
287
+
288
+ - [`_shared-sre/glossary.md`](../_shared-sre/glossary.md) — termos canônicos golden signals, black-box, white-box, percentile
289
+ - [`opentelemetry-standard`](../opentelemetry-standard/SKILL.md) (v1.9) — OTel SDK base, exporter, OTLP
290
+ - [`structured-events`](../structured-events/SKILL.md) (v1.9) — wide events que alimentam SLI de Errors
291
+ - [`event-based-slos`](../event-based-slos/SKILL.md) (v1.9) — SLO sobre Errors+Latency forma SLI canônico
292
+ - [`burn-rate-alerting`](../burn-rate-alerting/SKILL.md) (v1.9) — alertar em SLO burn-rate, não em CPU
293
+ - [`production-readiness-review`](../production-readiness-review/SKILL.md) — PRR axis "Instrumentation" exige 4 signals
294
+
295
+ ---
296
+
297
+ *Material-fonte: Site Reliability Engineering — Beyer, Jones, Petoff, Murphy (Google/O'Reilly, 2016) — Cap 6: "Monitoring Distributed Systems" (Four Golden Signals).*