Principle:A616567126 GPT WEB JAVA API Key Pool Management
| Knowledge Sources | |
|---|---|
| Domains | Resource_Management, API_Management |
| Last Updated | 2026-10-13 00:00 GMT |
Overview
Pattern that manages a pool of API keys in memory, selecting keys randomly at runtime to distribute load and avoid hitting rate limits on any single key.
Description
When an application uses a third-party API (e.g., OpenAI) with multiple API keys, a key pool management system loads all active keys into memory at startup and selects one randomly per request. This addresses the problem of per-key rate limits: by distributing requests across multiple keys, the effective throughput increases proportionally to the number of keys.
The pool is typically backed by a concurrent data structure (ConcurrentHashMap) for thread-safe access. Keys can be added, removed (when disabled), and selected randomly. Usage statistics (e.g., how many times each key was used) are tracked asynchronously to avoid blocking the request path.
Usage
Use this principle when:
- An application has multiple API keys for the same service
- Per-key rate limits require load distribution
- Keys may need to be disabled at runtime without restarting the application
Theoretical Basis
Random Selection with Uniform Distribution:
# Abstract algorithm (NOT real implementation)
def get_random_key(key_type):
pool = [k for k in all_keys if k.type == key_type and k.is_active]
if pool is empty:
raise NoKeyAvailableError()
selected = random_choice(pool)
async_increment_usage(selected)
return selected
Key Properties:
- In-memory cache: Keys loaded from DB at startup into
ConcurrentHashMap - Random selection:
Collections.shuffle()ensures even distribution - Type filtering: Keys are filtered by model type (GPT-3.5, GPT-4, Vision) to ensure the key supports the requested model
- Async tracking: Usage count incremented via
@Asyncto avoid blocking - Runtime removal: Disabled keys can be evicted from the pool without restart
Practical Guide
The repository implements this in InitUtil:
- At startup (
@PostConstruct), all active GPT keys (state=0) are loaded from DB into a staticConcurrentHashMap getRandomKey(type)filters keys by type, shuffles the list, and returns the first- Usage is tracked by incrementing
GptKey.use_numberasynchronously - SysConfig and PayConfig are also cached in Redis during initialization
Related Pages
Implemented By
- Implementation:A616567126_GPT_WEB_JAVA_InitUtil
- Implementation:A616567126_GPT_WEB_JAVA_CommonConst
- Implementation:A616567126_GPT_WEB_JAVA_KimiController
- Implementation:A616567126_GPT_WEB_JAVA_GptKeyController