Production-Grade Multi-Agent: Turning Task Delegation into Recoverable Execution Protocols
This article presents a reference architecture for production-grade multi-agent systems using Go, PostgreSQL, Kafka, and Kubernetes, detailing how to transform task delegation into recoverable execution protocols through persistent state machines, stable business idempotency keys, database conditional updates, tool boundary authorization, and external fact reconciliation.
Reading font

1. A Seemingly Simple but Dangerous Collaboration Flow
Consider a customer service request: "Refund then issue a price-difference coupon." A Supervisor creates two tasks: refund.create and coupon.grant, with refund success as a prerequisite for coupon granting. If agents merely exchange natural language over a message queue, the following failure scenario occurs:
Refund Agent initiates refund; payment gateway accepts but network times out, caller receives no response.
Coupon Agent reads stale order snapshot, believes refund incomplete, refuses to issue coupon and requests reprocessing.
Supervisor interprets "refund timeout" as "refund failed" and creates a new refund task.
Second request hits payment gateway again, potentially causing duplicate refunds.
The problem is not model intelligence but the lack of persisted facts: what was sent, who is executing, whether the remote side has taken effect. A reliable system must answer: which worker owns the task now and who can take over if it disappears? How to collapse duplicate messages and tasks? When external responses are lost, should we retry, query, compensate, or escalate to manual? At what boundary are agent tool calls validated?
Design principle: Models propose candidate actions; workflow and tool layers decide whether actions take effect based on persisted facts.
2. Write Invariants Before Code
Before discussing components, define testable business invariants:
For third parties supporting idempotency keys and queries, the same business key yields at most one effective side effect.
A worker that has lost its lease cannot update task terminal state, result, or compensation progress.
Tasks with unsatisfied dependencies cannot be claimed.
Once a workflow enters compensation, no new forward-write tasks may be claimed.
Every external request with uncertain outcome has a query, reconciliation, or manual intervention loop.
Every tool call must pass identity, tenant, operation, resource, quota, timeliness, and workflow state checks.
If a third party lacks idempotency keys and result queries, the local database cannot guarantee "at most one effective refund"; correct behavior is to stop auto-retry, preserve evidence, and enter manual reconciliation — not fabricate false certainty with local locks.
3. Objects, Identities, and State: Four Concepts Not to Conflate
Workflow : One complete business process. Stable identifier: workflow_id. Solves: global result, approval, compensation.
Task : A schedulable logical step. Stable identifiers: task_id, logical_step_key. Solves: deduplication, dependencies, scheduling.
Attempt : One task claim generation. Stable identifier: attempt_no. Solves: lease and fencing.
Tool operation : One call that may change external facts. Stable identifier: business_key. Solves: idempotency, query, reconciliation. task_id is the scheduling-layer identity; it cannot replace the business idempotency key. attempt_no is merely a claim count, not a refund idempotency key. The correct business key derives from stable facts, not natural language summaries:
tenant=T1 | operation=refund.create | order=ORD-991 | after_sale=AS-77If the key itself lacks tenant, operation, and business domain, the unique constraint should at minimum be (tenant_id, operation, business_key). The same intent phrased differently by the model changes the summary hash; the same after-sale ticket does not.
3.1 Workflow State
RUNNING ─────────────────────────→ SUCCEEDED
│ └─ Confirmed irrecoverable failure ─────→ FAILED
│
├─ Successful steps need undo ────────→ COMPENSATING ──→ COMPENSATED
│ └→ NEEDS_REVIEW
└─ External facts cannot be auto-confirmed ──────→ NEEDS_REVIEWFAILEDmeans failure fact is known; NEEDS_REVIEW means the system cannot safely decide the next step automatically. After entering COMPENSATING, the scheduler must block new forward-write task claims and first confirm in-flight remote facts.
3.2 Task State and Lease
WAITING ──deps met──→ READY ──claim──→ CLAIMED ──start──→ RUNNING
│ ▲ │ │
│ └──lease expired──────┴────lease expired────┘
│ │
└──deps unsatisfied──→ CANCELLED ┌───────┴───────┐
▼ ▼
SUCCEEDED FAILED / UNKNOWNCLAIMEDand RUNNING must both carry a lease. Only reclaiming expired CLAIMED leaves tasks permanently stuck if a worker crashes in RUNNING. UNKNOWN is not ordinary failure: it means the write request may have succeeded remotely but locally there is no conclusion; the only safe path is to query the remote fact or escalate to manual.
4. End-to-End Sequence: Why Not Retry Immediately After Timeout
Using a lost refund response as example, the correct state progression:
Worker PostgreSQL Tool Gateway Refund Service
│ │ │ │
│ claim task │ │ │
├──────────────>│ │ │
│ task=RUNNING │ │ │
│ │ │ │
│ INSERT operation(PENDING, business_key) │ │
├──────────────>│ │ │
│ │ │ │
│ refund.create(business_key, capability) │ │
├────────────────────────────────────────>│───────────────────>│
│ │ │ │
│ │ │ success │
│ │ │<────────────────────│
│ timeout / response lost │ │
│ │ │ │
│ task=UNKNOWN, operation=UNKNOWN │ │
├──────────────>│ │ │
│ query(business_key) │ │
├────────────────────────────────────────>│───────────────────>│
│ confirmed(external_ref) │ │
│<────────────────────────────────────────│<────────────────────│
│ task=SUCCEEDED, operation=CONFIRMED │ │
├──────────────>│ │ │Two key points: PENDING intent is persisted before the external request is actually sent, so after a failure we know "this operation may have been sent".
On timeout, do not retry; instead query by business key first. If the remote side lacks query capability, stay in UNKNOWN and hand off to reconciliation or manual.
This explains why "exponential backoff retry on HTTP failure" does not apply to all write operations.
5. Delegation Envelope: Pass References and Constraints, Not Executable Context
Each delegation should be described by a structured protocol. If using CloudEvents, still provide required id, source, specversion, type attributes. Example envelope:
{
"schema_version": 5,
"workflow_id": "wf-123",
"task_id": "task-refund-1",
"logical_step_key": "refund:create:AS-77",
"parent_task_id": "task-root",
"target_agent": "refund",
"operation": "refund.create",
"tenant_id": "T1",
"business_key": "refund:T1:ORD-991:AS-77",
"workflow_version": 12,
"deadline_at": "2026-11-21T10:00:00Z",
"input_ref": "state://wf-123/refund-input-v4",
"input_digest": "sha256:...",
"traceparent": "00-...",
"capability_ref": "cap-123"
}Original conversations, attachments, and reasoning drafts reside in a controlled state store; messages carry only minimal input, references, and content digests. input_ref is not an access credential: the reader must still pass server-side validation of caller, tenant, expiry, authorization scope, and input_digest. Root tokens, database credentials, S3 direct credentials, and sensitive plaintext must never enter Kafka or LLM context.
6. Transaction Boundaries: PostgreSQL Persists Facts, Outbox Completes Reliable Handoff
The Supervisor performs three actions in a single database transaction: create/update task, advance workflow version, write to outbox. The Publisher then asynchronously delivers outbox events to Kafka. This eliminates the dual-write vulnerability where the database has the task but the message is never sent.
6.1 Minimal Data Model
CREATE TABLE workflow (
workflow_id text PRIMARY KEY,
tenant_id text NOT NULL,
status text NOT NULL CHECK (status IN ('RUNNING','SUCCEEDED','FAILED','COMPENSATING','COMPENSATED','NEEDS_REVIEW')),
version bigint NOT NULL DEFAULT 0,
deadline_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE agent_task (
task_id text PRIMARY KEY,
tenant_id text NOT NULL,
workflow_id text NOT NULL REFERENCES workflow(workflow_id),
logical_step_key text NOT NULL,
parent_task_id text,
operation text NOT NULL,
business_key text,
status text NOT NULL CHECK (status IN ('WAITING','READY','CLAIMED','RUNNING','SUCCEEDED','FAILED','UNKNOWN','CANCELLED')),
version bigint NOT NULL DEFAULT 0,
lease_owner text,
lease_until timestamptz,
attempt_no integer NOT NULL DEFAULT 0,
deadline_at timestamptz NOT NULL,
input_ref text NOT NULL,
input_digest text NOT NULL,
result_ref text,
last_error_code text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (workflow_id, logical_step_key)
);
CREATE TABLE task_dependency (
task_id text NOT NULL REFERENCES agent_task(task_id),
depends_on_task_id text NOT NULL REFERENCES agent_task(task_id),
PRIMARY KEY (task_id, depends_on_task_id),
CHECK (task_id <> depends_on_task_id)
);
CREATE TABLE outbox_event (
event_id text PRIMARY KEY,
aggregate_id text NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
payload_digest text NOT NULL,
published_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX outbox_unpublished_idx ON outbox_event(created_at) WHERE published_at IS NULL;
CREATE TABLE tool_operation (
tenant_id text NOT NULL,
operation text NOT NULL,
business_key text NOT NULL,
workflow_id text NOT NULL REFERENCES workflow(workflow_id),
status text NOT NULL CHECK (status IN ('PENDING','CONFIRMED','FAILED','UNKNOWN')),
external_ref text,
version bigint NOT NULL DEFAULT 0,
last_error_code text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, operation, business_key)
);Production should add indexes for workflow_id, status + deadline_at, dependency queries, and lease scans adapted to load; the above DDL illustrates constraints, not a complete sharding solution.
6.2 Create Task and Outbox in Single Transaction
func (s *Store) CreateRefundTask(ctx context.Context, in CreateInput) error {
return s.db.WithTx(ctx, func(tx Tx) error {
// 1. Optimistic lock advances workflow; reject if already compensating or version mismatch.
ok, err := tx.AdvanceWorkflow(ctx, in.WorkflowID, in.ExpectedWorkflowVersion)
if err != nil || !ok { return ErrWorkflowNotRunnable }
// 2. Logical step unique. On conflict, read existing task, compare immutable payload digest; alert if inconsistent.
task, inserted, err := tx.InsertTaskIfAbsent(ctx, in)
if err != nil { return err }
if !inserted && task.InputDigest != in.InputDigest { return ErrStepConflict }
if !inserted { return nil }
// 3. Write event in same transaction; Publisher may send only after commit.
return tx.InsertOutbox(ctx, TaskReadyEvent(task))
})
}Consumers likewise follow "persist first, then commit offset". If the process crashes after DB commit but before offset commit, Kafka replays; stable event ID, task unique key, and immutable payload digest handle replays. Conversely, committing offset before delivering to an in-memory queue loses tasks permanently on crash.
6.3 Outbox Publisher: Allow Duplicates, Never Miss
Multiple publisher instances can use FOR UPDATE SKIP LOCKED to batch-claim unpublished records. If Kafka send succeeds but published_at write-back crashes, the event is sent again; this is exactly why consumer idempotency remains necessary.
WITH picked AS (
SELECT event_id
FROM outbox_event
WHERE published_at IS NULL
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 100
)
SELECT e.* FROM outbox_event e JOIN picked p USING (event_id);After publish success, update published_at by event_id. Do not conflate "publish acknowledged" with "exactly-once delivery"; Kafka transactions improve Kafka-internal read-write consistency but do not cover PostgreSQL, payment gateway, or coupon systems.
7. Worker Loop: Claim, Renew, Execute, Confirm, Commit
Leases solve "who temporarily has execution rights"; fencing solves "can an old executor write back". Do not use Redis SET NX EX as the sole source of truth: it cannot natively guarantee consistency of task state, business version, and result commit.
7.1 Claim and Reclaim
res, err := db.ExecContext(ctx,
`UPDATE agent_task
SET status = 'CLAIMED', lease_owner = $2,
lease_until = now() + interval '30 seconds',
attempt_no = attempt_no + 1, version = version + 1,
updated_at = now()
WHERE task_id = $1
AND deadline_at > now()
AND (
status = 'READY'
OR (status IN ('CLAIMED', 'RUNNING') AND lease_until < now())
)`, taskID, workerID)
if err != nil { return err }
n, err := res.RowsAffected()
if err != nil { return err }
if n != 1 { return ErrNotClaimable }After successful claim, the worker conditionally updates CLAIMED to RUNNING, recording this attempt_no and version. Lease renewal must also carry these two values; otherwise a stale worker could accidentally extend a new worker's lease.
7.2 Main Execution Loop
func (w *Worker) Execute(ctx context.Context, task Task) error {
run, err := w.store.StartAndRead(ctx, task.ID, w.id, task.AttemptNo, task.Version)
if err != nil { return err } // condition not met means lease lost
leaseCtx, stopRenew := w.startLeaseRenewal(ctx, run)
defer stopRenew()
spec := w.registry.MustGet(run.Operation)
proposal, err := w.agent.Propose(leaseCtx, run.InputRef, spec.InputSchema)
if err != nil { return w.store.FailOrRetry(ctx, run, err) }
call, err := w.gateway.ValidateAndPrepare(leaseCtx, run, proposal, spec)
if err != nil { return w.store.FailPolicy(ctx, run, err) }
result, err := w.invokeWithFactCheck(leaseCtx, run, call, spec)
if err == ErrOutcomeUnknown { return w.store.MarkUnknown(ctx, run) }
if err != nil { return w.store.FailOrRetry(ctx, run, err) }
return w.store.Complete(ctx, run, result)
}invokeWithFactCheckresponsibilities: create or read tool_operation(PENDING); call external service; on response timeout, query by business key; only after obtaining a definite fact submit CONFIRMED or FAILED. If the completion update affects not exactly one row, the worker has lost task ownership and must discard local results and re-read database facts.
UPDATE agent_task
SET status = 'SUCCEEDED', result_ref = $1,
lease_owner = NULL, lease_until = NULL,
version = version + 1, updated_at = now()
WHERE task_id = $2
AND status = 'RUNNING'
AND lease_owner = $3
AND attempt_no = $4
AND version = $5
AND lease_until > now();Database fencing cannot retract requests already sent to external systems; therefore external side effects must still rely on business keys, query interfaces, and reconciliation processes.
8. DAG Convergence: Let Dependencies Decide Order, Not Message Arrival Time
Parallel tasks form a DAG. At task creation, write to task_dependency; the scheduler advances a task from WAITING to READY only when all dependencies have succeeded, result versions are acceptable, and workflow remains RUNNING.
UPDATE agent_task t
SET status = 'READY', version = version + 1, updated_at = now()
WHERE t.task_id = $1
AND t.status = 'WAITING'
AND EXISTS (
SELECT 1 FROM workflow w
WHERE w.workflow_id = t.workflow_id AND w.status = 'RUNNING'
)
AND NOT EXISTS (
SELECT 1 FROM task_dependency d
JOIN agent_task prerequisite ON prerequisite.task_id = d.depends_on_task_id
WHERE d.task_id = t.task_id AND prerequisite.status <> 'SUCCEEDED'
);Kafka messages for the same business aggregate should preferably partition by workflow_id or order_id to preserve intra-partition order; cross-partition dependencies still rely on the above state validation. Ordinary DAGs need not introduce vector clocks: explicit dependency edges, fact versions, and conditional updates are usually sufficient. Only when the system truly needs to judge causality between arbitrary concurrent events should vector clocks be considered; HLC approximate physical-time ordering cannot replace causal judgment.
To control model-driven graph growth, the scheduler should limit max_steps, max_depth, single-delegation quotas, and duplicate creation of same operation + input_version. Semantic similarity suits alerting or manual-escalation signals, not automatic loop termination with uncalibrated fixed thresholds.
9. Tool Contracts and Zero-Trust Boundary
Tickets, knowledge-base documents, and tool responses may carry prompt injections. Agents must not hold general permissions to core business services; all tool calls must pass through a Gateway, and downstream services must re-validate critical constraints.
A tool registry must declare at least these contracts:
name: refund.create
side_effect: idempotent_write
input_schema: RefundCreateV1
business_key: refund:{tenant_id}:{order_id}:{after_sale_id}
query_operation: refund.get_by_business_key
compensation: null
approval:
required_when: amount > 500
limits:
max_amount: 5000
max_attempts: 2
timeout:
request: 5s
reconciliation: 24hGateway validates on every call:
Caller identity, tenant, token audience, and expiry.
Tool name, resource ID, allowed fields, and amount/quantity limits.
Whether workflow still permits forward operations.
Whether approval covers current immutable parameter snapshot.
Whether business key matches task, tenant, and tool contract.
Capability tokens should be short-lived, audience-specific, and parameter-constrained. Subtask permissions can only narrow, never expand downstream. Macaroon or Biscuit can implement authorization attenuation but must use mature implementations and full validation chains; custom "parent token + caveat text + HMAC" concatenation is not a secure authorization protocol.
10. External Side Effects: Before Retry, Ask "Can We Confirm the Fact?"
Read-only : Required capabilities: timeout, rate-limit, retry. Safe action after timeout: re-query.
Idempotent write : Required capabilities: stable business key, result query, state verification. Safe action after timeout: query by key, then decide retry.
Compensable write : Required capabilities: above capabilities, compensation operation, compensation deadline. Safe action after timeout: verify, then execute independent compensation.
Irreversible write : Required capabilities: approval or manual confirmation, audit trail. Safe action after timeout: mark for manual handling, no auto-retry.
Compensation is not database rollback. Flight cancellation may incur fees, coupons may have been used, settled refunds may not be reversible. Therefore:
Register compensation records only for actually successful and compensable steps.
Compensation steps have their own business keys, leases, retry budgets, and audit states.
Parallel branches compensate in reverse topological order of the dependency graph; independent branches can compensate in parallel.
Compensation failures must not delete records; after budget exhaustion, preserve facts and transition to NEEDS_REVIEW.
For irreversible writes, the system should convert "higher confidence" into approvals, quota limits, and manual confirmations — not pretend automatic rollback is possible.
11. Operational Design: Separate Handoff and Execution, Scale Independently
Kafka consumer threads must not perform long-running model inference. max.poll.interval.ms constrains the interval between two poll calls; inference blocking the consumer loop may trigger consumer group rebalance.
Kafka Ingest Consumer ──persist task──→ PostgreSQL Task Queue ──claim──→ Execution Worker
│ │ │
Scale by Kafka lag Replayable, auditable Scale by task backlogIngress consumers commit offset after task persistence; Execution Workers then run models and tool calls. KEDA's Kafka scaler suits scaling ingress consumers by lag; but once messages land quickly in the DB, Kafka lag may be low while the bottleneck shifts to the task table. Therefore execution workers should scale based on pending task count, oldest task wait time, lease renewal failure rate, and available concurrency.
11.1 Observability and Alerting
Oldest READY task age : Meaning: queue or capacity shortage. Recommended action: scale out, check dependencies and DB.
Lease expiry re-claim count : Meaning: worker crashes or execution time misestimated. Recommended action: check timeouts, renewals, downstream latency.
UNKNOWN operation count : Meaning: external facts unconfirmable. Recommended action: trigger reconciliation and manual queue.
Same business key hit count : Meaning: replay or upstream duplication. Recommended action: verify correct merging.
Compensation backlog age : Meaning: business risk exposure time. Recommended action: raise compensation priority, manual intervention.
Token/task, P50/P95/P99 : Meaning: cost and experience. Recommended action: adjust model, concurrency, deadlines.
Logs record business key, state version, trace ID, and error classification; must not log root tokens, full sensitive conversations, or unnecessary PII. On pod shutdown, stop claiming new tasks first; claimed tasks complete within graceful termination window or wait for lease expiry to hand over. terminationGracePeriodSeconds is a buffer, not a reliability guarantee.
12. Five Mandatory Chaos Tests
Reliability cannot rely on code review alone. The following tests should run in pre-production and assert the invariants from Section 2:
Publish acknowledgment lost : Operation: kill Publisher after Kafka accepts event. Expected result: allow event duplicate; consumer creates only one logical task.
Crash after consumer persists : Operation: kill Consumer before offset commit. Expected result: Kafka replays; task and payload consistent, no loss.
Worker loses contact while holding lease : Operation: kill RUNNING Worker. Expected result: after lease expiry, exactly one new worker takes over; old worker cannot commit.
External success, response timeout : Operation: gateway drops success response. Expected result: task transitions to UNKNOWN, queries by business key, confirms success, no duplicate refund.
Late callback during compensation : Operation: inject success callback after entering COMPENSATING. Expected result: forward task cannot reopen; callback only updates acceptable facts or escalates to manual.
Also cover cross-partition reordering, approval parameter tampering, capability token expiry, dependency failure, database primary-secondary failover, and third-party query unavailability. Every drill must record final task, workflow, tool operation, and audit event states — not just observe HTTP 200.
13. Progressive Migration from Existing Agent Services
No need to rewrite existing synchronous agent apps from scratch. Evolve by risk from high to low:
Phase 1: Protect Write Operations First
Establish stable business keys for refunds, coupon grants, order changes.
Introduce tenant, resource, quota, approval, and timeliness validation in Tool Gateway.
Route high-risk writes lacking query capability to manual approval.
Phase 2: Introduce Persistent Tasks and Outbox
Replace in-memory queues with task table, adding state, version, lease, attempt_no.
Add outbox in existing DB transaction; consumers persist then commit offset.
Start with single worker consuming, verify state recovery and idempotency.
Phase 3: Separate Handoff and Execution
Kafka Consumer only validates and persists handoff.
Execution Workers use DB leases for long tasks.
Manage user-request deadlines and background workflow deadlines separately.
Phase 4: Enable Dynamic Parallelism Last
First implement explicit dependencies, result versions, and WAITING → READY advancement.
Configure step, depth, and budget limits for delegation graphs.
After passing chaos tests, gradually increase parallelism and automation scope.
A minimal production loop does not require a complex multi-agent network: one Supervisor, one task table, one Outbox Publisher, one Worker, one Tool Gateway, and query/reconciliation capabilities for high-risk tools are enough to first contain the most dangerous side effects.
14. How to Evaluate Whether Multi-Agent Is Worth It
When comparing single-agent vs multi-agent, fix model version, toolset, test set, context budget, and fault injection rules. At minimum report: task accuracy, manual intervention rate, end-to-end P50/P95/P99, token cost, external side-effect consistency, retry count, and task age distribution. Also report sample size and confidence intervals. Without measurement, do not claim multi-agent is necessarily faster, cheaper in tokens, or achieves "zero privilege escalation success rate". Complexity itself is cost; when subtasks are tightly coupled, tool calls are few, or task scale is small, a single agent plus deterministic workflow is often the better choice.
Conclusion
The core of production-grade multi-agent is not making agents talk more, but ensuring every delegation has state, every external write has a queryable business identity, every authorization is validated at the execution boundary, and every uncertainty has a defined destination.
Models may choose paths; process ownership, permissions, and business facts must be adjudicated by an auditable deterministic system.
References
CloudEvents Specification
Apache Kafka Consumer API
Apache Kafka Delivery Semantics
KEDA Apache Kafka scaler
For questions about attribution, corrections or content rights, please contactand we will review it promptly.