Streaming
Server, client and bidirectional streams, and when not to use one.
Three more call shapes, all over the one connection.
Four kinds of RPC
The stream keyword goes on either side, or both:
| Shape | Declaration |
|---|---|
| Unary | rpc F(Req) returns (Res) |
| Server streaming | rpc F(Req) returns (stream Res) |
| Client streaming | rpc F(stream Req) returns (Res) |
| Bidirectional | rpc F(stream Req) returns (stream Res) |
syntax = "proto3";
package stream;
option go_package = "xz/grpc/streampb";
service Streams {
rpc Countdown(StartRequest) returns (stream Tick);
rpc Upload(stream Chunk) returns (Summary);
rpc Chat(stream Chunk) returns (stream Chunk);
}
message StartRequest { int32 from = 1; }
message Tick { int32 value = 1; }
message Chunk { string text = 1; }
message Summary { int32 count = 1; }One server implements all three:
package main
import (
"io"
"log"
"net"
"google.golang.org/grpc"
"xz/grpc/streampb"
)
type server struct{ streampb.UnimplementedStreamsServer }
func (s *server) Countdown(req *streampb.StartRequest, stream grpc.ServerStreamingServer[streampb.Tick]) error {
for i := req.GetFrom(); i > 0; i-- {
if err := stream.Send(&streampb.Tick{Value: i}); err != nil {
return err
}
}
return nil
}
func (s *server) Upload(stream grpc.ClientStreamingServer[streampb.Chunk, streampb.Summary]) error {
var n int32
for {
_, err := stream.Recv()
if err == io.EOF {
return stream.SendAndClose(&streampb.Summary{Count: n})
}
if err != nil {
return err
}
n++
}
}
func (s *server) Chat(stream grpc.BidiStreamingServer[streampb.Chunk, streampb.Chunk]) error {
for {
in, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
if err := stream.Send(&streampb.Chunk{Text: "echo:" + in.GetText()}); err != nil {
return err
}
}
}
func main() {
lis, _ := net.Listen("tcp", ":50053")
s := grpc.NewServer()
streampb.RegisterStreamsServer(s, &server{})
log.Fatal(s.Serve(lis))
}Server streaming
The handler returns no response. It calls Send and returns nil to end the stream:
package main
import (
"context"
"fmt"
"io"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"xz/grpc/streampb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50053",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := streampb.NewStreamsClient(conn)
down, _ := c.Countdown(context.Background(), &streampb.StartRequest{From: 3})
for {
t, err := down.Recv()
if err == io.EOF {
break
}
fmt.Println("down:", t.GetValue())
}
}Countdown returns a stream, not a result. Each Recv blocks for the next message.
Order is guaranteed within a stream, which a series of unary calls does not promise.
Client streaming
The client sends many and gets one answer, with CloseAndRecv doing both halves:
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"xz/grpc/streampb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50053",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := streampb.NewStreamsClient(conn)
up, _ := c.Upload(context.Background())
for _, s := range []string{"a", "b", "c"} {
up.Send(&streampb.Chunk{Text: s})
}
sum, _ := up.CloseAndRecv()
fmt.Println("up: got", sum.GetCount())
}SendAndClose is the server-side mirror: it answers and ends the call in one step.
Bidirectional streaming
Both directions are independent — neither side has to take turns:
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"xz/grpc/streampb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50053",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := streampb.NewStreamsClient(conn)
chat, _ := c.Chat(context.Background())
chat.Send(&streampb.Chunk{Text: "hi"})
r, _ := chat.Recv()
fmt.Println("chat:", r.GetText())
chat.CloseSend()
}This handler replies once per message. Nothing requires that.
The generated generic types
The stream types are generics, parameterised by message type:
sed -n '/^type StreamsServer interface/,/^}/p' streampb/stream_grpc.pb.go \
| grep -E 'Countdown|Upload|Chat'Older tutorials show per-method interfaces like Streams_CountdownServer. Those still exist, as
aliases:
grep -E '^type Streams_\w+Server = ' streampb/stream_grpc.pb.goEnding a stream
io.EOF from Recv means the stream ended normally:
package main
import (
"context"
"fmt"
"io"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"xz/grpc/streampb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50053",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := streampb.NewStreamsClient(conn)
chat, _ := c.Chat(context.Background())
chat.Send(&streampb.Chunk{Text: "a"})
chat.CloseSend()
r, err := chat.Recv()
fmt.Println("recv 1:", r.GetText(), err)
_, err = chat.Recv()
fmt.Println("recv 2:", err)
fmt.Println("EOF is io.EOF:", err == io.EOF)
}A real error is a status, not io.EOF, and chapter 5 is how to read one.
Streams and goroutines
The usual bidirectional shape: a receive loop in its own goroutine, sends from the main one:
package main
import (
"context"
"fmt"
"sync"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"xz/grpc/streampb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50053",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := streampb.NewStreamsClient(conn)
chat, _ := c.Chat(context.Background())
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
in, err := chat.Recv()
if err != nil {
return
}
fmt.Println("got", in.GetText())
}
}()
for _, s := range []string{"a", "b"} {
chat.Send(&streampb.Chunk{Text: s})
}
chat.CloseSend()
wg.Wait()
}One goroutine sends, one receives, and the output is ordered because a stream guarantees order:
| Operation | Concurrent with |
|---|---|
Send |
Recv, yes |
Send |
another Send, no |
Recv |
another Recv, no |
When not to stream
Three cases where unary is the better call:
| Case | Why |
|---|---|
| A list that fits in one message | A stream adds bookkeeping for nothing |
| A request/reply you retry | Chapter 8’s retry policy cannot replay a stream |
| Work behind a load balancer | One long stream pins you to one backend |
Stream for unbounded or incremental data: an event tail, a large upload, a live feed. Paging a result set is usually unary with a token.