Optimizing gRPC Performance

1. Tuning Message Size

OptionDefaultDetail
MaxRecvMsgSize4 MBIncrease for large payloads
MaxSendMsgSize~math.MaxInt32Cap to prevent OOM
Chunked streamingPrefer over single huge message

2. Tuning Window Size

Example: HTTP/2 windows

srv := grpc.NewServer(
    grpc.InitialWindowSize(1<<20),         // 1 MiB stream
    grpc.InitialConnWindowSize(1<<24),     // 16 MiB connection
)
WindowDetail
BDP estimationDefault; auto-tunes
Manual tuningFor high BDP networks

3. Using Connection Pooling

PatternDetail
One conn per serviceHTTP/2 multiplexes streams — usually enough
Pool of N connsFor very high concurrency on single peer
SETTINGS_MAX_CONCURRENT_STREAMSOften 100 default — pool around it

4. Enabling Multiplexing

DetailNote
HTTP/2 multiplexingMany RPCs share one TCP conn
No head-of-line at L7Streams interleave
L4 still blocksTCP loss stalls — consider QUIC/HTTP/3 future

5. Optimizing Message Encoding

TipDetail
Reuse messagesPool via sync.Pool
Avoid any.AnyDouble encoding cost
Smaller field numbers1–15 use 1-byte tag
packed repeatedDefault in proto3 for scalars

6. Reducing Allocations

TechniqueDetail
vtprotobuf codecFaster marshal, fewer allocs
Reuse response objectsReset and refill in streaming hot paths
Avoid string→[]byte conversionsUse unsafe carefully

7. Implementing Caching

LayerDetail
In-memory LRUFor hot reads
Distributed (Redis)Shared across replicas
SingleflightDedupe concurrent identical requests

8. Batching Requests

ApproachDetail
Server batches DBCoalesce within short window
Client batch RPCRepeated request field; one call returns N results
Stream of itemsAvoid round-trip per item

9. Using Streaming for Bulk Data

PatternDetail
Server streamingLarge result sets — chunk & flush
Client streamingUploads in chunks (64–256 KB)
BackpressureFlow control via HTTP/2 windows handles it

10. Tuning Thread Pool

LanguageDetail
GoEach RPC = goroutine; tune GOMAXPROCS
JavaSet executor on ServerBuilder
PythonThreadPoolExecutor(max_workers=N) on server

11. Profiling gRPC Performance

StepDetail
CPU pprofIdentify hot marshal/handler paths
Block profileFind lock contention
Trace exporterEnd-to-end latency breakdown

12. Optimizing Network Usage

LeverDetail
gzip compressionFor text-heavy payloads
Keep-alive pingsCatch dead conns early
Co-locateSame zone/region to cut latency
HTTP/3 (experimental)QUIC avoids TCP HOL