Skip to main content

Overview

The canary middleware enables canary deployments by routing a percentage of traffic to different handlers, allowing gradual rollouts. Use it when you need:
  • Gradual feature rollouts
  • A/B testing
  • Blue-green deployments

Installation

Quick Start

Configuration

Options

Examples

Percentage-Based

With Sticky Sessions

Header Override

Gradual Rollout

API Reference

Functions

Technical Details

Implementation Overview

The canary middleware uses a deterministic counter-based approach for traffic distribution:
  • Counter-Based Distribution: Uses an atomic counter (atomic.AddUint64) that increments on each request. The modulo operation (counter % 100 < percentage) ensures predictable distribution over time.
  • Context Storage: Stores the canary decision in the request context using a private context key, accessible via IsCanary(c).
  • Override Precedence: Decision order is: Header override > Cookie override > Custom Selector > Percentage-based selection.

Key Components

Core Functions:
  • New(percentage int): Creates middleware with simple percentage-based routing
  • WithOptions(opts Options): Creates middleware with full configuration options
  • IsCanary(c *mizu.Ctx): Checks if current request is using canary version
  • Route(canary, stable Handler): Routes to different handlers based on canary status
  • Middleware(canaryMw, stableMw): Applies different middleware chains based on canary status
ReleaseManager:
  • Manages multiple named canary releases
  • Each release has independent counter and percentage
  • Useful for managing multiple feature rollouts simultaneously
Selectors:
  • RandomSelector(percentage): Uses math/rand for random selection (non-cryptographic)
  • HeaderSelector(header, value): Selects based on header value
  • CookieSelector(name, value): Selects based on cookie value
  • Custom selectors via Options.Selector function

Security Notes

The implementation intentionally uses math/rand (not crypto/rand) for performance:
  • Canary selection is non-security-critical
  • gosec G404 warnings are suppressed with explanation
  • The counter-based default approach is fully deterministic

Best Practices

  • Start with low percentages (1-5%)
  • Monitor error rates for canary traffic
  • Use sticky sessions for stateful applications
  • Provide override mechanism for testing

Testing

Test Coverage