gRPC Development
This skill covers best practices for building gRPC-based services and APIs using Protocol Buffers, including service design, streaming patterns, interceptors, security, and observability.
Workflow for Building a gRPC Service
- Define the service contract — Write
.proto files with service definitions, RPC methods, and message types following the style and naming conventions below.
- Generate language stubs — Run
protoc with the appropriate language plugin (e.g., protoc-gen-go-grpc, grpcio-tools) to produce server and client code.
- Implement the server — Create handler functions for each RPC method, register them with a gRPC server, and configure TLS, interceptors, and health checks.
- Implement the client — Create a channel to the server, instantiate the generated client stub, and call RPC methods with proper deadlines and error handling.
- Add interceptors — Wire in server and client interceptors for logging, authentication, metrics, and tracing.
- Write tests — Unit-test handlers with mocked dependencies; integration-test with a real gRPC connection.
- Deploy and observe — Enable distributed tracing (OpenTelemetry), structured logging, and metrics dashboards before going to production.
Core Principles
- gRPC uses Protocol Buffers as both its Interface Definition Language (IDL) and message interchange format
- Design services around the idea of defining methods that can be called remotely with their parameters and return types
- Prioritize type safety, performance, and backward compatibility
- Leave NO todos, placeholders, or missing pieces in the implementation
Protocol Buffer Best Practices
File Organization (1-1-1 Pattern)
- Structure definitions with one top-level entity (message, enum, or extension) per .proto file
- Correspond each .proto file to a single build rule
- This promotes small, modular proto definitions
- Benefits include simplified refactoring, improved build times, and smaller binary sizes
Message Design
- Use structured messages for extensibility - Protocol Buffers supports adding fields without breaking existing clients
- Be careful to use structs in places you may want to add fields later
- Don't re-use messages across RPCs - APIs may change over time, avoid coupling separate RPC calls tightly together
- Fields should always be independent of each other - don't have one field influence the semantic meaning of another
Field Guidelines
- Use descriptive field names with underscore_separated_names
- Reserve field numbers for deleted fields to prevent future conflicts
- Use
optional for fields that may not always be present
- Consider using
oneof when users need to choose between mutually exclusive options
Enum Best Practices
- Ensure the first value is always 0
- Use an "UNSPECIFIED" default value (e.g.,
STATUS_UNSPECIFIED = 0)
- Use prefixes to avoid naming collisions (e.g.,
ORDER_STATUS_CREATED vs STATUS_PENDING)
- Reserve enum values that are removed to prevent accidental reuse
Style Guidelines
- Keep line length to 80 characters
- Prefer double quotes for strings
- Package names should be in lowercase
- Use CamelCase (with initial capital) for message names
- Use underscore_separated_names for field names
- Use CamelCase for service and RPC method names
Service Design
RPC Patterns
- Unary RPC: Client sends single request, server responds with single response
- Server Streaming: Client sends request, server responds with stream of messages
- Client Streaming: Client sends stream of messages, server responds with single response
- Bidirectional Streaming: Both sides send streams of messages
Example: Proto Definition
syntax = "proto3";
package order.v1;
option go_package = "gen/order/v1;orderv1";
// OrderService manages customer orders.
service OrderService {
// Creates a new order and returns the created resource.
rpc CreateOrder(CreateOrderRequest) returns (CreateOrderResponse);
// Streams real-time status updates for an order.
rpc WatchOrder(WatchOrderRequest) returns (stream OrderStatus);
}
message CreateOrderRequest {
string customer_id = 1;
repeated OrderItem items = 2;
}
message CreateOrderResponse {
string order_id = 1;
OrderStatus status = 2;
}
message WatchOrderRequest {
string order_id = 1;
}
message OrderItem {
string product_id = 1;
int32 quantity = 2;
}
message OrderStatus {
string order_id = 1;
OrderState state = 2;
string updated_at = 3;
}
enum OrderState {
ORDER_STATE_UNSPECIFIED = 0;
ORDER_STATE_CREATED = 1;
ORDER_STATE_PROCESSING = 2;
ORDER_STATE_SHIPPED = 3;
ORDER_STATE_DELIVERED = 4;
}
Example: Go Server Implementation
package main
import (
"context"
"log"
"net"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "example.com/gen/order/v1"
)
type orderServer struct {
pb.UnimplementedOrderServiceServer
}
func (s *orderServer) CreateOrder(ctx context.Context, req *pb.CreateOrderRequest) (*pb.CreateOrderResponse, error) {
if req.GetCustomerId() == "" {
return nil, status.Error(codes.InvalidArgument, "customer_id is required")
}
orderID := "ord-" + time.Now().Format("20060102150405")
return &pb.CreateOrderResponse{
OrderId: orderID,
Status: &pb.OrderStatus{
OrderId: orderID,
State: pb.OrderState_ORDER_STATE_CREATED,
},
}, nil
}
func (s *orderServer) WatchOrder(req *pb.WatchOrderRequest, stream pb.OrderService_WatchOrderServer) error {
for i, state := range []pb.OrderState{
pb.OrderState_ORDER_STATE_PROCESSING,
pb.OrderState_ORDER_STATE_SHIPPED,
pb.OrderState_ORDER_STATE_DELIVERED,
} {
select {
case <-stream.Context().Done():
return stream.Context().Err()
case <-time.After(time.Duration(i) * time.Second):
if err := stream.Send(&pb.OrderStatus{
OrderId: req.GetOrderId(),
State: state,
UpdatedAt: time.Now().Format(time.RFC3339),
}); err != nil {
return err
}
}
}
return nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
srv := grpc.NewServer(
grpc.UnaryInterceptor(loggingUnaryInterceptor),
)
pb.RegisterOrderServiceServer(srv, &orderServer{})
log.Println("serving on :50051")
if err := srv.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
// loggingUnaryInterceptor logs each unary RPC call.
func loggingUnaryInterceptor(
ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
) (any, error) {
start := time.Now()
resp, err := handler(ctx, req)
log.Printf("method=%s duration=%s err=%v", info.FullMethod, time.Since(start), err)
return resp, err
}
API Design
- Design clear, intuitive service interfaces
- Group related methods in the same service
- Use meaningful method names that describe the action
- Document each RPC with comments describing behavior, parameters, and return values
Performance Optimization
Channel Management
- Reuse channels when working with gRPC
- Creating a gRPC channel is costly as it creates a new HTTP/2 connection
- Implement connection pooling for high-throughput scenarios
- Configure keepalive settings appropriately
Message Optimization
- Keep messages reasonably sized - large messages impact performance
- Consider streaming for large data transfers
- Use compression for bandwidth-constrained environments
- Avoid deeply nested message structures
Error Handling
Status Codes
- Use appropriate gRPC status codes (OK, INVALID_ARGUMENT, NOT_FOUND, etc.)
- Include meaningful error messages in status details
- Use rich error details for complex error scenarios
- Document expected error conditions in service definitions
Retry Logic
- Implement retry with exponential backoff for transient failures
- Use deadlines/timeouts for all RPC calls
- Handle UNAVAILABLE and RESOURCE_EXHAUSTED with retries
- Don't retry non-idempotent operations blindly
Security
Authentication
- Use TLS for transport security in production
- Implement per-RPC authentication using metadata/headers
- Support multiple authentication mechanisms (JWT, OAuth2, mTLS)
- Validate credentials on every request
Authorization
- Implement method-level access control
- Use interceptors for centralized authorization logic
- Validate all input data regardless of authentication status
- Follow the principle of least privilege
Interceptors and Middleware
Server Interceptors
- Use interceptors for cross-cutting concerns (logging, auth, metrics)
- Order interceptors carefully - execution order matters
- Keep interceptors focused on single responsibilities
- Handle errors gracefully within interceptors
Client Interceptors
- Add metadata (headers) for tracing and authentication
- Implement request/response logging
- Add automatic retry logic
- Collect client-side metrics
Testing
Unit Testing
- Mock gRPC services for isolated testing
- Test message serialization/deserialization
- Verify error handling paths
- Test interceptor logic independently
Integration Testing
- Test with real gRPC connections where possible
- Verify streaming behavior end-to-end
- Test timeout and cancellation scenarios
- Load test with realistic traffic patterns
Observability
Distributed Tracing
- Use OpenTelemetry for distributed tracing across service boundaries
- Propagate trace context in metadata
- Instrument both client and server sides
- Start spans for each RPC call
Metrics
- Track RPC latency histograms
- Monitor error rates by method and status code
- Count active connections and streams
- Alert on anomalies and SLA violations
Logging
- Use structured logging with consistent fields
- Log RPC method, duration, and status
- Include trace IDs for correlation
- Avoid logging sensitive data
Language-Specific Guidelines
Go
- Use the official
google.golang.org/grpc package
- Implement services as interface types
- Use context for cancellation and deadlines
- Leverage code generation with
protoc-gen-go-grpc
Python
- Use
grpcio and grpcio-tools packages
- Implement async services with
grpcio-aio for better concurrency
- Use type hints with generated stubs
- Handle blocking calls appropriately in async contexts
Node.js/TypeScript
- Use
@grpc/grpc-js (pure JavaScript implementation)
- Consider using
nice-grpc for better TypeScript support
- Leverage async/await patterns
- Use static codegen for type safety
1---2name: grpc-development3description: "Best practices for building high-performance services with gRPC and Protocol Buffers. Use when designing RPC services, defining protobuf schemas, implementing streaming APIs, setting up gRPC interceptors, or building cross-language service communication."4metadata:5 maintainer: Mindrally6 source: https://skillmd.com/skills/mindrally/grpc-development7 upstream: https://github.com/Mindrally/skills8---910# gRPC Development1112This skill covers best practices for building gRPC-based services and APIs using Protocol Buffers, including service design, streaming patterns, interceptors, security, and observability.1314## Workflow for Building a gRPC Service15161. **Define the service contract** — Write `.proto` files with service definitions, RPC methods, and message types following the style and naming conventions below.172. **Generate language stubs** — Run `protoc` with the appropriate language plugin (e.g., `protoc-gen-go-grpc`, `grpcio-tools`) to produce server and client code.183. **Implement the server** — Create handler functions for each RPC method, register them with a gRPC server, and configure TLS, interceptors, and health checks.194. **Implement the client** — Create a channel to the server, instantiate the generated client stub, and call RPC methods with proper deadlines and error handling.205. **Add interceptors** — Wire in server and client interceptors for logging, authentication, metrics, and tracing.216. **Write tests** — Unit-test handlers with mocked dependencies; integration-test with a real gRPC connection.227. **Deploy and observe** — Enable distributed tracing (OpenTelemetry), structured logging, and metrics dashboards before going to production.2324## Core Principles2526- gRPC uses Protocol Buffers as both its Interface Definition Language (IDL) and message interchange format27- Design services around the idea of defining methods that can be called remotely with their parameters and return types28- Prioritize type safety, performance, and backward compatibility29- Leave NO todos, placeholders, or missing pieces in the implementation3031## Protocol Buffer Best Practices3233### File Organization (1-1-1 Pattern)3435- Structure definitions with one top-level entity (message, enum, or extension) per .proto file36- Correspond each .proto file to a single build rule37- This promotes small, modular proto definitions38- Benefits include simplified refactoring, improved build times, and smaller binary sizes3940### Message Design4142- Use structured messages for extensibility - Protocol Buffers supports adding fields without breaking existing clients43- Be careful to use structs in places you may want to add fields later44- Don't re-use messages across RPCs - APIs may change over time, avoid coupling separate RPC calls tightly together45- Fields should always be independent of each other - don't have one field influence the semantic meaning of another4647### Field Guidelines4849- Use descriptive field names with underscore_separated_names50- Reserve field numbers for deleted fields to prevent future conflicts51- Use `optional` for fields that may not always be present52- Consider using `oneof` when users need to choose between mutually exclusive options5354### Enum Best Practices5556- Ensure the first value is always 057- Use an "UNSPECIFIED" default value (e.g., `STATUS_UNSPECIFIED = 0`)58- Use prefixes to avoid naming collisions (e.g., `ORDER_STATUS_CREATED` vs `STATUS_PENDING`)59- Reserve enum values that are removed to prevent accidental reuse6061## Style Guidelines6263- Keep line length to 80 characters64- Prefer double quotes for strings65- Package names should be in lowercase66- Use CamelCase (with initial capital) for message names67- Use underscore_separated_names for field names68- Use CamelCase for service and RPC method names6970## Service Design7172### RPC Patterns7374- **Unary RPC**: Client sends single request, server responds with single response75- **Server Streaming**: Client sends request, server responds with stream of messages76- **Client Streaming**: Client sends stream of messages, server responds with single response77- **Bidirectional Streaming**: Both sides send streams of messages7879### Example: Proto Definition8081```proto82syntax = "proto3";8384package order.v1;8586option go_package = "gen/order/v1;orderv1";8788// OrderService manages customer orders.89service OrderService {90 // Creates a new order and returns the created resource.91 rpc CreateOrder(CreateOrderRequest) returns (CreateOrderResponse);92 // Streams real-time status updates for an order.93 rpc WatchOrder(WatchOrderRequest) returns (stream OrderStatus);94}9596message CreateOrderRequest {97 string customer_id = 1;98 repeated OrderItem items = 2;99}100101message CreateOrderResponse {102 string order_id = 1;103 OrderStatus status = 2;104}105106message WatchOrderRequest {107 string order_id = 1;108}109110message OrderItem {111 string product_id = 1;112 int32 quantity = 2;113}114115message OrderStatus {116 string order_id = 1;117 OrderState state = 2;118 string updated_at = 3;119}120121enum OrderState {122 ORDER_STATE_UNSPECIFIED = 0;123 ORDER_STATE_CREATED = 1;124 ORDER_STATE_PROCESSING = 2;125 ORDER_STATE_SHIPPED = 3;126 ORDER_STATE_DELIVERED = 4;127}128```129130### Example: Go Server Implementation131132```go133package main134135import (136 "context"137 "log"138 "net"139 "time"140141 "google.golang.org/grpc"142 "google.golang.org/grpc/codes"143 "google.golang.org/grpc/status"144145 pb "example.com/gen/order/v1"146)147148type orderServer struct {149 pb.UnimplementedOrderServiceServer150}151152func (s *orderServer) CreateOrder(ctx context.Context, req *pb.CreateOrderRequest) (*pb.CreateOrderResponse, error) {153 if req.GetCustomerId() == "" {154 return nil, status.Error(codes.InvalidArgument, "customer_id is required")155 }156 orderID := "ord-" + time.Now().Format("20060102150405")157 return &pb.CreateOrderResponse{158 OrderId: orderID,159 Status: &pb.OrderStatus{160 OrderId: orderID,161 State: pb.OrderState_ORDER_STATE_CREATED,162 },163 }, nil164}165166func (s *orderServer) WatchOrder(req *pb.WatchOrderRequest, stream pb.OrderService_WatchOrderServer) error {167 for i, state := range []pb.OrderState{168 pb.OrderState_ORDER_STATE_PROCESSING,169 pb.OrderState_ORDER_STATE_SHIPPED,170 pb.OrderState_ORDER_STATE_DELIVERED,171 } {172 select {173 case <-stream.Context().Done():174 return stream.Context().Err()175 case <-time.After(time.Duration(i) * time.Second):176 if err := stream.Send(&pb.OrderStatus{177 OrderId: req.GetOrderId(),178 State: state,179 UpdatedAt: time.Now().Format(time.RFC3339),180 }); err != nil {181 return err182 }183 }184 }185 return nil186}187188func main() {189 lis, err := net.Listen("tcp", ":50051")190 if err != nil {191 log.Fatalf("failed to listen: %v", err)192 }193 srv := grpc.NewServer(194 grpc.UnaryInterceptor(loggingUnaryInterceptor),195 )196 pb.RegisterOrderServiceServer(srv, &orderServer{})197 log.Println("serving on :50051")198 if err := srv.Serve(lis); err != nil {199 log.Fatalf("failed to serve: %v", err)200 }201}202203// loggingUnaryInterceptor logs each unary RPC call.204func loggingUnaryInterceptor(205 ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,206) (any, error) {207 start := time.Now()208 resp, err := handler(ctx, req)209 log.Printf("method=%s duration=%s err=%v", info.FullMethod, time.Since(start), err)210 return resp, err211}212```213214### API Design215216- Design clear, intuitive service interfaces217- Group related methods in the same service218- Use meaningful method names that describe the action219- Document each RPC with comments describing behavior, parameters, and return values220221## Performance Optimization222223### Channel Management224225- Reuse channels when working with gRPC226- Creating a gRPC channel is costly as it creates a new HTTP/2 connection227- Implement connection pooling for high-throughput scenarios228- Configure keepalive settings appropriately229230### Message Optimization231232- Keep messages reasonably sized - large messages impact performance233- Consider streaming for large data transfers234- Use compression for bandwidth-constrained environments235- Avoid deeply nested message structures236237## Error Handling238239### Status Codes240241- Use appropriate gRPC status codes (OK, INVALID_ARGUMENT, NOT_FOUND, etc.)242- Include meaningful error messages in status details243- Use rich error details for complex error scenarios244- Document expected error conditions in service definitions245246### Retry Logic247248- Implement retry with exponential backoff for transient failures249- Use deadlines/timeouts for all RPC calls250- Handle UNAVAILABLE and RESOURCE_EXHAUSTED with retries251- Don't retry non-idempotent operations blindly252253## Security254255### Authentication256257- Use TLS for transport security in production258- Implement per-RPC authentication using metadata/headers259- Support multiple authentication mechanisms (JWT, OAuth2, mTLS)260- Validate credentials on every request261262### Authorization263264- Implement method-level access control265- Use interceptors for centralized authorization logic266- Validate all input data regardless of authentication status267- Follow the principle of least privilege268269## Interceptors and Middleware270271### Server Interceptors272273- Use interceptors for cross-cutting concerns (logging, auth, metrics)274- Order interceptors carefully - execution order matters275- Keep interceptors focused on single responsibilities276- Handle errors gracefully within interceptors277278### Client Interceptors279280- Add metadata (headers) for tracing and authentication281- Implement request/response logging282- Add automatic retry logic283- Collect client-side metrics284285## Testing286287### Unit Testing288289- Mock gRPC services for isolated testing290- Test message serialization/deserialization291- Verify error handling paths292- Test interceptor logic independently293294### Integration Testing295296- Test with real gRPC connections where possible297- Verify streaming behavior end-to-end298- Test timeout and cancellation scenarios299- Load test with realistic traffic patterns300301## Observability302303### Distributed Tracing304305- Use OpenTelemetry for distributed tracing across service boundaries306- Propagate trace context in metadata307- Instrument both client and server sides308- Start spans for each RPC call309310### Metrics311312- Track RPC latency histograms313- Monitor error rates by method and status code314- Count active connections and streams315- Alert on anomalies and SLA violations316317### Logging318319- Use structured logging with consistent fields320- Log RPC method, duration, and status321- Include trace IDs for correlation322- Avoid logging sensitive data323324## Language-Specific Guidelines325326### Go327328- Use the official `google.golang.org/grpc` package329- Implement services as interface types330- Use context for cancellation and deadlines331- Leverage code generation with `protoc-gen-go-grpc`332333### Python334335- Use `grpcio` and `grpcio-tools` packages336- Implement async services with `grpcio-aio` for better concurrency337- Use type hints with generated stubs338- Handle blocking calls appropriately in async contexts339340### Node.js/TypeScript341342- Use `@grpc/grpc-js` (pure JavaScript implementation)343- Consider using `nice-grpc` for better TypeScript support344- Leverage async/await patterns345- Use static codegen for type safety