Article · Event-Driven Architecture · Microservices
Event-driven architecture: who publishes, who listens and what can go wrong
Event-driven architecture in practice: Fowler's four meanings of "events", choreography and orchestration, delivery guarantees, the outbox, idempotent consumers, ordering and contracts. Code in C#, TypeScript, Java, Go and Python.
When someone places an order at Halina's pierogi place, several things happen: the kitchen gets a ticket, the loyalty programme awards points, analytics updates its charts, and the customer gets a text message. In the first version, OrderService called four services in a row – and when the SMS gateway went down, nobody could place an order. In event-driven architecture (EDA), orders just announce the fact "order placed", and everything else reacts at its own pace.
- 4
- meanings of "event-driven" – according to Martin Fowler (2017)
- ≥1
- deliveries of every message – the typical guarantee: at-least-once, so duplicates happen
- 2011
- Kafka goes open source – LinkedIn releases its event streaming platform
Context and forces
- Many recipients of one fact – kitchen, loyalty, analytics and notifications; tomorrow a fifth one will join.
- Independent teams and deployments – adding a recipient shouldn't require a change in orders.
- Resilience – an SMS outage must not block placing orders.
- Traffic peaks – at 6 p.m. on a Friday, a queue smooths the load instead of knocking the kitchen over.
Four things people call "event-driven"
In What do you mean by "Event-Driven"? (2017), Martin Fowler pointed out that the label covers different patterns:
| Pattern | What it means | Example in the pierogi place |
|---|---|---|
| Event Notification | The event only informs; the recipient asks the sender for details if needed | OrderPlaced(orderId) – the kitchen fetches the details through an API |
| Event-Carried State Transfer | The event carries data, the recipient keeps a local copy and doesn't need to ask | OrderPlaced with lines and phone – Delivery doesn't call Orders |
| Event Sourcing | Events are the source of truth about state | the loyalty account stream |
| CQRS | Separate write and read models, often fed by events | the kitchen board as a projection |
This article focuses on the first two – communication between components. The others are covered in the Event sourcing and CQRS articles.
Structure
Choreography or orchestration? In choreography, every component reacts to events and publishes its own – there's no central conductor (as in the diagram). In orchestration, one component (an orchestrator, process manager or saga) sends commands and waits for replies. Choreography is simpler for short reactions ("award points"), orchestration is clearer for multi-step processes with compensation, e.g. catering with a deposit: reserve the date → payment → confirmation, and on a declined payment, release the date.
Delivery guarantees
| Guarantee | What it means | Consequence |
|---|---|---|
| At-most-once | A message may be lost, never repeated | fine for metrics, bad for loyalty points |
| At-least-once | A message won't be lost, but may arrive more than once | the standard; consumers must be idempotent |
| Exactly-once | In practice: effectively once, thanks to deduplication or broker transactions | works within one system (e.g. Kafka Streams), not end to end with an arbitrary database |
What it looks like in code
The dual write problem: if you save the order to the database and then send the event to the broker, a failure between those steps loses the event (or, in the reverse order, sends an event about an order that doesn't exist). The solution is the transactional outbox: the event goes into a table in the same transaction as the order, and a separate process (a relay or CDC, e.g. Debezium) forwards it to the broker.
A producer with an outbox
// The order and the event are saved in ONE transaction. A relay publishes the outbox later.
public async Task<Guid> Handle(PlaceOrder cmd, CancellationToken ct)
{
var order = Order.Place(cmd.Phone, cmd.Lines);
db.Orders.Add(order);
db.Outbox.Add(new OutboxMessage
{
Id = Guid.NewGuid(), // becomes the message id (for dedup)
Type = "orders.order-placed.v1",
Key = order.Id.ToString(), // partition key: per-order ordering
Payload = JsonSerializer.Serialize(new OrderPlacedV1(order.Id, order.Phone, order.Total)),
OccurredAt = clock.GetUtcNow()
});
await db.SaveChangesAsync(ct); // both rows or neither
return order.Id;
}
// Relay (BackgroundService): SELECT TOP 100 ... WHERE PublishedAt IS NULL ORDER BY OccurredAt,
// produce to Kafka, then UPDATE PublishedAt. Crashes cause re-sends, never losses -> at-least-once.// The order and the event are saved in ONE transaction. A relay publishes the outbox later.
export async function placeOrder(cmd: PlaceOrder): Promise<string> {
return prisma.$transaction(async (tx) => {
const order = await tx.order.create({ data: toOrderRow(cmd) });
await tx.outboxMessage.create({
data: {
id: crypto.randomUUID(), // becomes the message id (for dedup)
type: "orders.order-placed.v1",
key: order.id, // partition key: per-order ordering
payload: { orderId: order.id, phone: order.phone, total: order.total },
},
});
return order.id;
});
}
// Relay: every second read unpublished rows in order, send them with
// producer.send({ topic, messages: [{ key, value, headers: { "message-id": id } }] }),
// then mark them as published. A crash means a re-send, never a loss.@Service
class PlaceOrderHandler {
private final OrderRepository orders;
private final OutboxRepository outbox;
private final ObjectMapper json;
PlaceOrderHandler(OrderRepository orders, OutboxRepository outbox, ObjectMapper json) {
this.orders = orders; this.outbox = outbox; this.json = json;
}
// The order and the event are saved in ONE transaction. A relay publishes the outbox later.
@Transactional
public UUID handle(PlaceOrder cmd) throws JsonProcessingException {
var order = orders.save(Order.place(cmd.phone(), cmd.lines()));
outbox.save(new OutboxMessage(
UUID.randomUUID(), // message id for dedup
"orders.order-placed.v1",
order.id().toString(), // partition key
json.writeValueAsString(new OrderPlacedV1(order.id(), order.phone(), order.total())),
Instant.now()));
return order.id();
}
}
// Relay: a @Scheduled job (or Debezium reading the outbox table via CDC) publishes and marks rows.// PlaceOrder saves the order and the event in ONE transaction; a relay publishes the outbox later.
func (s Service) PlaceOrder(ctx context.Context, cmd PlaceOrder) (string, error) {
tx, err := s.DB.BeginTx(ctx, nil)
if err != nil {
return "", err
}
defer tx.Rollback()
orderID := uuid.NewString()
if _, err := tx.ExecContext(ctx,
`INSERT INTO orders (id, phone, total) VALUES ($1, $2, $3)`, orderID, cmd.Phone, cmd.Total()); err != nil {
return "", err
}
payload, _ := json.Marshal(OrderPlacedV1{OrderID: orderID, Phone: cmd.Phone, Total: cmd.Total()})
if _, err := tx.ExecContext(ctx,
`INSERT INTO outbox (id, type, key, payload) VALUES ($1, 'orders.order-placed.v1', $2, $3)`,
uuid.NewString(), orderID, payload); err != nil {
return "", err
}
return orderID, tx.Commit()
}
// Relay goroutine: SELECT ... FOR UPDATE SKIP LOCKED LIMIT 100, publish, UPDATE published_at.import json
import uuid
from sqlalchemy.orm import Session
def place_order(session: Session, cmd: "PlaceOrder") -> str:
"""The order and the event are saved in ONE transaction; a relay publishes the outbox later."""
order = Order.place(cmd.phone, cmd.lines)
session.add(order)
session.flush() # assigns order.id
session.add(OutboxMessage(
id=str(uuid.uuid4()), # message id for dedup on the consumer side
type="orders.order-placed.v1",
key=str(order.id), # partition key: per-order ordering
payload=json.dumps({"order_id": str(order.id), "phone": order.phone, "total": str(order.total)}),
))
session.commit() # both rows or neither
return str(order.id)
# Relay: a loop (or a Celery beat task) reads unpublished rows, produces them with
# confluent_kafka.Producer.produce(topic, key=..., value=..., headers=...), then marks them published.The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Ordering, contracts and observability
- Trade-offs
- Adoption path
- In practice
- Anti-patterns
- Related topics
- Test yourself