Understanding gRPC Fundamentals

1. Understanding gRPC Architecture

gRPC is a high-performance, open-source RPC framework built on HTTP/2 using Protocol Buffers as the interface definition language and on-the-wire format. A client invokes methods on a generated stub as if they were local; the framework handles serialization, network transport, multiplexing, and deserialization.

LayerResponsibilityComponent
IDLService & message contract.proto files
CodegenStub & skeleton generationprotoc, language plugins
SerializationBinary message encodingProtocol Buffers
TransportMultiplexed framing & flow controlHTTP/2
ChannelConnection abstractionClient channel / server
SecurityAuth & encryptionTLS, credentials, interceptors
Client App                              Server App
   │                                       │
[Stub] ─proto─► [Marshal] ─HTTP/2─► [Unmarshal] ─► [Service Impl]
   ▲                                                     │
   └────────── response stream ◄────────── [Marshal] ◄───┘
      

2. Understanding HTTP/2 Benefits

FeatureBenefit for gRPC
MultiplexingMany concurrent RPCs over a single TCP connection
Binary framingCompact, fast to parse vs HTTP/1.1 text
Header compression (HPACK)Reduces metadata overhead per call
Server push / streamsEnables true bidirectional streaming
Flow controlPer-stream backpressure
TLS by defaultEncrypted transport with ALPN

3. Comparing gRPC vs REST

AspectgRPCREST/JSON
TransportHTTP/2 onlyHTTP/1.1 or HTTP/2
PayloadProtobuf binaryJSON text
ContractStrongly typed .protoOpenAPI (optional)
StreamingUnary, server, client, bidiRequest/response (SSE/WS for stream)
Browser supportVia gRPC-Web proxyNative
Performance~5–10× faster, smaller payloadsSlower, larger payloads
Toolinggrpcurl, reflection, codegencURL, Postman, Swagger
Best forMicroservices, polyglot internalsPublic APIs, browsers

4. Understanding Protocol Buffers

PropertyValue
TypeLanguage-neutral binary serialization format
Current versionproto3 (recommended) 2026
SchemaRequired — defined in .proto files
Wire formatTag-length-value with varint encoding
EvolutionField numbers (not names) define identity

5. Understanding RPC Communication Patterns

PatternClient → ServerServer → ClientUse Case
Unary1 message1 messageStandard request/response
Server streaming1 messageN messagesFeed, large result sets
Client streamingN messages1 messageUploads, aggregation
BidirectionalN messagesN messagesChat, real-time sync

6. Understanding gRPC Service Definition

ElementSyntaxPurpose
serviceservice Name { ... }Groups related RPCs
rpcrpc Method(Req) returns (Res);Unary method
stream (req)rpc M(stream Req) returns (Res);Client streaming
stream (res)rpc M(Req) returns (stream Res);Server streaming
bidirpc M(stream Req) returns (stream Res);Bidirectional

Example: Minimal service definition

syntax = "proto3";
package user.v1;
option go_package = "example.com/api/user/v1;userv1";

service UserService {
  rpc GetUser(GetUserRequest) returns (User);
  rpc ListUsers(ListUsersRequest) returns (stream User);
}

message GetUserRequest { string id = 1; }
message User { string id = 1; string email = 2; }
message ListUsersRequest { int32 page_size = 1; }

7. Understanding Wire Format

ComponentEncodingNotes
Tagvarint = (field_number << 3) | wire_typeIdentifies field
Wire types0=varint, 1=64-bit, 2=length-delim, 5=32-bitDefines length parsing
Varint7 bits/byte, MSB=continuationSmall ints = 1 byte
ZigZagUsed by sint32/sint64Efficient negative numbers
gRPC frame1-byte flag + 4-byte length + payloadPlus HTTP/2 framing

8. Understanding Channel Abstraction

ConceptDescription
ChannelClient-side connection abstraction to a server
SubchannelPer-address transport managed by the channel
ResolverTranslates target URI into address list
Load balancerPicks subchannel for each RPC
ReusableOne channel → many concurrent RPCs
Note: Create channels once and reuse them. Creating a new channel per RPC defeats HTTP/2 multiplexing and causes massive overhead.

9. Understanding Stub Generation

ArtifactSideRole
Stub / ClientClientLocal proxy invoking RPCs
Server / SkeletonServerBase type to implement service
Message typesBothStrongly typed DTOs
DescriptorsBothUsed by reflection & tooling

10. Understanding gRPC Ecosystem

ToolPurpose
protocProtocol Buffer compiler
Buf MODERNLinting, breaking-change detection, build
grpcurlcURL-like CLI for gRPC
grpc-gatewayGenerates REST/JSON ↔ gRPC proxy
gRPC-WebBrowser support via Envoy proxy
EnvoyL7 proxy with native gRPC support
protoc-gen-validateGenerates field validation
OpenTelemetryTracing & metrics instrumentation