How-To Guide

How to Use the Four gRPC Streaming Modes

Pick unary, server-streaming, client-streaming, or bidirectional RPC by data shape, wire them with deadlines and flow control, and test partial results.

On this page

  1. Introduction
  2. Match the mode to the data
  3. Define the proto contract
  4. Implement the server side
  5. Client calls, deadlines, and cancellation
  6. Flow control and slow consumers
  7. Test partial results and cancellation
  8. Common pitfalls
  9. Conclusion

Introduction

gRPC offers four shapes of remote procedure, and choosing among them by taste rather than data shape produces awkward APIs: polling loops emulating streams, streams that carry exactly one message, and uploads chunked through unary calls that were never meant for it. The four modes are unary, one request to one response; server-streaming, one request to a sequence of responses; client-streaming, a sequence of requests to one response; and bidirectional, two independent message streams over one call. Each maps to a natural data shape, and each carries distinct obligations for deadlines, cancellation, and error semantics that do not exist in the unary world. This tutorial defines all four in one proto contract, implements the server and client sides in Go, covers the flow-control and deadline behavior that makes streams safe under load, and finishes with the tests that matter: partial results, mid-stream errors, and client cancellation.

Match the mode to the data

Mode selection is a data-shape question. Unary fits the classic command-and-query: fetch a record, submit a form, run a short computation. Server-streaming fits result sets and subscription flows: a search returning thousands of hits, a log tail, a progress feed, or a query whose answer is produced incrementally. The client gets first results before generation completes, which converts total latency into time-to-first-item. Client-streaming fits uploads and aggregation: a file transfer, a stream of measurements, a batch assembled from many sources, all summarized by one final response. Bidirectional fits genuine dialogue: chat relay, collaborative editing synchronization, or control channels where either side initiates. The anti-patterns are equally clear: server-streaming that always sends exactly one message is unary with extra machinery; unary calls fired in a loop to simulate upload pay per-call overhead and lose ordering guarantees. When a mode is chosen honestly, the API reads like the problem.

Define the proto contract

The proto file declares all four modes in one service. The distinction is purely in the stream keyword placement, which makes it easy to read and easy to get subtly wrong, so treat the contract as documentation of intended semantics.

syntax = "proto3";
package telemetry.v1;

service Ingest {
 rpc GetSnapshot(SnapshotRequest) returns (Snapshot);

 rpc Watch(WatchRequest) returns (stream Event);

 rpc Upload(stream Chunk) returns (UploadSummary);

 rpc Relay(stream ClientMessage) returns (stream ServerMessage);
}

message WatchRequest { string device_id = 1; int64 since_seq = 2; }
message Event { int64 seq = 1; string kind = 2; bytes payload = 3; }
message Chunk { int64 offset = 1; bytes data = 2; }
message UploadSummary { int64 total_bytes = 1; string digest = 2; }

Naming communicates obligations: Watch carries a since_seq for resumption, Chunk carries an offset so the server can detect gaps, and every Event carries a sequence number so clients can detect loss. These fields are the difference between a stream that is merely connected and one that is correct after a reconnect. Document cancellation and partial-result semantics in the service comments, because code generation erases the informal contract otherwise.

Implement the server side

The Go server implements each mode with the same skeleton: a context that carries cancellation, and a stream object for send and receive. The discipline is to check ctx.Done between messages and release everything on exit.

func (s *server) Watch(req *telemetryv1.WatchRequest, stream telemetryv1.Ingest_WatchServer) error {
 events := s.broker.Subscribe(req.DeviceId, req.SinceSeq)
 defer events.Close()
 for {
  select {
  case <-stream.Context().Done():
   return nil
  case ev, ok := <-events.C():
   if !ok {
    return nil
   }
   if err := stream.Send(toProto(ev)); err != nil {
    return err
   }
  }
 }
}

func (s *server) Upload(stream telemetryv1.Ingest_UploadServer) error {
 var total int64
 hasher := sha256.New()
 for {
  chunk, err := stream.Recv()
  if err == io.EOF {
   return stream.SendAndClose(&telemetryv1.UploadSummary{
    TotalBytes: total, Digest: hex.EncodeToString(hasher.Sum(nil))})
  }
  if err != nil {
   return err
  }
  if chunk.Offset != total {
   return status.Errorf(codes.InvalidArgument, "gap at %d, want %d", chunk.Offset, total)
  }
  total += int64(len(chunk.Data))
  hasher.Write(chunk.Data)
 }
}

The offset check in Upload is load-bearing: it converts a silently corrupted upload into an explicit InvalidArgument, and the digest in the summary lets the client verify integrity end to end. Errors mid-stream are protocol-level statuses; the client sees the stream terminate with that status rather than a partial success presented as complete.

Client calls, deadlines, and cancellation

Every streaming client needs a deadline decision. For bounded work like Upload, a fixed deadline fits. For unbounded subscriptions like Watch, a deadline is wrong because the whole point is to run indefinitely; instead the client relies on cancellation and on a health signal in the message stream, and the server can enforce a maximum session age by ending the stream with a specific status the client treats as a reconnect trigger. The client below sets a deadline on a bounded call and cancels an unbounded one on process shutdown.

ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
summary, err := client.Upload(ctx)
if err != nil { return err }
for chunk := range chunks {
 if err := summary.Send(chunk); err != nil { cancel(); return err }
}
if err := summary.CloseSend(); err != nil { return err }
final, err := summary.CloseAndRecv()

CloseSend matters for client-streaming: it is the half-close that tells the server no more input is coming, without which Upload never reaches its summary. For server-streaming, treat io.EOF as the normal end and a status error as a failure, and distinguish them explicitly in error handling, because conflating the two turns truncated results into silent successes.

Flow control and slow consumers

gRPC rides on HTTP/2, which gives every stream an independent flow-control window. A fast server streaming to a slow client does not flood the connection: send calls block when the client window fills, and other streams on the same channel continue unaffected. This is the transport-level protection, and it composes with an application-level concern: a blocked Send pins a goroutine and whatever memory the producer has already materialized. For high-volume streams, bound the in-flight work, produce messages lazily rather than materializing the full result set, and size the channel between producer and sender so a slow consumer applies backpressure to the source. On the client side, the mirror-image failure is a consumer that stops Recv-ing: the window fills, the server blocks, and the session stalls until cancellation. A read deadline or an application-level keepalive in the message stream distinguishes a quiet stream from a dead one, which matters for subscriptions that may legitimately go minutes without data.

Test partial results and cancellation

Streaming APIs fail in ways unary APIs cannot, and the test suite must target those specifically. Partial delivery: make the handler error after N messages and assert the client receives N messages followed by the error status, not a success with truncation. Client cancellation: cancel the context mid-stream and assert the server handler observes Done and returns within a bounded interval, which catches producers that ignore cancellation and leak goroutines. Slow consumer: a client that reads one message per hundred milliseconds should not exhaust server memory, which validates bounded production. Resume correctness: kill a Watch stream, reconnect with the last sequence number, and assert the replay begins exactly there with no duplicates or gaps. These four tests, run against a real loopback channel rather than mocks, encode nearly the entire streaming contract.

func TestWatchCancellation(t *testing.T) {
 ctx, cancel := context.WithCancel(context.Background())
 stream, _ := client.Watch(ctx, &telemetryv1.WatchRequest{DeviceId: "d1"})
 go func() { time.Sleep(50 * time.Millisecond); cancel() }()
 _, err := stream.Recv()
 if !errors.Is(err, context.Canceled) {
  t.Fatalf("want canceled, got %v", err)
 }
}

Common pitfalls

  • Streaming exactly one message. A server-stream that always emits one item is unary complexity with nothing gained; change the mode.
  • Ignoring cancellation in handlers. Abandoned streams pin goroutines and buffers; select on Done in every loop.
  • Missing CloseSend. Client-streaming servers wait forever for EOF; the half-close is part of the protocol.
  • Treating EOF and error identically. Truncation becomes silent success; classify stream termination explicitly.
  • Materializing full result sets. Large streams should produce lazily; a blocked consumer then applies backpressure instead of exhausting memory.
  • Deadlines on unbounded streams. Subscriptions need cancellation plus keepalive, not a fixed timeout that kills healthy sessions.

Conclusion

The four gRPC modes are data-shape tools: unary for command-response, server-streaming for incremental result sets with early first results, client-streaming for uploads and aggregation verified by a summary, bidirectional for genuine two-way sessions. Define the proto with resumption and integrity fields, since sequence numbers and offsets are what make streams correct across reconnects. Implement handlers that respect cancellation, close client streams with CloseSend, and classify EOF versus error precisely on the client. Respect flow control by producing lazily, and test the streaming-specific failures, partial results, cancellation, slow consumers, and resume, against a real channel. A mode chosen by data shape and wired with these disciplines reads like the problem it solves and stays correct under the conditions that break naive versions.

Sources: gRPC core concepts, Protocol Buffers overview, RFC 7540: HTTP/2.

FAQ

Are streaming RPCs faster than unary?
Not inherently. Streaming wins by overlapping transfer with production for large result sets or by avoiding repeated call setup for ongoing exchanges. For a small request-response, unary is simpler and equally fast.
What happens when a client abandons a stream?
Cancellation propagates through the context to the handler, which should stop producing, release resources, and let the framework close the stream. Handlers that ignore cancellation keep pinning goroutines and buffers per abandoned call.
Can I multiplex many streams over one channel?
Yes, that is the designed behavior over HTTP/2. Streams are multiplexed over one connection, subject to per-stream flow-control windows, so a slow consumer on one stream does not block the others at the transport layer.

Related Examples