# Event-Driven

**Also known as:** EDA (between services)  
**Category:** System Architecture (Macro)  
**Complexity:** 3/5  
**Fit:** 5+ engineers  
**Guide:** https://layra4.dev/architectures/system/event-driven-system

*Services react to events on a broker instead of calling each other.*

In an event-driven system, a service that changes something publishes an event: a record, in the past tense, that it happened (OrderPlaced). It sends the event to a broker such as Kafka or RabbitMQ. Any number of other services subscribe and react. The producer does not know who listens.

You can add a consumer without touching the producer, and the broker absorbs load spikes. The cost is that the flow no longer sits in one call stack. Data is consistent only after a delay, and events can arrive late, twice or out of order, so every consumer must handle that.

> **In one sentence.** A service publishes a fact and moves on; any number of consumers react in their own time, so each one can scale, fail or be added alone.

## Origin

Applies long-standing messaging ideas, publish–subscribe and queues from Enterprise Integration Patterns, between services. Log-based brokers like Apache Kafka, built at LinkedIn, made it mainstream.

## The moving parts

### Events are past-tense facts

An event records something that already happened: OrderPlaced, not PlaceOrder. The producer states the fact; each consumer decides what to do.

- Immutable once published
- Named in the past tense
- Carries an id for deduplication

> { id: "e-91", type: "order.placed", orderId: "o-42", total: 59.90 }

### The broker

Stores events and delivers them to subscribers. A log (Kafka) keeps events for days so consumers can replay them; a queue (RabbitMQ, SQS) removes each message once it is handled.

- Buffers spikes
- Decouples producer and consumer in time
- Critical infrastructure to run

### Choreography vs. orchestration

In choreography, each service reacts to events and the flow emerges. In orchestration, one coordinator tells each service what to do next. The first decouples more; the second is easier to follow.

- Choreography: no central owner
- Orchestration: one visible flow
- A saga can use either

### At-least-once delivery

Brokers retry until a consumer confirms, so the same event can arrive twice. A consumer that is idempotent (gives the same result if run twice) stays correct.

- Duplicates are normal
- Order is only per partition or key
- Dedupe on the event id

## Designing event flows

### Make every consumer idempotent

At-least-once delivery means the same event will arrive twice one day. Record each event id you have processed and skip repeats, or a routine redelivery corrupts your data.

### Publish with an outbox, not a dual write

Writing to the database and then to the broker can fail halfway and lose the event. Write the event to an outbox table in the same transaction, and let a relay publish it.

### Name events as facts, not commands

“PaymentCaptured”, not “CapturePayment”. When an event tells a consumer what to do, the producer depends on that consumer again.

### Version event schemas by adding fields

Consumers you do not know read your events. Add optional fields; never rename or remove one. For a breaking change, publish a new event type (order.placed.v2) next to the old one.

## Diagrams

Rendered as geometry on the guide page; not reproducible as text.

- `event-flow` — see https://layra4.dev/architectures/system/event-driven-system
- `event-topologies` — see https://layra4.dev/architectures/system/event-driven-system

## Contracts first, one deployable per service

```
platform/
contracts/                      # the only shared code: event schemas
  order-placed.v1.ts            # a past-tense fact; additive changes only
services/                       # each ships alone and owns its database
  orders/                       # PRODUCER; never calls a consumer
    domain/
    outbox.ts                   # event written in the same transaction as the state
    relay.ts                    # moves outbox rows to the broker, at least once
  shipping/                     # CONSUMER; subscribes, never calls orders
    handlers/
      onOrderPlaced.ts          # idempotent; skips event ids it has seen
    dlq.ts                      # events that keep failing, parked for a human
broker/                         # operated infrastructure, not a library
  topics.yaml                   # one topic per event type; partition by order id
```

Services share event schemas and nothing else. The two files that make at-least-once delivery safe sit at opposite ends of every flow: the producer's outbox and the consumer's dedupe check.

## Examples

### Outbox on one side, dedupe on the other

```typescript
// PRODUCER (orders) — the state change and the event commit together.
await db.transaction(async (tx) => {
  await tx.query("insert into orders (id, total) values ($1, $2)", [id, total]);
  await tx.query(                                 // the outbox: same transaction
    "insert into outbox (event_id, type, payload) values ($1, $2, $3)",
    [crypto.randomUUID(), "order.placed", { orderId: id, total }],
  );
});
// A relay reads the outbox and publishes each row to the broker, at least once.

// CONSUMER (shipping) — may see the same event twice, so it dedupes.
broker.subscribe("order.placed", async (event) => {
  await db.transaction(async (tx) => {
    const fresh = await tx.query(
      "insert into processed (event_id) values ($1) on conflict do nothing",
      [event.id],
    );
    if (fresh.rowCount === 0) return;             // seen before: skip safely
    await tx.query("insert into shipments (order_id) values ($1)", [event.orderId]);
  });
});
// Billing and email subscribe the same way. The producer never changes.
```

The producer cannot lose the event, because it commits with the order. The consumer cannot apply it twice, because the processed-id insert and the shipment commit together.

## When to use

- One action triggers many reactions: ship, bill, email, analytics
- Consumers must scale or fail without affecting the producer
- New consumers will be added over time without touching producers

## When not to use

- The caller needs an answer now, as in a request/response query
- A read must see the write at once (strong consistency)
- The team cannot yet run a broker or debug asynchronous flows

## Benefits

- Add or remove consumers without changing the producer
- The broker absorbs spikes, and consumers scale on their own
- A slow or failed consumer does not block the producer

## Costs

- No call stack: following one flow needs tracing across services
- Data is consistent only after a delay, and the UI must handle that
- The broker is critical infrastructure to run, scale and monitor

## Pitfalls

- Consumers that are not idempotent, so a redelivered event charges a card twice
- Writing to the database and the broker separately, so a crash loses the event
- A changed event field that silently breaks a consumer nobody knew about
- Long chains of events that nobody can follow end to end

## Related patterns

- [Event-Driven](https://layra4.dev/architectures/application/event-driven-app) — the same idea inside one process, without the network
- [Publish–Subscribe & Event Streams](https://layra4.dev/architectures/core-building-blocks/pub-sub) — the delivery model behind fan-out to many consumers
- [Outbox](https://layra4.dev/architectures/infrastructure/outbox) — publish events reliably with the local commit
- [Idempotent Consumer](https://layra4.dev/architectures/infrastructure/idempotent-consumer) — make redelivered events harmless
- [Saga / Process Manager](https://layra4.dev/architectures/architectural/saga) — multi-step work across services, run on these events

## Further reading

- *Enterprise Integration Patterns* — Gregor Hohpe & Bobby Woolf (2003) — The classic messaging pattern language.
- *Designing Event-Driven Systems* — Ben Stopford (2018) — Event-driven services on a log-based broker.
- *What do you mean by “Event-Driven”?* — Martin Fowler (2017) — Separates the several things people mean by the term.
