gRPC Python Tutorial
I wrote this gRPC Python tutorial because the official docs show you how to say hello world but skip the parts that actually break in production. You need working patterns for schema evolution, deadline propagation, and wiring gRPC into an existing FastAPI stack without rewriting your HTTP layer. Below are the patterns I run in production across a handful of internal services.
How do I design Protobuf schemas that survive version changes?
Start every .proto file with syntax = "proto3"; and a unique package name. Use optional keywords for fields you might remove later; proto3 drops field presence for scalars unless you opt in. I reserve field numbers 1 through 10 for core identifiers and leave gaps. Never reuse a tag number. Never change a field type. If you need a new shape, add a new field with a new tag.
syntax = "proto3";
package user.v1;
option python_generic_services = true;
message User { string id = 1; string email = 2; optional string display_name = 3; // safe to drop later repeated string roles = 4; google.protobuf.Timestamp created_at = 5;}
service UserService { rpc GetUser(GetUserRequest) returns (User); rpc ListUsers(ListUsersRequest) returns (stream User); // server streaming rpc CreateUsers(stream CreateUserRequest) returns (CreateUsersResponse); // client streaming rpc Chat(stream ChatMessage) returns (stream ChatMessage); // bidirectional}
message GetUserRequest { string id = 1; }message ListUsersRequest { int32 page_size = 1; string page_token = 2; }message CreateUserRequest { string email = 1; string display_name = 2; }message CreateUsersResponse { int32 created = 1; }message ChatMessage { string user_id = 1; string text = 2; }Generate code with grpcio-tools. I pin the version in pyproject.toml and run generation in CI so the checked-in stubs match the container image.
python -m grpc_tools.protoc \ -I./proto \ --python_out=./generated \ --grpc_python_out=./generated \ ./proto/user/v1/user.protoCommit the generated/ folder. Do not regenerate at container start. It adds non-determinism and slows cold starts.
Implementing unary, server-streaming, client-streaming, and bidirectional RPCs
The generated *_pb2_grpc.py gives you a base servicer class. Subclass it and implement the four method signatures. Use async def everywhere. The standard library grpc.aio module handles the event loop integration.
import grpcfrom generated.user.v1 import user_pb2, user_pb2_grpcfrom google.protobuf import timestamp_pb2import datetimeimport uuid
class UserServiceServicer(user_pb2_grpc.UserServiceServicer): async def GetUser(self, request, context): # unary: single request, single response if request.id == "missing": await context.abort(grpc.StatusCode.NOT_FOUND, "user not found") return user_pb2.User( id=request.id, email=f"{request.id}@example.com", display_name="Test User", roles=["member"], created_at=timestamp_pb2.Timestamp(seconds=int(datetime.datetime.utcnow().timestamp())) )
async def ListUsers(self, request, context): # server streaming: single request, stream of responses for i in range(request.page_size): yield user_pb2.User( id=str(uuid.uuid4()), email=f"user{i}@example.com", display_name=f"User {i}", roles=["member"], created_at=timestamp_pb2.Timestamp(seconds=int(datetime.datetime.utcnow().timestamp())) )
async def CreateUsers(self, request_iterator, context): # client streaming: stream of requests, single response count = 0 async for req in request_iterator: # persist req.email, req.display_name here count += 1 return user_pb2.CreateUsersResponse(created=count)
async def Chat(self, request_iterator, context): # bidirectional: stream both ways async for msg in request_iterator: # echo back with a prefix yield user_pb2.ChatMessage(user_id="bot", text=f"echo: {msg.text}")
async def serve(): server = grpc.aio.server() user_pb2_grpc.add_UserServiceServicer_to_server(UserServiceServicer(), server) server.add_insecure_port("[::]:50051") await server.start() await server.wait_for_termination()
if __name__ == "__main__": import asyncio asyncio.run(serve())Client side looks similar. For streaming calls you iterate an async generator. Keep your stubs in a dependency injection container so you can mock them in tests.
Building a production-ready gRPC server with interceptors for auth and logging
Interceptors are middleware. They run on every RPC. I use one for structured logging, one for JWT validation, and one for promoting grpc-status-details-bin into rich error payloads.
import grpcimport timeimport structlogfrom typing import Callable, Awaitable
logger = structlog.get_logger()
class LoggingInterceptor(grpc.aio.ServerInterceptor): async def intercept_service(self, continuation, handler_call_details): handler = await continuation(handler_call_details) if handler.request_streaming or handler.response_streaming: return handler # streaming wrapping is more complex, skip for brevity
original_behavior = handler.unary_unary async def new_behavior(request, context): start = time.perf_counter() method = handler_call_details.method try: response = await original_behavior(request, context) logger.info("grpc_unary_complete", method=method, duration_ms=(time.perf_counter()-start)*1000) return response except grpc.RpcError as e: logger.warning("grpc_unary_error", method=method, code=e.code().name, details=e.details()) raise return grpc.unary_unary_rpc_method_handler( new_behavior, request_deserializer=handler.request_deserializer, response_serializer=handler.response_serializer, )
class AuthInterceptor(grpc.aio.ServerInterceptor): def __init__(self, public_key: str): self.public_key = public_key
async def intercept_service(self, continuation, handler_call_details): handler = await continuation(handler_call_details) # In reality, extract token from metadata, verify JWT, populate context.state # For demo, we just pass through return handlerWire them in serve():
server = grpc.aio.server(interceptors=[LoggingInterceptor(), AuthInterceptor(public_key="...")])Interceptors add latency. Keep them fast. Do not hit a database inside an interceptor. Cache the JWKS. If you need per-method auth checks, put that logic in the handler or a shared dependency.
Connecting gRPC services to FastAPI via grpc-gateway or async clients
You have two main paths. Run grpc-gateway as a sidecar proxy that translates REST to gRPC, or call the gRPC stubs directly from your FastAPI route handlers. I prefer direct async calls. It keeps the dependency graph visible and avoids an extra network hop.
from fastapi import APIRouter, Depends, HTTPExceptionimport grpcfrom generated.user.v1 import user_pb2, user_pb2_grpc
router = APIRouter()
async def get_grpc_stub() -> user_pb2_grpc.UserServiceStub: # In production, use a channel pool or singleton managed by lifespan channel = grpc.aio.insecure_channel("user-service:50051") try: yield user_pb2_grpc.UserServiceStub(channel) finally: await channel.close()
@router.get("/users/{user_id}")async def get_user(user_id: str, stub: user_pb2_grpc.UserServiceStub = Depends(get_grpc_stub)): try: user = await stub.GetUser(user_pb2.GetUserRequest(id=user_id)) return {"id": user.id, "email": user.email, "display_name": user.display_name} except grpc.RpcError as e: if e.code() == grpc.StatusCode.NOT_FOUND: raise HTTPException(status_code=404, detail="User not found") raise HTTPException(status_code=500, detail="Internal service error")
@router.post("/users/batch")async def create_users(emails: list[str], stub: user_pb2_grpc.UserServiceStub = Depends(get_grpc_stub)): async def request_gen(): for email in emails: yield user_pb2.CreateUserRequest(email=email) resp = await stub.CreateUsers(request_gen()) return {"created": resp.created}Manage the channel lifecycle in lifespan events. Reusing a single channel across requests is critical for performance. Creating a channel per request kills throughput. If you need grpc-gateway for external partners, run it as a separate deployment. It adds operational overhead but keeps your Python services clean.
Load testing and TLS/mTLS configuration for internal service mesh
Before you ship, load test. I use ghz (hey for gRPC). It speaks protobuf natively.
ghz --insecure \ --proto ./proto/user/v1/user.proto \ --call user.v1.UserService.GetUser \ -d '{"id": "test-123"}' \ -c 100 -n 10000 \ user-service:50051Watch p99 latency and error rates. gRPC uses HTTP/2 multiplexing. A single slow request can head-of-line block others on the same connection if you don’t tune flow control. Set grpc.max_receive_message_length and grpc.max_send_message_length on both client and server if you move large payloads.
For mTLS, generate certs with your internal CA (or step-ca). Mount them in the container. Configure the server credentials:
import grpcimport ssl
def load_credential(path: str) -> bytes: with open(path, "rb") as f: return f.read()
server_creds = grpc.ssl_server_credentials( [(load_credential("/certs/server.key"), load_credential("/certs/server.pem"))], root_certificates=load_credential("/certs/ca.pem"), require_client_auth=True)server.add_secure_port("[::]:50051", server_creds)Client side:
import grpc
creds = grpc.ssl_channel_credentials( root_certificates=load_credential("/certs/ca.pem"), private_key=load_credential("/certs/client.key"), certificate_chain=load_credential("/certs/client.pem"))channel = grpc.aio.secure_channel("user-service:50051", creds)Rotate certs before they expire. Automate this with cert-manager or a custom controller. Expired certs cause silent connection drops that look like network partitions.
Common pitfalls: deadline propagation, error handling, and versioning
Deadlines. gRPC deadlines are absolute timestamps, not timeouts. If service A calls B calls C, the deadline must propagate. The Python grpc.aio library does this automatically if you pass the context from the incoming call to the outgoing stub call. Do not create a new ClientCallDetails with a fresh timeout. Pass the metadata.
# Inside a handler calling another serviceasync def GetUser(self, request, context): # context contains the deadline from the caller # Pass it implicitly by using the same stub call pattern # Explicit propagation for metadata: metadata = list(context.invocation_metadata()) downstream_resp = await self.downstream_stub.SomeCall(req, metadata=metadata)Error handling. Use context.abort(code, details) for expected failures (NotFound, InvalidArgument). Reserve INTERNAL for actual bugs. Rich errors via google.rpc.Status protobuf let clients distinguish retryable vs non-retryable failures without parsing strings. I define a custom AppError exception that serializes to Status details.
Versioning. Never break a deployed .proto. Add new services (UserServiceV2) or new RPCs. Deprecate old ones with option deprecated = true; on the RPC. Run both versions in parallel during migration. If you must change a message, add a new field. The optional keyword is your friend for removable fields.
When not to use gRPC
Don’t reach for gRPC if your team has zero protobuf experience and the project ships in two weeks. The tooling tax is real. Don’t use it for public APIs consumed by browsers unless you run grpc-web or grpc-gateway. The browser support story is still rough. For simple internal CRUD, REST with OpenAPI is often faster to iterate on. gRPC pays off when you have high throughput, polyglot clients, complex streaming needs, or strict contract enforcement across service boundaries.
FAQ
How do I handle gRPC health checks in Kubernetes?
Implement the standard grpc.health.v1.Health service. The grpcio-health-checking package provides a servicer. Wire it to your readiness probe. It supports per-service health status so you can drain traffic from a single logical service while keeping the process alive.
Can I use gRPC with Python’s standard logging module?
Yes, but structured logging (JSON) is far more useful for distributed tracing. I use structlog with grpc interceptors to bind trace_id and span_id from incoming metadata to every log line. See Fix SQLAlchemy Memory Leaks in FastAPI: Sessions & Pooling for how I structure logging context in long-running async processes.
What is the difference between grpcio and grpcio-tools?
grpcio is the runtime. grpcio-tools contains protoc plugins for code generation. You only need grpcio-tools in your build/CI environment, not in the final runtime image. Keep your production image lean.
How do I test gRPC services without a running server?
Use grpc_testing (part of grpcio-testing) for in-memory server simulation. It executes handlers directly without network I/O. It’s fast and deterministic. For integration tests, spin up the real server in a test container using testcontainers-python.
Key Takeaways
- Pin
grpcio-toolsversion and commit generated stubs to avoid drift. - Use
async defhandlers withgrpc.aiofor native asyncio integration. - Interceptors are for cross-cutting concerns: auth, logging, metrics. Keep them fast.
- Reuse gRPC channels. Create one per process lifetime, not per request.
- Propagate deadlines via context metadata. Do not invent new timeouts per hop.
- Version by adding, never by changing. Run v1 and v2 simultaneously during migrations.
- Load test with
ghzbefore shipping. Watch for head-of-line blocking on multiplexed streams.
Working on something similar?
If you're building backend or AI systems and want a second set of senior eyes, let's talk.