Add notification-service module: Kafka fan-out by user preference, per-channel templates, rate-limited workers, non-blocking retries with DLT, idempotent delivery (10 tests on embedded Kafka, 9 transcripts)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7rAEgiNi4Fo94nVoB
This commit is contained in:
Claude
2026-11-24 00:30:04 +05:30
parent ce12a80f58
commit 09f875ddd9
54 changed files with 1516 additions and 0 deletions
+70
View File
@@ -0,0 +1,70 @@
# notification-service
Runnable companion code for ankurm.com's **System Design: Notification Service with Spring Boot and Kafka (Email, SMS, Push)**.
One HTTP call becomes a Kafka message; a fan-out step applies the user's preferences and renders a template per channel; one
worker per channel delivers it with a rate limit, non-blocking retries and a dead-letter topic. Providers are simulated, and Kafka
runs **inside the test JVM** (KRaft via `spring-kafka-test`), so there is nothing to install except JDK 25 and Maven.
## Versions
| Component | Version | Verified against |
|---|---|---|
| JDK | **25.0.5.1+2** (Temurin, LTS) | `java -version` |
| Spring Boot | **4.2.0** | `maven-metadata.xml` on Maven Central (GA, no `-M`/`-RC`) |
| Spring for Apache Kafka | **4.2.0** | `mvn dependency:tree` |
| Apache Kafka clients / embedded broker | **4.4.0** | `mvn dependency:tree` (managed by Boot 4.2.0) |
| Jackson | **3.1.8** (`tools.jackson`) | `mvn dependency:tree` |
| Maven | 3.9.11 | `mvn -v` |
## Quickstart
```bash
export JAVA_HOME=/path/to/jdk-25 && export PATH="$JAVA_HOME/bin:$PATH"
cd notification-service
./scripts/run-all.sh # runs all 10 tests and regenerates every file in output/
```
The first Maven run must be online so the plugins are cached; `-o` works afterwards. The test run prints a lot of
embedded-broker shutdown noise (`KafkaStorageException ... NoSuchFileException` while the broker's temp directory is deleted);
it is harmless and happens after the tests have passed.
To run the service against a real broker, start Kafka on `localhost:9092` and `mvn spring-boot:run`, then
`POST /api/notifications` with `{"requestId":"r-1","userId":"u-1","templateId":"welcome","params":{"name":"Asha"}}`.
The in-memory `UserDirectory` starts empty, so save a `UserProfile` first (the tests show how), otherwise the request is
logged as `SKIPPED: unknown user`.
## How the pieces fit
| Class | Job |
|---|---|
| `NotificationController` | `POST /api/notifications` &rarr; publish to `notification.requests`, answer `202` |
| `FanOutService` | read a request, check preferences and template, publish one rendered `ChannelMessage` per allowed channel |
| `TemplateRegistry`, `TemplateEngine` | one template id, one body per channel, `{{placeholder}}` substitution |
| `UserDirectory`, `UserProfile` | preferences and contact points (in-memory stand-in for a table) |
| `EmailWorker`, `SmsWorker`, `PushWorker` | one `@RetryableTopic` listener per channel, plus the `@DltHandler` |
| `ChannelWorker` | shared delivery logic: dedupe, wait for a rate-limit token, call the provider, log |
| `TokenBucket`, `RateLimiters` | per-channel limit with a testable clock |
| `IdempotencyStore` | remembers delivered `(requestId, channel)` pairs |
| `FaultInjector`, `SimulatedProvider` | scripted provider failures, transient or permanent |
| `DeliveryLog` | append-only event list that every transcript is built from |
## Captured output (`output/`)
Every file is written by a JUnit test that asserts the same facts it prints.
| File | What it shows |
|---|---|
| `01-templates.txt` | one template, three channel bodies, missing-parameter error |
| `02-token-bucket.txt` | burst of 5 then 20/s, on a fake clock |
| `03-fan-out.txt` | preferences, template coverage, unknown user, bad parameters |
| `04-retries-and-dlt.txt` | transient failures retried, permanent ones not, outage ends in the DLT |
| `05-idempotency.txt` | same `requestId` twice, one delivery |
| `06-rate-limit.txt` | 25 SMS against a 20/s limit (timing is indicative) |
| `07-retry-reorders.txt` | a retried message is overtaken by a later one |
| `08-http-end-to-end.txt` | HTTP `202`, then the deliveries |
| `09-topics.txt` | the retry and dead-letter topics Spring Kafka created |
## What this module deliberately is not
In-memory preferences, in-memory idempotency and a single JVM: the code shows the shape, not the storage. See the article for what
changes in production (a shared idempotency store, a preference service, per-partition limits across instances).
@@ -0,0 +1,12 @@
Template rendering: one template id, one body per channel
=========================================================
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}}
@@ -0,0 +1,17 @@
Token bucket: 20 tokens/second, burst 5, fake clock
===================================================
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]
@@ -0,0 +1,31 @@
Fan-out: one request in, one message per allowed channel out
============================================================
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
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
4. unknown user
- SKIPPED notification.requests unknown user u-ghost
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}}
@@ -0,0 +1,21 @@
Retries and the dead-letter topic (SMS channel, 4 attempts, 250 ms doubling)
============================================================================
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
@@ -0,0 +1,10 @@
Idempotency: the same requestId published twice
===============================================
one request, published twice, user opted in to EMAIL and PUSH (not SMS)
FANNED_OUT SENT DUPLICATE
EMAIL 2 1 1
PUSH 2 1 1
The provider was called once per channel; the second copy was recognised and dropped.
@@ -0,0 +1,8 @@
Per-channel rate limit: 25 SMS at once, gateway allows 20/s with burst 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)
@@ -0,0 +1,14 @@
Ordering: Kafka orders a partition, retry topics do not
=======================================================
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
@@ -0,0 +1,14 @@
HTTP in, Kafka in the middle, providers at the end
==================================================
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
+19
View File
@@ -0,0 +1,19 @@
Topics that exist after startup (internal topics hidden)
========================================================
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
+78
View File
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm.interviewlab</groupId>
<artifactId>notification-service</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>java-interview-lab :: notification-service</name>
<description>
Runnable companion code for ankurm.com's "System Design: Notification Service with Spring Boot and Kafka" article:
fan-out by user preferences, templates, per-channel workers, non-blocking retries with a dead-letter topic,
per-channel rate limits and idempotent delivery, all tested against an in-JVM Kafka broker.
</description>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot.version>4.2.0</spring-boot.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<argLine>-Xmx768m -Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# Regenerates every file in output/. Needs JDK 25 and Maven; the first Maven run must be online.
# Each file is written by a JUnit test that asserts the same facts it prints, so a claim in the article
# fails the build the moment it stops being true. Kafka runs inside the test JVM: no Docker, no ZooKeeper.
set -euo pipefail
cd "$(dirname "$0")/.."
rm -f output/*.txt
mkdir -p output
mvn -B -q -T1 test
echo "done:"; ls -1 output
@@ -0,0 +1,18 @@
package com.ankurm.interviewlab.notification;
/** The three delivery channels. Each one owns a Kafka topic, so a slow SMS gateway cannot stall email. */
public enum Channel {
EMAIL(Topics.EMAIL),
SMS(Topics.SMS),
PUSH(Topics.PUSH);
private final String topic;
Channel(String topic) {
this.topic = topic;
}
public String topic() {
return topic;
}
}
@@ -0,0 +1,8 @@
package com.ankurm.interviewlab.notification;
/**
* One fully rendered message for exactly one channel. By the time it exists, the preference check and the
* template rendering are done, so a channel worker only has to deliver it.
*/
public record ChannelMessage(String requestId, String userId, Channel channel, String address, String body) {
}
@@ -0,0 +1,8 @@
package com.ankurm.interviewlab.notification;
/** The edge of the system: SES / Twilio / FCM in real life, a simulator here. */
public interface ChannelProvider {
Channel channel();
void send(ChannelMessage message);
}
@@ -0,0 +1,53 @@
package com.ankurm.interviewlab.notification;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import tools.jackson.databind.json.JsonMapper;
/**
* The delivery logic shared by the three channels: dedupe, wait for a rate-limit token, call the provider.
* Subclasses only add the Kafka annotations, because {@code @RetryableTopic} and {@code @DltHandler} are
* per-class and each channel needs its own retry topics and dead-letter topic.
*/
abstract class ChannelWorker {
private final ChannelProvider provider;
private final RateLimiters limiters;
private final IdempotencyStore idempotency;
private final DeliveryLog log;
private final JsonMapper json;
ChannelWorker(ChannelProvider provider, RateLimiters limiters, IdempotencyStore idempotency, DeliveryLog log,
JsonMapper json) {
this.provider = provider;
this.limiters = limiters;
this.idempotency = idempotency;
this.log = log;
this.json = json;
}
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);
}
protected void handleDead(ConsumerRecord<String, String> record) {
ChannelMessage message = json.readValue(record.value(), ChannelMessage.class);
log.record(message.requestId(), provider.channel(), Outcome.DEAD_LETTERED, record.topic(),
"needs a human or a replay tool");
}
}
@@ -0,0 +1,8 @@
package com.ankurm.interviewlab.notification;
/**
* @param channel null for events that happen before fan-out picks channels (unknown user, unknown template)
* @param topic the Kafka topic the record was read from, which is how retries become visible
*/
public record DeliveryEvent(String requestId, Channel channel, Outcome outcome, String topic, String detail, long nanos) {
}
@@ -0,0 +1,29 @@
package com.ankurm.interviewlab.notification;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.stereotype.Component;
/** Append-only record of everything that happened. Production would use metrics and a table; here it is a list. */
@Component
public class DeliveryLog {
private final List<DeliveryEvent> events = new CopyOnWriteArrayList<>();
public void record(String requestId, Channel channel, Outcome outcome, String topic, String detail) {
events.add(new DeliveryEvent(requestId, channel, outcome, topic, detail, System.nanoTime()));
}
public List<DeliveryEvent> forRequest(String requestId) {
return events.stream().filter(e -> e.requestId().equals(requestId)).toList();
}
public List<DeliveryEvent> forRequest(String requestId, Channel channel) {
return events.stream()
.filter(e -> e.requestId().equals(requestId) && e.channel() == channel)
.toList();
}
public int count(String requestId, Channel channel, Outcome outcome) {
return (int) forRequest(requestId, channel).stream().filter(e -> e.outcome() == outcome).count();
}
}
@@ -0,0 +1,32 @@
package com.ankurm.interviewlab.notification;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.BackOff;
import org.springframework.kafka.annotation.DltHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.RetryableTopic;
import org.springframework.stereotype.Component;
import tools.jackson.databind.json.JsonMapper;
/** Delivers EMAIL messages. Four attempts in total, 250 ms then 500 ms then 1 s between them, then the dead-letter topic. */
@Component
public class EmailWorker extends ChannelWorker {
public EmailWorker(FaultInjector faults, RateLimiters limiters, IdempotencyStore idempotency, DeliveryLog log,
JsonMapper json) {
super(new SimulatedProvider(Channel.EMAIL, faults), limiters, idempotency, log, json);
}
@RetryableTopic(attempts = "4", numPartitions = "3",
backOff = @BackOff(delay = 250, multiplier = 2.0),
exclude = {PermanentProviderException.class, MissingParameterException.class})
@KafkaListener(id = "email-worker", topics = Topics.EMAIL)
public void onMessage(ConsumerRecord<String, String> record) throws InterruptedException {
handle(record);
}
@DltHandler
public void onDead(ConsumerRecord<String, String> record) {
handleDead(record);
}
}
@@ -0,0 +1,78 @@
package com.ankurm.interviewlab.notification;
import java.util.Optional;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import tools.jackson.databind.json.JsonMapper;
/**
* Step one of the pipeline. Reads "tell user U about event E", looks up the user's preferences and the
* template, and publishes one rendered message per allowed channel. It never talks to a provider.
*/
@Service
public class FanOutService {
private final UserDirectory users;
private final TemplateRegistry templates;
private final KafkaTemplate<String, String> kafka;
private final JsonMapper json;
private final DeliveryLog log;
public FanOutService(UserDirectory users, TemplateRegistry templates, KafkaTemplate<String, String> kafka,
JsonMapper json, DeliveryLog log) {
this.users = users;
this.templates = templates;
this.kafka = kafka;
this.json = json;
this.log = log;
}
@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();
}
}
private void skip(NotificationRequest request, Channel channel, String reason) {
log.record(request.requestId(), channel, Outcome.SKIPPED, Topics.REQUESTS, reason);
}
}
@@ -0,0 +1,37 @@
package com.ankurm.interviewlab.notification;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.stereotype.Component;
/**
* Lets a test script a provider's bad day: "fail the next 2 sends of request X with a transient error",
* "always reject request Y as permanent". Real providers cannot be asked to fail on cue; this can.
*/
@Component
public class FaultInjector {
private record Fault(boolean permanent, AtomicInteger remaining) {
}
private final Map<String, Fault> faults = new ConcurrentHashMap<>();
public void failTransiently(String requestId, int times) {
faults.put(requestId, new Fault(false, new AtomicInteger(times)));
}
public void failPermanently(String requestId) {
faults.put(requestId, new Fault(true, new AtomicInteger(Integer.MAX_VALUE)));
}
void maybeFail(String requestId) {
Fault fault = faults.get(requestId);
if (fault == null || fault.remaining().getAndDecrement() <= 0) {
return;
}
if (fault.permanent()) {
throw new PermanentProviderException("provider rejected " + requestId + " (invalid destination)");
}
throw new TransientProviderException("provider timeout for " + requestId);
}
}
@@ -0,0 +1,27 @@
package com.ankurm.interviewlab.notification;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Component;
/**
* Remembers which (requestId, channel) pairs were delivered. Kafka gives at-least-once delivery, so the same
* message can arrive twice (a rebalance, a retried fan-out, a producer that retried). This is what makes the
* second arrival harmless. In production: a Redis SETNX with a TTL, or a unique-key insert.
*/
@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;
}
}
@@ -0,0 +1,8 @@
package com.ankurm.interviewlab.notification;
/** A {{placeholder}} had no value. Retrying cannot fix this, so it is never retried. */
public class MissingParameterException extends RuntimeException {
public MissingParameterException(String message) {
super(message);
}
}
@@ -0,0 +1,11 @@
package com.ankurm.interviewlab.notification;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class NotificationApplication {
public static void main(String[] args) {
SpringApplication.run(NotificationApplication.class, args);
}
}
@@ -0,0 +1,31 @@
package com.ankurm.interviewlab.notification;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.TopicBuilder;
/** Declares the four main topics. Retry and dead-letter topics are created by {@code @RetryableTopic} itself. */
@Configuration
class NotificationConfig {
@Bean
NewTopic requestsTopic() {
return TopicBuilder.name(Topics.REQUESTS).partitions(Topics.PARTITIONS).replicas(1).build();
}
@Bean
NewTopic emailTopic() {
return TopicBuilder.name(Topics.EMAIL).partitions(Topics.PARTITIONS).replicas(1).build();
}
@Bean
NewTopic smsTopic() {
return TopicBuilder.name(Topics.SMS).partitions(Topics.PARTITIONS).replicas(1).build();
}
@Bean
NewTopic pushTopic() {
return TopicBuilder.name(Topics.PUSH).partitions(Topics.PARTITIONS).replicas(1).build();
}
}
@@ -0,0 +1,31 @@
package com.ankurm.interviewlab.notification;
import java.util.Map;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import tools.jackson.databind.json.JsonMapper;
/** The only synchronous part: accept the request, put it on Kafka, answer 202. Delivery happens later. */
@RestController
public class NotificationController {
private final KafkaTemplate<String, String> kafka;
private final JsonMapper json;
public NotificationController(KafkaTemplate<String, String> kafka, JsonMapper json) {
this.kafka = kafka;
this.json = json;
}
@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));
}
}
@@ -0,0 +1,15 @@
package com.ankurm.interviewlab.notification;
import java.util.Map;
/**
* What a producer (order service, auth service, marketing job) sends. It names a user and a template,
* never a channel: choosing channels is the notification service's job, using the user's preferences.
*
* @param requestId idempotency key chosen by the caller; the same id twice means "same notification"
* @param userId the recipient, also the Kafka key, so one user's messages stay in order
* @param templateId which template to render
* @param params values for the template's {{placeholders}}
*/
public record NotificationRequest(String requestId, String userId, String templateId, Map<String, String> params) {
}
@@ -0,0 +1,17 @@
package com.ankurm.interviewlab.notification;
/** What happened to one (request, channel) pair at one moment. The delivery log is a list of these. */
public enum Outcome {
/** The rendered message was published to the channel topic. */
FANNED_OUT,
/** The fan-out step decided not to send (no user, no template, opted out, no address, bad params). */
SKIPPED,
/** The provider call failed; Spring Kafka will route the record to the next retry topic or the DLT. */
ATTEMPT_FAILED,
/** The provider accepted the message. */
SENT,
/** The same requestId and channel had already been delivered, so nothing was sent. */
DUPLICATE,
/** Retries are over (or the error was permanent): the record landed on the dead-letter topic. */
DEAD_LETTERED
}
@@ -0,0 +1,8 @@
package com.ankurm.interviewlab.notification;
/** Provider said no and will keep saying no: invalid phone number, unregistered device token. Never retried. */
public class PermanentProviderException extends RuntimeException {
public PermanentProviderException(String message) {
super(message);
}
}
@@ -0,0 +1,32 @@
package com.ankurm.interviewlab.notification;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.BackOff;
import org.springframework.kafka.annotation.DltHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.RetryableTopic;
import org.springframework.stereotype.Component;
import tools.jackson.databind.json.JsonMapper;
/** Delivers PUSH messages. Four attempts in total, 250 ms then 500 ms then 1 s between them, then the dead-letter topic. */
@Component
public class PushWorker extends ChannelWorker {
public PushWorker(FaultInjector faults, RateLimiters limiters, IdempotencyStore idempotency, DeliveryLog log,
JsonMapper json) {
super(new SimulatedProvider(Channel.PUSH, faults), limiters, idempotency, log, json);
}
@RetryableTopic(attempts = "4", numPartitions = "3",
backOff = @BackOff(delay = 250, multiplier = 2.0),
exclude = {PermanentProviderException.class, MissingParameterException.class})
@KafkaListener(id = "push-worker", topics = Topics.PUSH)
public void onMessage(ConsumerRecord<String, String> record) throws InterruptedException {
handle(record);
}
@DltHandler
public void onDead(ConsumerRecord<String, String> record) {
handleDead(record);
}
}
@@ -0,0 +1,28 @@
package com.ankurm.interviewlab.notification;
import java.util.EnumMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* One token bucket per channel. The numbers are what the provider contract allows (an SMS gateway might allow 20
* messages a second, an email provider 50), not what we would like to send.
*/
@Component
public class RateLimiters {
private final Map<Channel, TokenBucket> buckets = new EnumMap<>(Channel.class);
public RateLimiters(@Value("${notification.rate.email:50}") double email,
@Value("${notification.rate.sms:20}") double sms,
@Value("${notification.rate.push:200}") double push,
@Value("${notification.rate.burst:5}") int burst) {
buckets.put(Channel.EMAIL, new TokenBucket(email, burst, System::nanoTime));
buckets.put(Channel.SMS, new TokenBucket(sms, burst, System::nanoTime));
buckets.put(Channel.PUSH, new TokenBucket(push, burst, System::nanoTime));
}
public void acquire(Channel channel) throws InterruptedException {
buckets.get(channel).acquire();
}
}
@@ -0,0 +1,22 @@
package com.ankurm.interviewlab.notification;
/** A provider that succeeds unless the {@link FaultInjector} says otherwise. One instance per channel. */
public class SimulatedProvider implements ChannelProvider {
private final Channel channel;
private final FaultInjector faults;
public SimulatedProvider(Channel channel, FaultInjector faults) {
this.channel = channel;
this.faults = faults;
}
@Override
public Channel channel() {
return channel;
}
@Override
public void send(ChannelMessage message) {
faults.maybeFail(message.requestId());
}
}
@@ -0,0 +1,32 @@
package com.ankurm.interviewlab.notification;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.BackOff;
import org.springframework.kafka.annotation.DltHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.RetryableTopic;
import org.springframework.stereotype.Component;
import tools.jackson.databind.json.JsonMapper;
/** Delivers SMS messages. Four attempts in total, 250 ms then 500 ms then 1 s between them, then the dead-letter topic. */
@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);
}
}
@@ -0,0 +1,7 @@
package com.ankurm.interviewlab.notification;
import java.util.Map;
/** One body per channel, because an SMS has 160 characters to work with and an email does not. */
public record Template(String id, Map<Channel, String> bodies) {
}
@@ -0,0 +1,28 @@
package com.ankurm.interviewlab.notification;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Replaces {{name}} with a value. Deliberately tiny: no loops, no conditionals, no HTML escaping logic. */
public final class TemplateEngine {
private static final Pattern PLACEHOLDER = Pattern.compile("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*}}");
private TemplateEngine() {
}
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();
}
}
@@ -0,0 +1,24 @@
package com.ankurm.interviewlab.notification;
import java.util.Map;
import java.util.Optional;
import org.springframework.stereotype.Component;
/** Templates keyed by id. A template that has no body for a channel simply never goes out on that channel. */
@Component
public class TemplateRegistry {
private final Map<String, Template> templates = Map.of(
"order-shipped", new Template("order-shipped", Map.of(
Channel.EMAIL, "Hi {{name}}, your order {{orderId}} has shipped and arrives on {{eta}}.",
Channel.SMS, "Order {{orderId}} shipped. ETA {{eta}}.",
Channel.PUSH, "{{name}}, order {{orderId}} is on its way")),
"otp", new Template("otp", Map.of(
Channel.SMS, "{{code}} is your verification code. It expires in 5 minutes.")),
"welcome", new Template("welcome", Map.of(
Channel.EMAIL, "Welcome {{name}}! Your account is ready.",
Channel.PUSH, "Welcome {{name}}")));
public Optional<Template> find(String id) {
return Optional.ofNullable(templates.get(id));
}
}
@@ -0,0 +1,41 @@
package com.ankurm.interviewlab.notification;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
/**
* Token bucket: holds up to {@code burst} tokens, refills at {@code ratePerSecond}. A send needs one token.
* {@link #reserve()} never blocks; it says how long the caller must wait, which keeps the maths testable with
* a fake clock. {@link #acquire()} is the blocking wrapper the channel workers use.
*/
public final class TokenBucket {
private final double ratePerSecond;
private final double burst;
private final LongSupplier nanoClock;
private double tokens;
private long lastRefill;
public TokenBucket(double ratePerSecond, int burst, LongSupplier nanoClock) {
this.ratePerSecond = ratePerSecond;
this.burst = burst;
this.nanoClock = nanoClock;
this.tokens = burst;
this.lastRefill = nanoClock.getAsLong();
}
/** 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);
}
}
}
@@ -0,0 +1,14 @@
package com.ankurm.interviewlab.notification;
/** Topic names and the one place partitions are decided. */
public final class Topics {
/** What producers publish: "tell user U about event E". Channel-agnostic. */
public static final String REQUESTS = "notification.requests";
public static final String EMAIL = "notify.email";
public static final String SMS = "notify.sms";
public static final String PUSH = "notify.push";
public static final int PARTITIONS = 3;
private Topics() {
}
}
@@ -0,0 +1,8 @@
package com.ankurm.interviewlab.notification;
/** Provider hiccup: timeout, 503, 429. Worth retrying. */
public class TransientProviderException extends RuntimeException {
public TransientProviderException(String message) {
super(message);
}
}
@@ -0,0 +1,23 @@
package com.ankurm.interviewlab.notification;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Component;
/**
* In-memory stand-in for the preference store. In production this is a table or a cache in front of one;
* the fan-out code only needs {@link #find(String)}, so swapping it changes nothing else.
*/
@Component
public class UserDirectory {
private final Map<String, UserProfile> users = new ConcurrentHashMap<>();
public void save(UserProfile profile) {
users.put(profile.userId(), profile);
}
public Optional<UserProfile> find(String userId) {
return Optional.ofNullable(users.get(userId));
}
}
@@ -0,0 +1,16 @@
package com.ankurm.interviewlab.notification;
import java.util.Set;
/** Contact points plus the channels the user has agreed to receive. */
public record UserProfile(String userId, String email, String phone, String deviceToken, Set<Channel> optedIn) {
/** Where to send on this channel, or null when the user has no such contact point. */
public String addressFor(Channel channel) {
return switch (channel) {
case EMAIL -> email;
case SMS -> phone;
case PUSH -> deviceToken;
};
}
}
@@ -0,0 +1,14 @@
spring:
application:
name: notification-service
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: notification-service
auto-offset-reset: earliest
notification:
rate:
email: 50
sms: 20
push: 200
burst: 5
@@ -0,0 +1,64 @@
package com.ankurm.interviewlab.notification;
import static org.assertj.core.api.Assertions.fail;
import java.time.Duration;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.BooleanSupplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.test.context.EmbeddedKafka;
import tools.jackson.databind.json.JsonMapper;
/**
* One embedded Kafka broker (KRaft, in this JVM) and one Spring context shared by every integration test class,
* because they all inherit the same annotations. Each test uses its own request ids and users, so they do not
* see each other's events.
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EmbeddedKafka(partitions = 3, bootstrapServersProperty = "spring.kafka.bootstrap-servers")
abstract class AbstractKafkaTest {
@Autowired protected UserDirectory users;
@Autowired protected DeliveryLog log;
@Autowired protected FaultInjector faults;
@Autowired protected KafkaTemplate<String, String> kafka;
@Autowired protected JsonMapper json;
@Value("${local.server.port}") protected int port;
protected static String id(String prefix) {
return prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
}
protected UserProfile user(String userId, Channel... channels) {
UserProfile profile = new UserProfile(userId, userId + "@example.com", "+91-98" + Math.abs(userId.hashCode() % 100000000),
"device-" + userId, Set.of(channels));
users.save(profile);
return profile;
}
protected void publish(String requestId, String userId, String templateId, Map<String, String> params) {
NotificationRequest request = new NotificationRequest(requestId, userId, templateId, params);
kafka.send(Topics.REQUESTS, userId, json.writeValueAsString(request)).join();
}
protected static void await(String what, Duration timeout, BooleanSupplier condition) {
long deadline = System.nanoTime() + timeout.toNanos();
while (System.nanoTime() < deadline) {
if (condition.getAsBoolean()) {
return;
}
try {
Thread.sleep(25);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail("interrupted while waiting for " + what);
}
}
fail("timed out after " + timeout + " waiting for " + what);
}
}
@@ -0,0 +1,54 @@
package com.ankurm.interviewlab.notification;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
class FanOutTest extends AbstractKafkaTest {
@Test
void preferencesAndTemplatesDecideTheChannels() {
String all = id("u-all"), noSms = id("u-nosms"), ghost = "u-ghost"; // ghost is never saved: unknown user
user(all, Channel.EMAIL, Channel.SMS, Channel.PUSH);
user(noSms, Channel.EMAIL, Channel.PUSH); // has a phone number, but has not opted in to SMS
String r1 = id("r-all"), r2 = id("r-nosms"), r3 = id("r-otp"), r4 = id("r-ghost"), r5 = id("r-badparam");
Map<String, String> shipped = Map.of("name", "Asha", "orderId", "A-1042", "eta", "27 Nov");
publish(r1, all, "order-shipped", shipped);
publish(r2, noSms, "order-shipped", shipped);
publish(r3, all, "otp", Map.of("code", "482913"));
publish(r4, ghost, "order-shipped", shipped);
publish(r5, all, "order-shipped", Map.of("name", "Asha")); // orderId and eta missing
await("every request to be fully processed", Duration.ofSeconds(20), () ->
log.count(r1, Channel.EMAIL, Outcome.SENT) + log.count(r1, Channel.SMS, Outcome.SENT) + log.count(r1, Channel.PUSH, Outcome.SENT) == 3
&& log.count(r2, Channel.EMAIL, Outcome.SENT) == 1 && log.count(r2, Channel.PUSH, Outcome.SENT) == 1
&& log.count(r3, Channel.SMS, Outcome.SENT) == 1
&& !log.forRequest(r4).isEmpty()
&& log.forRequest(r5).size() == 3);
Transcript out = Transcript.start("03-fan-out.txt", "Fan-out: one request in, one message per allowed channel out")
.events("1. user opted in to all three, template has all three (order-shipped)", log.forRequest(r1)).blank()
.events("2. user has a phone number but has not opted in to SMS", log.forRequest(r2)).blank()
.events("3. otp template only has an SMS body, so only SMS goes out", log.forRequest(r3)).blank()
.events("4. unknown user", log.forRequest(r4)).blank()
.events("5. params missing: every channel skipped, nothing half-rendered is sent", log.forRequest(r5));
out.flush();
assertThat(sent(r1)).containsExactlyInAnyOrder(Channel.EMAIL, Channel.SMS, Channel.PUSH);
assertThat(sent(r2)).containsExactlyInAnyOrder(Channel.EMAIL, Channel.PUSH);
assertThat(log.forRequest(r2, Channel.SMS)).singleElement()
.satisfies(e -> assertThat(e.detail()).isEqualTo("user has not opted in"));
assertThat(sent(r3)).containsExactly(Channel.SMS);
assertThat(log.forRequest(r4)).singleElement()
.satisfies(e -> assertThat(e.detail()).startsWith("unknown user"));
assertThat(sent(r5)).isEmpty();
}
private List<Channel> sent(String requestId) {
return log.forRequest(requestId).stream().filter(e -> e.outcome() == Outcome.SENT).map(DeliveryEvent::channel).toList();
}
}
@@ -0,0 +1,41 @@
package com.ankurm.interviewlab.notification;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class HttpEndToEndTest extends AbstractKafkaTest {
@Test
void postReturns202ThenTheMessagesArrive() throws Exception {
String u = id("u-http");
user(u, Channel.EMAIL, Channel.PUSH);
String r = id("r-http");
String body = "{\"requestId\":\"" + r + "\",\"userId\":\"" + u + "\",\"templateId\":\"welcome\",\"params\":{\"name\":\"Asha\"}}";
HttpResponse<String> response = HttpClient.newHttpClient().send(
HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/api/notifications"))
.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body)).build(),
HttpResponse.BodyHandlers.ofString());
await("email and push sent", Duration.ofSeconds(20), () ->
log.count(r, Channel.EMAIL, Outcome.SENT) == 1 && log.count(r, Channel.PUSH, Outcome.SENT) == 1);
Transcript.start("08-http-end-to-end.txt", "HTTP in, Kafka in the middle, providers at the end")
.line("POST /api/notifications")
.line(" " + body.replace(r, "<requestId>").replace(u, "<userId>"))
.line("HTTP " + response.statusCode())
.line(" " + response.body().replace(r, "<requestId>"))
.blank()
.events("what happened afterwards", log.forRequest(r))
.flush();
assertThat(response.statusCode()).isEqualTo(202);
assertThat(response.body()).contains(r);
}
}
@@ -0,0 +1,40 @@
package com.ankurm.interviewlab.notification;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.Map;
import org.junit.jupiter.api.Test;
class IdempotencyTest extends AbstractKafkaTest {
@Test
void theSameRequestTwiceDeliversOnce() {
String u = id("u-idem");
user(u, Channel.EMAIL, Channel.PUSH);
String r = id("r-idem");
publish(r, u, "welcome", Map.of("name", "Asha"));
publish(r, u, "welcome", Map.of("name", "Asha")); // a producer retry, a replay, a rebalance: same requestId
await("both copies processed on both channels", Duration.ofSeconds(20), () ->
log.count(r, Channel.EMAIL, Outcome.SENT) + log.count(r, Channel.EMAIL, Outcome.DUPLICATE) == 2
&& log.count(r, Channel.PUSH, Outcome.SENT) + log.count(r, Channel.PUSH, Outcome.DUPLICATE) == 2);
// The two copies interleave with the workers, so the transcript prints counts, which are stable, not the sequence.
Transcript out = Transcript.start("05-idempotency.txt", "Idempotency: the same requestId published twice")
.line("one request, published twice, user opted in to EMAIL and PUSH (not SMS)").blank()
.line(String.format("%-6s %10s %10s %10s", "", "FANNED_OUT", "SENT", "DUPLICATE"));
for (Channel c : new Channel[] {Channel.EMAIL, Channel.PUSH}) {
out.line(String.format("%-6s %10d %10d %10d", c, log.count(r, c, Outcome.FANNED_OUT),
log.count(r, c, Outcome.SENT), log.count(r, c, Outcome.DUPLICATE)));
}
out.blank().line("The provider was called once per channel; the second copy was recognised and dropped.").flush();
for (Channel c : new Channel[] {Channel.EMAIL, Channel.PUSH}) {
assertThat(log.count(r, c, Outcome.FANNED_OUT)).isEqualTo(2);
assertThat(log.count(r, c, Outcome.SENT)).isEqualTo(1);
assertThat(log.count(r, c, Outcome.DUPLICATE)).isEqualTo(1);
}
}
}
@@ -0,0 +1,39 @@
package com.ankurm.interviewlab.notification;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.Map;
import org.junit.jupiter.api.Test;
class OrderingTest extends AbstractKafkaTest {
@Test
void aRetryLetsALaterMessageOvertakeAnEarlierOne() {
String u = id("u-order");
user(u, Channel.SMS);
String first = id("r-first"), second = id("r-second");
faults.failTransiently(first, 1); // the first message hits one provider timeout
publish(first, u, "otp", Map.of("code", "111111")); // same user => same key => same partition
publish(second, u, "otp", Map.of("code", "222222"));
await("both sent", Duration.ofSeconds(20), () ->
log.count(first, Channel.SMS, Outcome.SENT) == 1 && log.count(second, Channel.SMS, Outcome.SENT) == 1);
long firstSent = log.forRequest(first, Channel.SMS).getLast().nanos();
long secondSent = log.forRequest(second, Channel.SMS).getLast().nanos();
Transcript.start("07-retry-reorders.txt", "Ordering: Kafka orders a partition, retry topics do not")
.line("published order : first, second (same user, so same key and same partition)")
.line("delivered order : " + (secondSent < firstSent ? "second, first" : "first, second"))
.blank()
.events("first (one transient failure)", log.forRequest(first, Channel.SMS)).blank()
.events("second (no failures)", log.forRequest(second, Channel.SMS))
.flush();
assertThat(secondSent).isLessThan(firstSent);
assertThat(log.forRequest(first, Channel.SMS).getLast().topic()).startsWith("notify.sms-retry");
assertThat(log.forRequest(second, Channel.SMS).getLast().topic()).isEqualTo("notify.sms");
}
}
@@ -0,0 +1,46 @@
package com.ankurm.interviewlab.notification;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
class RateLimitTest extends AbstractKafkaTest {
private record Pending(String requestId, String userId) {
}
@Test
void smsGatewayLimitHoldsEvenWhenEveryoneIsWaiting() {
int total = 25;
List<Pending> pending = new ArrayList<>();
for (int i = 0; i < total; i++) {
String userId = id("u-rl");
user(userId, Channel.SMS);
pending.add(new Pending(id("r-rl"), userId));
}
long start = System.nanoTime();
pending.forEach(p -> publish(p.requestId(), p.userId(), "otp", Map.of("code", "555555")));
await("25 SMS sent", Duration.ofSeconds(30), () ->
pending.stream().allMatch(p -> log.count(p.requestId(), Channel.SMS, Outcome.SENT) == 1));
long lastSent = pending.stream()
.mapToLong(p -> log.forRequest(p.requestId(), Channel.SMS).getLast().nanos()).max().orElseThrow();
long elapsedMs = (lastSent - start) / 1_000_000;
// 5 go out immediately (burst); the other 20 are released at 20 per second: at least 1.0 s in total.
long floorMs = 900;
Transcript.start("06-rate-limit.txt", "Per-channel rate limit: 25 SMS at once, gateway allows 20/s with burst 5")
.line("messages sent : " + total)
.line("rate limit : 20 per second, burst 5")
.line("theoretical minimum : (25 - 5) / 20 = 1.0 s")
.line("assertion : elapsed >= " + floorMs + " ms")
.line("elapsed (indicative) : about " + (elapsedMs / 100) / 10.0 + " s (varies from run to run)")
.flush();
assertThat(elapsedMs).isGreaterThanOrEqualTo(floorMs);
}
}
@@ -0,0 +1,46 @@
package com.ankurm.interviewlab.notification;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.Map;
import org.junit.jupiter.api.Test;
class RetryTest extends AbstractKafkaTest {
@Test
void transientFailuresRetryAndPermanentOnesDoNot() {
String u = id("u-retry");
user(u, Channel.SMS);
String flaky = id("r-flaky"), rejected = id("r-rejected"), down = id("r-down");
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"));
await("flaky to be SENT and the other two dead-lettered", Duration.ofSeconds(30), () ->
log.count(flaky, Channel.SMS, Outcome.SENT) == 1
&& log.count(rejected, Channel.SMS, Outcome.DEAD_LETTERED) == 1
&& log.count(down, Channel.SMS, Outcome.DEAD_LETTERED) == 1);
Transcript.start("04-retries-and-dlt.txt", "Retries and the dead-letter topic (SMS channel, 4 attempts, 250 ms doubling)")
.events("1. provider times out twice, then works", log.forRequest(flaky, Channel.SMS)).blank()
.events("2. provider says the number is invalid (permanent): no retries", log.forRequest(rejected, Channel.SMS)).blank()
.events("3. provider is down for the whole window: all attempts used", log.forRequest(down, Channel.SMS))
.flush();
assertThat(log.count(flaky, Channel.SMS, Outcome.ATTEMPT_FAILED)).isEqualTo(2);
assertThat(log.count(flaky, Channel.SMS, Outcome.DEAD_LETTERED)).isZero();
assertThat(log.forRequest(flaky, Channel.SMS).stream().filter(e -> e.outcome() == Outcome.SENT).findFirst().orElseThrow().topic())
.startsWith("notify.sms-retry");
assertThat(log.count(rejected, Channel.SMS, Outcome.ATTEMPT_FAILED)).isEqualTo(1);
assertThat(log.forRequest(rejected, Channel.SMS).getLast().topic()).isEqualTo("notify.sms-dlt");
assertThat(log.count(down, Channel.SMS, Outcome.ATTEMPT_FAILED)).isEqualTo(4);
assertThat(log.forRequest(down, Channel.SMS).getLast().topic()).isEqualTo("notify.sms-dlt");
}
}
@@ -0,0 +1,44 @@
package com.ankurm.interviewlab.notification;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Map;
import org.junit.jupiter.api.Test;
class TemplateEngineTest {
private final TemplateRegistry registry = new TemplateRegistry();
@Test
void oneTemplateRendersDifferentlyPerChannel() {
Template t = registry.find("order-shipped").orElseThrow();
Map<String, String> params = Map.of("name", "Asha", "orderId", "A-1042", "eta", "27 Nov");
Transcript out = Transcript.start("01-templates.txt", "Template rendering: one template id, one body per channel");
for (Channel c : Channel.values()) {
String rendered = TemplateEngine.render(t.bodies().get(c), params);
out.line(String.format("%-5s (%3d chars) %s", c, rendered.length(), rendered));
}
assertThat(TemplateEngine.render(t.bodies().get(Channel.SMS), params)).isEqualTo("Order A-1042 shipped. ETA 27 Nov.");
assertThat(TemplateEngine.render(t.bodies().get(Channel.EMAIL), params))
.isEqualTo("Hi Asha, your order A-1042 has shipped and arrives on 27 Nov.");
out.blank().line("A template with no body for a channel never goes out on it (otp has only SMS):");
Template otp = registry.find("otp").orElseThrow();
out.line("otp channels: " + otp.bodies().keySet());
assertThat(otp.bodies()).containsOnlyKeys(Channel.SMS);
out.blank().line("A missing parameter is an error, not an empty string:");
assertThatThrownBy(() -> TemplateEngine.render(t.bodies().get(Channel.SMS), Map.of("orderId", "A-1042")))
.isInstanceOf(MissingParameterException.class)
.hasMessage("no value for {{eta}}");
out.line("MissingParameterException: no value for {{eta}}");
out.flush();
}
@Test
void valuesContainingDollarSignsSurvive() {
assertThat(TemplateEngine.render("Total {{amt}}", Map.of("amt", "$5 \\ back"))).isEqualTo("Total $5 \\ back");
}
}
@@ -0,0 +1,39 @@
package com.ankurm.interviewlab.notification;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;
class TokenBucketTest {
private static final long MS = 1_000_000L;
@Test
void burstThenSteadyRate() {
AtomicLong now = new AtomicLong(0);
TokenBucket bucket = new TokenBucket(20, 5, now::get);
Transcript out = Transcript.start("02-token-bucket.txt", "Token bucket: 20 tokens/second, burst 5, fake clock");
out.line("10 sends requested at the same instant (t = 0):");
List<Long> waits = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
long waitMs = bucket.reserve() / MS;
waits.add(waitMs);
out.line(String.format(" send %2d waits %3d ms", i, waitMs));
}
assertThat(waits).containsExactly(0L, 0L, 0L, 0L, 0L, 50L, 100L, 150L, 200L, 250L);
out.blank().line("After the queue drains and the clock idles for 10 seconds the bucket refills, but only to the burst size:");
now.set(10_300 * MS);
List<Long> after = new ArrayList<>();
for (int i = 1; i <= 7; i++) {
after.add(bucket.reserve() / MS);
}
out.line(" next 7 sends wait (ms): " + after);
assertThat(after).containsExactly(0L, 0L, 0L, 0L, 0L, 50L, 100L);
out.flush();
}
}
@@ -0,0 +1,29 @@
package com.ankurm.interviewlab.notification;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
import java.util.TreeSet;
import org.apache.kafka.clients.admin.Admin;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaAdmin;
class TopicsTest extends AbstractKafkaTest {
@Autowired KafkaAdmin admin;
@Test
void retryAndDeadLetterTopicsAreCreatedForEachChannel() throws Exception {
try (Admin client = Admin.create(admin.getConfigurationProperties())) {
Set<String> names = new TreeSet<>(client.listTopics().names().get());
names.removeIf(n -> n.startsWith("__"));
Transcript out = Transcript.start("09-topics.txt", "Topics that exist after startup (internal topics hidden)");
names.forEach(n -> out.line(" " + n));
out.flush();
assertThat(names).contains("notification.requests", "notify.email", "notify.sms", "notify.push",
"notify.sms-dlt", "notify.email-dlt", "notify.push-dlt");
assertThat(names.stream().filter(n -> n.startsWith("notify.sms-retry"))).hasSize(3);
}
}
}
@@ -0,0 +1,61 @@
package com.ankurm.interviewlab.notification;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/** Writes output/NN-*.txt while the calling test asserts the same numbers it prints. */
final class Transcript {
private final Path path;
private final List<String> lines = new ArrayList<>();
private Transcript(Path path, String header) {
this.path = path;
lines.add(header);
lines.add("=".repeat(Math.min(header.length(), 100)));
lines.add("");
}
static Transcript start(String fileName, String header) {
Path dir = Path.of("output");
try {
Files.createDirectories(dir);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return new Transcript(dir.resolve(fileName), header);
}
Transcript line(String text) {
lines.add(text);
return this;
}
Transcript blank() {
lines.add("");
return this;
}
/** Prints one request's events grouped by channel (insertion order kept inside a channel) so reruns diff cleanly. */
Transcript events(String label, List<DeliveryEvent> events) {
lines.add(label);
events.stream()
.sorted(Comparator.comparingInt((DeliveryEvent e) -> e.channel() == null ? -1 : e.channel().ordinal()))
.forEach(e -> lines.add(String.format(" %-5s %-15s %-28s %s",
e.channel() == null ? "-" : e.channel(), e.outcome(), e.topic(), e.detail())));
return this;
}
void flush() {
try {
Files.write(path, (String.join("\n", lines) + "\n").getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}