# rhythamtech/keymesh architecture

> Architecture diagram of the GitHub repository rhythamtech/keymesh, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-13). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/rhythamtech/keymesh
- Repository: https://github.com/rhythamtech/keymesh

## Overview

#### Purpose and Public Surface
KeyMesh is a Python 3.12+ library that multiplexes AI-provider API credentials across concurrent workloads. It is provider-agnostic at its core; callers either manage key lifecycle directly or use OpenAI HTTP-client adapters. Public exports are centralized in `keymesh/__init__.py`; runnable usage appears in `example.py` and `examples/openai_handler_example.py`.

#### Dual Runtime Model
The package maintains parallel async and synchronous/thread-safe implementations rather than adapting one runtime to the other:
- Async orchestration: `keymesh/pool/pool.py`, `keymesh/state/key_state.py`, `keymesh/storage/base.py`
- Sync orchestration: `keymesh/pool/sync_pool.py`, `keymesh/state/sync_key_state.py`, `keymesh/storage/sync_base.py`

This is the primary boundary: async callers await pool/storage/state operations, while threaded callers use synchronous equivalents and locks.

#### Pool Orchestration
`KeyPool` and `SyncKeyPool` are the central lifecycle coordinators in `keymesh/pool/pool.py` and `keymesh/pool/sync_pool.py`. Their control flow is:
1. Acquire an eligible, non-cooled-down key through a scheduler.
2. Track active request state.
3. On successful completion, release the key and update latency/health metrics.
4. On rate limiting or failures, cool down or mark the key failed.

Pool exhaustion, cooldown eligibility, and lifecycle errors are surfaced through `keymesh/exceptions.py`.

#### Key State, Health, and Concurrency
Per-credential operational state is maintained by `keymesh/state/key_state.py` and `keymesh/state/sync_key_state.py`. State tracks active requests, cooldown timing, failure behavior, success/health signals, and latency statistics. Concurrency primitives are isolated in `keymesh/concurrency/semaphores.py`, enabling high-frequency acquisition without relying on mutable global client API keys.

#### Scheduling Layer
Schedulers are stateless selection policies behind the abstraction in `keymesh/scheduler/base.py`. Implementations choose among currently eligible key states:
- Rotation: `keymesh/scheduler/round_robin.py`
- Load-aware selection: `keymesh/scheduler/least_busy.py`
- Configured preference/capacity: `keymesh/scheduler/weighted.py`

The pool owns eligibility and lifecycle mutation; schedulers decide only which candidate to select.

#### Cooldown, Metrics, and Persistence
Rate-limit recovery is separated into `keymesh/cooldown/manager.py`, including cooldown duration handling such as `Retry-After` processing. Aggregate/per-pool observability lives in `keymesh/metrics/pool_metrics.py`, including EMA latency and success/failure health inputs. State persistence is abstracted through storage contracts and implementations:
- Async: `keymesh/storage/base.py`, `keymesh/storage/memory.py`, `keymesh/storage/json_storage.py`
- Sync: `keymesh/storage/sync_base.py`, `keymesh/storage/sync_json.py`

Memory storage is runtime-local; JSON storage provides local-file persistence. No database or remote control plane is represented.

#### HTTP Integration Boundary
`keymesh/integrations/openai_handler.py` provides `httpx.Client` and `httpx.AsyncClient`-based handlers for the OpenAI SDK (optional dependency). At the transport boundary, handlers acquire a key, inject it into the request Authorization header, time the request, then release, cool down on HTTP 429, or mark failures. This is the only provider-specific integration and avoids shared-client credential mutation while delegating actual API calls to OpenAI/httpx.

Main entry points: [`keymesh/pool/pool.py`](https://github.com/rhythamtech/keymesh/blob/main/keymesh/pool/pool.py) (KeyPool), [`keymesh/pool/sync_pool.py`](https://github.com/rhythamtech/keymesh/blob/main/keymesh/pool/sync_pool.py) (SyncKeyPool), [`keymesh/integrations/openai_handler.py`](https://github.com/rhythamtech/keymesh/blob/main/keymesh/integrations/openai_handler.py) (OpenAI handlers), [`keymesh/storage/base.py`](https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/base.py) (Async storage contract)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_async["Async runtime"]
  node_async_pool["KeyPool<br/>async lifecycle coordinator<br/>[pool.py]"]
  node_async_state["KeyState<br/>async credential state<br/>[key_state.py]"]
  node_async_storage["Async storage contract<br/>persistence abstraction<br/>[base.py]"]
  node_memory_storage[("Memory storage<br/>runtime-local storage<br/>[memory.py]")]
  node_json_storage[("JSON storage<br/>file persistence<br/>[json_storage.py]")]
end

subgraph group_sync["Sync runtime"]
  node_sync_pool["SyncKeyPool<br/>thread-safe lifecycle coordinator<br/>[sync_pool.py]"]
  node_sync_state["SyncKeyState<br/>sync credential state<br/>[sync_key_state.py]"]
  node_sync_storage["Sync storage contract<br/>persistence abstraction<br/>[sync_base.py]"]
  node_sync_json_storage[("Sync JSON storage<br/>file persistence<br/>[sync_json.py]")]
end

subgraph group_shared["Shared policies"]
  node_scheduler["Scheduler abstraction<br/>stateless selection policy<br/>[base.py]"]
  node_scheduler_policies["Selection policies<br/>round-robin, least-busy, weighted<br/>[round_robin.py]"]
  node_cooldown["Cooldown manager<br/>rate-limit recovery<br/>[manager.py]"]
  node_metrics["Pool metrics<br/>health and latency metrics<br/>[pool_metrics.py]"]
  node_semaphores["Concurrency primitives<br/>semaphore controls<br/>[semaphores.py]"]
  node_exceptions["Lifecycle exceptions<br/>public errors<br/>[exceptions.py]"]
end

subgraph group_integration["OpenAI integration"]
  node_openai_handler{{"OpenAI handlers<br/>httpx client adapters<br/>[openai_handler.py]"}}
  node_openai_sdk{{"OpenAI API<br/>external provider"}}
end

node_public_api["Public exports<br/>package API<br/>[__init__.py]"]

node_public_api -->|"exports"| node_async_pool
node_public_api -->|"exports"| node_sync_pool
node_openai_handler -->|"acquire and report"| node_async_pool
node_openai_handler -->|"acquire and report"| node_sync_pool
node_openai_handler -->|"sends requests"| node_openai_sdk
node_async_pool -->|"mutates lifecycle"| node_async_state
node_sync_pool -->|"mutates lifecycle"| node_sync_state
node_async_pool -->|"selects eligible key"| node_scheduler
node_sync_pool -->|"selects eligible key"| node_scheduler
node_scheduler_policies -->|"implements"| node_scheduler
node_async_pool -->|"applies rate-limit recovery"| node_cooldown
node_sync_pool -->|"applies rate-limit recovery"| node_cooldown
node_async_pool -->|"records outcomes"| node_metrics
node_sync_pool -->|"records outcomes"| node_metrics
node_async_pool -->|"coordinates acquisition"| node_semaphores
node_sync_pool -->|"coordinates acquisition"| node_semaphores
node_async_pool -->|"persists state"| node_async_storage
node_async_storage -->|"implemented by"| node_memory_storage
node_async_storage -->|"implemented by"| node_json_storage
node_sync_pool -->|"persists state"| node_sync_storage
node_sync_storage -->|"implemented by"| node_sync_json_storage
node_async_pool -->|"raises"| node_exceptions
node_sync_pool -->|"raises"| node_exceptions

click node_async_pool "https://github.com/rhythamtech/keymesh/blob/main/keymesh/pool/pool.py"
click node_async_state "https://github.com/rhythamtech/keymesh/blob/main/keymesh/state/key_state.py"
click node_async_storage "https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/base.py"
click node_memory_storage "https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/memory.py"
click node_json_storage "https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/json_storage.py"
click node_sync_pool "https://github.com/rhythamtech/keymesh/blob/main/keymesh/pool/sync_pool.py"
click node_sync_state "https://github.com/rhythamtech/keymesh/blob/main/keymesh/state/sync_key_state.py"
click node_sync_storage "https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/sync_base.py"
click node_sync_json_storage "https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/sync_json.py"
click node_scheduler "https://github.com/rhythamtech/keymesh/blob/main/keymesh/scheduler/base.py"
click node_scheduler_policies "https://github.com/rhythamtech/keymesh/blob/main/keymesh/scheduler/round_robin.py"
click node_cooldown "https://github.com/rhythamtech/keymesh/blob/main/keymesh/cooldown/manager.py"
click node_metrics "https://github.com/rhythamtech/keymesh/blob/main/keymesh/metrics/pool_metrics.py"
click node_semaphores "https://github.com/rhythamtech/keymesh/blob/main/keymesh/concurrency/semaphores.py"
click node_exceptions "https://github.com/rhythamtech/keymesh/blob/main/keymesh/exceptions.py"
click node_openai_handler "https://github.com/rhythamtech/keymesh/blob/main/keymesh/integrations/openai_handler.py"
click node_public_api "https://github.com/rhythamtech/keymesh/blob/main/keymesh/__init__.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_async_pool,node_async_state,node_async_storage,node_memory_storage,node_json_storage toneBlue
class node_sync_pool,node_sync_state,node_sync_storage,node_sync_json_storage toneAmber
class node_scheduler,node_scheduler_policies,node_cooldown,node_metrics,node_semaphores,node_exceptions toneMint
class node_openai_handler,node_openai_sdk toneRose
class node_public_api toneNeutral
```

## Components

### Async runtime

- [KeyPool](https://github.com/rhythamtech/keymesh/blob/main/keymesh/pool/pool.py): async lifecycle coordinator · Acquires, releases, cools down, and fails credential state. · `keymesh/pool/pool.py`
- [KeyState](https://github.com/rhythamtech/keymesh/blob/main/keymesh/state/key_state.py): async credential state · Tracks request activity, health, cooldown, and latency. · `keymesh/state/key_state.py`
- [Async storage contract](https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/base.py): persistence abstraction · `keymesh/storage/base.py`
- [Memory storage](https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/memory.py): runtime-local storage · `keymesh/storage/memory.py`
- [JSON storage](https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/json_storage.py): file persistence · `keymesh/storage/json_storage.py`

### Sync runtime

- [SyncKeyPool](https://github.com/rhythamtech/keymesh/blob/main/keymesh/pool/sync_pool.py): thread-safe lifecycle coordinator · Synchronous counterpart to the async pool. · `keymesh/pool/sync_pool.py`
- [SyncKeyState](https://github.com/rhythamtech/keymesh/blob/main/keymesh/state/sync_key_state.py): sync credential state · Uses synchronous state and locking semantics. · `keymesh/state/sync_key_state.py`
- [Sync storage contract](https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/sync_base.py): persistence abstraction · `keymesh/storage/sync_base.py`
- [Sync JSON storage](https://github.com/rhythamtech/keymesh/blob/main/keymesh/storage/sync_json.py): file persistence · `keymesh/storage/sync_json.py`

### Shared policies

- [Scheduler abstraction](https://github.com/rhythamtech/keymesh/blob/main/keymesh/scheduler/base.py): stateless selection policy · Selects from candidates made eligible by pools. · `keymesh/scheduler/base.py`
- [Selection policies](https://github.com/rhythamtech/keymesh/blob/main/keymesh/scheduler/round_robin.py): round-robin, least-busy, weighted · `keymesh/scheduler/round_robin.py`
- [Cooldown manager](https://github.com/rhythamtech/keymesh/blob/main/keymesh/cooldown/manager.py): rate-limit recovery · Handles cooldown durations and Retry-After values. · `keymesh/cooldown/manager.py`
- [Pool metrics](https://github.com/rhythamtech/keymesh/blob/main/keymesh/metrics/pool_metrics.py): health and latency metrics · Aggregates EMA latency and success/failure signals. · `keymesh/metrics/pool_metrics.py`
- [Concurrency primitives](https://github.com/rhythamtech/keymesh/blob/main/keymesh/concurrency/semaphores.py): semaphore controls · Supports high-frequency credential acquisition. · `keymesh/concurrency/semaphores.py`
- [Lifecycle exceptions](https://github.com/rhythamtech/keymesh/blob/main/keymesh/exceptions.py): public errors · Reports exhaustion, eligibility, and lifecycle failures. · `keymesh/exceptions.py`

### OpenAI integration

- [OpenAI handlers](https://github.com/rhythamtech/keymesh/blob/main/keymesh/integrations/openai_handler.py): httpx client adapters · Injects credentials and reports HTTP outcomes to pools. · `keymesh/integrations/openai_handler.py`
- **OpenAI API**: external provider · Actual requests are delegated through OpenAI/httpx.

### Other components

- [Public exports](https://github.com/rhythamtech/keymesh/blob/main/keymesh/__init__.py): package API · `keymesh/__init__.py`

## Connections

- Public exports → KeyPool: exports
- Public exports → SyncKeyPool: exports
- OpenAI handlers → KeyPool: acquire and report
- OpenAI handlers → SyncKeyPool: acquire and report
- OpenAI handlers → OpenAI API: sends requests
- KeyPool → KeyState: mutates lifecycle
- SyncKeyPool → SyncKeyState: mutates lifecycle
- KeyPool → Scheduler abstraction: selects eligible key
- SyncKeyPool → Scheduler abstraction: selects eligible key
- Selection policies → Scheduler abstraction: implements
- KeyPool → Cooldown manager: applies rate-limit recovery
- SyncKeyPool → Cooldown manager: applies rate-limit recovery
- KeyPool → Pool metrics: records outcomes
- SyncKeyPool → Pool metrics: records outcomes
- KeyPool → Concurrency primitives: coordinates acquisition
- SyncKeyPool → Concurrency primitives: coordinates acquisition
- KeyPool → Async storage contract: persists state
- Async storage contract → Memory storage: implemented by
- Async storage contract → JSON storage: implemented by
- SyncKeyPool → Sync storage contract: persists state
- Sync storage contract → Sync JSON storage: implemented by
- KeyPool → Lifecycle exceptions: raises
- SyncKeyPool → Lifecycle exceptions: raises
