python 106 lines · 3 tabs

Flask Health-Check Blueprint Reporting Database and Redis Status as JSON

Shared by codesnips Aug 2026
3 tabs
import time
from collections import namedtuple

from sqlalchemy import text

CheckResult = namedtuple("CheckResult", ["name", "healthy", "latency_ms", "detail"])


def _timed(name, probe):
    start = time.perf_counter()
    try:
        detail = probe()
        healthy = True
    except Exception as exc:  # a probe must never propagate
        detail = str(exc)
        healthy = False
    latency_ms = round((time.perf_counter() - start) * 1000, 2)
    return CheckResult(name=name, healthy=healthy, latency_ms=latency_ms, detail=detail)


def check_database(engine):
    def probe():
        with engine.connect() as conn:
            conn.execute(text("SELECT 1"))
        return "connection ok"

    return _timed("database", probe)


def check_redis(redis_client):
    def probe():
        if not redis_client.ping():
            raise RuntimeError("PING returned falsy")
        return "ping ok"

    return _timed("redis", probe)
3 files · python Explain with highlit

A health-check endpoint is one of the smallest pieces of infrastructure that pays for itself repeatedly: load balancers, orchestrators like Kubernetes, and uptime monitors all poll it to decide whether an instance should receive traffic. This snippet builds that endpoint as a self-contained Flask blueprint that probes each critical dependency and reports the results as machine-readable JSON, distinguishing between liveness (is the process running?) and readiness (can it actually serve requests?).

The checks module isolates the actual probing logic from the web layer. Each check is a small function returning a CheckResult namedtuple with a name, boolean status, latency, and optional detail. check_database runs a trivial SELECT 1 through SQLAlchemy's engine so it exercises the real connection pool rather than trusting stale state, and check_redis issues a PING. Both wrap their work in _timed, which measures duration and converts any exception into a failed result with the error string — a probe must never raise, or the health endpoint itself becomes the outage.

The health blueprint wires these into three routes. /health/live is deliberately cheap: it returns 200 as long as the process can respond, which is what a liveness probe wants, since restarting a pod because Redis blipped would be counterproductive. /health/ready runs every registered check and aggregates them; if any dependency is down it returns HTTP 503 so orchestrators stop routing traffic while still reporting per-dependency detail in the body. The status code is derived from all(...) over the results, and the jsonify payload includes each check's latency so slow-but-alive dependencies are visible in dashboards.

The app factory shows the idiomatic registration: dependencies (engine, redis_client) are created once and passed into init_health via the app config, keeping the blueprint free of import-time side effects and easy to test with fakes. Registering under /health with url_prefix groups the routes cleanly.

A few trade-offs are worth noting. The readiness check does real I/O on every hit, so aggressive polling intervals can add load; caching results for a second or two is a common refinement. Timeouts matter too — the Redis client is configured with a short socket_timeout so a hung dependency fails fast instead of blocking the worker. This pattern generalizes to any number of backends by appending checks to the list.


Related snips

go
package api

import (
  "net/http"
  "runtime/debug"
)

Expose build metadata for debugging deploys

go observability build
by Leah Thompson 1 tab
rust
use tracing::{info, instrument};

#[instrument]
fn process_request(user_id: u64) {
    info!(user_id, "Processing request");
    // Work happens here

tracing for structured logging and distributed tracing

rust observability tracing
by Marcus Chen 1 tab
ruby
json.array! @posts do |post|
  json.cache! ['v1', post], expires_in: 1.hour do
    json.id post.id
    json.title post.title
    json.excerpt post.excerpt
    json.published_at post.published_at

Fragment caching for expensive JSON serialization

rails caching performance
by Alex Kumar 1 tab
typescript
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";

const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";

JWT access + refresh token rotation (conceptual)

security node jwt
by codesnips 3 tabs
python
import pandas as pd
from sklearn.ensemble import IsolationForest

df = pd.read_csv('service_metrics.csv')
features = df[['latency_p95', 'error_rate', 'throughput', 'cpu_utilization']]

Anomaly detection with isolation forest and robust thresholds

anomaly-detection isolation-forest monitoring
by Dr. Elena Vasquez 1 tab
yaml
# Grafana provisioning: datasources
# /etc/grafana/provisioning/datasources/prometheus.yml
apiVersion: 1
datasources:
  - name: Prometheus
    type: prometheus

Grafana dashboards as code with JSON provisioning

grafana dashboards monitoring
by Ryan Nakamura 2 tabs

Share this code

Here's the card — post it anywhere.

Flask Health-Check Blueprint Reporting Database and Redis Status as JSON — share card
Link copied