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.
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:
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.
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:
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.
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:
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:
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.
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:
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:
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.
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:
--debug, in an appropriate environment.@Import declarations.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.
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.
A secure API should enforce both broad access rules and resource-level business authorization.
For example:
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:
Interview takeaway: Role-based rules protect endpoint categories, while resource-based authorization protects individual business objects.
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:
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.
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:
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.
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.
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:
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.
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.
Spring Batch provides infrastructure for defining and executing batch workflows with persistent execution metadata, restart support, and operational visibility.
The main concepts are:
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.
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:
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.
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.
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.
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.
A common failure occurs when a service performs two operations independently:
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.
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:
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.
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.
Determine whether time is spent in the application, database, external API, message broker, or another microservice.
Compare JVM options, active Spring profiles, timeouts, connection-pool settings, Kubernetes resource limits, secrets, and dependency versions.
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.
Examples include optimizing a slow query, reducing excessive concurrency, fixing a thread leak, correcting a timeout, or limiting an unbounded queue.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
Focus on the security filter chain, authentication providers, SecurityContext, authorization rules, OAuth2 resource servers, JWT validation, method security, and debugging unexpected access decisions.
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.
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.
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.
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.
Use explicit timeouts, bounded concurrency, selective retries, token budgets, cost monitoring, data-protection controls, and clear fallback behavior when the model provider is unavailable.
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?
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
0 Comments