How to Monitor FastAPI App Uptime with Pingzo
FastAPI is a modern, high-performance web framework for building APIs with Python, based on standard Python type hints. Built on top of Starlette and Pydantic, FastAPI is incredibly fast and popular for building microservices, AI endpoints, and backend APIs.
While FastAPI is naturally robust and asynchronous, production applications can experience failures due to database pool exhaustion, background worker crashes, memory leaks in heavy ML models, or database query timeouts.
This guide walks you through setting up a dedicated health check endpoint in FastAPI and configuring external monitoring with Pingzo to receive instant WhatsApp alerts if your API drops.
🛠️ Step 1: Create a Health Check Endpoint in FastAPI
To monitor more than just the HTTP 200 homepage status, you should expose a dedicated /health route that verifies critical dependencies like your database, Redis cache, or storage buckets.
Below is an example of a FastAPI application exposing a /health endpoint that checks a PostgreSQL database connection:
from fastapi import FastAPI, HTTPException, status
from sqlalchemy.sql import text
from database import database_session_maker # Your SQLAlchemy session maker
app = FastAPI(title="FastAPI Production App")
@app.get("/health", status_code=status.HTTP_200_OK)
def health_check():
health_status = {
"status": "healthy",
"services": {
"database": "unknown"
}
}
# 1. Verify Database Connection
try:
db = database_session_maker()
db.execute(text("SELECT 1"))
db.close()
health_status["services"]["database"] = "healthy"
except Exception as e:
health_status["status"] = "unhealthy"
health_status["services"]["database"] = f"failed: {str(e)}"
# 2. Return HTTP 503 if any service is down
if health_status["status"] == "unhealthy":
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=health_status
)
return health_status
Sending Heartbeat Pings in FastAPI Tasks (No SDK Required)
For asynchronous background workers (like Celery, ARQ, or custom asyncio loops), you can ping Pingzo's heartbeat check-in endpoints using httpx or python's native standard libraries:
import httpx
import asyncio
async def my_async_background_task():
try:
# Execute your background job processing logic
await asyncio.sleep(1)
# Ping Pingzo cron check-in URL
ping_url = "https://ping.pingzoapp.com/ping/your-unique-heartbeat-secret"
async with httpx.AsyncClient() as client:
await client.get(ping_url, timeout=5.0)
except httpx.HTTPError as e:
print(f"Index check-in failed: {str(e)}")
⚙️ Step 2: Configure External Monitoring in Pingzo
Once your /health endpoint is live, set up Pingzo to check it regularly from outside your hosting provider (such as AWS, Heroku, or Render):
- Log in to your Pingzo dashboard.
- Click Create Monitor.
- Set the monitoring URL to your endpoint:
https://your-api.com/health. - Set the Check Interval to
1 Minuteor5 Minutes. - Select WhatsApp or Telegram as your target notification channels.
- Click Save Monitor.
💡 Best Practices for FastAPI Monitoring
When deploying asynchronous APIs, follow these operational best practices:
- Use External Verification: Internal monitoring tools can fail if the server crashes or loses internet connectivity. External pings from Pingzo verify actual client connectivity.
- Keep Health Checks Fast: Do not run heavy calculations inside the
/healthroute. Limit checks to simple database handshakes (e.g.,SELECT 1) to prevent health checks from blocking the FastAPI event loop. - Monitor Cron Heartbeats: If you run background tasks with Celery or RQ alongside FastAPI, use Pingzo's cron monitoring to verify that workers are executing tasks successfully.
Summarize with AI
Instantly generate a summary of this page using your favorite LLM