Polski

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.

By · · 13 min read

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:

PatternWhat it meansExample in the pierogi place
Event NotificationThe event only informs; the recipient asks the sender for details if neededOrderPlaced(orderId) – the kitchen fetches the details through an API
Event-Carried State TransferThe event carries data, the recipient keeps a local copy and doesn't need to askOrderPlaced with lines and phone – Delivery doesn't call Orders
Event SourcingEvents are the source of truth about statethe loyalty account stream
CQRSSeparate write and read models, often fed by eventsthe 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

Diagram: Broker topology: the sender doesn't know the recipients

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

GuaranteeWhat it meansConsequence
At-most-onceA message may be lost, never repeatedfine for metrics, bad for loyalty points
At-least-onceA message won't be lost, but may arrive more than oncethe standard; consumers must be idempotent
Exactly-onceIn practice: effectively once, thanks to deduplication or broker transactionsworks 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

PlaceOrderWithOutbox.cs
// 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.
place-order.outbox.ts
// 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.
PlaceOrderWithOutbox.java
@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.
orders/outbox.go
// 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.
orders/outbox.py
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

Create a free account · Sign in