Production and Using gRPC Well
TLS, limits, load balancing, and when REST wins.
The parts a tutorial skips, and the honest case for not using this.
TLS
insecure.NewCredentials() was a placeholder in every client so far. This replaces it:
truesyntax = "proto3";
package greet;
option go_package = "xz/grpc/greetpb";
service Greeter {
rpc SayHello(HelloRequest) returns (HelloReply);
}
message HelloRequest { string name = 1; }
message HelloReply { string message = 1; }Chapter 1’s server with two lines changed — the handler is untouched:
package main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"xz/grpc/greetpb"
)
type server struct{ greetpb.UnimplementedGreeterServer }
func (s *server) SayHello(ctx context.Context, req *greetpb.HelloRequest) (*greetpb.HelloReply, error) {
return &greetpb.HelloReply{Message: "hello " + req.GetName()}, nil
}
func main() {
creds, err := credentials.NewServerTLSFromFile("c.pem", "k.pem")
if err != nil {
log.Fatal(err)
}
lis, _ := net.Listen("tcp", ":50443")
s := grpc.NewServer(grpc.Creds(creds))
greetpb.RegisterGreeterServer(s, &server{})
log.Fatal(s.Serve(lis))
}The client swaps one option. A cleartext client gets nothing:
package main
import (
"context"
"fmt"
"log"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"xz/grpc/greetpb"
)
func main() {
creds, err := credentials.NewClientTLSFromFile("c.pem", "localhost")
if err != nil {
log.Fatal(err)
}
conn, _ := grpc.NewClient("localhost:50443", grpc.WithTransportCredentials(creds))
defer conn.Close()
r, err := greetpb.NewGreeterClient(conn).SayHello(
context.Background(), &greetpb.HelloRequest{Name: "ada"})
fmt.Println("with TLS:", r.GetMessage(), err)
bad, _ := grpc.NewClient("localhost:50443",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer bad.Close()
_, err = greetpb.NewGreeterClient(bad).SayHello(
context.Background(), &greetpb.HelloRequest{Name: "ada"})
st, _ := status.FromError(err)
fmt.Println("cleartext to TLS port:", st.Code())
}Authentication
Two places to put a credential, and they are not equivalent:
| Approach | Behaviour |
|---|---|
| Metadata by hand | you attach it per call |
PerRPCCredentials |
the library attaches it to every call |
type token struct{ value string }
func (t token) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{"authorization": "Bearer " + t.value}, nil
}
func (t token) RequireTransportSecurity() bool { return true }Verify it in a chapter 6 interceptor, so no handler repeats the check.
Message size limits
The default maximum received message is 4MB, and exceeding it fails the call:
package main
import (
"context"
"fmt"
"log"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/status"
"xz/grpc/greetpb"
)
func main() {
creds, err := credentials.NewClientTLSFromFile("c.pem", "localhost")
if err != nil {
log.Fatal(err)
}
conn, _ := grpc.NewClient("localhost:50443", grpc.WithTransportCredentials(creds))
defer conn.Close()
c := greetpb.NewGreeterClient(conn)
for _, mb := range []int{3, 5} {
name := strings.Repeat("x", mb*1024*1024)
_, err := c.SayHello(context.Background(), &greetpb.HelloRequest{Name: name})
st, _ := status.FromError(err)
fmt.Printf("%dMB request: %s\n", mb, st.Code())
if msg := st.Message(); msg != "" {
fmt.Println(" ", strings.TrimPrefix(msg, "grpc: "))
}
}
}4194304 is 4MB exactly. Raise it with grpc.MaxRecvMsgSize on the server.
Keepalives
HTTP/2 connections are long-lived, so both ends ping to detect a dead peer:
grpc.KeepaliveParams(keepalive.ServerParameters{
Time: 30 * time.Second,
Timeout: 10 * time.Second,
})
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: 15 * time.Second,
})Load balancing
One HTTP/2 connection carries every call, which breaks the usual proxy:
| Balancer | Result |
|---|---|
| L4 / TCP | one connection, pinned to one backend forever |
| L7 / gRPC-aware | per-call balancing |
Client-side (round_robin) |
per-call, no proxy |
grpc.NewClient("dns:///greeter.internal:50051",
grpc.WithDefaultServiceConfig(`{"loadBalancingConfig":[{"round_robin":{}}]}`))Retries
A policy on the connection, instead of a loop in your code:
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"xz/grpc/greetpb"
)
const policy = `{
"methodConfig": [{
"name": [{"service": "greet.Greeter"}],
"retryPolicy": {
"maxAttempts": 4,
"initialBackoff": "0.1s",
"maxBackoff": "1s",
"backoffMultiplier": 2.0,
"retryableStatusCodes": ["UNAVAILABLE"]
}
}]
}`
func main() {
conn, err := grpc.NewClient("localhost:59999",
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultServiceConfig(policy))
if err != nil {
fmt.Println("config rejected:", err)
return
}
defer conn.Close()
fmt.Println("retry policy accepted")
_, err = greetpb.NewGreeterClient(conn).SayHello(
context.Background(), &greetpb.HelloRequest{Name: "ada"})
st, _ := status.FromError(err)
fmt.Println("after 4 attempts:", st.Code())
}Nothing was listening, so all four attempts failed.
Graceful shutdown and health
GracefulStop stops accepting calls and waits for the ones in flight:
package main
import (
"fmt"
"net"
"time"
"google.golang.org/grpc"
"xz/grpc/greetpb"
)
type server struct{ greetpb.UnimplementedGreeterServer }
func main() {
lis, _ := net.Listen("tcp", ":50056")
s := grpc.NewServer()
greetpb.RegisterGreeterServer(s, &server{})
go s.Serve(lis)
time.Sleep(300 * time.Millisecond)
start := time.Now()
s.GracefulStop()
fmt.Println("GracefulStop returned, no calls in flight:", time.Since(start) < time.Second)
}Stop drops in-flight calls immediately. Health checking has a standard service,
grpc.health.v1.Health, so orchestrators can probe any gRPC server.
Register health.NewServer() and a Kubernetes probe works with no HTTP endpoint.
What gRPC cannot do
A browser cannot speak it: the status code is a trailer, and fetch cannot read trailers.
| Need | Answer | Cost |
|---|---|---|
| Browser client | grpc-web + proxy | a proxy, and no client streaming |
| Browser client | Connect | different protocol, works with curl |
| Human debugging | grpcurl |
needs reflection or a .proto |
Settle this before choosing gRPC for anything a browser calls: the answer is always a proxy or a second protocol.
gRPC versus REST versus GraphQL
| Use | Best choice |
|---|---|
| Internal service-to-service, many calls | gRPC |
| Public API for unknown clients | REST |
| Anything a browser calls directly | REST or Connect |
| Streaming or long-lived feeds | gRPC |
| One request, many shapes of response | GraphQL |
A human will debug it with curl |
REST |
REST is the right answer more often than gRPC advocacy admits. gRPC earns its cost with many internal calls, a schema worth generating, and no browser.
Anti-patterns
| Pattern | Problem |
|---|---|
| Chatty RPCs in a loop | each call is a round trip; batch instead |
| One god service | every change redeploys every caller |
| Leaking database rows as messages | the schema becomes your table |
Internal for every error |
no caller can tell what to retry |
| A shared message for two methods | they diverge, and chapter 3 said so |
| No deadline anywhere | a stuck server holds every caller |
Where to look things up
| Question | Source |
|---|---|
| Wire format detail | protobuf encoding spec |
| What a status code means | grpc/codes source, which chapter 5 enumerated |
| Schema conventions | buf lint rules |
| Error details | status.WithDetails and google.rpc.Status |
| Metrics and tracing | OpenTelemetry’s gRPC interceptors |
Observability attaches at chapter 6’s interceptors: OpenTelemetry ships its own, so tracing is a server option rather than a code change.