Skip to the page

Spring microservices · senior

The outbox pattern and distributed tracing

A database write and a message are two systems, so one can fail alone. Use an outbox row in the same transaction. Tracing needs propagation to be set up on every hop.

The notes

What you must know

  • kafkaTemplate.send is asynchronous and not part of the database transaction. If a later step throws, the order rolls back but the event may already be out.
  • An HTTP call inside the transaction also holds a database connection while it waits.
  • Outbox: in the same database transaction insert a row into an outbox table. A relay (a scheduled job or change data capture) publishes it and marks it sent.
  • @TransactionalEventListener(phase = AFTER_COMMIT) alone is not enough: a crash after the commit loses the event.
  • At-least-once delivery means consumers must be idempotent: store processed event ids or upsert by order id and version. Inventory goes through events or a saga with compensation.
  • HTTP tracing: Boot's auto-configured RestClient.Builder and WebClient.Builder add W3C traceparent headers through Micrometer Tracing. A client made with RestClient.create() does not.
  • Kafka observation is off by default: spring.kafka.template.observation-enabled=true and spring.kafka.listener.observation-enabled=true.
  • Trace and span ids go into the MDC. The log pattern or structured logging must include them. @Async and hand-made executors need context propagation. Boot's default management.tracing.sampling.probability is 0.1, so most requests have no trace. Boot 4 has spring-boot-starter-opentelemetry to export over OTLP.

The red pen

Common traps: mistake → fix

  • Mistake: A Kafka send inside @Transactional is rolled back with the database

    Fix: it is not part of that transaction.

  • Mistake: Tracing works everywhere after adding a starter

    Fix: each client and listener must be instrumented.

  • Mistake: AFTER_COMMIT listeners are safe

    Fix: a crash after the commit loses the event.

Easy to hard

Questions interviewers ask, easy to hard

  1. What can go wrong when a method saves an order and publishes an event?
  2. How does the outbox pattern fix it?
  3. The trace stops at Kafka. How do you find the delay and fix tracing?
  4. Why must consumers be idempotent?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview