Swarm on AWS
The agent swarm of examples/swarm - the same HTTP API, the same session semantics -
built on AWS’s own primitives instead of Temporal + Postgres: DynamoDB holds every session’s
state, event log, runs, call journal, leases, parked items, children and an outbox of effects;
SQS drives the work - one message per turn attempt, per child attempt, per pipeline step and
per near timer; the Node core @dudko.dev/agent runs in Lambda
functions (a gateway behind a streaming Function URL, and a worker fed by the queues) or, from the
same code, in containers on ECS Fargate.
This is an example, not a package: private in the workspace, never published. Its
platform-independent part - the session reducer, the answer checks, the ids, the cursor and the
HTTP API itself - is swarm-shared, the same code the Temporal swarm, the
Cloudflare one and the Google Cloud one run.
Nothing in this repository deploys it or talks to an AWS account. Everything here was built and tested on DynamoDB Local and a stand-in for SQS (what that leaves unproven); deploying is the owner’s, by hand (Deploying).
- Architecture
- What replaces Temporal and Postgres (the mapping table)
- The HTTP API
- Turns, parking, children, pipelines
- What happens on a crash
- The limits of DynamoDB, SQS and Lambda, and what is done about each
- Costs to watch
- Lambda or containers
- Configuration
- Run it locally
- Deploying (the owner’s commands)
- Security
- Limits, and what is not supported
- What was only tested on stand-ins
- Development and tests
Architecture
Section titled “Architecture” HTTPS, bearer token clients ──────────────────────► gateway (a Lambda Function URL, streaming - or ECS behind an ALB; ▲ │ swarm-shared's createGatewayHandler) │ SSE: replay = a query, │ a call = ONE DynamoDB transaction on the session │ live = a poll of the │ (the reducer applied; its effects into the outbox), │ stream's newest key │ then the outbox is drained: messages are sent └───────────────────────────────┤ ▼ DynamoDB, one table pk = s#<session> a partition per session on demand meta the session: small, the hot item, its LOCK blob/<key> + part/... the reducer's state, a phase's input, ... run/<run> + jrn/<run>/ binding, attempt, fence, snapshot; journal lease/<run> runLease: a counter its holder raises evt/<stream>/<cursor> the event log, a range per stream parked/ child/ settled/ phase/ outbox/ pk = l#<bucket> sharedLimits index `sweep` (sparse) the sessions with something due ▲ │ every hook of the agent: persistence + journal, │ runLease, onEvent (batches), sharedLimits SQS (standard) worker (Lambda: an event source mapping per queue invokes it; swarm-turns ─────────► ECS: it polls. NO URL, NO PORT: its queues are its only { task: turn | child } way in, and only the swarm's roles may send to them) swarm-control ─────────► turn / child one attempt of a phase = one agent.run { task: pipeline | pipeline one replay of a pipeline (the core's graph engine) timer | sweep } timer a session's timer: idle end, watchdog, retention EventBridge Scheduler ──► swarm-control { task: sweep } every minute: the net under it allThe single writer is a transaction. There is no process that owns a session (a Temporal
workflow, a Durable Object). Every transition - a message, an answer, a stop, a turn’s or a child’s
outcome, a timer - is ONE DynamoDB transaction that reads the session’s item and its state,
applies swarm-shared’s reducer, and writes - together or not at all - the state it leaves, the
turn.ended and child markers, the parked items, the children, and the effects on SQS as items of
an outbox. DynamoDB has no interactive transaction, so this one is optimistic: every item
carries a version, and the commit (TransactWriteItems) holds on the condition that what was read
is still there. The session’s own item is the lock of every transition - each of them writes
it - so of two transitions that meet, one commits and the other runs again on what the first left
(tests/session.test.ts runs six at once). After the commit the same process makes the effects,
in the order they were decided.
A turn’s attempt is one message. The worker takes it from the turns queue, counts the attempt
(in DynamoDB - not by the queue’s receive count), runs ONE agent.run with every scale-out hook
of the agent pointed at DynamoDB, and reports the outcome to the session (applied once per phase).
A run that parks ends its attempt - nothing runs and nothing is billed while a person decides -
and the answer’s transition sends the message of the next phase, which resumes the SAME run
(resumeFromRunId + answers). An attempt that dies is delivered again by SQS, and the next
attempt finds the run on record and resumes it from its last snapshot, replaying its call journal:
a recorded model call is not sent again, a recorded tool call does not run again.
A queue delivers at least once, and the swarm is built for twice. SQS has no task names and no deduplication: an effect made twice is two messages, and a standard queue may hand any message out a second time while its first consumer still works on it. So every message is safe to take twice - see what happens on a crash.
The streams are served by the gateway from DynamoDB. Replay is a query; live is a poll of the stream’s newest key (see why).
What replaces Temporal and Postgres
Section titled “What replaces Temporal and Postgres”| examples/swarm (Temporal + Postgres) | Here (DynamoDB + SQS + Lambda / ECS) | Where |
|---|---|---|
the session workflow (signals, query, the loop) |
a transaction per call on the session’s partition: the reducer applied, its state stored (blob/state), view() for the query |
src/session.ts |
| deterministic replay of the session | none needed: the state is stored, not replayed (no patched(), no continue-as-new) |
|
| Temporal’s “one workflow task at a time” | an optimistic transaction whose lock is the session’s own item: every transition writes it, on the condition of its version (and, inside one process, a queue per session) | src/dynamo.ts transact |
| commands a workflow task emits (start an activity, a child, a timer) | the outbox: items written in the transition’s transaction, made into SQS messages after it; the sweep makes what a dead process left | src/host.ts drain, sweep |
the runTurn activity, its retries |
a message per phase on the turns queue; a failed attempt makes its message visible again after a backoff; the attempts of a phase are the SESSION’s count (TURN_MAX_ATTEMPTS) |
src/worker.ts, src/steps.ts |
TURN_REFUSED (non-retryable) |
the worker fails the phase at once and deletes the message (a refusal, refused credentials, a misconfiguration) | src/worker.ts |
startToCloseTimeout |
TURN_TIMEOUT_MS - on Lambda at most 14 minutes (an invocation ends at 15). The attempt gives its run up at the limit and the next one resumes it |
src/worker.ts, src/config.ts |
| the activity heartbeat = the lease | runLease in lease/<run>: a counter its holder raises every TTL/3 (LEASE_TTL_MS). A holder that renews is never replaced - a second delivery of its message watches the lease, sees it move and is told busy, uncounted - and the run is taken only by a process that watched the lease stand still for a whole TTL |
src/store.ts leaseAcquire |
| a user’s stop = activity cancellation | the answer of the lease’s renew (and of every event batch): stop → the attempt aborts the run, which records cancelled |
src/steps.ts |
| heartbeat timeout → retried elsewhere | SQS itself: a message whose consumer died becomes visible again. And the watchdog: a phase nobody heard of for 3 TTLs, whose message is not waiting out a backoff and whose queue has nothing waiting, is sent again as the phase’s next generation (r): the message it replaced is dropped if it shows up after all. The watchdog fails nothing on its clocks: a phase whose attempts ran out is sent again too, and its delivery decides (the run on record, the lease watched for a TTL, the last delivery); only a phase sent again 10 times without an attempt that counted fails - and not while its run’s lease, watched, is renewed |
src/host.ts watchdog, src/session.ts beginAttempt |
worker shutdown (revokedReason) |
SIGTERM (a container): attempts give their runs up, let their leases go, and their messages go back at once (not counted); another worker resumes | src/poller.ts |
swarm_runs (snapshots, fence, supersedeRun) |
run/<run>, the same fences, each check and its write in one transaction |
src/store.ts |
swarm_journal (FOR SHARE against the fence) |
jrn/<run>/<entry>; the append’s transaction carries the run’s item as a condition |
src/store.ts appendJournal |
swarm_events + NOTIFY |
evt/<stream>/<cursor> + a poll of the stream’s newest key, one per stream per gateway instance |
src/store.ts, src/feed.ts |
swarm_parked |
parked/<item> (the same rows, the same states) |
src/store.ts |
swarm_sessions |
the session’s item exists | |
swarm_limiter (row lock, the database’s clock) |
an item per bucket: a transaction, the taker’s clock (DynamoDB has none to read); the bucket math is the same | src/limiter.ts |
child workflows (startChild, child.result()) |
messages the session sends from its outbox (task: child); a child reports its outcome to the session |
src/session.ts, src/worker.ts |
a child’s wait (signals into child-state.ts) |
the same child-state.ts, applied in the session’s transaction; the answer’s transition sends the child’s next phase |
src/session.ts |
the pipeline workflow (the engine, replayed by Temporal) |
a replay per settled visit: the session appends each visit’s outcome to the pipeline’s log in ONE order and sends task: pipeline, which runs the engine from the start over that log |
src/pipeline-run.ts |
the workflow’s timer (condition(ready, idleTimeoutMs)) |
the session’s earliest deadline, stored: a delayed message when it is at most 15 minutes away, the sweep otherwise | src/session.ts save, timer |
| workflow / child ids as dedup | none: SQS has no names. A message taken twice finds its phase’s outcome applied, its run’s lease held, or nothing left to do | src/queue.ts |
the gateway on node:http |
the same adapter in a container, or a streaming Function URL | src/http-adapter.ts, src/lambda-url.ts |
.env, *_FILE secrets |
the functions’ variables, Secrets Manager (<NAME>_SECRET_ID, or a task definition’s secrets) |
deploy/, src/secrets.ts |
compose.yaml, the Helm chart |
Terraform | deploy/terraform |
Why this way, where there was a choice
Section titled “Why this way, where there was a choice”- One DynamoDB table, a partition per session. Everything of a session shares a partition key,
so a request for one session cannot name another’s data, every read of a session is a
Queryof one partition, and retention deletes a session by emptying it. The key is all the access pattern there is: one sparse index (the sweep’s) and no other. - Large values in parts in the same table, not in S3. A value that outgrows an item (the
state, a snapshot, a journal entry) is cut in parts written before the transaction that names
them. S3 would hold them more cheaply (see costs) - at the price of a second
store, a second set of permissions, and a second thing whose deletion has to be kept in step
with the session’s. Here a session’s parts are in its partition: they are read with the same
call, deleted with the session, and guarded by the same key. If your snapshots run to megabytes
each,
storeText/loadText(src/dynamo.ts) are the seam to put S3 behind. - SQS standard queues, not FIFO. A FIFO queue would deduplicate (for five minutes) and order (within a group) - and neither is what makes a session right: a duplicate can arrive hours later (a visibility timeout, a redrive), and order is the session’s transaction’s business. FIFO would cost throughput and the per-message delay the timers use. The swarm is built for at-least-once instead.
- Lambda by default, containers as an option - one handler behind both. A worker is a function
of a message (
src/worker.ts: a verdict - done, come back later, busy). Lambda runs it with nothing to keep warm and nothing to patch: an event source mapping polls, scales and caps it. Its price is the 15-minute wall, which the journal already answers (a longer turn goes on in the next attempt), and a billed second for every second an attempt waits for its model. A container (src/poller.ts) has no wall and runs many attempts at once for the same money; it needs a VPC and something to scale it. See Lambda or containers. - Timers: a delayed message when near, the sweep when far. SQS delays a message by 15 minutes at most. A deadline within that (the watchdog’s, a short idle timeout) is a delayed message; one further away (an idle timeout of a day, a retention of a month) is only stored, in the sparse index the sweep reads every minute - no chain of wake-ups that each write the session, and no schedule per session to keep in step with it. The price: a far deadline is met to the minute, not to the second.
- A poll for live events, not DynamoDB Streams. DynamoDB pushes changes to a Lambda function,
not to the process that holds a client’s connection; to get from one to the other takes a bus
every gateway instance subscribes to - one more service that can be down - or the gateway reading
the stream’s shards itself, which two readers per shard allow. A poll needs nothing but the
table: one poller per stream per gateway instance, shared by that stream’s readers, asking for
the stream’s newest key only (eventually consistent, no event read) every
SSE_POLL_MSwhile it moves and everySSE_POLL_IDLE_MSwhile it is quiet. Honest about its price: a quiet open stream costs one small query per idle interval, and an event is seen up to one interval late. An instance that goes away (a scale-in, a deploy, a Lambda invocation at its time limit) ends its streams; clients reconnect to another withLast-Event-IDand miss nothing - the log is in the table, not in the instance. No hole either: a Query is read-committed per item, not per transaction - DynamoDB’s own words: “If a non-transactional read is made on multiple items that were part of the same transaction write request in-flight, it’s possible that you’ll be able to read the new state of some of the items and the old state of the other items” (isolation levels). A reader that read rows 1, 2 and 5 of a batch while it committed, and moved its cursor to 5, would never be sent 3 and 4. So a read is taken only as far as the stream’s own numbering says it has no hole (an attempt’s events are numbered by one, each kind of child marker too; aturn.endedread last is taken once a second read agrees, since its commit may also hold the turn’s last child markers) and read again a moment later otherwise; a hole that stays for 20 reads (two seconds) is one for good - a batch its writer gave up on - and is passed (src/feed.tssettledRead,tests/feed.test.ts). DynamoDB Local cannot show the race. - A lease that compares no clocks. DynamoDB has no clock a caller can read, and two machines’ clocks are not one. So nothing here decides “this lease ran out” from a stored time: a run is taken from its holder only by a process that itself watched the lease’s counter stand still for a whole TTL, by its own stopwatch - and the take is conditional on the very item it watched. A holder that is alive is never replaced, whatever anybody’s clock says; the price is that taking over a dead attempt’s run always waits one TTL (15 s by default). What a holder has to spare: the core renews every third of the TTL, and a renew is skipped only when an event batch wrote the lease less than a sixth of the TTL before - so the counter moves at least every half TTL, and a healthy holder survives a stall of half a TTL (7.5 s by default) before a watcher may take its run. A renew that the store does not answer (throttling, a lost connection) is not a lost lease: the last answer stands - but only while the next renew still comes inside one TTL of the last write the store confirmed (in practice: one renew in a row); after that the attempt gives the run up, before any watcher could have taken it. A holder may count a renew that only repeats an event batch’s write as fresh, so it may believe in its lease up to a sixth of a TTL longer than a watcher would wait: nothing it writes then lands (the fences), and no tool call of it starts after a taker’s fence (a call starts only once the model’s answer that asked for it is in the journal).
- A pipeline is replayed, not kept alive. As on Google Cloud: the core’s graph engine is deterministic by contract, so the pipeline’s log of settled visits is written in the session’s transaction and each entry sends a replay.
- An agent per attempt (as on Cloudflare and Google Cloud): made for the attempt with its hooks closed over it, closed with it. The price is an MCP connection per attempt.
The HTTP API
Section titled “The HTTP API”The same as examples/swarm’s, served by the same code: routes,
bodies, answers, status codes, the event stream’s frames and cursor (<turn>:<attempt>:<seq>,
?after= and Last-Event-ID), parking and its answer checks, the children’s streams and listings.
The platform’s differences:
- A
503namesdynamodb: the store cannot be reachedwhere the Temporal swarm names Postgres or Temporal - one fixed sentence, whatever DynamoDB said (the log has that)./readyz(unauthenticated, as there) reads nothing - a read is billed, and anyone can call/readyz: it says the process is up, its configuration was read, and whether a stream’s poll is failing right now. POST /sessionsmay answer429 too_many_sessionswithRetry-After: at mostSESSION_CREATE_PER_MINUTEsessions are started per minute over the whole deployment (60 by default;0turns it off). See Security.SSE_MAX_CONNECTIONScounts the open streams of one gateway instance, as in the Temporal swarm. A stream behind a Function URL is one invocation, ended on purpose shortly before the function’s 15 minutes; behind a load balancer it lasts as long as its task. Either way clients reconnect withLast-Event-ID(anEventSourcedoes it by itself).- A Function URL streams at most 200 MB per response (the first 6 MB at full speed, then 2 MB a
second - AWS’s “Response streaming for Lambda functions”). A replay from
0of a long session can be larger: the gateway ends the response cleanly after the frame that passes 150 MB (URL_STREAM_MAX_BYTES,src/lambda-url.ts), and the client goes on from the last frame it got in the next invocation - nothing is lost, it takes as many invocations as it needs (a 500 MB replay: four, about four minutes at 2 MB a second). AWS also says a streamed response is not stopped when the client goes away: such a stream’s invocation runs - and is billed - until the gateway ends it shortly before the timeout. Beyond a few users, the container gateway. - An event reaches an open stream up to
SSE_POLL_MSafter it was stored (up toSSE_POLL_IDLE_MSwhen the stream had been quiet). - An ended session answers
404on every route once its retention has passed, whether its items have been deleted yet or not.
Turns, parking, children, pipelines
Section titled “Turns, parking, children, pipelines”The semantics are examples/swarm’s; how they run here:
- A turn - phases
0, 1, ...(one per park and resume), each a message{ task: "turn", sessionId, turn, k }. A stop while an attempt runs reaches it at its next lease renew or event batch (at most TTL/3, 5 s by default); a stop while it is parked ends the turn at once (its items closed; no message of it exists). A stop between attempts is read by the next attempt before it runs anything. - Parking - the attempt reports
parkedand ends; the session records the items (what the gateway checks an answer against), the reducer takes the answers (the authority), and the transition that takes the last one sends the next phase. A session that goes idle while its turn is parked ends as a stop withendwould end it. Not mirrored: a turn holds at most 30 open questions at once (its own and its children’s): a park beyond that fails the turn (or the child) - the Temporal swarm has no such bound; here a transaction holds 100 actions. - Static subagents -
SUBAGENTS, as in the Temporal swarm: the tool defers, the session sends atask: childper call (withinSUBAGENT_MAX_PER_ROUND/_PER_SESSION), the child runs its profile’s agent in its own stream<session>/<item>, its outcome answers the item. A child parks like a turn (CHILD_ASK=park): its items are the session’s, owned by it; the gateway recomputes the owner (childOwnerOf) and the session routes the answer to that child’s wait, which is checked again there. - Pipelines -
PIPELINES: the session sendstask: pipeline; every node visit is atask: childof its own (itsagent.run, then the route call where it ran), a wave started together. A visit’s outcome is appended to the pipeline’s log by the transition that takes it, which sends the next replay. The pipeline runs the definition it started with (kept at its first replay), whatever a later deploy setsPIPELINESto.
What happens on a crash
Section titled “What happens on a crash”- An attempt fails (the provider fails past the agent’s retries, a journal append is refused):
the worker makes its message visible again after a backoff (
WORKER_RETRY_BASE_MS, doubling with each attempt), and the next attempt resumes the run from its last snapshot. Once the phase’s attempts ran out (TURN_MAX_ATTEMPTS, counted in DynamoDB) the turn fails and the message is done - unless its run is over on record (the last attempt finished it and died before it could say so): then that outcome is reported, not a failure (tests/worker.test.ts). What is guaranteed today: a failure between two planned steps resumes at the next step, and nothing the run did before is done again (e2e/crash.test.ts(a)). What is not, until the core’s fix lands (@dudko.dev/agent, PR #90): a run that fails inside a step, after a tool call of that step ran, is resumed under the next iteration’s journal positions - that step’s tool calls run again (at least once, not exactly once). The other swarms have the same limit; nothing here works around it, and nothing here needs to change when it is fixed. - The worker dies mid-attempt (a task evicted, a machine, an invocation killed; in the tests:
SIGKILL): nobody extends its message’s visibility any more, and SQS hands the message out again - withinSQS_VISIBILITY_SECONDSfor a container; for a Lambda invocation that was cut, within the queue’s visibility timeout (15 minutes), or as soon as the watchdog sends the phase again (about a minute). The next attempt watches the dead one’s lease stand still for a TTL, takes the run, raises its fence and resumes it - the write the dead attempt made is answered from the journal (e2e/crash.test.ts(b)). - The worker is told to stop (
SIGTERM: an ECS scale-in or deploy): its attempts give their runs up as a lost lease (the core writes nothing more), let the leases go, and their messages go back at once; the attempt is not counted, and another worker resumes at once (e2e/platform.test.ts). A Lambda function gets no such signal: its invocations end by themselves. - An attempt over its time (
TURN_TIMEOUT_MS, or the end of its Lambda invocation, whichever comes first): the same, counted as an attempt. A turn longer than one attempt may take is therefore not lost - it goes on in the next attempt, from the journal - but each such cut spends one ofTURN_MAX_ATTEMPTS. - A tool that does not heed the abort:
agent.runsettles when its run ends - also when the attempt gives the run up - while such a tool’s call may still be at work (the core does not wait for it;tests/steps.test.tsshows it). In a container the call would go on in the background; in a Lambda function, at some later thaw of the execution environment. So an attempt waits for its own tools’ calls before it ends, for at most a TTL (15 s), and logs a call that outlives that. Its result is never journaled: the next attempt may make the call again. - An attempt that is alive and says nothing (a paused or partitioned process): it renews its
lease no more and extends its message no more. The message comes back; the next attempt watches
the lease for a TTL, then: before the first snapshot it supersedes the run - the old attempt’s
next journal append is refused and the core stops it before any tool call it makes runs; after
its plan, it raises the run’s fence and resumes: nothing of the old attempt is written again -
no snapshot, no journal entry, no event (
e2e/zombie.test.ts,tests/steps.test.ts). What no fence undoes is a tool call the old attempt had already started. - A message is delivered twice while its attempt is alive (a standard queue does that; a
visibility timeout that ran out under a long attempt; a message the watchdog sent again while
the first was only slow): the second delivery finds the run’s lease held, watches it for a TTL
and a half, sees it renewed, and is told
busy- not counted, nothing run, the attempt untouched. The message comes back after a delay that grows; by then the phase has its outcome (done) or its attempt died (resumed). A duplicate never stops a healthy attempt and never re-runs its tool call (tests/steps.test.ts,tests/worker.test.ts,e2e/crash.test.ts(c): a real tool call in flight, run once). A duplicate that gets the lease only because the attempt has just finished reports what is on record: it fences nothing and runs nothing. - The store would not serve (writers that kept colliding past a transaction’s retries,
throttling, a request that got no answer): a delivery that could not take its run for it is
told
busy- not an attempt. An attempt is counted when its delivery begins, so the count includes attempts under way: a phase is never failed on the bare count. A delivery that finds the count over the limit reports the run if it is over on record, is toldbusyif an attempt holds the run and renews, is toldbusytoo if another delivery of the phase began less than three TTLs ago (it may still be on its way to its lease) - and only then fails the phase. - A commit’s answer was lost (applied by DynamoDB, a broken connection to the caller): the
same request is sent again under its idempotency token, and DynamoDB applies it once. If no
answer ever comes, the call fails as “busy” - and may be in. Nothing is undone for that: parts
written ahead of a transaction are never deleted because it “did not commit” (nobody can know);
a write that was refused deletes its parts only after reading the owner again
(
tests/store.test.ts). - The result was lost (the run ended, the report did not arrive): the next attempt finds the
snapshot
complete(orwaiting) and reports it without running anything - also after the attempts ran out. - A message is lost (somebody purged the queue; it ended in the dead-letter queue after
max_receive_countreceives): the watchdog sends the phase again (e2e/platform.test.ts); out of attempts, that delivery fails the turn - after it found no run on record and no lease renewed. A message that is not a task at all is dropped by the worker; one that keeps failing comes back more and more slowly, and ends in the dead-letter queue - it cannot loop for ever. - An effect cannot be made (SQS is briefly unavailable): retried with backoff, in order. A message that starts a turn or a child is given up after 12 tries and what it would have run fails, so the session goes on; any other message (a resume, a pipeline’s next step, a timer) is never given up - dropping one would leave the session “running” for something nobody will finish.
- A process dies between its commit and its send: the effects are in DynamoDB; the sweep (every minute) makes them.
The limits of DynamoDB, SQS and Lambda, and what is done about each
Section titled “The limits of DynamoDB, SQS and Lambda, and what is done about each”| Limit | What is done |
|---|---|
| DynamoDB: an item holds 400 KB | Values that may be larger - the reducer’s state, a run’s snapshot, a journal entry, a phase’s input, a child’s input - are blobs: JSON text in parts of 120,000 characters (under 360 kB each). A text of up to 60,000 characters lives in its owner’s item; a longer one is written before the transaction that names it, under a fresh version, and the transaction writes only the pointer - a reader never sees half a value. Parts nothing names any more (the value before, a write that was refused or never committed) are not deleted at once: a reader may still hold the pointer of the value before, and a commit can go through without the writer learning it. They are collected by age - fifteen minutes, more than a transaction’s retries and a commit’s idempotency token live - after later writes of the same owner (at most once a minute per owner and process); a reader that still loses a part reads the pointer again once. What is left when the writes stop goes with the session at its retention. A stored event is capped by EVENT_MAX_BYTES (a stub beyond; 350,000 at most); a turn.ended marker over the cap keeps its fields with the long texts cut (truncated); a parked item’s question over 100,000 characters is stored as a stub. |
| DynamoDB: a transaction holds 100 actions and 4 MB | Big values go in by pointer (above), so a transition’s transaction is small whatever the state’s size; items a transition only read need no action of their own (the session’s lock covers them). Event batches are cut by count (90) and by bytes (3 MB). A transaction beyond either limit is refused before it is sent - it would be refused again, so it is not retried as “busy”: an attempt whose outcome does not fit fails its phase saying so, and the gateway answers 500 too_large, never “cannot be reached”. What would grow a transition’s transaction is bounded where it comes in: a turn holds at most 30 open questions (its own and its children’s - a stop of the turn closes them all at once, one action each); a park beyond that fails the turn (or that child) with a sentence that says why, instead of a transition that can never commit. A stop of more children than fit one transaction (a wide pipeline wave) is done in parts: as many as fit, the rest by the session’s timer at once (tests/session.test.ts). |
| DynamoDB: no interactive transaction, no lock held between a read and a write | Optimistic: every item has a version; a commit holds on the condition that every item it writes is still the version it saw. An item it only read carries a condition of its own (a ConditionCheck) only in a transaction without a lock; a session’s transition writes the session’s item - its lock - with the version it read, and whoever changes anything under the session writes that item too, so the lock’s condition covers every item the transition read or listed (src/dynamo.ts Uow.actions). The effect is the same - nothing a transition decided from has changed when it commits - with fewer actions. A conflict runs the function again (up to 10 times, with a growing, jittered wait). Inside one process the transitions of a session are queued instead, so a pipeline’s wave of starts does not fight itself. A transition that still cannot commit answers 503 to the client (a retry is safe: every call is idempotent). |
| DynamoDB: a commit can be applied and its answer lost | Every commit carries a ClientRequestToken: the same request sent again (by the SDK, or here) is applied once for ten minutes. Beyond that the caller’s own records make a repeat harmless: a snapshot’s write mark, a journal entry that is “the same entry”, an outcome applied once per phase. |
| DynamoDB: no clock a caller can read | The lease compares no clocks (it is watched); the limiter counts by the taker’s clock and never lets a bucket’s time go back; the watchdog’s “heard of” is a guess whose only effect is one more message - which then watches the lease itself. |
| DynamoDB: a partition takes about 1000 writes a second; a transactional write costs double | A session is one partition, and its event stream is the hot part of it: batched by EVENT_FLUSH_MS, at most a few hundred events a second in bursts. The session’s own item is written once per transition, never per event or heartbeat. A lease is written at most every sixth of its TTL however often event batches ask (and at least every half TTL while its attempt runs). A limiter bucket is written once per model call: use LIMITER_SCOPE=model to spread a busy deployment. |
| DynamoDB: a global index is eventually consistent | Only the sweep reads one, and it reads the session’s own item (consistently) before it acts: a session that became due a moment ago is found by the next sweep. |
| DynamoDB: TTL deletes when it likes (up to days late), one item at a time | Used only for housekeeping: a lease nobody released, an idle limiter bucket. A session is deleted by the sweep at its retention - its 404 starts at the deadline, whatever is still stored. |
| SQS: at least once; no names; no order | See above: a phase’s outcome is applied once, a run’s lease is never taken from a holder that renews, a replaced message is dropped by its generation, a timer or a replay that comes twice finds nothing to do. |
| SQS: a delay of at most 15 minutes | A deadline further away has no message: it is stored, and the sweep runs it. |
| SQS: a message is hidden for its visibility timeout, 12 hours at most | A container extends its message’s visibility while it works (every third of SQS_VISIBILITY_SECONDS) and sets it to the verdict’s delay when it does not finish. On Lambda the queue’s timeout covers one invocation, and a message that is to come back sooner has its visibility set before it is reported. |
SQS: the receive count is the queue’s, and a busy delivery is a receive |
A phase’s attempts are counted in DynamoDB. max_receive_count (20) only ends a message nobody can take; keep it well above TURN_MAX_ATTEMPTS. |
| SQS: a message holds 1 MiB | A message carries ids only (the worker reads its input from DynamoDB). |
| Lambda: an invocation ends at 15 minutes | TURN_TIMEOUT_MS is at most 14 minutes there; the attempt is told when its invocation ends and gives its run up 20 seconds before. A longer turn continues in the next attempt (from the journal), spending one of TURN_MAX_ATTEMPTS each time; a single model call or tool call longer than that can never finish on Lambda - use containers. |
| Lambda: one request per execution environment; concurrency is a quota | Each attempt is an invocation (the turns mapping’s maximum_concurrency is the cap, and the spending cap); control messages have a function - and a concurrency - of their own, so attempts never starve them. An open event stream is an invocation too, held for up to 15 minutes: the account’s concurrency is shared by all three functions, so by default each one’s is reserved (reserve_concurrency: the gateway’s max_concurrency = 10 open streams and calls at once, the turns’ max_turns, the control’s max_control) - streams can never take the worker’s, and a holder of the token cannot open more than the gateway’s share. SSE_MAX_CONNECTIONS counts one execution environment’s streams and bounds nothing on Lambda: the reservation is the cap. An account with a small concurrency limit (a new one’s may be 10) cannot reserve: reserve_concurrency = false there, and nothing but the account then caps the gateway - serve more than one user from the container gateway instead. See Lambda or containers. |
| Lambda: an SQS mapping retries a whole batch unless told otherwise | ReportBatchItemFailures, and one message per invocation on both queues (batch_size = 1): an invocation answers its batch only when all of it is done, so a sweep in a batch would hold the timers and replays beside it - and their receive counts. |
| A sweep is one delivery, with a time limit | The sweep reads the index a page at a time and reads on past sessions it could not serve (each one it failed leaves the head of the index for a minute, doubling, at most an hour), stops twenty seconds before its delivery’s end (a purge too, which the next sweep finishes), and serves at most 1000 sessions a run: one session whose timer keeps failing never stalls the others. |
| EventBridge Scheduler: once a minute at the finest | The sweep’s pace: a far deadline is met to the minute. |
Costs to watch
Section titled “Costs to watch”Nothing here was measured on AWS; these are the things that grow.
- DynamoDB writes (on demand: per write unit of 1 KB; a transactional write costs two): one
item per stored event (a streaming model emits many
text.deltaevents: this is the largest number by far), two journal entries per model or tool call, a snapshot per planned step, a lease renew everyLEASE_TTL_MS / 3per running attempt, about five items per transition. A value in parts costs its size: a megabyte of snapshot is about a thousand write units - where an S3PUTwould be one request. If your runs carry megabytes of tool output, that is the first thing to move (why it is not), or to shrink (AGENT_COMPACTION). - DynamoDB reads: one query per page of events replayed to a stream reader, one small query per
poll per open stream per gateway instance (
SSE_POLL_MS/SSE_POLL_IDLE_MS: an open, quiet stream is one eventually consistent query a second by default), a handful per transition, three per event batch (the run’s fence, the stop flag, the lease). - Storage: every model response and tool result is stored twice (the journal and the snapshot)
and once more as events.
SESSION_RETENTION_DAYSdeletes an ended session whole; a session that never ends is never deleted - setSESSION_IDLE_TIMEOUT_MS. - Lambda: the worker is billed for every second an attempt’s invocation runs - including the seconds it waits for the model, and the TTL a duplicate delivery spends watching a lease. The gateway is billed for every second a stream is open. Containers turn both into a flat price.
- SQS / Scheduler: a few requests per attempt, per pipeline step, per near timer; a sweep a minute (43,200 messages a month, each one index query per index partition).
- What bounds a runaway: the turns mapping’s
maximum_concurrency(or the worker tasks xWORKER_MAX_CONCURRENT_TURNS),SESSION_CREATE_PER_MINUTE,SESSION_MAX_QUEUED_MESSAGES, the agent’s ownAGENT_MAX_TOTAL_TOKENS/AGENT_MAX_TOOL_CALLS,LIMITER_*.
Lambda or containers
Section titled “Lambda or containers”One codebase, two ways to run each role; Terraform’s worker_runtime and gateway_runtime choose
(lambda by default), independently.
| Lambda (default) | Containers (ECS Fargate) | |
|---|---|---|
| What runs | a zip of dist/lambda (build): worker.handler (two functions: turns, control), gateway.handler |
the image (Dockerfile): gateway and worker services |
| The core it runs | the one in this tree, as built (package:lambda: a pnpm deploy --prod from the workspace lockfile, so every package - their own dependencies too - is the version pnpm-lock.yaml names; the zip’s package.json names exact versions, no range) |
the one in this tree (the image builds it, the same way) |
| The worker’s way in | an event source mapping per queue invokes it; no URL, no permission to invoke for anybody | it polls the queues; no port, no inbound rule |
| An attempt’s time | 14 minutes (TURN_TIMEOUT_MS); a longer turn continues in the next attempt |
29 minutes by default, up to 4 hours |
| Attempts at once | the turns mapping’s maximum_concurrency (one per invocation) |
tasks x WORKER_MAX_CONCURRENT_TURNS (attempts mostly wait: many fit one vCPU) |
| Control work beside attempts | a function and a mapping of its own | slots of its own in every task (WORKER_CONTROL_CONCURRENCY) |
| A worker that dies | its message returns after the queue’s visibility timeout (15 minutes) - or the watchdog sends the phase again after about a minute | its message returns after SQS_VISIBILITY_SECONDS (60) |
| A deploy / a scale-in | nothing to hand over: an invocation ends by itself | SIGTERM: attempts give their runs up, messages go back at once |
| Event streams | one invocation per open stream, at most 15 minutes each, billed while open; at most gateway_scaling.max_concurrency at once (reserved) |
long-lived behind the load balancer; SSE_MAX_CONNECTIONS per task |
| The gateway’s address | a Function URL (HTTPS, AWS’s certificate) | an Application Load Balancer (HTTPS, your certificate) |
| The runtime | AWS’s Node.js 22 runtime | Node 22 too (the same major), distroless, uid 1000, nothing writable but /tmp, no shell; its base images are pinned by tag as the other ports’ are - pin them by digest (--build-arg NODE_IMAGE=node:22-bookworm-slim@sha256:...) for an image you ship |
| stdio MCP servers | only what the package brings | the command must be in the image (the distroless one has only node) |
| Secrets | read from Secrets Manager at a cold start (<NAME>_SECRET_ID) |
the task definition’s secrets |
| Network | none to make | a VPC, private subnets with a way out, a load balancer for the gateway |
| Scaling | Lambda’s own | tasks (fixed here: add Application Auto Scaling on the queue’s depth) |
A sensible mix: the worker on Lambda until attempts get long or many, the gateway on containers
once many clients hold streams open. On Lambda the core’s worker-thread subagents and run_js
sandbox work as far as the packaged node_modules carries their files (it is the image’s, made
the same way).
Configuration
Section titled “Configuration”Everything comes from the environment. The names are
examples/swarm’s wherever the meaning is the same; a bad value
stops the process at start with the variable’s name in the log. A secret may be named instead of
given: <NAME>_SECRET_ID (a Secrets Manager secret’s name or ARN, read once when the process
starts - for GATEWAY_TOKENS, AGENT_API_KEY and MCP_SERVERS, and nothing else), or
<NAME>_FILE (a mounted file).
The platform (both roles)
| Variable | Default | |
|---|---|---|
AWS_REGION |
- (required; Lambda sets it) | The region of the table and the queues |
DYNAMODB_TABLE |
swarm |
The table |
SQS_QUEUE_TURNS_URL / SQS_QUEUE_CONTROL_URL |
- (required) | The queue of attempts; the queue of pipeline steps, timers and the sweep. https:// |
WORKER_RUNTIME |
lambda in a function, else container |
How the workers run - the whole deployment’s, so the gateway knows what one attempt may take |
LEASE_TTL_MS |
15000 |
The run lease’s TTL (renewed every third of it; a stop reaches an attempt within that third; a run is taken from a silent holder after one whole TTL of watching); what TURN_HEARTBEAT_TIMEOUT_MS is to the Temporal swarm. The watchdog looks every four TTLs and is patient for three |
EVENT_MAX_BYTES |
262144 |
One stored event’s cap (at most 350000) |
LOG_LEVEL |
info |
One JSON line per entry (CloudWatch Logs), redacted |
Local only - refused unless SWARM_LOCAL=true, and SWARM_LOCAL=true is refused on AWS
(AWS_LAMBDA_FUNCTION_NAME, AWS_EXECUTION_ENV, ECS_CONTAINER_METADATA_URI_V4, … set):
| Variable | |
|---|---|
SWARM_LOCAL |
The one switch for everything below. With it, a <NAME>_SECRET_ID is refused: a local try calls no AWS service |
DYNAMODB_ENDPOINT |
DynamoDB Local (fixed fake credentials are used - never the machine’s own) |
SQS_ENDPOINT |
A stand-in for SQS (the same) |
GATEWAY_AUTH=none |
No bearer token |
The gateway
| Variable | Default | |
|---|---|---|
GATEWAY_AUTH |
bearer |
|
GATEWAY_TOKENS |
- (required; a secret) | Bearer tokens, comma separated, 16+ characters each; a placeholder (change-me...) is refused |
GATEWAY_HOST / GATEWAY_PORT |
0.0.0.0 / 8080 |
A container’s; PORT wins over GATEWAY_PORT |
CORS_ORIGINS |
none | Allowed browser origins (exact), or * |
GATEWAY_MAX_BODY_BYTES |
65536 |
|
MESSAGE_MAX_CHARS |
32000 |
|
CONTEXT_KEYS |
(none) | The page-context keys a message may carry (context of POST /sessions/:id/messages), comma-separated, exact names; every other key is dropped, and with none the context is ignored. Untrusted: shown to the model as data, never a policy input |
SSE_MAX_CONNECTIONS |
200 |
Open event streams per instance (more: 503) |
SSE_KEEPALIVE_MS / SSE_BATCH |
15000 / 500 |
|
SSE_POLL_MS / SSE_POLL_IDLE_MS |
500 / 1000 |
How often an open stream’s newest key is asked for: while it moves, and once it has been quiet for five seconds |
SESSION_CREATE_PER_MINUTE |
60 |
Sessions the whole deployment may start in a minute (429 beyond); 0: no limit |
SESSION_RETENTION_DAYS |
30 |
An ended session’s items are deleted this long after it ended; 0 keeps them. Fixed when the session starts |
A session’s options - fixed when it starts (its item keeps them); read by the gateway:
| Variable | Default | |
|---|---|---|
SESSION_IDLE_TIMEOUT_MS |
86400000 |
No work for this long ends the session (a parked turn ends stopped); 0 never. Met to the minute when it is longer than 15 minutes |
TURN_TIMEOUT_MS |
840000 on Lambda, 1740000 in a container |
One attempt of a turn; at most 840000 on Lambda, 14400000 in a container. The Temporal swarm’s default, 1800000, is refused on Lambda. It is a session’s option, fixed when the session starts - by the gateway, from the gateway’s WORKER_RUNTIME: Terraform sets that on both roles; a deployment made by hand with the worker on Lambda and the gateway elsewhere must set WORKER_RUNTIME=lambda (or TURN_TIMEOUT_MS) on the gateway too. (On Lambda each attempt also ends before its invocation does, whatever the option says - it is told the invocation’s end.) |
TURN_MAX_ATTEMPTS |
5 |
Attempts of one phase |
SESSION_HISTORY_MAX_CHARS |
200000 |
|
SESSION_MAX_QUEUED_MESSAGES |
50 |
|
SUBAGENT_MAX_PER_ROUND / SUBAGENT_MAX_PER_SESSION |
4 / 50 |
|
PIPELINE_MAX_PER_ROUND / PIPELINE_MAX_PER_SESSION |
2 / 20 |
The worker
| Variable | Default | |
|---|---|---|
WORKER_RETRY_BASE_MS |
2000 |
A failed attempt’s first backoff; it doubles with each attempt of the phase (5 minutes at most) |
EVENT_FLUSH_MS |
500 |
How long an attempt buffers its run’s events before one write sends them |
LIMITER_REFILL_PER_SECOND, LIMITER_CAPACITY, LIMITER_MAX_WAIT_MS, LIMITER_SCOPE |
off | sharedLimits, as in the Temporal swarm (a DynamoDB item per bucket) |
CHILD_ASK |
park |
park / deny |
WORKER_MAX_CONCURRENT_TURNS |
10 |
A container: attempts one process runs at once |
WORKER_CONTROL_CONCURRENCY |
10 |
A container: control messages one process runs at once - slots of their own |
SQS_WAIT_SECONDS / SQS_VISIBILITY_SECONDS |
20 / 60 |
A container: its long poll, and how long a message it took stays hidden (extended while it works; what a worker that died leaves before the message comes back) |
WORKER_SHUTDOWN_GRACE_MS |
25000 |
A container: how long a worker told to stop waits for its attempts to give their runs up (ECS gives 30 seconds by default; Terraform sets 60) |
The agent (the worker) - the Temporal swarm’s variables, with the model built in code
(src/agent-config.ts): AGENT_PROVIDER_TYPE (openai default,
anthropic, google, openai-compatible - the providers this example installs), AGENT_API_KEY
(a secret, required), AGENT_MODEL (required), AGENT_BASE_URL (required for
openai-compatible), AGENT_PROVIDER_OPTIONS, AGENT_PLANNER_MODEL, AGENT_SYNTHESIZER_MODEL,
MCP_SERVERS (HTTP {"url": ..., "headers": {...}} and stdio {"command": ..., "args": [...]},
as in the Temporal swarm - a secret when its headers carry a token), AGENT_TOOL_APPROVAL,
AGENT_TOOL_RULES, SUBAGENTS, PIPELINES (a profile’s or a node’s model is a model id on the
same provider), AGENT_MAX_ITERATIONS, AGENT_MAX_STEPS_PER_TASK, AGENT_MAX_REVISIONS,
AGENT_MAX_TOOL_CALLS, AGENT_MAX_TOTAL_TOKENS, AGENT_LLM_TIMEOUT_MS, AGENT_LLM_MAX_RETRIES,
AGENT_COMPACTION, AGENT_CONTEXT_WINDOW_TOKENS, AGENT_SYSTEM_PROMPT, AGENT_CLIENT_NAME,
AGENT_LOG_LEVEL.
Everything else of the Node core works here as in the Temporal swarm - web_fetch / egress, the
run_js sandbox, worker-thread subagents - and, as there, none of it has a variable: build the
config in code (agentSetupFromEnv(env, extra)).
Not read here (no meaning on this platform): DATABASE_URL, PG_POOL_MAX,
MIGRATE_DATABASE_URL, TEMPORAL_*, WORKER_IDENTITY, WORKER_HEALTH_PORT,
WORKER_HEARTBEAT_THROTTLE_MS, WORKFLOW_BUNDLE_PATH, TURN_HEARTBEAT_TIMEOUT_MS (the lease TTL
is it), SESSION_MAX_TURNS_PER_RUN (no continue-as-new).
Run it locally
Section titled “Run it locally”Stand-ins only: DynamoDB Local (AWS’s own local build of DynamoDB, a Java program - Java 21) and a stand-in for SQS that this example brings. No AWS account, no credentials, nothing deployed.
pnpm install && pnpm nx run-many -t build -p @dudko.dev/agent,swarm-sharedcd examples/swarm-awspnpm dynamodb:install # once: DynamoDB Local's archive (43 MB, checksum pinned)cp .env.example .env # set GATEWAY_TOKENS and AGENT_API_KEY; never commit itpnpm dev # DynamoDB Local, the SQS stand-in, the gateway (:8080), the workerTalk to it exactly as to the Temporal swarm:
TOKEN=... # one of GATEWAY_TOKENSS=$(curl -s -X POST localhost:8080/sessions -H "authorization: Bearer $TOKEN" \ -H 'content-type: application/json' -d '{"message":"What is 2+2?"}' | jq -r .sessionId)curl -N localhost:8080/sessions/$S/events -H "authorization: Bearer $TOKEN"Nothing is kept when it stops (DynamoDB Local runs in memory).
Deploying
Section titled “Deploying”The owner’s steps. This repository never runs any of them, and its CI holds no AWS credentials. Terraform makes everything but the secrets’ values, the functions’ package and the image.
cd examples/swarm-aws/deploy/terraformcp terraform.tfvars.example terraform.tfvars # region, worker_env (never commit it)aws sso login # the owner's own credentials, however you hold themterraform init # the provider is pinned (.terraform.lock.hcl)
# 1. Everything but the compute: the table and its index, the queues and their policies, the# roles, the (empty) secrets, the log groups.terraform apply
# 2. The secrets' values - never in Terraform (they would be in its state), never in a file here.aws secretsmanager put-secret-value --secret-id swarm/gateway-tokens --secret-string "$(openssl rand -hex 32)"aws secretsmanager put-secret-value --secret-id swarm/agent-api-key --secret-string "$PROVIDER_API_KEY"
# 3. The functions' package: the bundle, its node_modules pinned by pnpm-lock.yaml, a zip.# (Never `npm install` there: with no lockfile it takes the newest version every range allows# on the day - of the core too.)cd ../../../..pnpm nx build swarm-aws # examples/swarm-aws/dist/lambdapnpm --filter swarm-aws package:lambda # its node_modules: pnpm deploy --prod(cd examples/swarm-aws/dist/lambda && zip -qr ../lambda.zip .)
# 4. The functions, their mappings, the Function URL and the sweep's schedule.cd examples/swarm-aws/deploy/terraformterraform apply -var deploy_compute=true -var lambda_package=../../dist/lambda.zipterraform output gateway_urlContainers instead of functions (either role, or both - worker_runtime = "container",
gateway_runtime = "container", with vpc_id, private_subnet_ids and, for the gateway,
public_subnet_ids and certificate_arn); instead of step 3:
REPO=$(terraform -chdir=examples/swarm-aws/deploy/terraform output -raw image_repository)aws ecr get-login-password | docker login --username AWS --password-stdin "${REPO%%/*}"docker build -f examples/swarm-aws/Dockerfile -t "$REPO:v1" . # from the repository's rootdocker push "$REPO:v1"DIGEST=$(docker inspect --format '{{index .RepoDigests 0}}' "$REPO:v1")terraform -chdir=examples/swarm-aws/deploy/terraform apply -var deploy_compute=true -var "image=$DIGEST"(image_architecture must be what the image was built for: X86_64 by default.)
After the first deploy, look at the two dead-letter queues (terraform output queues): a message
there is one nobody could take - an alarm on their depth is the first thing to add. To move one
back, name your operator role in operator_role_arns (see Security).
With a customer managed key (kms_key_arn): the roles made here get what they need of the key
(the ECS execution role kms:Decrypt, to read the secrets it injects); the key’s own policy is
yours, and it must let CloudWatch Logs use it, or the log groups cannot be made - a statement for
the principal logs.<region>.amazonaws.com with kms:Encrypt*, kms:Decrypt*,
kms:ReEncrypt*, kms:GenerateDataKey* and kms:Describe*, conditioned on
kms:EncryptionContext:aws:logs:arn being one of the two log groups’ ARNs (AWS’s
“Encrypt log data in CloudWatch Logs using AWS KMS”). The queues, the table, the secrets and the
image repository are used through the roles’ own permissions (the key’s default policy lets the
account’s IAM grant them).
Security
Section titled “Security”- The API’s bearer token is checked in constant time (swarm-shared) before anything else: an
unauthenticated request reads nothing from DynamoDB (
tests/gateway.test.tsruns every route against a store that fails the test if it is touched). It is one shared secret for the whole API - whoever holds it can start, steer and read any session: put your own authentication in front before serving several users. - The worker is not an endpoint. It runs turns, ends sessions and deletes them - and nothing
can call it: as a function it has no URL and no resource policy (no principal may invoke
it; the event source mappings poll its queues as its own role and hand it what they
received), as a container it has no port and a security group that lets nothing in. The only
way into the session logic through it is a message on one of its two queues, and each queue’s
own policy says who may put one there: the gateway’s role, the worker’s role, and - on the
control queue only - the sweep’s schedule (and the roles you name in
operator_role_arns, see below). Every other principal is denied by the queue’s own policy, whatever identity policies grant it; only the worker’s role may take a message; and nothing travels in clear (the dead-letter queues too). The schedule’s role can send one message to one queue and nothing else.tests/deploy.test.tsreads all of that out of Terraform. What a queue policy does not stop: an administrator of the account, who can rewrite the policy, redeploy the worker or pass its role - the policy keeps out a mistake or another principal’s leaked credentials, not the account’s own administrators. - Moving messages back from a dead-letter queue:
aws sqs start-message-move-tasksends as the principal that started it, which the queues deny - name the operator’s role inoperator_role_arnsto allow it (that role can then start work in the swarm, which is what a move does). Without one, a message there is looked at and not moved; the watchdog sends a phase whose message was lost again by itself. - A message carries ids, and a child only of its own session - and is still checked as if
anyone could have written it: its task is one of five, a session id is checked against the API’s
id pattern, a child’s workflow id must be one the session’s id names (
subagent-<session>-...), numbers are numbers. Anything else is dropped (logged in the worker’s words, never the message’s). A message for a session nobody created does nothing and writes nothing. - Tenant isolation is the key. Everything of a session is in the partition
s#<id>, and every key is built from the id by one module (src/dynamo.ts), which refuses an id that is not an id. A parked item is looked up under its session and checked against it; a child’s answer goes only to the child the session named (childOwnerOf, swarm-shared). - The roles hold what the code calls and no more: items by key, ranges of a partition and
transactions on the swarm’s table (no
Scan, noUpdateItem, no table administration), the sweep’s index for the worker alone, the queue calls each role makes, and each role’s own secret - the gateway cannot read the provider key, the worker cannot read the API’s tokens. - Secrets are Secrets Manager’s: named by the functions’ variables (
<NAME>_SECRET_ID) or the task definitions’secrets, never in a variable’s value, a variable file or Terraform’s state (it makes the secret, the owner puts the value in). The provider key reaches the provider through the model object built in the attempt; it is in no snapshot, event or log. A secret that cannot be read stops the process with the kind of failure in the log, not what the service said. - Local-only switches have one guard.
DYNAMODB_ENDPOINT,SQS_ENDPOINTandGATEWAY_AUTH=noneare refused withoutSWARM_LOCAL=true, andSWARM_LOCAL=trueis refused wherever a Lambda or ECS runtime variable is present - none of them can reach a deployment by a copied variable. With a stand-in’s endpoint the clients use fixed fake credentials, never the machine’s own. - The fences keep an attempt that lost its run from writing: a snapshot below the attempt on record or below the run’s fence is refused, so is a journal entry, and so is an event; a lease is taken from its holder only after a watched TTL of silence, never while the holder renews; a heartbeat of a phase that is not the current one answers stop. Each check and the write it guards are one transaction.
- Logs: every line goes through one filter (
src/redact.ts): the message and the fields that carry outside text (error,reason,message, …) have bearer tokens, API keys andkey=valuesecrets redacted and are clipped to 300 characters; the core’s own warnings are a field, never the line. What DynamoDB or SQS said of a failure (it may name the account, a role, a table) goes to the log and never to a client or into a message’s verdict. /healthzand/readyz(the gateway, unauthenticated) read nothing from DynamoDB and call nothing. The worker has neither: there is nothing to ask it on.- Denial of wallet. The shared API has no per-user quota (it has one token): what bounds the
spend of a leaked token or a loop is the deployment’s -
SESSION_CREATE_PER_MINUTE(a global bucket;429beyond),SESSION_MAX_QUEUED_MESSAGESper session, the cap on attempts running at once, the agent’s own token and tool-call budgets. A per-user or per-token quota belongs in the authentication you put in front. - The data at rest is the conversation: each session’s items hold its events (tool inputs and
outputs), snapshots, journal (every model response and tool result) and parked items; SQS holds
only ids. Everything is encrypted at rest with AWS’s keys, or with yours (
kms_key_arn).
Retention
Section titled “Retention”SESSION_RETENTION_DAYS (30 by default) after a session ended - a stop with end, or the idle
timer - its items are deleted: everything in its partition, its own item last (a purge that was
cut short is taken up by the next sweep). From its deadline on its id answers 404 on every
route, whether the deletion has run yet or not. The deadline is in the sweep’s index; the sweep
deletes within a minute of it. A session that has not ended is never deleted: end the ones you
are done with, or set SESSION_IDLE_TIMEOUT_MS.
Why not DynamoDB’s TTL on a session’s items: TTL deletes an item at a time, when it likes (up
to days after its time), and a session’s items are written long before anybody knows when the
session will end - every one of them would have to be rewritten at its end. TTL is used where an
item stands alone: a lease nobody released, a limiter bucket nobody draws from. An operator who
must delete one session’s data sooner ends it with a short retention, or deletes its partition by
hand (a Query of pk = s#<id> and a batch of deletes).
Limits, and what is not supported
Section titled “Limits, and what is not supported”- Interactive MCP OAuth, MCP elicitation,
rememberon an approval, steering inside a turn: as in examples/swarm. - A run that fails in the middle of a step re-runs that step’s tool calls (the core’s limit, PR #90; see What happens on a crash).
- One attempt is one delivery: 14 minutes at most on Lambda. A longer turn continues in the
next attempt (from the journal), spending one of
TURN_MAX_ATTEMPTSeach time. - A stopped or failed attempt’s in-flight tool call is not undone: the journal closes every window but the one between a tool’s side effect and its result being on record.
- An agent per attempt: MCP servers are connected to at every attempt (a stdio server is started at every attempt).
- Taking over a dead attempt’s run waits one lease TTL (15 s), always: the price of a lease that compares no clocks. And a duplicate delivery holds a worker slot (or an invocation) for a TTL and a half each time it comes.
- The watchdog cannot see a message that is in flight: it reads “nothing waits in the queue,
nobody was heard of for three TTLs” as lost, and sends the phase again. An attempt that needs
longer than that to get as far as its lease (a very slow MCP server start) gets a second
message: the first delivery goes on if it is alive (the second is told
busy), nothing runs twice; it costs a slot for a lease’s wait. - A start can fail though its message was sent, in one corner: twelve sends in a row fail, and the last of them was in fact accepted by SQS. The turn is failed; the message, when it comes, finds the phase’s outcome and is dropped. (Cloud Tasks’ names let the Google Cloud port ask whether the task exists; SQS has nothing to ask.)
- A far deadline is met to the minute (the sweep’s pace), an event is streamed up to a poll interval late, and a duplicate that comes back just as an attempt ends is counted as a delivery that began (it runs nothing).
- No per-session cap on open streams (Cloudflare’s port has one): the cap is per gateway instance.
- No autoscaling of the container worker in Terraform (a fixed number of tasks): add Application Auto Scaling on the turns queue’s depth.
What was only tested on stand-ins
Section titled “What was only tested on stand-ins”Everything. Nothing here has run on AWS. What that means, concretely:
- DynamoDB: DynamoDB Local is AWS’s own build of the API on SQLite. It enforces the 400 KB
item size, runs
TransactWriteItemswith its conditions, honoursClientRequestToken(seen:tests/dynamo.test.ts) and serves the sparse index - but its transactions never meet real contention (TransactionConflictfrom another transaction in flight, throttling, the latency under which the retries were tuned), its index is consistent at once where the service’s is not, its capacity is unlimited (no partition was ever hot here), and TTL does nothing in it. Nor does it ever show a Query a transaction’s rows half committed: the event readers’ guard against that (settledRead) is tested with a scripted read only. - SQS: a stand-in of this example’s own (
tests/helpers/sqs-fake.ts, whose header lists what it does and does not do), driven through the SDK’s real client. Never seen on the service: how often a standard queue really delivers twice and out of order, approximate counts (the watchdog reads “about none waiting” as “none”), the behaviour ofChangeMessageVisibilityat the edges (a message whose visibility ran out a moment before), the queue policies’Denystatements against real principals - in particular that an event source mapping and EventBridge Scheduler present the role’s ARN asaws:PrincipalArn, which is what the policies allow - and KMS. - Lambda: the built handlers are loaded and invoked in-process with an SQS batch and a
Function URL event (
tests/lambda-entry.test.ts), with the runtime’sawslambdaobject played by the test. Never run by the runtime: cold starts (and the secrets read in them), a real streamed response through a Function URL (buffering, the 15 minutes, a client that goes away - AWS says the stream is not stopped then - and the 200 MB / 2 MB-a-second limits), an event source mapping’s own behaviour (its scaling, what it does with a function that is throttled,maximum_concurrency), an invocation cut at its timeout, the packagednode_modules(package:lambda) loaded by the runtime from the zip. - ECS: the image was not built on this machine at all (no Docker daemon was running; CI builds
it and starts it read-only as uid 1000). Never run on Fargate:
readonlyRootFilesystemwith the/tmpvolume, secrets injected by the agent, the load balancer in front of an event stream, the worker’s shutdown insidestopTimeout. - Terraform:
fmtandvalidatepass (the configuration is well-formed against the provider’s schema). Noplanwas ever made: the roles’ trust policies (theaws:SourceAccountcondition for ECS and the scheduler), the queue policies,reserved_concurrent_executionson a new account’s small concurrency limit, the Function URL’s two permissions, and the mappings’ requirement that a queue’s visibility timeout cover the function’s timeout are the places a firstapplyis most likely to object. - IAM: the least-privilege lists were read off the code (
tests/deploy.test.tscompares them with the commands the code sends), not off an access-denied log. A missing action shows as a503at the gateway or a message that keeps coming back. - Costs and performance: not measured at all.
Development and tests
Section titled “Development and tests”The unit tests of the attempts, the worker, the feed, the store and the functions wait on no
clock: the core’s lease timers run on a clock the test moves (the core’s own seam,
Symbol.for('@dudko.dev/agent:run-lease-test-time')), and so do the store’s stopwatch, an
attempt’s wait for a lease, the worker’s deadline timer, the feed’s polls and the built gateway’s
stream timer (tests/helpers/time.ts); a “slow model” is a call the test holds; a wait is for
something the code reached, with a 30-second hang guard that is never an expectation. They are
meant to pass on a machine starved of CPU. (The queue tests drive the SQS stand-in, which keeps
SQS’s own seconds - visibility timeouts, delays: there the waits are for what reached the queue,
with the same hang guard. The end-to-end tests run real processes on real time.)
The workspace project swarm-aws (examples/swarm-aws): typecheck, format:check, build
(the Lambda package, offline), test and test:e2e.
pnpm --filter swarm-aws dynamodb:install # oncepnpm nx run-many -t typecheck format:check build test -p swarm-awspnpm nx run swarm-aws:test:e2e # a few minutestest and test:e2e start DynamoDB Local themselves (scripts/with-dynamodb.mjs) and stop it.
Without it (no Java, or the archive not installed) the unit tests that need DynamoDB skip,
saying why - the others run - and the script says so in a banner before and after the run (and
as a warning annotation on GitHub Actions: the repository’s ci.yml has no Java set up for it, so
most of this suite skips there). REQUIRE_DYNAMODB_LOCAL=1 makes that a failure (swarm-aws.yml
sets it: that workflow is where they run), and the end-to-end tests always require it.
- Unit tests (
tests/*.test.ts,node --test, inpnpm check): the store’s foundation on DynamoDB Local (dynamo.test.ts: the keys, the optimistic transaction and its lock, a commit whose answer is lost, the limits refused before they are met, values larger than an item and their parts); every fenced write (store.test.ts: runs and snapshots, the journal’s order and its race against a fence, the lease - watched, never computed - events, parked items, the limiter); the session with the messages played by the test (session.test.ts: every transition, six at once, children and their waits, the outbox and a process that dies before its drain, the timer near and far, the watchdog, retention, no item for a made-up id); the attempts with the real core against the scripted model (steps.test.ts: a phase, a lost result, parking, a stop, a refusal, an attempt over its time, both fences against an attempt that lost its run, a second delivery while a tool call is in flight); the worker’s verdicts (worker.test.ts); the queues, the poller and the Lambda adapter against the SQS stand-in (queue.test.ts); the gateway over DynamoDB (gateway.test.ts); the polling feed (feed.test.ts); a pipeline’s replay (pipeline.test.ts); the Function URL adapter (lambda-url.test.ts); the built functions invoked in-process (lambda-entry.test.ts); the configuration and the secrets (config.test.ts), the limiter’s math, the log filter; and what is deployed, as text (deploy.test.ts). - End to end (
e2e/*.test.ts): the gateway and the worker as real processes (node src/main.ts ..., the worker polling), DynamoDB Local, the SQS stand-in over real HTTP, the scripted OpenAI-compatible model ofpackages/agent/tests/helpers/openai-server.ts, the MCP server of@dudko.dev/test-servers. Mirrored from examples/swarm’s integration tests (and the other ports’ e2e):session(a turn end to end, replay from a cursor,Last-Event-ID, live, the refusals, the stream cap),parking(park, answer, the write once; a partial answer; stop during a park),crash(a failure between steps; the worker killed mid-step; a second delivery while a tool call is in flight),zombie(a worker paused withSIGSTOPbefore its first snapshot and woken after the turn ended elsewhere),stop,subagents(two children side by side, the per-round cap, stop while they run),child-parking((a), (d), (e)),pipelines(a wave, a routed node, the streams; stop while a node runs),limits(the shared bucket refuses a call: the turn fails, not retried),mcp, andplatform(the worker is no endpoint and drops what is not a task; SIGTERM hands a turn over; a lost message; the sweep; the idle timer). Not mirrored: what is Postgres’ or Temporal’s own (postgres.test.ts’s races - their counterparts are instore.test.ts-, continue-as-new),subagents-crashandpipelines-crash(a child’s attempt is the same code path as a turn’s, covered bycrash; a pipeline’s replay killed half way ispipeline.test.ts‘s), the pipelines’ caps, child parking’s (b), (c), (f), (g) (the shared reducer’s unit tests andsession.test.ts), and the worker as Lambda functions under a real runtime (the handlers are invoked in-process instead). - CI:
.github/workflows/swarm-aws.yml- the checks and every test with DynamoDB Local, the image built (never pushed) and started read-only, Terraform’sfmtandvalidate. No AWS credentials.
Ask about the agents
What you write goes to the project's server and an AI model. Answers can be wrong.
Loading the chat…