Java Backend Interview Preparation

Spring Boot Interview Preparation

Complete source content converted into a readable HTML study guide. Tables are recreated as real HTML tables so they remain searchable, selectable, responsive and easy to read.

Spring Framework

Spring is a powerful open-source framework for building Java applications. It simplifies Java enterprise development by handling lots of heavy lifting (like managing objects, database connections, transactions, etc.).

Key Goals:

Make Java programming easier.
Promote good practices like Dependency Injection (DI) and Aspect-Oriented Programming (AOP).
Provide a lightweight alternative to Java EE (J2EE) applications.

Bean

In Spring, a Bean is just a normal Java object (POJO) that is managed by Spring.Bean = an object registered in the Spring container.

Ways to define a Bean:

Using @Component Annotation:
Using Java Configuration:
Using XML Configuration (older way):

ApplicationContext

The ApplicationContext is the Spring Container that:

Creates Beans
Wires them together
Manages their life cycle
Provides utilities (like internationalization, events, etc.)

1.3.1 There are different types of ApplicationContext

ClassPathXmlApplicationContext
AnnotationConfigApplicationContext
WebApplicationContext (for Spring MVC)

Core Concepts of Spring

1.4.1 Dependency Injection (DI):

Objects do not create their dependencies.
Dependencies are injected (provided) by the Spring container.
Promotes loose coupling.

1.4.2 Aspect-Oriented Programming (AOP):

Separate cross-cutting concerns like logging, security, transactions.
You don't mix these concerns into your business logic code.
Sometimes you need to apply common behavior across different parts of an app (e.g., logging, security checks, transactions).
Without AOP: You would duplicate this logic in multiple classes.
With AOP: You define it once and apply it where needed automatically.
Embedded document image

Embedded document image

Aspect: A module that encapsulates cross-cutting logic.

Advice: The action taken at a join point (@Before, @After, etc.).

Join Point: A point during execution (e.g., method call).

Pointcut: A predicate that matches join points.

@Aspect → Marks this class as an aspect.
@Before("execution(...)") → Runs before matched method executes.
@After("execution(...)") → Runs after matched method completes (even if it throws an exception).
"execution(* com.example.service.*.*(..))" → Pointcut expression: match all methods in all classes under com.example.service.

1.4.3 Spring Container:

The heart of Spring.
Manages the life cycle and configuration of your application objects (called Beans).
Uses configuration files (XML) or Java Annotations (@Component, @Service, etc.).

1.4.4 Important Modules in Spring

Spring is not just one thing; it's a collection of modules.

Embedded document image

How Spring Works (Internally)?

Create Objects (Beans) and their dependencies.
Configure them (either via XML or Annotations).
Spring Container reads this configuration.
Container Instantiates the objects.
Container Injects Dependencies.
Application Runs with fully ready Beans.

Containers like BeanFactory and ApplicationContext manage all this.

Advantages of Spring

Lightweight: You don't have to write too much code.
Flexible: You can pick only the parts you need.
Loose Coupling: Thanks to Dependency Injection.
Easy Integration: Works well with other frameworks (Hibernate, JPA, etc.).
Powerful Web Development: Using Spring MVC and Spring Boot.

Ways to Configure Spring

XML Configuration:
Annotation-Based Configuration:
Java-based Configuration (using @Configuration and @Bean):

SpringBoot

Spring Boot is a framework designed to simplify the development of Java applications, particularly those built with the Spring Framework.

It provides:

Auto-configuration: Automatically configures your application based on the dependencies in the classpath.
Standalone applications: You can run Spring Boot applications with a simple main() method.
Embedded servers: No need to deploy WAR files—Spring Boot includes Tomcat, Jetty, or Undertow as embedded web servers.
Production-ready features: Like health checks, metrics, and externalized configuration.

Core Spring Boot Annotations

AnnotationDescription
@SpringBootApplicationCombines @Configuration, @EnableAutoConfiguration, and @ComponentScan
@EnableAutoConfigurationEnables Spring Boot’s auto-configuration mechanism
@ComponentScanScans the package for Spring components (@Component, @Service, etc.)
@ConfigurationMarks a class as a source of bean definitions
@BeanDeclares a bean manually inside a @Configuration class

How does Spring Boot auto-configuration work?

Uses @EnableAutoConfiguration and classpath scanning.
Reads spring.factories to auto-configure beans conditionally.
Example: If DataSource class is found, it configures a datasource.
Can override with @ConditionalOnMissingBean, custom @Configuration.

Component Stereotypes

AnnotationDescription
@ComponentGeneric Spring-managed component
@ServiceMarks a class as a service layer component
@RepositoryMarks a class as a DAO/repository component
@ControllerMarks a class as a web controller
@RestControllerCombines @Controller + @ResponseBody

Dependency Injection

AnnotationDescription
@AutowiredInjects a dependency by type
@QualifierUsed with @Autowired to resolve ambiguity
@ValueInjects values from application properties

@Qualifier Common Scenarios for @Qualifier

ScenarioWhy Use @Qualifier?
Multiple @Service or @Component of same interfaceTo inject a specific one
Multiple @Bean definitionsTo differentiate them
Multiple implementations of repository or strategy patternFor flexibility and testing
When integrating third-party APIsInject appropriate handler

@Qualifier is used to resolve ambiguity when multiple beans of the same type are present.

Web & REST Annotations

AnnotationDescription
@RequestMappingMaps HTTP requests to handler methods/classes
@GetMappingShortcut for @RequestMapping(method = GET)
@PostMappingShortcut for @RequestMapping(method = POST)
@PutMappingShortcut for @RequestMapping(method = PUT)
@DeleteMappingShortcut for @RequestMapping(method = DELETE)
@PathVariableBinds URL path variables to method parameters
@RequestParamBinds request parameters (query strings)
@RequestBodyBinds request body to a method parameter
@ResponseBodyReturns object data as response body (JSON, etc.)
@CrossOriginEnables CORS for controller/method

Persistence (Spring Data JPA)

AnnotationDescription
@EntityMarks a class as a JPA entity
@TableMaps the entity to a database table
@IdMarks the primary key
@GeneratedValueSpecifies auto-generation strategy for ID
@ColumnMaps a field to a table column
@RepositoryMarks the interface as a Spring Data repository
@QueryCustom JPQL/native SQL query

Validation (JSR-303)

AnnotationDescription
@ValidTriggers validation on method arguments
@NotNullField must not be null
@NotBlankField must not be null or empty (String)
@Min, @MaxSpecifies numeric constraints
@SizeSpecifies size limits for collections or strings

Spring AOP

AnnotationDescription
@AspectDeclares a class as an AOP aspect
@BeforeRuns before the matched method execution
@AfterRuns after the method execution
@AfterReturningRuns after a method returns successfully
@AfterThrowingRuns if method throws an exception
@AroundSurrounds method execution (pre & post)

Test Annotations (Spring Boot Test)

AnnotationDescription
@SpringBootTestLoads full Spring Boot context for integration tests
@WebMvcTestLoads only web layer (controllers)
@DataJpaTestLoads JPA components only (repository layer)
@MockBeanAdds mock of a bean to Spring context
@TestConfigurationCustom configuration class for tests

Spring Boot Runners

RunnerInterfacePurposeMethod to ImplementParameter TypeUse Case
CommandLineRunnerorg.springframework.boot. CommandLineRunnerRun code after Spring Boot application startsrun(String... args)Raw command-line argumentsSimple use cases, quick startup scripts
ApplicationRunnerorg.springframework.boot. ApplicationRunnerRun code after app starts (with structured access to args)run( ApplicationArguments args)Parsed args with option accessMore control over startup args and options

Spring Boot provides two main interfaces to run logic after the application context is initialized.

CommandLineRunner
Executes after the application context is loaded and receives the command-line arguments.
ApplicationRunner
Similar to CommandLineRunner, but provides access to application arguments in a more structured way.

You can have multiple runners, and you can order them with @Order(1) or implement Ordered.

SpringBoot Application invocation:

SpringBoot application invokes from the main() method and main() method is responsible to invoke the run() method

Run() method performs the activities like

Stopwatch counters
Prepares Environment
Print Banner
Start the IOC container
Refresh the context
Trigger runners
And return application context reference (Spring IOC).
StepComponent/CodeDescription
1public static void main(String[] args)Entry point of the Spring Boot application (Java main method)
2SpringApplication.run()Boots up the Spring application context and starts the embedded server
3@SpringBootApplicationConvenience annotation for @Configuration + @EnableAutoConfiguration + @ComponentScan
4Auto-configuration (@EnableAutoConfiguration)Spring Boot automatically configures beans based on classpath and properties
5Component Scan (@ComponentScan)Detects and registers @Component, @Service, @Repository, @Controller
6Application Context is initializedAll beans are instantiated, dependencies injected
7CommandLineRunner / ApplicationRunnerExecutes logic right after application context is loaded
8Embedded Server Starts (e.g., Tomcat)Starts embedded servlet container and listens on the configured port

Different approaches of designing class having dependency

Compostion
Factory Pattern
JNDI Registry
Inheritence
IOC Dependency lookup/pull and dependency injection/Push

Dependency lookup: It is an approach where we can get the resource after demand

Depedency Injection: IOC/DI describes the situation where one object uses a second object to provide a particular capacity.

Instead of you asking for dependencies, Spring pushes them into your classes. This is the "Inversion of Control" (IoC) concept

Constructor Injection when object must be created with all it’s dependencies.

Setter Injection: Use Setter Injection when the number of dependencies is large or when some of them are optional.

In field injection, Spring injects dependencies directly into class variables (fields), typically marked with @Autowired

How to create a singleton beans in SpringBoot

Creating singleton beans in Spring Boot is quite straightforward because Spring beans are singleton by default. This means that when you define a bean in a Spring Boot application, Spring will create only one instance of that bean and reuse it wherever it's injected.

Using @Component (Default Singleton)
Using @Bean in a @Configuration Class
Explicitly Declaring Singleton Scope (Optional)
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class MySingletonService {
// Same as before
}

how to create Mutable state in Springboot

In Spring Boot, mutable state refers to data that can be changed during the application's runtime—like in-memory counters, caches, or user sessions

Using Singleton Beans with Mutable Fields
Using @Scope("prototype") or Request/Session Scopes (if needed)
Using ConcurrentHashMap or Similar for In-Memory Storage
Use @Scope("session") to Maintain User-Specific Mutable State

Spring Boot automatically manages the session via cookies (usually JSESSIONID).

As long as the session is active, the state is maintained for that user.

When the session expires or the browser is closed, the state is lost.

Handle Exception in SpringBoot

In Spring Boot, you handle exceptions centrally using the @ControllerAdvice annotation along with @ExceptionHandler. This allows you to define global exception handling logic, keeping your controllers clean and consistent.

Different actuator in SpringBoot

Spring Boot Actuator provides production-ready features to help monitor and manage your application. It exposes various endpoints to get internal insights like health, metrics, environment properties, etc.

Actuator EndpointURL PathDescription
health/actuator/healthShows application health status (UP/DOWN)
info/actuator/infoDisplays arbitrary application info (from application.properties)
metrics/actuator/metricsShows metrics like JVM memory, CPU usage, etc.
env/actuator/envDisplays all environment properties
beans/actuator/beansLists all Spring beans in the application context
mappings/actuator/mappingsShows all @RequestMapping paths
loggers/actuator/loggersView and modify logger levels at runtime
threaddump/actuator/threaddumpShows a thread dump from the JVM
httptrace/actuator/httptraceDisplays recent HTTP request/response trace (requires enabling explicitly)
auditevents/actuator/auditeventsDisplays audit events (e.g., login success/failures)
shutdown/actuator/shutdownGracefully shuts down the application (must be enabled explicitly)
caches/actuator/cachesShows available caches and statistics
scheduledtasks/actuator/scheduledtasksShows scheduled tasks in the application
startup/actuator/startupDisplays startup steps and timing (Spring Boot 3.x+)

Configuration Tips

PropertyPurpose
management.endpoints.web.exposure.include=*Enables all actuator endpoints
management.endpoint.shutdown.enabled=trueEnables the shutdown endpoint
management.endpoint.health.show-details=alwaysShows detailed health info

Metrics in Spring Boot (Micrometer)

Metric CategoryExamples (Metric Names)Description
JVM Metricsjvm.memory.used, jvm.threads.liveMonitors heap, non-heap memory, GC, threads
System Metricssystem.cpu.usage, system.load.average.1mTracks CPU and system load
Process Metricsprocess.uptime, process.cpu.usageUptime, CPU time used by the JVM
HTTP Metricshttp.server.requestsTracks HTTP request count, status, response times
Datasource Metricshikaricp.connections, jdbc.connections.activeMonitors database connection pools
Cache Metricscache.gets, cache.puts, cache.evictionsTracks cache usage and hit/miss stats
Logback Metricslogback.eventsTracks log events (info, error, warn)
Custom MetricsCustom via @Timed, MeterRegistry.counter()Developers can define custom metrics

Enabling Prometheus Exporter

StepConfiguration
Add dependencyspring-boot-starter-actuator + micrometer-registry-prometheus
Enable endpoint in application.propertiesmanagement.endpoints.web.exposure.include=prometheus
Access metrics athttp://localhost:8080/actuator/prometheus

Key Config Properties

PropertyDescription
management.metrics.enable.*Enable/disable specific metric categories
management.endpoint.metrics.enabled=trueEnable the /actuator/metrics endpoint
management.metrics.distribution.percentilesConfigure custom percentiles for timers

Spring Boot Core Starters

StarterUsageCategory
spring-boot-starterCore starter, includes auto-configuration, logging, and YAML support.Core
spring-boot-starter-webBuilds web, RESTful applications using Spring MVC. Uses Tomcat as default embedded container.Web
spring-boot-starter-data-jpaSimplifies JPA-based database access. Used with Hibernate as the default JPA provider.Data Access
spring-boot-starter-securityAdds Spring Security for authentication and authorization.Security
spring-boot-starter-testAdds testing libraries like JUnit, Hamcrest, Mockito, and Spring Test.Testing
spring-boot-starter-thymeleafIntegrates Thymeleaf template engine for server-side rendering of HTML.Template Engines
spring-boot-starter-actuatorAdds production-ready features like health checks, metrics, and monitoring.Monitoring
spring-boot-starter-validationSupports Java Bean Validation (JSR-380) with Hibernate Validator.Validation
spring-boot-starter-data-mongodbSimplifies MongoDB access with Spring Data MongoDB.Data Access
spring-boot-starter-batchSupports Spring Batch for batch processing and ETL applications.Batch Processing
spring-boot-starter-amqpEnables AMQP messaging with RabbitMQ.Messaging
spring-boot-starter-cacheAdds abstraction support for caching.Caching
spring-boot-starter-mailProvides JavaMail support for sending emails.Email
spring-boot-starter-quartzIntegrates Quartz Scheduler for scheduling tasks.Scheduling
spring-boot-starter-aopAdds Aspect-Oriented Programming support using Spring AOP and AspectJ.AOP
spring-boot-starter-data-redisEnables Spring Data Redis for Redis key-value store support.Data Access
spring-boot-starter-oauth2-clientSupports OAuth2-based Single Sign-On and client applications.Security
spring-boot-starter-graphqlSupports building GraphQL APIs.API Development
spring-boot-starter-websocketAdds WebSocket support for real-time bi-directional communication.WebSocket
spring-boot-starter-integrationSupports Spring Integration for building messaging-based applications.Integration
spring-boot-starter-freemarkerAdds support for FreeMarker template engine.Template Engines
spring-boot-starter-mustacheAdds support for Mustache template engine.Template Engines
spring-cloud-starter-circuitbreaker-resilience4jProvides Circuit Breaker support using Resilience4j library.Cloud Resilience
spring-cloud-starter-gatewayEnables building API gateways with routing, load balancing, and filtering using Spring Cloud Gateway.Cloud API Gateway
spring-kafkaSupports Apache Kafka integration for event-driven messaging applications.Messaging
spring-boot-starter-activemqProvides support for Java Message Service (JMS) API using ActiveMQ as the message broker.Messaging
spring-boot-starter-webfluxBuilds reactive web applications using Spring WebFlux with support for non-blocking APIs, Reactor, and Netty server.Reactive Web

Spring Boot realistic, end-to-end flow of a Microservices system

end-to-end flow of a Microservices system

Spring Boot (for services)
API Gateway (central entry point)
Circuit Breaker (for fault tolerance)
JWT Authentication (secure the APIs)
PostgreSQL (database per service)

High-Level Architecture

Embedded document image

Each microservice handles its own domain, has its own database, and communicates through HTTP (REST) or sometimes Messaging (Kafka/RabbitMQ).

Components Setup

Embedded document image

Step-by-Step Flow

(A) User Request

A client (browser/app) makes a request with credentials (/login).

(B) API Gateway Routing

Request first hits the API Gateway.
Gateway routes /auth/** calls to the Authentication Service.

(C) Authentication Service

Auth Service validates credentials against the database.
If valid, it generates a JWT token (with username/roles/expiry).

JWT = base64(header) + base64(payload) + signature

It sends back the JWT token to the client.

(D) Subsequent Requests with JWT

Now, for any protected API (/user/**, /order/**):
Client sends JWT token in Authorization header.
API Gateway can have a JWT filter to verify the token before forwarding.

Example header:

Authorization: Bearer <your_jwt_token_here>

(E) Gateway forwards request

API Gateway checks routing rules and forwards to the correct microservice.

POST /user/create → User-Service

GET /order/history → Order-Service

(F) Microservice verifies JWT again (optional)

Microservice may revalidate the token and extract user info from JWT for authorization.

(G) Business Logic + PostgreSQL

Service handles the request, interacts with its PostgreSQL database (using JPA/Hibernate).

User user = userRepository.findById(userId);

(H) Circuit Breaker in Action

If one service (like Order-Service) goes down, the API Gateway (or the client microservice) uses a Circuit Breaker to:
Detect failure
Open the circuit (stop requests temporarily)
Fallback to default response

Resilience4j example:

@CircuitBreaker(name = "orderService", fallbackMethod = "orderFallback")

public Order getOrder(String orderId) { ... }

If getOrder() fails, orderFallback() will be triggered.

Diagram (Simple View)

Embedded document image

Real Life Example

Let's say:

You have an E-commerce app.
User logs in via /auth/login, gets a JWT.
User places an order via /order/create.
Order-Service talks to Order-DB.
If Order-Service is down, Circuit Breaker gives "Order Service is temporarily unavailable" instead of crashing the app.

Spring Boot-level transactions

(using @Transactional): Spring manages the transaction boundaries for you, calling COMMIT or ROLLBACK based on success or exception.

Easier to work with in complex business workflows.
Integrates well with services, repositories, multiple DBs, and external systems.
Easier to maintain, test, and debug.
Slightly more overhead than pure DB transactions.

Global Exception Handler

Handling global exceptions in Spring Boot is super important for clean, maintainable, and user-friendly error management. The best way to handle global exceptions is through @ControllerAdvice. It provides a centralized way of handling exceptions across your whole application.

How to Handle Global Exceptions in Spring Boot

Create a Global Exception Handler with @ControllerAdvice

@ControllerAdvice is used to handle exceptions in a centralized way, across all controllers.
It can be used to handle specific exceptions or general exceptions for your entire application.

Embedded document image

Embedded document image

Explain how you designed a scalable microservices architecture in Spring Boot.

ComponentTechnology / PatternPurpose
Service LayerSpring Boot MicroservicesIndependent, loosely coupled services for business domains
API GatewaySpring Cloud Gateway / ZuulSingle entry point, routing, security, and rate-limiting
Service DiscoveryEureka / ConsulDynamic service registration and discovery
Load BalancerRibbon (legacy), Spring Cloud LoadBalancer, external (e.g. NGINX)Distributes requests across instances
ConfigurationSpring Cloud Config Server / VaultCentralized and dynamic configuration management
Database LayerPolyglot Persistence (MySQL, MongoDB, PostgreSQL)Each service has its own DB (Database per service pattern)
CommunicationREST (Feign), Messaging (RabbitMQ/Kafka)Sync (Feign) and Async (Messaging) communication
SecurityOAuth2 / JWT / Spring SecurityCentralized authentication and authorization
ObservabilitySpring Boot Actuator, Micrometer + Prometheus + GrafanaMetrics, health checks, and custom monitoring
LoggingELK (Elasticsearch, Logstash, Kibana) / EFK (Fluentd)Centralized logging and search
TracingSleuth + Zipkin / JaegerDistributed tracing
ContainerizationDockerPackaged and portable deployment
OrchestrationKubernetes (AKS, EKS, GKE)Automated deployment, scaling, and management
CI/CDGitHub Actions / Jenkins / Azure DevOpsAutomated build, test, and deployment pipelines

Microservice Design Principles

Design ElementApproach
Bounded ContextEach service aligns with a single business domain (e.g., User, Order, Payment)
Loose CouplingServices interact via REST APIs or messaging queues
High CohesionEncapsulate business logic within a single service
ResilienceCircuit Breakers (Resilience4j), retries, timeouts
ScalabilityStateless services + Kubernetes HPA

Sample Tech Stack

LayerTechnology
API GatewaySpring Cloud Gateway
Service DiscoveryNetflix Eureka
Inter-Service Comm.Feign, Kafka
ConfigurationSpring Cloud Config
AuthenticationKeycloak / OAuth2 / JWT
MonitoringPrometheus + Grafana
TracingSleuth + Zipkin
LoggingLogback + Elasticsearch/Kibana
DeploymentDocker + Kubernetes (AKS)

Architecture Diagram

+---------------------+

| Client UI |

+---------------------+

|

+---------------------+

| API Gateway |

+---------------------+

|

+------------+------------+

| | |

▼ ▼ ▼

+---------+ +----------+ +----------+

| Order | | User | | Payment | ← Spring Boot Services

+---------+ +----------+ +----------+

| | |

+---------+ +----------+ +----------+

|MySQL DB | |MongoDB | |Postgres |

+---------+ +----------+ +----------+

(All services registered in Eureka)

Scalability Features Implemented

FeatureDetails
Horizontal ScalingServices are stateless and deployed as replicas in Kubernetes
Central ConfigSpring Cloud Config Server enables dynamic reloading via Actuator
Health Monitoring/actuator/health used by Kubernetes for liveness/readiness checks
ResilienceRetry and circuit breaker patterns via Resilience4j
Asynchronous MessagingKafka used for non-blocking inter-service communication (e.g., order events)
JWT SecurityAuth tokens are validated at the API Gateway level
AutoscalingHPA scales pods based on CPU/memory/requests per second

Key Best Practices

Avoid shared databases across microservices.
Use DTOs and API contracts to decouple services.
Ensure backward compatibility for APIs.
Use rate limiting and throttling at the gateway.
Enable caching for frequently accessed data (e.g., Redis).
Isolate faults using bulkheads and circuit breakers.

How do you handle service discovery and communication between services (e.g., Eureka, Feign, REST Template)?

When handling service discovery and communication between microservices, especially in a Spring Boot microservice architecture, you typically use a combination of tools like Eureka, Feign, and RestTemplate.

Service Discovery (Eureka)

Eureka is a service registry from Netflix used to register and discover services in a microservices architecture.

Eureka Server acts as a registry where all client services register themselves.
Eureka Client registers the service and queries other services via Eureka.

eureka:

client:

service-url:

defaultZone: http://localhost:8761/eureka/

Service Communication Options

A. Feign Client (Declarative REST Client)

Simplifies HTTP calls with a declarative interface.
Automatically integrates with Eureka for service discovery.

Use when: You want cleaner, readable code and tighter Spring Cloud integration.

@FeignClient(name = "order-service")

public interface OrderClient {

@GetMapping("/orders/{id}")

Order getOrderById(@PathVariable("id") Long id);

}

@EnableFeignClients

@SpringBootApplication

public class Application { }

RestTemplate

A more manual way to make HTTP calls.
You need to manually load-balance or resolve service names unless using Ribbon (now deprecated) or Spring Cloud LoadBalancer.

Use when: You want full control over the HTTP request or need to integrate with external APIs.

@Autowired

private RestTemplate restTemplate;

public Order getOrderById(Long id) {

return restTemplate.getForObject("http://order-service/orders/" + id, Order.class);

}

@Bean

@LoadBalanced // Enables service name resolution via Eureka

public RestTemplate restTemplate() {

return new RestTemplate();

}

What is the role of Spring Cloud Config? How do you manage configurations in production?

Spring Cloud Config provides centralized configuration management for distributed microservices. It allows you to externalize configuration properties from your application code and manage them in a central Git repository (or Vault, JDBC, etc.).

Why use Spring Cloud Config?

ProblemSolution with Spring Cloud Config
Duplication of configs across servicesCentralized config in a single place (e.g., Git)
Manual config updatesDynamic refresh using @RefreshScope and actuator/refresh
Multiple environments (dev, qa, prod)Profile-specific YAMLs like application-prod.yml
Secrets and sensitive valuesSupport for integration with Vault, KMS, etc.

Summary

AspectSpring Cloud Config Benefits
Centralized managementYes (via Git, Vault, etc.)
Environment segregationYes (via profiles)
Dynamic reloadYes (@RefreshScope, Spring Cloud Bus)
Secret managementYes (Vault integration)
Production safe?Yes, when using secure backends + Bus + refresh

How do you secure microservices (OAuth2, JWT, Spring Security)?

Securing microservices is critical in distributed architectures. You typically secure them using Spring Security, OAuth2, and JWT. Here's a structured breakdown of how to secure microservices in a modern Spring Boot setup:

Authentication and Authorization in Microservices

Security ConcernSolution
Identity verificationOAuth2 / OpenID Connect
Token-based authJWT (JSON Web Tokens)
Central auth managementAuthorization Server (e.g., Keycloak, Auth0)
Service-to-service authPropagate JWT or use Mutual TLS

Core Security Components

A. Spring Security

Foundation for securing endpoints.
Defines roles, authorities, and access control rules.

B. OAuth2 / OpenID Connect

Delegates authentication to an Authorization Server.
Generates access tokens (usually JWTs) for client authentication.

C. JWT (JSON Web Token)

Self-contained token with claims (user ID, roles, expiry).
Digitally signed, usually with an HMAC or RSA key.

How it Works (Flow)

Client logs in via Authorization Server (Keycloak, Auth0, Okta, etc.)
Server issues an Access Token (JWT).
Client includes JWT in the Authorization header for every request:

Authorization: Bearer <token>

Each microservice:

Validates the token signature and expiry.
Extracts claims for role-based access control.

What’s your approach to versioning REST APIs?

Versioning REST APIs is critical for maintaining backward compatibility while allowing continuous evolution of your services. Here's a structured approach to REST API versioning:

PurposeBenefit
Avoid breaking changesClients using old versions keep working
Allow iterative improvementsNew features added in new versions
Support multiple client versionsMobile apps, third-party consumers

Why API Versioning Matters

PurposeBenefit
Avoid breaking changesClients using old versions keep working
Allow iterative improvementsNew features added in new versions
Support multiple client versionsMobile apps, third-party consumers

Best Practices for API Versioning

Best PracticeWhy It Matters
Use semantic versioning (v1, v2)Clear evolution of API
Keep versions backward compatibleAvoid breaking existing clients
Deprecate old versions graduallyCommunicate EOL to clients
Document version changes clearlyUse Swagger/OpenAPI per version
Use consistent versioning strategyAcross all microservices

What’s your approach to ensuring high availability and fault tolerance?

Ensuring high availability (HA) and fault tolerance is critical for resilient, production-grade systems

Design for Failure

Assume components will fail at some point — hardware, network, software bugs.
Build systems that gracefully degrade rather than catastrophically crash.

Redundancy & Replication

Deploy multiple instances of services behind load balancers.
Use replicated databases or distributed data stores (e.g., master-slave, multi-master).
Data replication ensures no single point of failure.

Failover Mechanisms

Use automated failover for services and databases.
Health checks and heartbeats detect failures; traffic routed away from unhealthy nodes.
Example: Kubernetes readiness/liveness probes + service mesh retries.

Stateless Services

Design services to be stateless wherever possible.
Store state externally (databases, caches, distributed storage).
Makes horizontal scaling and failover simpler.

Graceful Degradation & Circuit Breakers

Implement circuit breakers (e.g., Resilience4j, Hystrix) to avoid cascading failures.
Provide fallback methods or degraded service responses if downstream systems fail.

Load Balancing & Auto-Scaling

Use load balancers (AWS ALB, NGINX, Envoy) to distribute traffic evenly.
Set up auto-scaling to handle spikes and failures by launching/removing instances dynamically.

Distributed Data Consistency

Use databases/configurations that support HA (e.g., distributed consensus protocols like Raft, Paxos).
Choose appropriate consistency models (strong vs eventual) based on application needs.

Data Backup & Recovery

Regular backups of data and configurations.
Tested recovery plans in place for disaster scenarios.

Monitoring, Alerting & Incident Response

Comprehensive monitoring (metrics, logs, traces).
Alerting on failures and thresholds.
Runbooks and automation for incident management.

Chaos Engineering

Intentionally inject failures in a controlled manner (e.g., Netflix Chaos Monkey).
Identify weaknesses and improve system resilience proactively.

Summary Table:

StrategyPurposeExample Tools / Techniques
Redundancy & ReplicationEliminate SPOFKubernetes, Multi-AZ DB replicas
FailoverAuto switch on failureKubernetes probes, DNS failover
Stateless DesignEasy scaling & recoveryExternal session stores
Circuit BreakersAvoid cascading failuresResilience4j, Hystrix
Load Balancing & Auto-ScalingHandle load and failuresAWS ALB, Kubernetes HPA
Monitoring & AlertingEarly detection & responsePrometheus, Grafana, PagerDuty
Chaos EngineeringTest fault toleranceChaos Monkey, Gremlin

Microservices Architecture Design

ComponentRole
API GatewaySingle entry point for all client requests, routing, authentication, rate limiting, and request aggregation.
Service MeshManages inter-service communication with features like service discovery, load balancing, retries, circuit breaking, and security.
MicroservicesIndependently deployable services implementing business capabilities, communicating over the network.
ObservabilityMonitoring, logging, tracing, and alerting across all services to gain insight and detect issues.

How to Run Spring Boot Actuator on a Different Port

You can specify a different port for Actuator endpoints by setting the management.server.port property in your application.properties or application.yml.

server.port=8080 # Application runs on port 8080

management.server.port=8081 # Actuator runs on port 8081

management.endpoints.web.exposure.include=* # Expose all actuator endpoints

To override or customize the /health endpoint

Instead of fully overriding /health, you typically contribute custom health indicators:

@Component

public class MyCustomHealthIndicator implements HealthIndicator {

@Override

public Health health() {

}

Fully Override the /health Endpoint (Not Recommended)

Exclude the default Actuator /health

management.endpoints.web.exposure.exclude=health

@RestController

public class CustomHealthController {

@GetMapping("/health")

public ResponseEntity<Map<String, Object>> customHealth() {

Map<String, Object> status = new HashMap<>();

status.put("status", "CUSTOM_HEALTH_OK");

status.put("timestamp", Instant.now());

return ResponseEntity.ok(status);

}

}

How do you design a microservices system using Spring Boot?

Break monolith into domain-driven bounded contexts.
Use Spring Boot for each service.
Communication via REST, gRPC, or messaging (Kafka, RabbitMQ).
Service discovery with Eureka or Consul.
Load balancing with Spring Cloud Gateway + Ribbon.
Centralized config (Spring Cloud Config), monitoring (Prometheus + Grafana).
Security: OAuth2/JWT with Spring Security.

What is a Bounded Context?

Bounded Context is a key concept in Domain-Driven Design (DDD). It helps you clearly define the boundaries within which a specific domain model applies — especially important in large-scale, enterprise, or microservices-based systems.

What is a Reactive Programming?

Reactive programming is an asynchronous programming paradigm that focuses on non-blocking, event-driven data processing with backpressure handling.

It’s useful when:

You need to handle a large number of concurrent users.
The application is I/O-bound (e.g., waiting for DB, APIs).
You want to optimize resource utilization (threads, memory).

Spring Boot Reactive

Spring Boot uses the Spring WebFlux module to support reactive programming using:

Mono<T> – Represents 0 or 1 result
Flux<T> – Represents 0 to N results (a stream)

Built on Project Reactor, a reactive library for Java.

When to Use It

Your system is event-driven or message-based.
You need high concurrency with limited hardware.
You integrate with non-blocking downstream systems.

@GetMapping

public Flux<Employee> getAll() {

return service.getAll();

}

@GetMapping("/{id}")

public Mono<Employee> get(@PathVariable String id) {

return service.getById(id);

}

@PostMapping

public Mono<Employee> create(@RequestBody Employee emp) {

return service.save(emp);

}

where your Spring Boot app needs to process a large file efficiently

To handle large files in Azure, we store them in Azure Blob. We split the file logically and use Service Bus to distribute chunks to Spring Boot instances. The app is containerized and deployed to AKS, and we scale it horizontally using HPA based on CPU or queue depth. This enables dynamic scaling and efficient processing.

Embedded document image

↑ Back to top