Open In App

Java Security, Monitoring & DevOps Interview Questions

Last Updated : 08 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

This highlights crucial interview questions related to security, observability, and deployment practices in Java microservices. It covers authentication and authorization using OAuth2 and JWT, API gateway security, CORS, and HTTPS configuration. Additionally, it dives into centralized logging, metrics, health checks, and modern DevOps practices like CI/CD pipelines, Docker, Kubernetes, and configuration management.

1. Explain the end-to-end flow of authentication and authorization in a Spring Boot microservice using OAuth2 and JWT. How do you secure downstream services?

OAuth2 provides authorization, JWT (JSON Web Tokens) carries user identity. The flow:

  1. User logs in via Identity Provider (Keycloak, Auth0)
  2. Gets JWT as access token
  3. Client sends JWT in Authorization: Bearer header
  4. Resource server validates token using public key

Securing downstream services: Use Spring Security’s @PreAuthorize, and propagate JWT via API Gateway.

Code Snippet:

@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
// JWT validation config
}

2. How does Spring Cloud Gateway provide centralized authentication and route-level security? How would you secure routes based on user roles?

Spring Cloud Gateway acts as a reverse proxy and auth gateway.

Features:

  • Token validation at gateway
  • Routes secured based on path, method, or user roles

YAML Example:

spring:
cloud:
gateway:
routes:
- id: orders
uri: lb://ORDER-SERVICE
predicates:
- Path=/orders/**
filters:
- RemoveRequestHeader=Cookie
- AddRequestHeader=Authorization, Bearer <JWT>

Security Filter: Custom AuthenticationWebFilter for role checks.

3. What is CSRF? Why is it not always needed in REST APIs? How do you configure CORS and HTTPS in a Spring Boot app?

  • CSRF (Cross-Site Request Forgery): Malicious sites sending unwanted POST requests.
  • In stateless REST APIs, CSRF is not needed since there's no session.

Disable CSRF:

http.csrf().disable();

CORS Config:

@Bean
public WebMvcConfigurer corsConfigurer() {
return registry -> registry.addMapping("/**")
.allowedOrigins("*").allowedMethods("*");
}

HTTPS Setup: Use server.ssl.* properties and keystore in application.yml.

4. Explain how centralized logging using ELK Stack works in a microservices ecosystem. How do services stream logs to Logstash?

  1. Elasticsearch stores logs
  2. Logstash parses and processes log entries
  3. Kibana visualizes logs

Log forwarding: Services log to stdout (Docker), or filebeat/logstash agent reads logs.

Logback to Logstash:

<appender name="LOGSTASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>logstash:5000</destination>
</appender>

Benefit: Correlated trace IDs across services using MDC.

5. What is Micrometer and how does it integrate with Prometheus and Grafana for monitoring Java microservices?

Micrometer is a metrics library integrated into Spring Boot Actuator.

Flow:

  1. Micrometer collects JVM, HTTP, and custom metrics
  2. Metrics exposed at /actuator/prometheus
  3. Prometheus scrapes and stores
  4. Grafana visualizes data via queries

Code:

@Timed("order.create.time")
public void createOrder(...) { ... }

6. What is distributed tracing and how do you implement it using Zipkin and Spring Cloud Sleuth? How do trace IDs help?

  • Sleuth generates trace and span IDs
  • Zipkin collects and displays traces
  • Each log has unique traceId, spanId

Benefit: Visualize call flow across services.

Config:

spring:
zipkin:
base-url: http://zipkin:9411
sleuth:
sampler:
probability: 1.0

Logs:

[TRACE-ID, SPAN-ID] OrderService - Called InventoryService

7. How does Spring Boot Actuator help in microservices monitoring? Which endpoints are critical in production and why?

Actuator endpoints:

  • /actuator/health : app health
  • /actuator/metrics : performance
  • /actuator/beans, /loggers, /info : diagnostics

Security: Protect sensitive endpoints via Spring Security.

Production Must-Haves:

  • Health checks for Kubernetes probes
  • Metrics for Prometheus scraping

8. Write a unit test using JUnit 5 and Mockito to verify a service method in isolation. What are common pitfalls in mocking?

@ExtendWith(MockitoExtension.class)
public class OrderServiceTest {

@Mock OrderRepository orderRepo;
@InjectMocks OrderService orderService;

@Test
void testCreateOrder() {
Order order = new Order(...);
when(orderRepo.save(order)).thenReturn(order);
assertEquals(order, orderService.createOrder(order));
}
}

Pitfalls:

  • Over-mocking (mocking what you shouldn't)
  • Not testing real behavior
  • Forgetting to mock nested dependencies

9. Describe a full-stack integration test using @SpringBootTest. How do you isolate external services in microservice tests?

Use @SpringBootTest with real context, embedded DB, and mock beans.

@SpringBootTest(webEnvironment = RANDOM_PORT)
@AutoConfigureMockMvc
class ProductIT {

@Autowired MockMvc mockMvc;

@Test
void testGetProduct() throws Exception {
mockMvc.perform(get("/products/1"))
.andExpect(status().isOk());
}
}

External Services:

  • Use WireMock or Testcontainers
  • Mock Feign clients or rest templates

10. What is contract testing in microservices and how does Spring Cloud Contract help avoid integration failures?

Contract Testing: Ensures provider and consumer agree on API structure.

Spring Cloud Contract Flow:

  1. Define contract (Groovy/YAML)
  2. Provider generates stub
  3. Consumer uses stub to verify

Benefits:

  • Early failure detection
  • CI-friendly
  • No need for running dependent services

11. Explain how you design a Jenkins pipeline for CI/CD of a Spring Boot microservice. Include build, test, and deploy stages.

pipeline {
agent any
stages {
stage('Build') {
steps { sh 'mvn clean package' }
}
stage('Unit Test') {
steps { sh 'mvn test' }
}
stage('Docker Build') {
steps { sh 'docker build -t app:latest .' }
}
stage('Deploy') {
steps { sh 'kubectl apply -f k8s/deployment.yaml' }
}
}
}

Best Practice: Run contract tests before integration test.

12. How do you containerize a Spring Boot application with Docker? What are best practices for image size, security, and layers?

Dockerfile:

FROM eclipse-temurin:17-jdk-alpine
COPY target/app.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]

Best Practices:

  • Use Alpine images
  • Multi-stage builds to avoid Maven inside image
  • Keep secrets out of Dockerfile
  • Use .dockerignore

13. Describe the key components of a Kubernetes deployment for a Java microservice. Include YAML structure.

YAML for deployment and service:

apiVersion: apps/v1
kind: Deployment
metadata:
name: app
spec:
replicas: 2
template:
spec:
containers:
- name: app
image: app:latest
---
apiVersion: v1
kind: Service
metadata:
name: app-service
spec:
selector:
app: app
ports:
- port: 80
targetPort: 8080

Components:

  • Deployment: versioning, replicas
  • Service: exposes app inside cluster

14. How do you securely manage secrets in Kubernetes? Explain the use of secrets, config maps, and Helm.

  • Secrets: For passwords, tokens (kubectl create secret)
  • ConfigMaps: For general config (env, application.yml)
  • Helm: Package manager for K8s, supports value templating

Values.yaml:

env:
SPRING_DATASOURCE_PASSWORD: ENC(password)

Mount secrets as environment variables or files.

15. What are readiness and liveness probes in Kubernetes? How do they relate to Spring Boot Actuator and microservice health?

  • Liveness Probe: Detects if app is alive; restarts if stuck.
  • Readiness Probe: App is ready to serve traffic.

Spring Actuator Integration:
livenessProbe:
httpGet:
path: /actuator/health/liveness
readinessProbe:
httpGet:
path: /actuator/health/readiness

Use: Ensures smooth rolling deployments and auto-recovery.


Article Tags :
Practice Tags :

Similar Reads