Module 1: Core Microservices Concepts
What are Microservices?
Answer:
Microservices is an architectural style where an application is built as a collection of small, independent services, each responsible for a specific business capability.
Each microservice:
- Has its own codebase
- Can be developed, deployed, and scaled independently
- Communicates with other services using lightweight protocols like REST, gRPC, or messaging
Example (real-world):
In an e-commerce application:
- Order Service → manages orders
- Payment Service → handles payments
- Inventory Service → manages stock
Each service can evolve independently without affecting others.
Key takeaway (for interviews):
Microservices improve scalability, agility, and fault isolation.
Difference between Monolithic and Microservices Architecture?
Answer:
| Feature | Monolithic | Microservices |
| Codebase | Single, tightly coupled | Multiple, loosely coupled |
| Deployment | One large unit | Independent per service |
| Scalability | Entire app scales | Only required services scale |
| Technology | Usually same stack | Polyglot (multiple stacks) |
| Fault isolation | Poor | Excellent |
Interview tip:
Monolithic is simpler to start, but microservices scale better for large, evolving systems.
When should you choose Microservices?
Answer:
Microservices are NOT always the default choice.
Choose microservices when:
- Application is large and complex
- Teams are multiple and independent
- High scalability is required
- Continuous delivery is needed
- Different modules evolve at different speeds
Avoid microservices when:
- Team size is small
- Application is simple
- Operational complexity is not justified
Interview-friendly line:
“Microservices add operational complexity, so they should be adopted only when the scale demands it.”
What are the key characteristics of Microservices?
Answer:
Key characteristics include:
- Single Responsibility
- Each service handles one business function
- Loose Coupling
- Services interact via APIs, not shared databases
- Independent Deployment
- One service failure should not bring down the entire system
- Decentralized Data Management
- Each service owns its database
- Fault Tolerance
- Failures are expected and handled gracefully
What are the challenges in Microservices?
Answer:
While powerful, microservices introduce challenges:
- Service-to-service communication
- Distributed debugging
- Data consistency
- Deployment complexity
- Monitoring & logging
How these are solved:
- API Gateway
- Centralized logging
- Distributed tracing
- Circuit breakers
- Containerization & orchestration
This question is often followed by:
“How do you solve these problems?”
(Which leads naturally to the next modules.)
What is Service Decomposition?
Answer:
Service decomposition is the process of breaking a monolithic application into microservices based on:
- Business capabilities
- Bounded contexts (DDD)
- Team ownership
Example:
Instead of one UserService, split into:
- Authentication Service
- Profile Service
- Notification Service
Golden rule:
Decompose by business logic, not by technical layers.
What is Bounded Context in Microservices?
Answer:
A bounded context defines a clear boundary where a specific domain model applies.
Within a bounded context:
- Terminology is consistent
- Data ownership is clear
- Services do not leak internal models
Example:
“User” in:
- Authentication context ≠ User in Order context
How do Microservices communicate with each other?
Answer:
Microservices communicate using:
- Synchronous
- REST APIs
- gRPC
- Asynchronous
- Kafka
- RabbitMQ
- Event-driven messaging
Best practice:
- Prefer asynchronous communication for scalability
- Use synchronous calls only when absolutely required
Why is Database-per-Service important?
Answer:
Each microservice must own its data to avoid tight coupling.
Benefits:
- Independent schema evolution
- Better fault isolation
- Enables independent scaling
Common mistake:
❌ Multiple services sharing the same database
Strong interview statement:
“Sharing a database defeats the purpose of microservices.”
⚙️ Module 2: Service Communication & APIs
How do Microservices communicate with each other?
Answer:
Microservices communicate using lightweight communication mechanisms instead of direct method calls.
There are two main types of communication:
- Synchronous communication
- Asynchronous communication
Each has its own use cases, advantages, and trade-offs.
What is Synchronous Communication in Microservices?
Answer:
In synchronous communication, one service sends a request and waits for a response before continuing.
Common technologies:
- REST (HTTP/JSON)
- gRPC (Protocol Buffers)
Example:
Order Service → calls → Payment Service
(wait for response)
Pros:
- Simple to implement
- Easy to understand
- Immediate response
Cons:
- Tight coupling
- Higher latency
- Failure propagation
Interview line:
“Synchronous calls increase coupling and reduce fault tolerance.”
What is Asynchronous Communication in Microservices?
Answer:
In asynchronous communication, services communicate via events or messages and do not wait for an immediate response.
Common technologies:
- Apache Kafka
- RabbitMQ
- AWS SQS
Example:
Order Service → publishes OrderCreated event
Payment Service → consumes the event
Pros:
- Loose coupling
- High scalability
- Better fault tolerance
Cons:
- Eventual consistency
- More complex debugging
Interview-friendly explanation:
“Asynchronous communication improves resilience at the cost of complexity.”
REST vs gRPC – which one is better?
Answer:
Both are valid, but serve different needs.
| Feature | REST | gRPC |
| Protocol | HTTP/JSON | HTTP/2 + Protobuf |
| Performance | Slower | Faster |
| Human readable | Yes | No |
| Browser support | Yes | Limited |
| Use case | Public APIs | Internal service calls |
When to use:
- REST → External APIs, frontend communication
- gRPC → Internal high-performance service communication
What is an API Gateway?
Answer:
An API Gateway is a single entry point for all client requests in a microservices system.
Responsibilities:
- Routing requests
- Authentication & authorization
- Rate limiting
- Request aggregation
- Logging & monitoring
Example:
Client → API Gateway → Order / Payment / Inventory Services
Strong interview statement:
“API Gateway hides internal microservice complexity from clients.”
Why is API Gateway required in Microservices?
Answer:
Without an API Gateway:
- Clients must know service locations
- Multiple network calls from frontend
- Security logic duplicated across services
With API Gateway:
- Centralized security
- Simplified client logic
- Better control & observability
What is Service Discovery?
Answer:
Service Discovery allows microservices to find each other dynamically without hardcoding IP addresses.
Types:
- Client-side discovery
- Server-side discovery
Tools:
- Eureka
- Consul
- Kubernetes DNS
What is Client-side Service Discovery?
Answer:
In client-side discovery:
- Client queries the service registry
- Chooses one instance
- Sends request directly
Example:
Order Service → Eureka → Payment Service instance
Drawback:
- Client becomes complex
- Load balancing logic inside client
What is Server-side Service Discovery?
Answer:
In server-side discovery:
- Client sends request to load balancer
- Load balancer queries registry
- Forwards request to service
Example:
Client → Load Balancer → Service Instance
Modern systems (Kubernetes) prefer server-side discovery.
What is Load Balancing in Microservices?
Answer:
Load balancing distributes traffic across multiple service instances to improve:
- Performance
- Availability
- Fault tolerance
Types:
- Client-side (Ribbon – deprecated)
- Server-side (Nginx, Kubernetes, AWS ALB)
What happens if one Microservice fails?
Answer:
In microservices, failure is expected, not exceptional.
Problems:
- Cascading failures
- Increased latency
- System downtime
Solutions:
- Timeouts
- Retries
- Circuit breakers
- Bulkheads
This leads directly to Resilience patterns.
What is a Circuit Breaker?
Answer:
A circuit breaker prevents repeated calls to a failing service.
States:
- Closed → calls allowed
- Open → calls blocked
- Half-open → test calls
Benefits:
- Prevents cascading failures
- Improves system stability
What is Retry Pattern?
Answer:
Retry pattern attempts a failed request again before giving up.
Best practices:
- Use limited retries
- Add exponential backoff
- Combine with circuit breaker
❌ Blind retries can make failures worse.
What is Timeout and why is it important?
Answer:
Timeout defines how long a service waits for a response.
Without timeouts:
- Threads block indefinitely
- System resources exhaust
Golden rule:
“Every remote call must have a timeout.”
What is Idempotency in Microservices?
Answer:
An operation is idempotent if multiple identical requests produce the same result.
Example:
- Payment request sent twice
- Charge happens only once
Why important:
- Network failures
- Retries
- Duplicate messages
📊 Module 3: Scalability & Resilience
What is scalability in software systems?
Answer:
Scalability is the system’s ability to handle increased load by adding resources. It ensures performance remains stable as traffic grows.
Q2. What are the types of scalability?
Answer:
- Vertical (scale-up): Add more CPU/RAM to a single node.
- Horizontal (scale-out): Add more nodes/instances to distribute load.
Q3. How does Spring Boot support horizontal scaling?
Answer:
Spring Boot apps are stateless by default, making them easy to replicate across multiple instances behind a load balancer.
Q4. What is statelessness and why is it important?
Answer:
Stateless apps don’t store session data on the server. This allows any instance to handle any request, enabling horizontal scaling.
Q5. How do you scale Spring Boot apps in Kubernetes?
Answer:
Use Deployment with replicas:
spec:
replicas: 3
Kubernetes handles load balancing and health checks.
Q6. What is a load balancer?
Answer:
A component that distributes incoming traffic across multiple instances to ensure availability and performance.
Q7. How do you handle shared state in scalable systems?
Answer:
Use external stores like Redis, databases, or distributed caches to manage shared state.
📌 Section 2: Resilience Patterns
Q8. What is resilience in microservices?
Answer:
Resilience is the system’s ability to recover from failures and continue functioning with minimal disruption.
Q9. What is a circuit breaker?
Answer:
A pattern that prevents repeated calls to a failing service. It “opens” after failures and “closes” after recovery.
Q10. How do you implement circuit breakers in Spring Boot?
Answer:
Use Resilience4j:
@CircuitBreaker(name = “inventoryService”, fallbackMethod = “fallback”)
public String getInventory() {
return restTemplate.getForObject(“/inventory”, String.class);
}
Q11. What is a fallback method?
Answer:
A method that’s called when the main method fails due to circuit breaker or timeout.
Q12. What is a retry pattern?
Answer:
Automatically reattempt failed operations with delay and limits.
Q13. How do you implement retries in Spring Boot?
@Retry(name = “paymentService”, maxAttempts = 3)
public String processPayment() { … }
Q14. What is a bulkhead pattern?
Answer:
Isolates components/resources to prevent failure in one part from affecting others.
Q15. What is timeout handling?
Answer:
Setting a maximum time for operations to complete. Prevents hanging requests.
Q16. How do you configure timeouts in RestTemplate?
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(3000);
factory.setReadTimeout(3000);
📌 Section 3: Observability for Resilience
Q17. How does observability help resilience?
Answer:
It enables early detection of failures via metrics, logs, and traces. Helps in root cause analysis and alerting.
Q18. What metrics indicate resilience issues?
- High error rates (5xx)
- Increased latency
- Frequent retries
- Circuit breaker open rate
Q19. How do you monitor circuit breaker status?
Answer:
Expose metrics via Micrometer:
registry.gauge(“resilience4j.circuitbreaker.state”, circuitBreaker, cb -> cb.getState().ordinal());
Q20. What is distributed tracing?
Answer:
Tracks requests across services. Tools: Spring Cloud Sleuth + Zipkin or OpenTelemetry.
📌 Section 4: Real-World Scenarios
Q21. Scenario: Service A depends on Service B, which is down. What happens?
Answer:
Without resilience: cascading failure.
With circuit breaker: fallback response or error message.
Q22. Scenario: Sudden traffic spike. How do you handle it?
Answer:
- Auto-scale instances
- Use rate limiting
- Offload heavy tasks to queues
Q23. Scenario: DB latency increases. What do you do?
Answer:
- Add caching
- Optimize queries
- Monitor with /actuator/metrics
Q24. Scenario: One service hogs thread pool. Impact?
Answer:
Other services slow down. Use bulkhead to isolate thread pools.
Q25. Scenario: Retry storm during outage. How to prevent?
Answer:
Use exponential backoff + circuit breaker to avoid overload.
📌 Section 5: Tools & Best Practices
Q26. What is Resilience4j?
Answer:
A lightweight fault tolerance library for Java. Supports circuit breaker, retry, rate limiter, bulkhead.
Q27. What is Hystrix?
Answer:
Legacy Netflix library for resilience. Deprecated in favor of Resilience4j.
Q28. What is rate limiting?
Answer:
Restricts number of requests per time unit. Prevents abuse and overload.
Q29. How do you implement rate limiting in Spring Boot?
Use Resilience4j:
@RateLimiter(name = “apiLimiter”)
public String getData() { … }
Q30. What are best practices for resilience?
- Fail fast
- Use timeouts
- Add fallbacks
- Monitor everything
- Test failure scenarios
- Isolate resources
🗄️ Module 4: Data Management
🟣 Module: Data Management – 30 Interview Questions & Answers
📌 Section 1: Data Access & Persistence
Q1. What is Spring Data JPA?
Answer:
A Spring abstraction over JPA that simplifies data access using repository interfaces.
public interface UserRepository extends JpaRepository<User, Long> {}
Q2. What is the difference between JPA and Hibernate?
Answer:
- JPA is a specification.
- Hibernate is a popular implementation of JPA.
Q3. What is the role of EntityManager?
Answer:
It manages persistence operations like persist(), merge(), remove(), and find().
Q4. How do you define an entity in Spring Boot?
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
}
Q5. What is the difference between @OneToMany and @ManyToOne?
Answer:
@OneToMany: One entity has many related entities.@ManyToOne: Many entities refer to one parent.
Q6. How do you configure a database in Spring Boot?
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=pass
Q7. What is the default database in Spring Boot?
Answer:
H2 in-memory database (used for quick testing).
📌 Section 2: Querying & Transactions
Q8. How do you write custom queries in Spring Data JPA?
@Query("SELECT u FROM User u WHERE u.name = :name")
List<User> findByName(@Param("name") String name);
Q9. What is the difference between findByName() and @Query?
Answer:
findByName()→ Derived query from method name.@Query→ Custom JPQL or native SQL.
Q10. How do you enable transactions in Spring Boot?
Use @Transactional:
@Transactional
public void updateUser(User user) { ... }
Q11. What is the default transaction behavior?
Answer:
Spring uses read committed isolation level and rollback on runtime exceptions.
Q12. How do you handle rollback manually?
@Transactional(rollbackFor = CustomException.class)
Q13. What is optimistic vs pessimistic locking?
Answer:
- Optimistic: Uses versioning; assumes no conflict.
- Pessimistic: Locks rows to prevent concurrent updates.
Q14. How do you implement optimistic locking?
@Version
private Integer version;
📌 Section 3: Pagination, Sorting & DTOs
Q15. How do you paginate results in Spring Data JPA?
Page<User> users = userRepo.findAll(PageRequest.of(0, 10));
Q16. How do you sort results?
List<User> users = userRepo.findAll(Sort.by("name").descending());
Q17. What is a DTO and why use it?
Answer:
A Data Transfer Object carries only required fields between layers. Improves performance and security.
Q18. How do you map an entity to a DTO?
Use ModelMapper, MapStruct, or manual mapping:
UserDTO dto = new UserDTO(user.getName(), user.getEmail());
Q19. How do you project partial fields in Spring Data?
interface UserView {
String getName();
String getEmail();
}
List<UserView> findBy();
📌 Section 4: Caching & Performance
Q20. How do you enable caching in Spring Boot?
@EnableCaching
@Cacheable("users")
public User getUser(Long id) { ... }
Q21. What is the difference between @Cacheable, @CachePut, and @CacheEvict?
@Cacheable: Caches method result.@CachePut: Updates cache.@CacheEvict: Removes cache entry.
Q22. What cache providers are supported?
Answer:
EhCache, Caffeine, Redis, Hazelcast, JCache.
Q23. How do you monitor cache performance?
Use /actuator/metrics/cache.* endpoints.
Q24. What is lazy loading vs eager loading?
- Lazy: Loads related entities on access.
- Eager: Loads related entities immediately.
Q25. How do you avoid N+1 query problem?
Use @EntityGraph or JOIN FETCH in queries.
📌 Section 5: Real-World Scenarios & Best Practices
Q26. Scenario: You need to fetch users with orders. How?
@Query("SELECT u FROM User u JOIN FETCH u.orders")
Q27. Scenario: You need to update user and log audit. How?
Use @Transactional and save audit entity in same transaction.
Q28. Scenario: You need to expose only selected fields. How?
Use DTOs or projections.
Q29. Scenario: You need to cache expensive DB calls. How?
Use @Cacheable with TTL (time-to-live) configuration.
Q30. What are best practices for data management?
- Use DTOs for APIs
- Avoid exposing entities directly
- Use pagination for large datasets
- Monitor query performance
- Use caching wisely
- Handle transactions carefully
- Avoid lazy loading in APIs
👉 Want me to design a diagram for JPA architecture or caching flow next? It’ll visually anchor this chapter.
🔒 Module 5: Security & Observability
Q1. Why is security more complex in Microservices than Monolith?
Answer:
In a monolithic application, security is usually centralized at one entry point.
In microservices, security becomes complex because:
- There are multiple services
- Each service runs independently
- Services communicate over the network
- Every service becomes a potential attack surface
In simple terms:
More services = more doors = more security challenges.
Interview Point:
“Security must be applied consistently across all microservices.”
Q2. What are the main security challenges in Microservices?
Answer:
Key security challenges include:
- Authentication across services
- Authorization between services
- Secure service-to-service communication
- Token propagation
- Preventing unauthorized internal access
Common risks:
- Token leakage
- Over-privileged services
- Man-in-the-middle attacks
- Insecure internal APIs
Q3. How is authentication handled in Microservices?
Answer:
Authentication is usually handled using centralized identity providers.
Common approaches:
- OAuth 2.0
- OpenID Connect (OIDC)
- JWT (JSON Web Tokens)
Typical flow:
- Client authenticates with Auth Server
- Auth Server issues a token (JWT)
- Client sends token to API Gateway
- API Gateway validates token
- Token is forwarded to downstream services
Q4. Why JWT is widely used in Microservices?
Answer:
JWT is popular because it is:
- Stateless
- Self-contained
- Easy to validate
- Suitable for distributed systems
JWT contains:
- User identity
- Roles / permissions
- Expiry time
- Signature
Interview Line:
“JWT avoids shared session storage, which fits microservices well.”
Q5. Where should authentication be enforced: API Gateway or Service?
Answer:
Both, but with different responsibilities.
API Gateway:
- First line of defense
- Token validation
- Request rejection
Microservices:
- Authorization checks
- Role-based access control
- Business-level security
Best Practice:
Gateway authenticates, services authorize.
Q6. What is service-to-service authentication?
Answer:
Service-to-service authentication ensures that only trusted services can call each other.
Common methods:
- mTLS (Mutual TLS)
- OAuth2 Client Credentials
- Service Mesh identity (Istio, Linkerd)
Example:
Order Service → Payment Service
Payment Service verifies the caller is Order Service.
Q7. What is mTLS and why is it important?
Answer:
mTLS (Mutual TLS) means:
- Both client and server authenticate each other
- Certificates are exchanged in both directions
Benefits:
- Strong identity verification
- Encrypted communication
- Prevents impersonation
Used in:
- Kubernetes
- Service Mesh (Istio)
Q8. What is Authorization and how is it handled?
Answer:
Authorization decides what an authenticated user or service can do.
Common techniques:
- Role-Based Access Control (RBAC)
- Scope-based access
- Policy-based access (OPA)
Example:
- USER → read orders
- ADMIN → create/delete orders
Q9. What is Zero Trust Security in Microservices?
Answer:
Zero Trust means:
“Never trust, always verify.”
Principles:
- No implicit trust (even internal traffic)
- Authenticate every request
- Authorize every action
- Encrypt all communication
Why important:
Microservices often run in shared environments like Kubernetes.
Q10. How to secure sensitive data in Microservices?
Answer:
Sensitive data must be protected:
- In transit → HTTPS / TLS
- At rest → Encryption
- In config → Secrets management
Tools:
- Kubernetes Secrets
- HashiCorp Vault
- AWS Secrets Manager
📊 PART 2: MICROSERVICES OBSERVABILITY
Q11. What is Observability in Microservices?
Answer:
Observability is the ability to understand the internal state of a system using external outputs.
It answers:
- What is happening?
- Why is it happening?
- Where is it happening?
Observability pillars:
- Logs
- Metrics
- Traces
Q12. Why is observability critical in Microservices?
Answer:
In microservices:
- Requests flow across multiple services
- Failures are distributed
- Debugging is hard
Without observability:
- Issues are invisible
- Root cause is unclear
- MTTR (Mean Time To Recovery) increases
Q13. What are Logs in Microservices?
Answer:
Logs are textual records of events happening in services.
Best practices:
- Structured logs (JSON)
- Include correlation IDs
- Centralized logging
Tools:
- ELK Stack (Elasticsearch, Logstash, Kibana)
- OpenSearch
- Loki
Q14. What are Metrics?
Answer:
Metrics are numerical measurements over time.
Examples:
- Request count
- Error rate
- Latency
- CPU / memory usage
Tools:
- Prometheus
- Grafana
- Micrometer (Spring Boot)
Q15. What are Distributed Traces?
Answer:
Distributed tracing tracks a single request across multiple services.
Each request has:
- Trace ID
- Span IDs
Benefits:
- Visualize request flow
- Identify slow services
- Debug latency issues
Tools:
- Zipkin
- Jaeger
- OpenTelemetry
Q16. What is a Correlation ID?
Answer:
A Correlation ID is a unique identifier attached to a request.
Used for:
- Linking logs
- Traces across services
- End-to-end debugging
Example:
Same request ID appears in Order, Payment, Inventory logs.
Q17. How does Spring Boot support Observability?
Answer:
Spring Boot provides built-in observability via:
- Spring Boot Actuator
- Micrometer
- OpenTelemetry integration
Common endpoints:
- /actuator/health
- /actuator/metrics
- /actuator/prometheus
Q18. What is Health Check and why is it important?
Answer:
Health checks determine if a service is:
- UP
- DOWN
- DEGRADED
Used by:
- Kubernetes
- Load balancers
- Monitoring systems
Types:
- Liveness probe
- Readiness probe
Q19. What is Alerting?
Answer:
Alerting notifies teams when something goes wrong.
Examples:
- High error rate
- Service down
- Latency spike
Tools:
- Prometheus Alertmanager
- Grafana Alerts
- CloudWatch
Q20. How Security & Observability work together?
Answer:
Security and observability are tightly linked:
- Logs help detect attacks
- Metrics show unusual behavior
- Traces identify suspicious flows
Example:
- Spike in failed auth requests → possible attack
- Unusual traffic → misconfiguration or abuse
Project Architecture (VERY IMPORTANT)
Client (Browser / Postman)
↓
OAuth2 Provider (Google)
↓
Spring Boot App
├── OAuth2 Login
├── JWT Generation
├── JWT Filter
├── RBAC
└── Protected APIs
🎯 Interview line:
“OAuth2 handles authentication, JWT handles API security.”
📦 2. Dependencies (Spring Boot 3)
spring-boot-starter-security
spring-boot-starter-web
spring-boot-starter-oauth2-client
spring-boot-starter-data-jpa
jjwt-api
jjwt-impl
jjwt-jackson
👤 3. User & Role Model (Foundation)
Role Entity
@Entity
public class Role {
@Id @GeneratedValue
private Long id;
private String name; // ROLE_USER, ROLE_ADMIN
}
User Entity
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String email;
@ManyToMany(fetch = FetchType.EAGER)
private Set<Role> roles;
}
🎯 Interview point:
“Roles are eagerly fetched because authorization happens on every request.”
🌐 4. OAuth2 Login Configuration
application.yml
spring:
security:
oauth2:
client:
registration:
google:
client-id: xxx
client-secret: xxx
scope:
– profile
🔑 5. OAuth2 Login Flow (Explain Slowly)
- User clicks Login with Google
- Redirected to Google
- User authenticates
- Google returns user info
- Spring Security creates OAuth2User
- Our app processes user & roles
- Our app generates JWT
🎯 Interview line:
“OAuth2 authenticates the user, but authorization is handled by our application.”
🔄 6. Custom OAuth2 Success Handler (KEY PART)
This is where OAuth2 → JWT conversion happens.
@Component
public class OAuth2SuccessHandler
extends SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException {
OAuth2User oauthUser = (OAuth2User) authentication.getPrincipal();
String email = oauthUser.getAttribute(“email”);
// create / load user
User user = userService.processOAuthUser(email);
String jwt = jwtUtil.generateToken(user);
response.sendRedirect(“/login-success?token=” + jwt);
}
}
🎯 Interview gold:
“OAuth2SuccessHandler is the bridge between OAuth2 and JWT.”
🪪 7. JWT Utility (Access Token)
public String generateToken(User user) {
return Jwts.builder()
.setSubject(user.getEmail())
.claim(“roles”, user.getRoles())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 15 * 60 * 1000))
.signWith(key)
.compact();
}
⚠️ Do NOT store sensitive data in JWT.
🔍 8. JWT Filter (API Protection)
@Component
public class JwtFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(…) {
String header = request.getHeader(“Authorization”);
if (header != null && header.startsWith(“Bearer “)) {
String token = header.substring(7);
String username = jwtUtil.extractUsername(token);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
}
filterChain.doFilter(request, response);
}
}
🎯 Interview line:
“JWT filter populates SecurityContext for authorization.”
🔐 9. Security Configuration (Spring Boot 3 Style)
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers(“/”, “/login**”).permitAll()
.requestMatchers(“/admin/**”).hasRole(“ADMIN”)
.anyRequest().authenticated()
)
.oauth2Login(oauth ->
oauth.successHandler(oAuth2SuccessHandler)
)
.sessionManagement(sess ->
sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
}
🎯 Interview line:
“Session is disabled because JWT is stateless.”
🧑⚖️ 10. Role-Based API Example
@PreAuthorize(“hasRole(‘ADMIN’)”)
@GetMapping(“/admin/dashboard”)
public String adminData() {
return “Admin only data”;
}
Enable method security:
@EnableMethodSecurity
🚪 11. Logout Strategy (Important)
- No session to invalidate
- JWT expires naturally
- Optional: revoke refresh token (if used)
🎯 Interview line:
“Logout in JWT means token expiration or revocation.”
🧠 12. Real-World Interview Scenarios
Q: Why not rely only on OAuth2 tokens?
A:
OAuth2 tokens are provider-specific.
We need application-controlled JWT for internal APIs.
Q: Why not store JWT in DB?
A:
It breaks stateless design and scalability.
Q: Can OAuth2 & JWT coexist?
A:
Yes — OAuth2 for login, JWT for authorization
Advanced Spring Boot & Microservices Security
(Senior / Architect Level Interview Scenarios)
Scenario 1: JWT Token Is Stolen – What Do You Do?
Interview Question:
“If a JWT token is compromised, how do you prevent misuse?”
Answer (Senior-level):
JWT is stateless, so it cannot be revoked easily.
Hence, we use defensive strategies, not brute-force revocation.
Best practices:
- Short-lived access tokens (5–15 mins)
- Refresh tokens stored securely
- Token rotation on refresh
- Logout → invalidate refresh token
- Monitor abnormal token usage
Interview power line:
“JWT security is achieved by minimizing damage, not by revocation.”
Scenario 2: Internal Microservice Calls Are Being Forged
Question:
“How do you ensure only trusted microservices call each other?”
Answer:
Never trust internal traffic blindly.
Secure approaches:
- mTLS (mutual TLS)
- OAuth2 Client Credentials
- Service Mesh identity
- JWT with service accounts
Best enterprise answer:
“We use mTLS or OAuth2 client credentials for service-to-service authentication.”
Scenario 3: Role Explosion Problem
Question:
“How do you manage authorization when roles grow too large?”
Answer:
Avoid role explosion by:
- Using scopes
- Using policy-based authorization
- Using OPA (Open Policy Agent)
Example:
Instead of:
ROLE_ORDER_CREATE
ROLE_ORDER_CANCEL
Use:
SCOPE_ORDER_WRITE
Interview line:
“Roles define identity, policies define permissions.”
Scenario 4: Zero Trust Security Model
Question:
“What is Zero Trust in microservices?”
Answer:
Zero Trust means:
- No service is trusted by default
- Every request is authenticated
- Every request is authorized
- Every request is encrypted
Why critical:
- Kubernetes clusters are shared
- Internal attacks are possible
- Network perimeter is gone
Interview line:
“Zero Trust assumes breach by default.”
Scenario 5: OAuth2 Token Validation Bottleneck
Question:
“Validating OAuth2 tokens at every service causes latency. How do you optimize?”
Answer:
Best solutions:
- Use JWT instead of opaque tokens
- Validate locally using public keys (JWKS)
- Cache token introspection responses
Enterprise setup:
- Auth Server publishes public keys
- Services validate tokens locally
Scenario 6: Multi-Tenant Security
Question:
“How do you secure multi-tenant microservices?”
Answer:
Approaches:
- Tenant ID in JWT
- Tenant-based authorization
- Row-level security
- Separate schemas or DBs
Interview line:
“Authentication is global, authorization is tenant-aware.”
Microservices Security with API Gateway & Service Mesh
1. Why API Gateway Is Mandatory for Security
Interview Question:
“Why can’t clients call microservices directly?”
Answer:
Direct access:
- Exposes internal APIs
- Duplicates security logic
- Makes versioning hard
API Gateway provides:
- Central authentication
- Rate limiting
- Request validation
- DDoS protection
Interview line:
“API Gateway is the first security boundary.”
2. Authentication vs Authorization (Gateway + Services)
Best Practice:
- API Gateway → Authentication
- Microservices → Authorization
Why?
- Gateway validates token once
- Services enforce business rules
Senior answer:
“Gateway authenticates identities, services authorize actions.”
3. API Gateway + JWT Flow (Real World)
Flow:
- Client authenticates
- JWT issued
- Client sends JWT to Gateway
- Gateway validates JWT
- Gateway forwards request
- Services trust JWT claims
Benefits:
- Reduced duplication
- Better performance
- Consistent security
4. Rate Limiting & Abuse Protection
Question:
“How do you protect APIs from abuse?”
Answer:
- Rate limiting at gateway
- IP throttling
- Token-based quotas
Tools:
- Spring Cloud Gateway
- Kong
- NGINX
- AWS API Gateway
5. What Is a Service Mesh?
Answer:
A service mesh is an infrastructure layer that handles:
- Security
- Traffic management
- Observability
Without code changes.
Popular meshes:
- Istio
- Linkerd
6. How Service Mesh Secures Microservices
Security features:
- Automatic mTLS
- Service identity
- Certificate rotation
- Zero Trust by default
Interview line:
“Service mesh moves security out of application code.”
7. API Gateway vs Service Mesh (Important)
| API Gateway | Service Mesh |
| North-south traffic | East-west traffic |
| Client → services | Service → service |
| Entry point | Internal communication |
| Required | Optional (but powerful) |
Enterprise answer:
“Gateway + Service Mesh together provide full security coverage.”
8. Observability Integration (Security + Tracing)
Why important:
- Detect attacks
- Identify suspicious patterns
- Trace malicious requests
Tools:
- OpenTelemetry
- Prometheus
- Grafana
- Jaeger
Example:
Spike in failed auth → security alert.
Module 6: CI/CD & DevOps
Q10. How do you implement CI/CD in Microservices?
- Answer: Each service has its own pipeline:
- Build → Test → Deploy independently.
- Use container registries (Docker Hub, ECR).
- Deploy via Kubernetes with Helm charts.
- Benefit: Faster releases, isolated rollbacks.
🧠 Module 7: Advanced & Tricky Questions
- Q11. What is Bounded Context in Microservices?
- From Domain-Driven Design (DDD). Each service defines its own business boundary.
- Q12. What are challenges of Microservices?
- Complexity in monitoring, debugging, and data consistency.
- Q13. How do you decide service boundaries?
- Based on business capabilities, not technical layers.