The Command Queue

You send two more messages while your agent is still working. The gateway can turn them into 3 runs and a last answer at 12 s, or 1 run and an answer at 4.8 s. The queue mode decides.

Pick a mode and press Send three messages. Watch where messages 2 and 3 land: inside the run, after it, merged, or as a restart. Then we build the queue piece by piece, from one turn per session to the rule that picks the mode.

You need a rough idea of an agent run (a loop of model calls and tool calls, Lesson 4) and what a list in Python is. We build the rest from zero.

Lesson 6 of 11 in Anatomy of an Agent Gateway. The running example is the OpenClaw command queue. We checked every OpenClaw detail here against its documentation.

Message a busy agent

Illustrative toy timing: one run is 4 s of model calls (purple) and tool calls (pink). Message 1 "summarize the email" at 0 s, message 2 "under three sentences" at 1.0 s, message 3 "make it friendly" at 1.4 s. What each mode does follows OpenClaw's queue docs.

Chapter 0

Two Runs, One Transcript

See what breaks when every message starts its own run, and name the three jobs of the queue

You ask your agent to "summarize that email". It starts reading. A second later you add "keep it under three sentences". The agent is still working on the first message.

Suppose each message starts its own run, one agent turn that reads the conversation, calls the model and tools, and writes a reply. Both runs read the same transcript, the ordered list of who said what. Both write to it. Run 2 started before run 1 replied, so it never sees that reply.

Send two messages

Press Send two messages with the rule off. Read the transcript on the right. Then turn on One turn per session and send again.

Illustrative toy: each run takes 3 s and writes one line per second. Message 2 arrives 0.8 s after message 1.

This is a race condition: two writers, one shared thing, and no rule for who goes first. The result depends on timing. The old fix works here: only one run may touch a transcript at a time.

One run at a time for the whole gateway is too blunt. Your phone chat, a teammate's Slack thread and a nightly job each have their own transcript. They cannot collide, so they should not wait for each other.

The command queue is the part of the gateway that sits between arriving messages and agent runs. It has three jobs:

  1. Run one turn at a time inside each conversation.
  2. Run different conversations side by side, up to a limit.
  3. Decide what happens to a message that arrives while its conversation is busy.

The road

  1. One turn per session: when a turn may start, as one rule.
  2. Lanes and their caps: how many turns run at once, and why background work gets its own line.
  3. Four answers to a busy agent: steer, followup, collect, interrupt. The hero's selector.
  4. Steer at the tool seam: where a steered message enters a run.
  5. Collect and the quiet window: turning a burst into one turn.
  6. Backpressure: the cap and what to drop when it is full.
  7. Who picks the mode: session, channel, global, default.
  8. The whole queue, live: every part on one run.
  9. Field guide: terms, numbers, a checklist and the core code.
Why is it a bug to let each incoming message start its own run at once?

Chapter 1

One Turn per Session

Line up the turns of each conversation in arrival order, and let conversations run side by side

A session is one conversation with its own transcript. The gateway names each session with a session key. Two messages from one chat share a key. Messages from two chats do not.

The rule: inside one session, turns run one at a time, in arrival order. That order is FIFO, first in, first out, like one line at a counter. Across sessions, turns run at the same time.

When may a turn start? Call the time message i arrives ai. Call the time the turn ahead of it, in the same session, ends ei−1. Call the turn's start si and its length di.

Say it aloud

s-i equals the max of a-i and e-i-minus-one, and e-i equals s-i plus d-i.

si
s-i the time turn i starts, in seconds.
max
the max of the later of the two times.
ai
a-i the time message i arrives at the gateway.
ei−1
e-i-minus-one the time the turn ahead of it in the same session ends. For the first turn it is 0.
ei
e-i the time turn i ends.
di
d-i how long turn i runs, in seconds.
In plain words

A turn starts at the later of two times. One is its own arrival a-i. The other is the end e-i-minus-one of the turn ahead of it in the same session. It ends d-i later. Turns of other sessions are not in the rule.

With numbers

With made-up numbers: session A gets messages at a = 0, 1.0 and 1.2 s, and each turn takes d = 2 s. s1 = 0, e1 = 2. s2 = max(1.0, 2) = 2, e2 = 4. s3 = max(1.2, 4) = 4, e3 = 6. The third message waits 4 − 1.2 = 2.8 s.

Line up three chats

Yellow ticks are arrivals; purple bars are turns. Raise the message rate and watch each row back up. Turn the rule off to see turns of one chat overlap.

16

Illustrative toy: arrivals are random but fixed, every turn takes 2 s, and the window is 15 s.

OpenClaw enforces this with a session controller. Its docs say the controller "selects one turn at a time" for each session, whichever runtime runs the turn. A run that was replaced cannot commit stale transcript data.

Waiting must not feel broken. OpenClaw sends the typing indicator the moment a message enters the queue, where the channel supports one. The user sees "typing" at once, even if the turn starts seconds later.

Session A's turn ends at 6 s. Its next message arrived at 2 s. A message in session B arrives at 3 s while B is idle. When does each start?

Chapter 2

Lanes and Their Caps

Limit how many turns run at once, and give background work its own line so it cannot block a chat

One turn per session still lets 500 sessions start 500 model calls in the same second. That breaks rate limits and the machine. So the queue adds lanes: named lines of work. Each lane has a concurrency cap, the most turns it may run at once.

OpenClaw laneWhat runs in itDefault cap
maininbound chat turns from every sessionmax(8, 4 × CPU parallelism), set by agents.defaults.maxConcurrent
subagent:<session>helper agents that one session spawns8 per spawning session
cron, cron-nested, nestedscheduled jobs, heartbeats and their childrentheir own budgets
any unconfigured laneanything else1

How many chat turns run at once? Call the number of sessions with a turn ready N. Call the main lane's cap C. Call the number of tasks the machine can run in parallel, about its core count, P. Call the number running A.

Say it aloud

A equals the min of N and C, and C equals the max of 8 and 4 times P.

A
A the number of chat turns running right now.
min
the min of the smaller of the two numbers.
N
N the number of sessions with a turn ready to start.
C
C the main lane's cap: the most chat turns at once.
max
the max of the larger of the two numbers, so C is never below 8.
P
P the CPU parallelism: how many tasks the machine runs at once.
In plain words

Count the ready sessions N. If N fits under the cap C, all of them run. If not, C run and the other N − A wait in FIFO order. OpenClaw's default C is 4 times P, but never less than 8.

With numbers

A 2-core machine has P = 2, so C = max(8, 8) = 8. With N = 20 sessions ready, A = min(20, 8) = 8 run and 12 wait. With P = 8, C = 32 and all 20 run.

Fill the lanes

Each square is one slot. Solid purple is a chat turn, outlined purple is a cron job. Start the nightly cron burst, then switch between one shared lane and separate lanes.

2
5

The main lane cap is OpenClaw's default formula. The cron lane's 4 slots are illustrative; OpenClaw gives background lanes their own budgets.

Why a separate lane? Ten cron jobs start at 02:00 while you send a message. In one shared lane they fill the free slots and your chat waits. In their own lane they spend their own budget. OpenClaw also lets foreground work overtake queued normal work by up to 15 s, and background work by up to 30 s. A running turn is never stopped to make room.

Why do scheduled jobs run in their own lane and not in the main lane?

Chapter 3

Four Answers to a Busy Agent

Choose what a message does when its session is busy: join the run, wait, merge or restart

A message arrives and its session already has a turn running. The queue can take one of four actions. OpenClaw calls them queue modes.

ModeWhat the new message doesBest when
steer (default)enters the running turn; the model reads it at its next callyou correct the current task
followupwaits, then runs as its own turn after the current oneyou ask for something separate
collectwaits; all waiting messages merge into one followup turn after a quiet windowyou type one request in several lines
interruptstops the running turn and runs the newest messagethe running turn is now pointless

Match the mode to the message

Message 1 is always "summarize the email". Pick what you send next, then try each mode. The verdict says if the mode fits.

You send
Mode

Same toy timing as the hero: a run is 4 s, and each steered message adds 0.4 s to the last model call. The fit verdicts are our judgement.

Steer is the default because the most common late message is a correction: "shorter", "in French", "use the second file". A person already on a task takes a correction without starting over. Interrupt is for the other case: the work so far is no longer wanted.

Collect has a limit in OpenClaw. It merges only messages that share routing, authorization and execution settings. On channels with durable ingress, such as Discord and Telegram, collect acts like followup.

The agent is writing a summary. You add "keep it under three sentences". The mode is OpenClaw's default. What happens?

Chapter 4

Steer at the Tool Seam

Find the exact moment a steered message reaches the model, and what interrupt does instead

Steer puts your message "into the running turn". But a model cannot read new input halfway through a call. It reads its whole input when a call starts. So the earliest moment the model sees your message is its next call.

Recall the agent loop from Lesson 4: the model asks for tools, the tools run, their results come back, and the model is called again. The gap after the tools return and before the next model call is the tool seam. Your steered message rides into that next call with the tool results.

Send during a run

Drag Send at across the run. The yellow line shows when the model reads your message. Turn streaming off, or switch to interrupt.

1.0

Illustrative toy timing. In this toy, a message after the last seam, or any message with streaming off, falls back to a followup turn. OpenClaw falls back when the runtime cannot accept same-turn steering.

You send duringThe model reads itDelay in the toy
tool 1 (sent at 1.0 s)when tool 1 ends, at 1.8 s0.8 s
model call 2 (sent at 2.0 s)after call 2 and tool 2, at 3.6 s1.6 s
the last model call (sent at 4.0 s)as a followup turn at 4.4 s0.4 s

OpenClaw accepts a steered message even while tools run. Ordinary steer does not abort tools in flight, because a tool cut in half can leave a half-written file. With partial or block streaming, steering can show up as several short replies. Without streaming, if the runtime cannot take the message in the same turn, steer falls back to followup.

Interrupt is the hard stop: /queue interrupt aborts the turn and runs the newest message. Tool calls that were skipped get synthetic error results, so the transcript stays valid: every tool request still has an answer.

A steered message arrives in the middle of a tool call. When does the model read it?

Chapter 5

Collect: Wait for a Quiet Window

Group a burst of messages by the pauses between them, and count the turns that come out

People type one request as several messages: "book a table", Enter, "for 4", Enter, "at 7", Enter. Followup turns that into three turns, and two of them are half a request. Collect turns it into one.

The trick is debounce: do not act on each message. Wait until the messages stop for a set time, the quiet window. Each new message restarts the wait.

How many turns does a burst become? Call the gap between message k and message k+1 gk. Call the quiet window D. Call the number of followup turns R.

Say it aloud

R equals one plus the sum over k of one-if g-k is at least D.

R
R the number of followup turns the burst becomes.
1
one the first batch, which always exists.
Σk
the sum over k add one term for each gap between two messages.
[ … ]
one-if the bracket is 1 when the test inside is true, and 0 when it is false.
gk
g-k the time between message k and message k+1, in ms.
D
D the quiet window, in ms. OpenClaw's default is 500.
In plain words

Look at each gap g-k. A gap of D or more closes one batch and starts the next. Count those gaps and add 1 for the first batch. Each batch is ready D after its last message.

With numbers

With made-up numbers: messages at 0, 300, 700 and 2,000 ms, D = 500 ms. The gaps are 300, 400 and 1,300 ms. Only 1,300 ≥ 500, so R = 1 + 1 = 2. Batch 1 is ready at 700 + 500 = 1,200 ms, batch 2 at 2,500 ms. Followup would make 4 turns.

Group a burst

Pick a typing pattern, or tap the timeline to add a message. Drag the quiet window and watch batches split or join.

500

Illustrative typing patterns. The 500 ms default is OpenClaw's.

In OpenClaw the quiet window defaults to 500 ms and also paces how queued followups drain. In a chat, write it as /queue collect debounce:0.5s. A bare number means milliseconds, and the units ms s m h d work. Per channel, set messages.queue.debounceMsByChannel.

The agent is busy. In collect mode with D = 500 ms, you send three lines 200 ms apart. How many followup turns do they become?

Chapter 6

Backpressure: Cap and Drop

Work out when a queue fills, how long its newest message waits, and which messages to drop

A busy group chat sends 6 messages a minute. Each followup turn takes a minute. The queue grows by 5 every minute and never stops. Backpressure is the rule a system uses when input arrives faster than the work drains.

When does the queue fill? Call the arrival rate λ, in messages per minute. Call the drain rate μ, in turns finished per minute. Call the largest number of queued messages a session may hold the cap.

Say it aloud

T-fill equals cap divided by lambda minus mu.

Tfill
T-fill the minutes until the queue is full, starting from empty.
cap
cap the most queued messages one session may hold. OpenClaw's default is 20.
λ
lambda messages arriving per minute.
μ
mu turns finished per minute.
In plain words

Each minute the queue gains lambda minus mu messages. Divide the cap by that gain to get the minutes until it is full. If lambda is not bigger than mu, it never fills.

With numbers

With made-up rates: lambda = 6, mu = 1, cap = 20. T-fill = 20 / (6 − 1) = 4 minutes. After that, 5 messages a minute must go somewhere.

How long does the newest message wait? Call the number of messages in the queue L. Call the wait, from arrival until its own turn is done, W.

Say it aloud

W equals L divided by mu.

W
W minutes from the newest message's arrival until its turn is done.
L
L messages in the queue, the newest included.
μ
mu turns finished per minute.
In plain words

The queue is FIFO, so the newest message is number L in line. The line drains mu turns a minute. Its turn is done after L divided by mu minutes.

With numbers

With made-up rates: a full queue, L = 20, and mu = 1. W = 20 / 1 = 20 minutes. The reply is about a message from 20 minutes ago.

So a cap must say what happens when the queue is full. That rule is the drop policy. OpenClaw has three:

PolicyWhen the queue is fullWhat the agent knows
summarize (default)drops the oldest queued messages and keeps compact summaries of themgets the summaries as a synthetic followup prompt
olddrops the oldest, with no summarynothing about the dropped messages
newrejects the newest messagenothing about the rejected message

Flood a session

The curve is the queue length over 10 minutes; the dashed red line is a queue with no cap. Drag Time to see which messages are in the queue then.

6
1
20
6

Illustrative rates, with steady arrivals and followup turns. The cap of 20 and the three policies are OpenClaw's.

Summarize is the default because it fails softly. With old, the agent forgets a constraint and does not know it. With new, the latest message vanishes. Summarize keeps memory bounded and tells the agent what it lost. In OpenClaw, cap and drop are set globally or per session, not per channel.

A session's queue is full at 20. Why is summarize a safer default than old?

Chapter 7

Who Picks the Mode

Resolve the mode from four places, most specific first, and change it from inside a chat

You want steer in your own chat, collect in a noisy Discord server, and followup in one thread today. One global switch cannot do that. OpenClaw checks four places, most specific first, and uses the first one that is set.

Call the mode stored for this session by a /queue command msession. Call the mode set for this channel in messages.queue.byChannel mchannel. Call the global messages.queue.mode mglobal. Call the mode the queue uses m.

Say it aloud

m equals the first set value among m-session, m-channel, m-global and steer.

m
m the mode the queue uses for this session.
first
the first set value among read left to right and take the first one that is not empty.
msession
m-session a mode stored in this chat with /queue.
mchannel
m-channel the mode for this channel, such as Discord.
mglobal
m-global the gateway-wide mode in the config.
steer
steer the built-in default, used when nothing else is set.
In plain words

Check m-session. If it is empty, check m-channel, then m-global. If all three are empty, use steer.

With numbers

An example: m-global is steer, the Discord m-channel is collect, and one Discord thread typed /queue followup. In that thread m = followup. After /queue reset, m = collect. Remove the Discord setting and m = steer.

Resolve the mode

Set each level, or leave it at none. The queue checks from the top and stops at the first level that is set.

Session (/queue)
Channel (byChannel.discord)
Global (messages.queue.mode)

The order of the four levels is OpenClaw's. The Discord channel is an example.

Inside a chat you change the session level with /queue:

chat commands# store a mode for this session
/queue steer
# a mode plus its options in one line
/queue collect debounce:0.5s cap:25 drop:summarize
# clear the session override: fall back to channel, global, steer
/queue default
/queue reset
# send one message as a new turn, without changing the stored mode
/followup also check my calendar

The options have their own order. The quiet window comes from the session's /queue options, then messages.queue.debounceMsByChannel, then plugin defaults, then the built-in 500 ms. Cap and drop come only from the session or the global config.

Global mode is steer, Slack is set to followup, and in one Slack thread you typed /queue collect. Which mode does that thread use?

Chapter 8

The Whole Queue, Live

Run one session with every rule switched on, and break it on purpose

Here is one session with a running turn. The ticks on the bar are its tool seams. Every rule from chapters 1 to 7 is live: the mode, the seam, the quiet window, the cap and the drop policy.

Run the queue

Pick a mode and press Send a message a few times. Then set the cap to 3, choose followup, and send faster than the turns finish.

Mode
6

Illustrative toy: a turn takes 6 s with 3 seams, and the quiet window is stretched to 1.5 s so you can see it.

Read one message through it. Steer sends it to the next seam on the bar. Followup puts it in a slot, and the next turn takes the oldest slot. Collect holds it in the buffer until the quiet bar empties, then merges the buffer into one slot. Interrupt cuts the bar and starts again. When the slots are full, the drop policy decides.

Mode followup, cap 3, drop new. Three messages wait and you send a fourth. What happens to it?

Chapter 9

Field Guide

Keep the terms, the numbers, a checklist and the core code in one place

Each session runs one turn at a time, in arrival order. Lanes cap how many turns run at once and keep background work apart. A message for a busy session steers, follows up, collects or interrupts. A cap and a drop policy bound the wait. The mode comes from the most specific level that is set.

TermMeaningOpenClaw value
sessionone conversation with its own transcriptone turn at a time, by the session controller
main laneinbound chat turns from all sessionscap max(8, 4 × CPU parallelism), agents.defaults.maxConcurrent
subagent lanehelpers one session spawns8 per spawning session
background lanesscheduled and nested workcron, cron-nested, nested
modewhat a message for a busy session doessteer (default), followup, collect, interrupt
quiet windowpause that ends a batch500 ms; units ms s m h d
capmost queued messages per session20
dropwhat to do when fullsummarize (default), old, new
precedencewhere the mode comes from/queue, then byChannel, then mode, then steer
overtakehow far priority work may jump the line15 s past normal work, 30 s past background work

Checklist for any command queue

The core, in code

A toy queue for one session. It is a sketch for reading, not OpenClaw's code. The quiet window and the lane caps are left out.

pythonclass SessionQueue:
    def __init__(self, mode="steer", cap=20, drop="summarize"):
        self.mode, self.cap, self.drop = mode, cap, drop
        self.pending, self.lost, self.run = [], [], None

    def on_message(self, msg):
        if self.run is None:                          # idle: start a turn now
            return self.start(msg)
        if self.mode == "steer" and self.run.can_steer():
            return self.run.inject(msg)               # model reads it at its next call
        if self.mode == "interrupt":
            self.run.abort()                          # skipped tools get error results
            return self.start(msg)
        self.enqueue(msg)                             # followup, collect, steer fallback

    def enqueue(self, msg):
        if len(self.pending) >= self.cap:
            if self.drop == "new": return              # reject the newest
            self.lost.append(self.pending.pop(0))      # old and summarize drop the oldest
        self.pending.append(msg)

    def on_turn_end(self):
        self.run = None
        note = ""
        if self.drop == "summarize" and self.lost:
            note = f"[{len(self.lost)} earlier messages: {summarize(self.lost)}] "
        self.lost = []
        if not self.pending: return
        if self.mode == "collect":                    # one turn for everything waiting
            batch, self.pending = self.pending, []
            return self.start(note + " / ".join(batch))
        self.start(note + self.pending.pop(0))          # FIFO: oldest first

Where each thread continues

The takeaway. One turn per session, a cap per lane, a mode for the late message, a seam for steering, a quiet window for bursts, and a cap with a summary for floods.
In one sentence, what is the command queue?

Now press Present or Teach and explain the queue from memory, chapter by chapter. Then go back to the hero and send three messages in each mode again.

Anatomy of an Agent Gateway, Lesson 6: The Command Queue
OpenClaw queue docs · Next: sessions and many agents · Back to Gleams