gRPC Interceptors — Middleware for Cross-Cutting Concerns
In this tutorial, you will learn about grpc interceptors. We cover key concepts, practical examples, and best practices to help you master this topic.
gRPC interceptors are middleware functions that intercept RPC calls on the client or server, enabling cross-cutting concerns like logging, authentication, and metrics.
Server Interceptor
import grpc
import time
from grpc_interceptor import ServerInterceptor
class LoggingInterceptor(ServerInterceptor):
def intercept(self, method, request, context, method_name):
start = time.time()
try:
response = method(request, context)
duration = time.time() - start
print(f"[{method_name}] ok {duration:.3f}s")
return response
except Exception as e:
duration = time.time() - start
print(f"[{method_name}] error {duration:.3f}s: {e}")
raise
# Apply interceptor
server = grpc.server(
futures.ThreadPoolExecutor(max_workers=10),
interceptors=[LoggingInterceptor()]
)
Client Interceptor
class AuthInterceptor(grpc.UnaryUnaryClientInterceptor):
def __init__(self, token):
self.token = token
def intercept_unary_unary(self, continuation, client_call_details, request):
# Add auth metadata
metadata = [("authorization", f"Bearer {self.token}")]
new_details = client_call_details._replace(metadata=metadata)
return continuation(new_details, request)
# Apply to channel
channel = grpc.insecure_channel("localhost:50051")
auth_channel = grpc.intercept_channel(channel, AuthInterceptor("my-token"))
stub = device_pb2_grpc.DeviceServiceStub(auth_channel)
Common Mistakes
1. Not Using Interceptors for Common Logic
Auth, logging, Rate Limiting — these belong in interceptors, not scattered across every service method.
2. Blocking in Interceptors
Interceptors run on the call thread. Blocking operations (DB queries, external API calls) slow down all RPCs.
3. Not Propagating Context
If an interceptor modifies the context, ensure changes propagate to all subsequent interceptors and the handler.
4. Interceptor Order
Interceptors execute in order. Auth before logging. Logging before rate limiting. Plan your interceptor chain.
5. Not Handling Async Interceptors
Async gRPC requires async interceptors. Use aio versions for asynchronous services.
Practice Questions
- What is a gRPC interceptor?
- What are common interceptor use cases?
- How do you add authentication via interceptors?
- What is the interceptor execution order?
- How do async interceptors differ?
Answers:
- An interceptor is middleware that wraps RPC calls, executing code before and after the handler on server or client.
- Authentication, logging, metrics, rate limiting, request validation, error handling, tracing.
- Add an Authorization metadata header in a client interceptor. Verify it in a server interceptor and attach user to context.
- Interceptors execute in the order they are added to the interceptor list (first added, first executed).
- Async interceptors use
async defandawait. They work with gRPC's async IO (aio) API.
Mini Project
Build an interceptor chain for DodaTech's gRPC services. Include auth interceptor (JWT verification), logging interceptor (request/response logging with duration), rate limiting interceptor (per-user), and error handling interceptor (consistent error formatting).
What's Next
| Topic | Description |
|---|---|
| Auth | JWT and token-based auth |
| SSL/TLS | Transport security |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro