Interview Practice

Theory then practice

Spring Boot

Injection, HTTP, transactions, testing and production behavior.

Theory chapters

Prerequisites: Java interfaces, exceptions, HTTP basics and relational database concepts.

  1. Chapter 1Spring container, injection and auto-configuration

    Understand how an application is assembled before using annotations.

  2. Chapter 2HTTP boundaries, validation and security

    Keep transport contracts clear while enforcing rules on the server.

  3. Chapter 3Transactions, JPA queries and concurrent updates

    Make consistency and database work visible.

  4. Chapter 4Testing, resilience and production operation

    Verify actual boundaries and keep failure behavior bounded.

  5. Chapter 5Events, messaging and idempotent consumers

    Publish and consume events without losing, duplicating or reordering business effects.

Interview questions

Try answering aloud before opening an answer. Reading an answer is exposure, not proof of independent mastery. Save reflections in your mistake notebook.

20 of 20 questions

Beginner

What does Spring Boot add to Spring?

Reveal answer and example

Spring supplies dependency injection and application infrastructure. Boot adds opinionated auto-configuration, starters and operational conventions to reduce setup; it still uses Spring's container and APIs.

Example: A web starter and matching classpath can configure a web application without manually wiring every infrastructure bean.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Boot is not a replacement for understanding bean lifecycles or application configuration.

Follow-up: How would you inspect why an auto-configuration matched?

Beginner

Why prefer constructor injection?

Reveal answer and example

Constructor injection declares required dependencies, supports straightforward unit testing and allows final fields. It also makes an excessive number of dependencies visible as a design smell.

Example: Construct OrderService with an OrderRepository interface and a PaymentGateway.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Field injection hides required collaborators and makes plain unit construction awkward.

Follow-up: What would a circular constructor dependency tell you about the design?

Beginner

What is a bean scope and is singleton thread-safe?

Reveal answer and example

A singleton is normally one instance per bean definition per container. It says nothing about thread safety: request-specific mutable state should not be kept in an unprotected singleton field.

Example: A stateless service can be shared; a currentCustomer field in that service can mix requests.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Singleton does not mean one object across every process or every application context.

Follow-up: How would a request-scoped dependency be used from a singleton?

Intermediate

How does auto-configuration back off?

Reveal answer and example

Boot uses conditions on classpath, properties, application type and existing beans. User configuration can supply a bean that causes a conditional default to back off; inspect the condition report rather than guessing.

Example: Defining a supported custom bean can replace an infrastructure default when its condition permits.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: A starter is a dependency bundle, not a guarantee that every related bean will be created.

Follow-up: How would you test a custom conditional auto-configuration?

Intermediate

How should you manage configuration and secrets?

Reveal answer and example

Bind related settings into validated ConfigurationProperties objects and understand property-source precedence. Supply secrets through deployment secret mechanisms and avoid committing or logging them.

Example: Fail startup when a required endpoint or timeout is invalid.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: A profile name is not a security boundary; accidentally enabled diagnostics can still expose data.

Follow-up: How would you validate production configuration before rollout?

Beginner

How do you design a clear REST controller?

Reveal answer and example

Keep transport parsing and response mapping in the controller, with business rules in application/domain services. Validate input, use appropriate status codes and document stable error shapes.

Example: POST an order and return its identifier and Location when a new resource is created.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Returning HTTP 200 for every failure forces clients to infer errors from ambiguous bodies.

Follow-up: How do you distinguish malformed input from a business conflict?

Beginner

How do profiles and externalized configuration work?

Reveal answer and example

Spring Boot reads properties from many sources with a defined precedence: command-line arguments and environment variables override application.yml, and profile-specific files such as application-prod.yml override the base file when that profile is active. @ConfigurationProperties binds a prefix into a typed, validatable object, which is preferable to scattering @Value annotations.

Example: SPRING_PROFILES_ACTIVE=prod with SPRING_DATASOURCE_URL supplied by the deployment environment, not committed to the repository.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Encoding environment behavior in code with if (profile == prod) instead of configuration, or committing secrets to profile files.

Follow-up: How would you fail application startup if a required property is missing or invalid?

Beginner

What does Spring Boot Actuator provide?

Reveal answer and example

Actuator adds operational endpoints such as health, info, metrics and readiness or liveness probes, and integrates Micrometer for metrics export to systems such as Prometheus. Health aggregates indicators for databases, disks and custom dependencies. Most endpoints are not exposed over HTTP by default, and exposed ones should be secured.

Example: Kubernetes uses /actuator/health/readiness to stop routing traffic while a pod warms up, and /actuator/health/liveness to restart a stuck one.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Exposing every endpoint publicly, including env or heapdump, which can leak configuration and memory contents.

Follow-up: Should a slow downstream dependency make liveness fail? Why or why not?

Intermediate

Where should validation happen?

Reveal answer and example

Validate request shape and constraints at the boundary, enforce domain invariants in the domain/service layer, and use database constraints for concurrent integrity. Map failures through consistent exception handling.

Example: Validate a positive quantity, then atomically enforce inventory availability in storage.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: A pre-check alone cannot prevent two concurrent requests from violating uniqueness.

Follow-up: How would cross-field validation differ from field-level annotations?

Intermediate

What does Transactional actually intercept?

Reveal answer and example

With the usual proxy mode, an external call through the proxy gets transaction advice. A method calling another annotated method on the same instance bypasses that proxy; place the boundary deliberately or use an appropriate explicit mechanism.

Example: Move the transactional operation into a separate collaborator invoked through its bean proxy.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: By default RuntimeException and Error trigger rollback; checked exceptions need suitable rollback rules unless defaults are customized.

Follow-up: How would you prove rollback with an integration test?

Advanced

REQUIRED versus REQUIRES_NEW: what changes?

Reveal answer and example

REQUIRED joins an existing transaction or creates one. REQUIRES_NEW suspends the outer transaction and uses an independent transaction, usually needing another connection; its commit survives a later outer rollback.

Example: An independent audit write may need a deliberately separate transaction and failure policy.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: An inner rollback-only mark can cause the outer REQUIRED commit to fail unexpectedly.

Follow-up: What happens if all pool connections are held by outer transactions?

Intermediate

How do you detect and fix an N+1 query problem?

Reveal answer and example

Inspect query counts for representative requests. Fetch associations deliberately with joins, entity graphs, batching or DTO queries; choose based on cardinality and pagination requirements.

Example: Loading 50 orders and then each customer's data may issue many extra queries.

Common mistake: Making every association eager can increase work and does not guarantee one efficient SQL query.

Follow-up: Why can collection fetch joins complicate pagination?

Advanced

How do you prevent lost updates?

Reveal answer and example

Optimistic locking uses a version check and detects stale writes; pessimistic locking reserves database locks and can block competitors. Choose based on contention and transaction duration.

Example: A versioned inventory update fails when another transaction has already changed that version.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Blindly retrying a payment after a version conflict can duplicate external side effects.

Follow-up: How would you bound retries and handle a conflict for the caller?

Intermediate

How do authentication and authorization differ?

Reveal answer and example

Authentication establishes identity; authorization decides what that identity may do. Apply server-side checks to routes and business operations, validate tokens correctly and keep browser-specific CSRF assumptions explicit.

Example: A valid token for user A must not allow reading user B's order.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: CORS is not authentication, and hiding a button does not authorize the API.

Follow-up: How would cookie-based sessions change CSRF protection needs?

Intermediate

Unit test, WebMvcTest or SpringBootTest?

Reveal answer and example

Use plain unit tests for isolated logic, a web slice for controller mapping/validation/security behavior, and a full application context for integration wiring. Use realistic database integration tests when SQL behavior matters.

Example: A service unit test need not start the container; a rollback test should exercise the real transactional boundary.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Mocking the repository cannot prove database constraints, query correctness or rollback semantics.

Follow-up: Which behavior requires a real external dependency instead of a mock?

Intermediate

What is the N+1 query problem in JPA and how do you fix it?

Reveal answer and example

Loading N parent entities and then touching a lazy association on each triggers one query for the parents plus one per parent. Fix it by fetching what the use case needs in one query: a JOIN FETCH, an @EntityGraph, batch fetching with hibernate.default_batch_fetch_size, or a DTO projection. Detect it by logging SQL or counting statements in tests.

Example: Listing 50 orders with their customer names issues 51 queries; @EntityGraph(attributePaths = "customer") reduces it to one.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Switching associations to EAGER globally; it moves the problem to every other query and can cause cartesian products.

Follow-up: Why does JOIN FETCH with pagination over a collection association produce a warning or in-memory paging?

Advanced

How do timeouts, retries and idempotency fit together?

Reveal answer and example

Assign a total deadline, bound each dependency call and retry only transient failures within that budget. Backoff with jitter reduces synchronized retries; idempotency prevents repeated business effects.

Example: Store an idempotency key and result for a payment request, with a defined retention period.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Retries at every layer multiply traffic and can worsen an outage.

Follow-up: How do you handle a timeout when the remote side may have committed?

Advanced

What makes a Boot application production-ready?

Reveal answer and example

Expose appropriately secured health and metrics, distinguish readiness from liveness, propagate trace context and design graceful shutdown. Observe latency, errors and saturation with bounded-cardinality labels.

Example: Stop accepting new work before terminating while giving in-flight requests a bounded drain period.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: An unrestricted actuator endpoint or user IDs as metric labels can create operational and security problems.

Follow-up: When should a database outage affect readiness but not liveness?

Advanced

How do you reliably publish an event when a database row changes?

Reveal answer and example

Write the business row and an outbox row in the same local transaction. A separate relay, either a poller or change-data-capture such as Debezium, publishes committed outbox rows to the broker and marks them sent. This removes the dual-write gap between database and broker; delivery becomes at least once, so consumers must be idempotent.

Example: OrderService saves Order and OutboxEvent(type=OrderPlaced, payload, aggregateId) together; the relay publishes keyed by aggregateId to keep per-order ordering.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Publishing to Kafka inside the @Transactional method, which can send events for transactions that later roll back.

Follow-up: How would you clean up the outbox table and monitor relay lag?

Advanced

How do you make a POST endpoint idempotent?

Reveal answer and example

Require an Idempotency-Key header. Store the key with a request fingerprint and the response in the same transaction as the business effect, protected by a unique constraint. A retry with the same key and body returns the stored response; the same key with a different body is rejected. Concurrent duplicates are serialized by the unique insert.

Example: A mobile client retries POST /payments after a timeout with the same key and receives the original 201 response instead of a second charge.

Big O is not intrinsic to this conceptual question. Define the implementation, input size and operation before assigning a complexity.

Common mistake: Checking for the key and then inserting in two steps without a constraint, letting two concurrent retries both pass the check.

Follow-up: How long should keys be retained, and what status do you return while the first request is still in progress?

Reference documentation