Critical-failure alerts: the admin knows before the user complains¶
The API answered 500 at three in the morning. The log has the traceback,
but nobody reads logs at three in the morning. You find out the next day,
from support.
This recipe makes the 500 (and the crash the app reports) reach whoever
needs to know by e-mail, once per defect, without flooding the inbox in
the middle of an incident.
What you will build¶
Three pieces, each replaceable:
| Piece | What it does |
|---|---|
AlertNotifier |
Decides whether the alert goes out: one per defect per window, a per-window ceiling for each source (API, app), never raises. |
EmailAlertChannel |
Delivers plain text through any mailer with send(to, subject, body) — EmailUtils works as is. |
static_recipients / admin_recipients |
Say who: the .env list or the active admins of the user table. |
from tempest_fastapi_sdk.alerts import (
AlertNotifier,
EmailAlertChannel,
admin_recipients,
make_server_error_alert,
static_recipients,
)
No new extra: the channel uses EmailUtils, which comes from the [email]
extra you already install to send e-mail.
Configuration¶
Add AlertSettings to your settings:
from tempest_fastapi_sdk.settings import AlertSettings, BaseAppSettings, EmailSettings
class Settings(AlertSettings, EmailSettings, BaseAppSettings):
pass
ALERT_ENABLED=true
ALERT_EMAILS=["ops@example.com", "oncall@example.com"]
ALERT_WINDOW_SECONDS=900
ALERT_MAX_PER_WINDOW=20
ALERT_SUBJECT_PREFIX=[ALERT]
ALERT_APP_MIN_SEVERITY=fatal
| Variable | Default | What it controls |
|---|---|---|
ALERT_ENABLED |
false |
Turns everything on. On with no recipient (empty ALERT_EMAILS and no admin_recipients), the alert is dropped with a WARNING on the tempest_fastapi_sdk.alerts logger — nothing more. Off, every call is a no-op and disabled_integrations() lists "alerts". |
ALERT_EMAILS |
[] |
Fixed recipients. |
ALERT_WINDOW_SECONDS |
900 |
After one alert, the same defect stays silent this long. |
ALERT_MAX_PER_WINDOW |
20 |
Ceiling of e-mails per window across every defect of one source (API and app count separately). |
ALERT_SUBJECT_PREFIX |
[ALERT] |
Start of every subject, for mail filters. |
ALERT_APP_MIN_SEVERITY |
fatal |
Lowest app-report severity that alerts. |
ALERT_EMAILS is a JSON list
Same shape as CORS_ORIGINS. ALERT_EMAILS=ops@example.com,oncall@example.com
does not become two entries: pydantic-settings refuses the value at
boot with SettingsError: error parsing value for field "ALERT_EMAILS".
API: alert on every 5xx¶
register_exception_handlers already has the on_server_error hook, which
runs after the response went out. make_server_error_alert is the ready
callback:
from fastapi import FastAPI
from tempest_fastapi_sdk import EmailUtils, register_exception_handlers
from tempest_fastapi_sdk.alerts import (
AlertNotifier,
EmailAlertChannel,
make_server_error_alert,
static_recipients,
)
from tempest_fastapi_sdk.settings import AlertSettings, BaseAppSettings, EmailSettings
class Settings(AlertSettings, EmailSettings, BaseAppSettings):
pass
settings = Settings()
mailer = EmailUtils(**settings.email_kwargs())
notifier = AlertNotifier(
EmailAlertChannel(mailer, **settings.email_alert_kwargs()),
static_recipients(settings.ALERT_EMAILS),
**settings.alert_kwargs(),
environment="production",
)
app = FastAPI()
register_exception_handlers(app, on_server_error=make_server_error_alert(notifier))
Three GET /orders/1, /orders/2, /orders/3 raising the same
RuntimeError produce one e-mail. This is the one that went out,
captured with FakeEmailUtils (the traceback is shortened here and the
paths, absolute in the real e-mail, abbreviated):
Subject: [ALERT] [production] 500 GET /orders/{order_id}: RuntimeError
500 GET /orders/{order_id}: RuntimeError
pricing failed for [REDACTED] token=[REDACTED]
source: api_server_error
environment: production
occurred_at: 2026-12-04T15:53:46.830313+00:00
status: 500
method: GET
route: /orders/{order_id}
exception: RuntimeError
request_id: 715fc7fe-a9f7-4dd4-9873-de773cb32751
fingerprint: cae7186ca235925a
traceback (innermost last):
...
.../fastapi/routing.py:381 in run_endpoint_function
.../orders.py:17 in read_order
The original message was pricing failed for ana@example.com token=s3cr3t.
Only the 500, not the maintenance 503¶
By default every 5xx the handlers report alerts, a deliberate
HTTPException(503) included. To keep it to unexpected errors:
from tempest_fastapi_sdk.alerts import AlertNotifier, make_server_error_alert
from tempest_fastapi_sdk.api.handlers import ServerErrorCallback
def only_500(notifier: AlertNotifier) -> ServerErrorCallback:
return make_server_error_alert(notifier, statuses={500})
App: alert on a crash¶
AppErrorService takes the same notifier. A report now has a severity
field (info, warning, error, fatal; default error), and only what is
at ALERT_APP_MIN_SEVERITY or above becomes an e-mail:
from collections.abc import Callable
from sqlalchemy.ext.asyncio import AsyncSession
from tempest_fastapi_sdk import BaseRepository
from tempest_fastapi_sdk.alerts import AlertNotifier
from tempest_fastapi_sdk.app_errors import (
AppErrorService,
AppErrorSeverityEnum,
make_app_error_model,
)
AppErrorModel = make_app_error_model()
def make_service_factory(
notifier: AlertNotifier, minimum: AppErrorSeverityEnum
) -> Callable[[AsyncSession], AppErrorService]:
def service_factory(session: AsyncSession) -> AppErrorService:
return AppErrorService(
BaseRepository(session, model=AppErrorModel),
notifier=notifier,
alert_min_severity=minimum,
)
return service_factory
The app sends the severity in the POST body:
{"code": "CHECKOUT_CRASH", "message": "NullPointerException at Cart.total", "severity": "fatal", "platform": "android", "app_version": "2.1.0"}
The service schedules the e-mail with AlertNotifier.dispatch and answers
without waiting for SMTP: the app that just crashed is not left hanging on
the send. The subject reads [ALERT] App fatal on android 2.1.0: CHECKOUT_CRASH,
and the body carries the report_id so you can open the full report in the
listing.
The severity comes from the client
The POST is public. Anyone can send fatal — which is why every app
alert goes through deduplication and the window ceiling, and an attacker
cannot get past ALERT_MAX_PER_WINDOW e-mails per window. The ceiling is
counted per source: forged reports with varied codes spend the
app's quota, not the API's, and the next real 500 still goes out (test:
test_app_flood_cannot_silence_an_api_alert).
Migration
The table gained a severity column (String(20), nullable, indexed,
server_default='error'). Generate the migration with Alembic; existing
rows get error from the server_default itself.
Who receives the e-mail¶
static_recipients(settings.ALERT_EMAILS) is the fixed list: blank entries
go away and repeats collapse into one.
admin_recipients reads the active admins (is_admin and is_active) of
your user table at every delivery — a newly promoted admin starts receiving
without a restart:
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from tempest_fastapi_sdk import BaseUserModel
from tempest_fastapi_sdk.alerts import AlertRecipientsProvider, admin_recipients
def recipients(
sessionmaker: async_sessionmaker[AsyncSession],
user_model: type[BaseUserModel],
emails: list[str],
) -> AlertRecipientsProvider:
return admin_recipients(sessionmaker, user_model, extra=emails)
The query runs in its own session, once per e-mail sent (not per error), because the alert runs after the response, when the request's session is already closed — or rolled back.
Deduplication and the ceiling¶
The fingerprint decides what "the same defect" is:
| Source | Fingerprint |
|---|---|
| API | exception type + method + route template (/orders/{order_id}, never /orders/42) |
| App | platform + code + app_version |
Inside ALERT_WINDOW_SECONDS, only the first occurrence of each fingerprint
becomes an e-mail. The rest are counted, and the next e-mail of the same
fingerprint says how many there were:
On top of that, ALERT_MAX_PER_WINDOW caps the window's total per
source: an incident that brings down a hundred different routes sends
twenty e-mails, not a hundred — and a flood from one source does not silence
the other.
Several workers: Redis¶
The default counter lives in the process memory. With four uvicorn workers, each one sends its own first occurrence. To count together, pass Redis:
import redis.asyncio as redis
from tempest_fastapi_sdk.alerts import AlertChannel, AlertNotifier, static_recipients
def shared_notifier(channel: AlertChannel, url: str) -> AlertNotifier:
return AlertNotifier(
channel,
static_recipients(["ops@example.com"]),
backend=redis.Redis.from_url(url),
)
If Redis goes down, the notifier counts in the process memory instead and
logs alert throttle backend failed; counting in memory: it neither drops
the alert nor sends one e-mail per error — and Redis being down is exactly
when every request fails.
What the e-mail never carries¶
No headers, no query string, no request body, no IP, no user_id, no
device_id, no source line, no traceback local. The exception message goes
through redact_database_errors and the default RedactionPolicy (e-mail,
Bearer, JWT, token=/password=…), and the route is the template, not the
path with the id.
The suite proves it with a real request: tests/alerts/test_server_errors.py
sends Authorization: Bearer headersecret, ?api_key=querysecret and a
message holding an e-mail, a token= and a JWT, and checks that none reaches
the e-mail.
Nothing here breaks the response¶
An SMTP, Redis or recipient-query failure is logged on
tempest_fastapi_sdk.alerts and swallowed. The client still gets the same
500 with the same envelope — tested with the fake mailer set to refuse the
send.
Recap¶
AlertSettings+alert_kwargs()/email_alert_kwargs()build the notifier;ALERT_EMAILSis a JSON list.make_server_error_alert(notifier)goes inon_server_error=;statuses=filters.AppErrorService(..., notifier=, alert_min_severity=)alerts on app crashes fromfatalup; theseveritycolumn needs a migration.- One e-mail per defect per window, a per-source ceiling, Redis for several workers.
- Recipients from
.envor from the database's active admins.