python
34 lines · 6 steps
Liveness vs readiness health checks in FastAPI
Two endpoints separate whether the process is alive from whether its dependencies are actually reachable.
Explained by
highlit
1from fastapi import APIRouter, status
2from fastapi.responses import JSONResponse
3from sqlalchemy import text
4from sqlalchemy.exc import SQLAlchemyError
5from sqlalchemy.ext.asyncio import AsyncSession
6from fastapi import Depends
7
8from app.db import get_session
9
10router = APIRouter(tags=["health"])
11
12
13@router.get("/health/live", status_code=status.HTTP_200_OK)
14async def liveness() -> dict[str, str]:
15 return {"status": "ok"}
16
17
18@router.get("/health/ready")
19async def readiness(session: AsyncSession = Depends(get_session)) -> JSONResponse:
20 checks: dict[str, str] = {}
21
22 try:
23 await session.execute(text("SELECT 1"))
24 checks["database"] = "ok"
25 except SQLAlchemyError as exc:
26 checks["database"] = f"error: {exc.__class__.__name__}"
27
28 healthy = all(value == "ok" for value in checks.values())
29 code = status.HTTP_200_OK if healthy else status.HTTP_503_SERVICE_UNAVAILABLE
30
31 return JSONResponse(
32 status_code=code,
33 content={"status": "ok" if healthy else "degraded", "checks": checks},
34 )
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Liveness answers whether the process runs; readiness answers whether it can serve traffic.
- 2Probing dependencies with a cheap query surfaces outages without failing the whole request.
- 3Mapping check results to HTTP status codes lets orchestrators route traffic automatically.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 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/liveness-vs-readiness-health-checks-in-fastapi-explained-python-4f6a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.