Heuristic:A616567126 GPT WEB JAVA GPT Key Pool Random Selection
| Knowledge Sources | |
|---|---|
| Domains | Optimization, API_Management |
| Last Updated | 2026-10-13 18:00 GMT |
Overview
Use random selection with type filtering from an in-memory ConcurrentHashMap for GPT API key pool rotation to distribute load evenly across keys.
Description
The GPT key pool in GPT-WEB-JAVA is managed by `InitUtil`, which loads all enabled keys from MySQL at startup into a `ConcurrentHashMap<String, GptKey>`. When a GPT request is made, `getRandomKey(type)` filters the pool by the requested key type (3.5 vs 4.0), shuffles the filtered list with `Collections.shuffle()`, and returns the first key. This random selection avoids the deterministic patterns of round-robin, reducing the chance of hitting rate limits on any single key. After each key usage, `asyncService.updateKeyNumber(key)` asynchronously updates the usage count in the database. Keys can be dynamically removed from the pool via `removeKey()` if they become invalid.
Usage
Use this heuristic when managing a pool of GPT API keys. Apply random selection (not round-robin) to distribute requests evenly across keys. Filter by type to ensure the correct model tier (3.5 or 4.0) is selected. Remove keys immediately from the in-memory pool when they are invalidated to prevent retry failures.
The Insight (Rule of Thumb)
- Action: Use `Collections.shuffle()` on the filtered key list and pick index 0 for each GPT request.
- Value: N/A (random selection, no fixed value).
- Trade-off: Random selection has slightly uneven distribution over small samples but prevents thundering-herd on a single key; round-robin would be deterministic but predictable.
- Compatibility: Keys are cached in-memory (`ConcurrentHashMap`); database updates are asynchronous to avoid blocking the request.
Reasoning
GPT API keys have per-key rate limits. If requests are routed deterministically (e.g., always to the first key), that key hits its rate limit faster while others remain underutilized. Random selection (`Collections.shuffle`) distributes requests probabilistically across all enabled keys of the correct type, maximizing the effective rate limit of the pool. The `ConcurrentHashMap` provides thread-safe access without locking the entire pool on reads, and `putIfAbsent` ensures safe concurrent additions. Asynchronous usage tracking prevents I/O from blocking the GPT streaming response.