python 40 lines · 7 steps

Building a health check endpoint in Django

A single view probes every database and cache connection and reports overall service health as JSON.

Explained by highlit
1from django.db import connections
2from django.db.utils import OperationalError
3from django.core.cache import caches
4from django.http import JsonResponse
5from django.views.decorators.http import require_GET
6 
7 
8@require_GET
9def health_check(request):
10 checks = {}
11 healthy = True
12 
13 for alias in connections:
14 try:
15 conn = connections[alias]
16 with conn.cursor() as cursor:
17 cursor.execute("SELECT 1")
18 cursor.fetchone()
19 checks[f"database:{alias}"] = "ok"
20 except OperationalError as exc:
21 healthy = False
22 checks[f"database:{alias}"] = f"error: {exc}"
23 
24 for alias in caches:
25 try:
26 cache = caches[alias]
27 probe_key = "__health_check__"
28 cache.set(probe_key, "1", timeout=5)
29 if cache.get(probe_key) != "1":
30 raise ValueError("cache read-back mismatch")
31 checks[f"cache:{alias}"] = "ok"
32 except Exception as exc:
33 healthy = False
34 checks[f"cache:{alias}"] = f"error: {exc}"
35 
36 status = 200 if healthy else 503
37 return JsonResponse(
38 {"status": "healthy" if healthy else "unhealthy", "checks": checks},
39 status=status,
40 )
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Iterating over Django's connections and caches registries lets one view check every configured backend generically.
  2. 2A cache write-then-read probe verifies real behavior, not just that the client object exists.
  3. 3Returning 503 when any dependency fails lets load balancers and orchestrators act on the response automatically.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a health check endpoint in Django — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code