Production-Hardened Go Microservice Foundations

Unified, zero-business-logic foundation primitives for high-throughput Go backends. Hardened with verified 100.0% statement coverage across 41 packages, zero heavy dependencies in core leaves, and zero data races under -race.

Release v0.6.0 · Go 1.26.0+ · Single-Module BOM
$ go get github.com/abeta-dev/go-libs@v0.6.0
41
Hardened Packages
100.0%
Statement Coverage
100.0%
Gin Middleware Gate
0
Data Races (-race)
1.69 ns
Retry Fast-Path Speed
1,000
Concurrent Conns Tested

System Architecture & Dependency Topology

Four-tier strict downward dependency hierarchy ensuring zero cyclical imports and clean separation of concerns.

Layer 4: Transport Adapters & Framework Composition

Top-Level Pipeline

Composes lower-level primitives into framework-native middleware pipelines.

ginmw httpmw examples/microservice

Layer 3: Cross-Cutting Middleware & HTTP Utilities

Framework Agnostic

Standard library http.Handler compatible middleware, context propagation, and transports.

compress etag loopbackguard sse httpclient ratelimit securityheaders requestid recovery httputil pagination health idempotency validation db sqlite jwks rbac rbaccontext telemetry

Layer 2: Core Infrastructure Primitives & Resilience

Concurrency & Lifecycle

State machines, generic caches, worker pools, bounded concurrency, and graceful shutdown orchestrators.

async cache circuitbreaker fsm retry workerpool shutdown

Layer 1: Low-Level Foundation & Primitives

Zero Internal/External Deps

Leaf utilities, mockable clocks, generic slice/map utilities, UUID v4/v7 helpers, and contextual slog logger.

clock metrics apperror sliceutil maputil stringutil timeutil uuidutil cryptoutil env logger bodylimit

Inbound HTTP Pipeline Execution Flow

BodyLimit Recovery SecurityHeaders RequestID CORS Logger Telemetry GlobalRateLimit AuthMiddleware AuthRateLimit RBAC Route Handler

Package Directory (41 Packages)

Explore the complete collection of production-hardened microservice packages with live filtering.

Showing 41 of 41 packages

Quick-Start Code Snippets

Drop-in production patterns designed for high throughput and zero boilerplate.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/abeta-dev/go-libs/retry"
)

func main() {
	ctx := context.Background()

	// Declarative exponential backoff with full jitter to avoid thundering herds
	cfg := retry.Config{
		Attempts:    3,
		InitialWait: 100 * time.Millisecond,
		MaxWait:     2 * time.Second,
		Strategy:    retry.ExponentialJitter,
	}

	result, err := retry.DoWithResult(ctx, cfg, func(ctx context.Context) (string, error) {
		// Call downstream service or database query
		return "data from upstream", nil
	})

	if err != nil {
		fmt.Printf("Execution failed: %v\n", err)
		return
	}
	fmt.Printf("Success: %s\n", result)
}
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/abeta-dev/go-libs/circuitbreaker"
)

func main() {
	ctx := context.Background()

	// Trips open after 3 consecutive failures; stays open for 500ms before half-open probe
	cb := circuitbreaker.NewConsecutiveBreaker(3, 500*time.Millisecond)

	err := cb.Execute(ctx, func() error {
		// Outbound call to external service
		return nil
	})

	if err != nil {
		if err == circuitbreaker.ErrOpenState {
			fmt.Println("Fast fail: Circuit breaker is OPEN")
		}
		return
	}
	fmt.Println("Outbound call succeeded")
}
package main

import (
	"fmt"
	"time"

	"github.com/abeta-dev/go-libs/ratelimit"
)

func main() {
	// Zero-allocation Token Bucket: 100 requests per minute capacity
	limiter := ratelimit.NewTokenBucket(100, time.Minute)

	clientIP := "192.168.1.100"
	if !limiter.Allow(clientIP) {
		fmt.Println("429 Too Many Requests: Rate limit exceeded")
		return
	}

	fmt.Println("Request allowed through rate limiter")
}
package main

import (
	"github.com/abeta-dev/go-libs/ginmw"
	"github.com/gin-gonic/gin"
)

func setupEngine() *gin.Engine {
	r := gin.New()

	// Hardened zero-leak middleware stack
	r.Use(ginmw.LimitBodyDefault())            // 2MB payload ceiling
	r.Use(ginmw.Recovery())                    // Structured JSON panic recovery
	r.Use(ginmw.SecurityHeaders("my-service")) // OWASP defensive HTTP headers
	r.Use(ginmw.RequestID())                  // W3C trace correlation propagation
	r.Use(ginmw.CORS([]string{"*.example.com"}))
	r.Use(ginmw.Logger())                     // Contextual slog access logging
	r.Use(ginmw.GlobalRateLimit())            // 200 req/min IP flood barrier

	r.GET("/healthz", func(c *gin.Context) {
		c.JSON(200, gin.H{"status": "ok"})
	})

	return r
}
package main

import (
	"context"
	"log"
	"time"

	"github.com/abeta-dev/go-libs/shutdown"
)

func main() {
	// Graceful shutdown manager with 15-second teardown timeout
	mgr := shutdown.New(15 * time.Second)

	// Register teardown hooks in reverse dependency order
	mgr.Register("http-server", func(ctx context.Context) error {
		log.Println("Stopping HTTP server listener...")
		return nil
	})

	mgr.Register("database-pool", func(ctx context.Context) error {
		log.Println("Closing database connections...")
		return nil
	})

	// Blocks until SIGINT/SIGTERM is caught, then executes hooks concurrently
	mgr.Wait()
}
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/abeta-dev/go-libs/cache"
)

type User struct {
	ID   string
	Name string
}

func main() {
	ctx := context.Background()

	// Generic type-safe cache with singleflight thundering-herd suppression
	c := cache.NewTypedCache[User](
		cache.WithCapacity(10000),
		cache.WithEvictionPolicy(cache.LRU),
	)

	user, err := c.GetOrFetch(ctx, "user:101", 5*time.Minute, func(ctx context.Context) (User, error) {
		// Only one concurrent fetcher will execute this fetch block; others await result
		return User{ID: "101", Name: "Ada Lovelace"}, nil
	})

	if err != nil {
		fmt.Printf("Cache fetch failed: %v\n", err)
		return
	}
	fmt.Printf("Retrieved user: %+v\n", user)
}

Performance Benchmarks & Zero-Alloc Guarantees

Supported on Go 1.26+; published benchmark measurements retain their historical Apple Silicon / ARM64 toolchain details.

Go 1.26 benchmark latency and memory allocations across core packages
Package / Operation Operations Run Speed (ns/op) Memory (B/op) Allocations
ratelimit.TokenBucket.Allow 13,521,060 88.1 ns/op 0 B/op 0 allocs/op
circuitbreaker.Execute (Closed) 29,211,739 48.7 ns/op 0 B/op 0 allocs/op
cache.TypedCache.Get (FIFO) 21,393,980 65.9 ns/op 2 B/op 0 allocs/op
cache.TypedCache.Get (LRU) 18,703,083 69.4 ns/op 2 B/op 0 allocs/op
rbac.Engine.Match (Exact) 34,307,360 33.8 ns/op 0 B/op 0 allocs/op
sliceutil.First 422,029,778 2.8 ns/op 0 B/op 0 allocs/op
sliceutil.Reduce (100 items) 35,211,697 32.9 ns/op 0 B/op 0 allocs/op
retry.Do (Parallel Fast-Path) 827,136,512 1.69 ns/op 0 B/op 0 allocs/op
retry.DoWithResult[T] 170,623,623 6.98 ns/op 0 B/op 0 allocs/op
workerpool.Submit (Enqueued) 5,000,000 ~95.0 ns/op 0 B/op 0 allocs/op

Open Source Governance & Branch Protection

Protected by automated truth gates to ensure continuous zero-regression guarantees.

Mandatory Status Checks

Every Pull Request must pass mandatory CI truth gates before merging:

  • CI / Test & Race (1.26.x)
  • CI / GolangCI-Lint
  • CI / Documentation & Version Gate
  • CI / Scale & Load Tests (-tags=scale)

Public Community Access

Community participation is open and actively encouraged:

  • Public Issues: Open to report bugs, submit enhancements, and request primitives.
  • GitHub Discussions: Architecture design records and RFCs.
  • Fork & PR Workflow: External contributors submit PRs via forks with 1 approval required.
  • Enforce Admins: Zero bypasses even for administrators.