Event-Driven Design
Purpose
Tightly coupled systems break and scale poorly. Event-driven architectures decouple producers from consumers by using immutable, timestamped facts as the communication mechanism. This enables systems to evolve independently, scale horizontally, and handle distributed failures gracefully.
When to use
- De-coupling monolithic microservices
- Implementing long-running asynchronous workflows (e.g., video processing, email sending)
- Triggering multiple side-effects across different domains from a single action
- Designing systems that need to replay history or audit changes
When NOT to use
- Simple synchronous request-response flows (don't add unnecessary complexity)
- Real-time bidirectional communication (use WebSockets instead)
- Workflows requiring immediate response to action
Inputs required
- Microservices or monolithic application with clear domain boundaries
- Message broker infrastructure (Kafka, RabbitMQ, EventBridge, etc.)
- Understanding of event sourcing concepts
Workflow
- Define Events: Identify state changes in the domain and model them as past-tense events (e.g.,
OrderPlaced, UserRegistered, PaymentProcessed)
- Design Event Payloads: Include Event ID, Timestamp, Event Type, and minimal required data (avoid large nested objects)
- Publishing Mechanism: Have the producer system emit the event to a Message Broker without caring who consumes it
- Idempotent Consumers: Ensure consumer services can process the same event multiple times without adverse side effects
- Handle Failures: Implement Dead Letter Queues (DLQ) for events that consumers repeatedly fail to process
- Track Processing: Add idempotency keys or processed event IDs to detect duplicates
- Monitor: Set up alerts for DLQ messages and processing delays
Rules
- MUST model events as immutable facts (past tense:
OrderPlaced not PlaceOrder)
- MUST NEVER modify or delete events once emitted (audit trail requirement)
- MUST make consumers idempotent (same event processed multiple times = same outcome)
- MUST avoid deeply nested, rapidly changing entity graphs in payloads
- MUST include Event ID, Timestamp, Event Type in all events
- MUST implement Dead Letter Queues for failed events
- MUST NOT use synchronous HTTP calls as part of event workflows
Anti-patterns
- Commands as Events: Naming events like actions (
SendEmailEvent) rather than facts (UserCreated)
- Distributed Monolith: Systems requiring synchronous HTTP calls in response to an event before completing their workflow
- Huge Event Payloads: Sending entire entity graphs; include only IDs and essential context
- No Idempotency: Processing events without tracking duplicate processing
- Synchronous Dependencies: Event handler blocks waiting for another service response
- Event Loss: Not persisting events to broker; memory-only event storage
Failure conditions
- Events cannot be replayed (no persistence)
- Consumers not idempotent (duplicates cause data corruption)
- No Dead Letter Queue for failed events
- Synchronous dependencies between event producers and consumers
- Event payloads change format without versioning support
Validation checklist
Output format
- Event schema: Event ID, Timestamp, Type, Payload (minimal data)
- Payload format: JSON with primitive types, IDs, not full objects
- Consumer pattern: Read event, validate idempotency key, process, mark as processed
- Infrastructure: Message broker setup with persistence and DLQ
- Monitoring: Dashboards for event processing latency and DLQ depth
Security considerations
- Event payloads MUST NOT contain credentials or PII
- Access control MUST be enforced at consumer (not all services can listen to all events)
- Event encryption MUST be used for sensitive domains
- Audit logging MUST track who published and consumed events
- Dead Letter Queues MUST be monitored (may contain sensitive data)
Agent execution notes
- Agent MAY: Define events, create event handlers, implement idempotency, set up DLQ
- Agent MUST NEVER: Use commands instead of events, create synchronous dependencies, lose events
- Agent MUST ASK: Before adding new event types, before changing event schema, before removing DLQ
- Agent MUST VALIDATE: Events are facts not commands, consumers are idempotent, DLQ configured
Example
❌ Anti-pattern (Commands as events, synchronous coupling, no idempotency):
// WRONG: Command not event
publishEvent('SendEmail', { userId, subject });
// WRONG: Synchronous dependency
async function handleOrderPlaced(event) {
const order = await orderService.fetch(event.orderId); // Blocks on external service
await emailService.send(order.email); // Fails if service is down
}
// WRONG: No idempotency tracking - processes duplicate
async function handleUserCreated(event) {
await database.createUser(event); // Processes same event twice = duplicate user
}
✅ Correct pattern (Events, async, idempotent):
// CORRECT: Past-tense event with minimal payload
publishEvent({
type: 'UserCreated',
id: uuid(),
timestamp: new Date(),
payload: {
userId: event.userId,
email: event.email
}
});
// CORRECT: Asynchronous, idempotent consumer
async function handleUserCreated(event) {
// 1. Track processed events (idempotency)
const alreadyProcessed = await cache.get(`processed:${event.id}`);
if (alreadyProcessed) return; // Skip duplicate
// 2. Process without waiting for external services
await emailQueue.enqueue({
email: event.payload.email,
template: 'welcome'
});
// 3. Mark as processed
await cache.set(`processed:${event.id}`, true, { ttl: 86400 });
}
// 4. Dead Letter Queue for failed events
async function handleFailedEvent(event, error) {
await dlq.store({
originalEvent: event,
error: error.message,
timestamp: new Date(),
retryCount: 0
});
}
1---2name: event-driven-design3description: When designing loosely coupled systems that react to state changes asynchronously.4license: MIT5---67# Event-Driven Design89## Purpose10Tightly coupled systems break and scale poorly. Event-driven architectures decouple producers from consumers by using immutable, timestamped facts as the communication mechanism. This enables systems to evolve independently, scale horizontally, and handle distributed failures gracefully.1112## When to use13- De-coupling monolithic microservices14- Implementing long-running asynchronous workflows (e.g., video processing, email sending)15- Triggering multiple side-effects across different domains from a single action16- Designing systems that need to replay history or audit changes1718## When NOT to use19- Simple synchronous request-response flows (don't add unnecessary complexity)20- Real-time bidirectional communication (use WebSockets instead)21- Workflows requiring immediate response to action2223## Inputs required24- Microservices or monolithic application with clear domain boundaries25- Message broker infrastructure (Kafka, RabbitMQ, EventBridge, etc.)26- Understanding of event sourcing concepts2728## Workflow291. **Define Events**: Identify state changes in the domain and model them as past-tense events (e.g., `OrderPlaced`, `UserRegistered`, `PaymentProcessed`)302. **Design Event Payloads**: Include Event ID, Timestamp, Event Type, and minimal required data (avoid large nested objects)313. **Publishing Mechanism**: Have the producer system emit the event to a Message Broker without caring who consumes it324. **Idempotent Consumers**: Ensure consumer services can process the same event multiple times without adverse side effects335. **Handle Failures**: Implement Dead Letter Queues (DLQ) for events that consumers repeatedly fail to process346. **Track Processing**: Add idempotency keys or processed event IDs to detect duplicates357. **Monitor**: Set up alerts for DLQ messages and processing delays3637## Rules38- MUST model events as immutable facts (past tense: `OrderPlaced` not `PlaceOrder`)39- MUST NEVER modify or delete events once emitted (audit trail requirement)40- MUST make consumers idempotent (same event processed multiple times = same outcome)41- MUST avoid deeply nested, rapidly changing entity graphs in payloads42- MUST include Event ID, Timestamp, Event Type in all events43- MUST implement Dead Letter Queues for failed events44- MUST NOT use synchronous HTTP calls as part of event workflows4546## Anti-patterns47- **Commands as Events**: Naming events like actions (`SendEmailEvent`) rather than facts (`UserCreated`)48- **Distributed Monolith**: Systems requiring synchronous HTTP calls *in response* to an event before completing their workflow49- **Huge Event Payloads**: Sending entire entity graphs; include only IDs and essential context50- **No Idempotency**: Processing events without tracking duplicate processing51- **Synchronous Dependencies**: Event handler blocks waiting for another service response52- **Event Loss**: Not persisting events to broker; memory-only event storage5354## Failure conditions55- Events cannot be replayed (no persistence)56- Consumers not idempotent (duplicates cause data corruption)57- No Dead Letter Queue for failed events58- Synchronous dependencies between event producers and consumers59- Event payloads change format without versioning support6061## Validation checklist62- [ ] All events named as past-tense facts (not commands)63- [ ] Events are immutable after emission64- [ ] Event payloads include ID, Timestamp, Type65- [ ] Consumers are idempotent (can process same event multiple times safely)66- [ ] Dead Letter Queue configured and monitored67- [ ] No synchronous HTTP dependencies in event handlers68- [ ] Event versioning strategy defined69- [ ] Idempotency keys tracked (to detect duplicates)70- [ ] Monitoring/alerting on DLQ messages71- [ ] Event processing latency within SLA7273## Output format74- **Event schema**: Event ID, Timestamp, Type, Payload (minimal data)75- **Payload format**: JSON with primitive types, IDs, not full objects76- **Consumer pattern**: Read event, validate idempotency key, process, mark as processed77- **Infrastructure**: Message broker setup with persistence and DLQ78- **Monitoring**: Dashboards for event processing latency and DLQ depth7980## Security considerations81- Event payloads MUST NOT contain credentials or PII82- Access control MUST be enforced at consumer (not all services can listen to all events)83- Event encryption MUST be used for sensitive domains84- Audit logging MUST track who published and consumed events85- Dead Letter Queues MUST be monitored (may contain sensitive data)8687## Agent execution notes88- Agent MAY: Define events, create event handlers, implement idempotency, set up DLQ89- Agent MUST NEVER: Use commands instead of events, create synchronous dependencies, lose events90- Agent MUST ASK: Before adding new event types, before changing event schema, before removing DLQ91- Agent MUST VALIDATE: Events are facts not commands, consumers are idempotent, DLQ configured9293## Example9495**❌ Anti-pattern (Commands as events, synchronous coupling, no idempotency):**96```javascript97// WRONG: Command not event98publishEvent('SendEmail', { userId, subject });99100// WRONG: Synchronous dependency101async function handleOrderPlaced(event) {102 const order = await orderService.fetch(event.orderId); // Blocks on external service103 await emailService.send(order.email); // Fails if service is down104}105106// WRONG: No idempotency tracking - processes duplicate107async function handleUserCreated(event) {108 await database.createUser(event); // Processes same event twice = duplicate user109}110```111112**✅ Correct pattern (Events, async, idempotent):**113```javascript114// CORRECT: Past-tense event with minimal payload115publishEvent({116 type: 'UserCreated',117 id: uuid(),118 timestamp: new Date(),119 payload: {120 userId: event.userId,121 email: event.email122 }123});124125// CORRECT: Asynchronous, idempotent consumer126async function handleUserCreated(event) {127 // 1. Track processed events (idempotency)128 const alreadyProcessed = await cache.get(`processed:${event.id}`);129 if (alreadyProcessed) return; // Skip duplicate130 131 // 2. Process without waiting for external services132 await emailQueue.enqueue({133 email: event.payload.email,134 template: 'welcome'135 });136 137 // 3. Mark as processed138 await cache.set(`processed:${event.id}`, true, { ttl: 86400 });139}140141// 4. Dead Letter Queue for failed events142async function handleFailedEvent(event, error) {143 await dlq.store({144 originalEvent: event,145 error: error.message,146 timestamp: new Date(),147 retryCount: 0148 });149}150```