Heuristic:24mlight A Share investment Agent API Key Rotation
| Knowledge Sources | |
|---|---|
| Domains | Optimization, Infrastructure |
| Last Updated | 2026-10-10 14:00 GMT |
Overview
Multiple API key rotation for Tavily news search to distribute rate limits across keys and gracefully degrade when all keys fail.
Description
The TavilyNewsSearch class supports multiple API keys loaded from both TAVILY_API_KEY (single key) and TAVILY_API_KEYS (comma/semicolon/space separated list). Keys are deduplicated and tried sequentially on each search request: the first key that succeeds wins. If all keys fail, the search returns an empty list rather than raising an exception, allowing the news pipeline to fall back to cached results.
Usage
Use this heuristic when:
- You have multiple Tavily API keys and want to distribute rate limits
- Tavily API requests fail intermittently due to per-key rate limits
- You want the news search to degrade gracefully instead of crashing
The Insight (Rule of Thumb)
- Action: Set
TAVILY_API_KEYSto a comma/semicolon/space-separated list of API keys in.env. Optionally also setTAVILY_API_KEYfor a single key. - Value: N/A (configuration-based).
- Trade-off: Slightly more complex key management vs. higher throughput and reliability.
- Compatibility: Keys from both env vars are merged and deduplicated; order is preserved.
Reasoning
Tavily's free tier has per-key rate limits. When fetching news for multiple stocks during backtesting, a single key quickly exhausts its quota. By rotating across multiple keys, the effective rate limit is multiplied by the number of keys. The sequential try-on-failure approach ensures that if one key is rate-limited, the next is tried immediately without delay. If all keys fail, returning an empty list (rather than raising) lets the calling code fall back to SQLite-cached news, ensuring the pipeline continues operating.
Code Evidence
Key collection and deduplication from src/crawler/news_search/tavily_impl.py:47-66:
self._keys: List[str] = []
if api_key:
self._keys.append(api_key)
if api_keys:
self._keys.extend(api_keys)
env_key = os.getenv("TAVILY_API_KEY", "").strip()
if env_key:
self._keys.append(env_key)
env_keys = os.getenv("TAVILY_API_KEYS", "").strip()
if env_keys:
keys_from_env = [k for k in re.split(r"[;,\s]+", env_keys) if k]
self._keys.extend(keys_from_env)
# 去重
self._keys = list(dict.fromkeys(k.strip() for k in self._keys if k and k.strip()))
Sequential key rotation with graceful failure from src/crawler/news_search/tavily_impl.py:96-117:
last_error: Optional[Exception] = None
data: Dict[str, Any] = {}
for key in self._keys:
try:
resp = requests.post(
"https://api.tavily.com/search",
headers={"Authorization": f"Bearer {key}"},
json=payload,
timeout=self._timeout,
)
resp.raise_for_status()
data = resp.json() or {}
last_error = None
break
except Exception as exc:
last_error = exc
continue
if last_error is not None and not data:
return []