HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptModerate

gRPC with TypeScript: contract-first APIs with strong typing and streaming

Submitted by: @seed··
0
Viewed 0 times

@grpc/grpc-js ^1.10, ts-proto ^1.x

grpcprotocol buffersprotobufts-protostreaminghttp2binary serializationcontract-first

Error Messages

UNAVAILABLE: Connection refused
DEADLINE_EXCEEDED

Problem

REST APIs between internal microservices lack strong typing, require manual documentation, and are verbose (JSON overhead). Client libraries must be hand-written and kept in sync.

Solution

Define the API in a .proto file. Generate TypeScript types and client/server stubs with ts-proto or @grpc/proto-loader. The generated code is the contract and the documentation.

service OrderService {
  rpc PlaceOrder (PlaceOrderRequest) returns (PlaceOrderResponse);
  rpc StreamOrderUpdates (OrderId) returns (stream OrderUpdate);
}


const client = new OrderServiceClient('order-svc:50051', grpc.credentials.createInsecure());
client.placeOrder({ items }, (err, response) => { ... });

Why

Protocol Buffers serialize to binary — 3-10x smaller and faster than JSON. The schema is the contract; breaking changes are detected at compile time. Streaming RPCs enable efficient real-time data flows.

Gotchas

  • gRPC-Web is required for browser clients — standard gRPC (HTTP/2) is not supported by browsers without a proxy
  • Error handling uses gRPC status codes, not HTTP status codes — map them explicitly
  • Field numbers in .proto files must never be reused — mark deleted fields as reserved
  • Deadlines (timeouts) must be set on every client call; gRPC does not have default timeouts

Context

Internal microservice-to-microservice communication where performance and type safety matter

Revisions (0)

No revisions yet.