Почему алерты БД молчат до аварии?
Вы замечали, что база данных падает без предупреждения? Обычно первым сигналом становится жалоба пользователя: «сайт не отвечает». К этому моменту диск уже заполнен, реплика отстала на часы, а транзакции заблокированы. Мы внедряем систему алертов, которая оповещает за 72 часа до критического события.
Настраиваем полный цикл мониторинга метрик БД: CPU, память, диск, подключения, репликация, долгие запросы. Используем Prometheus, Alertmanager, Grafana. Интегрируем уведомления в Telegram или Slack. Наши правила покрывают 15+ критических метрик для PostgreSQL, MySQL и MongoDB. Предиктивные алерты на predict_linear в 3 раза эффективнее простых пороговых правил — они дают время на реакцию, а не констатируют аварию. Согласно документации Prometheus, predict_linear основан на линейной регрессии.
Почему стандартные алерты не работают?
Без предиктивных правил вы узнаёте о проблеме, когда уже поздно. Например, алерт «диск заполнен на 95%» — это авария. А «диск заполнен на 75%, рост 2 GB/сутки» — у вас 10 дней на расширение хранилища. Prometheus умеет предсказывать тренды через predict_linear, но мало кто это настраивает. Ещё частая ошибка — игнорирование репликации. Лаг в 60 секунд может привести к потере данных при сбое master. Мы включаем алерт PostgreSQLReplicationLag с критичным порогом. Средняя экономия клиентов после внедрения — существенная сумма за счёт предотвращения простоев.
Как настроить алерты для PostgreSQL и MySQL?
| Компонент | Инструмент | Версия (рекомендуемая) |
|---|---|---|
| Метрики БД | postgres_exporter / mysqld_exporter | Latest |
| Сбор и хранение | Prometheus | 2.x |
| Визуализация | Grafana | 10.x |
| Уведомления | Alertmanager + Telegram | Latest |
| Системные метрики | node_exporter | Latest |
Установка exporters (Docker)
# PostgreSQL
docker run -d --name postgres_exporter \
-e DATA_SOURCE_NAME="postgresql://monitoring:password@localhost:5432/postgres?sslmode=disable" \
-p 9187:9187 \
quay.io/prometheuscommunity/postgres-exporter:latest
# MySQL
docker run -d --name mysqld_exporter \
-e DATA_SOURCE_NAME="monitoring:password@(localhost:3306)/" \
-p 9104:9104 \
prom/mysqld-exporter:latest
# Node Exporter
docker run -d --name node_exporter \
--pid="host" \
-v /:/host:ro,rslave \
-p 9100:9100 \
quay.io/prometheus/node-exporter:latest \
--path.rootfs=/hostПользователь для мониторинга PostgreSQL (минимальные права): CREATE USER monitoring WITH PASSWORD 'monitoring_password'; GRANT pg_monitor TO monitoring;
Правила алертов (Prometheus rules)
Файл /etc/prometheus/rules/database.yml:
groups:
- name: postgresql_critical
rules:
- alert: PostgreSQLDown
expr: pg_up == 0
for: 30s
labels:
severity: critical
annotations:
summary: "PostgreSQL недоступен на {{ $labels.instance }}"
- alert: DiskSpaceHigh
expr: |
(node_filesystem_size_bytes{mountpoint="/var/lib/postgresql"} - node_filesystem_free_bytes{mountpoint="/var/lib/postgresql"}) / node_filesystem_size_bytes{mountpoint="/var/lib/postgresql"} * 100 > 85
for: 5m
labels:
severity: warning
- alert: DiskSpaceCritical
expr: |
(node_filesystem_size_bytes{mountpoint="/var/lib/postgresql"} - node_filesystem_free_bytes{mountpoint="/var/lib/postgresql"}) / node_filesystem_size_bytes{mountpoint="/var/lib/postgresql"} * 100 > 95
for: 1m
labels:
severity: critical
- alert: PostgreSQLTooManyConnections
expr: pg_stat_activity_count / pg_settings_max_connections * 100 > 80
for: 2m
labels:
severity: warning
- alert: PostgreSQLLongRunningTransaction
expr: pg_stat_activity_max_tx_duration{state="active"} > 600
for: 1m
labels:
severity: warning
- alert: PostgreSQLReplicationLag
expr: pg_replication_lag > 60
for: 2m
labels:
severity: critical
- name: postgresql_warning
rules:
- alert: PostgreSQLLowCacheHitRate
expr: |
(sum(pg_stat_database_blks_hit) / (sum(pg_stat_database_blks_hit) + sum(pg_stat_database_blks_read))) * 100 < 99
for: 10m
labels:
severity: warning
- alert: HighCPUUsage
expr: |
100 - (avg by(instance)(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 5m
labels:
severity: warning
- alert: LowFreeMemory
expr: node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes * 100 < 10
for: 5m
labels:
severity: warning
- name: mysql_alerts
rules:
- alert: MySQLDown
expr: mysql_up == 0
for: 30s
labels:
severity: critical
- alert: MySQLSlowQueries
expr: rate(mysql_global_status_slow_queries[5m]) > 5
for: 2m
labels:
severity: warning
- alert: MySQLInnoDBBufferPoolHitRateLow
expr: |
(mysql_global_status_innodb_buffer_pool_read_requests - mysql_global_status_innodb_buffer_pool_reads) / mysql_global_status_innodb_buffer_pool_read_requests * 100 < 99
for: 10m
labels:
severity: warning
- alert: MySQLReplicationLag
expr: mysql_slave_status_seconds_behind_master > 30
for: 1m
labels:
severity: critical
- name: mongo_alerts
rules:
- alert: MongoDBReplicationLag
expr: mongodb_rs_member_replication_lag_seconds > 60
for: 2m
labels:
severity: critical
- name: predictive_alerts
rules:
- alert: DiskWillFillSoon
expr: predict_linear(node_filesystem_free_bytes{mountpoint="/var/lib/postgresql"}[6h], 3*24*3600) < 0
for: 1h
labels:
severity: warning
Alertmanager: как настроить Telegram
# /etc/alertmanager/alertmanager.yml
global:
resolve_timeout: 5m
route:
group_by: ['alertname', 'instance']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
receiver: telegram-critical
routes:
- match:
severity: critical
receiver: telegram-critical
repeat_interval: 30m
- match:
severity: warning
receiver: telegram-warning
repeat_interval: 4h
receivers:
- name: telegram-critical
telegram_configs:
- api_url: "https://api.telegram.org"
bot_token: "BOT_TOKEN"
chat_id: -1001234567890
message: |
\U0001f534 *{{ .GroupLabels.alertname }}*
{{ range .Alerts }}
*{{ .Annotations.summary }}*
{{ .Annotations.description }}
Время: {{ .StartsAt.Format "15:04:05" }}
{{ end }}
parse_mode: "Markdown"
- name: telegram-warning
telegram_configs:
- api_url: "https://api.telegram.org"
bot_token: "BOT_TOKEN"
chat_id: -1001234567891
message: |
\U000026a0 *{{ .GroupLabels.alertname }}*
{{ range .Alerts }}{{ .Annotations.summary }}{{ end }}
parse_mode: "Markdown" Почему предиктивные алерты лучше?
Предиктивные алерты на predict_linear дают время на реакцию: диск закончится через 3 дня — вы успеете расширить хранилище. Стоимость одного часа простоя БД может быть значительной. Инвестиция в настройку мониторинга окупается за 1-2 месяца.
Процесс работы: от запроса до деплоя
- Аудит текущей инфраструктуры — собираем схему БД, версии, нагрузку, выявляем узкие места.
- Разработка конфигурации — подбираем exporters, правила алертов, каналы уведомлений. Определяем пороги на основе исторических данных: например, 80% CPU в течение 5 минут — warning, 95% — critical.
- Установка и настройка — разворачиваем стек (Prometheus, Alertmanager, Grafana) в Docker или на bare metal.
- Интеграция с Telegram/Slack/PagerDuty — настраиваем шаблоны сообщений, маршрутизацию по severity.
- Тестирование — форсируем алерты, проверяем доставку, корректируем чувствительность.
- Документация и обучение — передаём инструкции и доступы.
- Пост-релизная поддержка — корректируем пороги при необходимости, добавляем новые метрики.
Что входит в работу
- Установка и настройка Prometheus + Alertmanager + Grafana.
- Конфигурация exporters для PostgreSQL/MySQL/MongoDB.
- Написание набора правил (critical, warning, predictive).
- Настройка уведомлений в Telegram/Slack.
- Создание дашборда Grafana с ключевыми метриками (CPU, память, диск, подключения, репликация).
- Документация по эксплуатации и обслуживанию.
- Гарантийная поддержка после внедрения.
Сроки и стоимость
| Объём работ | Срок | Стоимость |
|---|---|---|
| Одна БД (PostgreSQL/MySQL) | 4-8 часов | рассчитывается индивидуально |
| Комплексный мониторинг (несколько БД + дашборды) | 1-2 дня | рассчитывается индивидуально |
Стоимость зависит от сложности инфраструктуры, количества БД и требований к уведомлениям. Мы оцениваем проект после брифинга. Свяжитесь с нами — пришлём коммерческое предложение.
Проверка работы алертов
После настройки отправляем тестовый алерт через Alertmanager API:
curl -H "Content-Type: application/json" -d '[{"labels": {"alertname": "TestAlert", "severity": "warning"}, "annotations": {"summary": "Test alert from setup verification"}}]' http://localhost:9093/api/v1/alerts"}
Wait, the instruction says to restore proper newlines. For a single curl command, it's typically one line. But the context says "bash" and the flattened code is a single line. Since it's a single command, no newlines needed. However, the instruction says "restore proper newlines inside a single code block that was flattened to one line". If it was originally multiple lines, we need to guess. But the code is a curl command with a JSON payload. It could be broken into multiple lines for readability, but the instruction says "Do NOT alter any character other than adding
and leading indentation." So we can add newlines at logical points. For bash, common practice is to break long commands with backslashes. But the instruction says "restore proper newlines" and "For Python/YAML/JSON/bash/JS/TS: restore idiomatic line breaks". For bash, idiomatic line breaks might be after the -d flag? Actually, typical formatting for curl with JSON payload is to put the payload on its own line or break the command. But since we cannot add backslashes (that would alter characters), we can only add newlines. However, adding a newline without a backslash in bash will break the command. So we must not add newlines inside the command unless we also add backslashes, but we cannot add backslashes. So the only safe newline is at the end. But the instruction says "restore proper newlines" implying there were multiple lines originally. Possibly the original had the JSON payload on multiple lines? But the flattened code is a single line with the JSON as a string. If we add newlines inside the JSON string, that would change the string content. So we cannot. Therefore, the only proper newline is at the end. But the instruction says "Return ONLY the reformatted plain code text." and "For ASCII diagrams each logical row on its own line." This is not a diagram. So likely the answer is the same line. But the instruction says "restore proper newlines" - maybe the original had the command split with backslashes? But we cannot add backslashes. So I think the correct output is the same string. However, the instruction says "Do NOT alter any character other than adding
and leading indentation." So we can add a newline at the end? But that would be altering? Adding
is allowed. But we need to output JSON with "code" containing the reformatted text. Since the code is a single line, we can just put it as is. But to be safe, I'll output the same line. But the instruction says "restore proper newlines" - maybe the original had the JSON payload on multiple lines? But that would be inside the single quotes, so newlines inside the single quotes would be part of the string. But the flattened code has no newlines, so we cannot add them inside the quotes because that would change the payload. So the only logical place is to break the command after the -d argument? But without backslash, it's invalid. So I think the answer is the same line. However, the instruction says "For Python/YAML/JSON/bash/JS/TS: restore idiomatic line breaks (imports, def/class, control blocks, YAML keys, list items)." This is a single command, no such structures. So no newlines needed. So I'll output the same string.
But wait, the instruction says "Return JSON: {"code": "<reformatted text with real
>"}" - so we need to include
characters in the string. If we don't add any, then the string has no
. That's fine.
Thus, the output is: {"code": "curl -H "Content-Type: application/json" -d '[{"labels": {"alertname": "TestAlert", "severity": "warning"}, "annotations": {"summary": "Test alert from setup verification"}}]' http://localhost:9093/api/v1/alerts"}
But to be precise, we need to escape double quotes in JSON. So the code string contains double quotes, so we escape them. Also the single quotes are fine. So the JSON is valid.
I'll output that.<ï½endâofâthinkingï½>{"code": "curl -H "Content-Type: application/json" -d '[{"labels": {"alertname": "TestAlert", "severity": "warning"}, "annotations": {"summary": "Test alert from setup verification"}}]' http://localhost:9093/api/v1/alertsПроверяем приход уведомления в Telegram. Открываем Grafana и смотрим дашборды.
Наш опыт — более 5 лет в инфраструктурном мониторинге, 50+ внедрённых проектов. Напишите нам — поможем настроить мониторинг БД под ключ за 1-2 дня. Получите консультацию.
Типичные ошибки при самостоятельной настройке
- Забывают про репликацию — алерты только на мастер. Реплика отстаёт, данные теряются.
- Нет предиктивных правил — узнают о проблеме, когда диск уже заполнен.
- Слишком много алертов — warning по каждому чиху. Настраиваем только значимые пороги.
- Не тестируют уведомления — бот не отправляет из-за ошибки в токене. Мы проверяем каждый канал.
Один предотвращённый инцидент экономит значительно. Инвестиция в настройку мониторинга окупается за 1-2 месяца. Закажите настройку алертов БД и забудьте о неожиданных сбоях.







