Relay's Notification Pipeline, End to End: Outbox, Kafka, Redis and a Dead-Letter Topic
Ticket 3 moves to IN_PROGRESS, RESOLVED and CLOSED, and the customer gets exactly three e-mails. Along the way Kafka is stopped, the RESOLVED event reaches the notifier twice, a sent row is replayed, and a plain-text message is tried three times and parked. The fix found while recording: the dead-letter topic is ticket-events-dlt.
What you will learn
- Trace one status change from a PATCH call to an e-mail through the outbox, Kafka and a notifier
- Make the outbox writer refuse to run outside a transaction with Propagation.MANDATORY
- Share outbox rows between API copies with for update skip locked, and keep the order when Kafka is down
- Send each e-mail once with a Redis SET NX key, and park unreadable messages with DefaultErrorHandler and DeadLetterPublishingRecoverer
Before you start
- Spring Application Events and the Transactional Outbox: Three Designs, Two Failures
- Kafka 4 with Spring: Topics, Partitions, Offsets and Consumer Groups
- Retries, Dead-Letter Topics and Idempotency with Spring Kafka
The last few lectures each built one piece on a small demo app: the outbox, Kafka, Redis, retries and a dead-letter topic. Here they're joined on Relay, the support desk. When an agent changes a ticket's status, the customer gets an e-mail. One e-mail per change, even when Kafka is down, even when a message arrives twice. This article follows one ticket through all of it, and then breaks it on purpose.
Running it
Relay v2.0 has a compose profile called events that adds Kafka, Redis, Mailpit (a fake mail server with a web inbox) and a separate notifier service:
docker compose --profile events up --build -d
After that, docker compose ps listed api, db, kafka, mailpit, redis and web, all healthy except web and notifier, which have no health check. The notifier's log showed partitions assigned: [ticket-events-0, ticket-events-1, ticket-events-2]. (The recording ran on shifted ports because another Relay stack was using 3000 and 8080.)
The API itself never reads from Kafka. The listener, and even the topic creation, only switch on with relay.notifier.enabled=true, which the notifier service sets. So the API starts fine with no Kafka at all.
Step 1: the event is a row, written in the ticket's transaction
At the end of TicketService.patch, if the status really changed, the service publishes an application event:
if (ticket.getStatus() != from) {
events.publishEvent(TicketEvent.statusChanged(ticket, from, displayName(ticket.getLastModifiedBy())));
}
TicketEvent is a record with its own eventId (a UUID) and everything the e-mail needs, so the notifier never has to read the ticket table. A listener saves it:
@EventListener
@Transactional(propagation = Propagation.MANDATORY) // no transaction around the change? then fail loudly
public void on(TicketEvent event) {
jdbc.sql("""
insert into outbox_event (event_id, topic, message_key, payload)
values (:eventId, :topic, :key, :payload)""")
.param("eventId", event.eventId())
.param("topic", EventsConfig.TICKET_EVENTS)
.param("key", String.valueOf(event.ticketId())) // same ticket, same partition, same order
.param("payload", json.writeValueAsString(event))
.update();
}
A plain @EventListener runs on the same thread, inside the caller's transaction. That's exactly what we want here: the new status and the outbox row commit together. Propagation.MANDATORY is a guard. If someone ever publishes this event outside a transaction, the insert throws instead of quietly saving a row on its own. The message key is the ticket id, so every event for ticket 3 lands in the same partition, in order.
PATCH /api/tickets/3 with {"status":"IN_PROGRESS"} answered {"id":3,"status":"IN_PROGRESS","version":1}, and outbox_event had row 1: key 3, to IN_PROGRESS, sent, 1 attempt.
Step 2: the relay sends it
@Scheduled(fixedDelayString = "${relay.outbox.relay-delay:1000}")
public void tick() {
if (Instant.now().isBefore(pausedUntil)) {
return;
}
relayOnce();
}
Every second, relayOnce opens a transaction and selects up to 50 unsent rows, oldest first:
select id, topic, message_key, payload from outbox_event
where sent_at is null order by id limit :batch
for update skip locked
for update locks the rows it picks. skip locked tells a second copy of the API to skip rows another copy already has, instead of waiting for them. With two API instances, each row is taken by one of them.
For each row, the relay sends to Kafka and then waits for the broker's answer with .get(10, TimeUnit.SECONDS). Only then does it set sent_at. For row 1 the API log said outbox: sent 1 event(s) to Kafka.
Step 3: the notifier e-mails once
@KafkaListener(id = "notifier", topics = EventsConfig.TICKET_EVENTS)
public void on(String payload) {
TicketEvent event = json.readValue(payload, TicketEvent.class);
log.info("notifier got event {} for ticket {}: {} -> {}",
event.eventId(), event.ticketId(), event.from(), event.to());
notifier.handle(event);
}
Before sending, Notifier.handle asks whether this event id is new. That list lives in Redis:
@Override
public boolean firstTime(UUID eventId) {
return Boolean.TRUE.equals(redis.opsForValue().setIfAbsent(key(eventId), "sent", KEEP));
}
setIfAbsent is Redis SET key value NX EX: write the key only if it doesn't exist, with an expiry. It's one command, so of two copies of the same event only the first gets true. KEEP is seven days.
The notifier's log showed notifier got event 8ff47316-... for ticket 3: OPEN -> IN_PROGRESS and then the e-mail line. Mailpit's inbox had [Relay #3] Your ticket is now In progress. In Redis, the key relay:notified:8ff47316-... had a TTL of 604797 seconds, a few seconds under seven days.
There's one difference from the database version in the retries lecture. There, the stored id and the work shared a transaction, so a failure rolled the id back. Redis isn't in that transaction, so the notifier undoes it by hand:
try {
mail.send(message(event));
} catch (RuntimeException e) {
processed.forget(event.eventId()); // let the retry (or the dead-letter replay) send it
meters.counter("relay.notifications", "result", "failed").increment();
throw e;
}
Break it 1: Kafka is down
docker compose stop kafka, then PATCH ticket 3 to RESOLVED. The API still answered {"id":3,"status":"RESOLVED","version":2}. The change is safe in PostgreSQL, and so is the event:
id | key | to | sent | attempts | last_error
----+-----+-------------+------+----------+------------------------
1 | 3 | IN_PROGRESS | t | 1 |
2 | 3 | RESOLVED | f | 1 | TimeoutException: null
The API log said outbox: 1 event(s) waiting, Kafka did not take row 2 (TimeoutException: null). Next try in 30 s. On a failure the relay records the error, sets pausedUntil 30 seconds ahead, and breaks out of the loop. Breaking matters: it never sends a newer row before an older one, so the customer can't get "Closed" before "Resolved".
docker compose start kafka. 20.6 seconds later the row was sent, with 2 attempts, and the inbox had both e-mails: In progress and Resolved.
Break it 2: the same event twice
Without being asked, the RESOLVED event reached the notifier twice: the notifier log has two IN_PROGRESS -> RESOLVED lines, and the second was skipped as already handled, no second e-mail. The send that timed out while Kafka was down was delivered after all, and then the relay sent the row again on its next try. A timeout isn't proof that Kafka never got the record. This is why the notifier must be idempotent even with an outbox.
Then on purpose: update outbox_event set sent_at = null where id = 1 makes the relay send the IN_PROGRESS event again. The notifier logged event 8ff47316-... for ticket 3 was already handled, no second e-mail, and Mailpit's total was still 2.
Break it 3: a message nobody can read
Straight into the topic with Kafka's console producer: this is not json. json.readValue fails on every try. The notifier's error handler decides what happens next:
@Bean
CommonErrorHandler kafkaErrorHandler(KafkaOperations<String, String> kafka) {
var toDeadLetter = new DeadLetterPublishingRecoverer(kafka);
return new DefaultErrorHandler(toDeadLetter, new FixedBackOff(2000, 3));
}
FixedBackOff(2000, 3) means three more tries, two seconds apart. The log had three "Record in retry" lines at 22:01:52.484, 22:01:54.507 and 22:01:56.531. Then DeadLetterPublishingRecoverer published the record to the dead-letter topic. kafka-get-offsets.sh on ticket-events-dlt showed one record, in partition 2, and reading it back gave this is not json, the text intact. These retries are blocking, unlike the retry topics in the last lecture: the partition waits while they happen. But they're short, and afterwards the line moves on. Closing ticket 3 next sent the third e-mail, [Relay #3] Your ticket is now Closed.
The bug found while recording
Relay v2.0 declared a topic called ticket-events.DLT with one partition, and nothing ever landed in it. Spring for Apache Kafka 4 names the dead-letter topic <topic>-dlt, and by default it publishes to the same partition number the failed record came from. So messages went to an automatically created ticket-events-dlt. The fix declares that name, with three partitions like ticket-events:
public static final String TICKET_EVENTS_DLT = "ticket-events-dlt";
@Bean
NewTopic ticketEventsDlt() {
return TopicBuilder.name(TICKET_EVENTS_DLT).partitions(3).replicas(1).build();
}
Check the actual topic name in the broker rather than trusting the one in your config.
At the end
Three status changes, three e-mails, oldest first: In progress, Resolved, Closed. The outbox had three rows, all sent. Row 1 shows 2 attempts because it was replayed, and row 2 shows 2 attempts and the timeout from when Kafka was down. One unreadable message sat in the dead-letter topic, and it didn't block the e-mail after it.
| What went wrong | What caught it |
|---|---|
| Kafka stopped | the outbox row waited; the relay paused 30 s and kept the order |
| An event delivered twice | Redis SET NX on the event id |
| A message that can't be read | three retries, then ticket-events-dlt |
Common mistakes
- Marking a row sent before Kafka answers. Wait for the send's result, then update the row.
- Sending the next row after one failed. The customer then reads the changes out of order.
- Keeping the "already sent" key when the mail fails. With Redis outside the transaction, delete it so the retry can work.
- Declaring a dead-letter topic by a name you guessed. Check where messages really land, and give it as many partitions as the source topic.
Try it yourself
Stop Kafka and change ticket 3's status twice in a row. How many rows wait in outbox_event, and in what order do the e-mails arrive once Kafka is back?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
