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.
Python code
58 linesimport 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
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
- Replace SQLite with an in-memory database by passing `:memory:` to `sqlite3.connect`.
- 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
More from Observability & SRE
- Adding a Correlation ID to Log Context in Python medium
- Calculate Error Rate from Log Stream in Python easy
- Check if a Timestamp Falls in a Daily Maintenance Window in Python easy
- Export Metrics with OTLP Mock in Python medium
- Generate Mock CPU and Memory Metrics in Python easy
- Generate Prometheus Text Exposition Format in Python easy
Keep learning
Related tutorials and quizzes for this topic.