From 09f875ddd92fcfcc3c0da95c38bf2ac7b7fb5f6b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:30:04 +0530 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_017ic4b7rAEgiNi4Fo94nVoB --- README.md | 1 + notification-service/README.md | 70 +++++++++++++++++ notification-service/output/01-templates.txt | 12 +++ .../output/02-token-bucket.txt | 17 ++++ notification-service/output/03-fan-out.txt | 31 ++++++++ .../output/04-retries-and-dlt.txt | 21 +++++ .../output/05-idempotency.txt | 10 +++ notification-service/output/06-rate-limit.txt | 8 ++ .../output/07-retry-reorders.txt | 14 ++++ .../output/08-http-end-to-end.txt | 14 ++++ notification-service/output/09-topics.txt | 19 +++++ notification-service/pom.xml | 78 +++++++++++++++++++ notification-service/scripts/run-all.sh | 10 +++ .../interviewlab/notification/Channel.java | 18 +++++ .../notification/ChannelMessage.java | 8 ++ .../notification/ChannelProvider.java | 8 ++ .../notification/ChannelWorker.java | 53 +++++++++++++ .../notification/DeliveryEvent.java | 8 ++ .../notification/DeliveryLog.java | 29 +++++++ .../notification/EmailWorker.java | 32 ++++++++ .../notification/FanOutService.java | 78 +++++++++++++++++++ .../notification/FaultInjector.java | 37 +++++++++ .../notification/IdempotencyStore.java | 27 +++++++ .../MissingParameterException.java | 8 ++ .../notification/NotificationApplication.java | 11 +++ .../notification/NotificationConfig.java | 31 ++++++++ .../notification/NotificationController.java | 31 ++++++++ .../notification/NotificationRequest.java | 15 ++++ .../interviewlab/notification/Outcome.java | 17 ++++ .../PermanentProviderException.java | 8 ++ .../interviewlab/notification/PushWorker.java | 32 ++++++++ .../notification/RateLimiters.java | 28 +++++++ .../notification/SimulatedProvider.java | 22 ++++++ .../interviewlab/notification/SmsWorker.java | 32 ++++++++ .../interviewlab/notification/Template.java | 7 ++ .../notification/TemplateEngine.java | 28 +++++++ .../notification/TemplateRegistry.java | 24 ++++++ .../notification/TokenBucket.java | 41 ++++++++++ .../interviewlab/notification/Topics.java | 14 ++++ .../TransientProviderException.java | 8 ++ .../notification/UserDirectory.java | 23 ++++++ .../notification/UserProfile.java | 16 ++++ .../src/main/resources/application.yaml | 14 ++++ .../notification/AbstractKafkaTest.java | 64 +++++++++++++++ .../interviewlab/notification/FanOutTest.java | 54 +++++++++++++ .../notification/HttpEndToEndTest.java | 41 ++++++++++ .../notification/IdempotencyTest.java | 40 ++++++++++ .../notification/OrderingTest.java | 39 ++++++++++ .../notification/RateLimitTest.java | 46 +++++++++++ .../interviewlab/notification/RetryTest.java | 46 +++++++++++ .../notification/TemplateEngineTest.java | 44 +++++++++++ .../notification/TokenBucketTest.java | 39 ++++++++++ .../interviewlab/notification/TopicsTest.java | 29 +++++++ .../interviewlab/notification/Transcript.java | 61 +++++++++++++++ 54 files changed, 1516 insertions(+) create mode 100644 notification-service/README.md create mode 100644 notification-service/output/01-templates.txt create mode 100644 notification-service/output/02-token-bucket.txt create mode 100644 notification-service/output/03-fan-out.txt create mode 100644 notification-service/output/04-retries-and-dlt.txt create mode 100644 notification-service/output/05-idempotency.txt create mode 100644 notification-service/output/06-rate-limit.txt create mode 100644 notification-service/output/07-retry-reorders.txt create mode 100644 notification-service/output/08-http-end-to-end.txt create mode 100644 notification-service/output/09-topics.txt create mode 100644 notification-service/pom.xml create mode 100755 notification-service/scripts/run-all.sh create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/Channel.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelMessage.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelProvider.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelWorker.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/DeliveryEvent.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/DeliveryLog.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/EmailWorker.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/FanOutService.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/FaultInjector.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/IdempotencyStore.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/MissingParameterException.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/NotificationApplication.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/NotificationConfig.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/NotificationController.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/NotificationRequest.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/Outcome.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/PermanentProviderException.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/PushWorker.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/RateLimiters.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/SimulatedProvider.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/SmsWorker.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/Template.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/TemplateEngine.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/TemplateRegistry.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/TokenBucket.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/Topics.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/TransientProviderException.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/UserDirectory.java create mode 100644 notification-service/src/main/java/com/ankurm/interviewlab/notification/UserProfile.java create mode 100644 notification-service/src/main/resources/application.yaml create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/AbstractKafkaTest.java create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/FanOutTest.java create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/HttpEndToEndTest.java create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/IdempotencyTest.java create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/OrderingTest.java create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/RateLimitTest.java create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/RetryTest.java create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/TemplateEngineTest.java create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/TokenBucketTest.java create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/TopicsTest.java create mode 100644 notification-service/src/test/java/com/ankurm/interviewlab/notification/Transcript.java diff --git a/README.md b/README.md index b128eed..a9f31e7 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ One module per article. This repository currently holds: | [`experienced-2-3y`](experienced-2-3y/) | Java Interview Questions for 2 to 3 Years Experience (Scenario-Based, with Answers) | this commit | | [`food-delivery`](food-delivery/) | Low-Level Design: Food Delivery App (Zomato/Swiggy-Style) in Java | this commit | | [`binary-search`](binary-search/) | Binary Search in Java: Iterative, Recursive, Lower/Upper Bound and 10 Interview Problems | this commit | +| [`notification-service`](notification-service/) | System Design: Notification Service with Spring Boot and Kafka (Email, SMS, Push) | this commit | ## `collections` module diff --git a/notification-service/README.md b/notification-service/README.md new file mode 100644 index 0000000..a93e578 --- /dev/null +++ b/notification-service/README.md @@ -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` → 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). diff --git a/notification-service/output/01-templates.txt b/notification-service/output/01-templates.txt new file mode 100644 index 0000000..6938f88 --- /dev/null +++ b/notification-service/output/01-templates.txt @@ -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}} diff --git a/notification-service/output/02-token-bucket.txt b/notification-service/output/02-token-bucket.txt new file mode 100644 index 0000000..937e64c --- /dev/null +++ b/notification-service/output/02-token-bucket.txt @@ -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] diff --git a/notification-service/output/03-fan-out.txt b/notification-service/output/03-fan-out.txt new file mode 100644 index 0000000..28f179f --- /dev/null +++ b/notification-service/output/03-fan-out.txt @@ -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}} diff --git a/notification-service/output/04-retries-and-dlt.txt b/notification-service/output/04-retries-and-dlt.txt new file mode 100644 index 0000000..88ef008 --- /dev/null +++ b/notification-service/output/04-retries-and-dlt.txt @@ -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 diff --git a/notification-service/output/05-idempotency.txt b/notification-service/output/05-idempotency.txt new file mode 100644 index 0000000..ef214f7 --- /dev/null +++ b/notification-service/output/05-idempotency.txt @@ -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. diff --git a/notification-service/output/06-rate-limit.txt b/notification-service/output/06-rate-limit.txt new file mode 100644 index 0000000..b7ad39a --- /dev/null +++ b/notification-service/output/06-rate-limit.txt @@ -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) diff --git a/notification-service/output/07-retry-reorders.txt b/notification-service/output/07-retry-reorders.txt new file mode 100644 index 0000000..ceca5f4 --- /dev/null +++ b/notification-service/output/07-retry-reorders.txt @@ -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 diff --git a/notification-service/output/08-http-end-to-end.txt b/notification-service/output/08-http-end-to-end.txt new file mode 100644 index 0000000..e1026c4 --- /dev/null +++ b/notification-service/output/08-http-end-to-end.txt @@ -0,0 +1,14 @@ +HTTP in, Kafka in the middle, providers at the end +================================================== + +POST /api/notifications + {"requestId":"","userId":"","templateId":"welcome","params":{"name":"Asha"}} +HTTP 202 + {"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 diff --git a/notification-service/output/09-topics.txt b/notification-service/output/09-topics.txt new file mode 100644 index 0000000..53df3db --- /dev/null +++ b/notification-service/output/09-topics.txt @@ -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 diff --git a/notification-service/pom.xml b/notification-service/pom.xml new file mode 100644 index 0000000..ef5c5a8 --- /dev/null +++ b/notification-service/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + com.ankurm.interviewlab + notification-service + 1.0.0 + jar + + java-interview-lab :: notification-service + + 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. + + + + 25 + UTF-8 + 4.2.0 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-kafka + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-kafka-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.6.1 + + -Xmx768m -Duser.timezone=UTC -Dfile.encoding=UTF-8 + + + + + diff --git a/notification-service/scripts/run-all.sh b/notification-service/scripts/run-all.sh new file mode 100755 index 0000000..63af286 --- /dev/null +++ b/notification-service/scripts/run-all.sh @@ -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 diff --git a/notification-service/src/main/java/com/ankurm/interviewlab/notification/Channel.java b/notification-service/src/main/java/com/ankurm/interviewlab/notification/Channel.java new file mode 100644 index 0000000..1df428d --- /dev/null +++ b/notification-service/src/main/java/com/ankurm/interviewlab/notification/Channel.java @@ -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; + } +} diff --git a/notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelMessage.java b/notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelMessage.java new file mode 100644 index 0000000..35ba2aa --- /dev/null +++ b/notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelMessage.java @@ -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) { +} diff --git a/notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelProvider.java b/notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelProvider.java new file mode 100644 index 0000000..ac5f71a --- /dev/null +++ b/notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelProvider.java @@ -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); +} diff --git a/notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelWorker.java b/notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelWorker.java new file mode 100644 index 0000000..609647e --- /dev/null +++ b/notification-service/src/main/java/com/ankurm/interviewlab/notification/ChannelWorker.java @@ -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 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 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"); + } +} diff --git a/notification-service/src/main/java/com/ankurm/interviewlab/notification/DeliveryEvent.java b/notification-service/src/main/java/com/ankurm/interviewlab/notification/DeliveryEvent.java new file mode 100644 index 0000000..f50bede --- /dev/null +++ b/notification-service/src/main/java/com/ankurm/interviewlab/notification/DeliveryEvent.java @@ -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) { +} diff --git a/notification-service/src/main/java/com/ankurm/interviewlab/notification/DeliveryLog.java b/notification-service/src/main/java/com/ankurm/interviewlab/notification/DeliveryLog.java new file mode 100644 index 0000000..44c9ee1 --- /dev/null +++ b/notification-service/src/main/java/com/ankurm/interviewlab/notification/DeliveryLog.java @@ -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 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 forRequest(String requestId) { + return events.stream().filter(e -> e.requestId().equals(requestId)).toList(); + } + + public List 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(); + } +} diff --git a/notification-service/src/main/java/com/ankurm/interviewlab/notification/EmailWorker.java b/notification-service/src/main/java/com/ankurm/interviewlab/notification/EmailWorker.java new file mode 100644 index 0000000..61984db --- /dev/null +++ b/notification-service/src/main/java/com/ankurm/interviewlab/notification/EmailWorker.java @@ -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 record) throws InterruptedException { + handle(record); + } + + @DltHandler + public void onDead(ConsumerRecord record) { + handleDead(record); + } +} diff --git a/notification-service/src/main/java/com/ankurm/interviewlab/notification/FanOutService.java b/notification-service/src/main/java/com/ankurm/interviewlab/notification/FanOutService.java new file mode 100644 index 0000000..3fe2d58 --- /dev/null +++ b/notification-service/src/main/java/com/ankurm/interviewlab/notification/FanOutService.java @@ -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 kafka; + private final JsonMapper json; + private final DeliveryLog log; + + public FanOutService(UserDirectory users, TemplateRegistry templates, KafkaTemplate 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 user = users.find(request.userId()); + if (user.isEmpty()) { + log.record(request.requestId(), null, Outcome.SKIPPED, Topics.REQUESTS, "unknown user " + request.userId()); + return; + } + Optional