Skip to content

About

A single Python project that demonstrates every major gRPC communication pattern, cross-cutting concern, and operational feature. Works as a learning reference and as a template for production services.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

gRPC zero to hero

A single Python project that demonstrates every major gRPC communication pattern, cross-cutting concern, and operational feature. Works as a learning reference and as a template for production services.

Stack: Python 3.12+, grpcio (async grpc.aio server, both sync and async clients), proto3, uv, pytest.

Project layout

grpc-zero-to-hero
├── Dockerfile
├── README.md
├── certs
├── client
├── docker-compose.yml
├── generated
├── grpc-endpoints-on-postman.png
├── grpc_zero_to_hero.egg-info
├── proto
├── pyproject.toml
├── scripts
├── server
├── tests
└── uv.lock

Architecture Diagram

End-to-end request flow through the gRPC system:

flowchart TB
    subgraph Host Machine
        CLIENT[Client App\nclient/main.py]
    end

    CLIENT -->|Port 50051\nHTTP/2| SERVER

    subgraph gRPC Server
        subgraph Interceptors
            LOGGING[Request Logging]
            AUTH[Auth Interceptor]
            METRICS[Metrics Interceptor]
            LOGGING --> AUTH --> METRICS
        end

        SERVER[grpc.aio Server\nserver/main.py]
        SERVER --> LOGGING

        subgraph Services
            INV[InventoryService\nUnary + Streaming RPCs]
            STR[StreamingService\nBidi + Server/Client Streaming]
        end

        METRICS --> INV
        METRICS --> STR

        subgraph Operational
            HEALTH[Health Check]
            REFLECT[Server Reflection]
            CHANNELZ[Channelz]
        end
    end

    subgraph Proto Definitions
        PROTO[proto/*.proto] -->|generate_protos.sh| STUBS[generated/*_pb2.py]
    end

    STUBS -.->|used by| CLIENT
    STUBS -.->|used by| SERVER
Loading

Setup

uv venv --python 3.13           # create virtual environment for python 3.13
source .venv/bin/activate       # activate the virtual environment
uv sync                       # install everything (incl. dev deps)
./scripts/generate_protos.sh  # regenerate generated/ from proto/ (checked in)
./scripts/gen_certs.sh        # local CA + server/client certs (for TLS demos)

Quick start

uv run python -m server.main            # terminal 1
uv run python -m client.main            # terminal 2: runs most demos in order
uv run pytest                           # 36 tests, in-process server, ~2s

Every demo is also runnable standalone: uv run python -m client.demos.<name>.

Server Reflection

The server enables gRPC Server Reflection out of the box, so tools like Postman, grpcurl, and Evans can discover every service and method without importing .proto files.

# server/main.py
reflection.enable_server_reflection(service_names, server)

To test with Postman:

  1. Open Postman → New → gRPC
  2. Enter the server URL: localhost:50051
  3. Select a method from the auto-discovered list and click Invoke

gRPC endpoints discovered via Server Reflection in Postman

Feature map

Each row is a claim you can verify by running the command against uv run python -m server.main (plus the listed server flags).

Core RPC patterns

Feature Where Demo command
Unary RPC server/services/inventory.py uv run python -m client.demos.unary
Server streaming InventoryService.ListItems, StreamingService.StreamPrices uv run python -m client.demos.server_streaming
Client streaming StreamingService.UploadTelemetry, InventoryService.BulkCreateItems uv run python -m client.demos.client_streaming
Bidirectional streaming (independent read/write) StreamingService.Chat uv run python -m client.demos.bidi_streaming
Async implementation (grpc.aio) entire server/, all async demos any demo above
Sync API variants of all four patterns client/demos/sync_patterns.py uv run python -m client.demos.sync_patterns

Protocol Buffers

Feature Where
proto3, field numbering + reserved (versioning strategy) proto/common/v1/types.proto (Pagination)
Nested messages, enums, oneof, maps, repeated proto/inventory/v1/inventory.proto (Item)
Timestamp, Duration common/v1/types.proto (AuditInfo), streaming/v1/streaming.proto
Empty InventoryService.DeleteItem
Any Item.vendor_extension; packed/unpacked in client.demos.unary
FieldMask partial updates InventoryService.UpdateItem; demoed in client.demos.unary
Multiple proto files, cross-package imports inventory.proto imports common/v1/types.proto
Codegen pipeline scripts/generate_protos.sh -> generated/

Errors and status

Feature Where Demo command
Standard status codes (NOT_FOUND, INVALID_ARGUMENT, ALREADY_EXISTS, DEADLINE_EXCEEDED, UNAVAILABLE, UNIMPLEMENTED, UNAUTHENTICATED, CANCELLED) server/errors.py, services, tests/test_errors.py uv run python -m client.demos.errors
Rich error details (google.rpc.Status + grpcio-status) server/errors.py same
Custom structured error detail proto proto/common/v1/errors.proto (ErrorDetail, incl. retryable hint) same
Client retry vs fail-fast per code RETRY_HINTS table in client/demos/errors.py same

Metadata, deadlines, context

Feature Where Demo command
Custom metadata: headers out, initial + trailing metadata back StreamingService.Echo echoes x-request-id in trailers uv run python -m client.demos.metadata_deadlines
Per-call deadlines same demo same
Deadline propagation across chained calls StreamingService._chained_echo forwards context.time_remaining() same (send chain: prefix)
Client-side cancellation same demo + tests/test_metadata_deadlines.py same
Server-side handling of cancellation StreamPrices catches asyncio.CancelledError same

Interceptors

Feature Where Demo command
Client: logging + request-id injection client/interceptors/logging.py uv run python -m client.demos.interceptors_demo
Client: auth token injection (all 4 RPC kinds) client/interceptors/auth.py same
Client: retry with exponential backoff + jitter client/interceptors/retry.py same
Server: request logging with request-id contextvar server/interceptors/logging.py watch server logs during any demo
Server: bearer-token auth validation server/interceptors/auth.py start server with --auth-token secret123
Server: metrics collection (per-method call/status counts) server/interceptors/metrics.py logged when the server shuts down (Ctrl-C)
Structured logs correlated by request id RequestIdFilter in server/main.py any demo; grep the shared rid=

Note the grpc.aio gotcha documented in client/interceptors/auth.py: the channel sorts each interceptor instance into exactly one category, so an interceptor class must not implement more than one RPC kind.

Security

Feature Where Demo command (server flags first)
Server TLS scripts/gen_certs.sh, server/main.py --tls / uv run python -m client.demos.tls
Mutual TLS _server_credentials(mtls=True) --mtls / uv run python -m client.demos.tls --mtls
Bearer token via metadata interceptor client/interceptors/auth.py --tls --auth-token secret123 / uv run python -m client.demos.auth_tokens
Channel-level vs per-RPC credentials client/demos/auth_tokens.py same

Discovery and load balancing

Feature Where Demo command
Client-side round_robin over multiple backends client/demos/load_balancing.py see module docstring (3 local servers, ipv4: target)
DNS-based name resolution same docker compose up --build (dials dns:///server:50051)
Keepalive + max message size channel options SERVER_OPTIONS in server/main.py, default_options() in client/channel.py applied on every channel
Retry policy via service config JSON RETRY_SERVICE_CONFIG in client/channel.py uv run python -m client.demos.retry_config

Operational features

Feature Where Demo command
Health checking protocol (grpc.health.v1) server/main.py uv run python -m client.demos.health_reflection
Server reflection same same, or grpcurl -plaintext localhost:50051 list
channelz introspection same same demo prints server call counts
Graceful shutdown (health -> NOT_SERVING, drain, metrics dump) serve() in server/main.py Ctrl-C a running server; tests/test_health_reflection.py

Testing and load

Feature Where
In-process test server on a free port tests/conftest.py
Per-pattern tests tests/test_unary.py, tests/test_streaming_patterns.py
Error-path tests per status code tests/test_errors.py
Interceptor tests (auth rejection incl. streaming shape, metadata propagation) tests/test_interceptors.py, tests/test_metadata_deadlines.py
Load test (latency percentiles + streaming throughput) uv run python scripts/load_test.py

About

A single Python project that demonstrates every major gRPC communication pattern, cross-cutting concern, and operational feature. Works as a learning reference and as a template for production services.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages