> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch15-piagent-runtime-core/15.3-queue-and-concurrency-control.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 15.3 Queue and Concurrency Control

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~350,000 tokens, Output \~28,000 tokens (chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

AI conversation systems face a unique concurrency challenge: LLM calls are both expensive and time-consuming (typically 5-60 seconds), and conversation history in the same session must be strictly ordered. OpenClaw implements fine-grained concurrency control through a **Lane** system—ensuring serialization within the same session while allowing parallel execution across different sessions and subagents.

## 15.3.1 Session Lane Serialization

### Why Session-Level Serialization is Needed

Imagine a user rapidly sends three messages in succession:

```
User: Help me write a sorting algorithm      ← Message 1
User: In Python                              ← Message 2 (200ms later)
User: I want quicksort                       ← Message 3 (100ms later)
```

If all three messages trigger three concurrent LLM calls, they would simultaneously read the same conversation history file, each independently generate a reply, then attempt to write to history at the same time—causing data races and conversation chaos.

**Session lanes** solve this problem: all requests with the same session key are queued on the same lane and execute strictly serially.

### Lane Resolution

Each Agent run first resolves which session lane it belongs to:

```typescript
// src/agents/pi-embedded-runner/lanes.ts
export function resolveSessionLane(key: string) {
  const cleaned = key.trim() || CommandLane.Main;
  return cleaned.startsWith("session:") ? cleaned : `session:${cleaned}`;
}

export function resolveGlobalLane(lane?: string) {
  const cleaned = lane?.trim();
  return cleaned ? cleaned : CommandLane.Main;
}
```

Session lane names follow the format `session:{sessionKey}`, for example:

```
session:agent:main:telegram:default:dm:12345
session:agent:work:slack:T01234:dm:U56789
```

Each different `sessionKey` corresponds to an independent lane, ensuring requests in the same conversation don't interfere with each other, while different conversations can be processed in parallel.

## 15.3.2 Global Lane Rate Limiting

In addition to session-level serialization, OpenClaw also needs to limit the total number of concurrent LLM calls globally. This is because:

1. **API rate limits**—most LLM providers limit the number of concurrent requests
2. **Resource protection**—each LLM call consumes significant memory (conversation context) and network bandwidth
3. **Cost control**—higher concurrency means more tokens consumed in a short time

### Global Lane Types

OpenClaw defines four types of global lanes:

```typescript
// src/process/lanes.ts
export const enum CommandLane {
  Main = "main",         // Main lane: user-initiated conversations
  Cron = "cron",         // Scheduled task lane
  Subagent = "subagent", // Subagent lane
  Nested = "nested",     // Nested call lane
}
```

Each lane type has independent concurrency limits:

```typescript
// src/gateway/server-lanes.ts
export function applyGatewayLaneConcurrency(cfg: ReturnType<typeof loadConfig>) {
  setCommandLaneConcurrency(CommandLane.Cron, cfg.cron?.maxConcurrentRuns ?? 1);
  setCommandLaneConcurrency(CommandLane.Main, resolveAgentMaxConcurrent(cfg));
  setCommandLaneConcurrency(CommandLane.Subagent, resolveSubagentMaxConcurrent(cfg));
}
```

| Lane     | Default Concurrency | Purpose                                       |
| -------- | ------------------- | --------------------------------------------- |
| Main     | Configurable        | Direct user conversations                     |
| Cron     | 1                   | Scheduled tasks (heartbeats, reminders, etc.) |
| Subagent | Configurable        | Subagent background tasks                     |
| Nested   | Unlimited           | Nested tool calls                             |

### Two-Level Queueing

Agent run queueing is **nested**—first queue on session lane, then on global lane:

```typescript
// src/agents/pi-embedded-runner/run.ts
return enqueueSession(() =>       // First queue on session lane
  enqueueGlobal(async () => {     // Then queue on global lane
    // ... actual LLM call ...
  }),
);
```

This means a request needs to obtain two "passes" to execute: a turn on the session lane + a concurrency slot on the global lane.

```
Request A (session-1): ── Session lane queue ──→ Get session turn ──→ Global lane queue ──→ Execute
Request B (session-1): ── Session lane queue (wait for A)
Request C (session-2): ── Session lane queue ──→ Get session turn ──→ Global lane queue ──→ Execute
```

Requests A and C belong to different sessions and can simultaneously enter the global lane queue (even execute in parallel). But request B must wait for A to complete before entering the global lane.

## 15.3.3 Queue Modes: collect / steer / followup

When Agent is busy processing a request, what should happen to new messages? OpenClaw provides multiple **queue modes** to handle this situation:

```typescript
// src/auto-reply/reply/queue/types.ts
export type QueueMode =
  | "steer"          // Steer: inject into the running Agent loop
  | "followup"       // Followup: queue and auto-execute after current run ends
  | "collect"        // Collect: merge into one message then execute (default)
  | "steer-backlog"  // Steer first, fallback to collect if fails
  | "interrupt"      // Interrupt: abort current run and execute new message
  | "queue";         // Simple queue
```

### Collect Mode (Default)

Collect mode is the most conservative strategy. Multiple messages received while Agent is busy are collected and merged, then executed as a single merged message after the current run ends:

```
User: Help me write sorting            ← Agent starts processing
User: In Python                        ← Collect (Agent busy)
User: I want quicksort                 ← Collect (Agent busy)
Agent: [Reply with sorting]            ← First run ends
Agent: [Process "In Python + I want quicksort"]  ← Auto-execute after merge
```

### Steer Mode

Steer mode allows new messages to be **injected** into the running Agent loop. This leverages a characteristic of LLM conversations—during streaming output, new user messages can be appended:

```typescript
// src/agents/pi-embedded-runner/runs.ts
export function queueEmbeddedPiMessage(sessionId: string, text: string): boolean {
  const handle = ACTIVE_EMBEDDED_RUNS.get(sessionId);
  if (!handle || !handle.isStreaming() || handle.isCompacting()) return false;
  void handle.queueMessage(text);
  return true;
}
```

Steering only works when Agent is in the middle of streaming output. If Agent is still waiting for the LLM's first response, steering fails and falls back to collect mode.

### Followup Mode

Followup mode queues new messages to **automatically trigger** a new Agent loop after the current run ends. This guarantees each message gets independent processing:

```
User: Help me write sorting            ← Agent starts processing
User: Also, check my emails            ← Queue (independent task)
Agent: [Reply with sorting]            ← First run ends
Agent: [Auto-process email request]    ← Auto-trigger second run
```

### Queue Configuration

Queue mode can be configured at multiple levels, with priority from high to low:

```typescript
// src/auto-reply/reply/queue/settings.ts
export function resolveQueueSettings(params: ResolveQueueSettingsParams): QueueSettings {
  const resolvedMode =
    params.inlineMode ??                              // 1. Inline specification
    normalizeQueueMode(params.sessionEntry?.queueMode) ?? // 2. Session level
    normalizeQueueMode(providerModeRaw) ??            // 3. Channel level
    normalizeQueueMode(queueCfg?.mode) ??             // 4. Global config
    defaultQueueModeForChannel(channelKey);            // 5. Channel default (collect)
}
```

Queue also supports two important parameters:

| Parameter    | Default           | Description                                                              |
| ------------ | ----------------- | ------------------------------------------------------------------------ |
| `debounceMs` | Varies by channel | Debounce delay—consecutive messages within this time are merged into one |
| `cap`        | Config-determined | Queue cap—discard old or new messages when exceeded                      |

## 15.3.4 Lane Implementation (`src/process/command-queue.ts`)

The core implementation of the lane system is a lightweight in-process queue:

### Data Structure

```typescript
// src/process/command-queue.ts
type QueueEntry = {
  task: () => Promise<unknown>;
  resolve: (value: unknown) => void;
  reject: (reason?: unknown) => void;
  enqueuedAt: number;
  warnAfterMs: number;
  onWait?: (waitMs: number, queuedAhead: number) => void;
};

type LaneState = {
  lane: string;
  queue: QueueEntry[];   // Pending tasks
  active: number;        // Current active task count
  maxConcurrent: number; // Maximum concurrency
  draining: boolean;     // Whether currently draining
};

const lanes = new Map<string, LaneState>();
```

Each lane maintains a FIFO queue, an active counter, and a maximum concurrency limit. Session lanes always have `maxConcurrent` of 1 (serial), while global lanes have `maxConcurrent` determined by configuration.

### Drain Pump

The core scheduling algorithm of the queue is a **drain pump**:

```typescript
// src/process/command-queue.ts
function drainLane(lane: string) {
  const state = getLaneState(lane);
  if (state.draining) return;
  state.draining = true;

  const pump = () => {
    // As long as there are idle concurrency slots and queue is not empty, dequeue and execute
    while (state.active < state.maxConcurrent && state.queue.length > 0) {
      const entry = state.queue.shift()!;
      state.active += 1;
      void (async () => {
        try {
          const result = await entry.task();
          state.active -= 1;
          pump();  // Recursion: immediately try next task after completion
          entry.resolve(result);
        } catch (err) {
          state.active -= 1;
          pump();  // Continue draining even on failure
          entry.reject(err);
        }
      })();
    }
    state.draining = false;
  };

  pump();
}
```

> **Sidebar**: **Drain Pump** is a common asynchronous queue scheduling pattern. Its core idea is: whenever a task completes (or a new task is enqueued), try to dequeue as many tasks as possible and execute them concurrently until reaching the concurrency limit or the queue is empty. This pattern avoids the overhead of periodic polling and achieves efficient event-driven scheduling.

### Enqueue and Timeout Warning

```typescript
// src/process/command-queue.ts
export function enqueueCommandInLane<T>(
  lane: string,
  task: () => Promise<T>,
  opts?: { warnAfterMs?: number; onWait?: (waitMs: number, queuedAhead: number) => void },
): Promise<T> {
  const state = getLaneState(lane);
  return new Promise<T>((resolve, reject) => {
    state.queue.push({
      task: () => task(),
      resolve: (value) => resolve(value as T),
      reject,
      enqueuedAt: Date.now(),
      warnAfterMs: opts?.warnAfterMs ?? 2_000,
      onWait: opts?.onWait,
    });
    drainLane(lane);  // Immediately try to drain after enqueue
  });
}
```

Each enqueued task records its enqueue time and warning threshold. When the task finally dequeues and executes, if the wait time exceeds `warnAfterMs` (default 2 seconds), the system outputs a diagnostic warning. This is very useful for discovering bottlenecks—if a lane's wait time is consistently long, it suggests that lane's concurrency limit may need to be increased.

### Auxiliary Queries

```typescript
// src/process/command-queue.ts
export function getQueueSize(lane: string = CommandLane.Main) {
  const state = lanes.get(lane);
  return state ? state.queue.length + state.active : 0;
}

export function getTotalQueueSize() {
  let total = 0;
  for (const s of lanes.values()) {
    total += s.queue.length + s.active;
  }
  return total;
}
```

`getQueueSize` returns the total of pending + active (not just pending), making it more accurately reflect the system's current load.

***

## Summary of This Section

1. **Session lanes** ensure requests in the same session execute strictly serially, preventing concurrent write conflicts in conversation history. Each `sessionKey` corresponds to an independent lane.
2. **Global lanes** limit the total number of concurrent LLM calls across the system, divided into four types (Main, Cron, Subagent, Nested), each with independent concurrency quota.
3. **Two-level queueing** (session + global) ensures requests need to obtain both a session turn and a global concurrency slot to execute.
4. **Six queue modes** (collect/steer/followup/steer-backlog/interrupt/queue) provide flexible concurrent message handling strategies, with collect mode as the default for merging messages.
5. **Drain pump** algorithm implements efficient event-driven scheduling, automatically attempting to execute more tasks whenever a task completes or a new task is enqueued.
