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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Iterating over Django's connections and caches registries lets one view check every configured backend generically.
- 2A cache write-then-read probe verifies real behavior, not just that the client object exists.
- 3Returning 503 when any dependency fails lets load balancers and orchestrators act on the response automatically.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-health-check-endpoint-in-django-explained-python-35aa/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.