Cloud & ArchitectureComplete guide

Event-Driven Messaging

Event-driven messaging lets services react to what happened elsewhere without a direct, blocking call, trading immediate consistency for looser coupling and better resilience to partial failure.

Overview

Event-driven messaging communicates immutable facts or directed commands through durable asynchronous channels so publishers and consumers need not be available simultaneously. Temporal decoupling introduces duplicates, delay, reordering, poison data, schema evolution, backpressure, retention, and partial completion as normal conditions. A transactional outbox stores outgoing records with business state; a relay publishes later, and idempotent consumers store message identity with side effects. Events should be past-tense bounded facts with stable identity, correlation, causation, occurrence time, version, and ownership. Commands and events have different routing semantics. Sagas make long workflows, timeouts, and compensation explicit. Production needs dead-letter repair, replay, reconciliation, compatibility testing, capacity evidence, security controls, and a business definition of acceptable eventual consistency.

What you will learn

  • Distinguish events, commands, queues, publish-subscribe, streams, and synchronous calls.
  • Close the dual-write gap with an outbox and idempotent consumer inbox.
  • Design versioned contracts with identity, correlation, causation, and ownership.
  • Handle retries, duplicates, poison data, ordering, backpressure, and replay.
  • Model workflows with saga state, timeouts, and compensation.
  • Operate lag, throughput, dead letters, reconciliation, and recovery.

Prerequisites

  • Distributed systems, transactions, async C#, workers, and database basics.
  • Broker, serialization, retry, observability, and eventual-consistency concepts.
  • A business definition of acceptable delay and recovery.

When to use Event-Driven Messaging

Good fit

  • Publisher and consumer need temporal decoupling.
  • A fact fans out to independent consumers.
  • Bursts need durable buffering.

Choose another approach when

  • The caller needs an immediate authoritative response.
  • The workflow cannot tolerate eventual consistency.
  • A simple in-process call needs no durability or fan-out.

Key concepts

Events vs commands

An event states a fact that already happened and may have many subscribers; a command requests a specific action and expects exactly one handler.

Transactional outbox

Writing a business change and its outgoing event in the same local transaction avoids the dual-write problem of updating a database and publishing separately.

Idempotent consumers

A handler records which message identifiers it has already processed so redelivery does not repeat side effects.

Sagas

A saga coordinates a multi-step workflow across services using events and compensating actions instead of a distributed transaction.

Delivery semantics

At-most-once can lose work; at-least-once redelivers; end-to-end exactly-once depends on idempotent effects.

Event contracts

Identity, type, version, time, correlation, causation, ownership, and bounded payload form a durable contract.

Retries and dead letters

Bounded retries handle transients; poison messages move aside with diagnostics for repair or replay.

Ordering and backpressure

Order is scoped to a key while concurrency must be bounded to protect downstream dependencies.

Architecture

A service commits a business change and an outbox record in one transaction; a relay publishes the event to a broker, which delivers it to independent, idempotent subscribers.

Service + outbox
Relay
Broker
Idempotent subscribers

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The order sample records state and an outbox message together, relays pending events, and proves a loyalty consumer applies each message ID once.

  1. 01
    Define semantics

    Choose event or command ownership, consistency, ordering key, and failure outcome.

  2. 02
    Design the envelope

    Add ID, type, version, time, correlation, causation, tenant, and bounded payload.

  3. 03
    Write the outbox

    Persist business state and outgoing message atomically.

  4. 04
    Relay safely

    Lease bounded batches, confirm publish, and tolerate duplicate relay.

  5. 05
    Consume idempotently

    Record identity with side effects before acknowledgement.

  6. 06
    Handle failure

    Use bounded backoff, dead letters, repair, replay, and reconciliation.

  7. 07
    Operate capacity

    Measure throughput, age, lag, retries, failures, and saturation.

Code example

A background relay publishes outbox rows written in the same transaction as the business change, then marks them sent.

OutboxRelay.cs
public async Task RelayPendingAsync(CancellationToken ct)
{
    var pending = await db.OutboxMessages
        .Where(message => message.SentAtUtc == null)
        .OrderBy(message => message.CreatedAtUtc)
        .Take(50)
        .ToListAsync(ct);

    foreach (var message in pending)
    {
        await bus.PublishAsync(message.Type, message.Payload, ct);
        message.SentAtUtc = clock.UtcNow;
    }

    await db.SaveChangesAsync(ct);
}

Testing strategy

Inject duplication, delay, reordering, outage, and restart.

  • Prove state and outbox commit together.
  • Crash relay around publish and verify safe duplicates.
  • Redeliver messages and assert one side effect.
  • Test dead-letter repair and replay.
  • Contract-test old and new schemas.
  • Load-test bursts, backpressure, outage, and recovery.

Security considerations

Brokers carry durable business data across trust boundaries.

  • Use TLS, private networking, identity, and least privilege.
  • Authorize again at consumers.
  • Validate type, version, size, tenant, and schema.
  • Avoid secrets and unnecessary personal data.
  • Protect logs, dead letters, and replay tooling.

Performance and scalability

Throughput depends on batching, concurrency, payload, topology, and dependencies.

  • Batch within bounded latency.
  • Tune concurrency against dependency limits.
  • Keep payloads small.
  • Partition only for required ordering.
  • Measure end-to-end event age.

Deployment and operations

Publishers, consumers, schemas, and topology coexist during rollouts.

  • Use additive contracts.
  • Deploy tolerant consumers first.
  • Provision topology as code.
  • Drain consumers safely.
  • Rehearse failover, backlog recovery, replay, and rollback.

Common problems and fixes

State changed but no event exists.

Likely cause: Dual writes were separate.

Fix: Use an atomic outbox.

Side effects occur twice.

Likely cause: Deduplication is not durable.

Fix: Store message identity with effects.

Backlog grows.

Likely cause: Ingress exceeds processing.

Fix: Measure age and scale the bottleneck.

Poison data retries forever.

Likely cause: Retries are unbounded.

Fix: Cap retries and dead-letter with context.

Consumers break after deployment.

Likely cause: Schema is incompatible.

Fix: Use additive versions and contract tests.

Events arrive out of order.

Likely cause: Global order was assumed.

Fix: Use per-key sequence handling or order-independent logic.

Best practices

  • Write the outbox row in the same transaction as the business change it describes, never as a separate call.
  • Design every consumer to be safe against duplicate delivery before trusting the broker's delivery guarantees.
  • Version event contracts additively and keep old consumers working through a compatibility window.
  • Model multi-step workflows as explicit sagas with compensating actions instead of implicit chains of event handlers.
  • Bound retries and route poison data to controlled dead-letter workflows.
  • Carry identity, correlation, causation, version, and occurrence time.
  • Measure end-to-end event age and downstream saturation.
  • Rehearse replay and reconciliation before incidents.

Production checklist

  • Event and command semantics are explicit.
  • Outbox and inbox effects are atomic.
  • Contracts carry identity, version, correlation, causation, and bounded payload.
  • Consumers handle duplicates, delay, order, cancellation, and poison data.
  • Retries, dead letters, repair, and replay are controlled.
  • Security and tenant boundaries are enforced.
  • Age, lag, throughput, failures, and saturation are visible.
  • Failover and reconciliation are rehearsed.

Common interview questions

What is the dual-write problem and how does the outbox pattern fix it?

Dual-write happens when a service updates its database and publishes an event as two separate operations that can fail independently, leaving them out of sync; the outbox pattern writes the event as a row in the same local transaction as the business change, then relays it asynchronously, so the two are always consistent.

Why can't most message brokers guarantee exactly-once delivery?

Coordinating exactly-once delivery across a network requires distributed consensus that most brokers avoid for performance and availability reasons, so they offer at-least-once delivery and expect consumers to handle duplicates.

What is a saga, and why not just use a distributed transaction?

A saga coordinates a multi-step process across services using a sequence of local transactions and compensating actions on failure; distributed transactions need every participant to be available and lock resources together, which does not scale or fit independently deployed services.

How does an idempotent consumer work?

It records a stable message ID in the same transaction as business effects and skips or returns the recorded result on redelivery.

What belongs in an event envelope?

Message ID, type, schema version, occurrence time, correlation and causation IDs, tenant context, and a bounded payload.

How should poison messages be handled?

Use bounded retries for transients, dead-letter permanent failures with diagnostics, then repair and replay through controlled tooling.

What does exactly-once mean?

Broker claims are scoped; end-to-end business exactly-once requires idempotent effects or one constrained transaction boundary.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Event-Driven Orders

A .NET 10 order workflow demonstrating a transactional-outbox model, relay, at-least-once delivery, and idempotent consumer processing.

.NET 10Event-Driven ArchitectureTransactional OutboxxUnit
dedicated-sampleoutboxidempotent-consumerdelivery-semantics
Run
dotnet run --project src/EventDrivenOrders
Test
dotnet test EventDrivenOrders.slnx