МАТЧАСТЬ / MONITORING · SLO · SLA · INCIDENTS / DOCUMENT 42 / 02.09.2026
Monitoring / SLA / Incidents
Как сделать так, чтобы «Матчасть» сама понимала, что у неё сломалось, сама выполняла безопасную первичную диагностику и восстановление, а человек подключался только к действительно значимым исключениям. Документ описывает белый и чёрный мониторинг, Prometheus/Grafana/Loki/OpenTelemetry, внешние synthetic probes, бизнес-метрики, очереди, AI/provider health, Publication Health, SLO/error budget, alert routing, automated remediation, incident states, status page, postmortem, capacity planning и критерии перехода от одного сервера к HA.
Detect before clientсервис должен узнать о проблеме раньше первого сообщения в поддержку
Auto-remediate routineрестарт worker, retry, pause provider и queue recovery не требуют человека
Page only on novel riskесли ответ на alert всегда одинаковый, этот ответ надо автоматизировать
SLO ≠ SLAвнутренние reliability targets запускаются раньше любых договорных гарантий
1. Главное решение
Мониторинг «Матчасти» строится по принципу automation-first operations. Система непрерывно наблюдает user-visible availability, внутренние зависимости, очереди, данные, публикационный pipeline, Search/AI connectors и backups. Routine failures автоматически диагностируются и исправляются в заранее ограниченных сценариях. Человеку отправляется alert только когда событие materially affects users/data, не может быть безопасно исправлено автоматически или требует нового решения.
OBSERVE
↓
CLASSIFY
↓
CAN AUTO-REMEDIATE?
YES
→ execute bounded runbook
→ verify recovery
→ incident log
→ no human unless repeat/failure
NO
→ create incident
→ notify according severity
→ human exception.
2. Google SRE principle, который идеально подходит «Матчасти»
Google SRE прямо формулирует: если ответ на page является роботизированным и не требует интеллекта, он не должен быть page — такой ответ следует автоматизировать. Monitoring должен иметь высокий signal/noise и прежде всего ловить реальные пользовательские симптомы.
Это особенно важно для проекта, где мы сознательно хотим убрать почти весь ручной operational toil.
3. Что мониторить первым
USER:
Can open site?
Can read article?
Can login?
Can create/use workspace?
Can pay?
Can publish?
Can open report?
SYSTEM:
DB healthy?
disk filling?
queue stuck?
worker alive?
provider down?
backup current?
PRODUCT:
publication stuck?
measurement late?
AI run coverage broken?
client report missing?
credits inconsistent?
4. White-box + black-box
Google SRE distinguishes white-box monitoring of service internals and black-box monitoring of externally visible behavior. Для «Матчасти» нужны оба.
WHITE BOX:
CPU
RAM
DB
queue
application errors
worker state
provider latency
BLACK BOX:
https://mathchast.com
article renders
login path
public search
status endpoint
DNS/TLS
correct expected content.
5. Почему одного внутреннего Prometheus недостаточно
Если сам сервер полностью умер, monitoring stack на этом же сервере тоже умер и никому об этом не сообщил.
6. Поэтому две независимые точки наблюдения
INTERNAL OBSERVABILITY
Prometheus/Grafana/Loki
on Mathchast infra
PLUS
EXTERNAL SYNTHETIC
separate provider/network
checks:
DNS
TLS
HTTP
content correctness.
7. External synthetic вариантов несколько
Prometheus Blackbox Exporter умеет HTTP/HTTPS, DNS, TCP, ICMP and gRPC probes. Grafana Synthetic Monitoring также использует внешние probe locations и проверяет availability, performance and correctness.
P0 recommendation: внутренний Blackbox Exporter + минимум один действительно внешний probe/uptime service за пределами основного physical/network failure domain.
8. Если есть второй собственный сервер
Он может быть дополнительной probe point, но если оба сервера стоят в одной квартире/стойке/у одного провайдера, это не полноценная external independence.
9. Monitoring stack P0
Prometheus
node_exporter
cAdvisor
blackbox_exporter
application /metrics
Postgres metrics
Redis metrics
nginx metrics/logs
Grafana
Loki
OpenTelemetry Collector
external probe.
10. node_exporter
Prometheus Node Exporter предназначен для hardware/kernel metrics Linux host: CPU, memory, filesystem, network and related host state.
11. cAdvisor
Prometheus documentation uses cAdvisor specifically for Docker container resource/performance metrics such as CPU, memory and network.
12. Metrics architecture
Host exporters ─────┐
Containers ──────────┤
Apps /metrics ───────┤
Workers ─────────────┤
Postgres/Redis ──────┤
Blackbox ────────────┤
▼
Prometheus
│
recording rules
│
Grafana
│
Alertmanager/Grafana Alerting.
13. Logs architecture
nginx
web
api
workers
postgres relevant
redis relevant
security events
↓
structured JSON
↓
collector/agent
↓
Loki
↓
Grafana + log alerts.
14. Traces architecture
Next.js
FastAPI
workers
↓
OpenTelemetry
↓
OTel Collector
↓
Tempo later / trace backend.
15. Нужны ли traces в день №1
Не обязательны для самой первой версии. Metrics + structured logs + request/job correlation дают большую часть ценности. Tracing включается сначала для сложных flow: publish, payment, AI measurement and report generation.
16. OTel Collector
OpenTelemetry Collector даёт нейтральный слой приёма, обработки и экспорта traces/metrics/logs. Health Check Extension позволяет отдельно контролировать состояние Collector.
17. Telemetry не должна теряться при кратком backend outage
OTel Collector File Storage Extension может сохранять state на локальной файловой системе. Использовать только если это оправдано; critical business audit всё равно хранится в PostgreSQL, а не в telemetry.
18. Four Golden Signals
Google SRE выделяет четыре основных сигнала user-facing system: latency, traffic, errors and saturation.
LATENCY:
p50 / p95 / p99
TRAFFIC:
requests / reads / jobs
ERRORS:
5xx / failed jobs / invalid results
SATURATION:
CPU / RAM / disk / DB pool / queue / GPU.
19. Для «Матчасти» добавляем пятый класс
Freshness / Workflow Lag. Платформа сильно асинхронная, поэтому «HTTP 200» недостаточно: report или AI run может опоздать на сутки, хотя сайт формально healthy.
FRESHNESS:
queue age
last successful measurement
last crawler observation
last backup
report lateness
provider sync lag.
20. Public web metrics
http_requests_total
http_request_duration_seconds
http_5xx_total
active_requests
cache_hit_ratio
render_errors
search_latency
auth_failures.
21. Do not alert on average latency
Использовать percentile/histogram. Среднее легко скрывает плохой tail.
22. Public black-box check
GET /
expect 200
expect marker
GET /articles/{known-canary}
expect 200
canonical expected
headline marker present
TLS:
valid
expiry monitored
DNS:
resolves expected.
23. Canary publication
Создать одну постоянную synthetic/canary publication page, которая проходит тот же rendering stack, что реальные статьи.
24. Почему не только /health
/health:
API process alive
Canary article:
actual user path works
Could fail:
templates
read model
routing
cache
DB content
while /health = 200.
25. Auth synthetic check
Не делать внешний monitor с founder/admin credentials. Использовать отдельный synthetic user с минимальными правами или проверять OIDC endpoints independently.
26. Workspace synthetic
Synthetic account:
dedicated test workspace
Check:
login
dashboard API
read report fixture
No:
payment
publication
destructive actions every minute.
27. Transaction synthetic jobs
Hourly/daily:
create test draft
enqueue processing
verify worker
delete/archive fixture
Separate:
from high-frequency public probe.
28. Database metrics
connections
active/idle
locks
deadlocks
transactions
query latency
slow queries
replication/WAL archive
database size
table/index growth
vacuum health
checkpoint pressure.
29. Connection pool
Monitor:
used
available
wait time
timeouts
Alert:
pool exhaustion
before API completely fails.
30. Disk is one of the most important single-host alerts
Disk full can simultaneously break PostgreSQL, Loki, uploads, Docker and backup staging.
Alert:
70% trend/watch
80% action
90% critical
Also:
predict time-to-full
from growth.
Thresholds are initial engineering defaults and must be tuned to actual disk/layout.
31. Inode monitoring
Disk bytes:
free
Also:
inode usage
Millions of tiny files
can fail storage
with GB still free.
32. Memory
Host RAM
swap
OOM kills
container RSS
Postgres memory
browser worker peaks
AI worker host memory.
33. CPU
Sustained saturation
not one spike
Separate:
API
crawler
browser
Postgres
AI preprocessing.
34. GPU metrics
utilization
VRAM
temperature
power
job concurrency
queue wait
OOM/error
model load time.
35. GPU alert
100% GPU utilization itself is not an incident if jobs meet SLO. Queue age and failures matter more.
36. Redis metrics
memory
evictions
connected clients
stream length
consumer lag
pending entries
blocked clients
persistence errors
restart count.
37. Queue health
queue_depth
oldest_job_age
jobs_started
jobs_succeeded
jobs_failed
retry_count
dead_letter_count
processing_duration.
38. Queue age > queue length
1000 jobs processed in 2 minutes may be healthy. 5 jobs waiting 8 hours may be broken.
39. Per-queue SLO
| Queue | Initial target | Meaning |
| publish side effects | 95% ≤ 5 min | sitemap/OG/distribution starts quickly |
| health checks | 95% ≤ 10 min from schedule | Search Proof freshness |
| report generation | 95% ≤ 15 min | client does not wait hours |
| AI scheduled monitoring | 95% ≤ 4 h | batch may be provider-bound |
| low-priority embeddings/backfill | 24 h+ | not user-critical |
These are project hypotheses, not external SLA.
40. Worker heartbeat
worker_id
queue
last_heartbeat
current_job
started_at
version
If heartbeat stale:
restart/recover automatically.
41. Auto restart
Container restart policy handles simple process crash. Monitoring verifies the worker resumes actual useful work, not just that PID exists.
42. Stuck job detection
job RUNNING
duration > type threshold
worker heartbeat healthy?
→ cancel/reclaim
→ retry
→ dead-letter
→ alert if repeat.
43. Poison job
Same job crashes
3 workers
→ quarantine
→ DEAD
→ continue queue
→ do not block entire stream.
44. Retry storm
External provider outage can turn into thousands of retries. Circuit breaker pauses low-priority sends and rate-limits retries.
45. AI/provider monitoring
request count
success
429
5xx
timeouts
latency
tokens/cost
schema failures
citation parse rate
coverage
model/version change.
46. Provider 200 is not enough
HTTP success
but:
empty answer
schema changed
citations missing
wrong locale
Need:
semantic/contract validation.
47. Provider contract canary
Small known prompt
scheduled
Validate:
response exists
expected schema
citation structure where applicable
language/mode metadata.
48. Provider health state
HEALTHY
DEGRADED
RATE_LIMITED
SCHEMA_CHANGED
UNAVAILABLE
DISABLED.
49. Automatic provider routing
Provider A degraded
↓
stop low-priority
↓
fallback B/local
if data policy permits
Historical measurement:
mark provider/method break.
50. Never silently mix methodology
Failover from one model/UI/API to another can keep product operational, but the measurement series must record methodology/provider change.
51. AI cost monitoring
cost/day
cost/workspace
cost/report
cost/prompt
tokens
provider
budget burn
Alert:
unexpected 2×/5× spike.
52. Local Qwen health
endpoint
model loaded
VRAM
generation latency
JSON validity
queue age
restart count
quality canary.
53. Quality canary
Operational health AI should include a tiny eval set, because a model can be «up» but suddenly produce malformed or low-quality outputs after prompt/model change.
54. CMS/publishing metrics
drafts by state
moderation time
auto-approval %
exception %
publish failures
revision loop
publication latency
blocked legal checks.
55. Automation KPI becomes operational metric
straight_through_rate
human_exception_rate
reversal_rate
policy_failure_rate
sample_QA_error_rate.
56. Alert on automation degradation
Example:
human exception baseline 3%
suddenly:
22%
Possible:
prompt/provider/source/parser problem
→ anomaly/ticket
not necessarily page.
57. Publication Health fleet view
active URLs
HTTP healthy %
canonical correct %
unexpected noindex
schema errors
asset failures
broken outbound source links
crawler access anomalies.
58. One broken article vs systemic incident
1 URL 500:
content incident / ticket
500 URLs 500:
platform incident
Correlate:
template/deploy/source.
59. Mass failure correlation
Doc 32 rule becomes operational: 400 publication alerts after one deploy should collapse into one root incident, not 400 notifications.
60. Search Proof ingestion monitoring
GSC:
last successful sync
API errors
quota
data lag
Yandex:
last sync
quota
errors
IndexNow:
submission receipt
retry
Do not:
interpret external delay as site outage.
61. Data freshness states
FRESH
DELAYED
STALE
ERROR
PROVIDER_MAINTENANCE
UNKNOWN.
62. Freshness dashboard
Google Search:
2d expected lag
last data Aug 31
OK
AI ChatGPT:
last run 1h
OK
Perplexity:
last run 7h
DELAYED.
63. Reader analytics monitoring
ingest rate
event validation failures
aggregation lag
bot filtering
sudden zero traffic
Caution:
zero can be real low traffic.
64. Detect analytics pipeline break with canary event
synthetic event
→ ingest
→ aggregation
→ expected row
If missing:
analytics incident.
65. Billing metrics
payment webhook failures
duplicate webhook
order/payment mismatch
credit ledger mismatch
negative balance invariant
refund failures.
66. Financial invariants deserve immediate alert
Credit ledger inconsistency is not a dashboard curiosity. It is a high-severity business-data incident.
67. Backup metrics from Doc 41
last local backup
last off-host backup
last WAL archive
backup duration
backup size
repo errors
last restore test
restore result
RPO estimate.
68. Backup monitoring must be independent
Если backup job stopped for 3 days, system should know without anyone «вспомнив проверить».
69. Security metrics
failed auth
MFA coverage
blocked SSRF
malware
secret detections
privileged changes
RLS denials
bulk exports
provider policy blocks.
70. SLO vs SLA vs SLI
| Term | Для «Матчасти» |
| SLI | измерение: success rate, latency, freshness |
| SLO | внутренняя целевая граница reliability |
| Error Budget | допустимая доля bad events/downtime |
| SLA | договорное обязательство перед клиентом + последствия |
71. Главное коммерческое решение
На MVP не продавать contractual uptime SLA. Сначала накопить несколько месяцев реальной reliability data.
72. Почему
single production host
no automatic DB failover
young codebase
unknown load
unknown provider dependencies
Contractual 99.9/99.99:
premature liability.
73. Internal launch availability SLO
Рекомендуемый initial target: 99.5% monthly availability для публичного reader surface.
99.5% / 30-day month:
~216 minutes error budget
This is:
realistic for single-host early architecture
Not:
marketing boast.
74. After HA
When:
second app/db recovery path
external monitoring mature
months of reliability
Target:
99.9%
~43.2 min/month.
75. 99.99% сейчас — фантазия
~4.3 minutes monthly budget incompatible with a single physical server and 4-hour disaster RTO.
76. User-visible availability SLI
GOOD:
external black-box request
returns expected correct response
within latency threshold
TOTAL:
all scheduled probes
Availability =
GOOD / TOTAL.
77. Correctness matters
HTTP 200
with empty article
is BAD
HTTP 200
wrong tenant report
is security incident
Not merely:
status code.
78. Public latency SLO hypothesis
Cached/normal public page:
p95 server response < 1s
Dynamic product API:
p95 < 1.5s
Long analysis:
async, different SLO.
Initial target; measure before committing publicly.
79. Don't mix asynchronous jobs into HTTP latency SLO
Generate AI report:
queue + minutes
Correct UX:
202 Accepted
status
Not:
60-second HTTP request.
80. Workspace availability SLO
Initial internal:
99.5%
Separate SLI:
login/API success
authenticated dashboard.
81. Publication pipeline SLO
Platform-controlled:
approved → public URL
95% ≤ 5 min
Excluded/paused:
waiting client
manual high-risk exception.
82. Measurement freshness SLO
Scheduled AI:
95% runs completed
within defined batch window
Search provider:
measured against expected provider lag
not against instant freshness.
83. Report delivery SLO
When all required data ready:
95% report artifacts
≤ 15 min
Scheduled client delivery:
within promised delivery window.
84. SLO by dependency class
PUBLIC CORE:
strictest
WORKSPACE:
high
ASYNC MEASUREMENT:
freshness-based
LOW-PRIORITY BACKFILL:
loose
EXPERIMENTAL:
no SLO.
85. Error budgets
Google SRE recommends using error budget consumption, not raw threshold spam, to focus alerts on events that materially threaten the SLO.
86. Burn-rate alerts later
Example Google starting points
for a 99.9% SLO:
14.4× burn over 1h + 5m
6× over 6h + 30m
ticket for slower burn
Mathchast:
adapt after traffic exists.
87. On low traffic
Первые месяцы traffic may be low, so probe-based availability and direct symptoms are more reliable than sophisticated request-ratio burn alerts.
88. Alert classes
| Severity | Meaning | Default action |
| SEV0 | data breach/destruction, full critical outage | immediate human + automated containment |
| SEV1 | major user-facing outage / financial integrity risk | immediate human after auto-remediation attempt |
| SEV2 | degraded function, delayed jobs, provider loss | automation + working-hours escalation |
| SEV3 | warning, trend, low-risk anomaly | ticket/backlog |
89. Alert vs incident
Alert:
signal fired
Incident:
coordinated user/business-impact event
10 alerts
can map to:
1 incident.
90. Alert labels
severity
service
component
environment
symptom
workspace optional
runbook
auto_remediation
owner.
91. Alert must be actionable
Alert text must answer: что сломалось, кого затрагивает, насколько срочно, что система уже сделала и где runbook.
92. Bad alert
CPU > 70%
No context
No user impact
No action.
93. Better alert
SEV1
Public API error rate 31%
for 3 min
Affected:
article + company pages
Auto actions:
restarted API once
DB healthy
Runbook:
RB-PUBLIC-500.
94. Alert pending periods
Grafana Alerting supports Pending periods to avoid firing on temporary conditions and Keep Firing periods to reduce flapping.
Example:
disk full prediction:
pending 10m
site down:
pending 30–60s
payment ledger invariant:
0s.
95. No-data itself has meaning
Prometheus/Grafana «No Data» should not always resolve alert as healthy. A missing backup metric may mean exporter died.
96. Alert routing
Grafana notification policies route alerts using label matchers, group them and control timing/contact points.
SEV0/1:
Telegram + phone/push equivalent + email
SEV2:
Telegram/email
SEV3:
ticket/digest.
97. Telegram
Для маленькой команды Telegram is practical as primary immediate channel, but a second independent channel is required for critical alerts.
98. Why second channel
Telegram outage
phone disconnected
bot token broken
Critical incident:
still needs route.
99. Notification grouping
Prometheus Alertmanager and Grafana support grouping related alerts. Это предотвращает avalanche, когда one database outage creates 100 service notifications.
100. Inhibition
If:
HOST_DOWN
Suppress:
API_DOWN
REDIS_DOWN
WORKER_DOWN
GPU_DOWN
Still show:
affected summary.
101. Maintenance silences
Planned DB maintenance:
silence expected dependent alerts
But:
external public outage
still recorded in SLO
according policy.
102. Never mute alert evaluation
During maintenance better silence notification while rules keep evaluating, so telemetry/history remains.
103. Auto-remediation catalog
| Symptom | Auto action |
| single worker dead | restart container |
| stuck job | reclaim/retry |
| poison job | quarantine + continue queue |
| AI provider 5xx | circuit-break + retry/fallback |
| disk temp cache growth | safe cache cleanup |
| expired temp export | delete |
| high crawler load | lower concurrency |
| GPU OOM job | retry smaller batch / alternate route |
104. Auto-remediation safety rules
bounded
idempotent
reversible
rate-limited
verified afterward
audited
cannot touch unrelated resources.
105. Restart loop breaker
Container crashing 20 times must not auto-restart forever.
restart:
1
2
3
then:
open incident
pause
preserve logs.
106. Auto-clean disk
Allowed:
expired temp
rebuildable cache
old container layers by safe script
Forbidden:
random rm
DB files
backup repository
user originals.
107. AI-assisted diagnosis
Qwen can consume metrics/log excerpts + deployment diff + runbook and produce incident hypothesis, but it does not receive root shell.
Inputs:
alert
recent deploy
logs
metrics
known incidents
runbook
Output:
ranked causes
recommended bounded actions.
108. AI incident toolset
read_metrics
read_logs
read_deploy_history
restart_service(name)
pause_queue(name)
disable_provider(name)
run_health_check(name)
No:
arbitrary shell.
109. AI diagnosis confidence
Do not auto-execute high-risk remediation merely because model writes «95% confident».
110. Automated remediation classes
LOW:
auto
MEDIUM:
auto if pre-approved runbook
HIGH:
prepare plan
human authorize.
111. Incident state machine
DETECTED
→ TRIAGING
→ MITIGATING
→ MONITORING
→ RESOLVED
→ REVIEWED
Possible:
FALSE_POSITIVE
DUPLICATE
MERGED.
112. Incident object
incident_id
severity
started_at
detected_at
user_impact
services
root_alerts
actions
timeline
status
communication
resolved_at
root_cause
followups.
113. Incident commander?
Для маленькой команды formal IC role нужен только на SEV0/SEV1. В обычном SEV2 automation can own workflow until escalation.
114. Incident timeline automatically assembled
14:02 deploy
14:05 first 5xx
14:06 alert
14:06 restart
14:07 still failing
14:08 human paged
14:11 rollback
14:13 recovered.
115. Deployment correlation
Каждый alert/dashboard умеет показать current build SHA and recent deploys. Очень многие incidents становятся очевиднее.
116. Automatic rollback
Canary/smoke fails immediately
after deployment
AND rollback is safe
→ automatic rollback
Not:
random rollback hours later
without diagnosis.
117. Release canary
deploy
→ readiness
→ synthetic article
→ login/API canary
→ error/latency check
→ finalize.
118. Post-deploy watch window
15–30 min:
elevated comparison
to pre-deploy baseline
If severe regression:
rollback.
119. Status page
status.mathchast.com should live outside the main production failure domain.
120. Why
mathchast.com down
+
status page same server down
= useless status page.
121. Status components
Public Website
Client Workspace
Publishing
Reports
AI Visibility
Payments
External Measurement Providers.
122. Provider degradation wording
"AI Visibility updates delayed
due to external provider"
not:
"Mathchast fully down"
if publication/read still works.
123. Status states
Operational
Degraded Performance
Partial Outage
Major Outage
Maintenance.
124. Incident communication principle
Atlassian Statuspage recommends communicating early, often, precisely and consistently across channels.
125. Initial public update
We are investigating
increased errors in Client Workspace.
Public articles remain available.
Started:
14:06 MSK
Next update:
14:30.
126. Don't wait for root cause
Первое сообщение сообщает impact and investigation; root cause can come later.
127. Communication cadence
SEV0/1:
initial quickly
then ~30 min or meaningful change
SEV2:
on meaningful changes
Final:
resolved + later postmortem if material.
128. Automatic status update draft
System can generate accurate status message from incident fields. Publication can be automatic for straightforward known outages or require human approval for security-sensitive events.
129. Security incidents public wording
Never let general AI auto-publish speculative breach statements. Security/legal communication follows Doc 41 exception path.
130. Scheduled maintenance
Create maintenance
affected components
window
expected impact
start/end
reminder
completion.
131. Maintenance should be rare
Architecture/migrations aim to make routine deploys zero/low downtime, so status maintenance is not used for every release.
132. SLA public policy at launch
Terms:
no guaranteed contractual uptime
May publish:
historical status
internal reliability target optionally
Enterprise SLA:
later negotiated.
133. When contractual SLA becomes rational
≥6 months metrics
stable SLO attainment
HA/recovery mature
known support cost
enterprise willingness to pay
service credits modeled.
134. Enterprise SLA first candidate
99.9% monthly
for Workspace/API core
Exclusions:
documented scheduled maintenance
client/network issue
force majeure
external providers where explicitly excluded
But:
legal drafting later.
135. Do not promise AI-provider SLA as your own
If ChatGPT/Gemini endpoint is unavailable, we can promise our retry/reporting behavior, not their uptime.
136. Measurement SLA should be freshness-based
Better:
"scheduled observation completed
within X-hour window"
Not:
"ChatGPT available 99.9%".
137. Error budget policy
If public SLO budget:
healthy
→ normal releases
50% consumed early:
→ investigate reliability
budget nearly exhausted:
→ freeze risky releases
→ reliability work.
138. Error budget stops feature pressure
Это особенно полезно AI-driven development: ИИшка может производить features бесконечно быстро, но error budget создаёт объективную границу, когда надо чинить reliability.
139. Reliability release gate
If:
SEV0 open
backup unhealthy
error budget exhausted
critical queue broken
Then:
block non-essential production deploys.
140. Service catalog
public-web
api
auth
postgres
redis
object-storage
publisher
crawler
measurement
ai-local
ai-external
reports
billing
observability.
141. Every service has owner and runbook
service
criticality
dependencies
SLIs
alerts
auto-actions
runbook
dashboard.
142. Dependency map
public-web
├─ api
│ └─ postgres
└─ object assets
workspace
├─ auth
├─ api
└─ postgres
AI monitoring
├─ queue
├─ provider
└─ postgres.
143. Alert inhibition uses dependency map selectively
Google SRE warns against overly complex dependency hierarchies. Use only obvious stable relationships such as HOST_DOWN suppressing container alerts.
144. Dashboard hierarchy
01 Executive Reliability
02 Public Web
03 API
04 Database
05 Queue/Workers
06 AI Providers
07 Publishing
08 Search/Measurement
09 Billing
10 Backups
11 Security.
145. Executive dashboard
Availability
Error budget
Public p95
Open incidents
Oldest critical job
Measurement freshness
Backup/restore state
Current deploy.
146. No dashboard wall
Никто не должен сидеть и смотреть на Grafana. Dashboards explain; alerts interrupt only when needed.
147. Log levels
DEBUG:
off/default limited prod
INFO:
state/events
WARN:
recoverable anomaly
ERROR:
failed operation
SECURITY:
separate event type.
148. Error codes
PAYMENT_SIGNATURE_INVALID
AI_SCHEMA_INVALID
WORKSPACE_FORBIDDEN
SOURCE_FETCH_TIMEOUT
REPORT_BUILD_FAILED
Better than:
"Exception".
149. Correlation IDs
request_id
trace_id
job_id
incident_id
publication_id
workspace_id
Flow can be reconstructed.
150. Workspace ID in logs
ID is useful for support but logs remain access-controlled and must not include client-private payload.
151. Loki retention
Loki retention is configured explicitly through Compactor; current docs note that without retention enabled, logs can remain indefinitely.
Never leave production logs at infinite retention accidentally.
152. Initial log retention
Application INFO:
30 days
Error/security operational:
90 days
Audit:
separate longer policy
Debug:
days or disabled.
Initial policy hypothesis; Doc 41 legal/security retention takes precedence.
153. Metrics retention
High resolution:
15–30d
Downsample/recording:
months/year where useful
Product business metrics:
Postgres analytical records
not Prometheus forever.
154. Cardinality control
Never put user_id, publication_id or raw URL as unrestricted Prometheus labels across millions of values.
155. High-cardinality detail belongs in logs/traces/DB
Metric:
job_failures{type="ai"}
Log:
job_id=...
publication=...
error=...
156. Recording rules
Prometheus recording rules precompute expensive/common queries. Use them for SLO rates, error ratios and aggregated queue metrics.
157. Alert rule as code
monitoring/
prometheus/
alerts/
recording/
grafana/
dashboards/
blackbox/
runbooks/.
158. Alert config review
CI:
syntax
unit tests
promtool
duplicate names
missing runbook
severity labels.
159. Every page-level alert requires runbook
No runbook link = alert not ready for production.
160. Runbook anatomy
Symptom
User impact
Auto actions already tried
Likely causes
Checks
Safe actions
Escalation
Rollback
Verification.
161. Machine-readable runbook
runbook.yaml
+
human markdown
AI operator:
can execute allowed steps
from same source.
162. Runbook example: WORKER_STUCK
1 check heartbeat
2 inspect oldest jobs
3 reclaim expired
4 restart worker once
5 verify queue age drops
6 if not → SEV2.
163. Runbook example: DISK_HIGH
1 identify filesystem
2 classify growth
3 clean approved temp/cache
4 verify free space
5 throttle crawler/logging if needed
6 escalate if < critical headroom.
164. Runbook example: PROVIDER_DOWN
1 provider canary
2 circuit breaker
3 check fallback policy
4 reschedule batches
5 mark freshness delayed
6 status update if customer-impacting.
165. Runbook example: PUBLIC_5XX
1 blackbox confirm
2 recent deploy?
3 DB health
4 API logs
5 restart once if known crash
6 rollback if deployment correlated
7 escalate.
166. Incident automation state
Alert fires
→ incident candidate
→ correlate
→ run auto-runbook
→ verification
Recovered:
auto resolve + log
Not recovered:
human page.
167. Repeated self-heal is still a problem
Worker that auto-restarts 10 times a day is not healthy just because users never noticed.
Track:
auto_remediation_count
Threshold:
ticket/problem investigation.
168. Incident vs problem
Incident:
restore service now
Problem:
why this keeps recurring
Repeated incidents:
create problem/action item.
169. Postmortem threshold
Required:
SEV0
SEV1
data integrity
security
repeat incident
large error-budget burn
Optional:
routine SEV2.
170. Postmortem is blameless but concrete
Impact
Timeline
Detection
Root causes
Contributing factors
What worked
What failed
Actions
Owners
Deadlines.
171. Root cause can be multiple
Google SRE notes that an incident can have multiple root causes across software and process. Не искать удобного одного виноватого.
172. AI drafts postmortem automatically
Incident DB + logs + deploys + actions provide structured source. Qwen can draft postmortem; human only reviews material SEV0/1 before external publication if any.
173. Follow-up actions
action_id
incident
type
priority
owner
due
status
verification.
174. Don't close postmortem with vague action
Bad:
"monitor better"
Good:
"add canary for article body
and rollback if missing".
175. Incident review feeds automation
New recurring incident
→ new detector
→ runbook
→ auto-remediation
→ future page disappears.
176. This is core AI-native ops loop
Каждый ручной incident response должен рассматриваться как кандидат на последующую автоматизацию.
177. Capacity monitoring
DB size growth
disk growth
request growth
queue growth
AI run growth
GPU wait
crawler bandwidth
report CPU
backup duration.
178. Forecast headroom
Not only:
disk 70%
Also:
at current trend
disk full in 18 days.
179. Capacity thresholds
GREEN:
>30d headroom
WATCH:
14–30d
ACTION:
7–14d
CRITICAL:
<7d or immediate saturation.
Planning defaults; adjust per resource lead time.
180. Scaling trigger: AI worker
Move/add GPU node when:
high-priority AI queue p95 misses SLO
while GPU saturated
and optimization/batching insufficient.
181. Scaling trigger: crawler
Separate crawler host when:
browser/network workload
degrades public/API
or queue misses freshness target.
182. Scaling trigger: PostgreSQL
First:
query/index tune
pool
read models
Then:
more hardware/read replica
Not:
immediate sharding.
183. Scaling trigger: web/API
Add app host when:
CPU/latency saturation
or
availability target requires
removal of single app-host failure.
184. Scaling trigger: HA
HA becomes justified when reliability requirement, recurring revenue or enterprise SLA makes expected downtime more expensive than second-host complexity.
185. Incident metrics
MTTD
time to mitigation
time to recovery
incident count
repeat incident
auto-remediation rate
human pages
false alerts
SEV by component.
186. MTTD
detected_at
-
actual start estimate
Goal:
user-visible core
minutes, not hours.
187. MTTR
resolved_at
-
incident_start
But:
track mitigation separately
because service may recover
before root fix.
188. Alert quality metrics
alerts fired
incidents created
false positives
actionable %
auto-resolved %
human pages
repeat noise.
189. Human page budget
Если человек получает много pages, это product/ops bug.
Target mature:
rare
Review every page:
Could it be:
removed?
ticket?
automated?
190. No 24/7 human on-call in MVP
Реалистичный запуск: automation handles common failures 24/7; SEV0/1 uses best-effort critical escalation to founder/operator. Formal round-the-clock staffed on-call appears only when revenue/SLA justifies it.
191. This affects external promise
No contractual:
15-minute response SLA
while no staffed on-call exists.
192. Service hours vs system hours
System:
24/7 automated
Human support:
business hours initially
Critical security/outage:
exception escalation.
193. Support intake links incidents
Client report:
"dashboard broken"
System:
checks active incidents
attaches ticket
avoids duplicate triage.
194. Public incident reduces support flood
Statuspage’s product guidance explicitly frames status communication as a way to keep users informed and reduce repetitive support requests during outages.
195. Status history becomes trust asset
Не скрывать инциденты. Clean incident history + clear postmortems is stronger than pretending service never fails.
196. But no vanity uptime counter before data
Need:
real external probe
clear SLI
maintenance policy
Then:
show availability.
197. Synthetic monitoring intervals
Public website:
30–60s
TLS/DNS:
1–5m
Workspace synthetic:
5m
Full transactional:
hourly/daily.
198. Why not probe every second
Google SRE notes measurement resolution should fit the reliability target; excessive high-resolution collection creates cost without meaningful benefit.
199. Metrics scrape intervals
Critical app:
15–30s
Host/container:
30s
Slow capacity:
1m+
Expensive:
record/aggregate.
200. Alerting example P0: site down
SEV1
External blackbox:
2+ consecutive failures
AND independent/internal confirmation
or sustained 60s
Auto:
check/restart app
verify
Fail:
page.
201. Alerting example: DB unavailable
SEV1
App cannot connect
+
DB health fails
Auto:
no unsafe restart loop
collect state
attempt approved service recovery
Human:
if persists.
202. Alerting example: measurement late
SEV2
High-priority AI batch:
oldest age > 4h
Auto:
provider state
retry/fallback
scale worker if possible
Human:
working-hours if unresolved.
203. Alerting example: backup missing
SEV1/2 depending age
Off-host backup:
missed > defined RPO window
Auto:
retry backup
check repo
verify WAL
Escalate:
if no recovery.
204. Alerting example: restore test failed
SEV1 reliability risk even if production works. Because disaster recovery is no longer trustworthy.
205. Alerting example: disk forecast
SEV2:
<7d forecast
Auto:
clean permitted temp
reduce log retention
pause low-priority crawl if needed
Never:
delete durable user data.
206. Alerting example: payment mismatch
SEV1:
captured payment
but no matching order/credit state
Auto:
freeze affected ledger operation
reconcile event
human if unresolved.
207. Alerting example: cross-tenant anomaly
SEV0/1:
authorization invariant test
fails
Auto:
disable affected route/feature
capture evidence
security incident
human immediate.
208. Automated synthetic security tests
Scheduled:
workspace A → B forbidden
private file forbidden
admin endpoint forbidden
SSRF canary blocked
Failure:
security alert.
209. Observability itself must be monitored
«Нет alerts» может означать «сломался Prometheus».
Monitor:
Prometheus scrape health
Grafana
Alertmanager/contact delivery
Loki ingestion
external probe heartbeat.
210. Dead-man switch
Periodic heartbeat
must arrive externally
If no heartbeat:
monitoring path failure
alert from outside.
211. Alert delivery test
Daily/weekly:
synthetic alert
→ routing
→ Telegram/email
→ delivery status
Automated verify.
212. Grafana notification history
Current Grafana Alerting includes notification delivery history and routing via notification policies/contact points. Использовать для диагностики failed alert delivery.
213. Protect notification destinations
Grafana documentation specifically treats webhook/contact-point target URLs as protected fields because changing them can redirect sensitive alert data.
Only privileged admin can change critical alert destinations.
214. Monitoring config backup
Git:
Prometheus config
alerts
dashboards
blackbox
runbooks
Secrets:
separate.
215. Dashboard provisioning
Prefer:
versioned JSON/provisioning
as code
Not:
only manual dashboard edits
inside Grafana UI.
216. Alert changes are deployments
PR/change
test
staging
review
deploy
observe noise.
217. New alert probation
First:
dashboard/ticket
or lower severity
Measure:
precision
Then:
promote to page
if truly urgent.
218. Alert deletion
If alert fires repeatedly and is ignored, fix it or delete it. Ignorable alerts train operators to ignore everything.
219. Product health metrics
active workspaces
paid orders
publication throughput
time to value
report delivery
measurement coverage
automation %
repeat failures.
220. Product health is not paging by default
Sales drop is important business analytics, not a 3am infrastructure page.
221. Search/AI business anomalies
All clients:
AI Mention Rate suddenly 0
Potential:
measurement parser broken
This CAN be operational incident
because cross-client synchronized anomaly.
222. Cross-client anomaly detector
If:
same platform
same timestamp
many clients
metric structural break
Suspect:
provider/collector
before concluding brands disappeared.
223. This protects reports
System marks data PARTIAL/PROVIDER_CHANGED rather than sending 50 frightening client reports automatically.
224. Report publication gate
Before auto-send:
required data fresh?
coverage enough?
method version stable?
provider anomaly?
calculation valid?
If no:
hold report
auto diagnose.
225. No zero substitution
Missing provider data does not become 0 Mention Rate, 0 clicks or 0 impressions.
226. Client-facing degradation
AI provider delayed:
show:
"Data updating"
Keep:
last valid snapshot
Do not:
blank dashboard
or fake zero.
227. Incident communication inside app
Banner:
only if relevant component
affects this user
Link:
status page
Avoid:
global red banner
for low-priority crawler issue.
228. Planned provider maintenance
If known:
schedule
queue work around
mark measurement window
client status only if meaningful.
229. SLO review cadence
Monthly:
actual SLI
budget
incidents
alert noise
Quarterly:
adjust SLO
if product/reliability changed.
230. Never loosen SLO to hide failures
Change target only with explicit rationale/version, not after bad month to make dashboard green.
231. SLO versioning
slo_id
service
indicator
target
window
effective_from
version
reason.
232. Incident data model
incidents
incident_events
incident_components
incident_alerts
incident_actions
incident_communications
incident_followups
incident_postmortems.
233. Automated action model
remediation_run
runbook_version
incident_id
action
parameters
started
finished
result
verification
rollback.
234. Telemetry links
incident
→ Grafana dashboard
→ Loki query
→ trace
→ deploy
→ relevant jobs.
235. Incident replay
For test:
take historical incident
replay signals
validate:
new automation
would detect/remediate.
236. Chaos testing later
P1/P2:
kill worker
disable Redis
break provider
fill temp disk
fail API
Verify:
alerts
degradation
self-heal.
237. Don't chaos-kill production DB casually
Start in staging and controlled recovery environment.
238. Disaster drill from Doc 41
Quarterly:
simulate full host loss
Measure:
actual RTO
actual RPO
runbook gaps
credentials availability.
239. Reliability KPI: restore test age
Одно из самых важных чисел на founder dashboard: сколько дней прошло с последнего successful restore.
240. P0 monitoring scope
Prometheus
node_exporter
cAdvisor
blackbox_exporter
Grafana
structured logs + Loki
OTel Collector basic
external uptime probe
public canary article
app/API metrics
Postgres/Redis metrics
queue age/worker health
AI provider/local model health
Publication Health fleet
Search/AI freshness
billing invariants
backup/restore metrics
alert routing
Telegram + second critical channel
basic automated remediation
incident DB/timeline
external status page
runbooks as code
monthly SLO review.
241. P1
Tempo/tracing
burn-rate SLO alerts
advanced synthetic transactions
provider anomaly correlation
adaptive alerting thresholds where safe
capacity forecast
chaos tests
automatic status-page updates
incident postmortem generator
report data-quality gates
problem management
reliability deploy gates.
242. P2
HA monitoring
multi-host alert path
second DB/read/standby metrics
formal on-call
enterprise SLA
service credits
advanced synthetic regions
full tracing
external incident integrations
advanced auto-remediation
reliability analytics.
243. Что НЕ строим в MVP
| Не строим | Почему |
| 24/7 staffed NOC | Economically premature |
| 99.99% SLA | Incompatible with single-host architecture |
| 1000 alerts | Noise |
| ML anomaly detection everywhere | Simple rules first |
| Full distributed tracing for every request | Cost/complexity |
| Manual dashboard watching | Automation-first ops |
| AI with shell root for incidents | Unsafe agency |
| Same-host-only uptime monitor | Cannot detect host loss reliably |
244. Acceptance test: full site outage
Stop public web
Within ~1–2 min:
external probe fails
internal confirms
incident created
auto restart attempted
If recovered:
verify + resolve
If not:
SEV1 human alert
status page outside host remains accessible.
245. Acceptance test: main host powered off
Everything local disappears
Expected:
external monitor detects
second-channel alert fires
external status tooling usable
recovery runbook starts.
246. Acceptance test: worker crash
Kill AI worker
Expected:
container restarts
queue resumes
no human page
incident/remediation recorded.
247. Acceptance test: endless worker crash
Worker crashes 3×+
Expected:
restart circuit stops
queue preserved
SEV2/1 depending impact
human escalation.
248. Acceptance test: provider 500
External AI provider:
100% 5xx
Expected:
circuit breaker
batches delayed
fallback if allowed
data marked delayed
no fake zero.
249. Acceptance test: malformed AI response
Provider 200
schema changed
Expected:
contract canary fails
adapter marked SCHEMA_CHANGED
reports held
operator notified.
250. Acceptance test: cross-client metric collapse
All 30 clients
Mention Rate → 0 same hour
Expected:
provider/measurement anomaly
not 30 Next Best Actions
to "write more content".
251. Acceptance test: disk growth
Fill temp data
Expected:
forecast alert
safe cleanup
verify space
no durable files deleted.
252. Acceptance test: backup failure
Break off-host credentials
Expected:
backup retry
alert
deployment safety gate
recovery before RPO risk becomes hidden.
253. Acceptance test: alert channel broken
Break Telegram bot
Dead-man/test alert:
not delivered
Expected:
second channel reports
notification-path failure.
254. Acceptance test: bad deploy
New build:
article body blank
HTTP 200
Expected:
canary content check fails
deploy rollback
incident logged.
255. Acceptance test: report freshness
Search provider stale
AI current
Expected:
report shows stale source
does not substitute zero
and can delay auto-send if primary outcome unavailable.
256. Acceptance test: incident automation safety
AI suggests:
DROP TABLE
Expected:
tool unavailable
security audit event
no execution.
257. Reliability maturity ladder
LEVEL 0
logs when something breaks
LEVEL 1
metrics + alerts
LEVEL 2
external synthetic + runbooks
LEVEL 3
auto-remediation + SLO
LEVEL 4
HA + error budgets + formal on-call
LEVEL 5
contract SLA + mature automation.
258. MVP target
Запустить на Level 2–3, а не на Level 0. Для почти полностью автоматического продукта monitoring cannot be an afterthought.
259. Founder operational dashboard
SITE
99.72% this month
ERROR BUDGET
44% remaining
INCIDENTS
0 open
QUEUE
oldest critical 34s
AI
2/3 providers healthy
BACKUP
off-host 47m ago
RESTORE
passed 12d ago
DEPLOY
a82f31c · 3h ago.
260. Главная метрика автоматизации эксплуатации
Incidents mitigated
without human intervention
/
all routine eligible incidents.
261. Но 100% automation не является целью сама по себе
Цель — убрать repetitive toil. Novel, ambiguous or high-impact incidents intentionally escalate.
262. Ops loop
MONITOR
↓
DETECT
↓
AUTO-FIX
↓
VERIFY
↓
LEARN
↓
UPDATE RUNBOOK
↓
FEWER HUMAN INTERRUPTIONS.
263. Decision
Утвердить automation-first reliability model. P0 observability состоит из Prometheus + node_exporter + cAdvisor + Blackbox Exporter + Grafana + Loki + basic OpenTelemetry, дополненных независимым внешним synthetic monitor outside the primary server/network failure domain. Monitoring tracks five classes: latency, traffic, errors, saturation and workflow/data freshness. Для асинхронной платформы queue age, measurement freshness, report lateness and backup age являются такими же важными health signals, как HTTP errors. Initial internal availability SLO для public/workspace core — 99.5% monthly, без contractual SLA; после накопления данных и появления HA target can move toward 99.9%. AI providers, local Qwen, crawlers and external search sources receive their own health/freshness states; missing data never becomes zero. Routine incidents use bounded auto-remediation runbooks: restart, reclaim, retry, circuit-break, fallback, safe cleanup and rollback. Human is paged only for SEV0/SEV1, failed automation, data/security integrity or novel incidents. Alerts are grouped/inhibited and must be actionable; every page-level alert has a runbook. status.mathchast.com lives outside primary host. Incident timeline, actions and postmortem are generated from structured telemetry; repeated manual actions are candidates for future automation. Reliability gates can block risky deploys when backup state/error budget is unhealthy. This operating model is deliberately compatible with the user's main economic assumption: «Матчасть» should be able to run with very little routine human labor while still knowing exactly when automation is no longer enough.
264. Что дальше
Mathchast_42 Monitoring / SLA / Incidents
→ Mathchast_43 MVP Scope / Final Roadmap
→ Mathchast_44 MASTER PLAN реализации
→ реальная сборка Mathchast.
Источники исследования
- Google SRE — Monitoring Distributed Systems: white/black-box monitoring, Four Golden Signals, actionable paging and automation principles
- Google SRE Workbook — Alerting on SLOs: error budgets, burn rates and multi-window alerting
- Google SRE Workbook — Implementing SLOs
- Google SRE — Service Level Objectives
- Prometheus — Node Exporter host metrics
- Prometheus — monitoring Docker container metrics with cAdvisor
- Prometheus Blackbox Exporter — HTTP/HTTPS, DNS, TCP, ICMP and gRPC external probing
- Prometheus — recording and alerting rules, pending / keep_firing_for semantics
- Prometheus Alertmanager — grouping, routing, inhibition and silences
- Grafana Alerting — rules, notification policies, grouping, silences and mute timings
- Grafana — pending period, alert lifecycle and keep-firing behavior
- Grafana — notification policy routing, grouping and timing
- Grafana — contact points, delivery status and protected notification destinations
- Grafana Loki — alerting from log-derived metrics; reviewed July 2026
- Grafana Loki — explicit log-retention configuration through Compactor
- OpenTelemetry Collector — telemetry collection/processing/export architecture
- OpenTelemetry Collector Health Check Extension, current 2026 component
- OpenTelemetry File Storage Extension — persisted Collector state
- Grafana Synthetic Monitoring — external availability, performance and correctness checks
- Atlassian Statuspage — incident/status communication and user subscriptions
- Atlassian Statuspage — communicate incidents early, often, precisely and consistently
- Atlassian Statuspage — incident lifecycle, maintenance and postmortem communication
- NIST SP 800-61 Rev.3, final April 2025 — incident response integrated into cybersecurity risk management
Initial SLOs, queue deadlines, severity mapping, probe intervals, retention values, capacity thresholds and automation policies are Mathchast engineering hypotheses. They are intentionally conservative for a single-host launch and must be replaced with measured values after production traffic. Contractual SLA should not be introduced until actual SLO attainment, recovery performance and operational staffing are known.