@HamzaM to AI & LLMEnglish • 5 days ago

How do you build a zero-downtime API key rotation pool across multiple organization accounts for high throughput?

message-square
0
1
How do you build a zero-downtime API key rotation pool across multiple organization accounts for high throughput?
@HamzaM to AI & LLMEnglish • 5 days ago

How a Zero-Downtime Multi-Organization API Key Rotation Pool Works

A high-throughput API key pool distributes LLM requests across multiple organization accounts and API keys so you aggregate rate limits (RPM/TPM), isolate billing/quota faults, and rotate or retire keys with zero dropped traffic.

  • Pool state vs. static round-robin: Simple round-robin sends traffic to revoked, rate-limited (429), or over-quota (402/insufficient_quota) keys. A production pool tracks per-key health, cooldown/backoff timestamps, active concurrency, and remaining rate-limit capacity—ideally backed by Redis (using atomic Lua scripts/sorted sets) for multi-instance Node.js deployments, with a fast in-memory fallback.
  • Zero-downtime key rotation lifecycle: Rotating a key without dropping requests uses a drain-and-swap state machine (active -> draining -> retired or standby): new requests stop picking keys marked draining or disabled, in-flight requests on those keys finish cleanly, and newly added/rotated keys enter active immediately.
  • Failover across organizations without cascading retries: When a key hits 429 or 5xx, the pool marks that specific key/org in cooldown (honoring retry-after headers when present) and selects the next healthy key from a different organization if available—while capping cross-key retries so tail latency and token spend stay bounded.

Steps to Build a Zero-Downtime Multi-Org Key Rotation Pool

  1. Define key & org metadata and lifecycle states: Model each credential with keyId, orgId, secret, weight, maxConcurrent, state (active | draining | disabled), cooldownUntilMs, and rolling usage/error counters.
  2. Select healthy keys using weighted least-loaded / lowest-error scoring: Filter out keys where state !== "active" or Date.now() < cooldownUntilMs (or concurrency >= maxConcurrent), then pick among eligible keys using weighted random selection or lowest active load, preferring keys from distinct orgIds on failover.
  3. Update key health and cooldowns atomically on responses: On 200 / stream start, clear transient error streaks and update rate-limit hints; on 429, set cooldownUntilMs using Retry-After (or exponential backoff with jitter); on auth/quota errors (401/403/insufficient_quota), disable or quarantine the key and alert ops.
  4. Rotate keys with zero downtime: Add the new key in active state, mark the old key draining so no new requests pick it, wait for its active in-flight count to reach 0, and then revoke/remove the old key.

TypeScript Example: Zero-Downtime Multi-Org Key Pool with Cooldowns and Failover

import OpenAI, { APIError } from "openai";

export type KeyLifecycleState = "active" | "draining" | "disabled";

export interface OrgApiKeyConfig {
  keyId: string;
  orgId: string;
  apiKey: string;
  weight?: number;
  maxConcurrent?: number;
  state?: KeyLifecycleState;
}

interface InternalKeySlot {
  config: OrgApiKeyConfig;
  client: OpenAI;
  state: KeyLifecycleState;
  weight: number;
  maxConcurrent: number;
  inFlight: number;
  cooldownUntilMs: number;
  consecutiveErrors: number;
  totalRequests: number;
  total429s: number;
}

export class MultiOrgKeyPool {
  private readonly slots = new Map<string, InternalKeySlot>();
  private rrCursor = 0;

  constructor(initialKeys: OrgApiKeyConfig[]) {
    for (const cfg of initialKeys) {
      this.upsertKey(cfg);
    }
  }

  /**
   * Adds a new key or updates an existing key's weight/state without dropping traffic.
   */
  upsertKey(cfg: OrgApiKeyConfig): void {
    const existing = this.slots.get(cfg.keyId);
    if (existing) {
      existing.config = cfg;
      existing.weight = Math.max(1, cfg.weight ?? existing.weight);
      existing.maxConcurrent = Math.max(1, cfg.maxConcurrent ?? existing.maxConcurrent);
      if (cfg.state) {
        existing.state = cfg.state;
      }
      if (existing.state === "active") {
        existing.cooldownUntilMs = 0;
        existing.consecutiveErrors = 0;
      }
      return;
    }

    this.slots.set(cfg.keyId, {
      config: cfg,
      client: new OpenAI({
        apiKey: cfg.apiKey,
        organization: cfg.orgId,
        maxRetries: 0, // Let the pool handle cross-key failover deterministically
      }),
      state: cfg.state ?? "active",
      weight: Math.max(1, cfg.weight ?? 1),
      maxConcurrent: Math.max(1, cfg.maxConcurrent ?? 64),
      inFlight: 0,
      cooldownUntilMs: 0,
      consecutiveErrors: 0,
      totalRequests: 0,
      total429s: 0,
    });
  }

  /**
   * Zero-downtime rotation: marks old key as `draining` so no new requests start on it,
   * then resolves once all in-flight requests on that key complete.
   */
  async drainAndRetireKey(keyId: string, pollIntervalMs = 100): Promise<void> {
    const slot = this.slots.get(keyId);
    if (!slot) return;

    slot.state = "draining";

    while (slot.inFlight > 0) {
      await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
    }

    this.slots.delete(keyId);
  }

  async executeWithFailover<T>(
    operation: (client: OpenAI, meta: { keyId: string; orgId: string }) => Promise<T>,
    maxAttempts = 3
  ): Promise<T> {
    const triedKeyIds = new Set<string>();
    const triedOrgIds = new Set<string>();
    let lastError: unknown;

    for (let attempt = 0; attempt < maxAttempts; attempt++) {
      const slot = this.selectNextSlot(triedKeyIds, triedOrgIds);
      if (!slot) {
        break;
      }

      triedKeyIds.add(slot.config.keyId);
      triedOrgIds.add(slot.config.orgId);
      slot.inFlight += 1;
      slot.totalRequests += 1;

      try {
        const result = await operation(slot.client, {
          keyId: slot.config.keyId,
          orgId: slot.config.orgId,
        });
        slot.consecutiveErrors = 0;
        slot.cooldownUntilMs = 0;
        return result;
      } catch (err) {
        lastError = err;
        this.recordFailure(slot, err);

        if (!this.isRetryableAcrossKeys(err)) {
          throw err;
        }
      } finally {
        slot.inFlight = Math.max(0, slot.inFlight - 1);
      }
    }

    throw lastError ?? new Error("All API keys in pool are unavailable or rate-limited.");
  }

  private selectNextSlot(
    excludedKeyIds: Set<string>,
    preferredExcludedOrgIds: Set<string>
  ): InternalKeySlot | null {
    const now = Date.now();
    const allSlots = Array.from(this.slots.values());

    const eligible = allSlots.filter(
      (s) =>
        s.state === "active" &&
        now >= s.cooldownUntilMs &&
        s.inFlight < s.maxConcurrent &&
        !excludedKeyIds.has(s.config.keyId)
    );

    if (eligible.length === 0) {
      return null;
    }

    // Prefer a key from an organization we haven't failed on yet in this request
    const differentOrg = eligible.filter((s) => !preferredExcludedOrgIds.has(s.config.orgId));
    const candidates = differentOrg.length > 0 ? differentOrg : eligible;

    // Build weighted list and advance cursor to spread traffic evenly
    const weightedList: InternalKeySlot[] = [];
    for (const s of candidates) {
      for (let w = 0; w < s.weight; w++) {
        weightedList.push(s);
      }
    }

    const picked = weightedList[this.rrCursor % weightedList.length];
    this.rrCursor = (this.rrCursor + 1) % Math.max(1, weightedList.length);
    return picked ?? null;
  }

  private recordFailure(slot: InternalKeySlot, err: unknown): void {
    slot.consecutiveErrors += 1;
    const now = Date.now();

    if (err instanceof APIError) {
      if (err.status === 429) {
        slot.total429s += 1;
        const retryAfterHeader = err.headers?.get("retry-after");
        const retryAfterSec = retryAfterHeader ? Number(retryAfterHeader) : NaN;
        const backoffMs =
          Number.isFinite(retryAfterSec) && retryAfterSec > 0
            ? retryAfterSec * 1000
            : Math.min(60_000, 1_000 * 2 ** Math.min(slot.consecutiveErrors, 5)) +
              Math.floor(Math.random() * 250);
        slot.cooldownUntilMs = now + backoffMs;
        return;
      }

      if (err.status === 401 || err.status === 403 || err.code === "insufficient_quota") {
        // Quarantine invalid or out-of-quota keys immediately so traffic doesn't hit them
        slot.state = "disabled";
        return;
      }

      if (err.status && err.status >= 500) {
        const transientCooldownMs = Math.min(15_000, 500 * 2 ** Math.min(slot.consecutiveErrors, 4));
        slot.cooldownUntilMs = now + transientCooldownMs;
      }
    }
  }

  private isRetryableAcrossKeys(err: unknown): boolean {
    if (err instanceof APIError) {
      if (err.status === 400 || err.status === 422) return false;
      if (err.status === 429 || (err.status !== undefined && err.status >= 500)) return true;
      if (err.status === 401 || err.status === 403 || err.code === "insufficient_quota") return true;
    }
    // Network / socket / timeout errors are generally safe to retry on another key
    return true;
  }

  getStats() {
    const now = Date.now();
    return Array.from(this.slots.values()).map((s) => ({
      keyId: s.config.keyId,
      orgId: s.config.orgId,
      state: s.state,
      inFlight: s.inFlight,
      coolingDown: now < s.cooldownUntilMs,
      cooldownRemainingMs: Math.max(0, s.cooldownUntilMs - now),
      totalRequests: s.totalRequests,
      total429s: s.total429s,
    }));
  }
}

Helpful Tips for Production Multi-Org Key Pools

  • Disable SDK-level retries (maxRetries: 0) when the pool handles failover: If both the per-key client and the pool retry on 429 or 5xx, a single user request can multiply into 6–9 upstream calls and worsen rate-limit storms.
  • Share pool health state across Node.js pods via Redis: In multi-instance deployments, local in-memory cooldowns mean Pod A knows a key hit 429 while Pod B keeps sending to it—store key cooldowns and active counts in Redis (using atomic Lua scripts) for cluster-wide coordination.
  • Watch out for org-level usage tiers, data-retention/ZDR settings, and billing isolation: Ensure all organizations in the pool match your compliance, zero-data-retention, and model-access requirements, and alert immediately whenever a key transitions to disabled or 429 rates spike.