Skip to main content

Overview

The adaptive middleware dynamically adjusts rate limits based on system metrics like latency, error rate, and resource utilization. Use it when you need:
  • Auto-scaling rate limits
  • Load-based throttling
  • Self-tuning protection

Installation

Quick Start

Configuration

Options

Examples

Latency-Based

Error Rate-Based

Combined Metrics

How It Works

  1. Measure latency and error rate in sliding window
  2. If metrics exceed targets, decrease rate
  3. If metrics are good, gradually increase rate
  4. Rate stays within min/max bounds

API Reference

Functions

Technical Details

Architecture

The adaptive middleware uses a token bucket algorithm with dynamic rate adjustment:
  • Token Bucket: Implements a refillable token bucket where tokens are added at the current rate per second
  • Atomic Operations: Uses sync/atomic for lock-free access to metrics (request count, error count, latency)
  • Background Adjustment: Runs a goroutine that periodically adjusts the rate based on collected metrics

Rate Adjustment Algorithm

The middleware adjusts rates based on three conditions:
  1. High Error Rate: If error rate > threshold, reduce rate by 20%
  2. High Latency: If average latency > target, reduce rate by 10%
  3. Good Performance: If latency < target/2 AND error rate < threshold/2, increase rate by 10%
All adjustments are clamped to the configured MinRate and MaxRate bounds.

Metrics Collection

The middleware tracks:
  • Request Count: Total requests in current adjustment interval
  • Error Count: Requests that returned errors
  • Total Latency: Cumulative response time in nanoseconds
  • Current Rate: Dynamically adjusted rate limit
Metrics are atomically swapped and reset on each adjustment interval to prevent data races.

Token Refill Mechanism

Tokens are refilled based on elapsed time:
Tokens are capped at the current rate to prevent unbounded accumulation.

Best Practices

  • Start with conservative limits
  • Set reasonable target latency
  • Monitor rate adjustments
  • Use with circuit breaker for full protection

Testing

The adaptive middleware includes comprehensive test coverage for all features and edge cases: