Volume 4 · Chapter 7 — .NET Distributed Systems and Microservices Architecture
Event-Driven Architecture
7.1 Introduction
Event-driven architecture lets services communicate by announcing facts rather than issuing direct calls. A service publishes “PaymentCompleted” and moves on; whoever cares reacts independently. This inversion is the strongest form of loose coupling - the producer knows nothing about its consumers, so new reactions are added without changing the producer. It powers scalability, resilience, and extensibility, at the cost of embracing asynchrony and eventual consistency. (Volume 9 develops EDA in architectural depth.)
7.2 Commands vs Events
A command is an instruction to do something - imperative, directed at one handler, and rejectable (“ProcessPayment”). An event is a statement that something already happened - past tense, broadcast, and a fact (“PaymentProcessed”). Commands couple the sender to a receiver; events invert the dependency. Choosing the right one determines how coupled your system is.
public sealed record ProcessPayment(Guid PaymentId, decimal Amount); // command (imperative)
public sealed record PaymentProcessed(Guid PaymentId, decimal Amount, DateTime At); // event (fact)
7.3 Choreography vs Orchestration
In choreography, services react to each other’s events with no central coordinator - simple and decentralized for short flows, but the overall process is implicit and hard to follow as it grows. In orchestration, a central coordinator drives the steps explicitly - easier to monitor, change, and reason about for complex, long-running workflows, at the cost of a coordinator that must itself be resilient.
sequenceDiagram autonumber participant Order as Order Service participant Bus as Event Broker participant Pay as Payment participant Inv as Inventory participant Notif as Notification Order-)Bus: OrderCreated (fact) Bus-)Pay: OrderCreated Bus-)Inv: OrderCreated Bus-)Notif: OrderCreated Note over Bus,Notif: Choreography - each reacts independently; Order knows none of them
7.4 Reliable Publishing: The Outbox Pattern
The hardest problem is the dual write: updating state and publishing an event must be atomic, or you get lost or phantom events. The transactional outbox solves it - write the event to an outbox table in the same transaction as the state change, then a relay publishes committed rows and marks them sent. Consumers stay idempotent because delivery is at-least-once.
sequenceDiagram autonumber participant Svc as Service participant DB as Database (state + outbox) participant Relay as Outbox Relay participant Broker as Broker Svc->>DB: BEGIN TX: save state + insert outbox row DB-->>Svc: COMMIT (atomic) Relay->>DB: poll unsent outbox rows Relay->>Broker: publish event Broker-->>Relay: ack Relay->>DB: mark row sent
7.5 Event Streams and Versioning
Event streaming platforms (Kafka, Event Hubs) process continuous, retained, replayable event streams for real-time analytics, fraud detection, and audit. And because events are contracts that outlive any deployment, they must evolve without breaking consumers: additive backward-compatible changes, versioned schemas, and tolerant readers.
What is the difference between a command and an event, and why does it matter for coupling?
A command is an imperative request to perform an action, directed at a specific handler, and it can be validated and rejected - “ProcessPayment” tells one service to do something. An event is a past-tense statement that something has already happened, broadcast to any interested subscriber, and it cannot be rejected because it is a fact - “PaymentProcessed” announces that a payment occurred. The difference matters enormously for coupling. A command couples the sender to a known receiver and its contract: the sender must know who handles it and depends on that handler. An event inverts the dependency: the producer emits a fact and knows nothing about who, if anyone, consumes it, so consumers depend on the producer’s event contract but the producer depends on no one. This inversion is the source of event-driven architecture’s loose coupling and extensibility - you can add a new consumer that reacts to an existing event without changing the producer at all, whereas adding a new behavior with commands means the commanding service must know to send the new command. So designing interactions as events where possible (announcing what happened rather than telling specific services what to do) is what gives event-driven systems their independence: services react to facts on their own terms, and the system can grow new reactions without touching existing producers. You still use commands where you genuinely need a directed, rejectable action targeted at a specific handler. The naming and tense discipline reinforces the model - commands are imperative (“do X”), events are past tense (“X happened”) - and getting this distinction right is what determines whether your services are loosely coupled through facts or tightly coupled through directed instructions. In short: commands direct one receiver and create coupling to it; events broadcast a fact and invert the dependency, which is why events are the tool for loose coupling and extensibility in distributed systems.
How do you guarantee reliable event publishing so an event is never lost or duplicated inconsistently?
The core problem is the dual write: a service must both change its own state (in its database) and publish an event (to the broker), and these are two separate operations that can partially fail - the state commits but the publish fails (lost event, so downstream never learns of the change), or the publish succeeds but the transaction rolls back (phantom event for something that didn’t happen). Trying to do them together without care leads to inconsistency, and you can’t wrap a database and a broker in one atomic transaction reliably at scale. The robust solution is the transactional outbox pattern. Within the same database transaction that makes the state change, the service also inserts the event into an outbox table, so the state change and the intent to publish commit atomically or not at all - eliminating the lost/phantom event problem at the source. A separate relay process (or a change-data-capture mechanism) then reads committed, unsent outbox rows and publishes them to the broker, marking them sent once acknowledged. Because the relay guarantees at-least-once delivery (it will retry until it confirms the publish, and may occasionally publish a row more than once if it crashes between publishing and marking sent), the events are never lost. To handle the “duplicated” possibility, downstream consumers must be idempotent - deduplicating by the event’s unique id or using naturally idempotent operations - so a redelivered event does no harm; this turns the impossible “exactly once” into what’s actually achievable: atomically recorded, at-least-once delivered, idempotently consumed. So the guarantee is a combination: the outbox makes recording-and-intending-to-publish atomic (no lost or phantom events), the relay ensures at-least-once delivery to the broker, and idempotent consumers make the occasional duplicate harmless. I’d also keep events durable in the broker, use correlation ids and monitoring so I can trace and detect stuck outbox rows or failed publishes, and version event schemas so consumers aren’t broken by changes. The one thing I would never do is the naive dual write (save then publish as two independent steps and hope), because it’s exactly the pattern that loses or phantoms events under failure. The outbox plus idempotent consumers is the standard, correct answer for reliable event publishing in an event-driven system, and it’s why those two patterns almost always appear together.
7.6 Banking Enterprise Scenario
A banking transaction service publishes aTransactionCompletedevent after a successful payment, through the transactional outbox so the ledger change and the event commit atomically. Fraud detection, notifications, reporting, and audit services consume it independently and idempotently - so the transaction service isn’t coupled to any of them, and adding a rewards service later requires no change to it. High-volume transaction streams also feed an event-streaming platform for real-time fraud analytics with replay.
Chapter Revision Notes
- Events are past-tense facts (broadcast); commands are imperative requests (directed).
- Events invert dependencies - producers know nothing about consumers, enabling loose coupling.
- Choreography suits simple flows; orchestration suits complex, long-running workflows.
- The transactional outbox makes state change and event atomic (no lost/phantom events).
- Consumers must be idempotent; evolve event schemas additively with versioning.