liminfo

gRPC Reference

Free reference guide: gRPC Reference

25 results

About gRPC Reference

The gRPC Reference is a comprehensive, searchable guide to building gRPC services using Protocol Buffers (proto3) and the Go gRPC library. It covers six major areas: Proto Definition (syntax declaration, message types, enum, oneof, map fields), Service (service/rpc definitions, protoc compilation commands, Go server setup with grpc.NewServer(), and client connection with grpc.Dial()), Message (field types including google.protobuf.Timestamp, repeated fields, nested messages, google.protobuf.Any), Streaming (server streaming, client streaming, bidirectional streaming, and stream.Send()/Recv() operations), Interceptor (UnaryServerInterceptor, StreamServerInterceptor, and metadata handling for authorization headers), and Error Handling (status.Error(), the full gRPC status code table, status.FromError(), errdetails for structured errors, and deadline/timeout patterns).

Backend engineers building microservices in Go, platform engineers designing internal RPC APIs, and developers migrating from REST to gRPC are the primary audience. The reference is grounded in the Go ecosystem: all server and client code examples use the google.golang.org/grpc package, the protoc-gen-go and protoc-gen-go-grpc plugins, and standard patterns like context-based deadlines and grpc.WithTransportCredentials(insecure.NewCredentials()) for local development. Production-ready patterns such as interceptor chains for logging and authentication are demonstrated with complete function signatures.

A key differentiator of this reference is its coverage of all four gRPC communication patterns in one place: unary RPC (request-response), server streaming (one request, stream of responses), client streaming (stream of requests, single response), and bidirectional streaming (concurrent request and response streams). The error handling section covers the complete set of gRPC status codes (from codes.OK to codes.Unauthenticated) with their numeric values, plus the advanced errdetails package for attaching structured field violation information to error responses.

Key Features

  • Proto3 syntax: syntax declaration with package and go_package option, message type definitions with field numbers, enum with UNSPECIFIED zero value, oneof for mutually exclusive fields, and map<key, value> field type
  • Service and RPC definition: unary, server streaming, client streaming, and bidirectional streaming RPC signatures in .proto SDL
  • protoc compilation command with --go_out and --go-grpc_out flags, paths=source_relative option, and source proto file path
  • Go server setup: net.Listen(), grpc.NewServer(), pb.RegisterXxxServer(), and s.Serve(lis) — the complete server bootstrap pattern
  • Go client setup: grpc.Dial() with insecure.NewCredentials() for local dev, pb.NewXxxClient() from the generated stub
  • All four streaming patterns with Go implementation: stream.Send(), stream.Recv(), io.EOF detection for client streaming, and concurrent bidirectional Chat example
  • Interceptor patterns: UnaryServerInterceptor with (ctx, req, info, handler) signature for logging/auth middleware, StreamServerInterceptor, and metadata.FromIncomingContext() for header extraction
  • Complete gRPC status code reference (OK, Cancelled, InvalidArgument, NotFound, AlreadyExists, PermissionDenied, Unauthenticated, Internal) with numeric codes, plus errdetails.BadRequest for field-level validation errors

Frequently Asked Questions

What is gRPC and how does it differ from REST?

gRPC is a high-performance RPC framework that uses Protocol Buffers for binary serialization over HTTP/2. Unlike REST, it has a strongly-typed schema defined in .proto files, supports four communication patterns (unary, server streaming, client streaming, bidirectional streaming), and generates client/server code automatically. It is significantly faster than JSON over HTTP/1.1 for inter-service communication.

What is the role of the proto3 field number?

Field numbers (e.g., string id = 1;) are used by Protocol Buffers to identify fields in the binary wire format, not the field names. Once a field number is used in a deployed schema, it must never be reassigned to a different field, as this would break binary compatibility with existing clients and servers. Use the reserved keyword to retire old field numbers.

What is the difference between server streaming and bidirectional streaming?

In server streaming RPC, the client sends a single request and receives a stream of responses (e.g., streaming log lines). In bidirectional streaming, both the client and server can send messages independently over the same connection at the same time (e.g., a chat or real-time collaborative editing session). Both use the stream keyword in the .proto definition.

How do gRPC interceptors work?

Interceptors are middleware functions added to grpc.NewServer() with grpc.UnaryInterceptor() or grpc.StreamInterceptor(). A UnaryServerInterceptor has the signature func(ctx, req, info, handler) (interface{}, error) and calls handler(ctx, req) to invoke the actual RPC. Interceptors are used for logging, authentication token validation, rate limiting, and tracing.

How do I send authentication tokens in gRPC?

Use gRPC metadata, which functions like HTTP headers. On the client side, create metadata with metadata.Pairs("authorization", "Bearer token123") and attach it to the context with metadata.NewOutgoingContext(ctx, md). On the server side, extract it with metadata.FromIncomingContext(ctx) inside your interceptor or resolver to validate the token.

What gRPC status code should I use for different error scenarios?

Use codes.NotFound (5) when a requested resource does not exist, codes.InvalidArgument (3) for malformed input, codes.PermissionDenied (7) when the user is authenticated but lacks access, codes.Unauthenticated (16) when no valid credentials were provided, codes.AlreadyExists (6) for duplicate creation attempts, and codes.Internal (13) for unexpected server-side failures.

How do I set a request timeout in gRPC?

Use context.WithTimeout(context.Background(), 5*time.Second) to create a context with a deadline, and pass it to the client call. If the deadline is exceeded, the client receives a codes.DeadlineExceeded error. Always defer cancel() to release resources. The server can also check ctx.Err() to detect if the client cancelled early.

How does protoc generate Go code from a .proto file?

Run protoc with the --go_out and --go-grpc_out flags pointing to your output directory, add --go_opt=paths=source_relative and --go-grpc_opt=paths=source_relative to preserve the directory structure, and specify your .proto file path. This generates two files: a .pb.go file with message types and a _grpc.pb.go file with the server interface and client stub.