Publish and consume events asynchronously with Kafka. Compare @Async, publishing directly after the database write, and the transactional outbox with an idempotent consumer.
Problem
When an order is placed, the Inventory and Notification services must react. The order must never be lost, the event must never be published for an order that was rolled back, and consumers must cope with duplicates and poison messages.
Approach 1: In-process @Async event (feasible, lossy)
Fast and simple, but the work lives only in memory: a crash or deployment loses it, and other services never see it.
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
record OrderPlacedEvent(String eventId, String orderId, long totalPaise) {}
@Service
class InMemoryOrderService {
private final ApplicationEventPublisher events;
InMemoryOrderService(ApplicationEventPublisher events) { this.events = events; }
void place(String orderId, long total) {
// ... save order ...
events.publishEvent(new OrderPlacedEvent(java.util.UUID.randomUUID().toString(), orderId, total));
}
}
@Component
class InMemoryNotifier {
@Async
@EventListener
public void on(OrderPlacedEvent event) { /* send email: lost if the JVM dies first */ }
}Approach 2: Save, then KafkaTemplate.send (the dual-write problem)
Durable and cross-service, but the DB commit and the Kafka send are two separate operations: a crash between them loses the event, and sending inside the transaction can publish an event for an order that then rolls back.
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
class DualWriteOrderService {
private final KafkaTemplate<String, OrderPlacedEvent> kafka;
DualWriteOrderService(KafkaTemplate<String, OrderPlacedEvent> kafka) { this.kafka = kafka; }
@Transactional
public void place(String orderId, long total) {
// ordersRepository.save(...);
kafka.send("order-events", orderId, new OrderPlacedEvent(java.util.UUID.randomUUID().toString(), orderId, total));
// if the transaction rolls back after this line, consumers still see the event
}
}Approach 3: Transactional outbox + idempotent consumer + dead-letter topic (optimal)
The order and an outbox row commit atomically; a relay publishes unsent rows (or Debezium CDC reads the database log). Delivery is at least once, so the consumer records processed event ids in the same transaction as its own changes. Failing messages are retried with backoff, then sent to a DLT.
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
@Entity
class OutboxEvent {
@Id String id;
String aggregateId;
String type;
@Column(length = 4000) String payload;
Instant createdAt;
Instant publishedAt;
protected OutboxEvent() {}
OutboxEvent(String aggregateId, String type, String payload) {
this.id = UUID.randomUUID().toString();
this.aggregateId = aggregateId;
this.type = type;
this.payload = payload;
this.createdAt = Instant.now();
}
}
interface OutboxRepository extends JpaRepository<OutboxEvent, String> {
List<OutboxEvent> findTop100ByPublishedAtIsNullOrderByCreatedAt();
}
@Entity
class ProcessedMessage {
@Id String eventId;
Instant processedAt = Instant.now();
protected ProcessedMessage() {}
ProcessedMessage(String eventId) { this.eventId = eventId; }
}
interface ProcessedMessageRepository extends JpaRepository<ProcessedMessage, String> {}import java.time.Instant;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.backoff.ExponentialBackOff;
@Service
class OutboxOrderService {
private final OutboxRepository outbox;
OutboxOrderService(OutboxRepository outbox) { this.outbox = outbox; }
@Transactional // order + outbox row commit together, or neither
public void place(String orderId, long totalPaise) {
// ordersRepository.save(new Order(orderId, totalPaise));
outbox.save(new OutboxEvent(orderId, "OrderPlaced", "{\"orderId\":\"" + orderId + "\",\"totalPaise\":" + totalPaise + "}"));
}
}
@Component
class OutboxRelay {
private final OutboxRepository outbox;
private final KafkaTemplate<String, String> kafka;
OutboxRelay(OutboxRepository outbox, KafkaTemplate<String, String> kafka) { this.outbox = outbox; this.kafka = kafka; }
@Scheduled(fixedDelay = 500)
@Transactional
public void publish() {
for (OutboxEvent e : outbox.findTop100ByPublishedAtIsNullOrderByCreatedAt()) {
kafka.send("order-events", e.aggregateId, e.payload).join(); // key keeps per-order ordering
e.publishedAt = Instant.now(); // a crash here means a re-send: consumers dedupe
}
}
}
@Component
class InventoryOrderListener {
private final ProcessedMessageRepository processed;
InventoryOrderListener(ProcessedMessageRepository processed) { this.processed = processed; }
@KafkaListener(topics = "order-events", groupId = "inventory")
@Transactional
public void on(ConsumerRecord<String, String> record) {
String eventId = record.topic() + "-" + record.partition() + "-" + record.offset(); // or an id header from the producer
if (processed.existsById(eventId)) return; // duplicate delivery: already handled
// reserve stock for record.key() ...
processed.save(new ProcessedMessage(eventId)); // same transaction as the side effect
}
}
@Configuration
class KafkaErrorHandlingConfig {
@Bean
DefaultErrorHandler kafkaErrorHandler(KafkaTemplate<Object, Object> template) {
ExponentialBackOff backOff = new ExponentialBackOff(500, 2.0);
backOff.setMaxElapsedTime(10_000);
return new DefaultErrorHandler(new DeadLetterPublishingRecoverer(template), backOff); // then order-events.DLT
}
}Feasible → optimal
@Asyncevents: in-memory only; fine for non-critical, same-service side effects.- Save then
send: durable but inconsistent (dual write). - Outbox + idempotent consumer + DLT: no lost or phantom events, safe duplicates, poison messages isolated: the production pattern. Debezium CDC can replace the polling relay for lower latency.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related: how do you keep events for one order in sequence while scaling consumers?
Use the order id as the message key so all its events go to one partition (ordered), and scale consumers up to the partition count. Inside a consumer, process each partition's records sequentially; for more parallelism, a key-ordered parallel consumer can process different keys concurrently.
Related: request/reply over Kafka, or synchronous REST?
Prefer REST/gRPC when the caller needs an answer now. If you must do request/reply over Kafka (for example to cross a network boundary), Spring Kafka's ReplyingKafkaTemplate correlates replies by a header, but you take on timeouts and reply-topic management; usually the better design is fire-and-forget events plus a read model the caller can query.