Thanks to visit codestin.com
Credit goes to www.geeksforgeeks.org

Open In App

Java Security, Monitoring & DevOps Interview Questions

Last Updated : 25 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?

Authentication and authorization in Spring Boot using OAuth2 and JWT ensures secure access to microservices by validating user identity and permissions. JWT tokens carry user claims that downstream services can trust without re-authenticating.

Flow:

  1. User Login: Client authenticates via an Identity Provider (e.g., Keycloak, Auth0).
  2. Token Issuance: On successful login, the IdP issues a JWT access token.
  3. API Request: Client sends the JWT in the Authorization: Bearer <token> header.
  4. Resource Server Validation: Each microservice validates the token signature, expiration, and claims using Spring Security.
  5. Authorization: Services enforce permissions using annotations like @PreAuthorize or role-based checks.
  6. Securing Downstream Services: JWT is propagated to downstream calls, ensuring each service can independently verify authorization without central session storage.

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 central entry point for microservices, enabling centralized authentication, authorization, and route-level security. It validates incoming requests before they reach downstream services.

How it Works:

  1. Token Validation: Gateway intercepts requests and checks JWT or OAuth2 tokens.
  2. Route Matching: Requests are routed based on path, method, or predicates.
  3. Authorization: User roles or permissions are checked before forwarding to microservices.

Securing Routes Example:

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

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) is an attack where a malicious site tricks a user’s browser into sending unauthorized requests to a web application where the user is authenticated.

Why Not Always Needed in REST APIs:

  • REST APIs are usually stateless and rely on tokens (JWT/OAuth2) instead of sessions.
  • Since there’s no session-based authentication, CSRF attacks are less relevant.

Configuring CORS in Spring Boot:

Java
@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("*");
        }
    };
}

Disabling CSRF (for stateless APIs):

http.csrf().disable();

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

Centralized logging in microservices helps collect, store, and analyze logs from multiple services in one place, improving observability, debugging, and traceability. ELK Stack (Elasticsearch, Logstash, Kibana) is widely used for this purpose.

How ELK Works:

  1. Elasticsearch: Stores and indexes logs for fast searching.
  2. Logstash: Collects, parses, and transforms logs from services.
  3. Kibana: Visualizes logs and metrics via dashboards.

Streaming Logs to Logstash:

  • Microservices log to stdout (common in Docker) or log files.
  • Logstash reads these logs using Filebeat or directly via TCP/HTTP appenders.
  • Example using Logback appender:

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

Micrometer is a metrics library for Java applications, integrated with Spring Boot Actuator, providing a vendor-neutral way to collect and expose application metrics.

Integration with Prometheus and Grafana:

  1. Micrometer collects JVM metrics (CPU, memory), HTTP requests, and custom application metrics.
  2. Metrics are exposed at the /actuator/prometheus endpoint.
  3. Prometheus scrapes this endpoint at intervals and stores the metrics.
  4. Grafana visualizes the metrics from Prometheus via dashboards, enabling real-time monitoring and alerting.

Benefit:

  • Provides unified, consistent metrics.
  • Supports alerting, capacity planning, and performance optimization in microservices.

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

Distributed tracing helps track and visualize requests as they flow through multiple microservices, making it easier to debug, monitor latency, and identify bottlenecks.

Implementation with Zipkin and Spring Cloud Sleuth:

  1. Spring Cloud Sleuth automatically generates unique traceId and spanId for each request and propagates them across service calls.
  2. Zipkin collects trace and span data from Sleuth and provides a web UI to visualize the request flow.
  3. Configuration Example (application.yml):

spring:

zipkin:

base-url: http://zipkin:9411

sleuth:

sampler:

probability: 1.0

How trace IDs help:

  • Correlate logs across multiple services.
  • Identify slow services or failed requests.
  • Simplify root cause analysis in complex microservice architectures

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

Spring Boot Actuator provides built-in production-ready endpoints to monitor, manage, and gain insights into microservices, helping maintain health, performance, and reliability.

Key Points:

1. Monitoring Features:

  • Exposes metrics, health status, beans, environment properties, and loggers.
  • Supports custom metrics via Micrometer.

2. Critical Endpoints in Production:

  • /actuator/health-> Checks service health for readiness/liveness probes.
  • /actuator/metrics-> Provides JVM, HTTP, and custom performance metrics.
  • /actuator/loggers -> Dynamic log level adjustment for troubleshooting.
  • /actuator/info ->? Application metadata and versioning.

Importance:

  • Ensures microservices are operational (health checks).
  • Enables proactive monitoring and alerting.
  • Supports integration with Prometheus, Grafana, and Kubernetes for observability.

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

Unit testing in Spring Boot ensures that individual service methods work correctly in isolation. JUnit 5 and Mockito are widely used for writing such tests.

Example:

Java
@ExtendWith(MockitoExtension.class)
public class OrderServiceTest {

    @Mock
    private OrderRepository orderRepo;

    @InjectMocks
    private OrderService orderService;

    @Test
    void testCreateOrder() {
        Order order = new Order(1L, "Item1", 2);
        when(orderRepo.save(order)).thenReturn(order);

        Order result = orderService.createOrder(order);

        assertEquals(order, result);
        verify(orderRepo, times(1)).save(order);
    }
}

Common Pitfalls in Mocking:

  1. Over-mocking: Mocking unnecessary dependencies reduces test value.
  2. Not testing real behavior: Mocking logic instead of verifying method outcomes.
  3. Ignoring nested dependencies: Failing to mock deeper layers may cause NullPointerExceptions.
  4. Tight coupling to implementation: Tests may break if internal logic changes even when behavior is

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

Full-stack integration testing verifies the application’s components together in a realistic environment, including controllers, services, and repositories. In microservices, it’s important to isolate external dependencies to ensure consistent test results.

Example using @SpringBootTest:

Java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class ProductIntegrationTest {

    @Autowired
    private MockMvc mockMvc;

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

Isolating External Services:

  • WireMock: Mock HTTP endpoints for external services.
  • Testcontainers: Spin up lightweight containers for databases or dependent services.
  • Mock Feign Clients / RestTemplate: Replace actual calls with mock implementations.

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

Contract testing ensures that a microservice provider and its consumers agree on the API structure, preventing integration issues before runtime. It focuses on verifying that both sides adhere to a predefined “contract.”

How Spring Cloud Contract Helps:

  • Define Contracts: Write contracts in Groovy, YAML, or JSON describing expected requests and responses.
  • Provider Stub Generation: The provider uses the contract to generate stubs for testing.
  • Consumer Testing: Consumers use the generated stubs to verify compatibility without depending on the actual service.

Benefits:

  • Detects integration failures early in the CI/CD pipeline.
  • Reduces the need for running all dependent services during testing.
  • Ensures API consistency and backward compatibility across versions.

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

A Jenkins pipeline automates the build, test, and deployment of Spring Boot microservices, ensuring faster delivery, consistency, and repeatability in CI/CD workflows.

Java
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' }
    }
  }
}

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

Containerizing a Spring Boot application with Docker allows consistent deployments across environments, isolates dependencies, and simplifies scaling in microservices architectures.

Dockerfile Example:

# Use lightweight JDK image

FROM eclipse-temurin:17-jdk-alpine


# Copy the packaged Spring Boot jar

COPY target/app.jar app.jar


# Run the application

ENTRYPOINT ["java", "-jar", "app.jar"]

Best Practices:

  1. Image Size: Use lightweight base images (e.g., Alpine), remove unnecessary files, and use multi-stage builds.
  2. Security: Avoid storing secrets in the image; use environment variables or Kubernetes secrets.
  3. Layers: Minimize layers, order instructions to leverage caching, and use .dockerignore to exclude unnecessary files.

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

Kubernetes orchestrates containerized Java microservices, managing deployment, scaling, and networking to ensure high availability and reliability.

Key Components:

  1. Deployment: Manages application replicas, updates, and versioning.
  2. Service: Exposes the application inside or outside the cluster and enables load balancing.
  3. ConfigMaps & Secrets: Externalize configuration and manage sensitive data.
  4. Pods: Smallest deployable unit, hosting one or more containers.

Sample YAML

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

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

In Kubernetes, secrets and configuration management ensure that sensitive data and environment-specific settings are handled securely without hardcoding them into applications.

Key Components & Usage:

1. Secrets: Store sensitive information such as passwords, tokens, or API keys.

Example:

kubectl create secret generic db-password --from-literal=password=MySecretPass

2. ConfigMaps: Store non-sensitive configuration data like environment variables or application settings.

Example:

kubectl create configmap app-config --from-file=application.yml

3. Helm: Kubernetes package manager that manages deployment templates and securely injects secrets and config values through values.yaml.

Example:

env:

SPRING_DATASOURCE_PASSWORD: ENC(password)

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

Readiness and liveness probes in Kubernetes help ensure that microservices are running correctly and ready to serve traffic, enabling self-healing and smooth deployments.

Definitions & Usage:

  1. Liveness Probe: Checks if the application is alive. If the probe fails, Kubernetes restarts the container.
  2. Readiness Probe: Checks if the application is ready to handle requests. If it fails, Kubernetes temporarily removes the pod from service endpoints.

Spring Boot Actuator Integration:
You can expose actuator endpoints for probes:

livenessProbe:

httpGet:

path: /actuator/health/liveness

readinessProbe:

httpGet:

path: /actuator/health/readiness



Article Tags :

Explore