The 5-stage agent communication pipeline
Building production-ready autonomous email infrastructure requires moving beyond synchronous API calls. A resilient architecture separates the agent reasoning loop from the physical email dispatch loop across five distinct stages:
1. Intent & Context Extraction: Parsing user prompts and extracting clean parameters.
2. Guardrail & Policy Evaluation: Verifying key scopes, recipient allowlists, and hourly rate limits.
3. Transactional Outbox Staging: Committing the message payload into a durable PostgreSQL table inside the same database transaction as your business state.
4. Asynchronous Queue Dispatch: Workers (powered by Bun and BullMQ) pulling jobs, checking token buckets, and delivering via SadaSend REST API.
5. Telemetry & Feedback Ingestion: Webhooks updating message delivery, bounce, and complaint statuses back into the agent knowledge store.
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 (e.g. ticket status)
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 Retries
Agents frequently retry tool calls when they experience timeouts. 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.
Reconciling Delivery Feedback into Agent Context
When an email bounces or is flagged as spam, 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.