Agent skill

Openrouter Load Balancing

by jeremylongshore in jeremylongshore/tons-of-skills-marketplace

Distribute OpenRouter requests across multiple keys and models for high throughput.

MITAuto-check passedAI & LLM Engineering

Install Openrouter Load Balancing

skills CLI
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-load-balancing -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install jeremylongshore/tons-of-skills-marketplace openrouter-load-balancing --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/.curated/openrouter-load-balancing .claude/skills/openrouter-load-balancing && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
openrouter-load-balancing
GitHub stars
2.8k
Token cost
~2.4k tokens
SKILL.md length
516 words
Files
9 (incl. references)
Skills in repo
3,342
Repo updated
First seen
Licence
MIT

At a glance

Distribute OpenRouter requests across multiple keys and models for high throughput.

  • Works in 5 steps: Export your pool keys and build the… → Send traffic through… → For batch workloads, use… → …
  • Scaling beyond single-key rate limits
  • SKILL.md covers Overview, Prerequisites, Instructions and Multi-Key Round Robin, plus 8 more sections
  • Calls pip; reaches openrouter.ai; needs OPENROUTER_API_KEY

What it does

Openrouter Load Balancing is an agent skill from jeremylongshore/tons-of-skills-marketplace. Distribute OpenRouter requests across multiple keys and models for high throughput. Use when scaling beyond single-key rate limits or building high-availability systems. Triggers: 'openrouter load balance', 'openrouter scaling', 'distribute openrouter requests', 'multiple api keys'.

Its SKILL.md is about 2.4k tokens, which your agent loads only when the skill is triggered. The skill folder holds 9 other files, including reference files (for example `references/concurrent-request-distribution.md`, `references/credit-aware-load-balancing.md` and `references/errors.md`). Compatibility notes: Designed for Claude Code

It sits in AI & LLM Engineering, covering Model routing and gateways, Cloud networking and Rate limiting. It works with OpenRouter. The repository describes itself as: Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com. The licence is MIT.

When your agent uses it

  • Scaling beyond single-key rate limits
  • Building high-availability systems

Example prompts

  • “openrouter load balance”
  • “openrouter scaling”
  • “distribute openrouter requests”
  • “/openrouter-load-balancing”

Requirements

  • Python 3
  • A credential in OPENROUTER_API_KEY
  • Compatibility (from SKILL.md): Designed for Claude Code
  • Pre-approved tools (allowed-tools): Read, Write, Edit, Grep, Bash(python3:*)

Workflow steps

5 steps, taken from the first numbered list in SKILL.md.

  1. Export your pool keys and build the KeyPool from Multi-Key Round Robin — it round-robins across keys, trips a circuit breaker after 3…
  2. Send traffic through balanced_completion(): on RateLimitError it calls pool.mark_error(key) and retries with the next healthy key.
  3. For batch workloads, use parallel_completions() from Concurrent Request Processing — an asyncio.Semaphore (max_concurrent=3-5) caps…
  4. Layer on server-side distribution per Provider-Level Load Balancing: pass extra_body={"provider": {"order": [...], "allow_fallbacks"…
  5. Monitor quota per key with check_rate_limits() (GET /api/v1/auth/key) from Rate Limit Awareness, and when 429s hit all keys…

What it can do on your machine

Read from SKILL.md and the folder at commit cfae287. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit
    • Grep
    • Bash(python3:*)

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • pip

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • openrouter.ai

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • OPENROUTER_API_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    Designed for Claude Code

    From compatibility in the SKILL.md frontmatter.

Context cost

Openrouter Load Balancing loads about 2.4k tokens when it runs, and up to ~6.3k if it reads all its reference files. Until then it costs about 77 tokens; SKILL.md has 516 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~77
When it runs · the whole SKILL.md, loaded when a task matches
~2.4k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~6.3k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from jeremylongshore/tons-of-skills-marketplace at commit cfae287, republished under its MIT licence (© jeremylongshore). 516 words, ~2,372 tokens.

Download SKILL.mdSave it as .claude/skills/openrouter-load-balancing/SKILL.md (or your agent's skills folder). This skill also uses 8 other files; get the full folder from GitHub.
name
openrouter-load-balancing
description
Distribute OpenRouter requests across multiple keys and models for high throughput. Use when scaling beyond single-key rate limits or building high-availability systems. Triggers: 'openrouter load balance', 'openrouter scaling', 'distribute openrouter requests', 'multiple api keys'.
allowed-tools
Read, Write, Edit, Grep, Bash(python3:*)
compatibility
Designed for Claude Code
version
1.20.0
license
MIT
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
saas, openrouter, scaling, high-availability, load-balancing

OpenRouter Load Balancing

Overview

A single OpenRouter API key has rate limits (requests/minute and tokens/minute). To scale beyond those limits, distribute requests across multiple keys. OpenRouter also provides server-side load balancing via provider routing and the :nitro variant for low-latency inference. This skill covers multi-key rotation, health-based routing, circuit breakers, and concurrent request patterns.

Prerequisites

  • Two or more OpenRouter API keys exported as OPENROUTER_KEY_1, OPENROUTER_KEY_2, OPENROUTER_KEY_3 so the KeyPool has keys to rotate — see the openrouter-install-auth skill for creating and exporting keys
  • OPENROUTER_API_KEY exported for the single-key concurrent-processing pattern
  • Python 3.8+ with the OpenAI SDK and requests (pip install openai requests) — the concurrent example uses AsyncOpenAI from the same package
  • Adequate credits on every key in the pool; per-key quota is visible via GET /api/v1/auth/key

Instructions

  1. Export your pool keys and build the KeyPool from Multi-Key Round Robin — it round-robins across keys, trips a circuit breaker after 3 consecutive errors, and auto-recovers a key after a 60s cooldown.
  2. Send traffic through balanced_completion(): on RateLimitError it calls pool.mark_error(key) and retries with the next healthy key.
  3. For batch workloads, use parallel_completions() from Concurrent Request Processing — an asyncio.Semaphore (max_concurrent=3-5) caps in-flight requests against a single key.
  4. Layer on server-side distribution per Provider-Level Load Balancing: pass extra_body={"provider": {"order": [...], "allow_fallbacks": True}} so OpenRouter spreads the same model across Anthropic, AWS Bedrock, and GCP Vertex.
  5. Monitor quota per key with check_rate_limits() (GET /api/v1/auth/key) from Rate Limit Awareness, and when 429s hit all keys simultaneously, apply the fixes in Error Handling (more keys, request queuing).

Multi-Key Round Robin

python
import os, itertools, time, logging
from openai import OpenAI, RateLimitError
from dataclasses import dataclass, field

log = logging.getLogger("openrouter.lb")

@dataclass
class KeyPool:
    """Round-robin API key pool with health tracking."""
    keys: list[str]
    _cycle: itertools.cycle = field(init=False, repr=False)
    _health: dict[str, dict] = field(init=False, default_factory=dict)

    def __post_init__(self):
        self._cycle = itertools.cycle(self.keys)
        self._health = {k: {"errors": 0, "last_error": 0, "healthy": True} for k in self.keys}

    def next_key(self) -> str:
        """Get next healthy key."""
        attempts = 0
        while attempts < len(self.keys):
            key = next(self._cycle)
            h = self._health[key]
            # Recover after 60s cooldown
            if not h["healthy"] and time.time() - h["last_error"] > 60:
                h["healthy"] = True
                h["errors"] = 0
            if h["healthy"]:
                return key
            attempts += 1
        # All keys unhealthy -- return any and hope for the best
        return next(self._cycle)

    def mark_error(self, key: str):
        h = self._health[key]
        h["errors"] += 1
        h["last_error"] = time.time()
        if h["errors"] >= 3:  # Circuit breaker: 3 errors → unhealthy
            h["healthy"] = False
            log.warning(f"Key {key[:12]}... marked unhealthy after {h['errors']} errors")

    def mark_success(self, key: str):
        self._health[key]["errors"] = 0
        self._health[key]["healthy"] = True

pool = KeyPool(keys=[
    os.environ.get("OPENROUTER_KEY_1", ""),
    os.environ.get("OPENROUTER_KEY_2", ""),
    os.environ.get("OPENROUTER_KEY_3", ""),
])

def balanced_completion(messages, model="anthropic/claude-3.5-sonnet", **kwargs):
    """Send request using next healthy key from the pool."""
    key = pool.next_key()
    client = OpenAI(
        base_url="https://openrouter.ai/api/v1",
        api_key=key,
        default_headers={"HTTP-Referer": "https://my-app.com", "X-Title": "my-app"},
    )
    try:
        response = client.chat.completions.create(
            model=model, messages=messages, **kwargs
        )
        pool.mark_success(key)
        return response
    except RateLimitError:
        pool.mark_error(key)
        # Retry with next key
        return balanced_completion(messages, model, **kwargs)

Concurrent Request Processing

python
import asyncio
from openai import AsyncOpenAI

async def parallel_completions(prompts: list[str], model="openai/gpt-4o-mini",
                                max_concurrent=5, **kwargs):
    """Process multiple prompts concurrently with rate limiting."""
    semaphore = asyncio.Semaphore(max_concurrent)
    client = AsyncOpenAI(
        base_url="https://openrouter.ai/api/v1",
        api_key=os.environ["OPENROUTER_API_KEY"],
        default_headers={"HTTP-Referer": "https://my-app.com", "X-Title": "my-app"},
    )

    async def process_one(prompt: str):
        async with semaphore:
            response = await client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": prompt}],
                **kwargs,
            )
            return response.choices[0].message.content

    return await asyncio.gather(*[process_one(p) for p in prompts])

# Usage
results = asyncio.run(parallel_completions(
    ["Summarize X", "Translate Y", "Analyze Z"],
    max_concurrent=3,
    max_tokens=500,
))

Provider-Level Load Balancing

python
# OpenRouter can distribute across providers for the same model
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",
    messages=[{"role": "user", "content": "Hello"}],
    max_tokens=200,
    extra_body={
        "provider": {
            # Let OpenRouter pick the best available provider
            "order": ["Anthropic", "AWS Bedrock", "GCP Vertex"],
            "allow_fallbacks": True,
        },
    },
)

Rate Limit Awareness

python
import requests

def check_rate_limits(api_key: str) -> dict:
    """Check current rate limit status for a key."""
    resp = requests.get(
        "https://openrouter.ai/api/v1/auth/key",
        headers={"Authorization": f"Bearer {api_key}"},
    )
    data = resp.json()["data"]
    return {
        "requests_limit": data["rate_limit"]["requests"],
        "interval": data["rate_limit"]["interval"],
        "credits_used": data["usage"],
        "credits_limit": data.get("limit"),
    }

# Check all keys in pool
for key in pool.keys:
    limits = check_rate_limits(key)
    print(f"Key {key[:12]}...: {limits}")

Output

  • Chat completion responses served through whichever pool key was healthy at send time, plus per-key health state: error counts, healthy flags, and log lines like Key sk-or-v1-abc... marked unhealthy after 3 errors
  • An ordered list of completion strings from parallel_completions() — one per input prompt, gathered concurrently
  • Rate-limit status dicts per key from check_rate_limits(): requests_limit, interval, credits_used, credits_limit
Show full SKILL.md (193 more words)Show less

Examples

Six requests through a two-key pool split evenly, and the pool's stats confirm the distribution:

python
for i in range(6):
    balanced_completion(f"Request {i}: Hello!")
print(pool.get_stats())
# {'sk-or-v1-abc': {'requests': 3, 'errors': 0},
#  'sk-or-v1-def': {'requests': 3, 'errors': 0}}

Zero errors means no key tripped the circuit breaker; a nonzero errors count on one key with requests skewing to the other shows health-based routing doing its job. More worked examples: references/examples.md.

Error Handling

ErrorCauseFix
429 on all keysAll keys rate-limited simultaneouslyAdd more keys; implement request queuing
Uneven load distributionRound-robin not accounting for in-flight requestsUse weighted distribution based on current load
Key health false positiveTransient error marked key unhealthyUse sliding window (3 errors in 60s) before marking unhealthy
Concurrent request failuresToo many parallel requestsReduce semaphore limit; add backoff

Enterprise Considerations

  • Create separate API keys per service/team with individual credit limits for cost isolation
  • Use 3+ keys to multiply effective rate limits (each key gets its own quota)
  • Implement circuit breakers: mark keys unhealthy after N consecutive errors, recover after cooldown
  • Use asyncio.Semaphore to control concurrency and prevent overwhelming the API
  • Monitor per-key error rates and latency to detect degraded keys early
  • Combine multi-key rotation with provider routing for maximum resilience

References

© jeremylongshore, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 8 other files (references) in skills/.curated/openrouter-load-balancing of jeremylongshore/tons-of-skills-marketplace.

  • SKILL.md
  • references/concurrent-request-distribution.md
  • references/credit-aware-load-balancing.md
  • references/errors.md
  • references/examples.md
  • references/health-based-routing.md
  • references/model-based-load-balancing.md
  • references/monitoring-load-distribution.md
  • references/multi-key-load-balancing.md

Open the folder on GitHubat commit cfae287

Compare with similar skills

Openrouter Load Balancing next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Openrouter Load Balancing compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Openrouter Load Balancing this skilljeremylongshore/tons-of-skills-marketplace2.8k—~2.4kAutomated safety check: PassMIT
LLM GatewayBagelHole/DevOps-Security-Agent-Skills1.2k—~2kAutomated safety check: PassMIT
Using Ccproxy Inspectorstarbaser/ccproxy350—~2.7kAutomated safety check: PassCustom licence
LLM Gatewaysickn33/agentic-awesome-skills47k1 repos~2.1kAutomated safety check: PassMIT
Subzeroclaw Usegenlayerlabs/subzeroclaw137—~1.5kAutomated safety check: PassMIT
Quota Axikunchenguid/quota-axi147—~547Automated safety check: PassMIT

Similar skills

  • LLM Gateway

    BagelHole/DevOps-Security-Agent-Skills

    Deploy an API gateway for LLM traffic with load balancing, rate limiting, key management, semantic caching, fallback routing, and cost tracking.

    1.2k GitHub stars~2k tokensUpdated 4 mo ago
    AI & LLM EngineeringAuto-check passed
  • Using Ccproxy Inspector

    starbaser/ccproxy

    Operates the ccproxy inspector MITM system for intercepting, inspecting, and transforming LLM API traffic.

    350 GitHub stars~2.7k tokensUpdated 2 mo ago
    AI & LLM EngineeringAuto-check passed
  • LLM Gateway

    sickn33/agentic-awesome-skills

    Deploy an API gateway for LLM traffic with load balancing, rate limiting, key management, semantic caching, fallback routing, and cost tracking.

    47k GitHub starsUsed in 1 repo~2.1k tokens
    Backend & APIsAuto-check passed
  • Subzeroclaw Use

    genlayerlabs/subzeroclaw

    Run and operate SubZeroClaw — the ~550-line C agentic daemon (skill.md + LLM + shell + loop).

    137 GitHub stars~1.5k tokensUpdated 16 days ago
    AI & LLM EngineeringAuto-check passed
  • Quota Axi

    kunchenguid/quota-axi

    Report local Claude, Codex, Cursor, GitHub Copilot, Grok, Kimi, Z.AI, Alibaba, OpenCode Go, Antigravity, Command Code, MiniMax, MiMo, DeepSeek, OpenRouter, ElevenLabs, Devin, Muse, and Higgsfield…

    147 GitHub stars~547 tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Darwinian Evolver

    Luciole-Studio/Misaka-Agent

    Evolve prompts/regex/SQL/code with Imbue's evolution loop. An agent skill from Luciole-Studio/Misaka-Agent.

    171 GitHub starsUsed in 2 repos~2.1k tokens
    AI & LLM EngineeringAuto-check: warnings

More from jeremylongshore/tons-of-skills-marketplace

All 3,342 skills in this repo
  • Performing Security Code Review

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin.

    2.8k GitHub starsUsed in 2 repos~1.3k tokens
    Auto-check: notes
  • Adapting Transfer Learning Models

    jeremylongshore/tons-of-skills-marketplace

    Build this skill automates the adaptation of pre-trained machine learning models using transfer learning techniques.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Agent Context Loader

    jeremylongshore/tons-of-skills-marketplace

    Execute proactive auto-loading: automatically detects and loads agents.md files.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Aggregating Performance Metrics

    jeremylongshore/tons-of-skills-marketplace

    Aggregate and centralize performance metrics from applications, systems, databases, caches, and services.

    2.8k GitHub stars~1.2k tokensUpdated today
    Auto-check passed
  • Analyzing Capacity Planning

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to analyze capacity requirements and plan for future growth.

    2.8k GitHub stars~947 tokensUpdated today
    Auto-check passed
  • Analyzing Database Indexes

    jeremylongshore/tons-of-skills-marketplace

    Process use when you need to work with database indexing. An agent skill from jeremylongshore/tons-of-skills-marketplace.

    2.8k GitHub stars~2k tokensUpdated today
    Auto-check passed

Works with

Questions about Openrouter Load Balancing

What does Openrouter Load Balancing do?

Distribute OpenRouter requests across multiple keys and models for high throughput. Openrouter Load Balancing is an agent skill from jeremylongshore/tons-of-skills-marketplace. Distribute OpenRouter requests across multiple keys and models for high throughput.

When should I use Openrouter Load Balancing?

Openrouter Load Balancing fits situations like: scaling beyond single-key rate limits; building high-availability systems.

How do I install Openrouter Load Balancing in Claude Code?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-load-balancing -a claude-code`. Or copy the skill folder (skills/.curated/openrouter-load-balancing in jeremylongshore/tons-of-skills-marketplace) into .claude/skills/openrouter-load-balancing in your project. Claude Code loads it when a task matches its description.

How do I install Openrouter Load Balancing in Codex?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-load-balancing -a codex`. Or copy the skill folder (skills/.curated/openrouter-load-balancing in jeremylongshore/tons-of-skills-marketplace) into .agents/skills/openrouter-load-balancing in your project. Codex loads it when a task matches its description.

Can I use Openrouter Load Balancing in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-load-balancing -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/openrouter-load-balancing, .gemini/skills/openrouter-load-balancing, .github/skills/openrouter-load-balancing and .opencode/skills/openrouter-load-balancing in your project.

What does Openrouter Load Balancing need to run?

Going by SKILL.md and its folder, Openrouter Load Balancing needs the command-line tools its instructions call (pip) and credentials named OPENROUTER_API_KEY. Our summary lists: Python 3; A credential in OPENROUTER_API_KEY. Its frontmatter pre-approves these tools: Read, Write, Edit, Grep, Bash(python3:*). Compatibility (from SKILL.md): Designed for Claude Code.

Does Openrouter Load Balancing access the network?

SKILL.md names 1 domain. In commands or code: openrouter.ai; the agent is likely to contact it when it follows the instructions. This is read from the text; nothing was executed.

Is Openrouter Load Balancing safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Openrouter Load Balancing use?

Openrouter Load Balancing is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Openrouter Load Balancing use?

About 2.4k tokens (SKILL.md is roughly 9.5k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 3.9k tokens, read only when the agent opens those files.

What are the alternatives to Openrouter Load Balancing?

Skills that share tags, products or a category with Openrouter Load Balancing: LLM Gateway (BagelHole/DevOps-Security-Agent-Skills, 1.2k stars), Using Ccproxy Inspector (starbaser/ccproxy, 350 stars), LLM Gateway (sickn33/agentic-awesome-skills, 47k stars) and Subzeroclaw Use (genlayerlabs/subzeroclaw, 137 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Openrouter Load Balancing?

jeremylongshore (a GitHub user) maintains it in jeremylongshore/tons-of-skills-marketplace, which has 2,827 GitHub stars. The repository holds 3,342 skills in this directory. The repository was last updated on October 10, 2026.

Source: jeremylongshore/tons-of-skills-marketplace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.