From 4a6b7f33d348d51337f8b01422970ed89c2556fc Mon Sep 17 00:00:00 2001 From: Tole Date: Tue, 14 Jul 2026 22:10:36 +0200 Subject: [PATCH 1/7] feat(gateway): scaffold circuit breaker for task-service route MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add spring-cloud-starter-circuitbreaker-reactor-resilience4j dependency to api-gateway. Declare taskServiceBreaker instance with count-based sliding window (size 10, min 5 calls, 50% failure rate threshold, 10s wait duration in open state, 3 permitted calls in half-open). Wrap /tasks/** route with the CircuitBreaker filter and forward to /fallback/tasks on failure. Add FallbackController returning an RFC 7807 problem+json 503 response consistent with the platform error handling convention. End-to-end verification with Docker Compose deferred to next session. --- feat(gateway): scaffolding del circuit breaker para la ruta de task-service Añade la dependencia spring-cloud-starter-circuitbreaker-reactor- resilience4j al api-gateway. Declara la instancia taskServiceBreaker con ventana deslizante por conteo (tamaño 10, mínimo 5 llamadas, umbral de fallo del 50%, espera de 10s en estado open, 3 llamadas permitidas en half-open). Envuelve la ruta /tasks/** con el filter CircuitBreaker y redirige a /fallback/tasks en caso de fallo. Añade FallbackController que devuelve una respuesta problem+json 503 según RFC 7807, coherente con el manejo de errores del resto de la plataforma. Verificación end-to-end con Docker Compose diferida a la siguiente sesión. --- api-gateway/pom.xml | 5 ++- .../gateway/fallback/FallbackController.java | 43 +++++++++++++++++++ .../src/main/resources/application.yml | 17 ++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 api-gateway/src/main/java/com/mtole/gateway/fallback/FallbackController.java diff --git a/api-gateway/pom.xml b/api-gateway/pom.xml index 72e48c5..776056e 100644 --- a/api-gateway/pom.xml +++ b/api-gateway/pom.xml @@ -27,7 +27,10 @@ org.springframework.cloud spring-cloud-starter-gateway-server-webflux - + + org.springframework.cloud + spring-cloud-starter-circuitbreaker-reactor-resilience4j + io.projectreactor reactor-test diff --git a/api-gateway/src/main/java/com/mtole/gateway/fallback/FallbackController.java b/api-gateway/src/main/java/com/mtole/gateway/fallback/FallbackController.java new file mode 100644 index 0000000..5ae4be0 --- /dev/null +++ b/api-gateway/src/main/java/com/mtole/gateway/fallback/FallbackController.java @@ -0,0 +1,43 @@ +package com.mtole.gateway.fallback; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ProblemDetail; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +/** + * Fallback endpoints invoked internally by the {@code CircuitBreaker} + * filter when a downstream service is unavailable or the breaker is open. + * + *

Each fallback returns an RFC 7807 {@code application/problem+json} + * response with HTTP 503, consistent with the error handling convention + * used across the platform. + * + *

These endpoints are not intended for direct client consumption: + * they are reached via {@code forward:} directives from the gateway + * routes' {@code CircuitBreaker} filter. + */ +@RestController +@RequestMapping("/fallback") +public class FallbackController { + + @RequestMapping("/tasks") + public Mono> taskServiceFallback() { + ProblemDetail problem = ProblemDetail.forStatusAndDetail( + HttpStatus.SERVICE_UNAVAILABLE, + "The task service is temporarily unavailable. Please retry in a few seconds." + ); + problem.setTitle("Service Unavailable"); + problem.setInstance(java.net.URI.create("/fallback/tasks")); + + return Mono.just( + ResponseEntity + .status(HttpStatus.SERVICE_UNAVAILABLE) + .contentType(MediaType.APPLICATION_PROBLEM_JSON) + .body(problem) + ); + } +} diff --git a/api-gateway/src/main/resources/application.yml b/api-gateway/src/main/resources/application.yml index b7608f5..a84af5c 100644 --- a/api-gateway/src/main/resources/application.yml +++ b/api-gateway/src/main/resources/application.yml @@ -17,6 +17,11 @@ spring: uri: http://localhost:8082 predicates: - Path=/tasks/** + filters: + - name: CircuitBreaker + args: + name: taskServiceBreaker + fallbackUri: forward:/fallback/tasks - id: task-service-categories-route uri: http://localhost:8082 predicates: @@ -43,3 +48,15 @@ management: jwt: secret: ${JWT_SECRET:ZGV2T25seVNlY3JldE5vdEZvclByb2R1Y3Rpb25DaGFuZ2VNZVBsZWFzZU1pbjMyQ2hhcnM=} + +resilience4j: + circuitbreaker: + instances: + taskServiceBreaker: + registerHealthIndicator: true + slidingWindowType: COUNT_BASED + slidingWindowSize: 10 + minimumNumberOfCalls: 5 + failureRateThreshold: 50 + waitDurationInOpenState: 10s + permittedNumberOfCallsInHalfOpenState: 3 From ea0c3d0405ba2a65012f9e09eb678d23ce195630 Mon Sep 17 00:00:00 2001 From: Tole Date: Wed, 15 Jul 2026 08:52:06 +0200 Subject: [PATCH 2/7] fix: post-decomposition fixes for circuit breaker verification MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix TaskSpecifications.byUserId to reference the flat userId column after the monolith → microservices decomposition (was navigating root.get("user").get("id") which no longer exists). Refactor gateway routing config to externalise downstream URIs per profile via placeholders (services.auth-uri, services.task-uri). The previous approach duplicated the entire routes list between application.yml and application-docker.yml, causing filters added to base (like the new CircuitBreaker) to silently disappear under the docker profile. Enable circuit breaker health indicator at the management level (management.health.circuitbreakers.enabled: true) and expose the /actuator/circuitbreakers endpoint for direct observability of breaker state, in addition to the aggregated health endpoint. --- .../src/main/resources/application-docker.yml | 36 ++++--------------- .../src/main/resources/application.yml | 25 +++++++------ .../mtole/task/tasks/TaskSpecifications.java | 2 +- 3 files changed, 20 insertions(+), 43 deletions(-) diff --git a/api-gateway/src/main/resources/application-docker.yml b/api-gateway/src/main/resources/application-docker.yml index 92a3c50..24ee909 100644 --- a/api-gateway/src/main/resources/application-docker.yml +++ b/api-gateway/src/main/resources/application-docker.yml @@ -1,30 +1,8 @@ # Perfil "docker": activo cuando SPRING_PROFILES_ACTIVE=docker. -# Sobrescribe las URIs de las rutas para usar DNS interno de Compose -# (auth-service, task-service) en vez de localhost. - -spring: - cloud: - gateway: - server: - webflux: - routes: - - id: auth-service-route - uri: http://auth-service:8081 - predicates: - - Path=/auth/** - - id: task-service-route - uri: http://task-service:8082 - predicates: - - Path=/tasks/** - - id: task-service-categories-route - uri: http://task-service:8082 - predicates: - - Path=/categories/** - - id: task-service-activity-route - uri: http://task-service:8082 - predicates: - - Path=/me/activity/** - - id: auth-users-route - uri: http://auth-service:8081 - predicates: - - Path=/users/** +# Sobrescribe únicamente los hostnames de los servicios downstream para +# usar el DNS interno de Compose. La estructura de rutas (predicates, +# filters, ids) vive una sola vez en application.yml y se reutiliza +# entre perfiles. +services: + auth-uri: http://auth-service:8081 + task-uri: http://task-service:8082 diff --git a/api-gateway/src/main/resources/application.yml b/api-gateway/src/main/resources/application.yml index a84af5c..e340b0a 100644 --- a/api-gateway/src/main/resources/application.yml +++ b/api-gateway/src/main/resources/application.yml @@ -1,3 +1,7 @@ +services: + auth-uri: http://localhost:8081 + task-uri: http://localhost:8082 + server: port: 8080 @@ -10,28 +14,20 @@ spring: webflux: routes: - id: auth-service-route - uri: http://localhost:8081 + uri: ${services.auth-uri} predicates: - Path=/auth/** - id: task-service-route - uri: http://localhost:8082 + uri: ${services.task-uri} predicates: - - Path=/tasks/** + - Path=/tasks/**,/categories/**,/me/activity/** filters: - name: CircuitBreaker args: name: taskServiceBreaker fallbackUri: forward:/fallback/tasks - - id: task-service-categories-route - uri: http://localhost:8082 - predicates: - - Path=/categories/** - - id: task-service-activity-route - uri: http://localhost:8082 - predicates: - - Path=/me/activity/** - id: auth-users-route - uri: http://localhost:8081 + uri: ${services.auth-uri} predicates: - Path=/users/** @@ -39,12 +35,15 @@ management: endpoints: web: exposure: - include: health, info, gateway + include: health, info, gateway, circuitbreakers, circuitbreakerevents endpoint: health: show-details: always gateway: access: read-only + health: + circuitbreakers: + enabled: true jwt: secret: ${JWT_SECRET:ZGV2T25seVNlY3JldE5vdEZvclByb2R1Y3Rpb25DaGFuZ2VNZVBsZWFzZU1pbjMyQ2hhcnM=} diff --git a/task-service/src/main/java/com/mtole/task/tasks/TaskSpecifications.java b/task-service/src/main/java/com/mtole/task/tasks/TaskSpecifications.java index b57f243..c9244fa 100644 --- a/task-service/src/main/java/com/mtole/task/tasks/TaskSpecifications.java +++ b/task-service/src/main/java/com/mtole/task/tasks/TaskSpecifications.java @@ -11,7 +11,7 @@ private TaskSpecifications() { } public static Specification byUserId(Long userId) { - return (root, query, cb) -> cb.equal(root.get("user").get("id"), userId); + return (root, query, cb) -> cb.equal(root.get("userId"), userId); } public static Specification byStatus(TaskStatus status) { From 8c641b45fdc1c62913769c7702b2c93408efdb79 Mon Sep 17 00:00:00 2001 From: Tole Date: Wed, 15 Jul 2026 09:21:14 +0200 Subject: [PATCH 3/7] docs: add ADR-005 on externalising downstream hostnames via per-profile placeholders Documents the refactoring applied during Session 8 Part 2 of Fase 10 to eliminate the duplication of the routes list between application.yml and application-docker.yml. The pattern preserved was structural: keep routes declared once in the base file with placeholder-referenced hostnames, and let per-profile files override only the actual variance. Follows Nygard's format consistent with ADR-004. --- ...r-005-config-externalization-by-profile.md | 280 ++++++++++++++++++ 1 file changed, 280 insertions(+) create mode 100644 docs/adr-005-config-externalization-by-profile.md diff --git a/docs/adr-005-config-externalization-by-profile.md b/docs/adr-005-config-externalization-by-profile.md new file mode 100644 index 0000000..c8b6b36 --- /dev/null +++ b/docs/adr-005-config-externalization-by-profile.md @@ -0,0 +1,280 @@ +# ADR-005: Externalising Downstream Hostnames via Per-Profile Placeholders + +## Status + +Accepted — 2026-07-15. + +## Context + +The `api-gateway` module supports two execution scenarios that differ +only in how it reaches the downstream services: + +- **Local development** (`spring-boot:run` and `spring-boot:test-run`): + each service runs on the developer's host, so route URIs must + point at `localhost:808X`. +- **Docker Compose** (`docker compose up`): services live on an + internal bridge network, so route URIs must point at internal DNS + names (`auth-service:8081`, `task-service:8082`). + +The original configuration — inherited from the initial gateway +scaffolding during Fase 10 operational — encoded this difference by +duplicating the entire `spring.cloud.gateway.server.webflux.routes` +list between two files: `application.yml` (base) declared the five +routes pointing at localhost, and `application-docker.yml` declared +**the same five routes** pointing at the Compose DNS names. The two +lists were identical in every field except for the hostnames. +Roughly twenty-five lines were duplicated per profile. + +The implicit justification for this duplication was *"Spring Boot +activates the docker profile inside the container, and that profile +overrides the URIs"* — treating the override as a natural +per-environment tweak rather than as full structural replacement. + +### How the problem surfaced + +While adding a `CircuitBreaker` filter to the `/tasks/**` route in +`application.yml` (the base file only), the filter **did not apply** +when the application ran under the `docker` profile. Empirical +verification revealed it: requests to `/tasks/**` reached the task +service, but the breaker's `bufferedCalls` counter stayed at zero. +The filter was not seeing any of the traffic. + +Introspection through `/actuator/gateway/routes` confirmed that the +routes effectively loaded under the docker profile **did not include +the filter**, even though `application.yml` declared it explicitly on +the corresponding route. + +### Root cause + +When Spring Boot merges YAML across profiles, **it replaces complete +lists in the configuration tree; it does not merge list elements one +by one**. When `application-docker.yml` redefines +`spring.cloud.gateway.server.webflux.routes` as a five-element list, +that list wholesale replaces the base list. Individual elements are +**not combined by `id`**. Any property present in the base list but +absent from the override (a `filters:` block added to a specific +route, for example) is silently dropped at profile activation time. + +This behaviour is not a bug in Spring — it is consistent with the +"override is replacement" model for complex types. But it is a +classic source of multi-environment configuration bugs: **local CI +passes, target-environment runtime fails silently**. The bug is +particularly insidious because the diff between profiles looks +intentional and self-contained until the moment something in the +base file drifts away from what the override still says. + +Constraints acknowledged for this decision: + +- The gateway is the only module in the system that faces this + structural duplication. Auth and task services have small + per-profile overrides limited to actual environment differences + (database URLs, Mongo URIs). They do not exhibit the same problem. +- The team is a single developer. Any pattern chosen must survive + months of dormancy between edits without relying on institutional + memory to "remember to keep both files in sync." +- The project targets consultancy and enterprise Java positions + where multi-environment configuration is standard. The pattern + should be recognisable to reviewers, not a bespoke invention. + +## Decision + +Refactor the gateway configuration so that **only the hostnames** +— the single dimension that legitimately varies per environment — +live in per-profile files. The **structure of the routes** +(predicates, filters, ids, ordering) lives **exactly once**, in the +base `application.yml`, and references the hostnames through Spring +placeholders (`${property.name}`). + +Concretely: + +- A new top-level `services:` block in `application.yml` declares + two properties, `services.auth-uri` and `services.task-uri`, with + the local development values as defaults. +- Every route in `application.yml` references these properties via + `${services.auth-uri}` and `${services.task-uri}` instead of + hard-coded URIs. +- `application-docker.yml` is stripped down to a `services:` block + overriding those two properties with the internal Compose DNS + names. It no longer contains any part of the `spring.cloud.gateway` + tree. +- Any future environment (a hypothetical `application-staging.yml`, + `application-prod.yml`) follows the same shape: three lines + overriding `services.*`, nothing else. + +### Alternatives considered + +**Alternative A — Replicate the filter in `application-docker.yml`.** +The narrow fix to the immediate bug: add the `filters:` block to the +`task-service-route` in the docker override, mirroring the base. +Reasoned rejection: the fix does not address the structural cause. +The next time any change lands in a base route — a CORS filter, a +rate limiter, a header rewrite, an additional predicate — the same +silent drift will happen. The bug's category remains open; +Alternative A only closes a single instance of it. Worse, applying +this fix normalises the duplication as intentional and makes future +drifts easier to overlook. + +**Alternative B — Placeholders with inline default values.** +Use the syntax `uri: ${services.task-uri:http://localhost:8082}` +without declaring the `services:` block in the base at all. +Reasoned rejection: this disperses configuration across the file. +The default value for a property lives at the point of use rather +than in a dedicated, self-documenting `services:` block. IntelliJ +loses the ability to autocomplete the property (there is no +declaration to autocomplete against), and a future +`additional-spring-configuration-metadata.json` entry has nothing +to attach to. The inline-default syntax is valid Spring, but it +optimises for terseness at the cost of discoverability. + +**Alternative C — Keep the routes separate per endpoint after the +refactor, in case future filters need to diverge.** +Preserve `/tasks/**`, `/categories/**`, and `/me/activity/**` as +three separate route definitions in the base file even after +eliminating the duplication problem. Reasoned rejection: no evidence +justifies the divergence. The three routes point at the same bounded +context and share the same downstream health signal. Modelling them +as independent routes would suggest they can fail independently, +which is not the case at the infrastructure level. Applying the +same principle at the resilience layer, a per-endpoint breaker +would open and close out of sync with its siblings for no semantic +gain. If a legitimate need for per-resource filters emerges later, +splitting one unified route into three specialised ones is a five +minute refactor contained in a single file. + +## Consequences + +### Positive + +- **Route structure lives in exactly one place.** Changes to + predicates, filters, order, or identifiers apply to every profile + automatically. Adding a new filter to the base file is now safe: + it cannot be silently omitted from any environment because there + is no per-environment copy to omit it from. +- **Per-profile files reflect only what actually varies.** The + `application-docker.yml` file went from twenty-five lines + duplicating structure to three lines overriding hostnames. The + intent of the file is now legible at a glance: *"this is where + we tell the gateway how to reach the neighbours in Compose."* +- **Scalable to additional environments.** A future + `application-staging.yml` for a cloud deployment is three lines, + not twenty-five. The scaling cost of adding an environment is + linear in the number of things that actually differ (hostnames, + credentials, feature flags), not in the size of the module's + configuration. +- **Silent desynchronisation is structurally impossible.** The bug + category that surfaced during the CircuitBreaker verification + cannot recur in this form. It is not that the developer must + remember to keep files in sync — it is that there is nothing to + keep in sync. +- **The pattern reads as idiomatic Spring.** Placeholders with + per-profile property overrides is a documented, widely-used + approach in the Spring ecosystem. A reviewer sees a familiar + shape, not a project-specific convention. + +### Negative + +- **One extra level of indirection when reading a route.** A reader + who wants to know *"what URI does `task-service-route` point at + under the docker profile?"* must resolve the placeholder mentally + by looking up the value in `application-docker.yml`. This is a + small, familiar cost for anyone working with Spring; it is called + out here for completeness. +- **IntelliJ marks a "Scalar value is not allowed here" warning on + the `services:` block.** The IDE validates YAML against the Spring + Boot configuration schema and does not recognise + project-defined properties. The warning is cosmetic and does not + affect compilation, tests, or runtime. It is registered as + technical debt to be resolved by declaring the properties in + `META-INF/additional-spring-configuration-metadata.json`, which + both silences the warning and documents the properties formally + for downstream consumers of the artefact. +- **Tests instantiating the base configuration without an active + profile use the local URIs.** This is correct for local tests and + matches previous behaviour, but any test that needs to exercise + the gateway against alternate hostnames must activate an + appropriate profile explicitly. + +### Neutral + +- The decision commits to placeholder syntax as the mechanism for + per-environment variation. If future configuration needs a + fundamentally different variation model (feature flags conditioned + on runtime discovery, for example), it will be introduced + alongside placeholders rather than replacing them. + +## Verification + +The decision is verifiable operationally with the running compose +stack. From the repository root, after `docker compose up --build -d`: + +**Route structure loaded under the docker profile includes the +filter defined in the base file:** + +```bash +curl -s http://localhost:8080/actuator/gateway/routes | python3 -m json.tool +``` + +The response includes the unified `task-service-route` with +predicates `[/tasks/**, /categories/**, /me/activity/**]` and a +`CircuitBreaker` filter referencing `taskServiceBreaker` and +`forward:/fallback/tasks`. The URIs resolve to the Compose DNS +names (`http://task-service:8082`), confirming that the docker +profile applied the hostname override without erasing the filter. + +**The refactor is exercised through a route that was not touched by +the original filter definition:** + +```bash +docker compose stop task-service + +TOKEN=$(curl -s -X POST http://localhost:8080/auth/login \ + -H "Content-Type: application/json" \ + -d '{"email":"alice@example.com","password":"Password123!"}' \ + | jq -r '.accessToken') + +curl -s -w "\nHTTP %{http_code} — %{time_total}s\n" \ + -H "Authorization: Bearer $TOKEN" \ + http://localhost:8080/categories +``` + +The response is `HTTP 503` with the RFC 7807 `application/problem+json` +payload from the `/fallback/tasks` endpoint in approximately one +second (the first call after the breaker opens still incurs the real +downstream timeout; subsequent calls return in milliseconds). + +The route being tested is `/categories/**`, which had no filter in +the original base file. Its coverage by the breaker demonstrates +that the unified `task-service-route` correctly serves all three +downstream paths under the docker profile. + +**Reverting to a working baseline restores normal responses:** + +```bash +docker compose start task-service +# wait for tmm-task-service to report healthy + +curl -s -w "\nHTTP %{http_code} — %{time_total}s\n" \ + -H "Authorization: Bearer $TOKEN" \ + http://localhost:8080/categories +``` + +The response is `HTTP 200` with the paginated payload from +`task-service`, confirming that the placeholder-based configuration +resolves correctly to the internal Compose hostname under normal +operating conditions. + +## Related decisions + +- Border authentication at the gateway: + [ADR-004](adr-004-border-authentication.md). The route structure + refactored by this ADR is the same structure through which the + gateway propagates the authenticated identity as `X-User-Id`. +- The `CircuitBreaker` filter whose silent absence exposed the + duplication problem is documented in the module's README + (Getting started section) and will be covered in a dedicated + ADR-006 once the resilience module is complete (CircuitBreaker + + TimeLimiter + Retry). +- Technical debt: declare `services.auth-uri` and `services.task-uri` + in `api-gateway/src/main/resources/META-INF/additional-spring-configuration-metadata.json` + to silence IntelliJ's schema validation and document the + properties formally for tooling. From 267688f377bdd9ce61630a5744811f10f3e8d164 Mon Sep 17 00:00:00 2001 From: Tole Date: Thu, 16 Jul 2026 08:46:53 +0200 Subject: [PATCH 4/7] feat(gateway): add Retry filter to task-service route Wraps Retry inside CircuitBreaker on the unified task-service-route. Retry configured with retries=2, methods=GET, series=SERVER_ERROR, exponential backoff (500ms firstBackoff, 1500ms maxBackoff, factor 2). Empirical verification with task-service stopped: - HTTP 503 fallback served in ~1020ms consistently - Circuit breaker sees 1 aggregated failure per client request - CircuitBreaker order=1 (outer), Retry order=2 (inner) confirmed via /actuator/gateway/routes Refs: feature/circuit-breaker branch, ADR-006 pending (TimeLimiter + ADR-006 to be added in next session) --- api-gateway/src/main/resources/application.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/api-gateway/src/main/resources/application.yml b/api-gateway/src/main/resources/application.yml index e340b0a..ba92af4 100644 --- a/api-gateway/src/main/resources/application.yml +++ b/api-gateway/src/main/resources/application.yml @@ -26,6 +26,16 @@ spring: args: name: taskServiceBreaker fallbackUri: forward:/fallback/tasks + - name: Retry + args: + retries: 2 + methods: GET + series: SERVER_ERROR + backoff: + firstBackoff: 500ms + maxBackoff: 1500ms + factor: 2 + basedOnPreviousValue: false - id: auth-users-route uri: ${services.auth-uri} predicates: @@ -59,3 +69,4 @@ resilience4j: failureRateThreshold: 50 waitDurationInOpenState: 10s permittedNumberOfCallsInHalfOpenState: 3 + From 565bfb49311a791851fbb0e30e7575680da48afd Mon Sep 17 00:00:00 2001 From: Tole Date: Fri, 17 Jul 2026 08:15:09 +0200 Subject: [PATCH 5/7] feat(gateway): configure TimeLimiter explicitly for taskServiceBreaker Add resilience4j.timelimiter instance 'taskServiceBreaker' with timeoutDuration 5s and cancelRunningFuture true. This makes explicit the timeout mechanism previously acting as an invisible 1s default from Spring Cloud CircuitBreaker's integrated TimeLimiter. Empirically verified in Sesion 10: - With integrated default (1s): curl to paused downstream ~1.02s - With explicit config (5s): curl to paused downstream ~5.02s - The TimeLimiter is the dominant timeout mechanism, wrapping the entire operation including Retry attempts. Document per-route metadata timeouts as ineffective under the new spring.cloud.gateway.server.webflux prefix in SCG 2025.0.0. Kept in config with explanatory comment pointing to ADR-006 for future investigation. --- api-gateway/src/main/resources/application.yml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/api-gateway/src/main/resources/application.yml b/api-gateway/src/main/resources/application.yml index ba92af4..2b059f6 100644 --- a/api-gateway/src/main/resources/application.yml +++ b/api-gateway/src/main/resources/application.yml @@ -36,6 +36,14 @@ spring: maxBackoff: 1500ms factor: 2 basedOnPreviousValue: false + # Per-route timeouts declared per official docs. Verified + # empirically to have NO effect under the new + # spring.cloud.gateway.server.webflux prefix in SCG 2025.0.0. + # Effective timeout is defined by resilience4j.timelimiter + # instance 'taskServiceBreaker' (5s). See ADR-006. + metadata: + response-timeout: 2000 + connect-timeout: 1000 - id: auth-users-route uri: ${services.auth-uri} predicates: @@ -69,4 +77,8 @@ resilience4j: failureRateThreshold: 50 waitDurationInOpenState: 10s permittedNumberOfCallsInHalfOpenState: 3 - + timelimiter: + instances: + taskServiceBreaker: + timeoutDuration: 5s + cancelRunningFuture: true From e8a1affe3f1b6ed25ba06ea43be7fe75c90704a0 Mon Sep 17 00:00:00 2001 From: Tole Date: Fri, 17 Jul 2026 08:33:05 +0200 Subject: [PATCH 6/7] docs: add ADR-006 on resilience patterns at the gateway --- docs/adr-006-resilience-patterns.md | 508 ++++++++++++++++++++++++++++ 1 file changed, 508 insertions(+) create mode 100644 docs/adr-006-resilience-patterns.md diff --git a/docs/adr-006-resilience-patterns.md b/docs/adr-006-resilience-patterns.md new file mode 100644 index 0000000..8b58652 --- /dev/null +++ b/docs/adr-006-resilience-patterns.md @@ -0,0 +1,508 @@ +# ADR-006: Resilience Patterns at the Gateway + +## Status + +Accepted — 2026-07-17. + +## Context + +The `api-gateway` module is the single entry point for all client +traffic to the microservices system. It routes requests to +`auth-service` and `task-service` on the internal Compose network, +propagates authenticated identity (see ADR-004), and returns +responses to callers. Its availability is therefore not an +implementation detail but a property of the system as a whole: if +the gateway becomes unresponsive, every downstream service becomes +effectively unreachable regardless of its own health. + +The scenarios that threaten gateway availability are not primarily +those where a downstream service is cleanly down. A dead process +produces immediate `Connection Refused` responses at the TCP layer, +which the gateway observes in milliseconds and can react to +gracefully. The dangerous scenarios are the ones where a downstream +is **sick but not dead**: a saturated PostgreSQL under load, a JVM +in a long garbage-collection pause, a network path with dropped +packets and slow retransmits, a Mongo primary in the middle of a +failover election. In all of these, the TCP handshake with the +downstream completes normally, the request bytes arrive at its +kernel, but the response never arrives — or arrives after tens of +seconds — because the downstream process is stalled internally. + +From the gateway's perspective these two situations look +identical at the network layer up to the moment a response is +expected. The distinction only becomes visible if the gateway +enforces an explicit ceiling on how long it will wait. Without +such a ceiling, the reactive request pipeline holds the +downstream connection, the caller thread, and the associated +memory attached to the operation until either the operating +system's stack timeout fires (typically tens of seconds) or the +caller gives up. Under concurrent load, this behaviour compounds: +one sick downstream turns healthy gateway capacity into a queue +of pending calls waiting on a service that will not answer. The +gateway becomes unable to serve traffic to healthy neighbours +because its resources are exhausted holding requests to the sick +one. This is the **cascading failure** pattern documented in the +resilience literature since at least the Netflix Hystrix era; it +was the original motivation for the Circuit Breaker pattern +itself. + +No single resilience mechanism eliminates the risk. A CircuitBreaker +alone identifies a downstream as unhealthy after enough failures +accumulate, but if each failure takes tens of seconds to observe, +the breaker opens too late — the damage to gateway resources is +already done by the time the statistical threshold trips. A +Retry alone amortises transient network blips of a few hundred +milliseconds, but against a genuinely dead downstream it multiplies +the effective traffic load rather than reducing it, becoming an +internal denial-of-service. A response-time ceiling alone protects +individual requests but rejects transient blips as if they were +permanent failures, generating spurious 503s to callers when a +single retry would have succeeded. The three mechanisms are +complementary: the timeout gives the breaker something observable +to count quickly, the breaker prevents the retry from becoming an +amplifier of downstream distress, the retry absorbs the blips that +would otherwise pollute the breaker's statistical window and open +it spuriously. + +### How the problem surfaced + +The naive implementation of this ADR's concerns proceeded +incrementally across three sessions: CircuitBreaker (documented in +ADR-005 as the trigger for the config refactor), Retry, and finally +TimeLimiter. During the third session an empirical anomaly appeared +that reshaped the understanding of the whole composition. + +With `task-service` paused via `docker compose pause` — chosen +because it emulates a sick-but-not-dead downstream more faithfully +than `docker compose stop`, since the kernel of the paused +container continues to accept TCP connections while the Java +process is frozen and never reads them — the observed latency for +a curl to `/tasks` was **consistently ~1020 ms**, independent of +whether Retry was configured or not, independent of whether +`metadata.response-timeout` was declared on the route or not, and +independent of the specific values used for those parameters. + +The predicted latency, based on the documented behaviour of the +individual filters, was in the range of **30 seconds to +indefinite**: without a configured timeout on the downstream HTTP +client, a paused peer should keep the gateway waiting until either +Reactor Netty's own connection timeout (typically 30 seconds) or +the OS-level stack timeout intervened. The empirical measurement +did not match this prediction by more than an order of magnitude. + +### Root cause + +The `spring-cloud-starter-circuitbreaker-reactor-resilience4j` +dependency — the mandatory abstraction for the declarative +`CircuitBreaker` filter in Spring Cloud Gateway — **auto-configures +a TimeLimiter alongside every CircuitBreaker instance**, with a +default `timeoutDuration` of one second inherited from +`io.github.resilience4j.timelimiter.TimeLimiterConfig#ofDefaults()`. +This TimeLimiter is not a separate filter that a developer opts +into; it is embedded inside the CircuitBreaker abstraction, wraps +the entire operation the CircuitBreaker protects (including any +Retry logic nested within it), and applies its timeout regardless +of any downstream-client timeout configuration. + +Empirical verification made the mechanism visible. With the +integrated default of one second, the observed latency was +~1020 ms. With the TimeLimiter reconfigured explicitly to five +seconds via `resilience4j.timelimiter.instances.taskServiceBreaker`, +the observed latency became **~5020 ms** — precisely the new +ceiling. The default was neither hypothetical nor dormant: it had +been the dominant timeout mechanism from the moment the +CircuitBreaker starter was added to the classpath, invisibly, with +no configuration file mentioning it. + +A separate empirical finding confirmed the same session: the +per-route `metadata.response-timeout` and `metadata.connect-timeout` +declarations documented in the Spring Cloud Gateway reference for +per-route timeout configuration **have no observable effect** under +the new `spring.cloud.gateway.server.webflux.routes` prefix in +Spring Cloud Gateway 2025.0.0. Values declared as integers, visible +through `/actuator/gateway/routedefinitions`, do not translate into +timeout enforcement at runtime. The effective timeout in this +topology is exclusively the one imposed by the integrated +TimeLimiter of the CircuitBreaker abstraction. + +The consequence is architectural, not merely operational: the +resilience composition in this system is a **four-layer nesting** +rather than the three-layer one the naive reading of the +independent filters would suggest. From the outside in: the +TimeLimiter enforces the total ceiling on the protected operation; +the CircuitBreaker decides whether to admit the operation at all, +based on its statistical window; the Retry attempts the individual +call multiple times with backoff if failures are transient; the +raw HTTP call reaches the downstream. Every operation the gateway +routes through the protected task-service path traverses all four +layers, and any budgeting decision about latency, backoff, or +retry counts must be made against the outermost layer as the +binding constraint. + +Constraints acknowledged for this decision: + +- The gateway is reactive (Netty), not servlet. Bulkhead patterns + that isolate thread pools do not translate directly; recovery + paths depend on Reactor's cancellation semantics rather than on + thread interruption. +- The system has a single developer and no dedicated operations + team. The resilience configuration must remain readable months + after it was written, without ambient institutional memory. +- The target audience for the portfolio (consultancy, traditional + banking, insurance, public sector) expects standard patterns + recognisable to reviewers. Idiomatic Resilience4j configuration + in `application.yml` fits that expectation; bespoke Java + customisers or programmatic route locators do not. +- No chaos engineering infrastructure is available. Empirical + verification uses `docker compose pause` to emulate a sick + downstream and observes behaviour through actuator endpoints + and `curl` timing. + +## Decision + +Compose CircuitBreaker, Retry, and TimeLimiter at the gateway as a +single unified resilience policy for the `task-service-route`. +Configure each pattern with values that make its role in the +composition legible from the configuration file alone, and choose +values that make the outermost layer (TimeLimiter) the binding +constraint on total latency. + +Concretely: + +- The **CircuitBreaker** instance `taskServiceBreaker` is + configured with a count-based sliding window of ten calls, a + minimum of five calls before evaluation, a failure rate threshold + of fifty percent, a wait duration in OPEN state of ten seconds, + and three permitted calls in HALF_OPEN. These values are + didactic: they permit visible state transitions within a single + interactive session. In a production topology with hundreds of + requests per second per route, the window would be larger and + the wait duration longer, but the parameters would occupy the + same conceptual slots. +- The **Retry** filter is scoped to `GET` requests only, on the + `SERVER_ERROR` (5xx) series, with two retries and an exponential + backoff of `firstBackoff=500ms`, `maxBackoff=1500ms`, `factor=2`, + `basedOnPreviousValue=false`. GET-only scoping reflects RFC 9110 + idempotency: retrying a non-idempotent verb without an + `Idempotency-Key` protocol risks producing duplicate side effects + when a request succeeded at the downstream but the response was + lost in transit. The `maxBackoff` ceiling is a defensive + guardrail that does not bind at the current retry count but + bounds future increases. +- The **TimeLimiter** instance `taskServiceBreaker` (identically + named to the CircuitBreaker instance, so that Spring Cloud + CircuitBreaker's abstraction associates them automatically) is + configured with `timeoutDuration=5s` and `cancelRunningFuture= + true`. Five seconds is deliberately longer than the theoretical + worst case of Retry with per-call timeouts (which would be + 4.5 seconds: 2s + 500ms backoff + 2s) — the TimeLimiter acts as + a safety net around the entire protected operation, not as the + primary timeout per call. In the current topology no primary + per-call timeout is effective (see Alternative B below), so in + practice the TimeLimiter is the sole timeout mechanism, and its + value bounds the total user-visible latency directly. +- The **order in the filter chain** is CircuitBreaker (outermost) + then Retry (innermost), matching the argumentation established in + the Retry session: with CircuitBreaker outside, an OPEN state + short-circuits before Retry can amplify traffic against an + already-diagnosed sick downstream; with CircuitBreaker outside, + a transient blip that Retry successfully absorbs registers as a + single successful call at the breaker, preventing the blip from + contaminating the statistical window. The TimeLimiter sits above + the whole composition as a consequence of being integrated into + the CircuitBreaker abstraction, not as a filter-chain choice. + +### Alternatives considered + +**Alternative A — CircuitBreaker alone, no Retry, no explicit +TimeLimiter.** The minimal resilience configuration: rely on the +breaker to open after enough downstream failures and on the +integrated one-second default TimeLimiter to bound individual +calls. Reasoned rejection: the one-second default is invisible in +configuration and therefore not auditable; a future maintainer +would have no textual evidence that a timeout exists at all. More +importantly, without Retry, transient blips of a few hundred +milliseconds become 503s to the caller when a single retry with +backoff would have succeeded. The cost of adding Retry (a few +lines of YAML and a well-understood configuration surface) is far +lower than the cost of the false positives it prevents. + +**Alternative B — Per-route metadata timeouts +(`metadata.response-timeout`, `metadata.connect-timeout`).** The +mechanism documented in the Spring Cloud Gateway reference for +declaring timeouts on individual routes without programmatic +configuration. Reasoned rejection: verified empirically not to +have any effect under the new +`spring.cloud.gateway.server.webflux.routes` prefix in Spring +Cloud Gateway 2025.0.0. The declarations are read by +`RouteDefinitionRouteLocator` and visible through +`/actuator/gateway/routedefinitions` as integer values, but the +downstream HTTP client does not consult them at request time. The +declarations are preserved in the configuration file with an +explanatory comment as documentation of the finding, pointing to +this ADR; they do not participate in the effective policy. This +alternative could not be relied on regardless of merit, because +the mechanism does not function in the current framework version. + +**Alternative C — Bulkhead pattern +(`spring-cloud-starter-circuitbreaker-reactor-resilience4j` +supports it via the Resilience4j Bulkhead module).** Isolate the +resources used by different downstream calls into separate +semaphore-bounded or threadpool-bounded compartments, so that +saturation of one downstream cannot exhaust the resources used to +call the others. Reasoned rejection: the pattern targets systems +where a single application makes calls to many downstreams in +parallel and a slow one can starve the fast ones. In a gateway +whose sole responsibility per request is to relay one call to one +downstream, and where the reactive stack does not use thread pools +in the classical sense, the resource-isolation benefit is +marginal. The costs — additional configuration surface, additional +conceptual load for future maintainers, additional actuator noise +— are not justified. The Bulkhead pattern would become relevant +in a future evolution of the gateway that fans out requests to +multiple downstreams in parallel (a compose-and-forward endpoint, +for example), at which point a dedicated ADR would document the +change. + +**Alternative D — Increase Retry aggressiveness (three or four +retries, longer backoff).** More aggressive retry policies improve +resilience to intermittent failures at the cost of amplifying +traffic against genuinely unhealthy downstreams and increasing +worst-case latency observed by callers. Reasoned rejection: with +two retries and a 500ms/1s backoff schedule, the theoretical worst +case of Retry alone is 4.5 seconds, well under the TimeLimiter +ceiling of 5s. Additional retries would not increase the observed +worst case (bounded by the outer TimeLimiter regardless) but would +cause the operation to spend more of that time attempting downstream +calls, adding load to a service already exhibiting failure. The +current choice keeps the retry budget modest and lets the +CircuitBreaker take over as the primary mitigation once the failure +signal is statistically clear. + +## Consequences + +### Positive + +- **Total latency is bounded by an auditable value.** The 5s + TimeLimiter ceiling is declared in `application.yml` at the + path `resilience4j.timelimiter.instances.taskServiceBreaker. + timeoutDuration`. Any future review of the gateway's SLA + contract can point at that line as the answer to *"what is the + maximum time a client will wait for a task-service call?"*. + Before this ADR, the answer was the invisible one-second + default of the integrated TimeLimiter, which a reviewer would + have to derive from the Spring Cloud CircuitBreaker source + code. +- **Transient blips do not propagate to callers.** With Retry + configured on GET / 5xx / IOException / TimeoutException, a + brief downstream hiccup — a 300ms GC pause, a momentary Postgres + slowdown — is absorbed by the retry with backoff and only the + successful result is returned. The caller sees a slightly + longer response time, not an error. +- **Genuine downstream failures produce fast, cheap fallback + responses once the breaker opens.** Empirical verification of + the OPEN transition showed a latency discontinuity of three + orders of magnitude: from ~5000ms per call (TimeLimiter-bound) + to ~5ms per call (breaker short-circuit). Under concurrent load + this discontinuity is the primary protection against gateway + resource exhaustion: while the breaker is OPEN, all callers to + the sick downstream receive their 503 in milliseconds, freeing + gateway resources to serve traffic to healthy neighbours. +- **The composition is legible from configuration alone.** The + three patterns and their parameters live in a single + `application.yml`, at conventional paths recognisable to any + Spring engineer. A new maintainer can understand the policy by + reading the file top to bottom without needing to consult + external documentation or Java customisers. +- **The choice of GET-only Retry is defensible from first + principles.** The RFC 9110 idempotency argument is one + paragraph of explanation and generalises to any HTTP-based + system. Extending Retry to POST later would require introducing + an `Idempotency-Key` protocol between callers and downstreams, + a scope decision explicit enough to justify its own future ADR + rather than a silent configuration change. + +### Negative + +- **The worst-case pre-open latency is 5s.** Before the breaker + accumulates enough failures to open, each individual request + against a sick downstream consumes the full TimeLimiter budget. + For a system in genuine distress this means callers experience + 5 seconds of latency per request until the breaker trips. The + didactic parameter values in this project make the transition + fast (five failed calls in a ten-call window is enough); a + production configuration with larger windows and more + conservative thresholds would extend the vulnerable period. +- **Conceptual complexity increases nontrivially.** The composition + is a four-layer nesting where the outermost layer (TimeLimiter) + is invisible in the filter chain and lives in a different + section of the configuration file (under `resilience4j`, not + under `spring.cloud.gateway`). Explaining the request lifecycle + now requires four levels rather than three. This is a documented + and unavoidable characteristic of the Spring Cloud CircuitBreaker + abstraction, not a choice; but it is a cost paid by every + contributor who has to reason about latency in the future. +- **The per-route `metadata` mechanism becomes documentation + debt.** The `metadata.response-timeout` and + `metadata.connect-timeout` declarations remain in the route + configuration with an explanatory comment, because removing + them would erase the empirical finding that they do not + function. Their presence is misleading to a reader who has not + read this ADR, and their absence would be misleading to a + future maintainer who reintroduces them without knowing why. + The comment mitigates both, but the tension is real. + +### Neutral + +- **The 5s TimeLimiter is longer than the theoretical Retry worst + case (4.5s).** In the current topology, where the per-call + timeout is not effective, this margin is unused: the TimeLimiter + simply bounds the total. If the per-call timeout mechanism + becomes effective in a future framework version, or if a + programmatic route locator is introduced to enforce per-call + timeouts, the 5s ceiling will become a genuine safety net around + the 4.5s Retry ceiling, and the naming *"outer limit"* will + become semantically accurate. Until then, it is a value with two + possible readings and the same numeric expression. +- **The composition does not include Bulkhead.** This is a + positive decision (see Alternative C), not an oversight. The + absence is documented so that a future evolution introducing + fan-out routing can revisit it explicitly. + +## Verification + +The decision is verifiable operationally with the running compose +stack. All commands assume `docker compose up --build -d` completed +and all five containers are healthy. + +**The TimeLimiter is loaded with the configured value:** + +```bash +curl -s http://localhost:8080/actuator/gateway/routes \ + | python3 -m json.tool \ + | grep -A 5 taskServiceBreaker + +curl -s http://localhost:8080/actuator/circuitbreakers \ + | jq .circuitBreakers.taskServiceBreaker +``` + +The route definition includes the CircuitBreaker filter +(`order = 1`) referencing `taskServiceBreaker` and the Retry +filter (`order = 2`) with the retry parameters. The circuit +breaker actuator reports the instance in state `CLOSED` at the +start of the session. + +**The healthy path is not affected by the TimeLimiter ceiling:** + +```bash +TOKEN=$(curl -s -X POST http://localhost:8080/auth/login \ + -H "Content-Type: application/json" \ + -d '{"email":"alice@example.com","password":"Password123!"}' \ + | jq -r '.accessToken') + +curl -s -o /dev/null -w "%{http_code} — %{time_total}s\n" \ + -H "Authorization: Bearer $TOKEN" \ + http://localhost:8080/tasks +``` + +Observed: `200 — 0.264s`. Well below the 5s ceiling, well below +any of the Retry backoffs. The resilience policy imposes no +detectable cost on healthy operation. + +**A sick downstream is bounded by the TimeLimiter:** + +```bash +docker compose pause task-service + +curl -s -o /dev/null -w "%{http_code} — %{time_total}s\n" \ + --max-time 15 \ + -H "Authorization: Bearer $TOKEN" \ + http://localhost:8080/tasks +``` + +Observed: `503 — 5.017s`. The response payload is the RFC 7807 +`application/problem+json` document produced by the +`FallbackController`. The measurement is consistent across +repetitions (5.006s, 5.020s in immediate follow-up runs) and +matches the configured `timeoutDuration=5s` within measurement +noise. The Retry filter's individual attempts do not observably +bound the operation, confirming that the per-call +`metadata.response-timeout` declaration has no effect under the +current framework version. + +**The CircuitBreaker opens after the statistical threshold:** + +With `task-service` still paused, four consecutive curl +invocations produce: + +``` +call 1: HTTP 503 — 5.018072s +call 2: HTTP 503 — 5.006243s +call 3: HTTP 503 — 5.020617s +call 4: HTTP 503 — 0.004689s +``` + +The discontinuity between call 3 and call 4 marks the transition +CLOSED → OPEN. After three failed calls, combined with the two +recorded before the batch, the sliding window contains five calls +and four failures, exceeding the `failureRateThreshold` of 50%. +The immediately following call is short-circuited by the OPEN +breaker: it does not attempt the downstream and the fallback +responds in under five milliseconds. Actuator inspection confirms +the state transition: + +```json +{ + "failureRate": "80.0%", + "bufferedCalls": 5, + "failedCalls": 4, + "notPermittedCalls": 1, + "state": "OPEN" +} +``` + +The `notPermittedCalls` counter increments on each subsequent +request while OPEN, distinguishing calls the breaker refused to +attempt from calls it attempted and observed to fail. + +**Recovery to CLOSED after `waitDurationInOpenState`:** This +transition was verified in Sesión 8 with the earlier CircuitBreaker +scaffolding and is not re-verified here. The mechanism is +unchanged: after ten seconds in OPEN the breaker transitions to +HALF_OPEN, admits three probe calls, and returns to CLOSED if they +succeed against a recovered downstream. + +## Related decisions + +- Border authentication at the gateway: + [ADR-004](adr-004-border-authentication.md). The + `task-service-route` protected by this ADR is the same route + through which the gateway propagates the authenticated identity + as `X-User-Id`. The resilience patterns operate downstream of + the authentication filter, so failures observed by the breaker + are failures of authenticated requests reaching the downstream, + not authentication failures at the gateway itself. +- Configuration externalisation: + [ADR-005](adr-005-config-externalization-by-profile.md). The + route structure carrying this ADR's filter chain is declared + exactly once in `application.yml` and referenced through + placeholders resolved per profile. Adding a `CircuitBreaker`, + `Retry`, or `metadata` block to the route is safe from the + silent drop-on-profile-override problem that motivated ADR-005. +- Technical debt recorded and deferred: confirm the exact semantics + of `retries: N` in Spring Cloud Gateway 2025.0.0 (whether it + means "N total attempts including the original" or "N additional + attempts after the original") through a controlled experiment + with `retries: 3` and observation of the timing shift. The + empirical measurement in Sesión 9 suggested the former; a formal + confirmation would strengthen the decision record but is not + operationally blocking. +- Technical debt recorded and deferred: investigate whether the + `metadata.response-timeout` and `metadata.connect-timeout` + mechanisms are intended to function under the + `spring.cloud.gateway.server.webflux` prefix in Spring Cloud + Gateway 2025.0.0 and, if so, why they do not in this project. + A minimal reproduction against a fresh Spring Boot 3.5.4 + + Spring Cloud 2025.0.0 project would clarify whether the finding + is a framework issue, a project-specific misconfiguration, or a + documentation gap. From f43936ad8c8cafca1152f2b1c9e615159c0a89b2 Mon Sep 17 00:00:00 2001 From: Tole Date: Sat, 18 Jul 2026 06:57:56 +0200 Subject: [PATCH 7/7] docs: document resilience patterns and update foundation description - Add dedicated section 'Resilience at the gateway' summarizing CircuitBreaker + Retry + TimeLimiter composition, link to ADR-006. - Extend tech stack bullet on Spring Cloud Gateway and add Resilience4j entry. - Include /actuator/gateway/routedefinitions and /actuator/circuitbreakers in observability endpoints. - Retire Circuit Breaker from Future work (implemented); add Bulkhead pattern as deferred item conditional on fan-out routing. - Update foundation description to include resilience patterns as part of the operational core. --- README.md | 76 ++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 67 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 8ff8c79..02b9292 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,8 @@ the operational core of Phase 10 of the roadmap. - **Java 21** — modern language features (records, pattern matching, virtual threads support). - **Spring Boot 3.5.4** — application framework across the three services (downgraded from monolith's Spring Boot 4.x for Spring Cloud 2025.0.0 compatibility). -- **Spring Cloud Gateway 2025.0.0 (Northfields)** — reactive gateway on Netty, declarative routing, `GlobalFilter` for JWT validation. +- **Spring Cloud Gateway 2025.0.0 (Northfields)** — reactive gateway on Netty, declarative routing, `GlobalFilter` for JWT validation, `CircuitBreaker` and `Retry` filters for downstream resilience. +- **Resilience4j (via `spring-cloud-starter-circuitbreaker-reactor-resilience4j`)** — CircuitBreaker, Retry, and TimeLimiter on gateway → task-service calls. Full rationale in [ADR-006](docs/adr-006-resilience-patterns.md). - **Spring Security 6** — servlet-stack security in the task service, custom `OncePerRequestFilter` for header-based authentication. - **Spring Data JPA + Hibernate 6** — ORM in both services, JPA Specifications, entity graphs, optimistic locking with `@Version`. - **Spring Data MongoDB** — activity audit log in the task service. @@ -110,6 +111,58 @@ transactional data (tasks, categories) and MongoDB for the append-only activity audit log — the same rationale documented in the monolith's [ADR-001](https://github.com/Toleflaco/task-manager-api/blob/main/docs/adr-001-polyglot-persistence.md). +## Resilience at the gateway + +The gateway protects itself and healthy downstreams from failures in +the task service by composing three resilience patterns on the +`task-service-route`. The full rationale, alternatives considered, +and empirical verification are documented in +[`docs/adr-006-resilience-patterns.md`](docs/adr-006-resilience-patterns.md). +Summary: + +- **CircuitBreaker** (`taskServiceBreaker`) — count-based sliding + window of ten calls, minimum five before evaluation, opens at 50% + failure rate, ten seconds in OPEN before probing HALF_OPEN. +- **Retry** — two attempts on `GET` / `SERVER_ERROR` / `IOException` + / `TimeoutException`, exponential backoff (500ms → 1500ms). + GET-only scoping reflects RFC 9110 idempotency: retrying a + non-idempotent verb without an `Idempotency-Key` protocol risks + duplicate side effects. +- **TimeLimiter** (integrated in the Spring Cloud CircuitBreaker + abstraction) — explicitly configured to five seconds, overriding + the invisible one-second default that ships with the starter and + bounds the total operation regardless of any per-call timeout. + +**Order in the filter chain.** CircuitBreaker is the outer filter, +Retry the inner one. With CircuitBreaker outside, an OPEN state +short-circuits before Retry can amplify traffic against an already +diagnosed sick downstream; and a transient blip successfully +absorbed by Retry registers at the breaker as a single successful +call, preventing the blip from contaminating the statistical +window. The integrated TimeLimiter wraps the whole composition as a +consequence of the abstraction. + +**Observation and diagnostics.** + +```bash +# Current state of every breaker instance +curl -s http://localhost:8080/actuator/circuitbreakers | jq + +# Route definitions as read from YAML (includes metadata, filter args) +curl -s http://localhost:8080/actuator/gateway/routedefinitions | jq + +# Compiled routes with filter order and resolved URIs +curl -s http://localhost:8080/actuator/gateway/routes | jq +``` + +**Reproducing CLOSED → OPEN empirically:** with the stack up and a +valid access token, pause `task-service` and issue repeated curls +to `/tasks`. The first three or so calls take ~5 seconds each (the +TimeLimiter ceiling); once the sliding window crosses the failure +threshold, subsequent calls short-circuit in a few milliseconds. +Unpause `task-service` and wait 10 seconds for HALF_OPEN probing +to succeed and CLOSED to return. + ## Getting started Two ways to run the system: **Docker Compose** for a full end-to-end @@ -247,8 +300,10 @@ Only the gateway is reachable from the host: curl http://localhost:8080/actuator/health # gateway (public) ``` -The gateway additionally exposes `/actuator/gateway/routes` in -read-only mode for route introspection. The auth and task services' +The gateway additionally exposes `/actuator/gateway/routes` and +`/actuator/gateway/routedefinitions` in read-only mode for route +introspection, and `/actuator/circuitbreakers` for the state of the +Resilience4j circuit breaker instances. The auth and task services' health endpoints are only reachable from within the compose network: ```bash @@ -289,25 +344,28 @@ The current codebase covers the operational core of a distributed system: bounded-context decomposition, border authentication with JWT validation at the edge and `X-User-Id` propagation to downstream services, schema-per-service persistence with Flyway, per-service -Testcontainers for isolated development, GitHub Actions CI, and +Testcontainers for isolated development, GitHub Actions CI, end-to-end orchestration via Docker Compose with a health-check -cascade that makes container start ordering deterministic. +cascade that makes container start ordering deterministic, and +resilience patterns (CircuitBreaker + Retry + TimeLimiter) at the +gateway for graceful degradation under downstream failure. The following distributed-system patterns are intentionally deferred and will be layered on top of this foundation as separate iterations: -- **Resilience.** Circuit Breaker with Resilience4j on gateway → - downstream calls, retries with exponential back-off, bulkheads. - **Distributed tracing.** Micrometer Tracing with a Zipkin or Tempo backend to follow a request across the three services. -- **Async messaging.** RabbitMQ for events that don't need synchronous - responses (activity log fan-out, notifications). +- **Async messaging.** RabbitMQ or Kafka for events that don't need + synchronous responses (activity log fan-out, notifications). - **Saga / outbox.** Transactional outbox for reliable event publication tied to Postgres commits. - **Contract testing.** Consumer-driven contracts between the gateway and downstream services (Spring Cloud Contract or Pact). - **Distributed rate limiting and caching.** Redis-backed Bucket4j and second-level cache. +- **Bulkhead pattern.** Resource isolation between downstream calls + if the gateway evolves toward fan-out routing where a slow + downstream could starve the others. Each of these is worth its own ADR and dedicated iteration rather than a rushed inclusion.