Lesson 12 / 25

Bidirectional Streaming

Both sides talk independently.

Two independent streams

In bidirectional streaming, client and server each send a stream of messages over the same call, in any order: chat, collaborative editing, real-time games, or a long-lived session exchanging commands and events. The two streams are independent, so the server can respond to each message or batch them. Design message types carefully (often a oneof of message kinds), handle reconnection on the client, and resume from the last acknowledged position.

An echo-style chat in Python

Server responding to each incoming message (a sketch).

def Chat(self, request_iterator, context):
    for message in request_iterator:
        reply = support_bot.answer(message.text)
        yield order_pb2.SupportMessage(text=reply)

# client: send from a generator, read replies as they arrive
replies = stub.Chat(iter([order_pb2.SupportMessage(text="Where is my order?")]))
for reply in replies:
    print(reply.text)

Plan for reconnects

Long-lived streams break during deployments and network changes; clients should reconnect with backoff and resume.

Quick check: What is true of bidirectional streaming?

  • The server must wait for the client to finish
  • Client and server streams are independent and can interleave in any order
  • Only one message may be sent each way
  • It requires two TCP connections
Answer

Client and server streams are independent and can interleave in any order — Full-duplex over one call.