Documentation
¶
Overview ¶
Package keypool provides key pooling and rate limit tracking for multi-key API management.
The keypool package enables intelligent selection of API keys from a pool based on remaining capacity and health status. It tracks rate limits (RPM, ITPM, OTPM) and cooldown periods, learning dynamically from provider response headers.
Example usage:
key := keypool.NewKeyMetadata("sk-...", 50, 30000, 30000)
if key.IsAvailable() {
// Use key for request
}
// After response
key.UpdateFromHeaders(resp.Header)
Package keypool provides key pooling and rate limit tracking for multi-key API management.
Index ¶
- Constants
- Variables
- type KeyConfig
- type KeyMetadata
- func (k *KeyMetadata) GetCapacityScore() float64
- func (k *KeyMetadata) IsAvailable() bool
- func (k *KeyMetadata) MarkHealthy()
- func (k *KeyMetadata) MarkUnhealthy(err error)
- func (k *KeyMetadata) SetCooldown(until time.Time)
- func (k *KeyMetadata) String() string
- func (k *KeyMetadata) UpdateFromHeaders(headers http.Header) error
- type KeyPool
- func (p *KeyPool) GetEarliestResetTime() time.Duration
- func (p *KeyPool) GetKey(ctx context.Context) (keyID, apiKey string, err error)
- func (p *KeyPool) GetStats() PoolStats
- func (p *KeyPool) Keys() []*KeyMetadata
- func (p *KeyPool) MarkKeyExhausted(keyID string, retryAfter time.Duration)
- func (p *KeyPool) UpdateKeyFromHeaders(keyID string, headers http.Header) error
- type KeySelector
- type LeastLoadedSelector
- type PoolConfig
- type PoolStats
- type RandomSelector
- type RoundRobinSelector
- type WeightedSelector
Constants ¶
const ( StrategyLeastLoaded = "least_loaded" StrategyRoundRobin = "round_robin" StrategyRandom = "random" StrategyWeighted = "weighted" )
Strategy constants for configuration.
Variables ¶
var ( ErrAllKeysExhausted = errors.New("keypool: all keys exhausted") ErrNoKeys = errors.New("keypool: no keys configured") )
Common errors returned by key selectors.
var (
ErrKeyNotFound = errors.New("keypool: key not found")
)
Common errors returned by KeyPool.
Functions ¶
This section is empty.
Types ¶
type KeyConfig ¶
type KeyConfig struct {
// APIKey is the actual API key value
APIKey string `json:"-" yaml:"api_key"`
// RPMLimit is the requests per minute limit (0 = unlimited, learn from headers)
RPMLimit int `json:"rpm_limit" yaml:"rpm_limit"`
// ITPMLimit is the input tokens per minute limit (0 = unlimited, learn from headers)
ITPMLimit int `json:"itpm_limit" yaml:"itpm_limit"`
// OTPMLimit is the output tokens per minute limit (0 = unlimited, learn from headers)
OTPMLimit int `json:"otpm_limit" yaml:"otpm_limit"`
// Priority is the key priority (0=low, 1=normal, 2=high)
Priority int `json:"priority" yaml:"priority"`
// Weight is the key weight for weighted selection strategies
Weight int `json:"weight" yaml:"weight"`
}
KeyConfig defines the configuration for a single API key.
type KeyMetadata ¶
type KeyMetadata struct {
RPMResetAt time.Time
ITPMResetAt time.Time
OTPMResetAt time.Time
LastErrorAt time.Time
CooldownUntil time.Time
LastError error
APIKey string `json:"-"`
ID string
RPMLimit int
ITPMLimit int
OTPMLimit int
RPMRemaining int
ITPMRemaining int
OTPMRemaining int
Priority int
Weight int
Healthy bool
// contains filtered or unexported fields
}
KeyMetadata tracks rate limit state and health for a single API key. All methods are safe for concurrent use.
func NewKeyMetadata ¶
func NewKeyMetadata(apiKey string, rpm, itpm, otpm int) *KeyMetadata
NewKeyMetadata creates a new KeyMetadata with the given API key and rate limits. The ID is generated from the first 8 characters of the FNV-1a hash of the key. Initial state: full capacity, healthy, normal priority.
Note: The hash is for identification/logging only, NOT for security comparison. The key ID appears in logs for debugging purposes. It's not used for authentication.
func (*KeyMetadata) GetCapacityScore ¶
func (k *KeyMetadata) GetCapacityScore() float64
GetCapacityScore returns a 0-1 score representing remaining capacity. Higher score means more capacity available. Returns 0 if unhealthy or in cooldown.
func (*KeyMetadata) IsAvailable ¶
func (k *KeyMetadata) IsAvailable() bool
IsAvailable returns true if the key is healthy and not in cooldown.
func (*KeyMetadata) MarkHealthy ¶
func (k *KeyMetadata) MarkHealthy()
MarkHealthy marks the key as healthy and clears any previous error.
func (*KeyMetadata) MarkUnhealthy ¶
func (k *KeyMetadata) MarkUnhealthy(err error)
MarkUnhealthy marks the key as unhealthy with the given error. Unhealthy keys are skipped during selection.
func (*KeyMetadata) SetCooldown ¶
func (k *KeyMetadata) SetCooldown(until time.Time)
SetCooldown marks the key as unavailable until the specified time. Used when a 429 response includes a retry-after header.
func (*KeyMetadata) String ¶
func (k *KeyMetadata) String() string
String returns a human-readable representation of the key metadata.
func (*KeyMetadata) UpdateFromHeaders ¶
func (k *KeyMetadata) UpdateFromHeaders(headers http.Header) error
UpdateFromHeaders parses Anthropic rate limit headers and updates the key's state. Headers format:
- anthropic-ratelimit-requests-limit: 50
- anthropic-ratelimit-requests-remaining: 42
- anthropic-ratelimit-requests-reset: 2026-01-21T19:42:00Z
- anthropic-ratelimit-input-tokens-limit: 30000
- anthropic-ratelimit-input-tokens-remaining: 27000
- anthropic-ratelimit-output-tokens-limit: 30000
- anthropic-ratelimit-output-tokens-remaining: 27000
type KeyPool ¶
type KeyPool struct {
// contains filtered or unexported fields
}
KeyPool manages multiple API keys with rate limiting and intelligent selection. All methods are safe for concurrent use.
func NewKeyPool ¶
func NewKeyPool(provider string, cfg PoolConfig) (*KeyPool, error)
NewKeyPool creates a new KeyPool with the given configuration. Returns an error if no keys are configured or the strategy is unknown.
func (*KeyPool) GetEarliestResetTime ¶
GetEarliestResetTime returns the duration until the earliest rate limit reset. Used for setting retry-after headers when all keys are exhausted. Returns 60s default if no reset times are set.
func (*KeyPool) GetKey ¶
GetKey selects the best available key from the pool using the configured strategy. Returns (keyID, apiKey, error). Returns ErrAllKeysExhausted if no keys have capacity.
func (*KeyPool) Keys ¶
func (p *KeyPool) Keys() []*KeyMetadata
Keys returns a copy of the keys slice for external iteration. Callers can safely iterate over the returned slice.
func (*KeyPool) MarkKeyExhausted ¶
MarkKeyExhausted marks a key as unavailable until the cooldown expires. Used when a 429 response includes a retry-after header.
type KeySelector ¶
type KeySelector interface {
// Select chooses a key from the pool based on the strategy.
// Returns ErrAllKeysExhausted if no keys are available.
Select(keys []*KeyMetadata) (*KeyMetadata, error)
// Name returns the strategy name for logging and configuration.
Name() string
}
KeySelector defines the interface for key selection strategies. Implementations choose which key to use from the available pool.
func NewSelector ¶
func NewSelector(strategy string) (KeySelector, error)
NewSelector creates a KeySelector based on the strategy name. Returns an error if the strategy is unknown. Empty string defaults to least_loaded.
type LeastLoadedSelector ¶
type LeastLoadedSelector struct{}
LeastLoadedSelector picks the key with the most remaining capacity. Capacity is determined by GetCapacityScore() which considers both RPM and TPM (input + output tokens) remaining.
func NewLeastLoadedSelector ¶
func NewLeastLoadedSelector() *LeastLoadedSelector
NewLeastLoadedSelector creates a new least-loaded selector.
func (*LeastLoadedSelector) Name ¶
func (s *LeastLoadedSelector) Name() string
Name returns the strategy name.
func (*LeastLoadedSelector) Select ¶
func (s *LeastLoadedSelector) Select(keys []*KeyMetadata) (*KeyMetadata, error)
Select picks the key with the highest capacity score. Skips unavailable keys (unhealthy or in cooldown). Returns ErrAllKeysExhausted if no keys are available.
type PoolConfig ¶
type PoolConfig struct {
// Strategy is the selection strategy name (least_loaded, round_robin, etc.)
Strategy string `json:"strategy" yaml:"strategy"`
// Keys are the API keys to pool
Keys []KeyConfig `json:"keys" yaml:"keys"`
}
PoolConfig defines the configuration for a KeyPool.
type PoolStats ¶
type PoolStats struct {
TotalKeys int `json:"total_keys"`
AvailableKeys int `json:"available_keys"`
ExhaustedKeys int `json:"exhausted_keys"`
TotalRPM int `json:"total_rpm"`
RemainingRPM int `json:"remaining_rpm"`
}
PoolStats contains statistics about the key pool.
type RandomSelector ¶ added in v0.0.12
type RandomSelector struct {
}
RandomSelector picks a random available key.
func NewRandomSelector ¶ added in v0.0.12
func NewRandomSelector() *RandomSelector
NewRandomSelector creates a new random selector.
func (*RandomSelector) Name ¶ added in v0.0.12
func (s *RandomSelector) Name() string
Name returns the strategy name.
func (*RandomSelector) Select ¶ added in v0.0.12
func (s *RandomSelector) Select(keys []*KeyMetadata) (*KeyMetadata, error)
Select picks a random available key. Returns ErrAllKeysExhausted if no keys are available.
type RoundRobinSelector ¶
type RoundRobinSelector struct {
// contains filtered or unexported fields
}
RoundRobinSelector cycles through keys in order. Uses atomic counter for thread-safe operation without mutex overhead.
func NewRoundRobinSelector ¶
func NewRoundRobinSelector() *RoundRobinSelector
NewRoundRobinSelector creates a new round-robin selector.
func (*RoundRobinSelector) Name ¶
func (s *RoundRobinSelector) Name() string
Name returns the strategy name.
func (*RoundRobinSelector) Select ¶
func (s *RoundRobinSelector) Select(keys []*KeyMetadata) (*KeyMetadata, error)
Select picks the next available key in round-robin order. Skips unavailable keys (unhealthy or in cooldown). Returns ErrAllKeysExhausted if no keys are available after a full loop.
type WeightedSelector ¶ added in v0.0.12
type WeightedSelector struct {
}
WeightedSelector picks an available key using weighted random selection.
func NewWeightedSelector ¶ added in v0.0.12
func NewWeightedSelector() *WeightedSelector
NewWeightedSelector creates a new weighted selector.
func (*WeightedSelector) Name ¶ added in v0.0.12
func (s *WeightedSelector) Name() string
Name returns the strategy name.
func (*WeightedSelector) Select ¶ added in v0.0.12
func (s *WeightedSelector) Select(keys []*KeyMetadata) (*KeyMetadata, error)
Select picks a key using weighted random selection. Returns ErrAllKeysExhausted if no keys are available.