# How OAuth Session Occupancy Manages Concurrent Access for Claude Code and Kimi in OmniRoute

> Discover how OmniRoute leverages OAuth session occupancy to manage concurrent access for Claude Code and Kimi, preventing token collisions and ensuring atomic session selection.

- Repository: [Diego Rodrigues de Sa e Souza/OmniRoute](https://github.com/diegosouzapw/OmniRoute)
- Tags: deep-dive
- Published: 2026-08-16

---

**TL;DR:** OmniRoute uses OAuth session occupancy as a concurrency-control mechanism to ensure that OAuth-based providers like Claude Code and Kimi allow only one active request per connection at a time, preventing token collisions and enforcing atomic session selection.

OmniRoute is an open-source request router that handles multiple AI providers through a unified interface. When working with OAuth-based providers such as **Claude Code** and **Kimi**, the system must manage session tokens rather than static API keys. This article explains how OmniRoute's **OAuth session occupancy** system ensures safe, atomic access to these limited resources.

## What Is OAuth Session Occupancy?

OAuth session occupancy is a lightweight locking mechanism that tracks which connections are actively in use. According to the OmniRoute source code, it maintains a global `Map<string, Map<string, SessionLease>>` called `occupancy` that indexes:

- **Outer key:** The `connectionId` (unique OAuth account)
- **Inner key:** The `sessionKey` (unique per request)
- **Value:** A `SessionLease` object containing release callbacks

This structure enables OmniRoute to enforce **per-connection concurrency limits**—typically one active session per OAuth account—while supporting multiple distinct OAuth accounts simultaneously.

## Core Functions in oauthSessionOccupancy.ts

The occupancy system is implemented in [[`open-sse/services/oauthSessionOccupancy.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/open-sse/services/oauthSessionOccupancy.ts)](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/open-sse/services/oauthSessionOccupancy.ts). Four key functions control session lifecycle:

| Function | Purpose |
|----------|---------|
| `reserveOAuthSession(connectionId, sessionKey)` | Atomically reserves a session slot; returns `SessionLease` or `null` if at capacity |
| `wrapResponseWithOAuthSessionRelease(response, lease)` | Wraps the response stream to auto-release the lease on completion |
| `getOAuthSessionAvailability(connectionId)` | Returns boolean indicating if the connection has capacity |
| `getForeignOAuthSessionCount(connectionId, sessionKey)` | Counts other active sessions for the same connection (excluding current session) |

A test-only helper `_clearOAuthSessionOccupancyForTest()` resets the occupancy map for clean unit test isolation.

## How Claude Code and Kimi Use Session Occupancy

Providers like **Claude Code** and **Kimi** are flagged in their provider profiles as requiring OAuth session reservation. In [[`src/sse/handlers/chat.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/sse/handlers/chat.ts)](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/src/sse/handlers/chat.ts), the chat handler implements this flow:

1. **Detect OAuth requirement** — Check if `reserveOAuthSession: true` in the provider configuration
2. **Generate session key** — Create a unique `occupancySessionKey` for this request
3. **Reserve the session** — Call `reserveOAuthSession(connectionId, occupancySessionKey)` to acquire the lock
4. **Wrap the response** — Use `wrapResponseWithOAuthSessionRelease()` to ensure cleanup
5. **Execute the request** — Proceed with the OAuth-authenticated call

```typescript
// From src/sse/handlers/chat.ts (conceptual flow)
import {
  reserveOAuthSession,
  wrapResponseWithOAuthSessionRelease,
  type SessionLease
} from '@/open-sse/services/oauthSessionOccupancy';

async function handleChatRequest(req, res) {
  const { connectionId, provider } = req;
  
  // Only OAuth providers like Claude Code and Kimi need this
  if (provider.requiresOAuthSession) {
    const sessionKey = generateSessionKey();
    const lease = reserveOAuthSession(connectionId, sessionKey);
    
    if (!lease) {
      throw new Error('OAuth connection at capacity - try another account');
    }
    
    const response = await streamChatResponse(req);
    return wrapResponseWithOAuthSessionRelease(response, lease);
  }
  
  return streamChatResponse(req);
}

```

## Why This Matters for OAuth Providers

OAuth-based providers impose constraints that make occupancy control essential:

- **Token refresh race conditions** — Only one request should refresh an expired token at a time
- **Provider rate limits** — Claude Code and Kimi typically allow only one active conversation per OAuth account
- **Billing precision** — Prevents double-counting or ambiguous usage attribution

The occupancy system fails fast: if a connection is busy, `reserveOAuthSession` returns `null` immediately, allowing OmniRoute to **fallback to another available OAuth account** or return a clear error to the caller.

## Testing Session Occupancy Atomicity

The test suite in [[`tests/unit/sse-auth.test.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/tests/unit/sse-auth.test.ts)](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/tests/unit/sse-auth.test.ts) validates the occupancy mechanism with mock connections:

```typescript
// Tests concurrent reservation behavior
test('concurrent OAuth selections reserve different available accounts atomically', () => {
  const connA = 'codex-occupancy-a';
  const connB = 'codex-occupancy-b';
  
  const leaseA = reserveOAuthSession(connA, 'session-a');
  const leaseB = reserveOAuthSession(connB, 'session-b');
  
  // Verify isolation between connections
  expect(getForeignOAuthSessionCount(connA, 'session-b')).toBe(0);
  expect(getForeignOAuthSessionCount(connB, 'session-a')).toBe(0);
  
  // Verify same-connection counting works
  const leaseA2 = reserveOAuthSession(connA, 'session-a2');
  expect(getForeignOAuthSessionCount(connA, 'session-a2')).toBe(1);
  
  // Cleanup
  leaseA.releaseOAuthSession?.();
  leaseB.releaseOAuthSession?.();
  leaseA2?.releaseOAuthSession?.();
  _clearOAuthSessionOccupancyForTest();
});

```

## Provider Configuration

OAuth session requirements are defined in provider profiles. While the exact flag location may vary, providers like Claude Code and Kimi set properties indicating:

- `authType: 'oauth'` — Uses OAuth flow instead of API key
- `reserveOAuthSession: true` — Requires occupancy reservation
- `maxConcurrentSessions: 1` — Typical limit for these providers

These configurations are referenced in [[`src/shared/constants/providers.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/shared/constants/providers.ts)](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/src/shared/constants/providers.ts) or equivalent provider registry files.

## Summary

- OAuth session occupancy provides **atomic, per-connection locking** for OAuth-based providers
- **Claude Code** and **Kimi** require this mechanism due to single-session-per-account limits
- The `reserveOAuthSession()` / `wrapResponseWithOAuthSessionRelease()` pattern ensures **automatic cleanup** even on stream errors
- `getForeignOAuthSessionCount()` enables **diagnostics and capacity-aware routing**
- Fail-fast behavior allows **graceful fallback** to alternative OAuth accounts

## Frequently Asked Questions

### What happens if an OAuth connection is already occupied?

When `reserveOAuthSession()` detects that a connection is at capacity (typically one active session), it returns `null`. The calling handler in [`src/sse/handlers/chat.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/sse/handlers/chat.ts) can then select a different available OAuth account or return an error indicating temporary unavailability. This prevents queue buildup and gives clear feedback to callers.

### Does session occupancy block requests or queue them?

OmniRoute uses a **non-blocking fail-fast approach**. Rather than queuing requests, `reserveOAuthSession()` returns immediately with either a lease or `null`. This design choice keeps latency predictable and pushes queueing decisions to higher-level routing logic where fallback strategies can be applied.

### How does the system handle request failures or crashes?

The `wrapResponseWithOAuthSessionRelease()` utility attaches the lease release to the response stream's close and error events. Even if the request throws an exception or the connection drops, the cleanup handler runs, removing the session key from the occupancy map and freeing the slot for subsequent requests.