Extracting a Notifications Service From a Spring Boot Monolith: One Kafka Event as the Contract, No Database, and a Test Built From a Real Message
Relay's notifier was the API jar started a second time with a database it never used. As relay-notifications it reads the same TicketEvent from Kafka in the same consumer group, with 0 database settings. The API loses 47 lines and gains 3 comments, 7 tests pass without Docker, and with the service stopped a status change still answers HTTP 200 in 0.12 s.
What you will learn
- Move a Kafka listener out of a monolith into its own Spring Boot service without changing the API's events
- Keep the service's own copy of the event record so nothing is shared at build time
- Keep the same consumer group so the new service carries on where the old one stopped
- Write a contract test from a message read off the real topic, and show an outage delays the e-mail without losing it
Before you start
- Spring Boot and Spring for Apache Kafka basics
- Docker Compose
- Service boundaries and data ownership
The first piece to leave Relay, the support desk app, is notifications. The reasons are in service boundaries and data ownership: no other file uses the package, and it needs only one event. This article does the move and keeps three ideas in view: one event, no database, and a contract test.
Today: the API jar, started twice
Relay's API saves a ticket and writes a TicketEvent to the Kafka topic ticket-events. The notifier reads it and sends the e-mail. But look at how the notifier is deployed in the starter's compose.yaml:
notifier:
# the same jar as the API, with the "notifier" Spring profile: reads ticket-events, sends the e-mail
build: ./relay-api
profiles: [events]
environment:
SPRING_PROFILES_ACTIVE: notifier
SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/relay
KAFKA_BOOTSTRAP: kafka:9092
REDIS_HOST: redis
MAIL_HOST: mailpit
MAIL_PORT: 1025
It is the API jar again, switched on by a profile, with a database URL it never uses. To change one line of an e-mail, you rebuild and redeploy the whole API.
Its own config, no database
# Relay's notifications service. No database: everything an e-mail needs is inside the TicketEvent.
spring:
application:
name: relay-notifications
kafka:
bootstrap-servers: ${KAFKA_BOOTSTRAP:localhost:9092}
consumer:
auto-offset-reset: earliest
data:
redis:
host: ${REDIS_HOST:localhost}
mail:
host: ${MAIL_HOST:localhost}
port: ${MAIL_PORT:1025}
server:
port: 8081
auto-offset-reset: earliest means a brand new group starts from the oldest event on the topic. Redis remembers which events were already sent. The check for a database:
$ grep -c -i -E "datasource|jpa|postgres" relay-notifications/pom.xml relay-notifications/src/main/resources/application.yaml
relay-notifications/pom.xml:0
relay-notifications/src/main/resources/application.yaml:0
The service keeps its own copy of the event
/**
* The contract: the JSON Relay puts on the ticket-events topic. This is the service's own copy of it,
* so nothing here depends on Relay's code. The contract test checks it against a real message.
*/
public record TicketEvent(
UUID eventId,
String type,
long ticketId,
String subject,
Status from,
Status to,
String customerName,
String customerEmail,
String changedBy,
Instant occurredAt) {
public static final String STATUS_CHANGED = "STATUS_CHANGED";
}
Ten fields with the same names as the JSON on the topic, and Status is copied as its own four-value enum. There is no import from Relay, so the API and this service build and release on their own.
The listener moved, not rewritten
/** The listener id is also the consumer group: "notifier", the same group the old in-process notifier used. */
public static class TicketEventListener {
...
@KafkaListener(id = "notifier", topics = TICKET_EVENTS)
public void on(String payload) {
TicketEvent event = json.readValue(payload, TicketEvent.class);
log.info("notifications got event {} for ticket {}: {} -> {}",
event.eventId(), event.ticketId(), event.from(), event.to());
notifier.handle(event);
}
}
Same topic and same group, so Kafka knows which events the old notifier already handled, and the new service carries on from there. The Notifier class that sends the mail moved over unchanged. A failing message is retried three more times, 2 seconds apart, then parked on ticket-events-dlt by a DefaultErrorHandler.
The API only loses code
From relay-api go the notify package, its test, its YAML file and the mail and Redis dependencies only it used:
$ diff -r ../starter/relay-api relay-api | grep -c "^<"
47
$ diff -r ../starter/relay-api relay-api | grep -c "^>"
3
The three added lines are comments that now name the notifications service. No Java was added to the API, and its events are exactly the same.
A real message becomes the test
With only the API, Kafka and Mailpit running, an agent moves ticket 3 to in progress:
$ curl -s -X PATCH localhost:18602/api/tickets/3 -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"status":"IN_PROGRESS"}' | jq -c "{id, status}"
{"id":3,"status":"IN_PROGRESS"}
That message is read straight off the topic with kafka-console-consumer.sh and saved as src/test/resources/contract/status-changed.json:
{
"eventId": "b48aa57c-7313-4edf-a876-88c872164ca7",
"type": "STATUS_CHANGED",
"ticketId": 3,
"subject": "How do I export my data to CSV?",
"from": "OPEN",
"to": "IN_PROGRESS",
"customerName": "Olivia Bennett",
"customerEmail": "[email protected]",
"changedBy": "Liam Foster",
"occurredAt": "2026-11-18T02:04:11.795409109Z"
}
Mailpit has zero e-mails at this point, because nobody sends them yet. The event just waits in Kafka. The contract test reads the fixture:
/** status-changed.json is a message copied from Relay's ticket-events topic. If Relay changes it, this fails first. */
class TicketEventContractTest {
...
@Test
void everyFieldOfTheRecordIsInTheMessage() throws IOException {
JsonNode message = message();
var fields = Arrays.stream(TicketEvent.class.getRecordComponents()).map(c -> c.getName()).toList();
assertThat(message.propertyNames()).containsAll(fields);
}
@Test
void theMessageReadsIntoTheRecord() throws IOException {
TicketEvent event = json.treeToValue(message(), TicketEvent.class);
assertThat(event.type()).isEqualTo(TicketEvent.STATUS_CHANGED);
assertThat(event.to()).isNotNull();
assertThat(event.customerEmail()).contains("@");
}
}
$ mvn -B test 2>&1 | grep -E "Tests run:|BUILD"
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
Two contract tests plus the five Notifier tests that moved with the code, and none of them needs Docker. A renamed field or a new status shows up here first.
Start it, then stop it on purpose
$ docker compose --profile events up --build -d notifications
$ docker compose logs notifications --no-log-prefix | grep -o "e-mail sent to .*"
e-mail sent to olivia.bennett@example.com: ticket 3 is now IN_PROGRESS
Mailpit now has one e-mail, "[Relay #3] Your ticket is now In progress". The event waited in Kafka while the service did not exist. Now the reason for all this:
$ docker compose stop notifications
$ curl -s -o /dev/null -w "HTTP %{http_code} after %{time_total} s\n" -X PATCH localhost:18602/api/tickets/7 -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"status":"IN_PROGRESS"}'
HTTP 200 after 0.119335 s
$ curl -s localhost:18625/api/v1/messages | jq -r ".total, .messages[].Subject"
1
[Relay #3] Your ticket is now In progress
$ docker compose start notifications
$ curl -s localhost:18625/api/v1/messages | jq -r ".total, .messages[].Subject"
2
[Relay #7] Your ticket is now In progress
[Relay #3] Your ticket is now In progress
With notifications down, the API still answered in 0.12 seconds. When the service came back, it picked up the waiting event. The e-mail was late, and it was not lost. Getting that event onto Kafka safely in the first place is the job of the transactional outbox, and how several consumers share the topic is in the event-driven ticket flow.
Recap
| Check | Result |
|---|---|
| Database settings in the new service | 0 in the pom, 0 in the YAML |
| Change to the API | 47 lines removed, 3 comment lines added, events unchanged |
| Tests | 7 run, 0 failures, no Docker |
| Service stopped | API answers HTTP 200 in 0.12 s; the e-mail arrives after restart |
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
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.
