Implementing Proxies and Middleware

1. Using Envoy as gRPC Proxy

FeatureDetail
HTTP/2 nativeFirst-class gRPC support
Load balancingRound-robin, least-request, ring-hash
Retries / timeoutsPer-route policy
ObservabilityStats, tracing, access logs

2. Configuring Envoy Routes

Example: gRPC route

routes:
  - match: { prefix: "/user.v1.UserService/", grpc: {} }
    route:
      cluster: user_service
      timeout: 5s
      retry_policy:
        retry_on: cancelled,deadline-exceeded,unavailable
        num_retries: 3

3. Using NGINX for gRPC

Example: nginx grpc_pass

server {
    listen 443 ssl http2;
    ssl_certificate /etc/ssl/cert.pem;
    ssl_certificate_key /etc/ssl/key.pem;
    location / {
        grpc_pass grpc://backend:50051;
        grpc_set_header X-Real-IP $remote_addr;
    }
}

4. Implementing Auth Middleware

LayerDetail
Envoy JWT filterValidate before reaching backend
External authzext_authz filter calls OPA/custom
InterceptorApp-level auth in gRPC server

5. Implementing Logging Middleware

ApproachDetail
Envoy access logJSON/text format with gRPC status
go-grpc-middleware loggingInterceptor with field extraction

6. Implementing Caching Middleware

ApproachDetail
Read-through cachePer-method cache key from request hash
Cache TTL via metadataHonor cache-control from response
Avoid for streamsCache only safe, idempotent unary calls

7. Implementing Compression Middleware

LayerDetail
Built-inPer-call grpc.UseCompressor(gzip.Name)
EnvoyDisabled by default for gRPC (already compressed)

8. Chaining Middleware

Example: Chain with go-grpc-middleware

import gmw "github.com/grpc-ecosystem/go-grpc-middleware/v2"
srv := grpc.NewServer(
    grpc.ChainUnaryInterceptor(
        recovery.UnaryServerInterceptor(),
        logging.UnaryServerInterceptor(logger),
        auth.UnaryServerInterceptor(authFn),
        validate.UnaryServerInterceptor(),
    ),
)

9. Setting Middleware Order

Order (typical)Reason
1. RecoveryOutermost to catch panics in others
2. Tracing / metricsMeasure full handling time
3. LoggingCapture all attempts
4. AuthReject early
5. Rate limitAfter auth (per-principal)
6. ValidationJust before business logic

10. Implementing Custom Middleware

TipDetail
StatelessPass deps via closure, not globals
Both interceptorsProvide unary + stream variants
Stream wrappingWrap grpc.ServerStream to intercept Recv/Send