Conceptual study

Designing a Reliable Event-Driven Order Platform

A conceptual study of the transactional outbox, idempotent consumers, and failure handling in an asynchronous order pipeline.

Conceptual study

A conceptual design written for learning and discussion. It has not been deployed as described.

Executive summary

An online retailer needs to accept orders reliably while payment, fulfillment, and customer notification are handled by separate services. The proposed design keeps order placement synchronous and small, and moves every downstream step onto a durable, partitioned event log. A transactional outbox guarantees that an order and its “order placed” event are committed together. Idempotent consumers make at-least-once delivery safe. The main costs are eventual consistency for downstream views, a more complex debugging story, and the operational burden of the event log.

Problem statement

In a point-to-point design, the order service calls payment, fulfillment, and notification services directly during checkout. A slow or failing downstream service then slows or fails checkout itself, and a crash between two calls can leave an order paid but never fulfilled. The problem is to decouple these steps without losing or duplicating the effects of any order.

Business context

The hypothetical retailer sells physical goods online with seasonal peaks. Lost orders and double charges are the most damaging failures: both cost money directly and erode trust. A notification arriving a few seconds late is acceptable. A customer seeing a slightly outdated order status for a short time is acceptable if it converges quickly.

Functional requirements

  1. Customers can place an order and receive an immediate confirmation that it was accepted.
  2. Payment is authorized exactly once per order from the customer’s point of view.
  3. Paid orders are sent to the warehouse system for fulfillment.
  4. Customers are notified when an order is confirmed, shipped, or fails.
  5. Operations staff can view the status and history of any order.

Non-functional requirements

QualityScenarioTarget (assumed)
DurabilityAn accepted order survives the crash of any single componentZero acknowledged orders lost
CorrectnessA message is delivered more than onceNo duplicate charge, shipment, or notification side effect
AvailabilityCheckout during a downstream outage (payment excepted)Orders still accepted
LatencyOrder placement at peakp99 below 300 ms for acceptance
FreshnessOrder status view after a state changeConverges within 5 seconds at p99
ThroughputSeasonal peak500 orders per second sustained

Assumptions and constraints

  • A managed relational database is available for the order service and supports transactions.
  • A managed, partitioned, durable event log with consumer groups is available.
  • The payment provider exposes an API that accepts an idempotency key.
  • The warehouse system is an external system that can receive requests but is outside our control.
  • The team is small, so operational simplicity is weighted heavily.

System context diagram

The context diagram (C4 level 1) shows the platform as a single box and the people and systems around it.

System context: the order platform and its external dependencies
Text description

Customers place orders and receive notifications through the order platform. Operations staff view order status. The platform depends on three external systems: a payment provider for authorizing payments, a warehouse system for fulfillment, and an email and SMS provider for notifications.

Component architecture

The container view (C4 level 2) opens the platform box. Order placement is the only synchronous path. Everything after it is driven by events.

Containers: synchronous order acceptance, asynchronous processing through an event log
Text description

Requests enter through an API gateway to the order service, which writes the order and an outbox record to the orders database in one transaction. An outbox relay publishes outbox records to the event log. Four consumers read from the event log: a payment adapter that calls the payment provider, a fulfillment service that calls the warehouse system, a notification service, and a status projector that maintains a read model queried by the status API. Messages that repeatedly fail go to a dead-letter topic.

ComponentResponsibilityScales by
Order serviceValidate the order; write the order and its outbox record in one transactionStateless replicas
Outbox relayRead committed outbox records and publish them to the event logOne active relay per shard, with failover
Event logDurable, ordered per partition, replayablePartitions
ConsumersPerform one side effect each, idempotentlyConsumer group members, up to the partition count
Status projectorMaintain a denormalized read model of order statusPartitions

Data architecture

Each service owns its data. The order service’s database holds the source of truth for orders and an outbox table. Each consumer keeps a small inbox of processed event identifiers to detect duplicates.

erDiagram
    ORDER ||--|{ ORDER_LINE : contains
    ORDER ||--o{ OUTBOX_EVENT : emits
    ORDER {
        uuid id PK
        uuid customer_id
        string status
        int version
        timestamp created_at
    }
    ORDER_LINE {
        uuid order_id FK
        string sku
        int quantity
        decimal unit_price
    }
    OUTBOX_EVENT {
        uuid event_id PK
        uuid aggregate_id
        string event_type
        json payload
        timestamp created_at
        timestamp published_at
    }
    PROCESSED_EVENT {
        uuid event_id PK
        string consumer
        timestamp processed_at
    }

The outbox write is the heart of the design. The order and the event describing it are committed atomically, so there is no window in which one exists without the other:

BEGIN;

INSERT INTO orders (id, customer_id, status, version, created_at)
VALUES ($1, $2, 'PLACED', 1, now());

INSERT INTO outbox_event (event_id, aggregate_id, event_type, payload, created_at)
VALUES (gen_random_uuid(), $1, 'OrderPlaced', $3::jsonb, now());

COMMIT;

Integration design

The sequence below shows the happy path from placement to payment. Note that the customer receives a response as soon as the transaction commits; nothing downstream is on the critical path.

sequenceDiagram
    autonumber
    participant C as Customer
    participant O as Order service
    participant DB as Orders DB
    participant R as Outbox relay
    participant L as Event log
    participant P as Payment adapter
    participant PP as Payment provider
    C->>O: POST /orders
    O->>DB: insert order + outbox event (one transaction)
    O-->>C: 202 Accepted (order id)
    R->>DB: read unpublished outbox events
    R->>L: publish OrderPlaced (key = order id)
    R->>DB: mark event published
    L->>P: deliver OrderPlaced
    P->>PP: authorize (idempotency key = order id)
    PP-->>P: authorized
    P->>L: publish PaymentAuthorized

The relay may publish an event and crash before marking it as published. On restart it publishes the event again. This is why delivery is at least once, and why every consumer must be idempotent.

Security considerations

  • Events carry identifiers and the minimum payload needed; payment details never enter the event log.
  • Producers and consumers authenticate to the event log with per-service identities and topic-level permissions.
  • Event payloads are validated against versioned schemas at the consumer boundary.
  • Personally identifiable information in the read model follows the same retention rules as the source data.

Scalability strategy

Throughput scales by partitions. With orders keyed by order identifier, events for one order stay in order while different orders are processed in parallel. If one consumer instance sustains roughly 100 events per second (an assumption), then a 500-per-second peak needs at least five instances, and the topic needs at least as many partitions. Provisioning more partitions than current needs, for example 24, leaves room to grow without repartitioning.

Availability and reliability

Because checkout depends only on the gateway, the order service, and its database, the availability of order acceptance is roughly the product of those three:

Aaccept=Agateway×Aorder×AdbA_{\text{accept}} = A_{\text{gateway}} \times A_{\text{order}} \times A_{\text{db}}

With assumed availabilities of 99.95%, 99.95%, and 99.99%, acceptance availability is about 0.9995×0.9995×0.9999≈0.99890.9995 \times 0.9995 \times 0.9999 \approx 0.9989, or 99.89%. Had payment (99.9%), fulfillment (99.9%), and notification (99.9%) remained on the synchronous path, the product would fall to about 99.59%, roughly four times the expected downtime. Moving them behind the event log removes them from the multiplication.

An event’s processing follows a small state machine:

stateDiagram-v2
    [*] --> Pending: written to outbox
    Pending --> Published: relay publishes
    Published --> Processing: consumer receives
    Processing --> Done: side effect recorded
    Processing --> Retrying: transient failure
    Retrying --> Processing: backoff elapsed
    Retrying --> DeadLettered: retry budget exhausted
    DeadLettered --> Processing: replayed after fix
    Done --> [*]

Failure scenarios

FailureEffectMitigation
Order service crashes after commitOrder and event both persistedRelay publishes the event when it next runs
Relay crashes after publishing, before markingEvent published twiceConsumers deduplicate by event identifier
Payment provider times outUnknown whether authorization happenedRetry with the same idempotency key; provider returns the original result
Consumer receives a malformed eventProcessing cannot succeedBounded retries, then dead-letter with an alert
Event log unavailableEvents accumulate in the outboxCheckout continues; relay drains the backlog on recovery
Read model falls behindStatus page shows an older stateProjector lag is monitored against the 5-second freshness target

Idempotent consumption is a small amount of code with a large effect. The dedupe record and the side effect’s local state change commit together:

async function handle(event: OrderEvent, db: Database) {
  await db.transaction(async (tx) => {
    const firstTime = await tx.insertIfAbsent('processed_event', {
      event_id: event.id,
      consumer: 'fulfillment',
    });
    if (!firstTime) return; // Duplicate delivery: already handled.
    await tx.insert('shipment_request', { order_id: event.orderId, status: 'REQUESTED' });
  });
}

Observability

  • Outbox age: time since the oldest unpublished outbox record was written. Rising age means the relay is stuck.
  • Consumer lag per consumer group and partition, alerted against the freshness target.
  • Dead-letter rate, with every dead-lettered message linked to its trace.
  • Correlation identifiers: the order identifier and a trace identifier propagate in event headers so a single order can be followed across services.

Architecture decisions

ADR-1: Use a transactional outbox rather than publishing directly from the order service. Publishing after commit risks losing the event if the service crashes in between; publishing before commit risks announcing an order that was never saved. The outbox removes both windows at the cost of a relay component and slightly higher end-to-end latency.

ADR-2: Accept at-least-once delivery and require idempotent consumers. Exactly-once delivery across a database, a log, and external APIs is not achievable in general. Making effects idempotent is simpler and testable.

ADR-3: Partition by order identifier. This preserves per-order ordering, which consumers rely on, while allowing parallelism across orders. It gives up global ordering, which no requirement needs.

Alternatives considered

  • Synchronous orchestration. Simpler to trace, but places every downstream dependency on the checkout path and multiplies their failure rates into it.
  • Distributed transactions (two-phase commit). Atomic across resources in principle, but poorly supported by event logs and external APIs, and blocking when the coordinator fails.
  • Change data capture instead of a relay. Reads the database’s replication log rather than polling. It is a strong option with lower latency and less load on the database, but it adds infrastructure. It is a reasonable next step if relay polling becomes a bottleneck.

Trade-offs

GainedPaid
Checkout isolated from downstream failuresDownstream state is eventually consistent
No lost or phantom eventsAn extra component (relay) and an outbox table to maintain
Independent scaling and deployment of consumersDebugging spans services; tracing becomes mandatory
Replayable history for recoveryEvent schemas become long-lived contracts that must be versioned

Cost considerations

The largest new cost is operating the event log, whether managed or self-hosted. Partitions, retention period, and replication factor drive that cost. Retaining events for seven days rather than indefinitely bounds storage while still allowing replay after most incidents. The outbox table must be pruned once records are published, or it grows without limit.

Limitations

  • The design does not address inventory reservation, which needs stronger consistency and is a study of its own.
  • Cross-order business rules, such as fraud limits per customer, are not naturally expressed per partition.
  • Numbers in this study are assumptions. A real design would validate them with load testing.

Lessons learned

  • Moving work off the synchronous path is the most effective availability improvement available, because availability multiplies across serial dependencies.
  • Reliability in event-driven systems comes from accepting duplicates and designing for them, not from trying to prevent them.
  • The outbox pattern trades a small amount of latency for removing an entire class of consistency bugs.

References

Sources are listed at the end of this page.

Diagram

Search covers published writing, architecture studies, research, projects, and profile pages.