Skip to content

Scale switch-core to 10,000 agents at 346 messages a second on four nodes (CHOO-3667) - #1307

Merged
abeldantas merged 72 commits into
mainfrom
scale-core
Nov 2, 2026
Merged

abeldantas merged 72 commits into
mainfrom
scale-core

Conversation

@abeldantas

@abeldantas abeldantas commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

In this PR we raise what four nodes carry with 10,000 agents from 82 to 346 messages a second, and move the limit from the database to the pods' CPU.

Figure 1. p99 delivery time at each step, 10,000 agents on four nodes

It combines the 32 scaling PRs listed below, plus one new change: a message is announced after its commit, in a batch per pod, instead of from inside its own transaction, where every message waited in line for Postgres's NOTIFY lock (figures 8 and 9).

What changed

Figure 2. Pods re-read only what changed

Figure 3. Each message costs fewer statements

Figure 4. Each statement costs less

Figure 5. What a post checks is kept until a trigger says it changed

Figure 6. Agents' posts and reads ride the controller's socket

Figure 7. The statements every message runs skip SQLAlchemy's execution

Figure 8. Messages no longer wait in line for the NOTIFY lock

With and without the NOTIFY change

Figure 9. The database stops queueing on the NOTIFY lock

At 150 msg/s the batching adds about 15 ms at p50 and 0.24 s at p99; from 250 msg/s up it is faster. 82 msg/s is the first run with 10,000 agents (31 Oct), which had 12 of these PRs. Every migration here is expand only. The load test does not check message order, duplicates, or a pod restarted mid-run yet.

Combines

#1200, #1220, #1221, #1222, #1223, #1224, #1225, #1229, #1235, #1236, #1237, #1238, #1246, #1247, #1248, #1249, #1250, #1251, #1252, #1253, #1254, #1255, #1256, #1258, #1259, #1260, #1262, #1263, #1268, #1269, #1275, #1276

… agents' rooms at once (CHOO-3667)

With 3,000 agents behind 150 controllers and no messages, the database
ran 2,360 statements a second. Two loops did most of it:

- each controller stream's pass, including the one after every idle
  interval, opened a session per agent to read its events. A pass now
  reads all its agents' heads in one query and reads only the agents
  that have something new.
- every process re-reads each controller another process holds every 30
  seconds, and read each agent's rooms with a query of its own, so the
  count grew with processes times agents. It is now one query per
  controller (RoomStore.room_ids_by_agent).
…again (CHOO-3667)

Every process reconciles every room's clients at startup, under the
boot lock, and read two sessions per room to do it. With tens of
thousands of rooms that took about 100 s, close to the liveness
probe's limit, so pods starting together queued for the lock and were
restarted before they got it. The memberships are now read 1,000 rooms
per query, and only rooms missing a client are written to.
…(CHOO-3667)

Each delivery made the controller's stream read the heads of all its
agents three times, each in its own transaction: to find the work, again
after delivering, and again before waiting. In a load test with 10,000
agents behind controllers that was 9 of the ~50 transactions a message
cost.

The pass now clears its agents' doorbells before its one read of the
heads, so an event added after that read rings again and the wait
returns at once. It reads again without waiting only when a delivery
stopped short of the head (the batch size, or a gap).
…n, instead of closing its socket (CHOO-3667)

In a load test with 10,000 agents behind controllers, controller sockets
closed once the pods' CPU was full, and each closed socket made its 20
agents reconnect, which costs more of the CPU and connections that were
short. A stream ends when its pass raises, for example when the pass
waits out the pool timeout, and the socket closes with it.

A pass that fails because the connection or the pool did (the check the
event buffer already uses for its writes) is now tried again after a
jittered wait doubling from 0.5 to 5 seconds, and the stream ends only if
it is still failing after a minute. An agent is attached only once its
reads and writes are done, so an attach that fails part way is done again
from the start, and outcomes owed after a resync are marked read only
once the read succeeded.
…the server (CHOO-3667)

A CPU profile under message load put the tenant binding that starts each
transaction at about 2% of a pod's CPU and the pool's hold timer at about
0.5%. The binding built and compiled a text() statement every time; it
now goes to the driver as it is, the same statement in the same
transaction. The hold timer formatted a stack of strings on every
checkout; it now keeps each function's label, stops walking once it has
the frames it shows, and writes the stack out only for a long hold.
…space (CHOO-3667)

With usage reporting on, each message looked up its room's platform and
member counts, its sender's kind and the agent's runtime, each kept for
five minutes in caches capped at 10,000 entries. In a load test with
3,000 agents these were about three of the queries every message cost:
quiet rooms missed every time, and at 10,000 agents the caches evicted
entries before they were asked again.

A room's facts are now kept for fifteen minutes, a sender's kind and an
agent's runtime, which do not change, for an hour, and up to 50,000 of
each.
…ne sending (CHOO-3667)

A CPU profile of the pods under message load put the event loop's own
work (scheduling, socket reads and writes) at about 15% of a pod's CPU,
and finding the sending agent's actor, a scan of every client's actor
on every send, at about 3%.

The server now runs on uvloop where it is installed (not Windows, where
it keeps asyncio's own loop), keeps the client found for each agent and
checks it again on each use, and caches compiled mention patterns per
name instead of relying on re's 512-pattern cache.
…when only room agents are tagged (CHOO-3667)

The admin's consumer reads every message in a tenant on one process, and
checked each message with an @ for a tagged agent not in the room or a
role with no live holder: two sessions and a lookup by name for every
tag. In a load test at 60 messages a second the database saw these
checks for about 10 messages a second, so the consumer fell behind.

The router has read the room's agents to decide the message, so it now
runs the check after commit on the process that wrote the message, and
only when the message tags a name that is none of the room's agents. The
checks themselves moved unchanged to clients/mention_warnings.py.
…tops pinning every process (CHOO-3667)

Registering, renaming or deleting an agent made every process read every
client of the workspace and, with a messaging app connected, every agent
too, back to back while changes kept coming. Creating 10,000 agents kept
every process at full CPU until its health checks started failing.

The client.changed signal now names the clients it changed and each
process reads only those rows (ClientLifecycleService.reconcile_clients).
A bridge keeps the agents as it last read them and reads only the named
ones (CollaborationCore._update_agent_identities). The 30-second re-check
compares a fingerprint of the workspace's clients and agents before
reading them all (ClientLifecycleService.recheck_all). A signal that names
no clients, as an older process sends, still reads the whole workspace.
…ient (CHOO-3667)

Every process keeps an actor for every client. Finding a workspace's
admin (every room created asks) and the actor of an agent another process
had just registered (a lookup that misses) read every actor. While 10,000
agents were being created, these lookups took about 11% of a process's
CPU in a profile.

The running clients are now indexed by type and tenant, and by agent
(ClientLifecycleService._track and _forget). A lookup by agent that the
index cannot answer looks only at the agents' clients whose agent row
has not been seen yet.
…CHOO-3667)

The admin client's CommandConsumer acts on `!command` rows only, but the
process holding it was woken for every row of every room and read each
one to find them, so one process did a read per message for the whole
workspace on top of its share of everything else.

The message announcement now carries the row's type, a listener
subscriber can ask for some types only (MessageListener.subscribe), and a
consumer that names its types (Consumer.ROW_TYPES) is woken for those and
reads only those rows, through a partial index on the command rows. A
database or process from before this sends or reads announcements
without a type, which still wake every reader.
…cks to use

The client re-check's fingerprint (a row count and the sum of a 60-bit
hash of the columns acted on) moves to switch_core/db/fingerprint.py, so
the other families' 30-second re-checks can compare one before reading
everything. No change in behavior.
…ments changed (CHOO-3667)

Every 30 seconds every process read every placed agent definition, its
document included, then each controller with a query of its own. In a
profile of an idle process with 10,000 managed agents, the bindings
re-check took 3 to 12% of the active samples, and decoding the JSON
columns read while idle another 5 to 11%.

The bindings are now read from one query per workspace that returns the
columns a binding is made of (AgentDefinitionStore.placements), and the
re-check compares a fingerprint of those columns first
(reconcile_bindings with fingerprints). A resync still reads everything.
…e array (CHOO-3667)

The reads a client makes as it starts receiving (its memberships, the
rooms' heads, its stored cursors) matched the rooms with one bind
parameter each, and Postgres refuses more than 32,767. Switch's own
client is in every room of its workspace, archived ones included, so past
that many its reader failed at start, was retried as a transient error,
and failed again, re-adopting rooms one at a time in between. A load
test environment reached it with 41,461 rooms, and that process sat at
56% CPU while idle.

The three reads now bind the rooms as one text array (db/id_lists.any_of).
Each delivery to an agent behind a controller read the heads of all the
controller's agents first. The notification of a new agent event already
carries its number, so the event buffer now keeps it as the agent's head
while the listener listens, and the controller's stream reads heads only
after an idle interval, when it attaches an agent, and after the listener
reconnects. In our load test that read was one transaction per delivery,
about three per message.
Every message an agent sends is checked against Switch Trust, and the
check read the settings row each time: a transaction per message for a
row that hardly ever changes. Each process now keeps what it read, and
the gateway's settings routes tell every process when the row changes
(TrustSettingsSignals), so a change still takes effect on the next
message. A process that reconnects forgets the settings, and they are
read again after 30 seconds at most, for a signal that was lost.
Each client kept its own map from transport room ids to room ids, so an
agent writing to a room for the first time through a process read the
room first. With thousands of agents behind a load balancer that was
most sends. A room's transport id never changes, so a process's
transports now share the map (RoomIds), and the first miss in a process
reads every open room of the tenant at once rather than one room at a
time as its clients first write to them.
After a message commits, the router read the membership of every agent
it was addressed to, so that one removed from the room in the meantime
says nothing there. A connected agent has nothing to say about a message
addressed to it, so the read is now made only before a refusal or an
offline notice is posted, or a cloud machine woken. In our load test
that was one transaction per addressed agent, about three per message.
A delivery read the agent's events, then the rooms dropped after its
cursor, then the unread count: the agent's baselines, its own user id,
the room's window start and the count each in a statement of their own.
The dropped rooms are now read in the statement that reads the events,
which also makes the two one snapshot, and the unread count reads its
baseline, window start and user id in the statement that counts. In a
CPU profile of a load test, building and running statements was most of
the server's time.
Every message an agent posts reads its budget standings twice: once to
check the agent may post, and once as the router decides the row. Each
read built its statement again, a correlated subquery and a dozen
comparisons, and in a CPU profile of a load test building it was about a
tenth of the server's time, more than running it. The two statements
(every budget of a tenant, the budgets covering one agent) are now built
at import and run with bind parameters.
Each agent a message was for cost four statements in the writer's
transaction: a savepoint, its number claimed, its event inserted, the
savepoint released. The agents' events are now stored together
(EventBuffer.store_together): one statement locks their rows in
agent_event_heads in the order of their ids, and one inserts each event
for an agent still in the room and not already holding it, and moves
that agent's head, all in one savepoint. An event not stored takes no
number. If the two statements fail, the events are stored one at a time
as before, so one agent's failure still costs that agent alone.
…3667)

Each wait of a controller's stream started a waiter for the doorbell of
every agent on it, two more for the connection and the nudges, and
cancelled them all when one fired: with 20 agents that was 22 tasks per
wait, and a CPU profile of a load test put the waiting among the larger
costs of a delivery. The stream now has one bell that every attached
agent's doorbell rings (EventBuffer.listen), so a wait watches three
events. Reading a doorbell no longer builds an Event it then discards.
…667)

A stream reads an agent's own events for every event it delivers, and a
CPU profile of a load test put building that statement, and the check
of the rooms dropped after the agent's cursor, at the top of what the
server spent building statements. Each of the read's sixteen shapes
(rooms or not, notifiable only or not, a bound or not, a limit or not)
is now built once and run with bind parameters, and so is the check.
Every 30 seconds every process read the connection row of every
controller that ever opened one, revoked ones included, with their
status and platform JSON, and for each controller another process held,
the rooms of all its agents. At 10,000 agents behind 500 controllers
that was a one-second query and about a second of CPU decoding JSON per
process every 30 seconds, and about ten room queries a second.

The re-check now first compares a fingerprint of the connection
columns it acts on, and of the processes holding a lease, with the last
full read, and reads only the connection columns when it reads at all.
The rooms of a controller's agents are kept by the membership signals
and MessageRouter.recheck_agent_rooms meanwhile.
…HOO-3667)

Message telemetry looks up the room a message was said in, who sent it
and the sending agent's runtime, and keeps each answer for 15 minutes or
an hour. In a workspace of thousands of agents and rooms a process
reports on most of them before it reports a second message about any,
so the cache missed for most messages: a load test spent 1.4
transactions a message on these lookups. The first lookup that misses
now reads every open room, client and agent of the workspace at once
(MessageTelemetry._read_tenant), again once the rooms would expire; a
room or client made since is looked up on its own as before, and a
read that fails counts as the lookup's failure.
read_context read the room's newest message number, checked the agent
is a member and read the history, each in a session of its own: three
pool checkouts and three transactions for one read. They now share one
session (shared_tenant_session), in the same order, so the number is
still read before the history. Without a bound tenant AgentCore opens
its own session as before.
…-3667)

Every request a controller makes reads its controller row, to refuse a
revoked one, and acting as an agent, that agent's row. Both were kept
for 5 seconds. A controller's requests are spread over every process, so
with 12 processes each saw a given controller about once a minute and a
given agent less often: the cache missed on nearly every request, at two
transactions each.

An entry read while the signal bus listens is now kept for as long as
that same connection listens, and dropped when a signal names it.
Triggers on agents, and on a controller's owner, credential and
revocation, send agent.changed and controller.auth_changed, so no writer
can skip them. An entry read without a listening bus, or kept past a
reconnect, lasts the TTL as before. A miss reads every agent bound to
the controller at once (AgentStore.get_many), and the agent rows have a
bound of their own, CONTROLLER_AUTH_CACHE_MAX_AGENTS.
Reading the rooms an agent is in (RoomStore.get_rooms_for_agent and six
other reads by agent), and the foreign key's check when an agent is
deleted, filter room_agents by agent. Its primary key leads with the
room, so each was a sequential scan, 2.9 ms at 10,000 agents, and every
process runs it for each agent of a controller that connects. Expand
only, and not CONCURRENTLY, as for ix_client_rooms_room_id.
This was referenced Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants