Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
8ab1346
docs: realtime pre-warmed connection pool design + raw-passthrough fo…
ishaan-jaff Jun 24, 2026
80c341d
docs: realtime pool benchmark, repro steps, and deploy guidance
ishaan-jaff Jun 24, 2026
51e9496
feat: expose Router::deployments() for host-side upstream enumeration
ishaan-jaff Jun 24, 2026
030516f
refactor: split realtime dial/splice and add warm-handoff entry point
ishaan-jaff Jun 24, 2026
bc917b7
feat: pre-warmed upstream realtime connection pool with fresh-dial fa…
ishaan-jaff Jun 24, 2026
c82aae6
feat: add realtime pool handle to gateway AppState
ishaan-jaff Jun 24, 2026
1fabaaf
feat: try warm pooled upstream before fresh-dial in realtime service
ishaan-jaff Jun 24, 2026
9392d0c
feat: thread realtime pool through the realtime route bridge
ishaan-jaff Jun 24, 2026
5ee042c
feat: build and pre-warm the realtime pool at gateway startup
ishaan-jaff Jun 24, 2026
25e68dd
build: lean Dockerfile for the realtime gateway (default features, en…
ishaanj-berri Jun 24, 2026
4fa5c1b
docs: add generic ai-gateway benchmarking skill
ishaanj-berri Jun 24, 2026
6210975
docs: drop per-endpoint realtime benchmark README
ishaanj-berri Jun 24, 2026
ffc661e
test: add sanitized realtime WS load-gen harness for gateway benchmarks
ishaanj-berri Jun 24, 2026
01ee3cf
test: add hosted-runner serve.sh wrapper for the realtime harness
ishaanj-berri Jun 24, 2026
a42c0be
test: make serve.sh publish result atomically and clear stale output
ishaanj-berri Jun 24, 2026
08d5a4c
perf: refill the realtime pool concurrently so warm supply keeps up a…
ishaanj-berri Jun 24, 2026
4882202
build: drop Dockerfile.lean
ishaanj-berri Jun 24, 2026
f01eeb7
docs: slim benchmarks/realtime to a README (harness moved to its own …
ishaanj-berri Jun 24, 2026
e128f45
docs: add realtime route README with pooling design + diagram
ishaanj-berri Jun 24, 2026
e1f3fb6
fix: satisfy clippy manual_flatten on concurrent pool refill
ishaanj-berri Jun 24, 2026
1ad035b
Update litellm-rust/crates/providers/src/realtime_pool.rs
Jun 24, 2026
ed952e5
Update litellm-rust/crates/providers/src/realtime_pool.rs
Jun 24, 2026
6d59860
fix: back off the realtime pool replenisher for failing keys
ishaanj-berri Jun 24, 2026
2988237
docs: document the replenisher backoff in the realtime route README
ishaanj-berri Jun 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions litellm-rust/crates/ai-gateway/benchmarks/realtime/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Realtime gateway benchmark β€” pool on/off

Measures what the gateway adds over talking to OpenAI's realtime WebSocket
directly, and what the pre-warmed connection pool removes. See
`../../src/routes/realtime/README.md` for how the pool works.

## Results

5000 calls / 500 concurrency, gateway at 10 instances, pool ON
(`REALTIME_POOL_SIZE=64`), upstream OpenAI `gpt-realtime`. Each leg run twice.
Times in **ms**. Phases per connection: **dial** = TCP+TLS+WS upgrade,
**session** = upgrade β†’ `session.created` (the phase the pool removes),
**1st-audio** = `response.create` β†’ first audio delta (OpenAI inference),
**total** = full wall-clock.

| metric | Direct OpenAI | Gateway (pool ON) | Overhead (ms) | vs OpenAI |
| ------------------ | ------------- | ----------------- | ------------- | ---------- |
| success rate (%) | 99.8 | 99.8 | β€” | β€” |
| dial p50 (ms) | 276 | 158 | βˆ’118 | **faster** |
| session p50 (ms) | 7 | 0 | βˆ’7 | **faster** |
| 1st-audio p50 (ms) | 440 | 664 | +224 | slowerΒΉ |
| total p50 (ms) | 816 | 1010 | +194 | slowerΒΉ |
| total p95 (ms) | 2152 | 1970 | βˆ’182 | **faster** |
| total p99 (ms) | 2692 | 2610 | βˆ’82 | **faster** |

The gateway is **faster than direct on 4 of 6 metrics**. The warm pool makes the
**session phase sub-millisecond** at the median β€” ~76% of connects hit the pool,
~70% had session < 1 ms. ΒΉ The two "slower" rows are not gateway overhead:
`1st-audio` is OpenAI's own inference time (the gateway only relays it), which ran
slower during the gateway legs and drags `total p50` with it.

**Pool OFF** (control, `REALTIME_POOL_SIZE=0`): session p50 was **367 ms** β€” the
fresh-dial overhead the pool removes.

## Reproduce

The load generator lives in a separate repo:
**https://github.com/ishaan-berri/litellm-realtime-bench**

```bash
git clone https://github.com/ishaan-berri/litellm-realtime-bench
cd litellm-realtime-bench && go build -o wsbench .

# Direct to OpenAI (baseline)
./wsbench -host api.openai.com -key "$OPENAI_API_KEY" -m gpt-realtime -n 5000 -c 500 -t 60

# Through the gateway β€” run once with pool ON, once with REALTIME_POOL_SIZE=0
./wsbench -host <gateway-host> -key "$LITELLM_MASTER_KEY" -m gpt-realtime -n 5000 -c 500 -t 60
```

Run the gateway with the env stand-in (`OPENAI_REALTIME_MODEL=gpt-realtime`,
`OPENAI_API_KEY`, `LITELLM_MASTER_KEY`, `REALTIME_POOL_SIZE`, `HOST=0.0.0.0`). At
500 concurrency over N instances, size the pool to `β‰ˆ 500 / N` per instance (64 was
used here for 10 instances). The bench repo's README covers running 500-concurrency
legs from a hosted multi-vCPU runner. **Never commit keys β€” pass them via `-key`.**
45 changes: 44 additions & 1 deletion litellm-rust/crates/ai-gateway/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod state;
use std::sync::Arc;

use litellm_core::router::{Deployment, LiteLLMParams, Router};
use litellm_providers::realtime_pool::{upstream_key, PoolConfig, RealtimePool};

use crate::state::AppState;

Expand All @@ -37,9 +38,30 @@ async fn main() {
);
}

let router = Arc::new(build_router());

// Build the pre-warmed realtime pool and register each deployment's upstream
// so the background replenisher starts warming it. `REALTIME_POOL_SIZE=0`
// yields a disabled pool β†’ every connect fresh-dials (original behavior).
let pool_config = PoolConfig::from_env();
let realtime_pool = RealtimePool::spawn(pool_config);
if pool_config.enabled() {
register_deployments(&router, &realtime_pool);
eprintln!(
"realtime connection pool enabled: target {} warm sockets/key, max idle {}s",
pool_config.target_size,
pool_config.max_idle.as_secs()
);
} else {
eprintln!(
"realtime connection pool disabled (REALTIME_POOL_SIZE=0); fresh-dialing each connect"
);
}

let state = AppState {
router: Arc::new(build_router()),
router,
master_key,
realtime_pool,
};

let host = std::env::var("HOST").unwrap_or_else(|_| DEFAULT_HOST.to_string());
Expand All @@ -54,6 +76,27 @@ async fn main() {
.expect("server error");
}

/// Register every deployment's upstream key with the pool so the replenisher
/// pre-warms it. Mirrors `service::run`'s key derivation (strip `openai/`, resolve
/// api_key); deployments whose key can't be resolved are skipped (they fresh-dial
/// and surface the auth error on the request path, as before).
fn register_deployments(router: &Router, pool: &RealtimePool) {
for deployment in router.deployments() {
let params = &deployment.litellm_params;
let provider_model = params
.model
.strip_prefix("openai/")
.unwrap_or(&params.model);
if let Some(key) = upstream_key(
provider_model,
params.api_key.as_deref(),
params.api_base.as_deref(),
) {
pool.register(key);
}
}
}

/// Resolve `PORT`, warning (rather than silently defaulting) on an invalid value.
fn resolve_port() -> u16 {
match std::env::var("PORT") {
Expand Down
82 changes: 82 additions & 0 deletions litellm-rust/crates/ai-gateway/src/routes/realtime/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Realtime route (`GET /v1/realtime`)

Proxies OpenAI's realtime WebSocket. `mod.rs` is the axum surface (handler +
socket↔events adapter); `service.rs` is the pure logic (select a deployment, then
splice client ↔ upstream). The pool itself lives in
Comment thread
This conversation was marked as resolved.
Resolved
`crates/providers/src/realtime_pool.rs`.

## Connection pooling

### The problem

The gateway's realtime overhead lives **entirely in session establishment**. On each
client connect it dials a *fresh* upstream WS to OpenAI and waits for
`session.created` before it can serve. Measured at 5000 calls / 500 concurrency, the
fresh-dial session phase is **~360 ms** vs **~7 ms** direct; dial, first-audio, and
streaming add ~0. So the one lever is removing that per-connect handshake from the
critical path.

### The idea

Keep a few upstream OpenAI sockets **already connected and already past
`session.created`** (buffered). On a client connect, hand off a warm socket β€” relay
its buffered `session.created` instantly (a local `Vec::pop`, sub-millisecond) and
splice exactly as a fresh dial would. A background task keeps the pool topped up. On
a miss or dead socket we fall back to fresh-dial: the pool is a latency optimization,
never a correctness dependency.

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
client connect ──────► β”‚ routes/realtime β†’ service::run β”‚
β”‚ pool.take(key) β”‚
β”‚ hit β†’ relay buffered β”‚
β”‚ session.created, then splice β”‚
β”‚ miss β†’ fresh dial (original path) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚ replenish (async, concurrent)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
background task ─────► β”‚ RealtimePool: per-key warm sockets β”‚
β”‚ each = { ws, buffered session.created}β”‚
β”‚ liveness-checked before handoff β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

A warm session is indistinguishable from a fresh one: OpenAI sends `session.created`
unprompted on connect, we pre-read exactly that one frame and relay it on handoff,
and we send nothing else on the socket before a client exists β€” so the client's first
`session.update` behaves identically either way.

### Sizing

Each warm socket serves **exactly one** session (realtime isn't multiplexed), so the
pool is sized to the **peak concurrent connects per instance**, not total live
connections:

```
REALTIME_POOL_SIZE β‰ˆ peak_concurrency / instance_count
```

e.g. 500 concurrency over 10 instances β†’ ~50–64 per instance. The replenisher dials
the missing sockets **concurrently**, so a drained pool refills in ~one handshake
window and keeps supply close to the connect rate. Over-provisioning just burns idle
upstream sockets, which is why warm sockets are short-lived
(`REALTIME_POOL_MAX_IDLE_SECS`).

### Config

| env | default | meaning |
| ----------------------------- | ------- | --------------------------------------------------------------- |
| `REALTIME_POOL_SIZE` | `4` | target warm sockets per key. `0` disables pooling (fresh-dial). |
| `REALTIME_POOL_MAX_IDLE_SECS` | `30` | max time a warm socket sits before it's closed and replaced. |

### Notes

- **Miss / dead socket β†’ fresh dial.** Burst beyond warm supply, or a socket that
died, never blocks or fails β€” it falls back to the original path. The pool can only
make a connect faster, never slower or more fragile.
- **Auth scope.** The pool key includes `api_key`, so a warm socket is only handed to
a request resolving to the same key β€” no cross-tenant reuse.
- **Idle billing.** Warm sockets are liveness-checked at handoff and capped at
`REALTIME_POOL_MAX_IDLE_SECS` to bound idle billing and dodge OpenAI's idle timeout.

Benchmarks and repro: `../../benchmarks/realtime/README.md`.
13 changes: 10 additions & 3 deletions litellm-rust/crates/ai-gateway/src/routes/realtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use axum::Router;
use futures_util::{SinkExt, StreamExt};
use litellm_core::realtime::types::RealtimeEvent;
use litellm_core::router::Router as ModelRouter;
use litellm_providers::realtime_pool::RealtimePool;
use serde::Deserialize;

use crate::auth::RequireMasterKey;
Expand Down Expand Up @@ -55,13 +56,19 @@ async fn handle(
}

let router = state.router.clone();
let pool = state.realtime_pool.clone();
let model = query.model;
Ok(ws.on_upgrade(move |socket| bridge(socket, router, model)))
Ok(ws.on_upgrade(move |socket| bridge(socket, router, pool, model)))
}

/// Adapt the axum socket (text frames) to the typed-event `Stream`/`Sink` the
/// service wants, keeping axum types out of `service`.
async fn bridge(socket: WebSocket, router: Arc<ModelRouter>, model: String) {
async fn bridge(
socket: WebSocket,
router: Arc<ModelRouter>,
pool: Arc<RealtimePool>,
model: String,
) {
let (ws_sink, ws_stream) = socket.split();

let client_in = ws_stream.filter_map(|message| async move {
Expand All @@ -77,5 +84,5 @@ async fn bridge(socket: WebSocket, router: Arc<ModelRouter>, model: String) {
});

futures_util::pin_mut!(client_in, client_out);
let _ = service::run(&router, &model, None, client_in, client_out).await;
let _ = service::run(&router, &pool, &model, None, client_in, client_out).await;
}
31 changes: 31 additions & 0 deletions litellm-rust/crates/ai-gateway/src/routes/realtime/service.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
//! Business logic: select a deployment with the (pure) core router, then call the
//! provider splice. The seam between `core::router` (selection only) and
//! `providers` (the actual WebSocket I/O).
//!
//! On connect we try a pre-warmed upstream from the pool (handshake already paid,
//! `session.created` buffered) and relay it instantly. On a pool miss or dead warm
//! socket we fresh-dial exactly as before β€” the pool is never on the critical path
//! for correctness, only latency.

use std::time::Duration;

Expand All @@ -9,10 +14,16 @@ use litellm_core::error::CoreError;
use litellm_core::realtime::types::RealtimeEvent;
use litellm_core::router::Router;
use litellm_core::CoreResult;
use litellm_providers::realtime_pool::{upstream_key, RealtimePool};

/// Select a deployment for `model` and splice the client stream to the provider.
///
/// `pool` supplies a pre-warmed upstream when one is available; otherwise we
/// fresh-dial. A disabled pool always misses, so this collapses to the original
/// fresh-dial behavior.
pub async fn run<In, Out>(
router: &Router,
pool: &RealtimePool,
model: &str,
idle_timeout: Option<Duration>,
client_in: In,
Expand All @@ -33,6 +44,26 @@ where
.strip_prefix("openai/")
.unwrap_or(&params.model);

// Warm path: take a pooled upstream (handshake already paid) and relay its
// buffered session.created immediately. On miss/dead socket fall through.
if let Some(key) = upstream_key(
provider_model,
params.api_key.as_deref(),
params.api_base.as_deref(),
) {
if let Some(handoff) = pool.take(&key) {
return litellm_providers::realtime::realtime_warm(
provider_model,
handoff,
idle_timeout,
client_in,
client_out,
)
.await;
}
}

// Cold path: fresh dial (the original behavior).
litellm_providers::realtime::realtime(
provider_model,
params.api_key.as_deref(),
Expand Down
5 changes: 5 additions & 0 deletions litellm-rust/crates/ai-gateway/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::sync::Arc;

use litellm_core::router::Router;
use litellm_providers::realtime_pool::RealtimePool;

/// Shared application state handed to every route handler.
#[derive(Clone)]
Expand All @@ -9,4 +10,8 @@ pub struct AppState {
/// The gateway master key. Any caller presenting it as a bearer token may
/// invoke the gateway. `None` β†’ auth not configured (routes fail closed).
pub master_key: Option<Arc<str>>,
/// Pre-warmed upstream realtime connection pool. Disabled
/// (`RealtimePool::disabled()`) when `REALTIME_POOL_SIZE=0`, in which case
/// every realtime connect fresh-dials exactly as before.
pub realtime_pool: Arc<RealtimePool>,
}
6 changes: 6 additions & 0 deletions litellm-rust/crates/core/src/router/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ impl Router {
}
}

/// All deployments in the `model_list`. Read-only; used by the host to
/// enumerate upstreams (e.g. to pre-warm a connection pool per deployment).
pub fn deployments(&self) -> &[Deployment] {
&self.model_list
}

/// Whether any deployment is registered under `model`.
pub fn has_deployment(&self, model: &str) -> bool {
self.model_list
Expand Down
1 change: 1 addition & 0 deletions litellm-rust/crates/providers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pub mod mistral;
pub mod ocr;
pub mod openai;
pub mod realtime;
pub mod realtime_pool;
Loading
Loading