ARCHIVED from builddistributedsystem.com on 2026-04-28 — URL: https://builddistributedsystem.com/tracks/networker/tasks/task-5-3-4-grpc-interceptors
TASK

Implementation

Build a gRPC interceptor pipeline. Interceptors are middleware that wrap gRPC handler calls, running logic before and after the actual service method.

Interceptor chain: logging -> auth -> rate_limit -> handler

Implement handlers:

Request:  {"type": "grpc_call", "msg_id": 1, "service": "KeyValue", "method": "Get", "request": {"key": "k1"}, "metadata": {"authorization": "Bearer valid_token"}}
Response: {"type": "grpc_call_ok", "in_reply_to": 1, "status": "OK", "interceptors_applied": ["logging", "auth", "rate_limit"], "response": {"key": "k1", "value": "v1", "found": true}}

Request:  {"type": "grpc_call", "msg_id": 2, "service": "KeyValue", "method": "Get", "request": {"key": "k1"}, "metadata": {}}
Response: {"type": "grpc_call_ok", "in_reply_to": 2, "status": "UNAUTHENTICATED", "interceptor_failed": "auth"}

Request:  {"type": "grpc_interceptor_stats", "msg_id": 3}
Response: {"type": "grpc_interceptor_stats_ok", "in_reply_to": 3, "stats": {
    "total_requests": 2, "auth_failures": 1, "rate_limited": 0
}}

Sample Test Cases

Authenticated request passes all interceptorsTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"grpc_call","msg_id":2,"service":"KeyValue","method":"Put","request":{"key":"k1","value":"v1"},"metadata":{"authorization":"Bearer valid_token"}}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
Missing auth token fails at auth interceptorTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"grpc_call","msg_id":2,"service":"KeyValue","method":"Get","request":{"key":"k1"},"metadata":{}}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "grpc_call_ok", "in_reply_to": 2, "status": "UNAUTHENTICATED", "interceptor_failed": "auth", "msg_id": 1}}

Hints

Hint 1
Interceptors are middleware for gRPC calls, similar to HTTP middleware
Hint 2
They run before and after the actual handler
Hint 3
Chain multiple interceptors: logging -> auth -> rate_limit -> handler
Hint 4
Auth interceptor checks metadata for a valid token
Hint 5
Rate limiter uses a token bucket per client IP
OVERVIEW

Theoretical Hub

Concept overview coming soon

Key Concepts

interceptormiddlewareauthenticationrate limitingrequest pipeline
main.py
python
Build gRPC Interceptors for Logging, Auth, and Rate Limiting - The Networker | Build Distributed Systems