Skip to main content

System Design: Notification Service with Spring Boot and Kafka (Email, SMS, Push)

Build a notification service with Spring Boot 4.2 and Kafka: fan-out by user preference, per-channel templates, rate-limited workers, non-blocking retries with a dead-letter topic and idempotent delivery. Every number comes from a real test run on an embedded broker.

You have a working app. An order ships, a one-time password is requested, a new user signs up, and each of those has to reach a person by email, SMS or a phone notification. The first version is a method call inside the code that handles the event: emailClient.send(...), then smsClient.send(...). It works until the SMS provider takes four seconds to answer, or returns a 503, or until marketing sends 50,000 messages and your OTP texts are stuck behind them. A notification service pulls that job out of the apps and gives it a queue. The apps say “tell this user about this event” and move on; the service decides which channels the user allows, writes the message, sends it at a pace the provider accepts, tries again when the provider is having a bad moment, and keeps the messages it could not deliver. This article builds that service with Spring Boot and Kafka, small enough to run on a laptop and honest enough that every number and log line below came from a real test run. The code is in the notification-service module of the java-interview-lab repository. Kafka runs inside the test JVM, so ./scripts/run-all.sh is the only command you need. If you are preparing for interviews, this is the shape of answer to “design a notification system”; the URL shortener walkthrough is a companion in the same style.
Versions tested. JDK 25.0.5.1 (Temurin, LTS), Spring Boot 4.2.0 and Spring for Apache Kafka 4.2.0 (both timestamped 19 November 2026 on Maven Central), Apache Kafka clients and embedded broker 4.4.0 (managed by Boot, timestamped 6 October 2026 on Maven Central), Jackson 3.1.8 (tools.jackson), Maven 3.9.11. Versions were read from maven-metadata.xml and mvn dependency:tree, not from blog posts. The Spring Kafka reference pages still showed 4.2.0-M1 when I checked, so every API name below was confirmed with javap on the real jar or by compiling it.

A notification service is four small problems, not one big one

Before any code, here is the whole idea. A request enters over HTTP and is written to a Kafka topic, which is a durable, ordered log that other programs read at their own pace. A fan-out step reads each request, looks up what the user allows, and writes one ready-to-send message per channel to that channel’s own topic. A worker per channel reads its topic and calls the provider.
ProducerPOST /api/notificationsKafka topicnotification.requestsFanOutServicepreferences + templatesnotify.emailnotify.smsnotify.pushEmailWorker, SmsWorker, PushWorkerlimit, dedupe, sendProvidersSES, Twilio, FCM (simulated)Producers name a user and a template. Only FanOutService knows about channels,so adding a channel never touches a producer.
The diagram shows two things to hold on to. First, the caller gets its answer as soon as the request is on Kafka; delivery happens afterwards, which is why a slow SMS gateway does not slow down checkout. Second, there is one topic per channel. If the SMS provider is down, SMS messages pile up on notify.sms and email keeps flowing, because the workers are independent. The producer’s message names a user and a template, never a channel. This is the record, and the controller that accepts it (NotificationRequest.java, NotificationController.java):
public record NotificationRequest(String requestId, String userId, String templateId, Map<String, String> params) {
}
    @PostMapping("/api/notifications")
    public ResponseEntity<Map<String, String>> accept(@RequestBody NotificationRequest request) {
        String requestId = request.requestId() != null ? request.requestId() : UUID.randomUUID().toString();
        NotificationRequest withId = new NotificationRequest(requestId, request.userId(), request.templateId(), request.params());
        kafka.send(Topics.REQUESTS, withId.userId(), json.writeValueAsString(withId)).join();
        return ResponseEntity.status(HttpStatus.ACCEPTED).body(Map.of("requestId", requestId));
    }
The requestId is the caller’s own idempotency key. If the caller does not send one the controller makes one up, but a caller that retries after a timeout needs to send the same id both times; the idempotency section shows why. The user id is the Kafka key, so all of one user’s messages go to the same partition and stay in order. The ordering section near the end shows where that promise quietly breaks.
Why Kafka and not a database table or a plain thread pool? (intermediate)

A thread pool inside one app loses everything on a restart and cannot be shared by five apps. A database table as a queue works for small volumes, and plenty of systems start there, but you end up writing polling, locking and cleanup yourself. Kafka gives you the three things this service leans on: messages survive a restart, consumers read at their own speed and remember their position, and several instances of the same worker can split a topic between them.

The cost is real: a broker to run and a new failure mode, delivery that happens at least once. A message can arrive twice, and the service has to be built so that is harmless. The Kafka interview questions post covers partitions, consumer groups and delivery guarantees if those terms are new.

Going deeper

Fan-out: decide the channels once, in one place

Fan-out answers one question per message: which channels, and what text on each? It asks four things in order. Does the user exist? Does the template exist? Has the user opted in to this channel, and do they have an address for it? Does the template have a body for this channel? Every “no” is recorded as a skip with a reason, not thrown as an error, because retrying a message for a user who opted out of SMS will never make it deliverable (FanOutService.java).
    @KafkaListener(id = "fan-out", topics = Topics.REQUESTS)
    public void onRequest(String payload) {
        NotificationRequest request = json.readValue(payload, NotificationRequest.class);

        Optional<UserProfile> user = users.find(request.userId());
        if (user.isEmpty()) {
            log.record(request.requestId(), null, Outcome.SKIPPED, Topics.REQUESTS, "unknown user " + request.userId());
            return;
        }
        Optional<Template> template = templates.find(request.templateId());
        if (template.isEmpty()) {
            log.record(request.requestId(), null, Outcome.SKIPPED, Topics.REQUESTS, "unknown template " + request.templateId());
            return;
        }

        for (Channel channel : Channel.values()) {
            if (!user.get().optedIn().contains(channel)) {
                skip(request, channel, "user has not opted in");
                continue;
            }
            String body = template.get().bodies().get(channel);
            if (body == null) {
                skip(request, channel, "template " + request.templateId() + " has no " + channel + " body");
                continue;
            }
            String address = user.get().addressFor(channel);
            if (address == null) {
                skip(request, channel, "user has no " + channel + " address");
                continue;
            }
            String rendered;
            try {
                rendered = TemplateEngine.render(body, request.params());
            } catch (MissingParameterException e) {
                skip(request, channel, e.getMessage());
                continue;
            }
            ChannelMessage message = new ChannelMessage(request.requestId(), request.userId(), channel, address, rendered);
            log.record(request.requestId(), channel, Outcome.FANNED_OUT, Topics.REQUESTS, "publishing to " + channel.topic());
            // join(): wait for the broker's ack. If the publish fails the exception reaches the listener container,
            // the request is redelivered, and the channel workers' idempotency check absorbs the duplicates.
            kafka.send(channel.topic(), request.userId(), json.writeValueAsString(message)).join();
        }
    }
Five requests went through it in 03-fan-out.txt. The first is the happy path, the second is a user who has a phone number but never opted in to SMS:
1. user opted in to all three, template has all three  (order-shipped)
  EMAIL FANNED_OUT      notification.requests        publishing to notify.email
  EMAIL SENT            notify.email                 attempt 1
  SMS   FANNED_OUT      notification.requests        publishing to notify.sms
  SMS   SENT            notify.sms                   attempt 1
  PUSH  FANNED_OUT      notification.requests        publishing to notify.push
  PUSH  SENT            notify.push                  attempt 1
2. user has a phone number but has not opted in to SMS
  EMAIL FANNED_OUT      notification.requests        publishing to notify.email
  EMAIL SENT            notify.email                 attempt 1
  SMS   SKIPPED         notification.requests        user has not opted in
  PUSH  FANNED_OUT      notification.requests        publishing to notify.push
  PUSH  SENT            notify.push                  attempt 1
The one-time-password template has only an SMS body, so even a user who opted in everywhere gets one message, not three. And when a template parameter is missing, every channel is skipped rather than sending a half-filled message:
3. otp template only has an SMS body, so only SMS goes out
  EMAIL SKIPPED         notification.requests        template otp has no EMAIL body
  SMS   FANNED_OUT      notification.requests        publishing to notify.sms
  SMS   SENT            notify.sms                   attempt 1
  PUSH  SKIPPED         notification.requests        template otp has no PUSH body
5. params missing: every channel skipped, nothing half-rendered is sent
  EMAIL SKIPPED         notification.requests        no value for {{orderId}}
  SMS   SKIPPED         notification.requests        no value for {{orderId}}
  PUSH  SKIPPED         notification.requests        no value for {{orderId}}
Opt-in is checked at fan-out, not at send time. That is deliberate: the decision is made once, from one place, using the preferences as they were when the request arrived. The price is that a user who opts out a second after the request was fanned out still receives that one message. For marketing mail that window matters; for an OTP it does not.
What the fan-out step does when Kafka itself fails (intermediate)

The publish call ends in .join(), which waits for the broker’s acknowledgement. If it fails, the exception leaves the listener, Spring Kafka redelivers the request, and fan-out runs again from the top. If the first run had already published two of three channel messages, those two get published a second time. That is acceptable only because the workers drop duplicates, which is the subject of the duplicates section below. The design is “redelivery is safe”, not “redelivery never happens”.

The log entry for each channel is written before the publish, so its position relative to the worker’s SENT entry is stable. I first wrote it after the publish and the transcripts showed SENT before FANNED_OUT on some runs, because the worker is quick enough to win the race. That was a flaw in the exhibit, not in the service, and it cost one rerun to spot.

Going deeper

  • Quiet hours, digest batching and per-category opt-outs all belong in this step; the shape is another check in the loop above.
  • The preference store here is the in-memory UserDirectory.java; in production it is a table with a cache in front, and the loop only needs find(userId).

Templates: one id, one body per channel

An SMS has a few hundred characters to work with, an email has room for a paragraph, a push notification is one line. So a template is an id plus a body per channel, and the producer only ever names the id. The engine is deliberately tiny: it replaces {{name}} with a value and refuses to continue if a value is missing (TemplateEngine.java).
    public static String render(String template, Map<String, String> params) {
        Matcher m = PLACEHOLDER.matcher(template);
        StringBuilder out = new StringBuilder();
        while (m.find()) {
            String name = m.group(1);
            String value = params.get(name);
            if (value == null) {
                throw new MissingParameterException("no value for {{" + name + "}}");
            }
            m.appendReplacement(out, Matcher.quoteReplacement(value));
        }
        m.appendTail(out);
        return out.toString();
    }
From 01-templates.txt, the same event rendered three ways, and what a missing value does:
EMAIL ( 61 chars) Hi Asha, your order A-1042 has shipped and arrives on 27 Nov.
SMS   ( 33 chars) Order A-1042 shipped. ETA 27 Nov.
PUSH  ( 32 chars) Asha, order A-1042 is on its way

A template with no body for a channel never goes out on it (otp has only SMS):
otp channels: [SMS]

A missing parameter is an error, not an empty string:
MissingParameterException: no value for {{eta}}
A missing value is an error, never an empty string. “Order shipped. ETA .” is worse than no message, because it looks like a bug in your product. The engine throws, fan-out skips the channel and records why, and the exception type is marked non-retryable in the next section, because retrying cannot invent the missing value.
Escaping, localisation and real template engines (intermediate)

There is no HTML escaping here, and an email body built from user-supplied values needs it; this engine is for plain text. For HTML email, render with Thymeleaf or similar and keep the per-channel structure. Localisation multiplies the table: one body per channel per language, with the user’s locale chosen at fan-out.

The unit test also checks that a value containing $ or a backslash survives, because Matcher.appendReplacement treats those specially unless the value goes through Matcher.quoteReplacement. It is the kind of bug that appears only when a customer’s name or an amount contains a dollar sign.

Going deeper

Delivery workers: what happens when the provider has a bad day

Providers fail in two different ways, and the service has to treat them differently. A transient failure (a timeout, a 503, a 429 “slow down”) will probably work if you try again in a moment. A permanent failure (an invalid phone number, an unregistered device) will fail the same way forever, so retrying only wastes the provider’s time and delays everything behind it. Spring Kafka’s @RetryableTopic handles the waiting without blocking: instead of sleeping inside the consumer, it moves the failed message to a retry topic that is read after a delay, and the main topic carries on. After the last attempt the message lands on a dead-letter topic (DLT) where it can be inspected and replayed. Here is the whole SMS worker (SmsWorker.java); the email and push workers differ only in the channel name:
@Component
public class SmsWorker extends ChannelWorker {

    public SmsWorker(FaultInjector faults, RateLimiters limiters, IdempotencyStore idempotency, DeliveryLog log,
                      JsonMapper json) {
        super(new SimulatedProvider(Channel.SMS, faults), limiters, idempotency, log, json);
    }

    @RetryableTopic(attempts = "4", numPartitions = "3",
            backOff = @BackOff(delay = 250, multiplier = 2.0),
            exclude = {PermanentProviderException.class, MissingParameterException.class})
    @KafkaListener(id = "sms-worker", topics = Topics.SMS)
    public void onMessage(ConsumerRecord<String, String> record) throws InterruptedException {
        handle(record);
    }

    @DltHandler
    public void onDead(ConsumerRecord<String, String> record) {
        handleDead(record);
    }
}
notify.smsattempt 1sms-retry-250attempt 2sms-retry-500attempt 3sms-retry-1000attempt 4notify.sms-dltneeds a humanfailsfailsfailsfailsPermanentProviderException: no retries, one attempt, straight to the DLTEach retry topic is a waiting room: 250 ms, 500 ms, 1000 ms. While a message waits there, the main topic keeps moving.
The diagram is the topology Spring Kafka built from that annotation: four attempts in total, with waits of 250 ms, 500 ms and 1000 ms between them, and a dashed shortcut for permanent errors. The exceptions listed in exclude are the ones that skip retrying. The test script makes the fake provider fail on demand (RetryTest.java):
        faults.failTransiently(flaky, 2);   // fails twice, the third attempt succeeds
        faults.failPermanently(rejected);   // invalid destination: retrying cannot help
        faults.failTransiently(down, 100);  // provider outage: every attempt fails

        publish(flaky, u, "otp", Map.of("code", "111111"));
        publish(rejected, u, "otp", Map.of("code", "222222"));
        publish(down, u, "otp", Map.of("code", "333333"));
The three outcomes, from 04-retries-and-dlt.txt. Read the topic column: it shows the message moving from topic to topic.
1. provider times out twice, then works
  SMS   FANNED_OUT      notification.requests        publishing to notify.sms
  SMS   ATTEMPT_FAILED  notify.sms                   attempt 1: TransientProviderException
  SMS   ATTEMPT_FAILED  notify.sms-retry-250         attempt 2: TransientProviderException
  SMS   SENT            notify.sms-retry-500         attempt 3
2. provider says the number is invalid (permanent): no retries
  SMS   FANNED_OUT      notification.requests        publishing to notify.sms
  SMS   ATTEMPT_FAILED  notify.sms                   attempt 1: PermanentProviderException
  SMS   DEAD_LETTERED   notify.sms-dlt               needs a human or a replay tool
3. provider is down for the whole window: all attempts used
  SMS   FANNED_OUT      notification.requests        publishing to notify.sms
  SMS   ATTEMPT_FAILED  notify.sms                   attempt 1: TransientProviderException
  SMS   ATTEMPT_FAILED  notify.sms-retry-250         attempt 2: TransientProviderException
  SMS   ATTEMPT_FAILED  notify.sms-retry-500         attempt 3: TransientProviderException
  SMS   ATTEMPT_FAILED  notify.sms-retry-1000        attempt 4: TransientProviderException
  SMS   DEAD_LETTERED   notify.sms-dlt               needs a human or a replay tool
In the first case the message is sent on attempt 3 from the 500 ms retry topic. In the second there is exactly one attempt, then the dead-letter topic, with no waiting. In the third every attempt is used and the message ends up on notify.sms-dlt. The topics Spring Kafka created for this are in 09-topics.txt:
  notification.requests
  notify.email
  notify.email-dlt
  notify.email-retry-1000
  notify.email-retry-250
  notify.email-retry-500
  notify.push
  notify.push-dlt
  notify.push-retry-1000
  notify.push-retry-250
  notify.push-retry-500
  notify.sms
  notify.sms-dlt
  notify.sms-retry-1000
  notify.sms-retry-250
  notify.sms-retry-500
A compile error taught me where the backoff annotation lives. I wrote the first version of the worker from memory with org.springframework.retry.annotation.Backoff, the spring-retry class older Spring Kafka examples use. The compiler said the package does not exist. In Spring Kafka 4.2 @RetryableTopic.backOff() returns org.springframework.kafka.annotation.BackOff, which javap on the jar confirms. If you are copying a 3.x snippet, that import is the first thing to change.
What @RetryableTopic really creates, and what a dead letter is for (intermediate)

Each distinct delay gets its own topic, named with the delay in milliseconds: notify.sms-retry-250, -500, -1000. That is why the topic list above has three retry topics per channel, plus -dlt. The wait happens on the retry topic’s consumer, not the main one; the ordering test below shows a later message being sent while an earlier one is still waiting. I did not trace the pausing mechanism itself.

The dead-letter handler here (@DltHandler) only logs the event. A real one would alert, store the payload with its failure reason, and be paired with a small tool or endpoint that replays a dead letter once the underlying problem is fixed. A dead-letter topic nobody watches is the same as dropping the message, only slower.

The delays used here are demo-sized so the tests finish in seconds. Production values are minutes, not milliseconds, and should be longer than your provider’s typical outage blip.

Going deeper

Duplicates are normal, so make them harmless

Kafka promises at least once, not exactly once. A message can be delivered twice if a consumer restarts after processing but before recording its position, if a rebalance moves a partition, or, in this service, if fan-out is redelivered half-way through. Nobody wants two OTP texts or two “your order shipped” emails, so before calling the provider the worker asks whether this request has already been delivered on this channel.
copy 1: r-42SMScopy 2: r-42SMSWorkerseen r-42:SMS before?Provider callonce, then mark deliveredDUPLICATE: nothing sentThe key is the request id plus the channel, not the request id alone: one request legitimately produces onedelivery per channel.
The key is the request id plus the channel. One request legitimately produces one delivery per channel, so the request id alone would wrongly suppress the push notification after the email went out. The store itself is small (IdempotencyStore.java), and the check sits at the top of the shared worker logic (ChannelWorker.java):
@Component
public class IdempotencyStore {
    private final Set<String> delivered = ConcurrentHashMap.newKeySet();

    public boolean alreadyDelivered(String requestId, Channel channel) {
        return delivered.contains(key(requestId, channel));
    }

    public void markDelivered(String requestId, Channel channel) {
        delivered.add(key(requestId, channel));
    }

    private static String key(String requestId, Channel channel) {
        return requestId + ":" + channel;
    }
}
    protected void handle(ConsumerRecord<String, String> record) throws InterruptedException {
        ChannelMessage message = json.readValue(record.value(), ChannelMessage.class);
        Channel channel = provider.channel();

        if (idempotency.alreadyDelivered(message.requestId(), channel)) {
            log.record(message.requestId(), channel, Outcome.DUPLICATE, record.topic(), "already delivered, nothing sent");
            return;
        }
        int attempt = log.count(message.requestId(), channel, Outcome.ATTEMPT_FAILED) + 1;
        limiters.acquire(channel);
        try {
            provider.send(message);
        } catch (RuntimeException e) {
            log.record(message.requestId(), channel, Outcome.ATTEMPT_FAILED, record.topic(),
                    "attempt " + attempt + ": " + e.getClass().getSimpleName());
            throw e;
        }
        idempotency.markDelivered(message.requestId(), channel);
        log.record(message.requestId(), channel, Outcome.SENT, record.topic(), "attempt " + attempt);
    }
The test publishes the same request twice. 05-idempotency.txt shows both copies reached each worker and only one called the provider:
       FANNED_OUT       SENT  DUPLICATE
EMAIL           2          1          1
PUSH            2          1          1
There is still a small window, and this test does not close it. The worker calls the provider and then marks the pair as delivered. If the process dies between those two lines, the message is redelivered and sent again. Marking first would swap that for the opposite failure, a message that is recorded as delivered but never was. Between “occasionally twice” and “occasionally never”, notifications pick twice. If the provider offers its own idempotency key, pass the request id to it and the window closes. This is reasoning about the code above, not something the test run demonstrates.
Making the store survive restarts and scale out (intermediate)

A ConcurrentHashMap set forgets everything on restart and is not shared between instances, so two instances of the SMS worker could each send the same message. In production the store is shared and expires old entries: a Redis SET key value NX EX seconds, or an insert into a table with a unique constraint. The idempotency keys post builds that for HTTP APIs with Redis and Postgres, and the same ideas apply here.

Keep the expiry longer than the longest delay a message can spend in retry topics, otherwise a late retry of an already-delivered message finds an empty store.

Going deeper

Rate limits: the provider’s number, not yours

SMS gateways and email providers cap how fast you may send, and exceeding the cap gets you throttled or blocked. The limit therefore sits in the worker, per channel, using a token bucket: a bucket holds a few tokens (the burst), refills at a steady rate, and every send takes one. If the bucket is empty the worker waits. The rate limiter low-level design post compares the other algorithms; this one is the simplest to reason about and test.
t = 0+50 ms+100+150+200+250Sends 1 to 5 use the burst: no wait.After the burst the bucket refills at 20 tokens a second, so send 6 waits 50 ms, send 7 waits 100 ms, and so on.
The picture is the output of the test below: a burst of five goes out immediately, and after that one send every 50 ms, which is 20 a second. The class keeps the maths apart from the sleeping: reserve() returns how long to wait, and acquire() sleeps for it (TokenBucket.java). Splitting them lets the tests use a fake clock.
    /** Takes a token now (possibly going negative) and returns how many nanoseconds the caller must wait first. */
    public synchronized long reserve() {
        long now = nanoClock.getAsLong();
        tokens = Math.min(burst, tokens + (now - lastRefill) / 1e9 * ratePerSecond);
        lastRefill = now;
        tokens -= 1;
        return tokens >= 0 ? 0 : (long) (-tokens / ratePerSecond * 1e9);
    }

    public void acquire() throws InterruptedException {
        long wait = reserve();
        if (wait > 0) {
            TimeUnit.NANOSECONDS.sleep(wait);
        }
    }
02-token-bucket.txt is that class on a fake clock: ten sends at the same instant, then ten idle seconds:
10 sends requested at the same instant (t = 0):
  send  1 waits   0 ms
  send  2 waits   0 ms
  send  3 waits   0 ms
  send  4 waits   0 ms
  send  5 waits   0 ms
  send  6 waits  50 ms
  send  7 waits 100 ms
  send  8 waits 150 ms
  send  9 waits 200 ms
  send 10 waits 250 ms

After the queue drains and the clock idles for 10 seconds the bucket refills, but only to the burst size:
  next 7 sends wait (ms): [0, 0, 0, 0, 0, 50, 100]
The real thing, with real Kafka and real threads, is 06-rate-limit.txt. Twenty-five SMS were published at once against a 20-per-second limit with a burst of 5:
messages sent          : 25
rate limit             : 20 per second, burst 5
theoretical minimum    : (25 - 5) / 20 = 1.0 s
assertion              : elapsed >= 900 ms
elapsed (indicative)   : about 1.3 s  (varies from run to run)
The test asserts only the floor, 900 ms, because that is a property of the limiter. The elapsed figure is indicative and will differ on your machine.
Where this limiter is too simple (intermediate)

Each instance has its own bucket, so ten instances of the worker allow ten times the limit. Either divide the limit by the instance count, or move the bucket to Redis, which is what the Bucket4j and Redis post does. The worker also waits by sleeping inside the consumer thread. That is fine for short waits; a long wait holds the partition and can exceed Kafka’s max.poll.interval.ms, which makes the broker think the consumer died. I did not test that boundary here.

Retries consume tokens too: every attempt, including the failed ones, goes through acquire in the shared worker logic above. That is the right behaviour, because the provider counts failed calls against you.

Going deeper

What retries do to ordering

Earlier I said messages for one user stay in order because they share a Kafka key. That is true inside one topic. A retry moves a message to a different topic, and a different topic has its own timeline.
notify.smsfirst: attempt 1 failssecond: SENTsms-retry-250first: waits 250 msfirst: SENT (attempt 2)Published first, second. Delivered second, first. Kafka guarantees order inside one topic partition; a retry topic is adifferent topic, so that guarantee stops at the point where a message takes the detour.
The test publishes two SMS for the same user, first then second, and makes the first one fail once. The second goes out while the first is waiting in its 250 ms retry topic. From 07-retry-reorders.txt:
published order : first, second (same user, so same key and same partition)
delivered order : second, first

first  (one transient failure)
  SMS   FANNED_OUT      notification.requests        publishing to notify.sms
  SMS   ATTEMPT_FAILED  notify.sms                   attempt 1: TransientProviderException
  SMS   SENT            notify.sms-retry-250         attempt 2

second (no failures)
  SMS   FANNED_OUT      notification.requests        publishing to notify.sms
  SMS   SENT            notify.sms                   attempt 1
The test asserts that the second was sent before the first, so this is not a lucky run. For “your order shipped” followed by “your order was delivered”, arriving in the wrong order is a visible bug.
Retry topics trade ordering for throughput. If order matters for a class of messages, either put a sequence number in the message and let the receiving side discard stale ones, or use blocking retries for that class, which stall the partition so nothing overtakes. Blocking retries are the right choice when each message depends on the previous one and the volume is low; non-blocking retries are right when a single sick message must not hold up thousands of healthy ones.

Going deeper

Run it end to end

One HTTP test posts a request and waits for the deliveries, which is the path a real producer takes. 08-http-end-to-end.txt:
POST /api/notifications
  {"requestId":"<requestId>","userId":"<userId>","templateId":"welcome","params":{"name":"Asha"}}
HTTP 202
  {"requestId":"<requestId>"}

what happened afterwards
  EMAIL FANNED_OUT      notification.requests        publishing to notify.email
  EMAIL SENT            notify.email                 attempt 1
  SMS   SKIPPED         notification.requests        user has not opted in
  PUSH  FANNED_OUT      notification.requests        publishing to notify.push
  PUSH  SENT            notify.push                  attempt 1
Every test shares one embedded Kafka broker (KRaft, inside the test JVM) through a common base class (AbstractKafkaTest.java), so there is nothing to install:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EmbeddedKafka(partitions = 3, bootstrapServersProperty = "spring.kafka.bootstrap-servers")
abstract class AbstractKafkaTest {
To regenerate every transcript in this article (run-all.sh):
./scripts/run-all.sh
The test output is noisy at the end. When the embedded broker shuts down it logs KafkaStorageException and NoSuchFileException while its temp directory is deleted. It happens after the tests have passed and does not affect the result.
Running against a real broker (intermediate)

The application’s application.yaml points at localhost:9092. Start any Kafka 4.x broker there, run mvn spring-boot:run, and the four main topics and twelve retry and dead-letter topics are created on startup. The preference store starts empty, so a real run needs a UserProfile saved first, otherwise the request is logged as SKIPPED: unknown user. I tested only against the embedded broker.

Going deeper

Should you build this yourself?

Probably only the parts that are yours. Sending is a solved problem: email, SMS and push providers handle delivery, bounces and device tokens, and some offer templates and rate limits too. What a notification service adds is the part that is specific to your product: preferences, template choice, ordering rules, and one place to look when a customer says they never got the message. If you have one app and one channel, call the provider directly and add the queue when you feel the pain. If you have several producers, several channels, or a provider that sometimes falls over, this shape is worth having. What this module does not cover: a persistent preference store, a shared idempotency store, multi-instance rate limiting, delivery receipts and bounce handling, and a replay tool for the dead-letter topic. Those are most of the production work.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.