System Design Part 6: Event-Driven Architecture
The message that broke our monolith arrived at 3:47 AM on a Sunday.
We were running a mid-sized e-commerce platform—50,000 orders per day, growing 20% monthly. Our order processing was synchronous: when a customer clicked "Place Order," we called inventory, payment, shipping, and notification services sequentially. Total latency: 2-4 seconds.
That Sunday, our shipping partner's API started timing out. Not failing—timing out after 30 seconds. Every order was stuck waiting for shipping confirmation. The queue backed up. Database connections exhausted. The entire checkout flow went down.
We lost 8 hours of orders because one downstream service was slow.
That incident made us rebuild everything around events. Three years later, that same shipping outage? Users don't even notice. Orders complete instantly, shipping catches up when it recovers, and we've scaled 10x without architectural changes.
This guide explains how we got there.
The Problem with Synchronous Communication
Let's trace what happens when a customer places an order in a synchronous system:
Customer clicks "Place Order" → Order Service receives request → Calls Inventory Service (150ms) → Calls Payment Service (800ms) → Calls Shipping Service (200ms) → Calls Notification Service (100ms) → Returns success to customer (1,250ms total)

Synchronous Problem
What's wrong with this?
-
User waits for everything. The customer stares at a spinner for 1.25 seconds minimum.
-
Slowest service sets the pace. Payment taking 2 seconds? Everyone waits 2 seconds.
-
Any failure fails everything. Notification service down? Order fails. Even though notifications aren't critical.
-
Scaling is coupled. Need 10x Order Service capacity? You also need 10x Inventory, Payment, and Shipping capacity.
-
Adding services is risky. Want to add fraud detection? That's another synchronous call, more latency, more failure modes.
The Event-Driven Alternative
In an event-driven system:
Customer clicks "Place Order" → Order Service validates and saves order (50ms) → Publishes "OrderCreated" event → Returns success to customer Inventory Service consumes "OrderCreated" → Reserves items → Publishes "InventoryReserved" Payment Service consumes "InventoryReserved" → Charges customer → Publishes "PaymentCompleted" Shipping Service consumes "PaymentCompleted" → Schedules shipment → Publishes "ShipmentScheduled" Notification Service consumes various events → Sends appropriate emails/SMS

Event-Driven Solution
The customer gets a response in 50ms. Everything else happens asynchronously.
Failures are isolated. Notification service down? Orders still process. Notifications send when it recovers.
Scaling is independent. Need more payment processing? Scale Payment Service alone.
Real Incident: The Duplicate Order Disaster
Two months into our event-driven migration, we discovered a critical bug. A customer placed one order but received three copies of everything. And was charged three times.
The root cause: our Payment Service crashed after processing but before committing its offset. When it restarted, it reprocessed the same "InventoryReserved" event. Three times.
This is the fundamental challenge of event-driven systems: exactly-once processing is impossible without careful design.
The Solution: Idempotent Consumers
Every consumer must be idempotent—processing the same event multiple times produces the same result.
gotype PaymentProcessor struct { db *sql.DB kafka *kafka.Consumer paymentGw PaymentGateway } func (p *PaymentProcessor) ProcessEvent(ctx context.Context, event OrderEvent) error { // Start transaction tx, err := p.db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() // Check if we've already processed this event var exists bool err = tx.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM processed_events WHERE event_id = $1)", event.ID, ).Scan(&exists) if err != nil { return err } if exists { // Already processed, skip log.Info("Skipping duplicate event", "event_id", event.ID) return nil } // Process the payment paymentResult, err := p.paymentGw.Charge(ctx, event.Data.Amount, event.Data.PaymentMethod) if err != nil { return err } // Save payment record _, err = tx.ExecContext(ctx, `INSERT INTO payments (order_id, amount, transaction_id, status) VALUES ($1, $2, $3, $4)`, event.Data.OrderID, event.Data.Amount, paymentResult.TransactionID, "completed", ) if err != nil { return err } // Mark event as processed _, err = tx.ExecContext(ctx, "INSERT INTO processed_events (event_id, processed_at) VALUES ($1, NOW())", event.ID, ) if err != nil { return err } // Commit everything together return tx.Commit() }
Key insight: The event ID check and business logic must be in the same transaction. Otherwise, you can still get duplicates if crash happens between them.
Kafka: The Event Backbone
We chose Kafka after evaluating RabbitMQ, Redis Streams, and AWS SQS. Here's why:
| Feature | RabbitMQ | Kafka | Redis Streams | SQS |
|---|---|---|---|---|
| Throughput | 50K/s | 1M+/s | 500K/s | 3K/s |
| Ordering | Per-queue | Per-partition | Per-stream | None |
| Retention | Until consumed | Configurable days | Limited | 14 days |
| Replay | No | Yes | Limited | No |
| Consumer groups | Complex | Native | Native | Manual |
Kafka's killer feature: replay. When we find a bug in a consumer, we fix the code and replay events from the beginning. No data loss.
Architecture Overview

Kafka Architecture
Topics: Logical categories of events (e.g.,
orders, payments, shipments)Partitions: Physical divisions within a topic for parallelism
Consumer Groups: Independent consumers that share the workload
Partitioning Strategy
This is where most teams get it wrong. Consider:
go// Wrong: Random partition assignment producer.Send(topic, randomPartition(), orderEvent) // Events for same order can go to different partitions // Processed out of order! // Right: Partition by order ID producer.Send(topic, partition(orderEvent.OrderID), orderEvent) // All events for same order go to same partition // Guaranteed ordering!

Partitioning Strategy
Partition key choice matters:
- Order ID: All events for one order in sequence
- Customer ID: All events for one customer in sequence (good for account-level operations)
- None (round-robin): Maximum throughput, no ordering guarantees
Consumer Groups

Consumer Groups
Each partition is consumed by exactly one consumer in a group. This means:
- Consumers = Partitions: Perfect parallelism
- Consumers < Partitions: Some consumers handle multiple partitions
- Consumers > Partitions: Extra consumers are idle (waste of resources)
gofunc (c *OrderConsumer) Start(ctx context.Context) error { consumer, err := kafka.NewConsumer(kafka.ConsumerConfig{ Brokers: []string{"kafka-1:9092", "kafka-2:9092", "kafka-3:9092"}, GroupID: "order-processor", Topics: []string{"orders"}, AutoOffsetReset: "earliest", // Start from beginning if no offset }) if err != nil { return err } for { select { case <-ctx.Done(): return consumer.Close() default: msg, err := consumer.FetchMessage(ctx) if err != nil { continue } if err := c.processMessage(ctx, msg); err != nil { // Don't commit, message will be redelivered log.Error("Processing failed", "error", err) continue } consumer.CommitMessages(ctx, msg) } } }
Event Envelope: The Metadata That Saves You
Raw event data isn't enough. Every event needs context.

Event Envelope
gotype EventEnvelope struct { // Identity ID string `json:"id"` // Unique event identifier (UUID) Type string `json:"type"` // Event type (e.g., "order.created") // Tracing Source string `json:"source"` // Service that produced this CorrelationID string `json:"correlation_id"` // Links related events CausationID string `json:"causation_id"` // Event that caused this one // Timing Time time.Time `json:"time"` // When event occurred ReceivedAt time.Time `json:"received_at"` // When broker received it // Schema SchemaVersion string `json:"schema_version"` // For evolution // Payload Data json.RawMessage `json:"data"` }
Why each field matters:
- ID: Enables idempotency checks
- CorrelationID: Trace a user request across 15 services at 3 AM
- CausationID: Build event chains for debugging
- SchemaVersion: Handle different event formats during migrations
- Source: Know who to blame when something breaks
Using Correlation ID for Debugging
When a customer reports "my order is stuck," you can trace the entire flow:
sql-- Find all events for this order SELECT * FROM event_logs WHERE correlation_id = 'req-abc123' ORDER BY time;
time | source | type | status --------------------+-----------------+----------------------+--------- 2024-01-15 10:23:01 | order-service | order.created | success 2024-01-15 10:23:02 | inventory-svc | inventory.reserved | success 2024-01-15 10:23:03 | payment-service | payment.initiated | success 2024-01-15 10:23:08 | payment-service | payment.failed | error 2024-01-15 10:23:09 | inventory-svc | inventory.released | success
Now you know: payment failed after 5 seconds, inventory was correctly released.
Event Sourcing: When History Is the Feature
Traditional systems store current state. Event sourcing stores how you got there.

Traditional vs Event Sourcing
Traditional approach:
sqlUPDATE accounts SET balance = 750.00 WHERE id = 'ACC-001'; -- Previous balance? Unknown. Why changed? Unknown.
Event sourcing approach:
json{"type": "AccountOpened", "balance": 1000.00} {"type": "WithdrawalMade", "amount": 200.00} {"type": "DepositMade", "amount": 50.00} {"type": "WithdrawalMade", "amount": 100.00} // Current balance: 1000 - 200 + 50 - 100 = 750 // Complete history preserved
When Event Sourcing Makes Sense

Event Sourcing Decision
Use event sourcing when:
- Audit trail is legally required (financial systems)
- You need to answer "why did this happen?"
- You want to replay history with new logic
- Domain experts think in events ("when order is placed...", "when payment fails...")
Avoid event sourcing when:
- CRUD is sufficient (user profiles, settings)
- You don't need history
- Team isn't familiar with the pattern (complexity cost)
Implementing Event Sourcing
go// Domain events type AccountEvent interface { Apply(*Account) } type AccountOpened struct { AccountID string InitialBalance decimal.Decimal OpenedAt time.Time } func (e AccountOpened) Apply(a *Account) { a.ID = e.AccountID a.Balance = e.InitialBalance a.Status = "active" } type WithdrawalMade struct { Amount decimal.Decimal Description string OccurredAt time.Time } func (e WithdrawalMade) Apply(a *Account) { a.Balance = a.Balance.Sub(e.Amount) } // Aggregate reconstruction func (r *AccountRepository) Load(ctx context.Context, id string) (*Account, error) { events, err := r.eventStore.LoadEvents(ctx, id) if err != nil { return nil, err } account := &Account{} for _, event := range events { event.Apply(account) } return account, nil }

Event Sourcing Flow
The Snapshot Optimization
Loading 10,000 events to rebuild an account is slow. Snapshots solve this:
gofunc (r *AccountRepository) LoadWithSnapshot(ctx context.Context, id string) (*Account, error) { // Try loading latest snapshot snapshot, snapshotVersion, err := r.snapshotStore.Load(ctx, id) if err != nil && err != ErrNotFound { return nil, err } var account *Account var fromVersion int if snapshot != nil { account = snapshot fromVersion = snapshotVersion } else { account = &Account{} fromVersion = 0 } // Load only events after snapshot events, err := r.eventStore.LoadEventsFrom(ctx, id, fromVersion) if err != nil { return nil, err } for _, event := range events { event.Apply(account) } // Create new snapshot if many events since last if len(events) > 100 { r.snapshotStore.Save(ctx, id, account, fromVersion+len(events)) } return account, nil }

Snapshots
Snapshot strategy: Create snapshot every N events (we use 100). Balance between storage cost and load time.
CQRS: Separate Read and Write Models
The insight that changed how we built systems: reads and writes have different requirements.
Writes need:
- Strong consistency
- Simple, normalized data
- Transaction support
Reads need:
- Low latency
- Denormalized, pre-joined data
- Scalability
Trying to optimize one model for both is a losing battle.

Traditional Model
CQRS Architecture

CQRS Pattern
go// Command side: Validates and writes type OrderCommandHandler struct { eventStore EventStore } func (h *OrderCommandHandler) PlaceOrder(ctx context.Context, cmd PlaceOrderCommand) error { // Validate if err := cmd.Validate(); err != nil { return err } // Create event event := OrderPlaced{ OrderID: uuid.New().String(), CustomerID: cmd.CustomerID, Items: cmd.Items, Total: cmd.CalculateTotal(), PlacedAt: time.Now(), } // Store event (single source of truth) return h.eventStore.Append(ctx, event) } // Query side: Optimized for reading type OrderQueryHandler struct { readDB *sql.DB // Denormalized read database } func (h *OrderQueryHandler) GetOrderSummary(ctx context.Context, orderID string) (*OrderSummary, error) { // Pre-computed, denormalized data var summary OrderSummary err := h.readDB.QueryRowContext(ctx, ` SELECT order_id, customer_name, item_count, total, shipping_status, estimated_delivery FROM order_summaries WHERE order_id = $1 `, orderID).Scan( &summary.OrderID, &summary.CustomerName, &summary.ItemCount, &summary.Total, &summary.ShippingStatus, &summary.EstimatedDelivery, ) return &summary, err }
Building Read Models with Projections
Projections consume events and update read models:
gotype OrderProjection struct { readDB *sql.DB } func (p *OrderProjection) HandleEvent(ctx context.Context, event Event) error { switch e := event.(type) { case OrderPlaced: return p.handleOrderPlaced(ctx, e) case PaymentCompleted: return p.handlePaymentCompleted(ctx, e) case ShipmentScheduled: return p.handleShipmentScheduled(ctx, e) } return nil } func (p *OrderProjection) handleOrderPlaced(ctx context.Context, e OrderPlaced) error { _, err := p.readDB.ExecContext(ctx, ` INSERT INTO order_summaries (order_id, customer_id, item_count, total, status) VALUES ($1, $2, $3, $4, 'pending') ON CONFLICT (order_id) DO UPDATE SET item_count = $3, total = $4, status = 'pending' `, e.OrderID, e.CustomerID, len(e.Items), e.Total) return err }

Projections
Multiple Read Models
Different use cases need different views of the same data:

Multiple Projections
- Customer Dashboard: Order history with status
- Admin Panel: All orders with customer details
- Analytics: Aggregated metrics per region/product
- Search: Elasticsearch index for full-text search
Each projection maintains its own read model, optimized for its use case.
Saga Pattern: Distributed Transactions Done Right
The hardest problem in microservices: what happens when step 3 of 5 fails?

Distributed Transaction Problem
Traditional databases use two-phase commit (2PC). It doesn't work well across services:
- Locks held during coordination
- Single coordinator failure blocks everything
- Performance degrades significantly
Saga pattern: A sequence of local transactions with compensating actions for rollback.
Choreography vs Orchestration
Choreography: Services react to events, no central coordinator.

Choreography Saga
go// Each service reacts independently // Order Service func (s *OrderService) HandlePaymentFailed(event PaymentFailed) { s.orderRepo.UpdateStatus(event.OrderID, "cancelled") s.eventBus.Publish(OrderCancelled{OrderID: event.OrderID}) } // Inventory Service func (s *InventoryService) HandleOrderCancelled(event OrderCancelled) { s.inventoryRepo.ReleaseReservation(event.OrderID) s.eventBus.Publish(InventoryReleased{OrderID: event.OrderID}) }
Pros: Decoupled, simple services
Cons: Hard to track overall progress, distributed logic
Orchestration: Central coordinator manages the saga.

Orchestration Saga
gotype OrderSaga struct { state SagaState orderID string steps []SagaStep currentStep int } type SagaStep struct { Execute func(ctx context.Context) error Compensate func(ctx context.Context) error } func NewOrderSaga(orderID string, services *Services) *OrderSaga { return &OrderSaga{ orderID: orderID, steps: []SagaStep{ { Execute: func(ctx context.Context) error { return services.Inventory.Reserve(ctx, orderID) }, Compensate: func(ctx context.Context) error { return services.Inventory.Release(ctx, orderID) }, }, { Execute: func(ctx context.Context) error { return services.Payment.Charge(ctx, orderID) }, Compensate: func(ctx context.Context) error { return services.Payment.Refund(ctx, orderID) }, }, { Execute: func(ctx context.Context) error { return services.Shipping.Schedule(ctx, orderID) }, Compensate: func(ctx context.Context) error { return services.Shipping.Cancel(ctx, orderID) }, }, }, } } func (s *OrderSaga) Execute(ctx context.Context) error { for i, step := range s.steps { s.currentStep = i if err := step.Execute(ctx); err != nil { return s.Compensate(ctx) } } return nil } func (s *OrderSaga) Compensate(ctx context.Context) error { // Run compensations in reverse order for i := s.currentStep - 1; i >= 0; i-- { if err := s.steps[i].Compensate(ctx); err != nil { // Log and continue—must try all compensations log.Error("Compensation failed", "step", i, "error", err) } } return ErrSagaRolledBack }
Pros: Centralized logic, easy to track
Cons: Orchestrator is a critical component
Persisting Saga State
What if the orchestrator crashes mid-saga? Persist state:
gofunc (s *OrderSaga) ExecuteWithPersistence(ctx context.Context) error { // Load or create saga state state, err := s.stateStore.Load(ctx, s.orderID) if err != nil && err != ErrNotFound { return err } if state != nil { s.currentStep = state.CurrentStep } for i := s.currentStep; i < len(s.steps); i++ { // Update state before executing s.currentStep = i s.stateStore.Save(ctx, s.orderID, &SagaState{ CurrentStep: i, Status: "executing", }) if err := s.steps[i].Execute(ctx); err != nil { s.stateStore.Save(ctx, s.orderID, &SagaState{ CurrentStep: i, Status: "compensating", }) return s.Compensate(ctx) } } s.stateStore.Save(ctx, s.orderID, &SagaState{ CurrentStep: len(s.steps), Status: "completed", }) return nil }

Saga State Machine
On restart, the orchestrator loads incomplete sagas and resumes from where they left off.
Security: Protecting Event-Driven Systems
Event-driven architectures have unique security challenges.
Event Tampering
Malicious actors could modify events in transit. Defense: sign events.
gotype SignedEvent struct { Event EventEnvelope `json:"event"` Signature string `json:"signature"` } func (p *Producer) SignAndPublish(ctx context.Context, event EventEnvelope) error { // Serialize event eventBytes, _ := json.Marshal(event) // Sign with HMAC mac := hmac.New(sha256.New, p.signingKey) mac.Write(eventBytes) signature := base64.StdEncoding.EncodeToString(mac.Sum(nil)) signed := SignedEvent{ Event: event, Signature: signature, } return p.kafka.Publish(ctx, signed) } func (c *Consumer) VerifyAndProcess(ctx context.Context, signed SignedEvent) error { // Verify signature eventBytes, _ := json.Marshal(signed.Event) mac := hmac.New(sha256.New, c.signingKey) mac.Write(eventBytes) expectedSig := base64.StdEncoding.EncodeToString(mac.Sum(nil)) if !hmac.Equal([]byte(signed.Signature), []byte(expectedSig)) { return ErrInvalidSignature } return c.processEvent(ctx, signed.Event) }
Event Replay Attacks
An attacker captures and replays old events. Defense: timestamps and idempotency.
gofunc (c *Consumer) ProcessWithReplayProtection(ctx context.Context, event EventEnvelope) error { // Reject events older than 5 minutes if time.Since(event.Time) > 5*time.Minute { return ErrEventTooOld } // Idempotency check prevents processing same event twice if c.processed.Contains(event.ID) { return nil } // Process event if err := c.processEvent(ctx, event); err != nil { return err } c.processed.Add(event.ID) return nil }
Sensitive Data in Events
Events are persistent. Sensitive data in events is a liability.
go// Bad: PII in events type UserRegistered struct { UserID string Email string // PII! Password string // Never do this! SSN string // Absolutely not! } // Good: References only type UserRegistered struct { UserID string // Sensitive data stored in secure database // Event just references the user } // If event data must be sensitive, encrypt it type EncryptedEvent struct { ID string `json:"id"` Type string `json:"type"` EncryptedData string `json:"encrypted_data"` // AES-GCM encrypted KeyID string `json:"key_id"` // For key rotation }
Access Control on Topics
Not every service should read every event:
yaml# Kafka ACLs acl: - principal: "service:payment-processor" resource: "topic:payments" operation: "read,write" - principal: "service:order-service" resource: "topic:orders" operation: "write" - principal: "service:analytics" resource: "topic:*" operation: "read" # Read-only for analytics
Monitoring Event-Driven Systems
Distributed systems need distributed observability.
Key Metrics

Event Metrics
Producer metrics:
- Events published per second
- Publish latency (p50, p99)
- Failed publishes
Consumer metrics:
- Events consumed per second
- Processing latency
- Consumer lag (critical!)
- Processing errors
Consumer Lag: The Most Important Metric

Consumer Lag
Lag = Latest offset - Consumer offset
If lag grows, consumers are falling behind. Eventually:
- Data becomes stale
- Processing delays cascade
- Recovery takes hours
go// Expose lag metric func (c *Consumer) ReportMetrics() { ticker := time.NewTicker(10 * time.Second) for range ticker.C { for _, partition := range c.assignedPartitions { latest, _ := c.kafka.GetLatestOffset(partition) current, _ := c.kafka.GetConsumerOffset(partition) lag := latest - current metrics.Gauge("consumer_lag", float64(lag), "partition", partition, "consumer_group", c.groupID, ) if lag > 10000 { alerting.Send("High consumer lag", map[string]any{ "partition": partition, "lag": lag, }) } } } }
Distributed Tracing
Correlate events across services:
gofunc (c *Consumer) ProcessWithTracing(ctx context.Context, event EventEnvelope) error { // Extract trace context from event ctx = tracing.Extract(ctx, event.Headers) span, ctx := tracing.StartSpan(ctx, "process_event", tracing.Tag("event_type", event.Type), tracing.Tag("event_id", event.ID), tracing.Tag("correlation_id", event.CorrelationID), ) defer span.End() err := c.processEvent(ctx, event) if err != nil { span.SetError(err) } return err }
Interview Cheat Sheet
Event-Driven Fundamentals
-
"When would you use events vs synchronous calls?"
- Events: Decoupling needed, failure isolation, async processing acceptable
- Synchronous: Immediate response required, strong consistency needed
-
"How do you ensure exactly-once processing?"
- You can't—it's impossible in distributed systems
- Instead: Idempotent consumers + at-least-once delivery
- Store event ID with transaction, check before processing
Kafka Questions
-
"How does Kafka guarantee ordering?"
- Ordering guaranteed within a partition only
- Use partition key to route related events to same partition
- Cross-partition ordering requires sequence numbers
-
"What happens when a consumer crashes?"
- Uncommitted messages redelivered to another consumer in group
- Must handle duplicates (idempotency)
- Consumer lag increases until rebalanced
Architecture Patterns
-
"Event sourcing vs traditional CRUD?"
- Event sourcing: Audit trail, replay, temporal queries
- CRUD: Simpler, when history isn't needed
- Hybrid: Events for write model, projections for read
-
"CQRS: When and why?"
- When read/write patterns differ significantly
- Read-heavy systems with complex queries
- Trade-off: Eventual consistency, more infrastructure
Red Flags to Avoid
- Synchronous calls inside event handlers (defeats the purpose)
- No idempotency in consumers
- Missing correlation IDs (impossible to debug)
- No consumer lag monitoring
- Sensitive data in events without encryption
Key Takeaways

Event-Driven Architecture Mindmap
-
Events decouple services in time and space. Publisher doesn't wait, doesn't know consumers.
-
Exactly-once is a lie. Design for at-least-once with idempotent consumers.
-
Correlation IDs are non-negotiable. You will debug production issues at 3 AM.
-
Consumer lag is your primary health metric. Growing lag means growing problems.
-
Sagas handle distributed transactions. Every action needs a compensation action.
The shipping outage that took down our monolith? In our event-driven architecture, it's just a growing queue that drains when the service recovers. Users never notice. That's the power of events.
Series Complete
Congratulations! You've completed the System Design Mastery series:
- Part 1: Banking & High-Scale Systems — UPI architecture, idempotency, reconciliation
- Part 2: Distributed Systems — Rate limiting, fraud detection, saga patterns
- Part 3: Go Concurrency — Worker pools, goroutine leaks, deadlock debugging
- Part 4: Database & Storage — Partitioning, replication lag, indexing strategies
- Part 5: Caching — Multi-level caching, invalidation, security
- Part 6: Event-Driven Architecture — Kafka, CQRS, event sourcing, sagas
You now have the knowledge to design systems that scale to millions of users. The patterns here have been battle-tested in production, learned through incidents, and refined through years of iteration.
Go build something that handles the next million users.
The Sunday outage that killed our synchronous checkout taught us more about system design than any whiteboard interview. I hope these patterns help you learn without the 3 AM pages.