CTCaliberTek
Interview Questions

Spring Boot Security, Testing, and Microservices Interview Questions

15 questions on Spring Security, JWT, testing slices, Testcontainers, caching, scheduling, and microservice patterns.

  1. 1. How does Spring Security work at a high level?

    It installs a chain of servlet filters in front of your application. Each request passes through filters that handle authentication (who are you), authorization (what may you do), CSRF protection, session handling, and security headers. You configure the chain by declaring a SecurityFilterChain bean.

  2. 2. How do you configure which endpoints are secured?

    Declare a SecurityFilterChain bean with the lambda DSL (the WebSecurityConfigurerAdapter class was removed in Spring Security 6).

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
          .authorizeHttpRequests(auth -> auth
              .requestMatchers("/public/**").permitAll()
              .requestMatchers("/admin/**").hasRole("ADMIN")
              .anyRequest().authenticated())
          .httpBasic(Customizer.withDefaults());
        return http.build();
    }
  3. 3. How should passwords be stored?

    Never store plain text. Hash them with a slow, salted algorithm through a PasswordEncoder, usually BCryptPasswordEncoder or the delegating encoder from PasswordEncoderFactories, which supports Argon2 and others and lets you upgrade algorithms later.

  4. 4. How does JWT authentication work in a Spring Boot API?

    The client logs in and receives a signed token. On each request it sends the token in the Authorization header (Bearer). A filter, or Spring's built-in resource server support, validates the signature and expiry, loads the identity and roles, and places an Authentication in the security context. Keep tokens short-lived, use a refresh mechanism, protect signing keys, and never put secrets in the payload since it is only encoded, not encrypted.

  5. 5. What are method-level security annotations?

    With @EnableMethodSecurity you can protect individual methods using @PreAuthorize, @PostAuthorize, and @Secured, including expressions such as @PreAuthorize("hasRole('ADMIN') or #userId == authentication.name"). They apply through proxies, so they share the self-invocation limitation of @Transactional.

  6. 6. What is CSRF, and when can you disable it?

    Cross-site request forgery tricks a logged-in browser into sending a state-changing request. Spring Security enables CSRF protection by default. For a stateless API that authenticates with a bearer token in a header (not a cookie), CSRF is not exploitable and is commonly disabled. If you use cookie-based sessions, keep it enabled.

  7. 7. What testing support does Spring Boot provide?

    spring-boot-starter-test includes JUnit 5, Mockito, AssertJ, and Spring Test. Use plain unit tests for logic, test slices for specific layers, and @SpringBootTest for full integration tests. Slices load only part of the context, which keeps tests fast.

  8. 8. What are the common test slices?

    @WebMvcTest tests controllers with MockMvc and mocked services. @DataJpaTest configures JPA repositories with an in-memory or container database and rolls back after each test. @JsonTest checks serialization, and @RestClientTest tests REST clients. Use @MockBean (or @MockitoBean in newer versions) to replace beans.

    @WebMvcTest(OrderController.class)
    class OrderControllerTest {
        @Autowired MockMvc mvc;
        @MockBean OrderService service;
    
        @Test
        void returnsOrder() throws Exception {
            given(service.find(1L)).willReturn(new Order(1L));
            mvc.perform(get("/api/orders/1")).andExpect(status().isOk());
        }
    }
  9. 9. What is Testcontainers, and why use it?

    A library that starts real services such as MySQL, PostgreSQL, Kafka, or Redis in Docker containers for tests. It gives you integration tests against the same database engine as production, instead of an in-memory substitute that behaves differently. Spring Boot has built-in support through @ServiceConnection.

  10. 10. How does caching work in Spring Boot?

    Enable it with @EnableCaching and annotate methods with @Cacheable (store the result), @CachePut (update), and @CacheEvict (remove). Configure a provider such as Caffeine (local) or Redis (shared). Choose expiry and size limits deliberately, and remember it also uses proxies.

    @Cacheable("products")
    public Product findById(Long id) { return repository.findById(id).orElseThrow(); }
  11. 11. How do you run scheduled and asynchronous tasks?

    Enable scheduling with @EnableScheduling and annotate methods with @Scheduled (fixed rate, fixed delay, or a cron expression). Use @EnableAsync with @Async to run a method on another thread. In clustered deployments scheduled jobs run on every instance, so use a lock (such as ShedLock) or a dedicated job system. Spring Boot 3.2 and newer can run on virtual threads with spring.threads.virtual.enabled=true.

  12. 12. What is a microservices architecture, and what are its trade-offs?

    An application split into small independently deployable services, each owning its data and responsibility. Benefits: independent scaling and deployment, technology flexibility, and team autonomy. Costs: network failures, distributed transactions and data consistency, harder debugging, and operational overhead. A well-structured modular monolith is often a better starting point.

  13. 13. Which resilience patterns are used between services?

    Timeouts on every remote call, retries with exponential backoff and jitter (only for idempotent operations), circuit breakers that stop calling a failing service, bulkheads that isolate resources, and fallbacks. Resilience4j integrates with Spring Boot for these.

  14. 14. How do services communicate, and what is the difference between synchronous and asynchronous messaging?

    Synchronous communication (REST or gRPC) is simple but couples the caller to the callee's availability and speed. Asynchronous messaging through a broker such as Kafka or RabbitMQ decouples services and smooths load, but results arrive later and you must handle duplicates (make consumers idempotent) and ordering. Spring offers Spring for Apache Kafka, Spring AMQP, and Spring Cloud Stream.

  15. 15. How do you handle configuration and secrets in a deployed Spring Boot application?

    Keep configuration outside the image using environment variables, config maps, or Spring Cloud Config, and keep secrets in a secret manager (such as Kubernetes secrets, Vault, or a cloud provider's service), never in source control. Use profiles for environment differences, and health checks (Actuator) for readiness and liveness probes.

Interview Tips

  • Be clear about the difference between authentication and authorization.
  • Describe how you test at each level: unit, slice, and full integration.
  • When asked about microservices, discuss when you would not use them.