Middleware
Inspect and act on every request with built-in and custom middleware, configured declaratively in one file.
Middleware wraps every HTTP request, running code before it reaches your routes and after the response is produced. Alata ships maintenance mode and request logging out of the box, wires CORS, GZip, and trusted-host protection through one declarative config file, and makes registering your own middleware a two-step exercise.
How Middleware Is Configured
All middleware settings live in config/middleware.py as plain dicts:
from config.settings import settings
CORS = {
"allow_origins": ["http://localhost:3000"],
"allow_methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
"allow_headers": ["Content-Type", "Authorization", "X-Request-ID"],
"allow_credentials": True,
"max_age": 600,
}
GZIP = {"minimum_size": 500, "enabled": True}
TRUSTED_HOSTS = {
"allowed_hosts": ["localhost", "127.0.0.1"],
"enabled": settings.is_production(), # only enforce in production
}
REQUEST_LOGGING = {
"enabled": True,
"exclude_paths": ["/health", "/favicon.ico", "/docs", "/openapi.json", "/metrics"],
"slow_request_threshold": 5.0,
}
MAINTENANCE_MODE = {
"bypass_paths": ["/health"],
}During boot these dicts are merged into the config repository under the middleware.* namespace — middleware.cors, middleware.gzip, middleware.trusted_hosts, middleware.request_logging, and middleware.maintenance_mode — so framework code can read them with dot notation:
from alata.container import container
container.make("config").get("middleware.maintenance_mode.bypass_paths")
# ["/health"]Your application's HTTP provider reads the same dicts and attaches each middleware to the kernel:
from alata.http import FastapiProvider as HttpProvider
class FastapiProvider(HttpProvider):
def register(self):
super().register()
from config.middleware import MAINTENANCE_MODE, REQUEST_LOGGING
from alata.http.middleware.maintenance_mode_middleware import MaintenanceModeMiddleware
self.app.fastapi.add_middleware(
MaintenanceModeMiddleware,
bypass_paths=MAINTENANCE_MODE.get("bypass_paths"),
)
if REQUEST_LOGGING.get("enabled", True):
from alata.http.middleware.request_logging_middleware import RequestLoggingMiddleware
self.app.fastapi.add_middleware(
RequestLoggingMiddleware,
exclude_paths=REQUEST_LOGGING.get("exclude_paths"),
slow_threshold=REQUEST_LOGGING.get("slow_request_threshold", 5.0),
)
# ... GZip, TrustedHost, CORS, IdentityMiddleware, RateLimitHeadersMiddlewareBecause the middleware stack is plain code in your provider, adding, removing, or reordering middleware never requires touching the framework.
add_middleware builds the stack outside-in: the last middleware added is the outermost and runs first on each request. The scaffold adds IdentityMiddleware after request logging so the acting user is already resolved by the time the log line is written, and RateLimitHeadersMiddleware last of all — it replays the rate limiter's X-RateLimit-* headers onto responses that endpoints construct themselves, and only the outermost middleware sees the final response.
Maintenance Mode
MaintenanceModeMiddleware returns a 503 Service Unavailable for every request while the application is in maintenance mode:
{ "message": "Service is currently undergoing maintenance. Please try again shortly." }The response carries a Retry-After: 60 header so well-behaved clients and crawlers back off.
Toggling Maintenance Mode
Use the project CLI:
./alata down # enter maintenance mode
./alata up # back to normalBoth commands are registered automatically by the framework's HTTP provider, so every Alata app has them.
How State Is Stored
Maintenance mode is a flag file: storage/framework/down in your project root. ./alata down creates it, ./alata up deletes it, and the middleware simply checks for its existence on each request. That means:
- It survives restarts and works across multiple workers on the same host — no database or cache involved.
- In an emergency you can toggle it without the CLI:
touch storage/framework/down/rm storage/framework/down. - The scheduler also respects the flag and skips due events while it exists (unless a task is marked to run even in maintenance mode).
Bypass Paths
Paths listed in MAINTENANCE_MODE["bypass_paths"] are served normally while the app is down. The default, ["/health"], keeps load-balancer probes green so your instances are not pulled out of rotation during a planned maintenance window. Matching is exact-path.
Request Logging
RequestLoggingMiddleware writes one log line per request through the logging system:
GET /api/v1/orders → 200 (0.042s) [user-123] rid=a1b2c3d4It logs the method, path, status code, time until the response starts, acting user (from request.state.user_id when the identity middleware has set it, otherwise -), and a request id.
Request IDs
The middleware reads the incoming X-Request-ID header — or generates a short id if absent — stores it on request.state.request_id, and sets X-Request-ID on responses for paths that are not excluded. Pass the header between services and you can trace a single request across your whole system.
Log Levels
The level is chosen from the outcome:
| Condition | Level |
|---|---|
Duration ≥ slow_request_threshold (default 5.0s) | WARNING, prefixed SLOW |
| Status ≥ 500 | ERROR |
| Status ≥ 400 | WARNING |
| Everything else | INFO |
Tuning
In config/middleware.py, REQUEST_LOGGING supports:
enabled— setFalseto skip registering the middleware entirely.exclude_paths— endpoints that are never logged (health checks,/docs, metrics). Excluded requests still haverequest.state.request_id, but this middleware does not add the response header for them.slow_request_threshold— seconds before a request is flaggedSLOW.
Writing Your Own Middleware
The scaffold uses plain ASGI middleware. Its identity middleware passes non-HTTP scopes through and resets request context when the request ends:
from starlette.datastructures import Headers
from starlette.types import ASGIApp, Receive, Scope, Send
from alata.context import user_id_context
class IdentityMiddleware:
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
headers = Headers(scope=scope)
identity = headers.get("X-User-Id") or headers.get("X-Guest-Id")
scope.setdefault("state", {})["user_id"] = identity or "anonymous"
if identity is None:
await self.app(scope, receive, send)
return
token = user_id_context.set(identity)
try:
await self.app(scope, receive, send)
finally:
user_id_context.reset(token)The scaffold reads identity headers for demonstration; it does not verify credentials. Replace this with validated session or token authentication before using these helpers to protect routes.
request.state.user_id always has a value. Leave user_id_context unset for anonymous callers so the rate limiter can use their client IP instead of grouping them under a shared "anonymous" key.
To add a response header, wrap the ASGI send callable:
import time
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
class TimingHeaderMiddleware:
def __init__(self, app: ASGIApp, header_name: str = "X-Elapsed"):
self.app = app
self.header_name = header_name
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
start = time.perf_counter()
async def send_response(message: Message) -> None:
if message["type"] == "http.response.start":
elapsed = time.perf_counter() - start
MutableHeaders(scope=message)[self.header_name] = f"{elapsed:.3f}"
await send(message)
await self.app(scope, receive, send_response)The header measures time until the response starts, including for streaming responses. BaseHTTPMiddleware remains supported for middleware that uses its dispatch API.
Registering It
Add it to the stack in your app's FastapiProvider.register():
from alata.http import FastapiProvider as HttpProvider
from app.http.middleware import TimingHeaderMiddleware
class FastapiProvider(HttpProvider):
def register(self):
super().register()
# ... built-in middleware ...
self.app.fastapi.add_middleware(TimingHeaderMiddleware)Pass constructor options as keyword arguments to add_middleware:
self.app.fastapi.add_middleware(TimingHeaderMiddleware, header_name="X-Response-Time")Follow the scaffold's convention and source those options from a dict in config/middleware.py so all tuning stays in one file.
Service providers can also implement a boot_http(app) hook — the kernel calls it with the FastAPI instance after all providers have booted. It is how framework packages attach their own routes and middleware, and it works just as well for reusable packages of your own.
Middleware runs on every request, including excluded and bypassed paths (each middleware handles its own exclusions). Keep middleware fast and non-blocking — no synchronous I/O — or every endpoint pays the cost.