DEV Community

Mayur Bodhare
Mayur Bodhare

Posted on

Spring Boot Microservices Explained: Architecture, Communication and Eureka

Have you ever wondered how applications like Amazon, Netflix, or Uber handle millions of users without putting everything inside one application?

Imagine building an e-commerce application. Initially, you might put everything into one Spring Boot project:

  • User management
  • Product management
  • Order management
  • Payment processing
  • Notifications

Everything works fine initially. But as the application grows, things become complicated.

A small change in the payment module might require rebuilding and redeploying the entire application. If the payment functionality starts consuming too much memory, the entire application can suffer.

This is where microservices architecture comes into the picture.

Instead of building one massive application, we divide it into smaller, independent applications called services. Each service handles a specific business responsibility and communicates with other services when required.

But this introduces new questions:

  • How do different services communicate?
  • How does one service find another service?
  • What happens when a service has multiple running instances?
  • How do we avoid hardcoding service URLs?
  • What happens when a service becomes unavailable?

In this article, we'll understand these problems and see how Spring Boot and Spring Cloud help us solve them.

Versions used in this article:

  • Java 17 or later.
  • Spring Boot 4.2.0.
  • Spring Cloud 2026.0.0.
  • Spring Cloud OpenFeign 5.1.0, managed through the Spring Cloud BOM.

These are the latest stable versions available while writing this article, November 2026. Always check the compatibility matrix before choosing versions for your project.

Table of contents

Microservices from the beginning

Before understanding microservices, let's understand the problem they solve.

Suppose Asha wants to build an e-commerce application.

Initially, she creates one Spring Boot application containing all the functionality.

This architecture is called a monolithic architecture.

What is microservices architecture?

A monolithic application is an application where multiple business functionalities are developed, packaged, and deployed together as one unit.

For example:

                 E-Commerce Application
                 +--------------------+
                 |                    |
                 |   User Management  |
                 |                    |
                 |   Product Service  |
                 |                    |
                 |   Order Management |
                 |                    |
                 |   Payment Service  |
                 |                    |
                 |   Notification     |
                 |                    |
                 +--------------------+
                         |
                         v
                     Database
Enter fullscreen mode Exit fullscreen mode

All these modules belong to one deployable application.

Even if the modules are logically separated, they still share the same application runtime and deployment lifecycle.

Now imagine the order functionality receives a huge amount of traffic.

Asha wants to run five instances of the order functionality without running five copies of the entire application.

With a traditional monolithic deployment, scaling only the order module independently is difficult.

One solution is to split the application into independent services.

This is microservices architecture.

Microservices architecture is an architectural style in which an application is divided into small, independently deployable services. Each service focuses on a specific business capability and communicates with other services through well-defined interfaces.

Let's redesign our e-commerce application.

                 E-Commerce Application

       +------------------+
       |   User Service   |
       |                  |
       |   User Database  |
       +------------------+

       +------------------+
       |  Order Service   |
       |                  |
       |  Order Database |
       +------------------+

       +------------------+
       | Payment Service  |
       |                  |
       | Payment Database |
       +------------------+

       +------------------+
       | Product Service  |
       |                  |
       | Product Database |
       +------------------+
Enter fullscreen mode Exit fullscreen mode

Now each service is an independent application.

For example:

  • User Service manages users.
  • Order Service manages orders.
  • Payment Service processes payments.
  • Product Service manages products.

Each service can have its own codebase, deployment process, runtime, and database.

Let's see a simple example.

Suppose Ravi places an order.

The Order Service might need to:

  1. Verify whether the user exists.
  2. Check product availability.
  3. Create the order.
  4. Request payment processing.

The Order Service communicates with other services instead of directly accessing their internal code or database.

This is the fundamental idea behind microservices.

Behind the scenes

Unlike a monolithic application, microservices run as separate processes.

For example:

User Service
    |
    | HTTP :8081
    v
Independent JVM Process

Order Service
    |
    | HTTP :8082
    v
Independent JVM Process

Payment Service
    |
    | HTTP :8083
    v
Independent JVM Process
Enter fullscreen mode Exit fullscreen mode

Each application can be started, stopped, updated, and scaled independently.

A service can also be implemented using a different programming language, provided it follows the agreed communication contract.

Why teams choose microservices

If monolithic architecture is simpler, why do companies introduce microservices?

Because large applications introduce problems that become difficult to manage when everything is tightly coupled.

Let's understand the benefits.

1. Independent deployment

Suppose the payment team wants to add a new payment method.

In a microservices architecture, the team can update and deploy the Payment Service without redeploying the User Service or Product Service.

2. Independent scaling

Imagine the application receives:

  • 1,000 user requests.
  • 10,000 product requests.
  • 50,000 payment-related requests.

We can allocate more instances to the services receiving more traffic.

User Service       -> 2 instances

Product Service    -> 5 instances

Payment Service    -> 10 instances
Enter fullscreen mode Exit fullscreen mode

This avoids scaling the entire application unnecessarily.

3. Fault isolation

Suppose the Notification Service becomes unavailable.

The rest of the application can continue functioning, provided notification delivery is not a mandatory part of the current transaction.

However, this does not happen automatically. We must design proper timeouts, fallbacks, and failure handling.

4. Technology flexibility

One service can use Java and Spring Boot, while another uses Python and FastAPI.

This is possible because services communicate through technology-independent contracts such as HTTP APIs or messaging protocols.

5. Team independence

Different teams can own different services.

For example:

  • Team A owns User Service.
  • Team B owns Order Service.
  • Team C owns Payment Service.

Teams can develop and deploy independently as long as they maintain compatible service contracts.

But microservices are not free benefits.

They introduce additional complexity:

  • Network failures.
  • Service discovery.
  • Distributed logging.
  • Data consistency.
  • Deployment management.
  • Monitoring and tracing.
  • Security between services.

For a small application, a well-structured monolith is often a better starting point.

Microservices become useful when independent scaling, deployment, ownership, or fault isolation provides enough value to justify the operational complexity.

How services communicate

Now we have multiple independent services.

But there is a problem.

How does the Order Service communicate with the Payment Service?

Remember, these are separate applications running in separate processes.

We cannot simply call a Java method from one service as if both services were part of the same application.

We need a communication mechanism.

There are two major communication approaches:

  1. Synchronous communication.
  2. Asynchronous communication.

Synchronous communication

Synchronous communication means the calling service sends a request and waits for the response before continuing its work.

A common example is HTTP REST communication.

Imagine Ravi places an order.

The Order Service sends a request to the Payment Service.

        Order Service
              |
              |
       HTTP Request
              |
              v
       Payment Service
              |
              |
       Process Payment
              |
              v
       HTTP Response
              |
              v
        Order Service
Enter fullscreen mode Exit fullscreen mode

The Order Service waits until the Payment Service responds.

Let's understand this with a simple Spring Boot example.

Payment Service

@RestController
@RequestMapping("/payments")
public class PaymentController {

    @GetMapping("/{orderId}")
    public String getPaymentStatus(
            @PathVariable Long orderId) {

        return "Payment successful for order: " + orderId;
    }
}
Enter fullscreen mode Exit fullscreen mode

Order Service

For now, assume we know the Payment Service URL.

@RestController
@RequestMapping("/orders")
public class OrderController {

    private final RestClient restClient;

    public OrderController(RestClient.Builder builder) {
        this.restClient = builder
                .baseUrl("http://localhost:8082")
                .build();
    }

    @GetMapping("/{orderId}")
    public String getOrder(@PathVariable Long orderId) {

        String response = restClient.get()
                .uri("/payments/{orderId}", orderId)
                .retrieve()
                .body(String.class);

        return response;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Payment successful for order: 101
Enter fullscreen mode Exit fullscreen mode

Notice that the Order Service communicates with the Payment Service using HTTP.

It does not need to know how the Payment Service internally processes payments.

Behind the scenes

  1. Order Service creates an HTTP request.
  2. The request travels through the network.
  3. Payment Service receives the request.
  4. Payment Service executes its controller method.
  5. It creates an HTTP response.
  6. Order Service receives the response and continues execution.

Advantages:

  • Simple to understand.
  • Easy to implement using REST APIs.
  • Useful when the caller immediately needs the response.

Disadvantages:

  • The caller waits for the response.
  • Network latency affects the caller.
  • If the downstream service is unavailable, the request may fail.
  • Multiple dependent calls can increase response time.

Asynchronous communication

Asynchronous communication means the calling service sends a message without waiting for the receiving service to complete its processing.

A common approach is message-based communication using tools like Apache Kafka or RabbitMQ.

Imagine Ravi places an order.

The Order Service creates the order and publishes an event.

The Notification Service receives that event and sends an email.

             Order Service
                   |
                   |
             Publish Event
                   |
                   v
             Message Broker
              /          \
             /            \
            v              v
      Email Service    Analytics Service
            |              |
            v              v
       Send Email      Update Reports
Enter fullscreen mode Exit fullscreen mode

The Order Service does not need to wait for the email to be sent.

Here is a simplified Kafka-style example.

Order Service

@Service
public class OrderService {

    private final KafkaTemplate<String, String> kafkaTemplate;

    public OrderService(
            KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    public void createOrder() {

        kafkaTemplate.send(
                "order-created",
                "Order 101 created"
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Notification Service

@Service
public class NotificationService {

    @KafkaListener(topics = "order-created")
    public void consume(String message) {

        System.out.println("Received: " + message);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Received: Order 101 created
Enter fullscreen mode Exit fullscreen mode

This example assumes Kafka is configured and running, and the topic exists or automatic topic creation is enabled.

Behind the scenes

  1. Order Service publishes a message.
  2. Kafka stores the message in a topic.
  3. Notification Service subscribes to that topic.
  4. Kafka delivers the message to the consumer.
  5. Notification Service processes it independently.

Advantages:

  • The producer does not wait for the consumer.
  • Services become less tightly coupled.
  • Useful for background processing.
  • Helps absorb traffic spikes through message buffering.

Disadvantages:

  • More infrastructure and configuration.
  • Eventual consistency must be handled.
  • Message duplication and ordering need consideration.
  • Debugging distributed workflows can be more difficult.

API Gateway

Now let's introduce another problem.

Our e-commerce application has four services:

User Service       -> localhost:8081
Product Service    -> localhost:8082
Order Service      -> localhost:8083
Payment Service    -> localhost:8084
Enter fullscreen mode Exit fullscreen mode

Suppose a frontend application wants to access all these services.

Should the frontend maintain four different service URLs?

It could, but this creates problems.

  • The frontend needs to know about every backend service.
  • Authentication logic may get duplicated.
  • Changes in service addresses affect the frontend.
  • We need a common place to apply request-level policies.

This is where an API Gateway helps.

An API Gateway is a single entry point through which external clients access backend services.

Instead of directly accessing every service, the client sends requests to the gateway.

                  Frontend
                     |
                     |
                     v
              +--------------+
              |  API Gateway |
              +--------------+
                     |
          +----------+----------+
          |          |          |
          v          v          v
      User       Product      Order
      Service    Service      Service
                                |
                                v
                          Payment Service
Enter fullscreen mode Exit fullscreen mode

For example:

GET /users/101
    |
    v
API Gateway
    |
    v
User Service
Enter fullscreen mode Exit fullscreen mode

Another request:

GET /products
    |
    v
API Gateway
    |
    v
Product Service
Enter fullscreen mode Exit fullscreen mode

The frontend only needs to know the gateway address.

What does an API Gateway do?

Common responsibilities include:

  1. Routing: Sends requests to the correct service.
  2. Authentication: Checks whether the caller is authenticated.
  3. Authorization: Applies access rules.
  4. Rate limiting: Restricts excessive requests.
  5. Logging: Records incoming requests.
  6. Load balancing: Distributes requests across service instances when configured.

Spring Cloud Gateway

Spring Cloud Gateway is a Spring project used to build API gateways.

It supports routing, filters, security integration, and other gateway features.

A simplified route configuration looks like this:

spring:
  cloud:
    gateway:
      server:
        webflux:
          routes:
            - id: user-service
              uri: http://localhost:8081
              predicates:
                - Path=/users/**
Enter fullscreen mode Exit fullscreen mode

A request to:

http://localhost:8080/users/101
Enter fullscreen mode Exit fullscreen mode

is routed to:

http://localhost:8081/users/101
Enter fullscreen mode Exit fullscreen mode

The exact configuration should be matched to the Spring Cloud Gateway server variant and release train used by your application.

Behind the scenes

The gateway receives the request, evaluates its routing rules, applies configured filters, and forwards the request to the selected destination.

The backend service processes the request and returns a response through the gateway to the client.

Important: An API Gateway is not the same thing as a Service Registry.

  • API Gateway provides a common entry point for clients.
  • Service Registry helps services discover the network locations of other services.

We'll understand the Service Registry next.

Service Registry and Eureka

Let's look at another problem.

Suppose we have three instances of the Order Service.

Order Service Instance 1 -> localhost:8083
Order Service Instance 2 -> localhost:8084
Order Service Instance 3 -> localhost:8085
Enter fullscreen mode Exit fullscreen mode

Now the Payment Service wants to communicate with the Order Service.

Which URL should it use?

If we hardcode:

"http://localhost:8083"
Enter fullscreen mode Exit fullscreen mode

we have a problem.

What if that instance goes down?

What if another instance starts on a different port?

What if the application is deployed in a cloud environment where IP addresses change?

Maintaining service addresses manually becomes difficult.

This is the problem solved by Service Discovery.

Service Discovery is the process of finding the network location of another service dynamically.

A Service Registry is a central directory that stores information about available service instances.

Think of it like a contact directory.

Instead of remembering everyone's phone number, you search for their name in the directory.

The same idea applies to microservices.

                +------------------+
                |  Service Registry|
                |                  |
                |  Order Service   |
                |  localhost:8083  |
                |  localhost:8084  |
                |                  |
                |  Payment Service |
                |  localhost:8086  |
                +------------------+
                         ^
                         |
              Register / Heartbeat
                         |
              +----------+----------+
              |                     |
              v                     v
         Order Service         Payment Service
          Instances
Enter fullscreen mode Exit fullscreen mode

When a service starts, it registers its information with the registry.

Other services can then discover its available instances.

What is Eureka?

Netflix Eureka is a service discovery solution.

It provides two major components:

  • Eureka Server.
  • Eureka Client.

Eureka Server

Eureka Server maintains information about registered service instances.

It acts as the service registry.

Eureka Client

Eureka Client is included in applications that need to register themselves with Eureka or discover other registered services.

For example, the Order Service registers itself with Eureka.

The Payment Service can discover the Order Service through Eureka.

How Eureka works

               Eureka Server
                    |
          +---------+---------+
          |                   |
          v                   v
     Order Service       Payment Service
          |                   |
          | Register          | Register
          | Heartbeat         | Heartbeat
          |                   |
          +-------------------+
                    |
                    v
              Service Registry
Enter fullscreen mode Exit fullscreen mode

The basic lifecycle is:

  1. A service starts.
  2. The Eureka Client registers the service instance.
  3. The client periodically sends heartbeats.
  4. Eureka maintains information about registered instances.
  5. Other clients obtain service information.
  6. Clients can use the discovered addresses to communicate.

Eureka uses leases and heartbeat-based renewal. Failure detection is not instantaneous, and registry information can temporarily be stale.

Behind the scenes

Eureka stores service information such as:

  • Application name.
  • Instance ID.
  • Hostname.
  • Port.
  • Health-check information.
  • Registration status.

For example:

Application: ORDER-SERVICE

Instance 1:
    Host: 192.168.1.10
    Port: 8083

Instance 2:
    Host: 192.168.1.11
    Port: 8083

Application: PAYMENT-SERVICE

Instance 1:
    Host: 192.168.1.20
    Port: 8084
Enter fullscreen mode Exit fullscreen mode

When another service asks for ORDER-SERVICE, Eureka can provide the registered instances.

Load balancing

Now we know how services discover one another.

But another question remains.

Suppose Eureka returns three instances of Order Service.

Which instance should the Payment Service call?

Should every request go to the first instance?

That would overload one instance while leaving the others underutilized.

This is where Load Balancing comes into the picture.

Load balancing means distributing incoming requests across multiple available instances of a service.

                Payment Service
                       |
                       |
                       v
                Load Balancer
                       |
             +---------+---------+
             |         |         |
             v         v         v
          Order     Order     Order
          Instance  Instance  Instance
             1         2         3
Enter fullscreen mode Exit fullscreen mode

For example:

Request 1 -> Order Instance 1
Request 2 -> Order Instance 2
Request 3 -> Order Instance 3
Request 4 -> Order Instance 1
Enter fullscreen mode Exit fullscreen mode

This is a simplified round-robin example.

Actual load-balancing decisions depend on the configured algorithm and available instance information.

Types of load balancing

There are two common approaches.

1. Server-side load balancing

A dedicated load balancer receives requests and forwards them to backend instances.

Examples include:

  • NGINX.
  • HAProxy.
  • Cloud load balancers.
Client
   |
   v
Load Balancer
   |
   +----> Service Instance 1
   |
   +----> Service Instance 2
   |
   +----> Service Instance 3
Enter fullscreen mode Exit fullscreen mode

2. Client-side load balancing

The client obtains a list of available service instances and selects one before making the request.

Spring Cloud LoadBalancer provides client-side load-balancing capabilities.

Payment Service
      |
      v
Service Discovery
      |
      v
Available Instances
      |
      v
Client-side Load Balancer
      |
      v
Selected Order Instance
Enter fullscreen mode Exit fullscreen mode

Spring Cloud LoadBalancer

Spring Cloud LoadBalancer integrates with Spring Cloud service discovery.

When used with Eureka, the client can obtain service instances from Eureka and select an instance for an outgoing request.

For example, the client can use a logical service name:

http://ORDER-SERVICE/orders/101
Enter fullscreen mode Exit fullscreen mode

Instead of hardcoding:

http://localhost:8083/orders/101
Enter fullscreen mode Exit fullscreen mode

The logical service name is resolved to an actual instance.

Behind the scenes

The simplified process is:

  1. The client requests ORDER-SERVICE.
  2. The discovery mechanism provides available instances.
  3. Spring Cloud LoadBalancer selects an instance.
  4. The HTTP request is sent to that instance.
  5. The response is returned to the caller.

Important distinction:

  • Eureka answers: Where are the service instances?
  • Load Balancer answers: Which instance should receive this request?

They solve different problems but work together.

Fail fast

So far, we have discussed how services communicate and discover one another.

But distributed systems introduce one unavoidable problem.

What happens when another service is unavailable?

Imagine this scenario:

Ravi places an order.

The Order Service calls the Payment Service.

Unfortunately, the Payment Service is down.

What should the Order Service do?

Should it keep waiting indefinitely?

Of course not.

This is where the concept of Fail Fast becomes important.

Fail fast means detecting a failure quickly and stopping the operation instead of wasting resources waiting for something that is unlikely to succeed.

Let's understand this with an example.

Suppose the Order Service makes an HTTP request to the Payment Service.

           Order Service
                 |
                 v
           Payment Service
                 |
                 X
             Unavailable
Enter fullscreen mode Exit fullscreen mode

Without proper timeouts, requests can remain blocked while waiting for a response.

If hundreds of requests are waiting, application threads and other resources can become exhausted.

We need timeouts.

Timeout

A timeout defines how long a service should wait for another service to respond.

For example:

Payment Service timeout = 3 seconds
Enter fullscreen mode Exit fullscreen mode

If Payment Service does not respond within three seconds, the request fails.

A simplified example using RestClient:

@Configuration
public class HttpClientConfig {

    @Bean
    public RestClient paymentRestClient() {

        SimpleClientHttpRequestFactory factory =
                new SimpleClientHttpRequestFactory();

        factory.setConnectTimeout(Duration.ofSeconds(2));
        factory.setReadTimeout(Duration.ofSeconds(3));

        return RestClient.builder()
                .baseUrl("http://localhost:8082")
                .requestFactory(factory)
                .build();
    }
}
Enter fullscreen mode Exit fullscreen mode

The connection timeout limits how long establishing a connection can take.

The read timeout limits how long the client waits for response data.

These are not necessarily a complete end-to-end deadline for the entire business operation.

Circuit Breaker

Timeouts help us stop waiting too long.

But what if the Payment Service keeps failing?

Should we continue sending requests every time?

A Circuit Breaker helps prevent repeated calls to an unhealthy service.

It has three main states:

  1. CLOSED.
  2. OPEN.
  3. HALF-OPEN.
              +----------+
              |  CLOSED  |
              +----------+
                   |
             Failures exceed
               threshold
                   |
                   v
              +----------+
              |   OPEN   |
              +----------+
                   |
             Wait for a
             configured time
                   |
                   v
             +-----------+
             | HALF-OPEN |
             +-----------+
                |     |
          Success   Failure
                |     |
                v     v
             CLOSED  OPEN
Enter fullscreen mode Exit fullscreen mode

CLOSED: Requests are allowed normally. Failures are monitored.

OPEN: Requests are rejected or short-circuited without calling the downstream service.

HALF-OPEN: A limited number of test requests are allowed to check whether the service has recovered.

Spring Cloud CircuitBreaker provides an abstraction for integrating circuit breaker implementations such as Resilience4j.

Fail Fast vs Circuit Breaker

These concepts are related but not identical.

  • Timeout limits how long a request waits.
  • Fail fast avoids continuing an operation when failure is already known.
  • Circuit Breaker prevents repeatedly calling a failing dependency.

A production microservice should also consider retries, bulkheads, fallback behavior, and proper error responses.

Be careful with retries on payment operations. Retrying a non-idempotent operation can accidentally charge a customer twice unless the operation is protected with an idempotency mechanism.

Building a small Spring Cloud example

Now let's connect everything using Spring Boot and Spring Cloud.

We'll create three applications:

                 +------------------+
                 |  Eureka Server   |
                 |   Port: 8761     |
                 +------------------+
                          |
              +-----------+-----------+
              |                       |
              v                       v
       +-------------+         +-------------+
       | Order       |         | Payment     |
       | Service     |         | Service     |
       | Port: 8081  |         | Port: 8082  |
       +-------------+         +-------------+
              |                       ^
              |                       |
              +---- HTTP / Feign -----+
Enter fullscreen mode Exit fullscreen mode

Our goal:

  1. Start Eureka Server.
  2. Register Order Service.
  3. Register Payment Service.
  4. Call Payment Service from Order Service using OpenFeign.
  5. Understand how RestTemplate was traditionally used for the same purpose.

Project dependencies

For Spring Boot 4.2.0 and Spring Cloud 2026.0.0, use the Spring Cloud BOM to manage compatible Spring Cloud dependency versions.

Add this dependency management to the Maven project:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>2026.0.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
Enter fullscreen mode Exit fullscreen mode

For the Eureka Server project, add:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

For Order Service and Payment Service, add:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

For OpenFeign in Order Service, additionally add:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

These examples assume the projects also have the appropriate Spring Boot web starter.

Create the Eureka Server

First, let's create a Spring Boot application named eureka-server.

Add the Eureka Server dependency shown earlier.

Create the main application class:

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

    public static void main(String[] args) {

        SpringApplication.run(
                EurekaServerApplication.class,
                args
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

What does @EnableEurekaServer do?

It enables the Eureka Server functionality in our Spring Boot application.

Now configure application.properties:

spring.application.name=eureka-server

server.port=8761

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
Enter fullscreen mode Exit fullscreen mode

Why do we set these two properties to false?

A Eureka Server can also behave as a Eureka Client.

However, for a standalone development server, we don't need it to register itself with another Eureka Server or fetch another registry.

Start the application.

Open:

http://localhost:8761
Enter fullscreen mode Exit fullscreen mode

You should see the Eureka dashboard.

At this point, the registry is running, but no application has registered yet.

Register services with Eureka

Now let's create the Payment Service.

Add the Eureka Client dependency.

Create its main class:

@SpringBootApplication
public class PaymentServiceApplication {

    public static void main(String[] args) {

        SpringApplication.run(
                PaymentServiceApplication.class,
                args
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Create a simple REST controller:

@RestController
@RequestMapping("/payments")
public class PaymentController {

    @GetMapping("/{orderId}")
    public String getPayment(
            @PathVariable Long orderId) {

        return "Payment successful for order: " + orderId;
    }
}
Enter fullscreen mode Exit fullscreen mode

Configure application.properties:

spring.application.name=payment-service

server.port=8082

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
Enter fullscreen mode Exit fullscreen mode

Notice this property:

spring.application.name=payment-service
Enter fullscreen mode Exit fullscreen mode

This is the application name under which the service registers itself.

Now start Payment Service.

Open the Eureka dashboard again.

You should see:

Instances currently registered with Eureka

PAYMENT-SERVICE
    localhost:8082
Enter fullscreen mode Exit fullscreen mode

Now create the Order Service.

Its main class:

@SpringBootApplication
public class OrderServiceApplication {

    public static void main(String[] args) {

        SpringApplication.run(
                OrderServiceApplication.class,
                args
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Configure application.properties:

spring.application.name=order-service

server.port=8081

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
Enter fullscreen mode Exit fullscreen mode

Start the Order Service.

The Eureka dashboard should now show both applications:

Instances currently registered with Eureka

PAYMENT-SERVICE
    localhost:8082

ORDER-SERVICE
    localhost:8081
Enter fullscreen mode Exit fullscreen mode

Congratulations! Both services have registered themselves with Eureka.

Behind the scenes

Order Service
     |
     | Registration
     v
Eureka Server
     ^
     | Registration
     |
Payment Service
Enter fullscreen mode Exit fullscreen mode

Both applications use their Eureka clients to register and renew their leases.

Call another service with OpenFeign

Now comes the interesting part.

We want Order Service to communicate with Payment Service.

One way is to manually create HTTP requests.

But Spring Cloud provides a cleaner approach called OpenFeign.

What is OpenFeign?

OpenFeign is a declarative HTTP client.

Declarative means we describe what we want to call using an interface and annotations instead of manually writing the HTTP request logic.

Think about the difference.

Without OpenFeign, we manually write the code to:

  • Build an HTTP request.
  • Send the request.
  • Receive the response.
  • Convert the response into a Java object.

With OpenFeign, we define an interface describing the remote API.

Spring creates the implementation for us at runtime.

Let's implement it.

First, add the OpenFeign dependency to Order Service.

Now update the main application class:

@SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication {

    public static void main(String[] args) {

        SpringApplication.run(
                OrderServiceApplication.class,
                args
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

What does @EnableFeignClients do?

It enables scanning and registration of Feign client interfaces.

Now create an interface:

@FeignClient(name = "payment-service")
public interface PaymentClient {

    @GetMapping("/payments/{orderId}")
    String getPayment(
            @PathVariable("orderId") Long orderId
    );
}
Enter fullscreen mode Exit fullscreen mode

Let's understand this carefully.

1. @FeignClient

@FeignClient(name = "payment-service")
Enter fullscreen mode Exit fullscreen mode

This tells Spring Cloud that this interface represents an HTTP client for the Payment Service.

Notice that we are using the application name, not the IP address or port.

Why?

Because we want Spring Cloud to discover the service through Eureka.

2. @GetMapping

@GetMapping("/payments/{orderId}")
Enter fullscreen mode Exit fullscreen mode

This describes the HTTP endpoint that should be called.

3. Method definition

String getPayment(Long orderId);
Enter fullscreen mode Exit fullscreen mode

The return type describes the expected response.

Now inject this interface into the Order Service controller.

@RestController
@RequestMapping("/orders")
public class OrderController {

    private final PaymentClient paymentClient;

    public OrderController(PaymentClient paymentClient) {
        this.paymentClient = paymentClient;
    }

    @GetMapping("/{orderId}")
    public String getOrder(
            @PathVariable Long orderId) {

        return paymentClient.getPayment(orderId);
    }
}
Enter fullscreen mode Exit fullscreen mode

Start all three applications:

  1. Eureka Server.
  2. Payment Service.
  3. Order Service.

Now send this request:

curl http://localhost:8081/orders/101
Enter fullscreen mode Exit fullscreen mode

Expected output:

Payment successful for order: 101
Enter fullscreen mode Exit fullscreen mode

That's it!

We have successfully communicated between two independent Spring Boot applications using OpenFeign and Eureka.

Behind the scenes

You might be wondering:

We only created an interface. Where is its implementation?

Spring Cloud OpenFeign creates a client implementation using a runtime proxy.

The simplified flow is:

Order Controller
       |
       v
PaymentClient Interface
       |
       v
Feign Proxy
       |
       v
Service Discovery
       |
       v
Eureka Registry
       |
       v
Spring Cloud LoadBalancer
       |
       v
Payment Service Instance
       |
       v
HTTP Response
Enter fullscreen mode Exit fullscreen mode

The Feign proxy converts the Java method invocation into an HTTP request.

Eureka helps discover the service instances, and Spring Cloud LoadBalancer selects an instance.

The response is converted into the Java return type.

One important detail: OpenFeign does not require Eureka in every setup. Without Eureka, you can configure a fixed URL or use another discovery mechanism.

Call another service with RestTemplate

Before OpenFeign became a popular approach in Spring Cloud applications, developers commonly used RestTemplate to make HTTP calls.

What is RestTemplate?

RestTemplate is a synchronous HTTP client provided by Spring Framework.

It allows us to send HTTP requests and receive responses using Java methods.

Let's understand it using our Payment Service.

A traditional implementation in Order Service looks like this:

@Service
public class PaymentService {

    private final RestTemplate restTemplate;

    public PaymentService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String getPayment(Long orderId) {

        return restTemplate.getForObject(
                "http://localhost:8082/payments/" + orderId,
                String.class
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

We need to configure the RestTemplate bean:

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {

        return new RestTemplate();
    }
}
Enter fullscreen mode Exit fullscreen mode

The Order Service controller can call PaymentService just like any other Spring bean.

Output:

Payment successful for order: 101
Enter fullscreen mode Exit fullscreen mode

However, notice something.

We hardcoded:

http://localhost:8082
Enter fullscreen mode Exit fullscreen mode

This creates the same problem we discussed earlier.

What if Payment Service runs on a different port?

What if we have multiple instances?

We need service discovery and client-side load balancing.

In older Spring Cloud configurations, developers commonly used @LoadBalanced with a RestTemplate bean.

For example:

@Configuration
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {

        return new RestTemplate();
    }
}
Enter fullscreen mode Exit fullscreen mode

Now we can use the logical service name:

restTemplate.getForObject(
        "http://payment-service/payments/" + orderId,
        String.class
);
Enter fullscreen mode Exit fullscreen mode

Here, @LoadBalanced tells Spring Cloud to configure the RestTemplate with a client-side load-balancing interceptor.

That interceptor resolves payment-service using the configured discovery mechanism and selects an instance.

Important version note:

RestTemplate is now deprecated in Spring Framework 7.1 in favor of RestClient.

Spring Boot 4.2 also deprecates its RestTemplate support infrastructure in favor of RestClient.

The RestTemplate examples above demonstrate the established approach you will encounter in existing projects and older tutorials. For new Spring Framework 7 applications, prefer RestClient or an appropriate HTTP Service Client.

Also, do not assume that adding @LoadBalanced to every HTTP client automatically enables Eureka discovery. The required Spring Cloud LoadBalancer and discovery dependencies must be present.

Which one should I use?

We've covered several components and libraries.

Let's understand when to choose each one.

1. Synchronous vs Asynchronous communication

Choose synchronous communication when:

  • The caller immediately needs a response.
  • You are building request-response APIs.
  • The operation needs an immediate result.

Choose asynchronous communication when:

  • The operation can happen in the background.
  • Multiple consumers need the same event.
  • You want to reduce direct dependency between services.

Default: Use synchronous HTTP for straightforward request-response operations and asynchronous messaging for independent background workflows.

2. OpenFeign vs RestTemplate vs RestClient

Choose OpenFeign when:

  • You want a declarative HTTP client.
  • You have multiple service-to-service REST calls.
  • You want Spring Cloud LoadBalancer integration.
  • You prefer interface-based API definitions.

Choose RestClient when:

  • You want to build HTTP requests programmatically.
  • You need a synchronous HTTP client.
  • You are using modern Spring Framework versions.

Choose RestTemplate when:

  • You are maintaining an older Spring application.
  • You are working with existing code that already uses it.

Default: For a Spring Cloud application, OpenFeign is a convenient choice for declarative service-to-service communication. For a general synchronous HTTP client, prefer RestClient in modern Spring applications.

3. Eureka vs hardcoded URLs

Choose Eureka when:

  • Service instances change dynamically.
  • You have multiple instances of services.
  • You want centralized service registration and discovery.

Hardcoded URLs can be acceptable for small local examples or static infrastructure, but they become difficult to maintain as systems grow.

Default: Use service discovery when your environment has dynamic service instances.

4. API Gateway vs Service Registry

Use API Gateway when you need:

  • A single entry point for external clients.
  • Centralized routing.
  • Gateway-level authentication and rate limiting.

Use Service Registry when you need:

  • Dynamic service registration.
  • Service discovery.
  • Information about available service instances.

Default: They solve different problems. In a larger microservices system, you may need both.

Common mistakes

Here are six mistakes beginners commonly make while working with Spring Cloud microservices.

  1. Hardcoding service URLs: Avoid using fixed IP addresses and ports when services are deployed dynamically. Use service discovery and logical service names when appropriate.

  2. Thinking Eureka performs load balancing: Eureka maintains service registration information. Spring Cloud LoadBalancer selects an instance for a request. Understand the difference.

  3. Confusing API Gateway with Eureka: An API Gateway routes client requests, whereas Eureka helps services discover one another. They are not interchangeable.

  4. Ignoring timeouts: Never assume another service will always respond. Configure connection and response timeouts to prevent requests from waiting indefinitely.

  5. Using synchronous communication for everything: Not every operation needs an immediate response. Use asynchronous messaging for background workflows and independent event processing.

  6. Using outdated libraries in new applications: Learn RestTemplate because you will encounter it in existing projects, but prefer RestClient or suitable HTTP Service Clients for new Spring Framework 7 applications.

Quick recap

Let's quickly revise everything we learned.

  • Microservices: An architectural style where an application is divided into independently deployable services.
  • Synchronous communication: The caller waits for a response.
  • Asynchronous communication: The caller sends a message without waiting for the consumer to finish processing.
  • API Gateway: Provides a common entry point for external clients.
  • Service Registry: Maintains information about available service instances.
  • Eureka Server: Implements a service registry.
  • Eureka Client: Registers applications and discovers services.
  • Load Balancer: Selects an instance to handle a request.
  • Fail Fast: Detects failures quickly instead of waiting unnecessarily.
  • OpenFeign: A declarative HTTP client for communicating with other services.
  • RestTemplate: An older synchronous HTTP client, deprecated in modern Spring Framework.
  • RestClient: The modern synchronous HTTP client provided by Spring Framework.

Here is how the major components work together:

                    FRONTEND
                       |
                       v
                 API GATEWAY
                       |
                       v
                 ORDER SERVICE
                       |
                       v
                 OPENFEIGN CLIENT
                       |
                       v
                EUREKA DISCOVERY
                       |
                       v
                LOAD BALANCER
                       |
             +---------+---------+
             |         |         |
             v         v         v
          PAYMENT  PAYMENT   PAYMENT
          INSTANCE INSTANCE  INSTANCE
             1         2         3

                       |
                       v
                PAYMENT RESPONSE
Enter fullscreen mode Exit fullscreen mode

Remember the responsibilities:

API Gateway       -> Entry point

Eureka            -> Service discovery

Load Balancer     -> Instance selection

OpenFeign         -> HTTP communication

Timeout           -> Limits waiting time

Circuit Breaker   -> Prevents repeated calls
                     to an unhealthy service
Enter fullscreen mode Exit fullscreen mode

Try it yourself

Practice idea:

Build a small e-commerce microservices application with three Spring Boot projects:

  1. Eureka Server.
  2. Order Service.
  3. Payment Service.

Register both services with Eureka and use OpenFeign to communicate between them.

Try running two instances of Payment Service on different ports. Verify that the Order Service can communicate using the logical service name instead of a hardcoded URL.

Bonus experiment:

Stop the Payment Service while the Order Service is running.

Observe what happens when you call the Order Service.

Then introduce a timeout and a circuit breaker. Compare the behavior before and after.

If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.

Top comments (0)