Senior Java & Spring Boot Interview Questions – Top 20 (Part 6)

Senior Java interviews increasingly cover more than Core Java, REST APIs, and dependency injection. Developers are expected to understand how security filters work internally, how Spring Boot creates beans, how AI applications protect sensitive data, how batch jobs recover from failures, and how distributed systems maintain consistency.

In production, knowing an annotation is not enough. You need to understand what happens behind it, where failures occur, how to investigate them, and which trade-offs matter when designing a reliable system.

This guide covers 20 advanced Java and Spring Boot interview questions with detailed answers, practical code examples, architecture patterns, and real-world troubleshooting approaches.

Section 1: Spring Security Internals and Authentication

1. How does Spring Security process an incoming HTTP request internally, and what is the role of SecurityFilterChain?

Spring Security protects HTTP requests through a chain of servlet filters. These filters process requests before they reach the application's controller and can perform authentication, authorization, security-context management, CSRF protection, and other security operations.

A simplified request flow looks like this:

Client Request
      |
      v
Servlet Container
      |
      v
DelegatingFilterProxy
      |
      v
FilterChainProxy
      |
      v
Matching SecurityFilterChain
      |
      +-- Security Context Handling
      +-- Authentication Filters
      +-- Exception Translation
      +-- Authorization
      |
      v
DispatcherServlet
      |
      v
Controller

DelegatingFilterProxy connects the servlet container's filter mechanism to Spring-managed security infrastructure.

FilterChainProxy is the central Spring Security filter that selects an applicable security filter chain for the request.

SecurityFilterChain defines the security filters that should apply to matching requests. An application can configure multiple chains for different paths or request types, such as API endpoints and browser-based login flows.

For example:

@Bean
SecurityFilterChain apiSecurity(HttpSecurity http)
        throws Exception {

    http
        .securityMatcher("/api/**")
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/public/**").permitAll()
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer(oauth2 ->
            oauth2.jwt(Customizer.withDefaults())
        );

    return http.build();
}

This is a simplified resource-server configuration. A production application must also decide how to handle CSRF, CORS, error responses, token validation, and any additional security requirements.

When multiple filter chains exist, Spring Security generally uses the first matching chain. Therefore, chain ordering and matchers matter. A broad matcher placed before a more specific matcher can cause requests to use the wrong security configuration.

How to troubleshoot:

  • Check which SecurityFilterChain matches the request.
  • Inspect the configured filter order.
  • Enable targeted Spring Security debug logging in a safe environment.
  • Check whether the authentication filter extracts credentials correctly.
  • Determine whether the failure occurs during authentication or authorization.
  • Inspect the resulting HTTP status and security exception.

Interview takeaway: SecurityFilterChain determines which security filters process a request. Understanding chain selection and filter ordering is essential when debugging unexpected authentication or authorization behavior.

2. What is the difference between Authentication and Authorization, and how does Spring Security handle each?

Authentication establishes who or what is making a request. Authorization determines whether that authenticated identity has permission to perform the requested operation.

For example, a customer may successfully log in but still be forbidden from viewing another customer's order.

Aspect Authentication Authorization
Question answered Who are you? What are you allowed to do?
Typical inputs Password, session, OAuth2 login, bearer token Authorities, roles, permissions, resource ownership
Spring Security components AuthenticationManager, AuthenticationProvider, authentication filters AuthorizationManager, request rules, method security
Typical HTTP outcome 401 when valid authentication is missing or invalid 403 when access is denied

A simplified authentication flow is:

  1. An authentication filter extracts credentials from the request.
  2. The credentials are represented by an Authentication object.
  3. An AuthenticationManager delegates authentication to an appropriate AuthenticationProvider.
  4. The provider validates the credentials or token.
  5. On success, an authenticated Authentication object is established in the SecurityContext.
  6. Authorization rules evaluate whether the authenticated identity can access the requested resource.

For request-level authorization:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http)
        throws Exception {

    http.authorizeHttpRequests(auth -> auth
        .requestMatchers("/admin/**").hasRole("ADMIN")
        .requestMatchers("/customer/**").hasAnyRole(
            "CUSTOMER", "ADMIN"
        )
        .anyRequest().authenticated()
    );

    return http.build();
}

Spring Security's hasRole("ADMIN") convention normally checks for the authority ROLE_ADMIN.

For sensitive business operations, request-level rules may not be sufficient. The application should also verify resource ownership and business permissions.

Interview takeaway: A valid identity does not automatically grant access to every resource. Authentication and authorization must be designed and tested separately.

3. How would you implement OAuth2 login and JWT-based authentication in a Spring Boot microservices architecture?

OAuth2 login and JWT-based API authentication are related but serve different purposes.

OAuth2 login allows a user to authenticate through an identity provider, often using OpenID Connect. JWT bearer tokens can then be used to authorize API requests when the system's identity and token architecture supports that flow.

A common architecture is:

Browser / Client
      |
      v
Identity Provider
      |
      | OAuth2 / OpenID Connect
      v
Application or Login Client
      |
      v
Access Token
      |
      v
API Gateway / Resource Server
      |
      +-- Order Service
      +-- Payment Service
      +-- Customer Service

There are two common approaches:

  • Browser-based application: The application can use an OAuth2 login flow and maintain a server-side session, or use an appropriate token-based design.
  • API resource servers: Microservices validate bearer access tokens and enforce their own authorization rules.

For a Spring Boot resource server, a simplified configuration is:

@Bean
SecurityFilterChain apiSecurity(HttpSecurity http)
        throws Exception {

    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/public/**").permitAll()
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer(oauth2 ->
            oauth2.jwt(Customizer.withDefaults())
        );

    return http.build();
}

Configure the trusted issuer or public-key/JWK source through the application's supported resource-server configuration. The resource server must validate the token's signature and relevant claims, such as issuer, expiration, and audience where required by the system.

Important design decisions:

  • Use an established identity provider instead of building a custom authentication protocol.
  • Keep access tokens short-lived where appropriate.
  • Validate issuer, signature, expiry, and intended audience.
  • Define how roles and permissions are mapped to Spring Security authorities.
  • Do not assume that a gateway's authentication automatically replaces authorization inside every service.
  • Use TLS for communication and protect refresh tokens carefully.
  • For service-to-service communication, consider OAuth2 client credentials or another appropriate workload identity mechanism.
  • Define revocation and key-rotation strategies.

JWTs are often self-contained, so changes to a user's permissions may not be reflected until a new token is issued unless the architecture includes additional revocation or authorization checks.

Interview takeaway: OAuth2 and OpenID Connect establish trusted identity flows; resource servers validate access tokens and enforce service-specific authorization.

4. Why can a custom Spring Security filter execute multiple times, and how would you prevent unintended duplicate execution?

A custom filter may execute more than once because of servlet dispatch behavior, filter registration, multiple security chains, or incorrect filter placement.

Common causes include:

  • The filter is registered as a servlet-container filter and also added to Spring Security.
  • The request undergoes an additional dispatch, such as an error dispatch.
  • The filter is included in multiple applicable security configurations.
  • The filter's behavior does not account for asynchronous or error dispatches.
  • The filter is inserted at an inappropriate position in the security chain.

A common implementation mistake is declaring a custom filter as a Spring bean and also adding it explicitly to the security chain, while Spring Boot automatically registers it with the servlet container.

When the filter should be used only within Spring Security, disable its automatic servlet registration where appropriate.

@Bean
FilterRegistrationBean<RequestTokenFilter>
disableServletRegistration(RequestTokenFilter filter) {

    FilterRegistrationBean<RequestTokenFilter> registration =
        new FilterRegistrationBean<>(filter);

    registration.setEnabled(false);
    return registration;
}

Then add the filter to the intended security chain:

http.addFilterBefore(
    requestTokenFilter,
    UsernamePasswordAuthenticationFilter.class
);

The correct insertion point depends on the filter's purpose and the authentication mechanism being used.

Extending OncePerRequestFilter can help prevent repeated execution for the same request within its intended dispatch semantics. However, it does not fix duplicate registrations or incorrect chain configuration by itself.

How to troubleshoot:

  1. Log a correlation ID, dispatcher type, URI, and filter entry point.
  2. Check whether the filter is registered with the servlet container.
  3. Inspect all SecurityFilterChain beans and their matchers.
  4. Verify filter ordering.
  5. Test normal, error, and asynchronous dispatch behavior.

Interview takeaway: Prevent duplicate filter execution by understanding servlet registration, security-chain configuration, and dispatch behavior rather than relying only on a filter base class.

Section 2: Spring Boot Bean Creation and API Security

5. How does Spring Boot auto-configuration decide which beans to create, and how can you debug unexpected bean registration?

Spring Boot auto-configuration provides default beans based on the libraries on the classpath, application configuration, and conditions evaluated during startup.

For example, a configuration may create a bean only when a particular library is available and the application has not defined its own implementation.

@Configuration
@ConditionalOnClass(PaymentClient.class)
class PaymentConfiguration {

    @Bean
    @ConditionalOnMissingBean
    PaymentClient paymentClient() {
        return new PaymentClient();
    }
}

Common conditional annotations include:

  • @ConditionalOnClass — checks whether a class is available.
  • @ConditionalOnMissingBean — applies when a suitable bean is missing.
  • @ConditionalOnBean — applies when a suitable bean exists.
  • @ConditionalOnProperty — checks a configuration property.
  • @ConditionalOnWebApplication — checks the type of application environment.

Auto-configuration does not mean that every library automatically creates every possible bean. Conditions, explicit configuration, bean definitions, and configuration ordering all matter.

How to investigate unexpected beans:

  1. Start the application with the supported condition-evaluation diagnostic option, such as --debug, in an appropriate environment.
  2. Inspect the condition evaluation report.
  3. Check the application context for bean names and types.
  4. Inspect active profiles and relevant configuration properties.
  5. Review component scanning and explicit @Import declarations.
  6. Check dependency versions and classpath contents.

The Actuator beans endpoint can also help inspect registered beans, but it should be secured and exposed only according to operational requirements.

Interview takeaway: Debug bean registration by examining the conditions and configuration that created the bean, not by guessing from its annotation alone.

6. What happens when multiple beans of the same type exist, and how do @Primary, @Qualifier, and @ConditionalOnMissingBean differ?

Spring can register multiple beans implementing the same interface. When dependency injection requires one candidate but several match, Spring needs a way to resolve the ambiguity.

Consider two payment processors:

public interface PaymentProcessor {
    void process();
}

@Component("cardProcessor")
class CardPaymentProcessor implements PaymentProcessor {
    public void process() {}
}

@Component("bankProcessor")
class BankPaymentProcessor implements PaymentProcessor {
    public void process() {}
}

Injecting a single PaymentProcessor may be ambiguous unless Spring can determine a preferred candidate.

@Primary marks a bean as the preferred candidate when multiple candidates otherwise match.

@Primary
@Bean
PaymentProcessor defaultProcessor() {
    return new CardPaymentProcessor();
}

@Qualifier narrows the injection point to a specific candidate.

@Service
class PaymentService {

    private final PaymentProcessor processor;

    PaymentService(
            @Qualifier("bankProcessor")
            PaymentProcessor processor) {
        this.processor = processor;
    }
}

@ConditionalOnMissingBean is primarily used in configuration, particularly auto-configuration, to create a default bean only when an appropriate bean has not already been registered.

Mechanism Purpose Typical Use
@Primary Prefer one candidate Default implementation among multiple beans
@Qualifier Select a specific candidate Choose a processor by role or bean name
@ConditionalOnMissingBean Conditionally register a bean definition Provide an overridable auto-configuration default

Interview takeaway: @Primary and @Qualifier resolve injection choices; @ConditionalOnMissingBean controls whether a configuration should provide a bean at all.

7. How would you secure REST APIs with different access rules for administrators, customers, and internal services?

A secure API should enforce both broad access rules and resource-level business authorization.

For example:

  • Administrators can manage platform configuration.
  • Customers can access their own orders.
  • Internal services can invoke selected machine-to-machine endpoints.
  • Public endpoints may allow unauthenticated access.

Request-level authorization can enforce broad role or authority requirements:

@Bean
SecurityFilterChain apiSecurity(HttpSecurity http)
        throws Exception {

    http.authorizeHttpRequests(auth -> auth
        .requestMatchers("/api/admin/**")
            .hasRole("ADMIN")
        .requestMatchers("/api/customer/**")
            .hasAnyRole("CUSTOMER", "ADMIN")
        .requestMatchers("/api/internal/**")
            .hasAuthority("SCOPE_internal")
        .requestMatchers("/api/public/**")
            .permitAll()
        .anyRequest()
            .authenticated()
    );

    http.oauth2ResourceServer(oauth2 ->
        oauth2.jwt(Customizer.withDefaults())
    );

    return http.build();
}

This is an illustrative rule set. Internal endpoints should require credentials issued for the intended machine identity and appropriate scopes or authorities. A path prefix alone does not make an endpoint internal or secure.

For resource ownership, validate the actual object being accessed.

@PreAuthorize(
    "@orderAuthorization.canRead(authentication, #orderId)"
)
public OrderResponse getOrder(Long orderId) {
    // Load and return the order
}

The authorization component should check whether the current identity owns the order or has an explicit administrative permission.

Additional considerations include:

  • Validate JWT issuer, signature, expiry, and relevant audience claims.
  • Apply least privilege to service accounts.
  • Use TLS for network communication.
  • Configure CORS intentionally for browser clients.
  • Protect cookie-based authentication flows against CSRF where applicable.
  • Use deny-by-default rules for unclassified endpoints.
  • Test both allowed and denied cases.

Interview takeaway: Role-based rules protect endpoint categories, while resource-based authorization protects individual business objects.

Section 3: Spring AI and LLM Application Design

8. How does Spring AI connect an application to an LLM, and what roles do ChatClient, ChatModel, and advisors play?

Spring AI provides abstractions that help Spring applications communicate with supported AI models without embedding all provider-specific request logic into business services.

The core components have different responsibilities:

  • ChatModel: Represents the model integration that sends requests to a supported chat model and returns model responses.
  • ChatClient: Provides a higher-level API for constructing prompts, supplying parameters, invoking the model, and handling responses.
  • Advisors: Intercept or augment the chat interaction to implement reusable behaviors, such as retrieval, conversation context, logging, or other supported request/response processing.

A simplified flow looks like this:

REST Controller
      |
      v
Business Service
      |
      v
ChatClient
      |
      +-- Advisors
      |
      v
ChatModel
      |
      v
LLM Provider
      |
      v
Model Response

Example usage with the Spring AI ChatClient API:

@Service
public class AssistantService {

    private final ChatClient chatClient;

    public AssistantService(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    public String answer(String question) {
        return chatClient.prompt()
            .user(question)
            .call()
            .content();
    }
}

The exact configuration and available methods depend on the Spring AI version and model provider integration being used.

In a production application, the business service should also enforce prompt-size limits, handle model errors, apply timeouts, control cost, and avoid sending sensitive data without an approved policy.

Interview takeaway: ChatClient provides a convenient interaction API, ChatModel abstracts model communication, and advisors add reusable behavior around the interaction.

9. How would you prevent sensitive information from being exposed when sending user prompts to an external AI model?

An AI integration can unintentionally disclose personal information, credentials, internal documents, or confidential business data if the application forwards user input or retrieved content without appropriate controls.

Consider a customer-support assistant that retrieves a customer record before constructing a prompt. Sending the entire record to an external provider may disclose information that the model does not need.

Recommended controls:

  1. Classify data: Identify personal information, credentials, financial information, confidential documents, and regulated data.
  2. Minimize context: Send only the information required for the current task.
  3. Redact sensitive fields: Remove or mask secrets and unnecessary identifiers before building the prompt.
  4. Enforce authorization before retrieval: A user should not be able to retrieve documents merely by asking the model for them.
  5. Review provider policies: Understand data retention, processing, regional requirements, and whether inputs may be used for model improvement.
  6. Protect logs: Avoid logging complete prompts, model responses, credentials, or retrieved documents by default.
  7. Apply access controls: Restrict who can use AI features and which data sources they can query.
  8. Use approved deployment options: For highly sensitive workloads, evaluate enterprise controls or appropriately governed private deployments.

Prompt instructions alone are not a reliable security boundary. The application must enforce authorization and data filtering before content reaches the model.

Also remember that model output may repeat sensitive information contained in the input. Apply output controls before returning or logging the response.

Interview takeaway: Protect sensitive data before constructing the prompt. Security should be enforced by application controls, not delegated to the LLM.

10. How would you implement Retrieval-Augmented Generation (RAG) using Spring AI and a vector database?

Retrieval-Augmented Generation combines document retrieval with language-model generation. Instead of asking the model to answer only from its learned parameters, the application retrieves relevant information from a controlled knowledge source and includes that information in the model context.

A typical architecture is:

Document Sources
      |
      v
Text Extraction
      |
      v
Chunking
      |
      v
Embedding Model
      |
      v
Vector Database

User Question
      |
      v
Question Embedding / Retrieval
      |
      v
Relevant Document Chunks
      |
      v
Prompt Construction
      |
      v
LLM
      |
      v
Grounded Response

Step 1: Ingest documents. Extract text from PDFs, Word files, HTML pages, or other supported sources.

Step 2: Split documents into chunks. Chunk size and overlap affect retrieval quality. Chunks that are too large may contain irrelevant material; chunks that are too small may lose important context.

Step 3: Generate embeddings. An embedding model converts text into vectors representing semantic features.

Step 4: Store vectors and metadata. A vector database stores embeddings and supports similarity-based retrieval. Include metadata such as document ID, tenant, access classification, and source location where appropriate.

Step 5: Retrieve relevant chunks. Search using the user's question, optionally combining semantic search, keyword search, metadata filters, and reranking.

Step 6: Construct the prompt. Include the question and retrieved evidence, with instructions to distinguish supported facts from missing information.

Step 7: Generate and validate the answer. Return a grounded answer and, where appropriate, source references that allow users to inspect the evidence.

Spring AI provides document, embedding, vector-store, and retrieval integration abstractions. The exact configuration depends on the selected vector database and Spring AI version.

For multi-tenant or user-specific documents, authorization filtering must occur before retrieved content is sent to the model. Retrieval results should not be trusted merely because they are semantically similar.

Interview takeaway: RAG improves access to relevant external knowledge, but retrieval quality, document freshness, access control, and evidence validation determine whether the system is reliable.

11. How would you reduce hallucinations in an AI-powered Spring Boot application?

A hallucination occurs when a model produces information that is unsupported or incorrect. No single prompt instruction can guarantee that hallucinations will disappear.

Reduce the risk through multiple controls:

  • Use RAG: Provide relevant, trusted evidence from approved sources.
  • Improve retrieval: Tune chunking, metadata filters, search strategy, and reranking.
  • Constrain responses: Define the expected answer format and require evidence for factual claims.
  • Allow abstention: Instruct the system to say when the available evidence is insufficient.
  • Validate structured output: Parse and validate generated JSON against an application schema.
  • Use deterministic business logic: Do not ask the LLM to calculate critical financial values or enforce permissions when ordinary code can do so reliably.
  • Evaluate systematically: Build a representative test set and measure retrieval relevance, factual correctness, refusal behavior, and citation quality.
  • Monitor production: Track feedback, failed answers, unsupported claims, and changes in retrieval quality.

For example, an AI assistant that answers questions about internal company policies should retrieve the applicable policy version and return a reference to the source document. If the source does not contain the answer, it should avoid inventing a policy.

Retrieved documents can themselves contain misleading or malicious instructions. Treat document content as untrusted data, not as instructions that override the application's security policy.

Interview takeaway: Reduce hallucinations by grounding responses in evidence, controlling the workflow, validating outputs, and measuring quality—not by relying on prompt wording alone.

12. How would you handle LLM timeouts, rate limits, retries, and token-cost limits in production?

LLM providers may experience latency spikes, rate limits, transient errors, and quota exhaustion. Model calls can also be expensive, particularly when prompts include large conversation histories or retrieved documents.

A production design should establish clear operational limits.

Timeouts: Configure connection and response timeouts. Set an overall request deadline so multiple sequential operations cannot exceed the application's latency budget.

Rate limits: Limit requests per user, tenant, and application. Use a distributed limiter when several application instances share the same provider quota.

Retries: Retry only errors that are likely to be transient and safe to retry. Respect provider guidance such as retry-after information where available. Use bounded exponential backoff with jitter.

Concurrency limits: Bound the number of in-flight model calls so slow responses do not exhaust threads, connections, or memory.

Token budgets: Limit input size, retrieved context, conversation history, and maximum output tokens. Estimate or count tokens using an appropriate model-specific mechanism.

Cost controls: Track usage by model, tenant, feature, and request. Define budget alerts and hard limits for expensive workflows.

Fallback behavior: Decide whether the application should return a clear temporary failure, use a smaller model, return cached information, or provide a non-AI alternative.

Observability: Record latency, status, retry count, rate-limit events, token usage, and cost estimates without logging sensitive prompt content.

Do not retry every timeout blindly. The provider may have completed the request even though the client did not receive the response. For operations that trigger external side effects, use application-level idempotency and explicit operation tracking.

Interview takeaway: Treat LLM calls as external dependencies with latency, capacity, reliability, privacy, and cost constraints.

Section 4: Spring Batch and Large-Scale Data Processing

13. How does Spring Batch manage Job, Step, JobRepository, and JobExecution?

Spring Batch provides infrastructure for defining and executing batch workflows with persistent execution metadata, restart support, and operational visibility.

The main concepts are:

  • Job: Represents a complete batch process.
  • Step: Represents a phase of the job, such as reading data, transforming records, writing results, or running a tasklet.
  • JobInstance: Represents a logical job instance identified by the job and its identifying parameters.
  • JobExecution: Represents an attempt to execute a job instance.
  • StepExecution: Records an execution attempt for a step, including status and execution metadata.
  • JobRepository: Persists job and step execution metadata used for tracking and restart behavior.

A simplified structure looks like this:

Job: DailyOrderProcessing
      |
      +-- Step 1: Read and Validate Orders
      |
      +-- Step 2: Calculate Results
      |
      +-- Step 3: Write Results
      |
      +-- Step 4: Generate Summary

A step can use chunk-oriented processing, where records are read, processed, and written in chunks, or a tasklet for work represented as a task.

Spring Batch stores execution metadata so operators can inspect status and the framework can support restartable jobs when the job and its steps are configured appropriately.

Job parameters matter. Launching a job with the same identifying parameters may refer to the same JobInstance, whereas different identifying parameters can create a different instance.

Interview takeaway: Spring Batch separates the logical job, individual steps, execution attempts, and persistent metadata so long-running workflows can be monitored and recovered.

14. What happens when a Spring Batch job fails halfway through, and how does restartability work?

Suppose a batch job processes one million records and fails after processing 600,000. Whether it can restart from a useful point depends on the step configuration, transaction boundaries, reader state, execution context, and side effects.

Spring Batch records execution metadata in the JobRepository. For a properly configured restartable step, the framework can use persisted execution state to resume processing from a checkpoint rather than always starting from the beginning.

However, restartability is not automatic for every arbitrary piece of application code.

Important considerations:

  • Use restartable readers and writers where appropriate.
  • Persist checkpoint state correctly.
  • Understand which data changes commit with each chunk.
  • Ensure custom readers and processors handle restarts safely.
  • Make external side effects idempotent or track their completion.
  • Define how non-retryable data errors should be handled.

For example, if a chunk transaction rolls back, database changes in that transaction can be rolled back as well. But an email, external API request, or message sent outside that transaction may already have succeeded.

That creates a critical distinction: a database transaction can roll back database state, but it cannot automatically undo every external side effect.

Example: If a batch job sends a payment request and then fails before recording the successful result, restarting the job could send the payment again. Use a stable business operation ID, idempotency support, or a durable processing record to prevent duplicate effects.

Interview takeaway: Restartability depends on persisted state and safe processing design. Recovery must account for both database changes and external side effects.

15. How would you process millions of database records using Spring Batch without exhausting memory?

Loading millions of entities into a Java collection is risky because the heap must hold the loaded objects and their associated persistence-context state.

Use bounded, incremental processing instead.

1. Use chunk-oriented processing. Read a bounded number of records, process them, and write the results as a chunk.

2. Choose an appropriate reader. Use a paging, cursor, or other suitable reader depending on the database, transaction behavior, ordering, and restart requirements.

3. Avoid unnecessarily large persistence contexts. When using JPA, managed entities can accumulate in the persistence context. Consider periodic flushing and clearing when appropriate, or use JDBC-oriented processing for large bulk workloads.

4. Use stable ordering. Ensure the reader can continue predictably. For large datasets, keyset-based pagination can be more efficient than deep offset pagination when supported by the data model and query.

5. Tune chunk size through measurement. Very small chunks increase transaction and database overhead; very large chunks increase memory use and the amount of work affected by a rollback.

6. Bound concurrency. Parallel processing may improve throughput but can also increase database contention, connection demand, and memory usage.

7. Measure performance. Track records per second, query time, commit duration, memory use, connection-pool pressure, and failure rates.

Conceptual chunk flow:

Read 500 Records
      |
      v
Process Records
      |
      v
Write Results
      |
      v
Commit Transaction
      |
      v
Continue with Next Chunk

The value of 500 is only an illustration, not a universal recommendation. Determine the actual chunk size through representative load testing.

Interview takeaway: Process data incrementally, keep memory bounded, understand transaction and persistence-context behavior, and tune throughput using measurements.

16. What is the difference between chunk-oriented processing and tasklet-based processing in Spring Batch?

Spring Batch supports both approaches because some batch workloads process many records while others perform a bounded task.

Aspect Chunk-Oriented Processing Tasklet-Based Processing
Model Read, process, and write items in chunks Execute a task through a Tasklet
Typical use Importing, transforming, or exporting large datasets File cleanup, stored-procedure execution, simple bounded operations
Transaction behavior Typically commits according to configured chunk boundaries Depends on tasklet execution and transaction configuration
Memory strategy Can be designed for bounded item processing Depends on the implementation; a tasklet can still load too much data

Conceptual chunk example:

Reader
   |
   v
Processor
   |
   v
Writer
   |
   v
Chunk Commit

A tasklet is useful when the operation does not naturally map to an item-by-item pipeline.

Neither model automatically guarantees restart safety. The implementation must still consider transactions, checkpoints, and external side effects.

Interview takeaway: Use chunk-oriented processing for item pipelines and tasklets for task-based operations. Choose based on the workload rather than assuming one model is always better.

17. How would you prevent duplicate processing when a batch job is restarted after partial failure?

A batch job may restart after some records have already been processed. Duplicate processing can occur if the framework's checkpoint state and the application's business state are not aligned.

For example, a job may update an order in a database and then fail before its checkpoint is committed. When restarted, the job may encounter that order again.

Use several complementary controls.

1. Idempotent writes: Design the operation so repeating it produces the same intended business state.

2. Stable business identifiers: Use an order ID, transaction ID, or source record ID to identify the operation consistently.

3. Database constraints: Use unique constraints or upsert patterns where appropriate to prevent duplicate records.

4. Processing ledger: Persist the status of each business operation when detailed tracking is required.

5. Correct checkpoints: Configure readers and execution-context state so restart behavior is predictable.

6. Transactional updates: Where possible, commit the business update and the corresponding processing status in the same database transaction.

7. External side effects: Use provider-supported idempotency keys, durable outbox records, or reconciliation workflows for operations that cannot share the database transaction.

A processing table might conceptually contain:

source_record_id | processing_status
-----------------|------------------
10001            | COMPLETED
10002            | COMPLETED
10003            | PENDING
10004            | PENDING

Do not rely solely on an in-memory set of processed IDs because that state disappears when the process restarts.

Interview takeaway: Checkpoints help the framework resume work; idempotency and durable business state prevent duplicate effects.

Section 5: Distributed Systems and Production Architecture

18. How would you maintain data consistency when a Spring Boot service updates a database and publishes a Kafka event?

A common failure occurs when a service performs two operations independently:

  1. Update a database record.
  2. Publish a Kafka event describing the update.

If the database transaction commits but publishing fails, the database changes while downstream consumers never receive the event.

If the event is published before the database transaction commits and the transaction later rolls back, consumers may observe an event describing a change that never became durable.

This is the dual-write problem.

Recommended approach: Transactional Outbox Pattern

Within one database transaction, write both the business change and an outbox record.

Spring Boot Service
        |
        v
Database Transaction
        |
        +-- Update Business Data
        |
        +-- Insert Outbox Event
        |
        v
      Commit
        |
        v
Outbox Publisher / CDC
        |
        v
       Kafka
        |
        v
     Consumers

Because the business change and outbox record commit together, the application avoids losing the intent to publish when the database transaction succeeds.

A separate publisher or change-data-capture mechanism sends pending events to Kafka. The publisher may send an event more than once, so consumers should be designed for duplicate delivery.

Consumer-side protections:

  • Include a stable event ID.
  • Use idempotent consumer logic.
  • Record processed event IDs where necessary.
  • Use database constraints to prevent duplicate business effects.
  • Monitor outbox backlog and publication failures.
  • Define retry and dead-letter handling.

Kafka transactions can provide useful guarantees within Kafka workflows, but they do not automatically create one atomic transaction across an arbitrary relational database and Kafka.

Interview takeaway: Use the transactional outbox to coordinate database changes and event publication reliably, then make consumers resilient to duplicate delivery.

19. How would you troubleshoot a microservice that works locally but fails under production traffic?

A service that works locally may fail in production because of concurrency, data volume, infrastructure limits, dependency latency, configuration differences, or traffic patterns that are absent from development.

Do not immediately assume that the problem is a Java code defect. First establish what is failing and where the request spends its time.

Step 1: Establish the impact

  • Compare request rate, error rate, and latency percentiles.
  • Identify affected endpoints and user groups.
  • Determine whether the failure began after a deployment or configuration change.

Step 2: Inspect distributed traces

Determine whether time is spent in the application, database, external API, message broker, or another microservice.

Step 3: Inspect resource pressure

  • CPU saturation and throttling.
  • Heap usage, allocation rate, and garbage-collection pauses.
  • Thread-pool saturation and blocked threads.
  • Database connection-pool usage and connection acquisition time.
  • Queue depth and message-consumer lag.

Step 4: Check production configuration

Compare JVM options, active Spring profiles, timeouts, connection-pool settings, Kubernetes resource limits, secrets, and dependency versions.

Step 5: Reproduce under representative load

Use realistic request distributions, payload sizes, concurrency, and data volumes. A test using only a small dataset cannot reveal every query-plan or memory problem.

Step 6: Apply a targeted fix

Examples include optimizing a slow query, reducing excessive concurrency, fixing a thread leak, correcting a timeout, or limiting an unbounded queue.

Step 7: Verify the result

Compare the same metrics before and after the change. Confirm that the fix improves the intended outcome without creating new bottlenecks.

Interview takeaway: Production troubleshooting is a process of measurement, hypothesis, controlled investigation, and verification—not trial-and-error configuration changes.

20. How would you design an AI-powered document processing pipeline using Spring Boot, Spring AI, Spring Batch, and asynchronous messaging?

Consider a business application that accepts thousands of documents daily and needs to extract information, classify documents, summarize content, and store structured results.

Processing every document synchronously inside an upload request would create long response times and increase the risk of request timeouts.

A more reliable architecture separates upload, processing, AI inference, and result delivery.

Proposed architecture

Client
  |
  v
Spring Boot Upload API
  |
  +-- Validate Request
  +-- Store Document in Object Storage
  +-- Save Processing Metadata
  |
  v
Publish DocumentSubmitted Event
  |
  v
Message Broker
  |
  v
Document Processing Workers
  |
  +-- Extract Text
  +-- Validate File Content
  +-- Split into Chunks
  +-- Apply Redaction
  +-- Call Spring AI
  +-- Validate Structured Output
  |
  v
Persist Results
  |
  v
Status API / Notification


Spring Batch
  |
  +-- Bulk Document Import
  +-- Backfill / Reprocessing
  +-- Reconciliation
  +-- Scheduled Cleanup

Step 1: Accept documents asynchronously

The upload API validates file size, type, authorization, and basic metadata. Store large files in object storage rather than keeping their complete contents in application memory.

Persist a processing record with a stable document ID and status such as RECEIVED. Return a response that allows the client to query processing status.

Step 2: Publish work reliably

Use a durable messaging mechanism to notify workers that a document is ready. If saving the document metadata and publishing the event can fail independently, use an outbox or another reliable handoff mechanism.

Step 3: Extract and prepare content

Workers extract text, detect unsupported formats, remove unnecessary sensitive information, and split content into manageable chunks.

Do not assume uploaded documents are trustworthy. Validate file contents, enforce size limits, and isolate potentially dangerous parsers where appropriate.

Step 4: Invoke Spring AI

Use Spring AI to connect to a selected model for classification, extraction, summarization, or question answering. Apply timeouts, concurrency limits, token budgets, and cost controls.

Validate model output before storing it. For example, check that extracted dates, amounts, and identifiers satisfy the application's expected schema and business rules.

Step 5: Use Spring Batch for large-scale workflows

Spring Batch is suitable for bulk imports, scheduled backfills, reprocessing failed documents, reconciling processing statuses, and generating large reports.

Use bounded chunk processing and restartable steps where appropriate. Do not assume that every AI call or external side effect will be rolled back when a batch chunk fails.

Step 6: Make processing idempotent

Assign each document a stable ID and track processing attempts. A duplicate event should not create duplicate business records or repeat an irreversible action.

If a document must be reprocessed with a new prompt or model version, record the processing version explicitly rather than treating it as an accidental duplicate.

Step 7: Monitor and recover

Track queue depth, processing latency, retry counts, dead-letter messages, model usage, token costs, and failure categories. Provide a safe way to retry eligible failures and inspect permanently failed documents.

Interview takeaway: Combine Spring Boot for APIs and orchestration, Spring AI for model integration, Spring Batch for large-scale restartable processing, and asynchronous messaging for decoupled work. Reliability depends on idempotency, observability, security, and explicit failure handling.

Senior Java Interview: Key Takeaways

  • Spring Security processes requests through selected security filter chains.
  • Authentication establishes identity; authorization enforces access permissions.
  • OAuth2 login and JWT resource-server validation solve related but distinct problems.
  • Duplicate filter execution can result from servlet registration, dispatch behavior, or chain configuration.
  • Spring Boot auto-configuration creates beans according to classpath and configuration conditions.
  • @Primary, @Qualifier, and @ConditionalOnMissingBean have different responsibilities.
  • Secure APIs with both endpoint-level rules and resource-level authorization.
  • Spring AI separates higher-level chat interaction from model integration and reusable advisors.
  • AI applications should minimize sensitive prompt data and enforce authorization before retrieval.
  • RAG combines retrieval with generation, but retrieval quality and access controls remain critical.
  • Hallucination risk requires evidence, validation, evaluation, and controlled application logic.
  • LLM integrations need timeouts, bounded retries, concurrency limits, and cost controls.
  • Spring Batch uses jobs, steps, execution metadata, and repository state to support tracking and restartability.
  • Batch restart safety depends on checkpoint design and idempotent side effects.
  • Chunk processing helps bound memory when handling large datasets.
  • Tasklets suit task-based work, while chunk processing suits item pipelines.
  • The transactional outbox helps coordinate database updates and Kafka publication.
  • Production troubleshooting should begin with evidence and measurements.
  • AI document pipelines benefit from asynchronous processing and explicit status tracking.
  • Senior engineers design for failure, recovery, security, and operational visibility—not just the happy path.

Frequently Asked Questions

1. What Spring Security topics are important for senior Java interviews?

Focus on the security filter chain, authentication providers, SecurityContext, authorization rules, OAuth2 resource servers, JWT validation, method security, and debugging unexpected access decisions.

2. What is the difference between OAuth2 login and JWT authentication?

OAuth2 login commonly uses OAuth2 and OpenID Connect flows to establish a user's identity. JWT is a token format that can carry claims and can be validated by a resource server. They are related but are not interchangeable concepts.

3. What is RAG in Spring AI?

Retrieval-Augmented Generation retrieves relevant content from an external knowledge source and supplies it to a language model to help ground the response in available evidence.

4. How does Spring Batch restart a failed job?

Spring Batch persists execution metadata and can resume appropriately configured restartable jobs using saved execution state. Actual restart behavior depends on step configuration, checkpoints, transactions, and the safety of external side effects.

5. How do you prevent duplicate database updates and Kafka events?

The transactional outbox pattern records the business update and an event record in the same database transaction. A publisher then delivers the event, while idempotent consumers prevent duplicate business effects.

6. How should AI calls be handled in production?

Use explicit timeouts, bounded concurrency, selective retries, token budgets, cost monitoring, data-protection controls, and clear fallback behavior when the model provider is unavailable.

Conclusion

Senior Java developers are not defined by how many annotations they know. They are defined by how well they understand application internals, security boundaries, distributed workflows, scalability, and production failure modes.

Understanding a security annotation is useful, but diagnosing an incorrect filter chain is more valuable. Knowing how to call an LLM is useful, but protecting sensitive information and controlling production costs is more valuable. Knowing how to configure a batch job is useful, but ensuring that a restart does not duplicate a business operation is what protects real systems.

The strongest interview answers explain how a mechanism works, why a failure occurs, how to diagnose it, how to recover safely, and what trade-offs the solution introduces.

Which question would you find the hardest?

Explore More Java Interview Resources

Java Spring Boot & Microservices Interview Q&A (200 Questions)
https://lnkd.in/gqhJhmcZ

Full Interview Kit (600 Questions)
Java, Spring Boot, database, DevOps, cloud, system design, and microservices.
https://lnkd.in/gPi2W587

Complete Java Full Stack Developer Kit (900 Questions)
Core Java, Spring Boot, microservices, cloud, DevOps, system design, React, and Angular.
https://topmate.io/logicbrace/2306382

Senior Java and Spring Boot Interview Questions – Top 20 Part 6 covering Spring Security, Spring AI, Spring Batch, and microservices.

Post a Comment

0 Comments

Close Menu