DEV Community

DevCorner
DevCorner

Posted on

Microservices Architecture: A One-Stop Interview Guide

Microservices have become the go-to architecture for building scalable, maintainable, and distributed systems. This guide covers essential microservices concepts, including service discovery, inter-service communication, circuit breakers, distributed tracing, API gateways, and more.

1. Service Discovery in Microservices

Service discovery helps microservices locate and communicate with each other dynamically without hardcoded IPs. The most popular service discovery tools include:

Eureka (Netflix OSS)

  • Eureka Server acts as a service registry where microservices register themselves.
  • Eureka Clients query the registry to discover other services.
  • Supports self-healing and automatic failover.

Implementation in Spring Boot:

  1. Add dependencies:
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
   </dependency>
Enter fullscreen mode Exit fullscreen mode
  1. Enable Eureka Server:
   @EnableEurekaServer
   @SpringBootApplication
   public class EurekaServerApplication {
       public static void main(String[] args) {
           SpringApplication.run(EurekaServerApplication.class, args);
       }
   }
Enter fullscreen mode Exit fullscreen mode

Consul

  • Distributed, highly available service discovery and configuration system.
  • Supports health checking and key-value storage.

Zookeeper

  • Centralized service registry that follows a leader-follower model.
  • Used for distributed coordination and dynamic discovery.

2. Inter-Service Communication: Synchronous vs Asynchronous

Microservices communicate using REST, gRPC (synchronous) or message brokers like Kafka, RabbitMQ (asynchronous).

Synchronous Communication

  • Uses HTTP/REST or gRPC.
  • Simple but leads to tight coupling.
  • Example using Feign Client:
  @FeignClient(name = "order-service")
  public interface OrderClient {
      @GetMapping("/orders/{id}")
      Order getOrder(@PathVariable("id") Long id);
  }
Enter fullscreen mode Exit fullscreen mode

Asynchronous Communication

  • Uses message brokers like Kafka, RabbitMQ.
  • Improves scalability and decoupling.
  • Example using Kafka Producer and Consumer:
  @Service
  public class KafkaProducer {
      @Autowired private KafkaTemplate<String, String> kafkaTemplate;
      public void sendMessage(String message) {
          kafkaTemplate.send("order-topic", message);
      }
  }
Enter fullscreen mode Exit fullscreen mode

3. Circuit Breakers in Spring Boot

Circuit breakers prevent cascading failures by detecting failures and stopping requests to failing services.

Implementation Using Resilience4j

  1. Add dependency:
   <dependency>
       <groupId>io.github.resilience4j</groupId>
       <artifactId>resilience4j-spring-boot2</artifactId>
   </dependency>
Enter fullscreen mode Exit fullscreen mode
  1. Use @CircuitBreaker annotation:
   @CircuitBreaker(name = "orderService", fallbackMethod = "fallbackMethod")
   public String getOrder() {
       return restTemplate.getForObject("http://order-service/orders", String.class);
   }
   public String fallbackMethod(Exception e) {
       return "Fallback Order Service Response";
   }
Enter fullscreen mode Exit fullscreen mode

4. SAGA Pattern for Distributed Transactions

SAGA ensures data consistency across multiple microservices using a series of local transactions.

Two Types of SAGA

  • Choreography (event-driven, no central coordinator).
  • Orchestration (uses a central orchestrator to manage workflow).

Example using Orchestrator:

  1. Order Service creates an order and triggers an event.
  2. Payment Service processes the payment and publishes an event.
  3. If payment fails, Order Service rolls back.

5. Spring Cloud Config Server

Spring Cloud Config Server provides externalized configuration management.

Implementation

  1. Add dependencies:
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-config-server</artifactId>
   </dependency>
Enter fullscreen mode Exit fullscreen mode
  1. Enable Config Server:
   @EnableConfigServer
   @SpringBootApplication
   public class ConfigServerApplication {
       public static void main(String[] args) {
           SpringApplication.run(ConfigServerApplication.class, args);
       }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Store configuration in a Git repository.

6. OAuth2 & JWT for Authentication in Microservices

OAuth2 and JWT provide secure authentication in microservices.

OAuth2 Flow

  1. Client requests a token from Authorization Server.
  2. Token is validated by Resource Server.
  3. JWT (JSON Web Token) is used to pass claims securely.

Spring Security Implementation:

@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/secure/**").authenticated();
    }
}
Enter fullscreen mode Exit fullscreen mode

7. Distributed Tracing in Microservices

Distributed tracing helps track requests across microservices.

Using Spring Cloud Sleuth & Zipkin

  1. Add dependencies:
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-sleuth</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-zipkin</artifactId>
   </dependency>
Enter fullscreen mode Exit fullscreen mode
  1. Enable tracing:
   spring.zipkin.base-url=http://localhost:9411
   logging.pattern.level=%d{yyyy-MM-dd HH:mm:ss} [%X{traceId}/%X{spanId}]
Enter fullscreen mode Exit fullscreen mode

8. API Gateway Patterns

API Gateways handle authentication, routing, and load balancing.

Netflix Zuul

  • Route requests to different services.
  • Example:
  @EnableZuulProxy
  @SpringBootApplication
  public class ApiGatewayApplication {
      public static void main(String[] args) {
          SpringApplication.run(ApiGatewayApplication.class, args);
      }
  }
Enter fullscreen mode Exit fullscreen mode

Spring Cloud Gateway

  • Reactive, lightweight alternative to Zuul.
  • Example Route Configuration:
  spring:
    cloud:
      gateway:
        routes:
          - id: order-service
            uri: lb://order-service
            predicates:
              - Path=/orders/**
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding microservices architecture concepts like service discovery, inter-service communication, circuit breakers, authentication, tracing, and API gateways is crucial for building scalable systems. Mastering these topics will help you ace microservices interviews and build robust distributed applications.

Top comments (0)