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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
kafkaTemplate.sendis 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
outboxtable. 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.BuilderandWebClient.Builderadd W3Ctraceparentheaders through Micrometer Tracing. A client made withRestClient.create()does not. - Kafka observation is off by default:
spring.kafka.template.observation-enabled=trueandspring.kafka.listener.observation-enabled=true. - Trace and span ids go into the MDC. The log pattern or structured logging must include them.
@Asyncand hand-made executors need context propagation. Boot's defaultmanagement.tracing.sampling.probabilityis 0.1, so most requests have no trace. Boot 4 hasspring-boot-starter-opentelemetryto 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
- What can go wrong when a method saves an order and publishes an event?
- How does the outbox pattern fix it?
- The trace stops at Kafka. How do you find the delay and fix tracing?
- 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 voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.