Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 119 ยท Projects

Project: Task Management Microservices

Build task management microservices in Java: user and task services, service discovery, an API gateway, a circuit breaker, tracing and Docker Compose.

This is the course's final project, and it puts the whole Spring Cloud chapter to work. You will build a small task manager as a system of services: a user-service that owns the people, a task-service that owns the work and asks user-service who may be assigned, a discovery server where instances register, an API gateway that is the only door clients use, a circuit breaker that keeps task-service useful when user-service is down, and distributed tracing that follows one request across all of them. Docker Compose starts the lot.

The goal is not to learn new APIs. Each piece has its own lesson: Service Discovery with Eureka, Load Balancing and OpenFeign, API Gateway with Spring Cloud Gateway, Circuit Breakers and Resilience with Resilience4j and Distributed Tracing with Micrometer and Zipkin. The goal is to see how they fit together, which decisions only appear once they do (what counts as a failure? who retries? where does a request's identity live?), and what the system does when a part of it breaks.

As in the previous projects, the real Spring Cloud application is shown read-only, and four runnable stages rebuild the system in plain Java. Here every service is a real HTTP server on 127.0.0.1 with its own port, all started as threads of one program, so you can watch instances register, crash, get evicted, and recover. Read Microservices Architecture first if you haven't.

The system

TEXT
                       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  client โ”€โ”€HTTPโ”€โ”€โ–ถ     โ”‚     api-gateway      โ”‚  API key, rate limit, routing
                       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                    /api/users/** โ”‚ /api/tasks/**
               โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
               โ–ผ                                       โ–ผ
      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   GET /users/{id}   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
      โ”‚  user-service   โ”‚ โ—€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚  task-service   โ”‚  circuit breaker
      โ”‚  (2 instances)  โ”‚                     โ”‚                 โ”‚
      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
               โ”‚                                       โ”‚
          [users DB]                              [tasks DB]

  discovery-server: every service registers and sends heartbeats; callers look up instances by name
  zipkin: every service reports spans; one trace id links them

The services and their APIs:

Service Endpoint Meaning
user-service POST /users, GET /users/{id}, POST /users/{id}/deactivate People who can be assigned work
task-service POST /tasks, GET /tasks/{id}, GET /tasks?assigneeId= Tasks; each one has an assignee from user-service
api-gateway /api/users/**, /api/tasks/** The public entry point; strips /api and routes by service name

Three rules shape the design:

  • Each service owns its data. task-service stores an assignee_id, never a copy of the user table, and it can't join across databases. Everything it knows about users comes from user-service's API.
  • Writes are strict, reads are forgiving. Creating a task requires user-service to confirm that the assignee exists and is active; if it can't answer, the request fails with 503. Reading a task still works when user-service is down: the response just says the name is unavailable.
  • Clients only know the gateway. Service addresses change all the time; the gateway and the services find each other through discovery.

The real project layout

The Spring version is a multi-module Maven build. Each module is an ordinary Spring Boot application with its own pom.xml, application.yml and Docker image:

TEXT
task-manager/
โ”œโ”€โ”€ pom.xml                      # parent: Boot parent + Spring Cloud BOM, lists the modules
โ”œโ”€โ”€ docker-compose.yml
โ”œโ”€โ”€ discovery-server/            # Eureka server
โ”œโ”€โ”€ api-gateway/                 # Spring Cloud Gateway
โ”œโ”€โ”€ user-service/                # Spring MVC + Spring Data JPA + PostgreSQL
โ””โ”€โ”€ task-service/                # Spring MVC + Spring Data JPA + PostgreSQL + Resilience4j

The parent pom imports the Spring Cloud release train BOM, so no Spring Cloud starter needs its own version (Maven in Depth explains BOMs):

XML
<!-- pom.xml (parent) -->
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>4.1.1</version>                      <!-- use the latest 4.x release -->
  <relativePath/>
</parent>

<groupId>com.example.tasks</groupId>
<artifactId>task-manager</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>

<modules>
  <module>discovery-server</module>
  <module>api-gateway</module>
  <module>user-service</module>
  <module>task-service</module>
</modules>

<properties>
  <java.version>25</java.version>
  <spring-cloud.version>2025.1.1</spring-cloud.version>   <!-- check the current release train -->
</properties>

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>${spring-cloud.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

Should the services share a module with common DTOs? Usually no. A shared UserDto class couples the release of every service that uses it. Each consumer declares the fields it reads, as task-service does below, and tolerates fields it doesn't know about. Shared libraries are fine for technical concerns (logging setup, error format), not for the domain.

Stage 1: two services, two databases

Start with just the two business services, wired together with a fixed address. The toolkit at the top of the program is a few dozen lines of HttpServer, HttpClient and Jackson that every service uses, like a minimal Spring MVC plus RestClient. user-service and task-service each get their own H2 database.

Java Stage 1: two services, two databases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output as a conversation between the services:

  • Creating a task makes task-service call GET /users/{id} on user-service first. Ada and Grace are active, so their tasks are created. Linus was deactivated, and user 9 doesn't exist, so both requests are rejected with 400: the URL was fine, the data in the body wasn't.
  • GET /tasks/2 is API composition: task-service reads its own row and asks user-service for the name. The list endpoint skips that call and returns only the assignee_id, which is a typical trade-off: one remote call per row would make lists slow.
  • The last line proves the boundary: the task database simply has no app_user table. In the real system they are different PostgreSQL databases, possibly on different machines, and the only shared thing is the API.

Without a shared database there is no foreign key from task.assignee_id to a user. If someone deletes a user later, the task keeps a dangling id, which is why user-service deactivates users instead of deleting them, and why task-service renders a missing user as (unknown) instead of failing. Keeping data consistent across services is done with events: user-service publishes UserDeactivated, and task-service reassigns that user's open tasks (Messaging with JMS, RabbitMQ and Kafka shows the tools; the outbox pattern from Microservices Architecture makes the publishing reliable).

The real services

user-service is a standard layered Spring Boot application, structured exactly like Project: Employee Management with Spring Data JPA: an entity, a repository, a service and a controller. Its configuration is where the system-level settings appear:

YAML
# user-service/src/main/resources/application.yml
spring:
  application:
    name: user-service                 # the name others use to find it
  datasource:
    url: ${USERS_DB_URL:jdbc:postgresql://localhost:5432/users}
    username: ${USERS_DB_USER:users}
    password: ${USERS_DB_PASSWORD}
  jpa:
    open-in-view: false

server:
  port: ${PORT:0}                      # 0 locally: start as many instances as you like

eureka:
  client:
    service-url:
      defaultZone: ${EUREKA_URL:http://localhost:8761/eureka/}
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${random.value}

management:
  endpoints:
    web:
      exposure:
        include: health,info
  tracing:
    sampling:
      probability: 1.0                 # trace everything in development

task-service talks to user-service through an HTTP interface client. It declares only the fields it needs, so user-service can add fields freely:

Java
// task-service/src/main/java/com/example/tasks/assignee/UserClient.java
package com.example.tasks.assignee;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;

@HttpExchange("/users")
interface UserClient {

    @GetExchange("/{id}")
    UserDto find(@PathVariable long id);

    record UserDto(long id, String name, boolean active) {}
}
Java
// task-service/src/main/java/com/example/tasks/assignee/UserClientConfig.java
@Configuration
class UserClientConfig {

    /** Built with Boot's configurer, so Boot's customizers (including tracing) still apply. */
    @Bean
    @LoadBalanced
    RestClient.Builder loadBalancedRestClientBuilder(RestClientBuilderConfigurer configurer) {
        return configurer.configure(RestClient.builder());
    }

    @Bean
    UserClient userClient(RestClient.Builder loadBalancedRestClientBuilder) {
        var requestFactory = new JdkClientHttpRequestFactory(
            HttpClient.newBuilder().connectTimeout(Duration.ofMillis(500)).build());
        requestFactory.setReadTimeout(Duration.ofSeconds(2));

        RestClient restClient = loadBalancedRestClientBuilder
            .baseUrl("http://user-service")              // a service name, resolved through discovery
            .requestFactory(requestFactory)
            .build();
        return HttpServiceProxyFactory.builderFor(RestClientAdapter.create(restClient))
            .build()
            .createClient(UserClient.class);
    }
}

The RestClientBuilderConfigurer detail matters more than it looks. Declaring your own RestClient.Builder bean replaces the one Spring Boot would create, and with it the customizers Boot applies, including the observation setup that adds the traceparent header. A load-balanced builder created with a bare RestClient.builder() works, but its requests silently drop out of the trace. Building it through Boot's configurer keeps both.

Stage 2: discovery and client-side load balancing

Fixed addresses break the moment you run two instances or an instance restarts on a new port. Stage 2 adds a registry with leases, a registration component inside each service (register at startup, send a heartbeat every 100 ms, deregister on shutdown), and a load-balanced client that looks instances up by name and rotates through them. The timings are scaled down from Eureka's defaults (heartbeat every 30 s, lease 90 s) so the demo finishes quickly.

user-service now runs as two instances sharing the service's database. Instances of one service may share its database; different services may not.

Java Stage 2: a registry, heartbeats and client-side load balancing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Follow the lines indented under each request: they come from task-service's load balancer and show which instance it used.

  • With two healthy instances, the lookups alternate user-1, user-2, user-1: round robin.
  • Then user-2 crashes: its heartbeats stop, but it never says goodbye, so the registry still lists it. The next lookup picks user-2, the connection is refused, and the client retries on user-1. Retrying is safe here because a refused connection means the request never reached the instance. (A timeout after sending is different: the instance may have done the work, so only idempotent requests may be retried then.)
  • About 600 ms later the lease expires, the registry evicts user-2, and only user-1 remains.
  • user-1 shuts down gracefully and deregisters immediately. With no instances left, task-service can't verify the assignee and answers 503. Stage 3 deals with that.

The task creations that succeeded show the rule that writes are strict. task-service never guesses: no verified assignee, no task.

In the real system, the Eureka client starter on the classpath does everything Registration does, and @LoadBalanced does what LoadBalancedClient does: it looks the instances up by name and picks one per request. Spring Cloud LoadBalancer can also retry on another instance; check which HTTP clients its retry support covers in your version, or add the retry yourself as Load Balancing and OpenFeign shows. The discovery server itself is a Spring Boot application with @EnableEurekaServer, configured as in Service Discovery with Eureka. Clients cache the registry and refresh it every 30 seconds, which is why the window between a crash and eviction is long in production and why the retry matters.

Stage 3: the gateway and the circuit breaker

Stage 3 puts the gateway in front. It checks an API key, applies a token-bucket rate limit per key, and routes /api/users/** and /api/tasks/** to the services by name, stripping the /api prefix. Inside task-service, calls to user-service now go through a circuit breaker: after three consecutive failures it opens and fails fast for 500 ms, then lets one trial call through.

Two decisions are encoded in that code. First, a 404 is not a failure: "user 9 doesn't exist" is a correct answer from a healthy service, so only connection errors and 5xx responses count against the breaker. Second, the fallback depends on the operation: GET /tasks/{id} degrades to "name": "(unavailable)", while POST /tasks refuses with 503, because creating a task with an unverified assignee would break a business rule.

Java Stage 3: an API gateway, rate limiting and a circuit breaker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What happened, step by step:

  • Through the gateway, everything works as before. A request without an API key is rejected with 401 before any service is called, and a path with no route gets 404 from the gateway itself.
  • Rate limiting: trial-key has a bucket of 5 tokens refilled at 1 per second. Seven quick requests give five 200s and two 429 Too Many Requests. The app-key plan is much larger, so the rest of the script never hits it.
  • The outage: user-service's only instance deregisters. The first three GETs try to call it, fail ("no instances"), and return the degraded task; the third failure opens the breaker. The fourth GET never tries: the breaker rejects the call immediately, so the fallback reason changes to "circuit breaker 'user-service' is OPEN". The POST is refused with 503 just as fast.
  • Recovery: a new instance, user-2, registers. After the 500 ms open period, the next call moves the breaker to half-open; the trial call succeeds, the breaker closes, and names and task creation are back.

Note that the client never saw a 500 or a hanging request, even while a dependency was completely gone. That is the point of combining discovery, timeouts, a breaker and a deliberate fallback.

The real gateway is configuration. Routes use lb:// URIs, and the rate limiter runs on Redis so that several gateway instances share one budget per key:

YAML
# api-gateway/src/main/resources/application.yml
spring:
  application:
    name: api-gateway
  data:
    redis:
      host: ${REDIS_HOST:localhost}
  cloud:
    gateway:
      server:
        webflux:
          default-filters:
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 50
                redis-rate-limiter.burstCapacity: 100
                key-resolver: "#{@apiKeyResolver}"
          routes:
            - id: users
              uri: lb://user-service
              predicates:
                - Path=/api/users/**
              filters:
                - StripPrefix=1
            - id: tasks
              uri: lb://task-service
              predicates:
                - Path=/api/tasks/**
              filters:
                - StripPrefix=1

server:
  port: 8080

eureka:
  client:
    service-url:
      defaultZone: ${EUREKA_URL:http://localhost:8761/eureka/}

The apiKeyResolver bean is the KeyResolver from API Gateway with Spring Cloud Gateway. In a production system, the gateway would also validate a JWT with Spring Security's resource server support and rate-limit per user; the API key stands in for that here (JWT and OAuth 2).

In task-service, one small class owns every call to user-service and both fallbacks. It uses Spring Cloud Circuit Breaker's programmatic API, which makes the two different fallbacks easy to see:

Java
// task-service/src/main/java/com/example/tasks/assignee/Assignees.java
package com.example.tasks.assignee;

import com.example.tasks.common.InvalidRequestException;
import com.example.tasks.common.ServiceUnavailableException;
import java.util.Optional;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;

@Component
public class Assignees {

    private final UserClient users;
    private final CircuitBreaker breaker;

    Assignees(UserClient users, CircuitBreakerFactory<?, ?> breakers) {
        this.users = users;
        this.breaker = breakers.create("user-service");
    }

    /** For writes: the assignee must exist and be active. No answer means no task. */
    public void requireActive(long userId) {
        Optional<UserClient.UserDto> user = breaker.run(() -> Optional.of(users.find(userId)), failure -> {
            if (failure instanceof HttpClientErrorException.NotFound) {
                return Optional.empty();
            }
            throw new ServiceUnavailableException("Can't verify the assignee right now; try again later");
        });
        if (user.isEmpty()) {
            throw new InvalidRequestException("assigneeId", "assignee " + userId + " does not exist");
        }
        if (!user.get().active()) {
            throw new InvalidRequestException("assigneeId", "assignee " + userId + " is deactivated");
        }
    }

    /** For reads: degrade instead of failing. */
    public String nameOf(long userId) {
        return breaker.run(() -> users.find(userId).name(),
            failure -> failure instanceof HttpClientErrorException.NotFound ? "(unknown)" : "(unavailable)");
    }
}
YAML
# task-service/src/main/resources/application.yml (resilience part)
resilience4j:
  circuitbreaker:
    instances:
      user-service:
        sliding-window-type: COUNT_BASED
        sliding-window-size: 10
        minimum-number-of-calls: 5
        failure-rate-threshold: 50
        wait-duration-in-open-state: 10s
        permitted-number-of-calls-in-half-open-state: 2
        ignore-exceptions:
          - org.springframework.web.client.HttpClientErrorException   # 4xx: the service is fine
  timelimiter:
    instances:
      user-service:
        timeout-duration: 3s        # longer than the client's own read timeout

The production breaker opens on a failure rate over a sliding window instead of three failures in a row, which is less jumpy under real traffic. ignore-exceptions is the "404 is not a failure" rule. And watch the time limiter: Spring Cloud Circuit Breaker wraps calls in a Resilience4j TimeLimiter with a default timeout of 1 second, which can cut off calls before the RestClient's own 2-second read timeout. Decide on one timeout budget and make the layers agree.

Stage 4: following a request through the system

With four processes involved in one click, a log line saying "assignee lookup failed" is useless unless you can find the lines from the gateway and the other services that belong to the same request. Stage 4 adds what Micrometer Tracing does in every service:

  • When a request arrives, serve reads the W3C traceparent header. If it is valid, the service joins that trace with a new span id; if not (the gateway, at the edge), it starts a new trace.
  • Every outgoing call adds a traceparent header with the current trace id and span id, so the next service knows its parent.
  • When a request finishes, its span (trace id, span id, parent id, name, status, duration) goes to a collector, standing in for Zipkin.
  • Every log line is prefixed with [service,traceId,spanId], which is what Spring Boot's logging.pattern.correlation produces.

None of this is in the business code: it lives in the shared toolkit, just as Spring's instrumentation lives in the framework. The ids come from a seeded random generator so the output is repeatable; real tracers use secure random ids.

Java Stage 4: the whole system with distributed tracing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each request through the gateway produced one trace id shared by all its log lines, across three services. That is how you search logs in production: copy the trace id from an error and filter every service's logs by it. The trees at the end are what Zipkin shows as a timeline:

  • POST /api/tasks for Ada is three levels deep: gateway, task-service, and the lookup in user-service.
  • The rejected task for user 9 shows where it failed: user-service answered 404, so task-service answered 400, and the gateway passed it on.
  • The last trace has no user-service span at all, and task-service's span carries the fallback tag. In a tracing UI, that tag (a real tracer records it as a span tag or event) is how you find every request that was served degraded.

Your durations will differ from run to run, and the first request is slow because classes are loading and the JIT hasn't warmed up. Real instrumentation also records a separate client span for each outgoing call, so you can tell network time from processing time; the demo skips it to keep the trees short. Sampling, baggage and more are in Distributed Tracing with Micrometer and Zipkin.

The real setup is the same in every service: Actuator plus a tracing bridge and a reporter.

XML
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-tracing-bridge-brave</artifactId>
</dependency>
<dependency>
  <groupId>io.zipkin.reporter2</groupId>
  <artifactId>zipkin-reporter-brave</artifactId>
</dependency>
PROPERTIES
management.tracing.sampling.probability=1.0
management.tracing.propagation.type=w3c
# Spring Boot 3 name; Boot 4 reorganized some tracing properties, so check the reference for your version
management.zipkin.tracing.endpoint=${ZIPKIN_URL:http://localhost:9411/api/v2/spans}
logging.pattern.correlation=[${spring.application.name:},%X{traceId:-},%X{spanId:-}] 

Running the whole system with Docker Compose

Each module builds into an image with a short Dockerfile (Docker for Java Developers covers layered jars and smaller images):

DOCKERFILE
# user-service/Dockerfile (the other modules are the same)
FROM eclipse-temurin:25-jre
WORKDIR /app
COPY target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

The Compose file starts the infrastructure, two databases, the services and the gateway. Only the gateway, Eureka's dashboard and Zipkin's UI are published to the host; everything else is reachable only on Compose's internal network, by service name.

YAML
# docker-compose.yml
services:
  discovery:
    build: ./discovery-server
    ports:
      - "8761:8761"                        # Eureka dashboard

  users-db:
    image: postgres:17
    environment:
      POSTGRES_DB: users
      POSTGRES_USER: users
      POSTGRES_PASSWORD: ${USERS_DB_PASSWORD}
    volumes:
      - users-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U users -d users"]
      interval: 5s
      retries: 10

  tasks-db:
    image: postgres:17
    environment:
      POSTGRES_DB: tasks
      POSTGRES_USER: tasks
      POSTGRES_PASSWORD: ${TASKS_DB_PASSWORD}
    volumes:
      - tasks-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U tasks -d tasks"]
      interval: 5s
      retries: 10

  user-service:
    build: ./user-service
    deploy:
      replicas: 2                          # two instances, both register with Eureka
    environment:
      PORT: 8080
      USERS_DB_URL: jdbc:postgresql://users-db:5432/users
      USERS_DB_USER: users
      USERS_DB_PASSWORD: ${USERS_DB_PASSWORD}
      EUREKA_URL: http://discovery:8761/eureka/
      ZIPKIN_URL: http://zipkin:9411/api/v2/spans
    depends_on:
      users-db:
        condition: service_healthy
      discovery:
        condition: service_started

  task-service:
    build: ./task-service
    environment:
      PORT: 8080
      TASKS_DB_URL: jdbc:postgresql://tasks-db:5432/tasks
      TASKS_DB_USER: tasks
      TASKS_DB_PASSWORD: ${TASKS_DB_PASSWORD}
      EUREKA_URL: http://discovery:8761/eureka/
      ZIPKIN_URL: http://zipkin:9411/api/v2/spans
    depends_on:
      tasks-db:
        condition: service_healthy
      discovery:
        condition: service_started

  api-gateway:
    build: ./api-gateway
    ports:
      - "8080:8080"                        # the only public API port
    environment:
      EUREKA_URL: http://discovery:8761/eureka/
      REDIS_HOST: redis
      ZIPKIN_URL: http://zipkin:9411/api/v2/spans
    depends_on:
      - discovery
      - redis

  redis:
    image: redis:7-alpine

  zipkin:
    image: openzipkin/zipkin
    ports:
      - "9411:9411"                        # tracing UI

volumes:
  users-data:
  tasks-data:

Passwords come from a .env file next to the Compose file (never committed) or from your shell. depends_on with service_healthy waits for PostgreSQL to accept connections; for Eureka, service_started is enough, because Eureka clients keep retrying their registration until the server answers. Build and start everything, then try it (read-only commands; they need Docker on your machine):

Terminal
./mvnw -q package -DskipTests
docker compose up -d --build

curl -X POST localhost:8080/api/users -H "X-Api-Key: app-key" -H "Content-Type: application/json" \
     -d '{"name": "Ada", "email": "[email protected]"}'
curl -X POST localhost:8080/api/tasks -H "X-Api-Key: app-key" -H "Content-Type: application/json" \
     -d '{"title": "Write release notes", "assigneeId": 1}'

docker compose stop user-service          # simulate the outage
curl localhost:8080/api/tasks/1 -H "X-Api-Key: app-key"
docker compose start user-service

docker compose down                       # add -v to delete the database volumes too

Open http://localhost:8761 to see both user-service instances registered, and http://localhost:9411 to search the traces. On Kubernetes, the platform would replace Eureka (DNS names for services) and Compose (Deployments), and ConfigMaps or Spring Cloud Config would hold the configuration (Deploying Java Applications).

Design decisions in review

  • Database per service. No shared tables, no cross-service joins. References across services are plain ids, and consistency over time comes from events, not foreign keys.
  • Consumers declare what they read. task-service's UserDto has three fields; user-service can grow without breaking it.
  • Discovery with leases. Instances register and renew; crashed ones are evicted after the lease; graceful shutdown deregisters at once. Clients retry on another instance only when it is safe.
  • One edge. Authentication, rate limiting and routing happen once, at the gateway. Services trust the network inside, which is why only the gateway's port is published.
  • Failures are classified. Connection errors and 5xx count against the breaker; 4xx answers don't.
  • Fallbacks follow the business rules. Reads degrade, writes refuse. Neither hangs.
  • One timeout budget. Client timeouts, time limiters and gateway timeouts must agree, or the outermost one wins and the inner ones are noise.
  • Tracing everywhere, in the infrastructure. Trace context travels in traceparent; every log line carries the trace id; no business code knows about it.

Ideas for extending the project

  • Events. Publish UserDeactivated from user-service (with the outbox pattern) and let task-service move that user's open tasks back to unassigned (Messaging with JMS, RabbitMQ and Kafka).
  • Centralized configuration. Move the resilience and rate-limit settings into a Config Server and refresh them without restarts (Centralized Configuration with Spring Cloud Config).
  • Contract tests. Write a consumer-driven contract for GET /users/{id} so that user-service can't break task-service unnoticed (Spring Cloud Contract or Pact).
  • Bulkheads. Limit concurrent calls from task-service to user-service with Resilience4j's bulkhead, and show what happens when user-service is slow instead of down.
  • Batch lookups. Add GET /users?ids=1,2,3 so that GET /tasks?assigneeId= can include names with one call instead of one per task.
  • Kubernetes. Replace Eureka with Kubernetes Services and Compose with manifests, and compare what disappears from the code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. task-service needs the assignee's name for GET /tasks/{id}. Where does it get it?

    Each service owns its data, so task-service asks user-service. Because that call can fail, the read path has a fallback that returns the task without the name.
  2. 2. An instance of user-service crashes without deregistering. What happens to calls in the next few hundred milliseconds of the demo?

    Only heartbeats keep a lease alive. Until the lease expires, the dead instance stays registered. A refused connection never reached the instance, so retrying elsewhere is safe.
  3. 3. Why does user-service answering 404 for an unknown assignee not count as a circuit breaker failure?

    Counting client errors would let bad input open the breaker and cut off a perfectly healthy service. In Resilience4j this is the ignore-exceptions setting.
  4. 4. With the breaker OPEN, why does POST /tasks answer 503 while GET /tasks/{id} answers 200?

    Fallbacks are business decisions. Showing a task without the assignee's name is acceptable; creating a task for an unverified user isn't.
  5. 5. A request enters the gateway without a traceparent header. What does each service do with tracing in Stage 4?

    The edge starts the trace, and propagation does the rest. That's why every log line of the request carries the same trace id, and the spans form one tree.

Summary

  • A microservice system is several ordinary Spring Boot applications plus the infrastructure that connects them: discovery, a gateway, resilience and tracing.
  • Database per service: references across services are ids, data comes from APIs, and long-term consistency from events.
  • Discovery with registration, heartbeats and leases lets instances come and go; a load-balanced client picks an instance by name and retries elsewhere only when it is safe.
  • The gateway is the single public entry: authentication, rate limiting (shared through Redis in production) and routing with lb:// URIs.
  • A circuit breaker fails fast when a dependency is down; classify failures (5xx and connection errors, not 4xx) and design fallbacks per operation: reads degrade, writes refuse.
  • Tracing propagates traceparent through every hop, and log lines carry the trace id; it belongs in shared infrastructure, not in business code.
  • Docker Compose runs the whole system locally, with only the gateway and the dashboards exposed.

Next: Advanced Java Cheat Sheet