Microservices Architecture

Microservices is one of the most asked topics in PRA and Sprints 3-4. The questions are mostly conceptual — understanding the architecture, components, and when to use what. You won't be asked to build a full microservices system, but you need to know Spring Cloud annotations and the role of each component.

Exam Weight
PRA: 3-5 MCQs on microservices concepts, monolith comparison, and architecture components.
Sprint 3-4: You may build simple Spring Boot microservices with Eureka discovery. Know annotations cold.

1. What are Microservices?

Microservices is an architectural style where an application is built as a collection of small, independent services, each running in its own process and communicating via lightweight mechanisms (usually HTTP/REST).

Each service does ONE thing well — it has a single responsibility, its own database, and can be deployed independently.

Think of it this way
Monolith = one big restaurant kitchen where everyone cooks everything together. If the pizza oven breaks, the whole kitchen shuts down.

Microservices = a food court with specialized stalls. The pizza stall, the burger stall, the juice stall — each operates independently. If the pizza stall has a problem, everyone else keeps running.
Exam Tip
The definition question comes in many forms: "What is microservices architecture?", "Which architectural style breaks an application into small independent services?" — all the same answer.

2. Monolithic vs Microservices (ALWAYS ASKED)

This is the most frequently asked comparison in TCS ILP exams. Memorize this table — at least 1-2 questions will come from here.

Monolithic Architecture

The entire application is built as a single deployable unit. All features — UI, business logic, data access — are in one codebase, one project, one WAR/JAR file.

Microservices Architecture

Each feature is its own independently deployable service. User management is one service, payment is another, notifications is another. Each has its own codebase, database, and deployment pipeline.

AspectMonolithicMicroservices
CodebaseSingle codebase for everythingSeparate codebase per service
DeploymentDeploy entire app for any changeDeploy only the changed service
ScalingScale the entire app (vertical)Scale individual services (horizontal)
TechnologyOne tech stack for everythingEach service can use different tech
Team StructureOne large teamSmall teams per service
Failure ImpactOne bug can crash the whole appFailure is isolated to one service
DatabaseShared databaseDatabase per service
CommunicationIn-process method callsNetwork calls (REST, messaging)
ComplexitySimple to develop initiallyComplex (distributed systems)
Startup TimeSlow (loads entire app)Fast (small services)
TestingEasier (single app)Harder (integration across services)
Common Exam Trap
"Microservices are always better than monolith" — FALSE. For small applications with a small team, monolith is often the better choice. Microservices add complexity that isn't worth it for simple apps. Exam loves this trick.

When to use Monolith?

When to use Microservices?

3. Key Characteristics of Microservices

These are the defining features of microservices architecture. Exam asks "which of the following is a characteristic of microservices?"

CharacteristicWhat It Means
Single ResponsibilityEach service handles ONE business capability (e.g., only user management, only payments)
Independent DeploymentDeploy one service without affecting others. No need to redeploy the whole app.
Decentralized DataEach service owns its own database. No shared database across services.
Lightweight CommunicationServices talk via REST APIs (HTTP) or message queues. Not heavy protocols like SOAP.
Technology AgnosticUser Service can be in Java, Payment Service in Python, Notification Service in Node.js.
Fault IsolationIf Payment Service crashes, User Service and Product Service keep working.
Independently ScalableIf Order Service gets heavy traffic, scale only that service — not the entire app.
Organized Around BusinessTeams are organized by business domain (Order team, Payment team), not by technology layers.
Memory trick
S-I-D-L-T-F — Single responsibility, Independent deployment, Decentralized data, Lightweight communication, Technology agnostic, Fault isolation. These six cover 90% of characteristic-based questions.

4. Microservices Architecture Components

A microservices system isn't just services — it needs supporting infrastructure. Know each component's role.

Architecture Diagram (Text)

         ┌──────────────┐
         │    Client     │  (Browser / Mobile App)
         └──────┬───────┘
                │
         ┌──────▼───────┐
         │  API Gateway  │  (Single entry point)
         └──────┬───────┘
                │
    ┌───────────┼───────────┐
    │           │           │
┌───▼───┐ ┌────▼────┐ ┌────▼────┐
│ User  │ │ Order   │ │ Payment │  (Microservices)
│Service│ │ Service │ │ Service │
└───┬───┘ └────┬────┘ └────┬────┘
    │          │           │
┌───▼───┐ ┌────▼────┐ ┌────▼────┐
│User DB│ │Order DB │ │Pay DB   │  (Each owns its DB)
└───────┘ └─────────┘ └─────────┘

    All services register with:
    ┌────────────────────┐
    │  Service Registry  │  (Eureka Server)
    │  (Eureka)          │
    └────────────────────┘

    Config loaded from:
    ┌────────────────────┐
    │   Config Server    │  (Centralized config)
    └────────────────────┘
ComponentRoleSpring Cloud Tool
API GatewaySingle entry point — routes requests, handles auth, rate limitingSpring Cloud Gateway / Zuul
Service RegistryServices register themselves; other services discover them by nameNetflix Eureka
Config ServerCentralized configuration for all servicesSpring Cloud Config
Load BalancerDistributes incoming requests across service instancesRibbon (client-side)
Circuit BreakerPrevents cascading failures when a service is downResilience4j / Hystrix
Distributed TracingTrack a request across multiple servicesSleuth + Zipkin
Exam Tip
Exam often asks: "What is the role of API Gateway?" or "Which component handles service registration?" — know the component-to-role mapping from this table.

5. Communication Between Services

Services need to talk to each other. There are two main approaches:

Synchronous Communication

Service A calls Service B and waits for the response before continuing.

Asynchronous Communication

Service A sends a message and doesn't wait. Service B processes it later.

AspectSynchronous (REST)Asynchronous (Messaging)
WaitingCaller waits for responseCaller doesn't wait (fire-and-forget)
CouplingTighter — both services must be upLooser — services are decoupled
SpeedImmediate responseEventually processed
Use CaseGet user details, check inventorySend email notification, process order
Failure HandlingFails if target is downMessage waits in queue until target is up
When to use which?
Synchronous: When you NEED the response right now (e.g., "Is this product in stock?" before placing order).
Asynchronous: When you DON'T need an immediate response (e.g., "Send a confirmation email" after order is placed).

6. API Gateway

The API Gateway is the single entry point for all client requests. Instead of clients calling individual services directly, they call the gateway, and it routes the request to the right service.

How It Works

  Without API Gateway:
  Client → User Service    (port 8081)
  Client → Order Service   (port 8082)
  Client → Payment Service (port 8083)
  (Client needs to know every service's address!)

  With API Gateway:
  Client → API Gateway (port 8080) → routes to correct service
  Client only knows ONE address!

What API Gateway Does:

Spring Cloud Gateway Config (Know the Format)

# application.yml for API Gateway
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://USER-SERVICE
          predicates:
            - Path=/api/users/**
        - id: order-service
          uri: lb://ORDER-SERVICE
          predicates:
            - Path=/api/orders/**
Exam Tip
"What is the purpose of API Gateway in microservices?" — Answer: Single entry point that handles routing, authentication, rate limiting, and load balancing. Don't confuse with Service Registry (which handles service discovery, not routing).

7. Service Discovery (Eureka)

The Problem

In microservices, services run on dynamic IPs and ports. If Order Service needs to call User Service, how does it know where User Service is running? Hardcoding IPs breaks everything when services scale or restart.

The Solution: Service Registry

A Service Registry (like Netflix Eureka) acts as a phone book for services:

  1. Register — When a service starts, it registers itself with Eureka ("I'm User Service, running at 192.168.1.5:8081")
  2. Discover — When Order Service needs User Service, it asks Eureka ("Where is User Service?")
  3. Call — Order Service gets the address and makes the call

Client-Side vs Server-Side Discovery

TypeHow It WorksExample
Client-SideClient queries registry and picks an instance itselfNetflix Eureka + Ribbon
Server-SideClient calls a load balancer, which queries registry and routesAWS ELB, Kubernetes

Eureka Setup (Know These Annotations)

// Eureka SERVER — the registry itself
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

// Eureka CLIENT — any microservice that registers
@SpringBootApplication
@EnableEurekaClient
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}
# Eureka Server — application.properties
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

# Eureka Client — application.properties
spring.application.name=user-service
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
Don't confuse these
@EnableEurekaServer — goes on the REGISTRY application (the phone book itself).
@EnableEurekaClient — goes on EACH microservice that wants to register.
The server has register-with-eureka=false because the registry doesn't register itself!

8. Spring Cloud for Microservices

Spring Cloud provides tools to implement microservices patterns on top of Spring Boot. Know the mapping:

PatternSpring Cloud ToolAnnotation
Service DiscoveryNetflix Eureka@EnableEurekaServer, @EnableEurekaClient
API GatewaySpring Cloud Gateway / Zuul@EnableZuulProxy (Zuul)
Service-to-Service CallsOpenFeign@EnableFeignClients, @FeignClient
Client-Side Load BalancingRibbonAuto-configured with Eureka
Circuit BreakerResilience4j / Hystrix@CircuitBreaker
Centralized ConfigSpring Cloud Config@EnableConfigServer
Distributed TracingSleuth + ZipkinAuto-configured

Feign Client — Service-to-Service Calls

Instead of writing RestTemplate boilerplate, Feign lets you call other services like calling a local method:

// Enable Feign in main class
@SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication { ... }

// Define a Feign Client interface
@FeignClient(name = "USER-SERVICE")
public interface UserClient {

    @GetMapping("/api/users/{id}")
    User getUserById(@PathVariable Long id);
}

// Use it in Order Service — just inject and call!
@RestController
public class OrderController {

    @Autowired
    private UserClient userClient;

    @GetMapping("/orders/{id}")
    public Order getOrder(@PathVariable Long id) {
        User user = userClient.getUserById(id);  // Calls User Service via Eureka!
        // ...
    }
}
Key Point
@FeignClient(name = "USER-SERVICE") — the name must match the spring.application.name of the target service registered in Eureka. Feign uses Eureka to resolve the actual address.

9. Circuit Breaker Pattern

The Problem

If Order Service calls Payment Service, and Payment Service is down, Order Service keeps trying and waiting. Meanwhile, requests pile up, Order Service runs out of resources, and crashes too. Now User Service calls Order Service which is also down — cascading failure. One service going down takes everything down.

The Solution: Circuit Breaker

Like an electrical circuit breaker — when it detects too many failures, it "opens" the circuit and stops calling the failing service. Instead, it returns a fallback response immediately.

Three States

StateWhat HappensWhen It Transitions
CLOSED (Normal)All requests pass through normallyMoves to OPEN when failure threshold is reached
OPEN (Failing)All requests immediately return fallback response. No calls to failing service.After a timeout period, moves to HALF-OPEN
HALF-OPEN (Testing)Allows a few test requests through. If they succeed, back to CLOSED. If they fail, back to OPEN.Success → CLOSED, Failure → OPEN
Circuit Breaker Flow

  CLOSED (all good)
     │
     │ failures exceed threshold (e.g., 5 failures in a row)
     ▼
  OPEN (stop calling, return fallback)
     │
     │ wait timeout (e.g., 30 seconds)
     ▼
  HALF-OPEN (try a few requests)
     │
     ├── success → back to CLOSED ✓
     └── failure → back to OPEN ✗

Resilience4j Example (Know the Concept)

@RestController
public class OrderController {

    @GetMapping("/orders/{id}")
    @CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
    public String getOrder(@PathVariable Long id) {
        // calls Payment Service — may fail
        return restTemplate.getForObject("http://PAYMENT-SERVICE/pay/" + id, String.class);
    }

    // Fallback — runs when circuit is OPEN
    public String paymentFallback(Long id, Throwable t) {
        return "Payment service is currently unavailable. Please try later.";
    }
}
Exam Tip
The three states (Closed → Open → Half-Open) are the most asked circuit breaker question. Remember: CLOSED = normal (counterintuitive — think of it like an electrical circuit where closed = current flows).

10. Docker & Containers (Brief)

Docker packages your microservice + all its dependencies into a container — a lightweight, portable unit that runs the same everywhere.

Key Concepts

ConceptWhat It Is
Docker ImageA blueprint/template — like a class in Java. Read-only.
Docker ContainerA running instance of an image — like an object. You can have multiple containers from one image.
DockerfileA text file with instructions to build an image.
Docker HubPublic registry for images (like GitHub for Docker images).
Docker ComposeTool to run multiple containers together (e.g., all microservices + databases).

Dockerfile Basics

# Dockerfile for a Spring Boot microservice
FROM openjdk:17-jdk-slim
COPY target/user-service.0.0.1.jar app.jar
EXPOSE 8081
ENTRYPOINT ["java", "-jar", "app.jar"]

Common Docker Commands

# Build an image from Dockerfile
docker build -t user-service .

# Run a container from the image
docker run -p 8081:8081 user-service

# List running containers
docker ps

# Stop a container
docker stop <container-id>

# List images
docker images
Image vs Container — Exam favorite
Image = blueprint (like a Java class). Immutable, stored on disk.
Container = running instance (like a Java object). Has its own state, can be started/stopped.

11. Microservices Design Patterns

Database Per Service

Each microservice has its own database. Order Service uses its own Order DB, User Service uses User DB. They never access each other's database directly — only through APIs.

Why: Loose coupling, independent deployment, each service can choose its own database type (SQL, NoSQL).

Saga Pattern (Distributed Transactions)

In monolith, you have one database transaction. In microservices, an "order" might involve Order Service, Payment Service, and Inventory Service — each with its own DB. How do you keep them consistent?

Saga = a sequence of local transactions. If one step fails, compensating transactions undo the previous steps.

Saga Example: Place Order
  1. Order Service → Create order (PENDING)
  2. Payment Service → Charge customer
  3. Inventory Service → Reserve stock
  4. Order Service → Update order (CONFIRMED)
If Payment fails at step 2 → Order Service runs compensating transaction (cancel order).

Two types of Saga:

CQRS (Command Query Responsibility Segregation)

Separate the write model (commands: create, update, delete) from the read model (queries: get, search). Different databases or models for reads vs writes. Useful when read and write patterns are very different.

Event-Driven Architecture

Services communicate by publishing and subscribing to events. When Order Service creates an order, it publishes an "OrderCreated" event. Payment Service subscribes to this event and processes payment. Decouples services completely.

Exam Tip
Know what "Database per Service" means and why it's used. Saga pattern is asked as "How do you handle distributed transactions in microservices?" CQRS is rarely asked in detail — just know the full form and one-line definition.

12. Advantages vs Disadvantages

Advantages

AdvantageExplanation
Independent DeploymentDeploy one service without touching others
Independent ScalingScale only the services that need it
Technology FreedomEach service can use different languages, frameworks, databases
Fault IsolationOne service crashing doesn't take down the whole system
Faster DevelopmentSmall teams work on small services — faster iterations
Easy to UnderstandEach service is small and focused — easier to comprehend
ReusabilityServices can be reused across different applications

Disadvantages

DisadvantageExplanation
ComplexityDistributed system = harder to develop, deploy, and debug
Network LatencyServices communicate over network — slower than in-process calls
Data ConsistencyNo shared database — ensuring consistency across services is hard
Testing DifficultyIntegration testing across services is complex
Operational OverheadNeed monitoring, logging, deployment pipelines for EACH service
DebuggingA request goes through multiple services — tracing issues is harder
Exam Trap
Microservices are NOT always the answer. The exam may ask "What is a disadvantage of microservices?" — complexity and data consistency are the top answers. Don't fall for "microservices have no disadvantages."

13. Real-World Example: E-Commerce App

Let's see how a real e-commerce application would be split into microservices:

E-Commerce Microservices Architecture

  ┌─────────────────────────────────────────────┐
  │              API Gateway (:8080)             │
  └──────┬──────┬──────┬──────┬──────┬──────────┘
         │      │      │      │      │
    ┌────▼──┐ ┌─▼────┐ ┌▼─────┐ ┌───▼───┐ ┌────▼────────┐
    │ User  │ │Produc│ │Order │ │Payment│ │Notification │
    │Service│ │tServ.│ │Serv. │ │Service│ │  Service    │
    │ :8081 │ │:8082 │ │:8083 │ │ :8084 │ │   :8085     │
    └───┬───┘ └──┬───┘ └──┬───┘ └───┬───┘ └─────────────┘
        │        │        │        │
    ┌───▼───┐ ┌──▼───┐ ┌──▼───┐ ┌──▼────┐
    │UserDB │ │Prod  │ │Order │ │PayDB  │
    │(MySQL)│ │DB    │ │DB    │ │       │
    └───────┘ │(Mongo│ └──────┘ └───────┘
              │ DB)  │
              └──────┘
ServiceResponsibilityCommunicates With
User ServiceRegistration, login, profile managementAuth only — mostly independent
Product ServiceProduct catalog, search, inventoryOrder Service (stock check)
Order ServiceCreate/manage ordersUser Service, Product Service, Payment Service
Payment ServiceProcess payments, refundsOrder Service
Notification ServiceSend emails, SMS, push notificationsListens to events from all services

How a Customer Places an Order:

  1. Client sends request to API Gateway
  2. Gateway routes to Order Service
  3. Order Service calls User Service (via Feign) to validate user
  4. Order Service calls Product Service to check stock
  5. Order Service calls Payment Service to process payment
  6. Payment Service publishes "PaymentCompleted" event
  7. Notification Service listens to the event and sends confirmation email
  8. Order status updated to CONFIRMED
Notice the patterns
Steps 3-5 are synchronous (need immediate response). Steps 6-7 are asynchronous (event-driven, no waiting). The Notification Service uses a message queue — it doesn't need to respond to the Order Service.

14. Practice MCQs

Q1
Which architecture style breaks an application into small, independently deployable services?
  1. Monolithic
  2. Microservices
  3. Service-Oriented Architecture (SOA)
  4. Serverless
B) Microservices — each service is independently deployable and handles one business capability.
Q2
In a monolithic architecture, how is the application deployed?
  1. Each module is deployed separately
  2. As a single deployable unit
  3. Using Docker containers
  4. Through message queues
B) As a single deployable unit — monolith = one big deployment. Change anything, redeploy everything.
Q3
What is the primary role of an API Gateway in microservices?
  1. Store data for all services
  2. Act as a single entry point for all client requests
  3. Compile the source code
  4. Manage database connections
B) Act as a single entry point — API Gateway routes requests, handles auth, rate limiting, and load balancing.
Q4
Which Netflix component is used for Service Discovery in Spring Cloud?
  1. Zuul
  2. Hystrix
  3. Eureka
  4. Ribbon
C) Eureka — Netflix Eureka is the service registry where services register and discover each other. Zuul = gateway, Hystrix = circuit breaker, Ribbon = load balancer.
Q5
What are the three states of a Circuit Breaker?
  1. Start, Stop, Pause
  2. Closed, Open, Half-Open
  3. Active, Inactive, Pending
  4. Connected, Disconnected, Reconnecting
B) Closed, Open, Half-Open — Closed = normal flow, Open = stop calling failing service, Half-Open = testing if service recovered.
Q6
Which annotation is used to enable a Eureka Server?
  1. @EnableEurekaClient
  2. @EnableDiscoveryClient
  3. @EnableEurekaServer
  4. @EnableServiceRegistry
C) @EnableEurekaServer — placed on the main class of the Eureka registry application. @EnableEurekaClient goes on the microservices that register with it.
Q7
In microservices, how do services typically communicate synchronously?
  1. Shared database
  2. REST APIs over HTTP
  3. File transfer
  4. Shared memory
B) REST APIs over HTTP — synchronous communication in microservices uses lightweight REST/HTTP calls. Shared database violates the "database per service" principle.
Q8
What is the "Database per Service" pattern?
  1. All services share one large database
  2. Each service has its own private database
  3. Only the API Gateway has a database
  4. Databases are not used in microservices
B) Each service has its own private database — this ensures loose coupling. Services access other service's data only through APIs, never by directly querying another service's database.
Q9
What is a Docker container?
  1. A virtual machine
  2. A running instance of a Docker image
  3. A type of database
  4. A programming language
B) A running instance of a Docker image — Image = blueprint (class), Container = running instance (object). A container is lightweight, not a full VM.
Q10
Which of the following is NOT a characteristic of microservices?
  1. Single responsibility
  2. Shared database across all services
  3. Independent deployment
  4. Fault isolation
B) Shared database — microservices use "database per service" pattern. Shared database creates tight coupling and defeats the purpose of microservices.
Q11
What problem does the Saga pattern solve?
  1. Service discovery
  2. Distributed transactions across microservices
  3. Load balancing
  4. API routing
B) Distributed transactions — Saga handles transactions that span multiple services by using a sequence of local transactions with compensating actions for rollback.
Q12
What does @FeignClient do in Spring Cloud?
  1. Creates a database connection
  2. Enables declarative REST client for service-to-service calls
  3. Configures the API Gateway
  4. Enables circuit breaker
B) Declarative REST client — @FeignClient creates a proxy that lets you call another microservice as if calling a local interface method. It uses Eureka to resolve the service address.
Q13
In Circuit Breaker pattern, what does the "CLOSED" state mean?
  1. The service is down
  2. Requests are blocked
  3. Everything is working normally — requests flow through
  4. The circuit breaker is disabled
C) Everything is working normally — CLOSED = circuit is complete, current (requests) flows through. Think of it like an electrical circuit. OPEN = circuit broken, no flow.
Q14
Which is a disadvantage of microservices architecture?
  1. Independent deployment
  2. Technology freedom
  3. Increased complexity of distributed systems
  4. Fault isolation
C) Increased complexity — distributed systems bring challenges: network latency, data consistency, debugging across services, operational overhead for each service.
Q15
Which type of communication is best for sending notification emails after an order?
  1. Synchronous REST call
  2. Direct database query
  3. Asynchronous messaging (message queue)
  4. gRPC
C) Asynchronous messaging — notifications don't need immediate response. Order Service publishes event, Notification Service picks it up from the queue and sends email. No waiting.
Q16
What is the difference between Docker image and Docker container?
  1. They are the same thing
  2. Image is a running process, container is a template
  3. Image is a read-only template, container is a running instance
  4. Container is stored in Docker Hub, image runs locally
C) Image = read-only template, Container = running instance — like Class vs Object in Java. You build an image, then run containers from it.
Q17
Why does the Eureka Server have register-with-eureka=false in its configuration?
  1. To disable Eureka
  2. Because the server should not register itself as a client
  3. To enable security
  4. To allow only one instance
B) The server should not register itself — Eureka Server IS the registry. It doesn't need to register with itself. Only client microservices register.
Q18
When should you choose monolithic architecture over microservices?
  1. When building a large-scale enterprise application
  2. When you need independent scaling of components
  3. When building a small application with a small team
  4. When different services need different technologies
C) Small application, small team — monolith is simpler to develop, deploy, and debug. Microservices add unnecessary complexity for small projects.