Event-driven architecture is drawn on whiteboards constantly and shipped correctly rarely. Ordering, exactly-once, schema evolution, sagas, dead letters, replay — each hides trade-offs that lock in future flexibility. This guide is the discipline that keeps event-driven systems maintainable: when to use it, platform selection framework, schema design, ordering guarantees, delivery semantics, saga patterns, outbox pattern, DLQ design, replay strategy, migration approach, metrics that matter. Practical over aspirational.
What event-driven discipline is (and isn't)
Event-driven discipline is the set of practices that make event-driven systems maintainable past year 1. Without discipline, EDA systems accumulate technical debt distinctive to their pattern: schema drift, poison pill accumulation, ordering assumption violations, unbounded fan-out, dependency coupling via events. With discipline: schemas evolve safely, consumers stay idempotent, failure modes handled explicitly, replay works when needed.
Framed differently: EDA is a tool; discipline is how you use it. Same tool, different outcomes. Some workflows should stay request-response (discipline cost exceeds EDA benefit); some should adopt EDA (decoupling and resilience justify discipline).
Not just about “using message queues.” Discipline includes: schema registry, idempotency patterns, saga design, DLQ monitoring, replay tooling, observability, testing strategy, migration approach. Sum of many practices.
When to use event-driven (and when not)
Decision framework, not religion.
EDA helps when:
- Multiple consumers care about the same event (fan-out).
- Loose coupling matters (consumers evolve independently).
- Latency spike isolation (downstream slow doesn't slow upstream).
- Retry + eventual consistency acceptable.
- Audit + replay valuable (event log as source of history).
- Cross-team boundaries (each team owns their consumer).
EDA hurts when:
- Simple request-response works (extra complexity buys nothing).
- Consumer must respond synchronously to caller (fundamentally sync).
- Strong consistency required in narrow window (transactions simpler).
- Low volume (bus overhead exceeds benefit).
- Team lacks async debugging skills.
Common mistake: going all-in on EDA. Most real systems are mixed: some flows request-response, some event-driven. Match pattern to workflow characteristics.
Platform selection framework
Different platforms have different fits:
Apache Kafka: High throughput (100k-1M+ msgs/sec per broker), persistent log, ordering per partition, replay via retention. Best for: high volume, event sourcing, teams with Kafka ops capacity. Not ideal: low volume (ops overhead), simple pub/sub without replay needs.
AWS EventBridge: Serverless, integrates with 100+ AWS services, per-event billing, low ops. Best for: AWS-native, moderate volume, teams wanting managed. Not ideal: high volume (cost curve steep), replay-heavy (no built-in retention).
RabbitMQ: Mature, flexible routing (topic, direct, fanout), moderate throughput (10k-50k msgs/sec). Best for: complex routing, retries, dead letters. Not ideal: extreme throughput needs, event sourcing (not designed for it).
NATS / NATS JetStream: Lightweight, very fast, simple ops, at-least-once via JetStream. Best for: middle-ground volume, teams wanting lightweight. Not ideal: complex routing needs, deep vendor ecosystem integration.
SNS + SQS: AWS pub/sub with queue durability, per-consumer queues, dead letters. Best for: AWS-native pub/sub, simple architectures. Not ideal: high throughput, complex routing.
Redis Streams: If Redis already in stack, consumer groups, familiar. Not ideal for: durability-critical use cases (Redis persistence tricky), high throughput sustained loads.
Selection heuristic:
- Team on AWS, moderate volume: EventBridge or SNS+SQS.
- High volume + Kafka experience: Kafka.
- Complex routing needs: RabbitMQ.
- Lightweight, high-performance: NATS.
- Already have Redis, simple needs: Redis Streams (carefully).
Event schema design
Events are contracts. Design them like APIs.
Format: Avro (compact, schema evolution built-in), Protobuf (compact, cross-language), or JSON (human-readable, explicit versioning needed). Avro or Protobuf with schema registry recommended at 3+ producers.
Structure:
{
"event_id": "uuid", // unique per event
"event_type": "OrderCreated", // typed
"event_version": "1.2", // explicit version
"occurred_at": "2027-01-15T10:23:45Z",
"correlation_id": "uuid", // trace root
"causation_id": "uuid", // what caused this event
"actor": { "type": "user", "id": "..." },
"data": { /* domain payload */ }
}
Additive changes always safe: new optional field, new event type. Consumers ignore unknown; behavior unchanged.
Breaking changes: field removal, required field addition, type change. Consumers may break. Never do silently.
Schema evolution discipline:
- Schema registry enforces compatibility rules (Avro backward-compatible by default).
- New event types require review + registration.
- Breaking changes require: new major version, coexistence with old version, migration plan, consumer sign-off.
- Deprecation cycle: announce, coexist, remove.
Ordering guarantees
Ordering is expensive. Match guarantee to actual need.
Global ordering: single partition; slow at scale. Rarely needed. Consider: do consumers actually need to see events in exact global order? Usually no.
Per-key ordering: Kafka partitioned by key (customer_id, entity_id). Events for same key ordered; parallel across keys. Common pattern; matches most business needs.
No ordering: parallel processing, no guarantees. Fastest; consumers must be order-independent. Fine for many aggregations, notifications.
Common mistake: assuming global ordering when only per-key needed. Kills throughput unnecessarily.
Delivery semantics + idempotency
Three theoretical modes; two practical:
At-most-once: fire and forget. May lose events. Only for truly disposable data (metrics, some analytics).
At-least-once: retry until acknowledged. May duplicate. Standard for most systems.
Exactly-once: Kafka transactions can achieve; complex and expensive. Alternative and usually preferred: at-least-once + idempotent consumers.
Idempotency pattern:
- Every event has unique event_id.
- Consumer maintains dedup store (Redis, DynamoDB, DB table).
- On event: check if event_id already processed; if so, skip; if not, process and record.
- TTL on dedup store (24h-7d typical); assumes events reasonably in-order.
At-least-once delivery + idempotent consumer = exactly-once effect at much lower cost than true exactly-once.
Saga patterns (orchestration vs. choreography)
Distributed transactions replaced by sagas: sequence of local transactions + compensating actions if any step fails.
Orchestration: central coordinator (Temporal, Cadence, Camunda) tracks state; invokes each step; triggers compensations on failure.
Pros: single source of truth for saga state, easier to reason about, workflow visibility, versioning support.
Cons: coupling to workflow engine, coordinator can become bottleneck, orchestrator failure = saga stuck.
Choreography: each service listens for events and reacts; no central coordinator; state distributed.
Pros: pure event-driven, no coordinator dependency, services fully decoupled.
Cons: saga state distributed across services, harder to reason about, compensating logic scattered.
Recommendation: orchestration (Temporal) for anything with more than 3 steps or compensating logic. Choreography for simple 2-3 step flows where compensations obvious.
Outbox pattern (transactional consistency)
Problem: DB commit succeeds but event publish fails. Or vice versa. State inconsistent.
Solution: outbox table in same DB. Application writes state change + outbox event row in single DB transaction. Separate publisher process reads outbox, publishes to bus, marks published.
Guarantees:
- State change and event emission atomic (both or neither).
- At-least-once delivery (publisher retries on failure).
- Event ordering matches DB commit order.
Trade-offs: extra table; extra process; small latency for publish. Standard pattern for consistency-critical event-driven systems.
Alternative: Change Data Capture (CDC) via Debezium reads DB transaction log; publishes changes as events. Same guarantees; less application code.
Dead-letter queue design + monitoring
Events that fail processing after retries go to DLQ. Handling DLQ is essential discipline.
Design principles:
- Every consumer has DLQ.
- Retry policy explicit (e.g., 3 retries, exponential backoff).
- Failed event captured with error context (stack trace, timestamp, retry count).
- DLQ has retention (30-90 days typical) for investigation.
Monitoring:
- Alert on DLQ depth (e.g., >100 events).
- Alert on DLQ growth rate (sudden influx = new issue).
- Regular DLQ review (weekly minimum).
Response:
- Investigate cause (bad data, downstream outage, code bug).
- Fix cause.
- Replay DLQ events (manually or via replay tool).
- Post-mortem for recurring patterns.
Common failure: DLQ becomes graveyard nobody looks at. Alert + weekly review + response SLA prevents.
Replay strategies
Ability to reprocess historical events. Enables: consumer bug fixes reprocess affected events, new consumers backfill from history, disaster recovery.
Kafka native replay: events retained per config (7-30 days typical). Consumer can reset offset to earlier point; reprocesses from there.
Event store pattern: events persisted separately (DB, S3) beyond bus retention. Enables long-tail replay months or years later.
Selective replay: replay events matching criteria (specific customer, specific time range). Requires tooling; not automatic.
Idempotency essential for replay: reprocessing events shouldn't cause duplicate side effects. Dedup patterns apply.
Common pitfall: replay assumed to work; never tested. First real replay reveals broken assumptions. Test replay quarterly.
Correlation + causation IDs
Distributed system observability requires trace context. Two IDs:
Correlation ID: shared across all events + logs + traces in a single logical operation. Enables “show me everything about this checkout.”
Causation ID: ID of the event that caused this one. Enables reconstruction of event chain (event A caused event B caused event C).
Both in every event header. Every log line correlated. Trace context (W3C standard) propagates across services. Investigation via OpenTelemetry MCP becomes tractable.
Without correlation IDs, investigation is per-service log grepping. With them, one query surfaces the whole event chain.
Failure patterns to prevent
Common failures in mature event-driven systems:
Schema drift. Producer evolves independently; consumer breaks. Prevent with schema registry + compatibility rules.
Chatty events. Too fine-grained (“UserFieldChanged” per field). Aggregate to domain events (“UserProfileUpdated”).
Missing idempotency. At-least-once + non-idempotent = duplicates. Every consumer idempotent.
Coupling via events. Consumer needs specific producer field; producer can't remove. Consumer-driven contracts help.
Silent DLQ accumulation. Failed events pile up unnoticed. Monitor + alert + weekly review.
No replay tested. Assumed to work; broken in practice. Test quarterly.
Missing correlation. Investigations impossible. Correlation IDs from day 1.
Ordering assumptions. Consumer assumes order; events actually parallel. Explicit ordering guarantees documented.
Testing event-driven code
Different testing pyramid than synchronous:
Unit tests: consumer logic; mock event input. Fast; most coverage. Test idempotency, error handling, output events.
Integration tests: real message bus in test environment (testcontainers Kafka, LocalStack for AWS). Test producer + consumer end-to-end. Slower; catch integration issues.
Contract tests: consumer-driven contracts (Pact) prevent producer/consumer drift. Consumer publishes expected schema; producer verifies compatibility.
E2E tests: full flow across services. Rare; expensive. Only critical business flows.
Chaos tests: simulate consumer failures, bus outages, poison pills. Verify DLQ, retry, recovery work as designed.
Migration from request-response
Rewriting synchronous system as event-driven is a project.
Phased approach:
- Emit events alongside synchronous calls (dual-write).
- Add consumers processing events in parallel with existing logic.
- Verify parity (events + sync producing same outcomes).
- Cut over consumer-by-consumer (feature flag).
- Deprecate synchronous paths.
Duration: often 3-9 months for meaningful workflow. Not weeks.
Not everything migrates: some workflows should stay synchronous. Match pattern to characteristic.
Metrics that matter
Track these:
Event throughput: events/sec per topic. Capacity planning signal.
Consumer lag: how far behind head each consumer is. Sudden increase = consumer slow or stopped.
DLQ depth: events that failed. Should stay near zero.
Processing latency: time from event emitted to processed. SLO signal.
Retry rate: what percentage of events retried. High rate = downstream instability.
Idempotency hit rate: events skipped due to duplicate detection. Should be low but non-zero (proves idempotency working).
Schema violations: should be zero with registry.
What to do next
If you're synchronous and hitting coupling / latency / cascade issues: consider event-driven for those specific flows. Not everything; the ones that benefit.
If you're event-driven but debt accumulating (schema drift, DLQ backlog, no replay): pick one issue and invest a quarter fixing.
If you're event-driven and mature: audit against failure patterns list. Nothing left to prevent = healthy system.
If you're planning event-driven migration: read the 6-month migration blog before starting. Concrete lessons.
Combined with event-driven-architect subagent for decisions and opentelemetry MCP for observability, event-driven becomes maintainable instead of pattern-of-technical-debt.