The 5-stage agent communication pipeline
Building production-ready autonomous email infrastructure requires moving beyond synchronous API calls in HTTP request handlers. A resilient architecture separates the agent reasoning loop from the physical email dispatch loop across five distinct stages:
| Pipeline Stage | Primary Component | Responsibility & SLA | Failure Recovery Policy |
|---|---|---|---|
| 1. Context Extraction | LLM Reasoning Node | Parse user prompts & extract clean recipient parameters | Validation retry with structured Zod errors |
| 2. Policy & Scoping | Security Gateway | Enforce recipient domain allowlists & hourly velocity | HTTP 403 / 429 blocked before DB commit |
| 3. Transactional Outbox | PostgreSQL / Prisma | Commit message payload atomically with application state | ACID rollback prevents lost or phantom emails |
| 4. Asynchronous Dispatch | Bun outbox worker | Pull outbox jobs, manage backoff & dispatch to SadaSend | Exponential backoff with Dead Letter Queue (DLQ) |
| 5. Delivery Telemetry | Webhook Ingestion | Process bounces, spam complaints & clicks back into context | Auto-suppresses invalid recipients permanently |
The Transactional Outbox Pattern for Agents
If an agent crashes midway through execution or encounters a network partition after updating a database, a direct API call can result in either lost emails or double-sends. The Outbox Pattern guarantees at-least-once delivery with zero data loss:
// In your agent workflow transaction:
await db.transaction(async (tx) => {
// 1. Update application state atomically
await tx.tickets.update({ where: { id: ticketId }, data: { status: 'RESOLVED' } });
// 2. Commit outbound email to outbox table in the same atomic transaction
await tx.outbox.create({
data: {
idempotencyKey: `ticket_${ticketId}_resolve`,
sender: 'support@company.com',
recipient: customerEmail,
subject: 'Your ticket has been resolved',
payload: emailMarkdown,
status: 'PENDING',
},
});
});Idempotency and Agent Retry Handling
Agents frequently retry tool calls when they experience inference timeouts or gateway disconnects. Every outbound email must carry a deterministic idempotency key. SadaSend deduplicates requests within a 24-hour window, returning the original message ID if the same idempotency key is submitted multiple times.
Asynchronous Outbox Worker Implementation in Bun
Use a decoupled queue worker to poll the transactional outbox table and dispatch emails to SadaSend with concurrency limits:
// A plain Bun loop over the outbox table: no queue broker to run.
const BATCH = 25;
async function drainOutbox(): Promise<void> {
// SKIP LOCKED lets several workers drain the same table without double-sending.
const rows = await db.$queryRaw<OutboxRow[]>`
SELECT * FROM outbox
WHERE status = 'PENDING' AND next_attempt_at <= now()
ORDER BY created_at
LIMIT ${BATCH}
FOR UPDATE SKIP LOCKED`;
for (const row of rows) {
const res = await fetch('https://api.sadasend.com/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SADASEND_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': row.idempotencyKey, // a retry after a crash cannot double-send
},
body: JSON.stringify({ from: row.sender, to: row.recipient, subject: row.subject, text: row.payload }),
});
if (res.ok) {
await db.outbox.update({ where: { id: row.id }, data: { status: 'SENT' } });
} else if (res.status >= 500 || res.status === 429) {
// Transient: back off exponentially, then give up into a dead-letter state.
const attempts = row.attempts + 1;
await db.outbox.update({
where: { id: row.id },
data: attempts >= 5
? { status: 'DEAD', attempts }
: { attempts, nextAttemptAt: new Date(Date.now() + 2 ** attempts * 1_000) },
});
} else {
// 4xx is a refusal (allowlist, suppression, validation): retrying cannot help.
await db.outbox.update({ where: { id: row.id }, data: { status: 'REFUSED' } });
}
}
}
setInterval(drainOutbox, 1_000);Reconciling Delivery Feedback into Agent Context
When an email bounces or receives a spam complaint, that signal should immediately feed back into your agent’s state machine so it does not continue attempting follow-ups. Set up a webhook endpoint to listen for SadaSend email.bounced and email.complained events and mark the customer contact record suppressed.
Building AI agents that send email?
Scoped API keys, per-key recipient allowlists, approval mode and a hosted MCP server with twelve tools — 6,000 free sends monthly, without a credit card.
Building SadaSend — transactional email with an MCP server that has a ceiling. Writes about deliverability, email infrastructure, and what happens when you hand an autonomous agent a sending credential.