diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml
index d98e620..640e441 100644
--- a/.github/workflows/ci-cd.yml
+++ b/.github/workflows/ci-cd.yml
@@ -9,6 +9,9 @@ on:
env:
AWS_REGION: us-east-1
+permissions:
+ contents: read
+
jobs:
build-and-test:
name: Build and test
@@ -16,23 +19,18 @@ jobs:
steps:
- uses: actions/checkout@v4
- - name: Set up JDK 21
+ - name: Set up JDK 25
uses: actions/setup-java@v4
with:
distribution: temurin
- java-version: '21'
+ java-version: '25'
cache: maven
- - name: Build all services
- run: mvn -B -DskipTests package
-
- - name: Run unit tests
- run: mvn -B test
-
- - name: Run integration tests
+ - name: Build and test
# Docker is preinstalled on ubuntu-latest runners, so the
# Testcontainers-backed tests (order-service, notification-service)
- # run against real MySQL/Kafka/Redis containers here.
+ # run against real MySQL/Kafka containers here. verify covers
+ # compile, unit tests (surefire) and integration tests (failsafe).
run: mvn -B verify
- name: Upload test reports
@@ -50,6 +48,9 @@ jobs:
needs: build-and-test
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ id-token: write
strategy:
matrix:
service: [order-service, notification-service, email-service, sms-service, api-gateway]
@@ -84,6 +85,9 @@ jobs:
needs: build-and-push-images
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ id-token: write
strategy:
matrix:
service: [order-service, notification-service, email-service, sms-service, api-gateway]
diff --git a/README.md b/README.md
index 68bb29d..2a497e4 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,16 @@
# Etch
-Etch is a distributed notification hub using Apache Kafka to decouple high-volume business orders from email and SMS delivery.
+Etch is a small notification hub built on Kafka. You place an order, the order service answers right away, and the emails and texts go out in the background through their own services.
-## System architecture
+## Why I built it
+
+I wanted to understand what happens when the slow, unreliable part of a system sits behind a message queue. Sending a notification is a good example. Email and SMS providers time out, go down, and occasionally reject a message outright, and none of that should make an order fail or make a customer wait.
+
+So I built the whole path to see how it holds up: an order comes in, an event goes onto Kafka, and a separate service picks it up and handles delivery. The parts I cared about most were the unglamorous ones. What happens when a send fails? How many times do you retry? Where does a message go when it can never succeed? And what stops a customer from getting the same email twice when Kafka redelivers an event? Etch is my answer to those questions, kept small enough to read in an afternoon.
+
+## How it fits together
```mermaid
flowchart LR
@@ -37,31 +43,28 @@ flowchart LR
NOTIFY -->|sent / failed / dead-letter| KAFKA
```
-## Tech stack
+1. The client creates an order through the gateway.
+2. The order service saves it to MySQL, publishes an `order-created` event, and responds immediately.
+3. The notification service consumes the event and creates one notification per requested channel (email, SMS, or both).
+4. Each notification is sent through the email or SMS service. If a send fails temporarily, it's retried with exponential backoff.
+5. If it fails for good, or runs out of retries, it goes to a dead-letter topic instead of being dropped.
-- **Backend:** Java 21, Spring Boot, Spring Cloud Gateway
-- **Messaging:** Apache Kafka
-- **Database:** MySQL, Flyway
-- **Caching and idempotency:** Redis
-- **Testing:** JUnit, Spring Boot Test, Testcontainers
-- **DevOps:** Docker, Docker Compose, GitHub Actions
-- **Deployment:** AWS ECS/Fargate, Amazon ECR, Amazon RDS, ElastiCache
+## What it does
-## Key features
+- **Async by design.** Creating an order never waits on delivery.
+- **Retries and a dead-letter queue.** Temporary failures are retried with backoff. Permanent failures and exhausted retries land in the `notification-dlt` topic and get logged.
+- **No duplicates.** Redis tracks which events and notifications have already been handled, so a redelivered Kafka message doesn't send twice.
+- **Five services, each in its own container.** Gateway, order, notification, email, and SMS. The email and SMS services are mocks that fail on purpose, so you can watch the failure handling work.
+- **Tested.** Unit tests for the logic, plus Testcontainers integration tests that run against real MySQL, Kafka, and Redis.
+- **Ships to AWS.** A GitHub Actions pipeline tests the code, builds the Docker images, and deploys to ECS Fargate.
-- five Spring Boot services that process orders and deliver email and SMS notifications asynchronously over Kafka
-- retry handling with exponential backoff, and a dead-letter topic for notifications that fail permanently
-- Redis-backed deduplication, so a redelivered Kafka event is never processed or sent twice
-- persisted notification status per order and channel
-- unit and Testcontainers-based integration tests
-- Dockerfiles for every service, a Docker Compose stack, and a GitHub Actions pipeline that tests, builds, and deploys to AWS ECS
+## Tech stack
-## Prerequisites
+Java 25, Spring Boot, Spring Cloud Gateway, Apache Kafka, MySQL, Redis, JUnit and Testcontainers, Docker and Docker Compose, GitHub Actions, and AWS (ECS/Fargate, ECR, RDS, ElastiCache).
-- Docker with Docker Compose v2, to run the full stack
-- JDK 21 and Maven 3.9 or newer, to build and test outside Docker
+## Running it
-## Running locally
+You need Docker with Compose v2. To build or test outside Docker you also need JDK 25 and Maven 3.9 or newer.
From the repo root:
@@ -69,7 +72,7 @@ From the repo root:
docker compose up -d --build
```
-This starts Kafka (KRaft, single node), MySQL, Redis, and all five services. The first build takes a few minutes; subsequent starts are faster.
+That starts Kafka, MySQL, Redis, and all five services. The first build takes a few minutes.
| Service | URL |
|---|---|
@@ -79,9 +82,9 @@ This starts Kafka (KRaft, single node), MySQL, Redis, and all five services. The
| Email Service (mock) | http://localhost:8083 |
| SMS Service (mock) | http://localhost:8084 |
-### Try it end to end
+### Try it
-Create an order through the gateway. Demo users are seeded by Flyway.
+Create an order through the gateway. Three demo users are created on startup.
```bash
curl -s -X POST http://localhost:8080/orders \
@@ -89,63 +92,54 @@ curl -s -X POST http://localhost:8080/orders \
-d '{"userId":1,"orderNumber":"ORD-1001","total":49.99,"channels":["EMAIL","SMS"]}'
```
-Check the notification status for the order:
+Then look at what happened to its notifications:
```bash
curl -s http://localhost:8080/notifications/order/1
```
-The mock email and SMS services intentionally fail a configurable percentage of requests, which makes retries and dead-letter handling easy to observe. Watch them in the logs:
+The mock services reject some requests on purpose, so create a few orders and watch the notification service work through retries and dead-lettering:
```bash
docker compose logs -f notification-service
```
-### Stopping the stack
+### Stopping it
```bash
docker compose down
```
-Add `-v` to also delete the MySQL volume and start from a clean database next time.
+Add `-v` to also wipe the MySQL volume and start clean next time.
## Configuration
-Every setting has a local default, and `docker-compose.yml` overrides the ones that differ inside containers. The variables you are most likely to change:
+Everything has a sensible local default, and `docker-compose.yml` overrides what needs to change inside containers. These are the ones you're most likely to touch:
-| Variable | Used by | Default | Purpose |
+| Variable | Used by | Default | What it does |
|---|---|---|---|
-| `ORDER_SERVICE_URL`, `NOTIFICATION_SERVICE_URL` | api-gateway | `http://localhost:8081`, `http://localhost:8082` | Downstream routes |
+| `ORDER_SERVICE_URL`, `NOTIFICATION_SERVICE_URL` | api-gateway | `http://localhost:8081`, `http://localhost:8082` | Where the gateway forwards requests |
| `KAFKA_BOOTSTRAP_SERVERS` | order-service, notification-service | `localhost:9092` | Kafka brokers |
-| `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USERNAME`, `DB_PASSWORD` | order-service, notification-service | `localhost`, `3306`, per-service schema, `etch`, `etch` | MySQL connection |
-| `REDIS_HOST`, `REDIS_PORT` | notification-service | `localhost`, `6379` | Idempotency |
-| `EMAIL_SERVICE_URL`, `SMS_SERVICE_URL` | notification-service | `http://localhost:8083`, `http://localhost:8084` | Channel service endpoints |
-| `EMAIL_FAILURE_RATE`, `SMS_FAILURE_RATE` | email-service, sms-service | `0.05` | Fraction of requests the mock rejects as a permanent failure |
-| `EMAIL_UNAVAILABLE_RATE`, `SMS_UNAVAILABLE_RATE` | email-service, sms-service | `0.0` | Fraction of requests the mock answers with a 503, which notification-service retries |
+| `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USERNAME`, `DB_PASSWORD` | order-service, notification-service | `localhost`, `3306`, one schema per service, `etch`, `etch` | MySQL connection |
+| `REDIS_HOST`, `REDIS_PORT` | notification-service | `localhost`, `6379` | Redis, used for deduplication |
+| `EMAIL_SERVICE_URL`, `SMS_SERVICE_URL` | notification-service | `http://localhost:8083`, `http://localhost:8084` | Where deliveries are sent |
+| `EMAIL_FAILURE_RATE`, `SMS_FAILURE_RATE` | email-service, sms-service | `0.05` | Share of requests the mock rejects permanently |
+| `EMAIL_UNAVAILABLE_RATE`, `SMS_UNAVAILABLE_RATE` | email-service, sms-service | `0.0` | Share of requests the mock answers with a 503, which gets retried |
## Testing
-Run unit tests:
-
-```bash
-mvn test
-```
-
-Run unit and Testcontainers integration tests:
-
```bash
-mvn verify
+mvn test # unit tests
+mvn verify # unit tests plus the Testcontainers integration tests (needs Docker)
```
-The integration suite requires Docker.
-
-Run the tests for one service together with the shared modules it depends on:
+To test one service along with the shared modules it depends on:
```bash
mvn -pl services/order-service -am test
```
-## Project structure
+## Project layout
```text
services/
@@ -156,39 +150,17 @@ services/
└── sms-service/
shared/
-├── common-events/
-├── common-dto/
-└── common-utils/
+├── common-events/ event classes shared between services
+├── common-dto/ request and response types
+└── common-utils/ exceptions and logging helpers
infrastructure/
-├── docker/
-└── aws/
+├── docker/ MySQL init script
+└── aws/ ECS task definitions and setup notes
-.github/
-└── workflows/
+.github/workflows/ CI/CD pipeline
```
## Deployment
-The repository includes AWS ECS deployment configuration for:
-
-- ECS Fargate
-- Amazon ECR
-- Amazon RDS for MySQL
-- ElastiCache for Redis
-
-The GitHub Actions pipeline builds and tests the services, builds Docker images, and contains the configuration required to publish and deploy them when the appropriate AWS credentials and repository secrets are provided.
-
-## Design highlights
-
-### Asynchronous processing
-
-Creating an order does not wait for notification delivery. The Order Service persists the order and publishes an event to Kafka, allowing notification processing to happen independently.
-
-### Failure handling
-
-Transient delivery failures are retried with exponential backoff. Permanent failures, and messages that exhaust their retry attempts, are published to a dead-letter topic (`notification-dlt`) and logged by the notification service.
-
-### Idempotency
-
-Redis is used to prevent the same notification from being processed or delivered multiple times.
+The repo includes ECS task definitions for each service, targeting ECS Fargate with images in ECR, MySQL on RDS, and Redis on ElastiCache. The GitHub Actions pipeline runs the tests, builds the images, and pushes and deploys them when AWS credentials and repository secrets are configured. See [infrastructure/aws/README.md](infrastructure/aws/README.md) for the setup notes.
diff --git a/pom.xml b/pom.xml
index 9bafcfb..f86aae0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -15,16 +15,16 @@
org.springframework.boot
spring-boot-starter-parent
- 3.3.4
+ 3.5.16
- 21
- 21
- 21
+ 25
+ 25
+ 25
UTF-8
- 2023.0.3
+ 2025.0.3
@@ -90,11 +90,6 @@
org.apache.maven.plugins
maven-surefire-plugin
-
- -Dnet.bytebuddy.experimental=true
@@ -106,7 +101,6 @@
org.apache.maven.plugins
maven-failsafe-plugin
- -Dnet.bytebuddy.experimental=true
**/*IntegrationTest.java
diff --git a/services/api-gateway/Dockerfile b/services/api-gateway/Dockerfile
index 0f1526b..a85cd25 100644
--- a/services/api-gateway/Dockerfile
+++ b/services/api-gateway/Dockerfile
@@ -1,6 +1,6 @@
# Build from the repository root: docker build -f services/api-gateway/Dockerfile .
-FROM maven:3.9-eclipse-temurin-21 AS build
+FROM maven:3.9-eclipse-temurin-25 AS build
WORKDIR /workspace
COPY pom.xml .
@@ -9,11 +9,11 @@ COPY services services
RUN mvn -q -pl services/api-gateway -am -DskipTests package
-FROM eclipse-temurin:21-jre-alpine
+FROM eclipse-temurin:25-jre-alpine
RUN addgroup -S etch && adduser -S etch -G etch
WORKDIR /app
COPY --from=build /workspace/services/api-gateway/target/api-gateway.jar app.jar
USER etch
EXPOSE 8080
-ENTRYPOINT ["java", "-jar", "/app/app.jar"]
+ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
diff --git a/services/api-gateway/src/main/resources/application.yml b/services/api-gateway/src/main/resources/application.yml
index 03ce143..1927c92 100644
--- a/services/api-gateway/src/main/resources/application.yml
+++ b/services/api-gateway/src/main/resources/application.yml
@@ -17,6 +17,7 @@ spring:
server:
port: 8080
+ shutdown: graceful
management:
endpoints:
diff --git a/services/email-service/Dockerfile b/services/email-service/Dockerfile
index 46912ef..0bd27b9 100644
--- a/services/email-service/Dockerfile
+++ b/services/email-service/Dockerfile
@@ -1,6 +1,6 @@
# Build from the repository root: docker build -f services/email-service/Dockerfile .
-FROM maven:3.9-eclipse-temurin-21 AS build
+FROM maven:3.9-eclipse-temurin-25 AS build
WORKDIR /workspace
COPY pom.xml .
@@ -9,11 +9,11 @@ COPY services services
RUN mvn -q -pl services/email-service -am -DskipTests package
-FROM eclipse-temurin:21-jre-alpine
+FROM eclipse-temurin:25-jre-alpine
RUN addgroup -S etch && adduser -S etch -G etch
WORKDIR /app
COPY --from=build /workspace/services/email-service/target/email-service.jar app.jar
USER etch
EXPOSE 8083
-ENTRYPOINT ["java", "-jar", "/app/app.jar"]
+ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
diff --git a/services/email-service/src/main/java/com/etch/emailservice/service/EmailSendService.java b/services/email-service/src/main/java/com/etch/emailservice/service/EmailSendService.java
index d2b82f5..82cde6a 100644
--- a/services/email-service/src/main/java/com/etch/emailservice/service/EmailSendService.java
+++ b/services/email-service/src/main/java/com/etch/emailservice/service/EmailSendService.java
@@ -30,6 +30,11 @@ public class EmailSendService {
public EmailSendService(@Value("${etch.simulation.unavailable-rate:0.0}") double unavailableRate,
@Value("${etch.simulation.failure-rate:0.05}") double failureRate) {
+ if (unavailableRate < 0 || failureRate < 0 || unavailableRate + failureRate > 1.0) {
+ throw new IllegalArgumentException(
+ "etch.simulation rates must be non-negative and sum to at most 1.0 (unavailable="
+ + unavailableRate + ", failure=" + failureRate + ")");
+ }
this.unavailableRate = unavailableRate;
this.failureRate = failureRate;
}
diff --git a/services/email-service/src/main/resources/application.yml b/services/email-service/src/main/resources/application.yml
index 01d1d90..ae691e2 100644
--- a/services/email-service/src/main/resources/application.yml
+++ b/services/email-service/src/main/resources/application.yml
@@ -4,6 +4,7 @@ spring:
server:
port: 8083
+ shutdown: graceful
etch:
simulation:
diff --git a/services/email-service/src/test/java/com/etch/emailservice/service/EmailSendServiceTest.java b/services/email-service/src/test/java/com/etch/emailservice/service/EmailSendServiceTest.java
index 57bbbf5..a1254ec 100644
--- a/services/email-service/src/test/java/com/etch/emailservice/service/EmailSendServiceTest.java
+++ b/services/email-service/src/test/java/com/etch/emailservice/service/EmailSendServiceTest.java
@@ -41,4 +41,16 @@ void raisesServiceUnavailableWhenOutageIsCertain() {
.isInstanceOf(ResponseStatusException.class)
.hasMessageContaining("503");
}
+
+ @Test
+ void rejectsRatesThatSumPastOne() {
+ assertThatThrownBy(() -> new EmailSendService(0.6, 0.6))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void rejectsNegativeRates() {
+ assertThatThrownBy(() -> new EmailSendService(-0.1, 0.0))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
}
diff --git a/services/notification-service/Dockerfile b/services/notification-service/Dockerfile
index 6248193..70f50d1 100644
--- a/services/notification-service/Dockerfile
+++ b/services/notification-service/Dockerfile
@@ -1,6 +1,6 @@
# Build from the repository root: docker build -f services/notification-service/Dockerfile .
-FROM maven:3.9-eclipse-temurin-21 AS build
+FROM maven:3.9-eclipse-temurin-25 AS build
WORKDIR /workspace
COPY pom.xml .
@@ -9,11 +9,11 @@ COPY services services
RUN mvn -q -pl services/notification-service -am -DskipTests package
-FROM eclipse-temurin:21-jre-alpine
+FROM eclipse-temurin:25-jre-alpine
RUN addgroup -S etch && adduser -S etch -G etch
WORKDIR /app
COPY --from=build /workspace/services/notification-service/target/notification-service.jar app.jar
USER etch
EXPOSE 8082
-ENTRYPOINT ["java", "-jar", "/app/app.jar"]
+ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
diff --git a/services/notification-service/pom.xml b/services/notification-service/pom.xml
index 0441ee2..807e27f 100644
--- a/services/notification-service/pom.xml
+++ b/services/notification-service/pom.xml
@@ -55,14 +55,6 @@
mysql-connector-j
runtime
-
- org.flywaydb
- flyway-core
-
-
- org.flywaydb
- flyway-mysql
-
org.springframework.boot
diff --git a/services/notification-service/src/main/java/com/etch/notificationservice/retry/ExponentialBackOff.java b/services/notification-service/src/main/java/com/etch/notificationservice/retry/ExponentialBackOff.java
index 85d728c..c4fbc4f 100644
--- a/services/notification-service/src/main/java/com/etch/notificationservice/retry/ExponentialBackOff.java
+++ b/services/notification-service/src/main/java/com/etch/notificationservice/retry/ExponentialBackOff.java
@@ -6,6 +6,8 @@
@Component
public class ExponentialBackOff implements BackOff {
+ private static final long MAX_DELAY_MS = 30_000L;
+
private final long baseDelayMs;
public ExponentialBackOff(@Value("${etch.retry.base-delay-ms:500}") long baseDelayMs) {
@@ -22,6 +24,8 @@ public void waitBeforeRetry(int attempt) {
}
long delayMsFor(int attempt) {
- return baseDelayMs * (1L << Math.max(0, attempt - 1));
+ // clamp the shift so a large attempt count can't overflow into a negative delay
+ int shift = Math.min(Math.max(0, attempt - 1), 20);
+ return Math.min(baseDelayMs << shift, MAX_DELAY_MS);
}
}
diff --git a/services/notification-service/src/main/resources/application.yml b/services/notification-service/src/main/resources/application.yml
index 7bed260..b5813f3 100644
--- a/services/notification-service/src/main/resources/application.yml
+++ b/services/notification-service/src/main/resources/application.yml
@@ -11,13 +11,9 @@ spring:
jpa:
hibernate:
- ddl-auto: validate
+ ddl-auto: update
open-in-view: false
- flyway:
- enabled: true
- locations: classpath:db/migration
-
kafka:
bootstrap-servers: ${KAFKA_BOOTSTRAP_SERVERS:localhost:9092}
@@ -29,6 +25,7 @@ spring:
server:
port: 8082
+ shutdown: graceful
etch:
channel-clients:
diff --git a/services/notification-service/src/main/resources/db/migration/V1__init_schema.sql b/services/notification-service/src/main/resources/db/migration/V1__init_schema.sql
deleted file mode 100644
index 33171a8..0000000
--- a/services/notification-service/src/main/resources/db/migration/V1__init_schema.sql
+++ /dev/null
@@ -1,14 +0,0 @@
-CREATE TABLE notifications (
- id BIGINT AUTO_INCREMENT PRIMARY KEY,
- order_id BIGINT NOT NULL,
- channel VARCHAR(20) NOT NULL,
- recipient VARCHAR(255) NOT NULL,
- status VARCHAR(20) NOT NULL,
- retry_count INT NOT NULL DEFAULT 0,
- correlation_id VARCHAR(64),
- created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
- version BIGINT NOT NULL DEFAULT 0
-) ENGINE = InnoDB;
-
-CREATE INDEX idx_notifications_order_id ON notifications (order_id);
diff --git a/services/notification-service/src/test/java/com/etch/notificationservice/retry/ExponentialBackOffTest.java b/services/notification-service/src/test/java/com/etch/notificationservice/retry/ExponentialBackOffTest.java
index 3402b62..e2817db 100644
--- a/services/notification-service/src/test/java/com/etch/notificationservice/retry/ExponentialBackOffTest.java
+++ b/services/notification-service/src/test/java/com/etch/notificationservice/retry/ExponentialBackOffTest.java
@@ -23,6 +23,14 @@ void neverProducesANegativeExponentForAttemptZeroOrBelow() {
assertThat(backOff.delayMsFor(-5)).isEqualTo(100L);
}
+ @Test
+ void delayIsCappedForHighAttemptCounts() {
+ ExponentialBackOff backOff = new ExponentialBackOff(500L);
+
+ assertThat(backOff.delayMsFor(10)).isEqualTo(30_000L);
+ assertThat(backOff.delayMsFor(200)).isEqualTo(30_000L);
+ }
+
@Test
void waitBeforeRetry_actuallySleepsApproximatelyTheComputedDelay() {
ExponentialBackOff backOff = new ExponentialBackOff(20L);
diff --git a/services/order-service/Dockerfile b/services/order-service/Dockerfile
index fef0cd1..ebfee5d 100644
--- a/services/order-service/Dockerfile
+++ b/services/order-service/Dockerfile
@@ -2,7 +2,7 @@
# The reactor's root pom.xml lists every module, so Maven needs the whole
# source tree present even though this image only ships order-service.
-FROM maven:3.9-eclipse-temurin-21 AS build
+FROM maven:3.9-eclipse-temurin-25 AS build
WORKDIR /workspace
COPY pom.xml .
@@ -11,11 +11,11 @@ COPY services services
RUN mvn -q -pl services/order-service -am -DskipTests package
-FROM eclipse-temurin:21-jre-alpine
+FROM eclipse-temurin:25-jre-alpine
RUN addgroup -S etch && adduser -S etch -G etch
WORKDIR /app
COPY --from=build /workspace/services/order-service/target/order-service.jar app.jar
USER etch
EXPOSE 8081
-ENTRYPOINT ["java", "-jar", "/app/app.jar"]
+ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
diff --git a/services/order-service/pom.xml b/services/order-service/pom.xml
index d03505e..8da6846 100644
--- a/services/order-service/pom.xml
+++ b/services/order-service/pom.xml
@@ -55,14 +55,6 @@
mysql-connector-j
runtime
-
- org.flywaydb
- flyway-core
-
-
- org.flywaydb
- flyway-mysql
-
org.springframework.boot
diff --git a/services/order-service/src/main/resources/application.yml b/services/order-service/src/main/resources/application.yml
index ff800b7..e5e76d7 100644
--- a/services/order-service/src/main/resources/application.yml
+++ b/services/order-service/src/main/resources/application.yml
@@ -11,21 +11,23 @@ spring:
jpa:
hibernate:
- ddl-auto: validate
+ ddl-auto: update
+ defer-datasource-initialization: true
open-in-view: false
properties:
hibernate:
format_sql: false
- flyway:
- enabled: true
- locations: classpath:db/migration
+ sql:
+ init:
+ mode: always
kafka:
bootstrap-servers: ${KAFKA_BOOTSTRAP_SERVERS:localhost:9092}
server:
port: 8081
+ shutdown: graceful
management:
endpoints:
diff --git a/services/order-service/src/main/resources/data.sql b/services/order-service/src/main/resources/data.sql
new file mode 100644
index 0000000..8de4f3b
--- /dev/null
+++ b/services/order-service/src/main/resources/data.sql
@@ -0,0 +1,4 @@
+INSERT IGNORE INTO users (email, phone, created_at) VALUES
+ ('ada.lovelace@example.com', '+15550100001', CURRENT_TIMESTAMP),
+ ('grace.hopper@example.com', '+15550100002', CURRENT_TIMESTAMP),
+ ('alan.turing@example.com', '+15550100003', CURRENT_TIMESTAMP);
diff --git a/services/order-service/src/main/resources/db/migration/V1__init_schema.sql b/services/order-service/src/main/resources/db/migration/V1__init_schema.sql
deleted file mode 100644
index ca9bb11..0000000
--- a/services/order-service/src/main/resources/db/migration/V1__init_schema.sql
+++ /dev/null
@@ -1,21 +0,0 @@
-CREATE TABLE users (
- id BIGINT AUTO_INCREMENT PRIMARY KEY,
- email VARCHAR(255) NOT NULL,
- phone VARCHAR(20) NOT NULL,
- created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
- CONSTRAINT uq_users_email UNIQUE (email)
-) ENGINE = InnoDB;
-
-CREATE TABLE orders (
- id BIGINT AUTO_INCREMENT PRIMARY KEY,
- user_id BIGINT NOT NULL,
- order_number VARCHAR(40) NOT NULL,
- status VARCHAR(30) NOT NULL,
- total DECIMAL(12, 2) NOT NULL,
- channels VARCHAR(100) NOT NULL,
- created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
- CONSTRAINT uq_orders_order_number UNIQUE (order_number),
- CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES users (id)
-) ENGINE = InnoDB;
-
-CREATE INDEX idx_orders_user_id ON orders (user_id);
diff --git a/services/order-service/src/main/resources/db/migration/V2__seed_demo_users.sql b/services/order-service/src/main/resources/db/migration/V2__seed_demo_users.sql
deleted file mode 100644
index 5ffc0ab..0000000
--- a/services/order-service/src/main/resources/db/migration/V2__seed_demo_users.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO users (email, phone) VALUES
- ('ada.lovelace@example.com', '+15550100001'),
- ('grace.hopper@example.com', '+15550100002'),
- ('alan.turing@example.com', '+15550100003');
diff --git a/services/order-service/src/test/java/com/etch/orderservice/integration/OrderIntegrationTest.java b/services/order-service/src/test/java/com/etch/orderservice/integration/OrderIntegrationTest.java
index e0932d3..4011147 100644
--- a/services/order-service/src/test/java/com/etch/orderservice/integration/OrderIntegrationTest.java
+++ b/services/order-service/src/test/java/com/etch/orderservice/integration/OrderIntegrationTest.java
@@ -69,7 +69,7 @@ static void registerProperties(DynamicPropertyRegistry registry) {
@Test
void creatingAnOrder_persistsItAndPublishesOrderCreatedEvent() {
- // seeded by Flyway's V2__seed_demo_users.sql, which runs against the container on startup
+ // seeded by data.sql, which runs against the container on startup
OrderRequest request = new OrderRequest(1L, "ORD-IT-1001", new BigDecimal("42.50"), List.of(NotificationChannel.EMAIL));
ResponseEntity response = restTemplate.postForEntity("/orders", request, OrderResponse.class);
diff --git a/services/sms-service/Dockerfile b/services/sms-service/Dockerfile
index e74f9d8..b126971 100644
--- a/services/sms-service/Dockerfile
+++ b/services/sms-service/Dockerfile
@@ -1,6 +1,6 @@
# Build from the repository root: docker build -f services/sms-service/Dockerfile .
-FROM maven:3.9-eclipse-temurin-21 AS build
+FROM maven:3.9-eclipse-temurin-25 AS build
WORKDIR /workspace
COPY pom.xml .
@@ -9,11 +9,11 @@ COPY services services
RUN mvn -q -pl services/sms-service -am -DskipTests package
-FROM eclipse-temurin:21-jre-alpine
+FROM eclipse-temurin:25-jre-alpine
RUN addgroup -S etch && adduser -S etch -G etch
WORKDIR /app
COPY --from=build /workspace/services/sms-service/target/sms-service.jar app.jar
USER etch
EXPOSE 8084
-ENTRYPOINT ["java", "-jar", "/app/app.jar"]
+ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
diff --git a/services/sms-service/src/main/java/com/etch/smsservice/service/SmsSendService.java b/services/sms-service/src/main/java/com/etch/smsservice/service/SmsSendService.java
index e6efd0f..5243004 100644
--- a/services/sms-service/src/main/java/com/etch/smsservice/service/SmsSendService.java
+++ b/services/sms-service/src/main/java/com/etch/smsservice/service/SmsSendService.java
@@ -27,6 +27,11 @@ public class SmsSendService {
public SmsSendService(@Value("${etch.simulation.unavailable-rate:0.0}") double unavailableRate,
@Value("${etch.simulation.failure-rate:0.05}") double failureRate) {
+ if (unavailableRate < 0 || failureRate < 0 || unavailableRate + failureRate > 1.0) {
+ throw new IllegalArgumentException(
+ "etch.simulation rates must be non-negative and sum to at most 1.0 (unavailable="
+ + unavailableRate + ", failure=" + failureRate + ")");
+ }
this.unavailableRate = unavailableRate;
this.failureRate = failureRate;
}
diff --git a/services/sms-service/src/main/resources/application.yml b/services/sms-service/src/main/resources/application.yml
index 8407756..9f3345d 100644
--- a/services/sms-service/src/main/resources/application.yml
+++ b/services/sms-service/src/main/resources/application.yml
@@ -4,6 +4,7 @@ spring:
server:
port: 8084
+ shutdown: graceful
etch:
simulation:
diff --git a/services/sms-service/src/test/java/com/etch/smsservice/service/SmsSendServiceTest.java b/services/sms-service/src/test/java/com/etch/smsservice/service/SmsSendServiceTest.java
index 9dcdc71..b8602fe 100644
--- a/services/sms-service/src/test/java/com/etch/smsservice/service/SmsSendServiceTest.java
+++ b/services/sms-service/src/test/java/com/etch/smsservice/service/SmsSendServiceTest.java
@@ -41,4 +41,16 @@ void raisesServiceUnavailableWhenOutageIsCertain() {
.isInstanceOf(ResponseStatusException.class)
.hasMessageContaining("503");
}
+
+ @Test
+ void rejectsRatesThatSumPastOne() {
+ assertThatThrownBy(() -> new SmsSendService(0.6, 0.6))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void rejectsNegativeRates() {
+ assertThatThrownBy(() -> new SmsSendService(-0.1, 0.0))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
}
diff --git a/shared/common-utils/src/main/java/com/etch/common/logging/CorrelationIdFilter.java b/shared/common-utils/src/main/java/com/etch/common/logging/CorrelationIdFilter.java
index 4c07290..ad784ea 100644
--- a/shared/common-utils/src/main/java/com/etch/common/logging/CorrelationIdFilter.java
+++ b/shared/common-utils/src/main/java/com/etch/common/logging/CorrelationIdFilter.java
@@ -10,20 +10,25 @@
import java.io.IOException;
import java.util.UUID;
+import java.util.regex.Pattern;
/**
* Reads {@code X-Correlation-Id} from the incoming request (set by the API
* Gateway, or by an upstream service when one hop calls another) and puts
* it in the SLF4J MDC so every log line for the request can be tied
- * together, then echoes it back on the response.
+ * together, then echoes it back on the response. Values that don't look
+ * like an id (too long, odd characters) are replaced with a fresh UUID so
+ * a client can't push arbitrary text into the logs.
*/
public class CorrelationIdFilter extends OncePerRequestFilter {
+ private static final Pattern VALID_ID = Pattern.compile("[A-Za-z0-9._-]{1,64}");
+
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String correlationId = request.getHeader(CorrelationIdConstants.HEADER_NAME);
- if (!StringUtils.hasText(correlationId)) {
+ if (!StringUtils.hasText(correlationId) || !VALID_ID.matcher(correlationId).matches()) {
correlationId = UUID.randomUUID().toString();
}
try {
diff --git a/shared/common-utils/src/test/java/com/etch/common/logging/CorrelationIdFilterTest.java b/shared/common-utils/src/test/java/com/etch/common/logging/CorrelationIdFilterTest.java
index 8b0547c..a3f7fb0 100644
--- a/shared/common-utils/src/test/java/com/etch/common/logging/CorrelationIdFilterTest.java
+++ b/shared/common-utils/src/test/java/com/etch/common/logging/CorrelationIdFilterTest.java
@@ -48,6 +48,30 @@ void generatesAnIdWhenTheHeaderIsBlank() throws Exception {
assertThat(response.getHeader(CorrelationIdConstants.HEADER_NAME)).isNotBlank();
}
+ @Test
+ void replacesAHeaderWithUnexpectedCharacters() throws Exception {
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.addHeader(CorrelationIdConstants.HEADER_NAME, "abc 123