Skip to content
Designing Resilient Asynchronous Systems: From Synchronous APIs to Event-Driven Architecture at Scale · Rohan Kumar
BackDesigning Resilient Asynchronous Systems: From Synchronous APIs to Event-Driven Architecture at Scale By Rohan Kumar · Published February 7th, 2026
published ⏱ 8 min read
Slug: designing-resilient-asynchronous-systems
#architecture #scalability #resilience
Explore strategies and patterns for evolving synchronous APIs into scalable, resilient event-driven architectures. Learn how to design systems that handle failures gracefully and scale efficiently
Related Articles Continue exploring similar topics and insights
Learn how senior frontend engineers evolve feature-complete UIs into production-grade systems. Discover the critical upgrades in reliability, observability, performance, and security that separate hobby projects from scalable products.
reliability observability performance security architecture
Read More → An exploration of why resilience patterns exist in distributed systems, the failure modes they address, and the trade-offs behind health checks, timeouts, retries, and beyond.
distributed systems resilience reliability fault tolerance health checks +1
Read More → A deep dive into mastering Next.js, from core fundamentals to advanced architectural strategies, system design, and interview-level preparation for senior developers.
nextjs react architecture system-design interview-prep +5
Read More → Async Email Notifications with Queue + Worker + Retry/DLQ (Industry-Grade Deep Dive)
Most systems don’t fail because business logic is wrong. They fail because side effects are tightly coupled to user requests.
📧 A classic example is email notifications in booking/contact flows.
😬 The naive synchronous flow
When email sending is on the request path:
👤 User submits request
🗄️ API writes to DB
📨 API calls email provider
⏳ API waits for provider response
✅ User gets response
It works in early stage. It breaks under real traffic, provider instability, and retry storms.
⚠️ Why synchronous side effects fail at scale
When email sending is on the request path:
⏱️ API latency depends on third-party performance
🔌 Provider outages become API outages
🔁 Retries increase request time and duplicate risk
📈 Spikes amplify queueing and timeout cascades
🚫 A non-critical action (notification) can break a critical action (booking)
This is not just a performance issue.
It is a reliability architecture issue .
✅ Senior-level framing
The goal isn’t “make email faster.”
The goal is “make booking succeed even when email is unhealthy.”
🔄 The architecture shift
Move from request-coupled side effects to event-driven side effects.
The API does the critical work and publishes an event
A worker does the non-critical work asynchronously
🖼️ Diagram (async boundary + worker + retry/DLQ)
System Architecture Diagram
💡 Key idea
✅ Critical path: validate + persist + acknowledge user
💤 Non-critical path: notifications, analytics, webhooks, fan-out consumers
This keeps user-facing APIs reliable even when side effects degrade.
🧱 Concrete system design (practical stack)
A clean production pattern:
🌐 API service (Fly.io): producer
📥 Cloudflare Queue: durable async buffer
⚙️ Worker consumer: email orchestration
✉️ Resend: delivery provider
☠️ DLQ: poison message isolation
🧪 Feature mode: sync / dual / queue for safe migration
This gives decoupling now and extensibility later.
✅ Contracts first: shared types and constants
At scale, schema drift is one of the biggest causes of silent breakage.
📌 The fix: shared packages for event contracts + constants.
🧾 What to centralize
🏷️ Event names (SLOT_BOOKED, SLOT_UPDATED, SLOT_DELETED)
🎛️ Delivery mode values (sync, dual, queue)
📦 Payload schema
🧬 Source metadata (source, timestamp, correlationId, eventId)
🔢 schemaVersion for safe evolution
This creates a single source of truth across API and workers.
🧪 Example: shared contract types
// shared/contracts.ts
export type SlotEventType = 'SLOT_BOOKED' | 'SLOT_UPDATED' | 'SLOT_DELETED' ;
export interface SlotQueuePayload {
slotId : string ;
name : string ;
email : string ;
date : string ;
duration : number ;
🧬 Schema evolution rules (how you avoid production breakage)
Producers and consumers deploy independently. That means your worker will eventually process events created by older or newer API versions.
Keep your system evolvable by following simple rules:
➕ Additive changes only (add new optional fields)
🚫 Never rename or remove fields without a migration plan
🧠 Consumers must ignore unknown fields
🧾 Validate required fields ; malformed payloads go to DLQ
🔢 Bump schemaVersion only when necessary , and keep compatibility logic explicit
🛡️ Reliability semantics you must understand
1) 📬 At-least-once delivery
Queues are typically at-least-once.
Your consumer can process the same message more than once.
Implication: consumer operations must be idempotent.
2) 🔁 Idempotency (the only way at-least-once is safe)
Idempotency must exist at three layers:
🧾 API layer: protect booking mutations from client retries or double-clicks
📨 Event layer: dedupe using eventId
✉️ Provider layer: pass Idempotency-Key: eventId to avoid double-sends
If you skip any layer, duplicates will eventually happen during retries and timeouts.
3) ⏳ Retry is a feature, not a bug
Transient failures are normal (provider timeouts, temporary network errors).
Retries handle transient failures automatically.
✅ Good retries use:
bounded retry count
exponential backoff (with jitter)
per-attempt timeouts
❌ Bad retries:
infinite retries
no backoff
retrying poison messages forever
4) ☠️ DLQ is mandatory
Not all failures are transient.
Malformed payloads or invalid business state should land in a DLQ for manual or automated recovery.
Without a DLQ you usually get one of two bad outcomes:
🔥 infinite retry storms, or
🕳️ silent drops with data loss
5) 🧠 Reality check: ordering and eventual consistency
In distributed systems, assume:
messages may arrive late
messages may be duplicated
messages may be reordered
side effects are eventually consistent (email might arrive later)
Design UX and ops expectations accordingly.
🚦 Migration strategy that avoids incidents
Do not jump directly from sync to async-only.
✅ Phase 1: dual mode
API publishes queue event
API still sends sync email
Compare counts and behavior
Validate worker logs and delivery rates
✅ Phase 2: queue mode
Disable sync path
Keep rollback toggle available
Monitor queue health and email delivery SLOs
🎯 Why this matters
This is progressive delivery for architecture changes, not just code changes.
🧪 Feature-mode switch (sync / dual / queue)
const mode = process.env.EMAIL_DELIVERY_MODE ?? 'sync';
if (mode === 'dual' || mode === 'queue') {
await publishSlotEvent('SLOT_BOOKED', payload);
}
if (mode === 'dual' || mode === 'sync') {
await sendLegacySyncEmail(payload); // temporary during migration
}
📨 Producer implementation (publish safely without breaking user flow)
✅ Producer rules
Never block the booking response waiting on the queue
Add a short timeout (don’t hang)
Log failures with eventId / correlationId
Check non-2xx responses
import { nanoid } from 'nanoid';
import type { QueueEvent, SlotEventType, SlotQueuePayload } from './shared/contracts';
export async function publishSlotEvent(
eventType: SlotEventType,
data: SlotQueuePayload
): Promise<void> {
const event: QueueEvent<SlotEventType, SlotQueuePayload> = {
eventId: nanoid(),
correlationId: data.slotId,
schemaVersion: 1,
type: eventType,
source: 'api',
timestamp: new Date().toISOString(),
data,
};
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 1500);
try {
✅ The critical path still succeeds even if publishing fails.
If losing events is unacceptable, you graduate to the outbox pattern (covered below).
⚙️ Consumer implementation: idempotent processing + retries + DLQ
✅ Consumer rules
Parse and validate payload schema
Dedupe by eventId (idempotency store)
Send email with provider idempotency header
Ack on success
Retry on transient failures
Route poison messages to DLQ
🧠 Idempotency store concept
Store a marker like processed:{eventId} = true with TTL.
You can implement it using:
🧊 Cloudflare KV
🧠 Upstash Redis
🗃️ Durable Objects
🧾 DB table with TTL
🧾 Pseudocode: “exactly once effect” over at-least-once delivery
// 1) if processed(eventId) => ack + return
// 2) send email with Idempotency-Key = eventId
// 3) mark processed(eventId) with TTL
// 4) ack
##🧪 Example worker consumer
type Env = {
DEDUPE_KV: KVNamespace;
RESEND_API_KEY: string;
};
☠️ DLQ operations (what happens after messages land there)
DLQ is not just “a place failures go.” It’s a workflow.
✅ DLQ must answer these questions
🧾 How do we inspect messages?
🧠 How do we classify transient vs poison?
🔄 How do we replay safely?
🚫 How do we avoid duplicates on replay?
🗂️ Recommended DLQ handling model
Poison messages (schema mismatch, invalid business state):
fix producer/consumer contract
write a small transformer if needed
replay only after safe validation
Transient failures (provider outage, timeouts):
wait until provider is healthy
replay batch with concurrency limit
✅ Safe replay requires
idempotency store (eventId dedupe)
provider idempotency key (prevents double-email)
🚦 Backpressure + rate limiting (how you avoid melting providers)
Queues absorb spikes, but your provider still has limits.
✅ Protect the system
🚥 cap worker concurrency
🧯 backoff on 429 / 5xx
🧱 split high-priority vs bulk notifications into separate queues
💤 defer non-critical notification types when backlog grows
🧠 Staff-level truth:
“Queue depth rising” is not the incident.
“Oldest message age rising” is the incident.
🔍 Observability model (staff-level baseline)
You need both API and async pipeline visibility.
📊 Track at minimum
Producer / API
✅ publish success rate
⏳ publish latency (p95)
🚫 publish failure rate by reason (auth, 4xx, 5xx, timeout)
Queue
📥 queue depth
🕰️ oldest message age
Consumer
✅ success/failure rate
🔁 retry count
☠️ DLQ inflow
⏱️ end-to-end delay (event created → email sent)
🧵 Correlation IDs
Use correlationId across:
API logs
worker logs
provider request logs (if available)
So one user action is traceable end to end.
🧯 Failure modes and runbooks
Scenario: 🚫 queue publish failures
Symptoms
API logs show auth or publish errors
Runbook
Verify token scope and account binding
Verify queue URL, account, and queue IDs
Verify secret rollout on environment
Alert if publish failures exceed threshold
Scenario: 🔥 consumer failures rising
Symptoms
Runbook
Inspect worker errors
Classify transient vs poison messages
Fix parser/schema mismatch or provider issue
Replay valid DLQ messages after fix
Scenario: 📈 backlog growth
Symptoms
queue depth grows, message age increases
Runbook
Increase worker throughput
Validate provider rate limits
Defer non-critical notification types
Protect critical user journeys first
📈 Scale design patterns beyond v1
1) 📦 Outbox pattern (stronger guarantees)
If DB write succeeds but queue publish fails, events can be lost.
The outbox pattern solves this:
🧾 write domain data + outbox event in the same transaction
🔄 background publisher drains outbox to queue
✅ mark delivered
This is the next maturity level for mission-critical workflows.
2) 🧠 Idempotency store
Use eventId + KV/Redis to dedupe consumer processing with TTL.
3) 🧱 Multi-queue strategy
Split by domain or priority:
notifications-high
notifications-bulk
analytics-events
webhook-events
This isolates blast radius.
4) 🌟 Multi-consumer fan-out
One event can trigger:
✉️ email consumer
📊 analytics consumer
🤝 CRM/webhook consumer
No API code changes required beyond publish.
🔐 Security and governance
At scale, secret hygiene and permission scoping are non-negotiable.
Use:
🔑 least-privilege API tokens
🧪 per-environment tokens (stage/prod separation)
🗝️ secret managers (not local files)
♻️ token rotation process
🧼 redaction in logs
🙈 PII minimization in payloads
💰 Cost and operational efficiency
Async queue + worker architectures are usually cost-efficient for low and mid traffic:
💸 pay by operations, not always-on side-effect workers
🧠 reduce wasted API compute waiting on third parties
🏎️ avoid over-provisioning app servers for spikes
This architecture improves both resilience and cost profile.
🤝 When synchronous side effects are OK (useful nuance)
Not every side effect needs a queue.
Sync is acceptable when the side effect is:
✅ local (no third-party hop)
✅ fast and strictly time-bounded
✅ best-effort (failure does not break user flow)
✅ non-critical and tolerable if dropped
But if it calls an external provider and blocks the response, it will eventually become a reliability problem.
🧠 What this demonstrates from a staff engineer perspective
This is not just “added queue for email.” It demonstrates system-level engineering:
🔌 decoupling for fault isolation
🧪 controlled migration with rollback
📜 clear contracts and ownership boundaries
🧰 operational maturity (metrics, DLQ, runbooks)
🧩 scale-ready extension model for new consumers
The outcome is a system that degrades gracefully under failure and evolves without rewriting core request flows.
🧭 Final takeaway
The biggest shift is mindset:
🚀 Don’t optimize only for success-path speed
🧯 Optimize for failure containment and recoverability
Async event-driven design lets your user-facing API stay reliable while side effects execute independently, safely, and observably.
That is the difference between a project that works and a system that survives growth.
status
:
'booked'
|
'cancelled'
;
message ?: string ;
}
export interface QueueEvent < TType extends string , TData > {
id : string ;
correlationId : string ;
type : TType ;
source : 'api' ;
timestamp : string ;
data : TData ;
}
const res = await fetch(process.env.CLOUDFLARE_QUEUE_URL!, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.CLOUDFLARE_QUEUE_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
body: JSON.stringify(event),
content_type: 'text',
}),
signal: controller.signal,
});
if (!res.ok) {
const body = await res.text().catch(() => '');
console.error('Queue publish failed', {
status: res.status,
body,
eventId: event.eventId,
correlationId: event.correlationId,
});
}
} catch (err) {
console.error('Queue publish error', {
err,
eventId: event.eventId,
correlationId: event.correlationId,
});
} finally {
clearTimeout(timeout);
}
}
async function wasProcessed(env: Env, eventId: string): Promise<boolean> {
const key = `processed:${eventId}`;
return (await env.DEDUPE_KV.get(key)) === '1';
}
async function markProcessed(env: Env, eventId: string): Promise<void> {
const key = `processed:${eventId}`;
// TTL example: 7 days (tune based on your retry window + business tolerance)
await env.DEDUPE_KV.put(key, '1', { expirationTtl: 60 * 60 * 24 * 7 });
}
async function sendEmailViaResend(env: Env, to: string, subject: string, html: string, eventId: string) {
const res = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${env.RESEND_API_KEY}`,
'Content-Type': 'application/json',
// ✅ provider-level idempotency
'Idempotency-Key': eventId,
},
body: JSON.stringify({
to,
subject,
html,
}),
});
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`Resend failed: ${res.status} ${body}`);
}
}
export default {
async queue(batch: MessageBatch, env: Env): Promise<void> {
for (const message of batch.messages) {
try {
const raw = String(message.body);
const event = JSON.parse(raw) as {
eventId: string;
correlationId: string;
schemaVersion: number;
type: 'SLOT_BOOKED' | 'SLOT_UPDATED' | 'SLOT_DELETED';
data: { email: string; name: string; slotId: string };
};
// ✅ Minimal validation (expand as needed)
if (!event?.eventId || !event?.type || !event?.data?.email) {
throw new Error('Invalid event payload (missing required fields)');
}
// ✅ Dedupe: already processed => ack and stop
if (await wasProcessed(env, event.eventId)) {
message.ack();
continue;
}
// Do the side effect
const subject = `Slot event: ${event.type}`;
const html = `<p>Hi ${event.data.name}, your slot event is ${event.type}.</p>`;
await sendEmailViaResend(env, event.data.email, subject, html, event.eventId);
// ✅ Mark done before ack (so re-delivery is safe)
await markProcessed(env, event.eventId);
message.ack();
} catch (error) {
console.error('Consumer failed', error);
// 🔁 transient failures should retry, poison will end in DLQ per queue policy
message.retry();
}
}
},
};