Работа с мониторингом и наблюдаемостью.

Звёзды2 926
Авторjeremylongshore
Установок29

Установка

SKILL.md

Database Health Monitor

Overview

Monitor database server health across PostgreSQL, MySQL, and MongoDB by tracking key performance indicators including connection utilization, query throughput, replication lag, disk usage, cache hit ratios, vacuum activity, and lock contention.

Prerequisites

  • Database credentials with access to system statistics views (pg_stat_*, performance_schema, serverStatus)
  • psql, mysql, or mongosh CLI tools for running health check queries
  • Permissions: pg_monitor role (PostgreSQL), PROCESS privilege (MySQL)
  • Baseline metrics from a period of normal operation for threshold calibration
  • Alerting channel configured (email, Slack webhook, PagerDuty)

Instructions

  1. Check connection utilization:

    • PostgreSQL: SELECT count(*) AS active_connections, (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS max_connections, round(count(*)::numeric / (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') * 100, 1) AS utilization_pct FROM pg_stat_activity
    • MySQL: SELECT VARIABLE_VALUE AS connections FROM performance_schema.global_status WHERE VARIABLE_NAME = 'Threads_connected'
    • Alert threshold: utilization above 80%
  2. Monitor query throughput and error rate:

    • PostgreSQL: SELECT datname, xact_commit AS commits_total, xact_rollback AS rollbacks_total, xact_rollback::float / GREATEST(xact_commit, 1) AS rollback_ratio FROM pg_stat_database WHERE datname = current_database()
    • MySQL: SHOW GLOBAL STATUS LIKE 'Com_commit' and SHOW GLOBAL STATUS LIKE 'Com_rollback'
    • Alert threshold: rollback ratio above 5% or throughput drops more than 50% from baseline
  3. Check disk usage and growth:

    • PostgreSQL: SELECT pg_size_pretty(pg_database_size(current_database())) AS db_size and SELECT tablename, pg_size_pretty(pg_total_relation_size(tablename::text)) AS size FROM pg_tables WHERE schemaname = 'public' ORDER BY pg_total_relation_size(tablename::text) DESC LIMIT 10
    • Alert threshold: disk usage above 80% or growth rate projecting full disk within 7 days
  4. Monitor cache hit ratio:

    • PostgreSQL: SELECT sum(heap_blks_hit)::float / GREATEST(sum(heap_blks_hit) + sum(heap_blks_read), 1) AS cache_hit_ratio FROM pg_statio_user_tables
    • MySQL: SELECT (1 - (VARIABLE_VALUE / (SELECT VARIABLE_VALUE FROM performance_schema.global_status WHERE VARIABLE_NAME = 'Innodb_buffer_pool_read_requests'))) AS hit_ratio FROM performance_schema.global_status WHERE VARIABLE_NAME = 'Innodb_buffer_pool_reads'
    • Alert threshold: cache hit ratio below 95% indicates shared_buffers or innodb_buffer_pool_size needs increasing
  5. Check vacuum and autovacuum health (PostgreSQL):

    • SELECT relname, last_vacuum, last_autovacuum, n_dead_tup, n_live_tup, round(n_dead_tup::numeric / GREATEST(n_live_tup, 1) * 100, 1) AS dead_pct FROM pg_stat_user_tables WHERE n_dead_tup > 1000 ORDER BY n_dead_tup DESC LIMIT 10
    • Alert threshold: dead tuple percentage above 20% or autovacuum not running for more than 24 hours on active tables
  6. Monitor replication lag (if replicas exist):

    • PostgreSQL: SELECT client_addr, state, pg_wal_lsn_diff(sent_lsn, replay_lsn) AS lag_bytes FROM pg_stat_replication
    • MySQL: SHOW REPLICA STATUS\G - check Seconds_Behind_Source
    • Alert threshold: lag above 30 seconds or replication stopped
  7. Check for long-running queries:

    • PostgreSQL: SELECT pid, now() - query_start AS duration, state, query FROM pg_stat_activity WHERE state != 'idle' AND now() - query_start > interval '5 minutes' ORDER BY duration DESC
    • Alert threshold: any query running longer than 10 minutes (OLTP) or 1 hour (analytics)
  8. Monitor lock contention:

    • PostgreSQL: SELECT count(*) AS waiting_queries FROM pg_stat_activity WHERE wait_event_type = 'Lock'
    • Alert threshold: more than 10 queries waiting for locks simultaneously
  9. Compile all health checks into a single monitoring script that runs via cron every 60 seconds, outputs metrics in a structured format (JSON), and triggers alerts when thresholds are breached.

  10. Create a health summary dashboard query that returns a single-row result with RAG (Red/Amber/Green) status for each health dimension: connections, throughput, disk, cache, vacuum, replication, queries, and locks.

Output

  • Health check queries tailored to the specific database engine
  • Monitoring script (shell or Python) for scheduled health checks with alerting
  • Threshold configuration with default values and tuning guidance
  • Dashboard summary query providing RAG status across all health dimensions
  • Alert notification templates for Slack, email, or PagerDuty integration

Error Handling

ErrorCauseSolution
pg_stat_activity returns incomplete datatrack_activities = off in postgresql.confEnable track_activities = on and track_counts = on; reload configuration
Health check query itself times outDatabase under heavy load or lock contentionSet statement_timeout = '5s' for monitoring queries; use a dedicated monitoring connection
False alerts during maintenance windowsPlanned maintenance triggers threshold breachesImplement alert suppression windows; add maintenance mode flag to monitoring script
Disk usage alert but no obvious growthWAL files, temporary files, or pg_stat_tmp consuming spaceCheck pg_wal directory size; check for orphaned temporary files; verify wal_keep_size setting
Cache hit ratio drops after restartBuffer pool/shared_buffers cold after database restartImplement cache warming script that runs key queries after restart; alert will self-resolve as cache warms

Examples

PostgreSQL health dashboard for a production SaaS application: A single cron-based script checks 8 health dimensions every 60 seconds, writing results to a metrics table. A dashboard query shows: connections 45/200 (GREEN), cache hit 98.5% (GREEN), dead tuples 2.1% (GREEN), disk 62% (GREEN), replication lag 0.5s (GREEN), long queries 0 (GREEN), lock waiters 1 (GREEN), rollback ratio 0.3% (GREEN).

Detecting impending disk full condition: Health monitor tracks daily disk growth rate. Current usage: 72%, daily growth: 1.2GB, remaining: 280GB. Projected full date: 233 days. Alert triggers at 80% with recommendation to archive old data or add storage. A second alert at 90% escalates to PagerDuty.

Identifying autovacuum falling behind: Health check shows the events table with 15M dead tuples (45% dead ratio) and last autovacuum 3 days ago. Root cause: autovacuum_vacuum_cost_delay too conservative for a high-write table. Fix: set per-table autovacuum_vacuum_cost_delay = 2 and autovacuum_vacuum_scale_factor = 0.01.

Resources

  • PostgreSQL monitoring statistics: https://www.postgresql.org/docs/current/monitoring-stats.html
  • MySQL performance_schema: https://dev.mysql.com/doc/refman/8.0/en/performance-schema.html
  • MongoDB serverStatus: https://www.mongodb.com/docs/manual/reference/command/serverStatus/
  • PostgreSQL autovacuum tuning: https://www.postgresql.org/docs/current/runtime-config-autovacuum.html
  • check_postgres monitoring tool: https://bucardo.org/check_postgres/

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: monitoring-database-health](https://darkplay.ru/ai/skills/jeremylongshore-claude-code-plugins-plus-skills-monitoring-database-health)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Database Migrationaffaan-m · Каркас команды workflow для database-migration в everything-claude-code.
225 587 ★
Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
225 587 ★
Healthcare Revieweraffaan-m · Проверяет медицинский код: клиническая безопасность, CDSS, PHI и целостность данных.
225 587 ★
Mle Revieweraffaan-m · Ревьюер ML-инженерии: данные, признаки, обучение, оценка, сервинг и мониторинг.
225 587 ★
Skill Healthaffaan-m · Показывает панель состояния портфеля навыков с графиками и аналитикой.
225 587 ★
ui-ux-pro-maxnextlevelbuilder · Профессиональные знания по UI/UX-дизайну для ИИ-ассистентов программирования. Включает…
151 010 ★
ruflo-migrationsruvnet · Управление миграциями схемы: генерация, проверка, пробный запуск и откат миграций базы…
240 комп.
ruflo-ruvectorruvnet · Самообучающаяся векторная база данных: HNSW, FlashAttention-3, Graph RAG, гибридный…
240 комп.
ruflo-security-auditruvnet · Проверка безопасности, сканирование зависимостей, политики-гейты и мониторинг CVE.
240 комп.
agentic-bundle-observability-monitoringsickn33 · Установите набор редакционных навыков «Observability & Monitoring» для Claude Code.
49 917 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8