grip

module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 7, 2026 License: MIT

README ΒΆ

GRIP Logo

GRIP

Graceful gRPC with Resilience, Isolation, and Parallelism

Go Reference CI Release Go Report Card License

Features β€’ Quick Start β€’ Examples β€’ Documentation β€’ Contributing


Overview

GRIP is a production-ready Go library that adds resilience, intelligent error handling, and stream ordering guarantees to gRPC. It eliminates boilerplate while providing sophisticated patterns for correctness and performance.

Instead of writing repetitive error handling, retry logic, and stream management code, GRIP provides:

  • Automatic Error Classification - Consistent gRPC code mapping across all RPC types
  • Built-in Retry & Deadline Management - Configurable supervisor policies
  • Smart Stream Ordering - Per-key sequential ordering with cross-key parallelism
  • Unified Execution Pipeline - Admission control β†’ execution β†’ supervision
  • Production Observability - OpenTelemetry and Prometheus metrics
  • Zero Boilerplate - Interceptor-based integration with your gRPC services

Features

Error Handling

Priority-based error classification ensuring consistent gRPC codes:
β”œβ”€β”€ ResourceExhausted (admission rejected)
β”œβ”€β”€ Unavailable (server shutdown)
β”œβ”€β”€ Canceled (context cancelled)
└── Unknown (handler errors/panics)

All RPC Types Supported

  • Unary RPC - Request-response with supervision
  • Server Streaming - Server sends multiple messages
  • Client Streaming - Client sends multiple messages
  • Bidirectional Streaming - Full-duplex communication

Stream Ordering Modes

Mode Throughput Ordering Use Case
OrderingNone Maximum None Immutable events
OrderingFIFO Low Global Sequential Strict sequencing
OrderingKeyedFIFO High Per-Key Sequential RECOMMENDED

Integrated Metrics

  • OpenTelemetry (OTEL) support
  • Prometheus metrics
  • Pluggable metrics sink

Production Ready

  • 295+ unit and integration tests
  • Chaos and fuzz testing
  • Zero resource leaks
  • Race-free implementation (verified with go test -race)
  • Comprehensive error handling

Quick Start

Installation

go get github.com/abhipray-cpu/grip

Minimal Example - Unary RPC

package main

import (
    "context"
    "fmt"
    "github.com/abhipray-cpu/grip/unary"
)

func main() {
    // Create unary interceptor with default settings
    u := unary.New()

    // Use in your gRPC server
    server := grpc.NewServer(
        grpc.UnaryInterceptor(u.UnaryServerInterceptor()),
    )

    // Your handler (automatic error mapping, panic recovery)
    // Handler signature: func(ctx context.Context, req any) (any, error)
}

With Retry Policy

u := unary.New(
    unary.WithSupervisorPolicy(supervisor.SupervisorPolicy{
        Retry: &supervisor.RetryPolicy{
            MaxAttempts: 3,
            Backoff:     time.Second,
        },
    }),
)

Server Streaming

// Create engine with sensible defaults (no internal imports needed)
engine := serverstream.New(
    serverstream.WithAdmissionLimit(100), // max 100 concurrent streams
    serverstream.WithSupervisorPolicy(supervisor.SupervisorPolicy{}),
)

stream := serverstream.NewStream(ctx, grpcStream)
err := engine.Run(ctx, stream, core.AdmissionSoftAllow, handler)

Customization

All configuration is available through public packages β€” no internal/ imports needed:

import (
    "github.com/abhipray-cpu/grip/unary"
    "github.com/abhipray-cpu/grip/admission"       // admission control
    "github.com/abhipray-cpu/grip/lifecycle"        // shutdown coordination
    "github.com/abhipray-cpu/grip/metrics"          // metrics interface
    "github.com/abhipray-cpu/grip/metrics/prommetrics"  // Prometheus sink
    "github.com/abhipray-cpu/grip/metrics/otelmetrics"  // OpenTelemetry sink
    "github.com/abhipray-cpu/grip/streaming"        // streaming types (Handler, Message, OrderingPolicy)
)

// Simple: use convenience options (no extra imports)
u := unary.New(
    unary.WithAdmissionLimit(100),
)

// Advanced: use public packages for full control
sd := lifecycle.NewShutdown()
u := unary.New(
    unary.WithAdmissionLimiter(admission.NewLimiter(100)),
    unary.WithShutdown(sd),
    unary.WithMetricsSink(prommetrics.New(prommetrics.DefaultOptions())),
)

Examples

All examples are fully working and documented:

Unary RPC

Streaming

Advanced Patterns

Run any example:

cd examples/unary/basic
go run main.go

Documentation

Document Purpose
Architecture System design, error flow, execution pipeline
Usage Guide Complete API reference with patterns
Contributing How to contribute to GRIP

Key Concepts

Error Classification

GRIP maps all errors to gRPC codes using a priority system:

1. Admission Rejected/Signaled β†’ codes.ResourceExhausted
2. Server Shutdown β†’ codes.Unavailable
3. Context Cancelled β†’ codes.Canceled
4. Handler Errors β†’ codes.Unknown

This ensures consistent error handling across your entire service.

For partitioned workloads, use OrderingKeyedFIFO:

Per-key sequential:    User A transactions execute in order
                       User B transactions execute in order

Cross-key parallel:    User A and User B process simultaneously
                       Maximum throughput + Correctness

Real-world examples:

  • Banking: Transaction ordering per account
  • User sessions: Action ordering per user
  • Stream processing: Partition ordering (Kafka/Kinesis)
  • Event sourcing: Event ordering per aggregate
Supervisor Policies

Control execution behavior:

supervisor.SupervisorPolicy{
    Retry: &supervisor.RetryPolicy{
        MaxAttempts: 3,
        Backoff:     time.Second,
    },
    Deadline: &supervisor.DeadlinePolicy{
        Timeout: 5 * time.Second,
    },
    Admission: &supervisor.AdmissionPolicy{
        MaxConcurrency: 100,
    },
}

Running Tests

# All tests
go test -timeout 10m ./...

# Specific package
go test -v ./serverstream/test

# Fuzz tests (8 packages)
make fuzz

# Coverage
go test -cover ./...

Current Status:

  • 295/295 tests passing
  • 0 vet issues
  • 8/8 fuzz packages covered
  • 0 race conditions (go test -race ./... passes all packages)

Architecture

GRIP implements a unified execution pipeline:

Request
  ↓
Admission Controller (capacity check)
  ↓
Executor (panic recovery + deadline enforcement)
  ↓
Supervisor (retry + escalation + hooks)
  ↓
User Handler
  ↓
Response + Error Classification

For detailed architecture diagrams, see Architecture Documentation.

Use Cases

GRIP is ideal for:

  • Microservices - Consistent error handling across services
  • Stream Processing - Partition-aware ordering (Kafka consumers)
  • Banking/Finance - Transaction ordering guarantees
  • E-commerce - Order processing with correct sequencing
  • Real-time Chat - User session isolation
  • Event Sourcing - Aggregate event ordering

Performance

GRIP is designed for minimal overhead. The interceptor-based architecture adds only lightweight admission checks and error classification to the gRPC call path. The core execution pipeline avoids allocations on the hot path.

With OrderingKeyedFIFO, throughput scales linearly with key cardinality β€” each key gets sequential execution while different keys process in parallel.

Best Practices

DO

  • Use OrderingKeyedFIFO for partitioned workloads
  • Set appropriate retry policies per endpoint
  • Monitor admission limiter rejection rate
  • Use OpenTelemetry for observability
  • Implement supervisor hooks for custom behavior

DON'T

  • Use OrderingFIFO for high-throughput services
  • Set unbounded retry attempts
  • Ignore error codes in client code
  • Skip deadline policies for long operations
  • Create multiple engine instances unnecessarily

Contributing

GRIP is open for contributions! See CONTRIBUTING.md for:

  • Development setup
  • Testing requirements
  • Code style guidelines
  • PR process
  • Issue templates

Contributors Welcome!

  • Bug fixes
  • Documentation improvements
  • New examples
  • Performance optimizations
  • Integration examples

πŸ“‹ License

Licensed under the MIT License. See LICENSE for details.

Support

Getting Help

  1. Check Usage Guide for API documentation
  2. Browse Examples for working code
  3. Read Architecture for system design
  4. Open an issue with details and error logs

Bug Reports

Please include:

  • GRIP version
  • Go version
  • Minimal reproduction code
  • Error logs/stack traces
  • Expected vs actual behavior

Roadmap

Current focus areas:

  • Integration examples (gRPC service, microservice)
  • Additional streaming patterns (chat service, data pipeline)
  • Distributed tracing integration
  • Custom metrics collectors
  • Performance optimization guide

Learning Path

New to GRIP? Follow this path:

  1. Start: Read this README
  2. Understand: Run examples/unary/basic
  3. Learn: Work through examples in order
  4. Deep Dive: Read Architecture
  5. Reference: Use Usage Guide
  6. Implement: Build your service with GRIP

Key Achievements

  • Zero Boilerplate - Interceptor pattern, not config objects
  • Consistent Errors - Unified gRPC code mapping
  • Smart Ordering - Per-key sequential, cross-key parallel
  • Production Ready - 295+ tests, chaos testing, fuzz coverage
  • Well Documented - 1,400+ lines of docs, 15+ diagrams
  • Complete Examples - 7 working examples, all patterns covered

Contact


Made with care for the gRPC community

Star on GitHub β€’ Documentation β€’ Examples

Directories ΒΆ

Path Synopsis
Package admission provides public access to admission control primitives.
Package admission provides public access to admission control primitives.
Package backpressure provides queue-based backpressure control for GRIP streaming pipelines.
Package backpressure provides queue-based backpressure control for GRIP streaming pipelines.
Package bidistream provides an execution pipeline for gRPC bidirectional-streaming RPCs.
Package bidistream provides an execution pipeline for gRPC bidirectional-streaming RPCs.
Package circuitbreaker provides circuit breaker protection for gRPC execution pipelines.
Package circuitbreaker provides circuit breaker protection for gRPC execution pipelines.
Package clientstream provides an execution pipeline for gRPC client-streaming RPCs.
Package clientstream provides an execution pipeline for gRPC client-streaming RPCs.
Package core provides shared types and contracts used across all GRIP packages.
Package core provides shared types and contracts used across all GRIP packages.
Package dynconfig provides dynamic configuration with atomic reads.
Package dynconfig provides dynamic configuration with atomic reads.
examples
Package healthcheck provides component-level health monitoring.
Package healthcheck provides component-level health monitoring.
internal
ratelimit
Package ratelimit provides rate limiting primitives for gRPC execution pipelines.
Package ratelimit provides rate limiting primitives for gRPC execution pipelines.
Package lifecycle provides graceful shutdown coordination for GRIP components.
Package lifecycle provides graceful shutdown coordination for GRIP components.
Package loadshed provides priority-based load shedding.
Package loadshed provides priority-based load shedding.
Package metrics provides the metrics sink interface for GRIP.
Package metrics provides the metrics sink interface for GRIP.
otelmetrics
Package otelmetrics provides an OpenTelemetry metrics sink for GRIP supervisor events.
Package otelmetrics provides an OpenTelemetry metrics sink for GRIP supervisor events.
prommetrics
Package prommetrics provides a Prometheus metrics sink for GRIP supervisor events.
Package prommetrics provides a Prometheus metrics sink for GRIP supervisor events.
Package ratelimit provides rate limiting for gRPC services.
Package ratelimit provides rate limiting for gRPC services.
Package serverstream provides an execution pipeline for gRPC server-streaming RPCs.
Package serverstream provides an execution pipeline for gRPC server-streaming RPCs.
Package streaming provides public types for stream processing.
Package streaming provides public types for stream processing.
Package supervisor provides retry, restart, and escalation policies for GRIP execution pipelines.
Package supervisor provides retry, restart, and escalation policies for GRIP execution pipelines.
Package tracing provides OpenTelemetry trace integration for GRIP.
Package tracing provides OpenTelemetry trace integration for GRIP.
Package unary provides a production-ready execution pipeline for gRPC unary RPCs.
Package unary provides a production-ready execution pipeline for gRPC unary RPCs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL