How to Create a Deep Health Check Database in Python

Setup a SQLite-backed health check database, insert mock data with response times and statuses, and generate a report ordered by most recent check.

Easy Python 3.9+ Aug 9, 2026 Observability & SRE 13 views 0 copies

Python code

58 lines
Python 3.9+
import sqlite3
from datetime import datetime, timedelta
from pathlib import Path

DB_PATH = Path("deep_health_check.db")


def setup_database():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS health_checks (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            service TEXT NOT NULL,
            status TEXT NOT NULL,
            response_time_ms INTEGER NOT NULL,
            checked_at TEXT NOT NULL
        )
    """)
    conn.commit()
    return conn


def insert_mock_data(conn):
    services = ["auth", "database", "cache", "api"]
    statuses = ["healthy", "degraded", "unhealthy", "healthy"]
    base_time = datetime.now()
    cursor = conn.cursor()
    for i, service in enumerate(services):
        cursor.execute(
            """
            INSERT INTO health_checks (service, status, response_time_ms, checked_at)
            VALUES (?, ?, ?, ?)
            """,
            (
                service,
                statuses[i],
                (i + 1) * 47 + 12,
                (base_time - timedelta(minutes=i * 5)).isoformat(),
            ),
        )
    conn.commit()


def get_report(conn):
    cursor = conn.cursor()
    cursor.execute("SELECT service, status, response_time_ms, checked_at FROM health_checks ORDER BY checked_at DESC")
    rows = cursor.fetchall()
    return rows


if __name__ == "__main__":
    conn = setup_database()
    insert_mock_data(conn)
    report = get_report(conn)
    for row in report:
        print(', '.join(str(item) for item in row))
    conn.close()

Output

stdout
api, healthy, 200, 2025-01-14T15:26:45.123456
cache, unhealthy, 153, 2025-01-14T15:21:45.123456
database, degraded, 106, 2025-01-14T15:16:45.123456
auth, healthy, 59, 2025-01-14T15:11:45.123456

How it works

The script creates a SQLite database file and a health_checks table if it doesn't exist. Mock data is inserted with a mix of statuses and response times; checked_at is set relative to the current time using datetime and timedelta. The report query orders rows by checked_at descending, so the most recent check appears first. Using sqlite3 from the standard library makes the example dependency-free and easy to run in any environment.

Common mistakes

  • Not closing the database connection, which can leak locks on Windows.
  • Forgetting to commit after inserts, leaving the data unwritten.
  • Assuming `checked_at` string comparison works across timezone offsets without normalization.

Variations

  1. Replace SQLite with an in-memory database by passing `:memory:` to `sqlite3.connect`.
  2. Use pandas to load the report into a DataFrame for easier analysis.

Real-world use cases

  • Storing periodic health check results from microservices to detect degradation trends over time.
  • Simulating database state in development and test environments when building dashboards.
  • Populating a local metrics store to verify query logic before connecting to production monitoring.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Observability & SRE

Related tutorials and quizzes for this topic.