9.1 Core Event Patterns
Pattern 1: Event Notification
OrderService ──[OrderCreated]──▶ NotificationService
Publisher doesn't care who consumes it — loose coupling, fire-and-forget.
Pattern 2: Event-Carried State Transfer
OrderService ──[OrderCreated{orderId, items, total, customer}]──▶ ShippingService
Event carries enough data that the consumer never needs to call back —
removes a synchronous dependency and a point of cascading failure.
Pattern 3: Event Sourcing
All state changes are stored as an immutable sequence of events.
Current state = replay(all events). Gives a complete audit trail and
the ability to build new read projections retroactively.
When to use event-driven architecture:
| ✅ Use When | ❌ Avoid When |
|---|---|
| Services need to be independently deployable | Simple CRUD needing an immediate response |
| Spiky workloads need load leveling | Strong/immediate consistency is required (some financial transactions) |
| Multiple consumers need the same fact | Team lacks async debugging skills/tooling |
| A workflow spans several services | Latency-sensitive synchronous operation |
| You need audit trails / event sourcing | Small app with 2–3 services (overhead not justified) |
9.2 Saga Pattern — Choreography vs Orchestration
The Saga pattern breaks a distributed transaction into a sequence of local transactions, each with a compensating action to undo it if a later step fails.
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Order │───▶│ Payment │───▶│Inventory │───▶│ Shipping │
│ Service │ │ Service │ │ Service │ │ Service │
└────┬─────┘ └────┬─────┘ └────┬─────┘ └──────────┘
│ │ │
│ On failure: run compensating actions in reverse
▼ ▼ ▼
Cancel Refund Restock
Order Payment Items
Choreography (event-based, no central coordinator)
Each service reacts to events published by others and decides what to do next, including firing its own compensation event.
# Choreography — each service is independently subscribed to relevant events
# order_service.py
def create_order(order):
db.save(order)
event_bus.publish("OrderCreated", {"order_id": order.id, "total": order.total,
"customer_id": order.customer_id})
# payment_service.py — reacts to OrderCreated
@event_bus.subscribe("OrderCreated")
def on_order_created(event):
result = charge_customer(event["customer_id"], event["total"])
if result.success:
event_bus.publish("PaymentProcessed", {"order_id": event["order_id"]})
else:
event_bus.publish("PaymentFailed", {"order_id": event["order_id"]})
# inventory_service.py — reacts to PaymentProcessed
@event_bus.subscribe("PaymentProcessed")
def on_payment_processed(event):
if reserve_stock(event["order_id"]):
event_bus.publish("InventoryReserved", {"order_id": event["order_id"]})
else:
event_bus.publish("InventoryReservationFailed", {"order_id": event["order_id"]})
# order_service.py — also reacts to failures, to compensate
@event_bus.subscribe("PaymentFailed")
def on_payment_failed(event):
cancel_order(event["order_id"])
@event_bus.subscribe("InventoryReservationFailed")
def on_inventory_failed(event):
event_bus.publish("RefundRequested", {"order_id": event["order_id"]})
cancel_order(event["order_id"])
Orchestration (a central coordinator drives the flow)
// Orchestration with MassTransit state machine (.NET)
public class OrderSaga : MassTransitStateMachine<OrderSagaState>
{
public OrderSaga()
{
InstanceState(x => x.CurrentState);
Event(() => OrderSubmitted, x => x.CorrelateById(m => m.Message.OrderId));
Event(() => PaymentProcessed, x => x.CorrelateById(m => m.Message.OrderId));
Event(() => PaymentFailed, x => x.CorrelateById(m => m.Message.OrderId));
Event(() => InventoryReserved, x => x.CorrelateById(m => m.Message.OrderId));
Event(() => InventoryFailed, x => x.CorrelateById(m => m.Message.OrderId));
Initially(
When(OrderSubmitted)
.Then(ctx => ctx.Saga.OrderId = ctx.Message.OrderId)
.Publish(ctx => new ProcessPayment(ctx.Message.OrderId, ctx.Message.Total))
.TransitionTo(AwaitingPayment));
During(AwaitingPayment,
When(PaymentProcessed)
.Publish(ctx => new ReserveInventory(ctx.Saga.OrderId))
.TransitionTo(AwaitingInventory),
When(PaymentFailed)
.Publish(ctx => new CancelOrder(ctx.Saga.OrderId))
.TransitionTo(Failed));
During(AwaitingInventory,
When(InventoryReserved)
.Publish(ctx => new ShipOrder(ctx.Saga.OrderId))
.TransitionTo(Completed),
When(InventoryFailed)
// Compensate the payment step
.Publish(ctx => new RefundPayment(ctx.Saga.OrderId))
.Publish(ctx => new CancelOrder(ctx.Saga.OrderId))
.TransitionTo(Failed));
}
}
# Orchestration in Python — an explicit coordinator with compensation steps
class OrderSagaOrchestrator:
def __init__(self, payment_client, inventory_client, order_repo):
self.payment_client = payment_client
self.inventory_client = inventory_client
self.order_repo = order_repo
def run(self, order):
completed_steps = []
try:
self.payment_client.charge(order.customer_id, order.total)
completed_steps.append("payment")
self.inventory_client.reserve(order.id, order.items)
completed_steps.append("inventory")
self.order_repo.mark_confirmed(order.id)
completed_steps.append("confirm")
except Exception as exc:
self._compensate(order, completed_steps)
raise
def _compensate(self, order, completed_steps):
# Undo in reverse order — mirror image of the forward steps
if "inventory" in completed_steps:
self.inventory_client.release(order.id)
if "payment" in completed_steps:
self.payment_client.refund(order.customer_id, order.total)
self.order_repo.mark_failed(order.id)
Choreography vs Orchestration — Comparison
| Choreography | Orchestration | |
|---|---|---|
| How it works | Services react to events independently | A central coordinator drives and tracks the flow |
| Coupling | Very loose — services only know event shapes | Coordinator knows the whole workflow |
| Visibility | Hard to see the full flow (spread across services) | Clear — the entire workflow lives in one place |
| Debugging | Harder — needs distributed tracing to reconstruct the flow | Easier — single point to inspect state/history |
| Scalability | Better — no single coordinator to bottleneck | Coordinator can become a bottleneck/SPOF (mitigate with HA) |
| Best for | Simple flows (2–3 steps), truly independent reactions | Complex flows (4+ steps) with many compensation paths |
Practical guidance: prefer orchestration for complex business workflows (5+ step order fulfillment with multiple compensation branches) because the explicit state machine is much easier to reason about and test. Prefer choreography for simple, low-fan-out notifications (send an email when an order is placed). Many production systems mix both — orchestration for the core transactional workflow, choreography for peripheral side effects (analytics, notifications) hanging off the saga’s events.
9.3 Outbox Pattern (solving the dual-write problem)
The dual-write problem: a service needs to update its database and publish a message, but there’s no way to make both operations succeed or fail together without a transaction that spans both systems. If the DB commit succeeds but the publish fails (or vice versa), the system is left inconsistent.
┌─────────────────────────────────────────┐
│ Order Service │
│ │
│ 1. BEGIN TRANSACTION │
│ 2. INSERT INTO Orders (...) │
│ 3. INSERT INTO OutboxMessages ( │
│ EventType, Payload, CreatedAt, │
│ ProcessedAt = NULL) │
│ 4. COMMIT TRANSACTION ← atomic │
│ │
│ Background Worker (poller or CDC): │
│ 5. SELECT * FROM OutboxMessages │
│ WHERE ProcessedAt IS NULL │
│ 6. Publish to Kafka/RabbitMQ/Service Bus │
│ 7. UPDATE OutboxMessages SET │
│ ProcessedAt = NOW() │
└─────────────────────────────────────────┘
// EF Core Outbox — write and event insert share one transaction
public class OrderService
{
public async Task CreateOrderAsync(CreateOrderRequest request)
{
var order = new Order(request);
_context.Orders.Add(order);
_context.OutboxMessages.Add(new OutboxMessage
{
Id = Guid.NewGuid(),
Type = nameof(OrderCreatedEvent),
Payload = JsonSerializer.Serialize(new OrderCreatedEvent(order.Id, order.Total)),
CreatedAt = DateTime.UtcNow
});
await _context.SaveChangesAsync(); // one transaction, one commit
}
}
public class OutboxPublisher : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
var messages = await _context.OutboxMessages
.Where(m => m.ProcessedAt == null)
.OrderBy(m => m.CreatedAt)
.Take(100)
.ToListAsync(ct);
foreach (var msg in messages)
{
await _messageBroker.PublishAsync(msg.Type, msg.Payload);
msg.ProcessedAt = DateTime.UtcNow;
}
await _context.SaveChangesAsync(ct);
await Task.Delay(TimeSpan.FromSeconds(1), ct);
}
}
}
# Outbox pattern in Python (SQLAlchemy)
from sqlalchemy.orm import Session
import json, uuid, datetime
def create_order(session: Session, request: dict):
order = Order(**request)
session.add(order)
session.add(OutboxMessage(
id=str(uuid.uuid4()),
type="OrderCreated",
payload=json.dumps({"order_id": order.id, "total": str(order.total)}),
created_at=datetime.datetime.utcnow(),
processed_at=None,
))
session.commit() # single transaction — order row + outbox row commit atomically
def publish_outbox_batch(session: Session, broker):
pending = (session.query(OutboxMessage)
.filter(OutboxMessage.processed_at.is_(None))
.order_by(OutboxMessage.created_at)
.limit(100).all())
for msg in pending:
broker.publish(msg.type, msg.payload)
msg.processed_at = datetime.datetime.utcnow()
session.commit()
Key design decisions:
- Polling vs CDC: a poller (as above) is simple to build and reason about. Change Data Capture (Debezium reading the DB’s write-ahead log) gives lower latency and removes the polling load, at the cost of extra infrastructure (Kafka Connect, Debezium connectors).
- Idempotency: consumers must tolerate duplicate delivery (at-least-once) — dedupe on a message ID.
- Ordering: preserve order per aggregate (e.g., partition Kafka by
order_id) — global ordering is rarely needed. - Cleanup: archive or purge processed outbox rows on a schedule so the table doesn’t grow unbounded.
- Why not 2PC/XA? Distributed transactions across a DB and a broker are slow, reduce availability, and most modern brokers don’t support XA at all.
9.4 Message Broker Comparison — Kafka vs RabbitMQ vs Azure Service Bus vs Pulsar
| Factor | Kafka | RabbitMQ | Azure Service Bus | Apache Pulsar |
|---|---|---|---|---|
| Model | Distributed commit log | Traditional message broker (exchanges/queues) | Managed enterprise message queue/topic | Multi-layer pub-sub log (separates compute from storage) |
| Throughput | Millions of msgs/sec | Tens of thousands msgs/sec | ~1K msgs/sec per Messaging Unit (scales with tiers) | Millions of msgs/sec, comparable to Kafka |
| Message retention | Configurable (days/weeks), log-based — replay any offset | Until consumed (queue-based); gone after ack | Until consumed / TTL-based | Configurable tiered storage (hot + cold via BookKeeper + offload to object storage) |
| Ordering | Guaranteed per partition (by key) | Per queue, FIFO with a single consumer | FIFO per session | Guaranteed per partition/key, similar to Kafka |
| Consumer model | Pull (consumer polls) | Push (broker delivers) | Push (with peek-lock semantics) | Pull, with multiple subscription modes (exclusive, shared, failover, key-shared) |
| Routing | Topic/partition key only | Rich routing (direct/fanout/topic/headers exchanges) | Topics + subscriptions + SQL filter rules | Topic-based, with multi-tenancy built in (tenant/namespace/topic) |
| Multi-tenancy | Not built-in (roll your own) | Not built-in | Namespaces | Native (tenant/namespace isolation, quotas) |
| Compute/storage coupling | Coupled (brokers own partitions on local disk) | Coupled | Managed, opaque | Decoupled — brokers stateless, BookKeeper handles storage, enables faster rebalancing |
| Operational complexity | Higher (ZooKeeper/KRaft, partition rebalancing, tuning) | Lower — simpler to operate at moderate scale | Lowest — fully managed | High — more moving parts (brokers + bookies + ZooKeeper) unless using managed offering |
| Best for | Event streaming, event sourcing, log aggregation, real-time analytics, replay-heavy workloads | Traditional task queues, RPC-style messaging, complex routing needs | Enterprise .NET/Azure-native workflows, FIFO sessions, dead-lettering out of the box | Kafka-scale throughput with geo-replication and multi-tenancy as first-class features |
| Cloud-native fit | MSK/Confluent Cloud (AWS/multi-cloud) | CloudAMQP and self-hosted | Native to Azure | StreamNative Cloud, growing but less ubiquitous |
Decision guidance:
- Kafka: choose when you need high-throughput event streaming, replay/audit, or are building event sourcing / CQRS read-model rebuilding.
- RabbitMQ: choose for classic task-queue/RPC workloads with complex routing needs and moderate throughput, where operational simplicity matters more than raw scale.
- Azure Service Bus: choose in an Azure-centric enterprise stack needing FIFO sessions, dead-lettering, and duplicate detection out of the box with minimal ops burden.
- Pulsar: choose when you need Kafka-like throughput and strong multi-tenancy/geo-replication as first-class platform features, and you have the operational maturity to run (or budget to buy) a multi-component system.
// Kafka producer/consumer (.NET, Confluent.Kafka)
var config = new ProducerConfig
{
BootstrapServers = "kafka:9092",
Acks = Acks.All,
EnableIdempotence = true,
MaxInFlight = 5
};
using var producer = new ProducerBuilder<string, string>(config).Build();
await producer.ProduceAsync("orders", new Message<string, string>
{
Key = order.CustomerId.ToString(), // same key -> same partition -> ordering
Value = JsonSerializer.Serialize(order)
});
# Kafka producer/consumer in Python (confluent-kafka)
from confluent_kafka import Producer, Consumer
producer = Producer({"bootstrap.servers": "kafka:9092", "acks": "all",
"enable.idempotence": True})
producer.produce("orders", key=str(order["customer_id"]), value=json.dumps(order))
producer.flush()
consumer = Consumer({
"bootstrap.servers": "kafka:9092",
"group.id": "order-processor",
"auto.offset.reset": "earliest",
"enable.auto.commit": False,
})
consumer.subscribe(["orders"])
while True:
msg = consumer.poll(1.0)
if msg is None or msg.error():
continue
process_order(json.loads(msg.value()))
consumer.commit(msg) # manual commit after successful processing = at-least-once
9.5 Dead Letter Queue (DLQ) Pattern
Normal Queue → Consumer → ✅ Success → Acknowledge
→ ❌ Failure → Retry (bounded, e.g. 3x with backoff)
→ ❌ Still failing → Dead Letter Queue
→ Alert
→ Manual inspection
→ Reprocess or discard
9.6 Interview Q&A
Q1: Your order service needs to update the database AND send a message. How do you ensure both happen atomically?
This is the dual-write problem. My default solution is the Transactional Outbox pattern: write the order row and an outbox message row in the same local DB transaction, then a background worker (or CDC via Debezium) reads unpublished outbox rows and publishes them, marking them processed after a successful publish. I explicitly avoid two-phase commit / XA transactions — they’re slow, reduce availability, and most modern brokers (Kafka, SQS) don’t support XA at all. CDC-based outbox publishing (reading the DB’s write-ahead log) gives lower latency than polling but adds infrastructure; I default to polling and move to CDC only if latency requirements demand it.
Q2: Compare choreography vs orchestration for saga patterns. Which do you prefer?
Choreography lets services react to each other’s events independently — very loosely coupled and scales well, but the overall flow is hard to see and debug, since it’s spread across many services and needs distributed tracing to reconstruct. Orchestration uses a central coordinator that owns the workflow state explicitly — much easier to reason about, test, and extend with new compensation branches, at the cost of a coordinator that must be made highly available. I prefer orchestration for complex, multi-step business workflows (order fulfillment with several compensating paths), and choreography for simple, low-fan-out notifications. In practice, most production systems use both — orchestration for the core transactional flow, choreography for the peripheral side effects hanging off its events.
Q3: How do you handle message ordering in a distributed system?
Kafka guarantees ordering per partition, so I key messages by the entity that needs order preserved (e.g., customer ID or order ID) so all its events land in the same partition. RabbitMQ preserves FIFO order per queue only with a single consumer; multiple consumers on the same queue lose ordering. Azure Service Bus sessions give FIFO ordering per session ID. At the application level I can also add sequence numbers and have consumers reorder if strictly necessary. The key insight is that global ordering is rarely actually required — ordering per entity (per order, per customer) is almost always sufficient, and demanding global ordering usually just adds unnecessary throughput constraints.
Q4: How would you migrate synchronous REST calls between services to asynchronous messaging?
Incrementally. First identify calls that don’t actually need an immediate response — notifications, analytics, non-critical downstream updates. Introduce the message broker alongside the existing REST calls (strangler-style). Run a dual-write phase where the service both publishes the event and still makes the REST call, and verify the event-driven consumer produces the same result. Once verified, cut over — remove the REST call and rely on messaging only — while monitoring message lag, processing time, and error rates, and keeping the REST endpoint available (marked deprecated) as an emergency fallback during the transition.
Q5: When would you choose Kafka over RabbitMQ, and vice versa?
Kafka when I need high-throughput event streaming, the ability to replay history (event sourcing, rebuilding read models, audit), or many independent consumer groups each getting the full stream. RabbitMQ when the use case is closer to a classic task queue or RPC pattern, needs rich routing (topic/header-based exchange bindings), and throughput needs are moderate — RabbitMQ is operationally simpler to run at that scale. If I’m already deep in Azure and need enterprise features like FIFO sessions and built-in dead-lettering with minimal ops overhead, Azure Service Bus is often the pragmatic choice over self-managing either.