Working with Advanced Streaming Patterns

1. Implementing Batch Streaming

StrategyDetail
Batch size50–500 items per message; tune for latency vs CPU
Time + size triggersFlush on whichever hits first
Bound message sizeStay under MaxRecvMsgSize

Example: Batched server stream

batch := make([]*Event, 0, 100)
for e := range src {
    batch = append(batch, e)
    if len(batch) == cap(batch) {
        _ = stream.Send(&EventBatch{Events: batch})
        batch = batch[:0]
    }
}

2. Using Chunked File Upload

FieldPurpose
First messageMetadata (filename, mime, size)
Subsequentbytes data = 1; chunks (e.g. 64 KB)
FinalServer returns checksum + URI

3. Using Chunked File Download

PatternDetail
Server streamSend fixed-size chunks
Range supportInclude offset in request
ResumeClient tracks bytes received and resends offset on reconnect

4. Implementing Stream Multiplexing

ApproachDetail
Tag each messageuint64 stream_id field
DispatchRoute by id on receive
AlternativeUse multiple gRPC streams over same connection (built-in HTTP/2 mux)

5. Using Flow Control

MechanismDetail
HTTP/2 windowDefault 64 KB per stream; tuned via InitialWindowSize
InitialWindowSize / InitialConnWindowSizeServer option; raise to 4 MB for high-throughput streams
Slow consumerSend blocks — natural backpressure

6. Implementing Stream Cancellation

Example: Cancel from client

ctx, cancel := context.WithCancel(context.Background())
stream, _ := client.Subscribe(ctx, req)
go func() { time.Sleep(5*time.Second); cancel() }()
SideDetail
Clientcancel() ctx
Server seesstream.Context().Err() == context.Canceled

7. Using Stream Heartbeats

ApproachDetail
Application heartbeatSend empty / dedicated Heartbeat message every N seconds
HTTP/2 keep-aliveDetect dead TCP; not application-level
Detect livenessReset timer on each received message

8. Implementing Stream Reconnection

Example: Reconnect with backoff

backoff := time.Second
for {
    stream, err := client.Subscribe(ctx, &Req{LastSeq: last})
    if err == nil {
        last, err = consume(stream)
        if ctx.Err() != nil { return }
    }
    time.Sleep(backoff)
    if backoff < 30*time.Second { backoff *= 2 }
}

9. Handling Partial Failures

PatternDetail
Per-item statusResponse message includes repeated ItemStatus
Continue on errorDon't fail entire stream for one bad item
Trailer summaryCounts of OK/failed via trailer metadata

10. Using Stream Buffering

Buffer TypeUse
Channel buffer (Go)Decouple producer/consumer
Bounded queueDrop or block on overflow
Disk spillVery large or critical streams