Grpc

From paulpas/agent-skill-router · View interactive version

Grpc is an AI agent skill from the GitHub repository paulpas/agent-skill-router. "gRPC in Remote Procedure Call - cloud native architecture, patterns" pitfalls, and best practices

How to use this skill

Skill file

gRPC in Cloud-Native Engineering

Purpose and Use Cases

What Problem Does It Solve?

When to Use

Key Use Cases

Architecture Design Patterns

Core Components

Protocol Buffers (.proto files)
syntax = "proto3";

service UserService {
  rpc GetUser(GetUserRequest) returns (User);
  rpc ListUsers(ListUsersRequest) returns (stream User);
}

message GetUserRequest {
  string user_id = 1;
}

message User {
  string id = 1;
  string email = 2;
  string name = 3;
}
gRPC Client and Server Stubs

Component Interactions

Client Application
    ↓ (gRPC stub)
HTTP/2 Connection
    ↓ (Protocol Buffers serialization)
Service Mesh (Envoy)
    ↓ (mutual TLS)
Server Application
    ↓ (gRPC server)
Business Logic

Data Flow Patterns

Unary RPC (Traditional Request-Response)
Client → [Request] → Server → [Response] → Client
Server Streaming RPC
Client → [Request] → Server → [Response 1] → Client
                              → [Response 2] → Client
                              → [Response 3] → Client
Client Streaming RPC
Client → [Request 1] → Server
       → [Request 2] → [Aggregate Response] → Client
       → [Request 3] →
Bidirectional Streaming RPC
Client → [Req 1] → [Resp 1] ← Server
       → [Req 2] → [Resp 2] ←
       → [Req 3] →           ←

Design Principles

Interface-First Development
Error Handling Strategy
Authentication and Authorization

Integration Approaches

Integration with Other CNCF Projects

Kubernetes Integration
apiVersion: v1
kind: Service
metadata:
  name: user-service
spec:
  selector:
    app: user-service
  ports:
    - port: 50051
      targetPort: 50051
      name: grpc
Istio Service Mesh
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: user-service
spec:
  hosts:
    - user-service
  http:
    - match:
        - uri:
            prefix: /UserService
      route:
        - destination:
            host: user-service
            port:
              number: 50051
Envoy Proxy Integration

API Patterns

Package Naming Conventions
# Versioned package names enable evolution
package api.users.v1;
package api.users.v2;

# Nested messages for organization
message User {
  string id = 1;
  Profile profile = 2;
}

message Profile {
  string name = 1;
  string avatar_url = 2;
}
Versioning Strategy
Method Naming Conventions

Configuration Patterns

Client Configuration
grpc:
  target: user-service:50051
  keepalive:
    time: 30s
    timeout: 10s
  retry:
    max_attempts: 3
    initial_backoff: 100ms
    max_backoff: 1s
    backoff_multiplier: 1.5
  load_balancing: round_robin
Server Configuration
grpc:
  port: 50051
  max_concurrent_streams: 100
  max_metadata_size: 8192
  keepalive:
    min_time: 30s
    timeout: 10s
  reflection:
    enabled: true

Extension Mechanisms

Custom HTTP Mapping
import "google/api/annotations.proto";

service UserService {
  rpc GetUser(GetUserRequest) returns (User) {
    option (google.api.http) = {
      get: "/v1/users/{user_id}"
    };
  }
}
Interceptors/Filter Chains

Common Pitfalls and How to Avoid Them

Configuration Issues

Missing Keepalive Settings

Problem: Connections drop in environments with idle connection cleanup (load balancers, firewalls).

Solution:

# Client keepalive
grpc:
  keepalive:
    time: 30s
    timeout: 10s
    permit_without_stream: true
Unbounded Streams

Problem: Streaming endpoints without proper limits cause resource exhaustion.

Solution:

Insecure Default Configuration

Problem: gRPC defaults may not enforce TLS or proper authentication.

Solution:

Performance Issues

Serialization Overhead

Problem: Large Protocol Buffer messages impact memory and CPU.

Solutions:

Memory Leaks from Unhandled Streams

Problem: Clients that don't read streaming responses cause memory leaks.

Solution:

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

stream, err := client.ListUsers(ctx, &ListUsersRequest{})
if err != nil {
    return err
}

for {
    select {
    case <-ctx.Done():
        return ctx.Err()
    default:
        user, err := stream.Recv()
        if err == io.EOF {
            return nil
        }
        if err != nil {
            return err
        }
        processUser(user)
    }
}
Connection Pool Exhaustion

Problem: Too many concurrent connections exhaust system resources.

Solutions:

Operational Challenges

Debugging Without Visual Tools

Problem: gRPC traffic is binary and harder to inspect than HTTP/JSON.

Solutions:

Version Compatibility Failures

Problem: Breaking changes in .proto definitions cause runtime failures.

Solutions:

Service Discovery Integration

Problem: Services don't discover each other dynamically in Kubernetes.

Solutions:

Security Pitfalls

Missing Authentication

Problem: Services accept unauthenticated requests.

Solution:

// Server-side interceptor
func AuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    metadata, ok := metadata.FromIncomingContext(ctx)
    if !ok {
        return nil, status.Error(codes.Unauthenticated, "missing metadata")
    }
    
    token := metadata.Get("authorization")
    if len(token) == 0 {
        return nil, status.Error(codes.Unauthenticated, "missing token")
    }
    
    claims, err := validateToken(token[0])
    if err != nil {
        return nil, status.Error(codes.Unauthenticated, "invalid token")
    }
    
    ctx = context.WithValue(ctx, "claims", claims)
    return handler(ctx, req)
}
Insufficient Authorization

Problem: Authentication occurs but authorization is not enforced.

Solution: Implement role-based access control at service level.

Sensitive Data in Metadata

Problem: Authentication tokens in metadata logged accidentally.

Solution:

Coding Practices

Idiomatic Configuration

Client-Side Retry Policy
// Go example
import "google.golang.org/grpc"

conn, err := grpc.Dial(
    target,
    grpc.WithDefaultCallOptions(
        grpc.MaxCallRecvMsgSize(1024*1024*10),
        grpc.MaxCallSendMsgSize(1024*1024*10),
    ),
    grpc.WithResolvers(
        // Custom resolver if needed
    ),
)
Server Implementation
// Go example with proper error handling
func (s *server) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) {
    // Early exit for invalid input
    if req.UserId == "" {
        return nil, status.Error(codes.InvalidArgument, "user_id is required")
    }
    
    user, err := s.userService.GetByID(req.UserId)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
    }
    
    if user == nil {
        return nil, status.Errorf(codes.NotFound, "user %s not found", req.UserId)
    }
    
    return user, nil
}

API Usage Patterns

Streaming Client Pattern
# ✅ GOOD — gRPC streaming client using grpcurl CLI
# Test unary RPC
grpcurl -plaintext localhost:50051 list myapp.v1.MyService

# Test ListUsers streaming RPC
grpcurl -plaintext -d '{"page_size": 10}' localhost:50051 myapp.v1.MyService/ListUsers | jq .

# Test with TLS
grpcurl -d '{"user_id": "123"}' -cacert ca.crt localhost:50051 myapp.v1.MyService/GetUser | jq .

# Stream output to file for processing
grpcurl -plaintext localhost:50051 myapp.v1.MyService/ListUsers | jq -c '.users[] | .email' > users.txt

# Test with headers/metadata
grpcurl -H "Authorization: Bearer token123" -plaintext localhost:50051 myapp.v1.MyService/ListUsers | jq .

# Debug stream with verbose output
grpcurl -v -plaintext localhost:50051 myapp.v1.MyService/ListUsers
# ✅ GOOD — gRPC streaming with bash while loop
grpcurl -plaintext localhost:50051 myapp.v1.MyService/ListUsers |   while IFS= read -r line; do
    echo "$line" | jq -r '.email, .name' 2>/dev/null
  done || echo "Stream error: connection failed"
Context Management
// Go context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

// Pass context to all gRPC calls
response, err := client.GetUser(ctx, &pb.GetUserRequest{UserId: id})

Observability Best Practices

Request Logging
Metrics Collection
Distributed Tracing
// Include trace context
span := trace.SpanFromContext(ctx)
span.SetAttributes(
    attribute.String("grpc.service", info.FullMethod),
    attribute.String("grpc.method", filepath.Base(info.FullMethod)),
)

Development Workflow

Protobuf Development
  1. Edit .proto files
  2. Run protoc to generate stubs
  3. Implement service handlers
  4. Write integration tests
  5. Run contract tests against both old and new versions
CI/CD Integration
# GitHub Actions example
jobs:
  build:
    steps:
      - uses: actions/checkout@v3
      - name: Install protoc
        uses: arduino/setup-protoc@v1
      - name: Generate stubs
        run: make generate
      - name: Test
        run: make test
      - name: Lint protobuf
        run: make protoc-lint

Fundamentals

Essential Concepts

Protocol Buffers (Protobuf)
gRPC Core Concepts

Terminology Glossary

| Term | Definition |

| related-skills: null

| Stub | Client-side proxy that makes gRPC calls appear as local method calls |

| Server | Service implementation that receives and processes gRPC requests |

| Channel | Connection management object handle |

| Context | Request-scoped data including deadline, cancellation, and metadata |

| Reflection | Protocol for clients to query service capabilities at runtime |

| StatusCode | Standardized status codes (OK, CANCELLED, UNKNOWN, etc.) |

| Message | Structured data unit in Protocol Buffers |

| Service | Interface defining RPC methods in .proto file |

Data Models and Types

Protocol Buffer Type Mapping

| Protobuf Type | Go | Python | Java | Notes |

|


Constraints

MUST DO

MUST NOT DO

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.