Skip to content

Building a production gRPC service in Go

Define a .proto, generate Go stubs, run a gRPC server with TLS, add interceptors for auth/logging/metrics, and ship a Go client. Includes graceful shutdown.

gRPC is the right transport for service-to-service traffic when JSON-over-HTTP no longer pays for the typing and latency it costs. Go has first-party support via google.golang.org/grpc and protoc-gen-go-grpc. This article shows the gRPC service layout Stack Harbor uses for production Go services — TLS, interceptors, health checking, graceful shutdown.

How to verify

After generating stubs and starting the server, grpcurl lights it up:

protoc --go_out=. --go-grpc_out=. proto/billing.proto
go run ./cmd/server &
grpcurl -plaintext localhost:50051 list
grpcurl -plaintext -d '{"customer_id":"42"}' localhost:50051 billing.v1.BillingService/GetInvoice
grpcurl -plaintext localhost:50051 grpc.health.v1.Health/Check

The Health/Check endpoint comes from the standard health service — production servers always register it so load balancers can probe.

What’s happening

A gRPC service consists of: a .proto schema, generated Go code (*.pb.go for messages and *_grpc.pb.go for service stubs), a server implementation that satisfies the generated interface, and a client that uses the generated client stub. The wire format is protobuf; transport is HTTP/2; each method is a typed RPC.

The Go server uses interceptors — function chains around each unary or streaming call. The standard set in production: recovery (catch panics), logging (slog), auth (JWT/mTLS), metrics (prometheus), tracing (otelgrpc). All four ship as middleware libraries on top of grpc-ecosystem/go-grpc-middleware.

Health checking is a first-class protocol (grpc.health.v1.Health). Implement it once with the official health package and load balancers (envoy, traefik, linkerd) probe gRPC services correctly. Reflection (grpc.reflection.v1.ServerReflection) is the runtime introspection protocol that grpcurl uses — enable it in development only.

The procedure

  1. Author the .proto.

    // proto/billing/v1/billing.proto
    syntax = "proto3";
    package billing.v1;
    option go_package = "example.com/myapp/gen/billing/v1;billingv1";
    
    service BillingService {
      rpc GetInvoice (GetInvoiceRequest) returns (Invoice);
      rpc StreamCharges (StreamChargesRequest) returns (stream Charge);
    }
    
    message GetInvoiceRequest { string customer_id = 1; }
    message Invoice {
      string id = 1;
      string customer_id = 2;
      int64 amount_cents = 3;
      string currency = 4;
    }
    message StreamChargesRequest { string customer_id = 1; }
    message Charge { string id = 1; int64 amount_cents = 2; string at = 3; }
  2. Install the toolchain and generate stubs.

    go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
    go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
    
    protoc -I proto \
      --go_out=. --go_opt=paths=source_relative \
      --go-grpc_out=. --go-grpc_opt=paths=source_relative \
      proto/billing/v1/billing.proto

    That writes proto/billing/v1/billing.pb.go (messages) and billing_grpc.pb.go (service stubs). Commit both. Use buf (buf.build/buf) to lint and generate if you prefer a tool over raw protoc.

  3. Implement the server.

    package server
    
    import (
        "context"
        "log/slog"
    
        billingv1 "example.com/myapp/proto/billing/v1"
        "google.golang.org/grpc/codes"
        "google.golang.org/grpc/status"
    )
    
    type BillingServer struct {
        billingv1.UnimplementedBillingServiceServer
        store *Store
        log   *slog.Logger
    }
    
    func (s *BillingServer) GetInvoice(ctx context.Context, req *billingv1.GetInvoiceRequest) (*billingv1.Invoice, error) {
        inv, err := s.store.FindInvoice(ctx, req.CustomerId)
        if err == ErrNotFound {
            return nil, status.Error(codes.NotFound, "invoice not found")
        }
        if err != nil {
            return nil, status.Errorf(codes.Internal, "find invoice: %v", err)
        }
        return &billingv1.Invoice{
            Id:          inv.ID,
            CustomerId:  inv.CustomerID,
            AmountCents: inv.AmountCents,
            Currency:    inv.Currency,
        }, nil
    }

    Embedding UnimplementedBillingServiceServer means new methods added to the .proto later return Unimplemented automatically instead of breaking the build.

  4. Wire the gRPC server with TLS and interceptors.

    package main
    
    import (
        "context"
        "log/slog"
        "net"
        "os/signal"
        "syscall"
    
        "google.golang.org/grpc"
        "google.golang.org/grpc/credentials"
        "google.golang.org/grpc/health"
        healthv1 "google.golang.org/grpc/health/grpc_health_v1"
        "google.golang.org/grpc/reflection"
    )
    
    func main() {
        log := slog.Default()
        creds, err := credentials.NewServerTLSFromFile("/etc/myapp/tls/server.crt", "/etc/myapp/tls/server.key")
        if err != nil { log.Error("tls", "err", err); return }
    
        lis, err := net.Listen("tcp", ":50051")
        if err != nil { log.Error("listen", "err", err); return }
    
        srv := grpc.NewServer(
            grpc.Creds(creds),
            grpc.UnaryInterceptor(chainUnary(recoveryUnary, loggingUnary(log), authUnary, metricsUnary)),
            grpc.StreamInterceptor(chainStream(recoveryStream, loggingStream(log), metricsStream)),
        )
    
        billingv1.RegisterBillingServiceServer(srv, &BillingServer{store: NewStore(), log: log})
        healthSrv := health.NewServer()
        healthv1.RegisterHealthServer(srv, healthSrv)
        reflection.Register(srv)
        healthSrv.SetServingStatus("billing.v1.BillingService", healthv1.HealthCheckResponse_SERVING)
    
        ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
        defer stop()
        go func() {
            <-ctx.Done()
            log.Info("draining")
            healthSrv.Shutdown()
            srv.GracefulStop()
        }()
    
        if err := srv.Serve(lis); err != nil { log.Error("serve", "err", err) }
    }
  5. Unary auth interceptor. Validate a JWT or mTLS peer:

    func authUnary(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
        md, _ := metadata.FromIncomingContext(ctx)
        tokens := md.Get("authorization")
        if len(tokens) == 0 {
            return nil, status.Error(codes.Unauthenticated, "missing token")
        }
        claims, err := verifyJWT(tokens[0])
        if err != nil {
            return nil, status.Error(codes.Unauthenticated, "invalid token")
        }
        ctx = context.WithValue(ctx, userKey{}, claims)
        return handler(ctx, req)
    }
  6. Server-side streaming. Push a stream of charges:

    func (s *BillingServer) StreamCharges(req *billingv1.StreamChargesRequest, stream billingv1.BillingService_StreamChargesServer) error {
        rows, err := s.store.IterCharges(stream.Context(), req.CustomerId)
        if err != nil { return status.Errorf(codes.Internal, "iter: %v", err) }
        for c := range rows {
            if err := stream.Send(&billingv1.Charge{Id: c.ID, AmountCents: c.AmountCents, At: c.At.Format(time.RFC3339)}); err != nil {
                return err
            }
        }
        return nil
    }
  7. Client side.

    creds, _ := credentials.NewClientTLSFromFile("/etc/myapp/tls/ca.crt", "billing.internal")
    conn, err := grpc.NewClient("billing.internal:50051", grpc.WithTransportCredentials(creds))
    if err != nil { return err }
    defer conn.Close()
    cli := billingv1.NewBillingServiceClient(conn)
    inv, err := cli.GetInvoice(ctx, &billingv1.GetInvoiceRequest{CustomerId: "42"})

Common pitfalls

  • Unbounded streaming. Server-streaming handlers that never return hold a goroutine forever. Always select { case <-stream.Context().Done(): ... }.
  • Reflection in production. reflection.Register allows grpcurl to discover services — convenient in dev, leaking your schema in prod. Gate it on a flag.
  • MaxRecvMsgSize default is 4 MiB. Streaming large payloads requires grpc.MaxRecvMsgSize(64<<20) on both client and server.
  • Health protocol vs /health HTTP endpoint. Load balancers must use the gRPC health protocol. An HTTP healthz on a different port is fine for liveness probes, but readiness should use the gRPC protocol.
  • mTLS peer verification. grpc.NewServer(grpc.Creds(...)) does not enforce client certs by default — set tls.Config{ClientAuth: tls.RequireAndVerifyClientCert} if you need mutual TLS.

Stack Harbor stands up gRPC services with mTLS, health protocol, and the interceptor stack pre-tested on every Go service we operate where service-to-service typed RPC pays off. See how that fits into our managed operations practice when gRPC fleets need supervision.