Lesson 5 of 9 · 22m
Interceptors for Cross-Cutting Behavior Without Magic
Put authentication, logging, validation, metrics, and error mapping in predictable interceptor layers while preserving handler clarity.
Interceptors are where good gRPC services centralize policy — and where bad ones hide all behavior. The rule I give new hires is simple: if every RPC needs the concern, an interceptor is a candidate; if only one workflow needs it, keep it in the handler. Cross-cutting should mean boring and visible, not magical.
The interceptor pipeline
A server-side interceptor wraps each call:
class RequestIdInterceptor(grpc.aio.ServerInterceptor):
async def intercept_service(self, continuation, handler_call_details):
handler = await continuation(handler_call_details)
return handlerReal implementations differ by language, but the shape is consistent: inspect metadata, invoke the next layer, observe or transform the result. Ordering matters. Authentication must usually run before tenant resolution; logging must wrap both; error mapping often belongs near the boundary.
Good interceptor candidates
authentication and principal construction
request IDs and trace propagation
metrics and structured access logs
panic/exception-to-status mapping
schema-level validation hooks
rate limiting and quota checks
deadline enforcement guardsEach should have a narrow contract. If your logging interceptor starts mutating business objects, the pipeline is now an application layer nobody can test.
Do not hide authorization policy
Authentication can be centralized. Authorization often cannot. Knowing that a caller is user:42 is generic; knowing whether user:42 may void invoice 10492 is domain logic. Put coarse checks in interceptors if needed, but object-level policy belongs near the domain query where tenant and relationship context are available.
Client interceptors are operational leverage
On the client side, interceptors can attach credentials, propagate tracing, enforce deadlines, and standardize retry metadata:
channel = grpc.aio.insecure_channel(
"billing.internal:443",
interceptors=[AuthInterceptor(), DeadlineInterceptor(seconds=2.0)],
)This prevents every call site from inventing its own partial behavior. It also creates a single place to audit how credentials and tenant context propagate.
Streaming interceptors are harder
A unary interceptor sees one request and one response. A streaming interceptor sees a state machine. Counting messages, enforcing limits, or measuring duration requires wrapping iteration carefully. Do not assume code written for unary calls understands cancellation or half-close behavior.
Observability beats convenience
Expose interceptor order in documentation and startup configuration. When production misbehaves, you need to know whether validation ran before authentication, whether metrics saw aborted streams, and which layer returned the status. Hidden convenience becomes debugging fog.
Field notes
- Never silently swallow a status and replace it with
INTERNAL; preserve cause in server logs. - Interceptors should be cheap. Rejecting every call after a downstream query is expensive policy placement.
- Avoid reading large streaming payloads merely to log them.
- Unit test interceptors independently, then integration test the final order.
- If an interceptor has workflow-specific branching, that logic probably belongs in the service.
Was this lesson helpful?