🍃

Spring Boot & Microservices

Spring Boot core, dependency injection, REST APIs, JPA/Hibernate, transactions, Spring Security, and the microservices patterns — service discovery, API gateway, resilience, messaging — that hold a distributed system together.

Spring Boot Internals

Q

How does Spring Boot auto-configuration work internally (@EnableAutoConfiguration)?

advanced

@EnableAutoConfiguration (bundled inside @SpringBootApplication) triggers Spring to read META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports — a list of candidate auto-configuration classes each starter ships. Every candidate is guarded by @Conditional annotations (@ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty), so only the configurations whose conditions actually match your classpath and existing beans get activated — which is also exactly why defining your own bean of the same type silently overrides the auto-configured one.

Q

What's the difference between BeanFactoryPostProcessor and BeanPostProcessor?

intermediate

A BeanFactoryPostProcessor runs BEFORE any bean is instantiated, operating on bean DEFINITIONS (metadata) — PropertySourcesPlaceholderConfigurer, which resolves ${...} placeholders, is a classic example. A BeanPostProcessor runs AFTER each bean is instantiated, wrapping its initialization via postProcessBeforeInitialization()/postProcessAfterInitialization() — this is exactly how AOP proxies for @Transactional and @Cacheable get created, by replacing the raw bean instance with a proxy during this phase.

Q

When should you use @Lazy, and what are its trade-offs?

intermediate

Use @Lazy when a bean is expensive to create but rarely actually used, deferring its cost until the first real request for it, or to break specific circular-dependency deadlocks where eager initialization would otherwise fail. The trade-off: lazy beans move a configuration failure from a predictable, fail-fast point at application startup to an unpredictable point during request handling — most teams reserve @Lazy for genuinely optional or costly beans rather than applying it broadly, since it trades startup safety for startup speed.

Q

What happens internally during the Spring Boot application startup lifecycle?

advanced

SpringApplication.run() first prepares the Environment (property sources, active profiles), creates the appropriate ApplicationContext type, and invokes any registered ApplicationContextInitializers. It then calls context.refresh(), which loads all bean definitions, runs BeanFactoryPostProcessors, registers BeanPostProcessors, instantiates every singleton bean (triggering auto-configuration's conditional evaluation along the way), and publishes a ContextRefreshedEvent — finally, any ApplicationRunner/CommandLineRunner beans execute before the application is considered fully started.

Q

What's the difference between ApplicationContextInitializer, ApplicationRunner, and CommandLineRunner?

intermediate

ApplicationContextInitializer runs very early, BEFORE the context is refreshed — used to programmatically customize the context (e.g. adding property sources) before any bean exists yet. ApplicationRunner and CommandLineRunner both run AFTER the context is fully started with every bean ready, differing only in how they receive command-line arguments: CommandLineRunner gets a raw String[] array, while ApplicationRunner gets a parsed ApplicationArguments object with named-option support (e.g. --name=value).

Q

How does Spring Boot Actuator expose metrics, and how would you secure them in production?

intermediate

Actuator's /actuator/metrics endpoint is backed by Micrometer, a vendor-neutral metrics facade that Actuator auto-configures to collect JVM, HTTP request, and custom application metrics, which can then be exported to Prometheus, Datadog, or similar monitoring backends. In production, sensitive endpoints (env, heapdump, shutdown) should never be left publicly exposed — restrict what's exposed via management.endpoints.web.exposure.include, move actuator to a separate management port, and secure it with Spring Security rather than relying on obscurity.

Q

What does @SpringBootApplication do, and which annotations does it combine?

intermediate

Tests whether you can name the three it bundles -- @Configuration (marks it as a bean-definition source), @EnableAutoConfiguration (triggers condition-based auto-config), and @ComponentScan (scans the package and below) -- rather than treating it as one opaque magic annotation.

Q

How does Spring Boot auto-configuration work? How does @EnableAutoConfiguration work internally?

intermediate

Tests whether you know it works via spring.factories/AutoConfiguration.imports listing candidate @Configuration classes, each guarded by @Conditional annotations (ConditionalOnClass, ConditionalOnMissingBean) that only activate the config if the right classes/beans are present on the classpath.

Q

Explain the Spring bean lifecycle.

intermediate

Tests whether you can sequence it correctly: instantiation, dependency injection, BeanPostProcessor pre-initialization, @PostConstruct/InitializingBean, the bean's ready-to-use phase, and finally @PreDestroy/DisposableBean on container shutdown -- the ordering, not just the hook names.

Q

Two beans need each other through constructor injection. What does Spring Boot 3 do at startup?

advanced

Tests whether you know constructor-based circular dependencies cannot be resolved (unlike setter/field injection, which could defer injection) -- Spring Boot 3 fails fast at startup with a BeanCurrentlyInCreationException rather than silently working around it.

Q

500 outbound HTTP calls per second: RestTemplate or WebClient, and what breaks with the other?

advanced

Tests whether you pick WebClient -- RestTemplate is blocking and synchronous, so at 500 calls/sec each held thread ties up a pool slot until the downstream responds, exhausting the thread pool; WebClient's non-blocking, event-loop model handles that concurrency on a handful of threads.

SQL Query & Schema Design

Q

Table1 has 10 rows, Table2 has 20 rows -- what does `SELECT * FROM table1, table2` return? Now delete 10 rows from table1 -- what is the expected count?

intermediate

Tests whether you recognize the comma join as an implicit CROSS JOIN producing a Cartesian product (200 rows), and that the row count scales with whichever table still has rows, not a fixed delta.

Q

How do you store passwords in the database?

intermediate

Tests whether you know passwords must be hashed with a slow, salted algorithm like bcrypt/Argon2 rather than encrypted or stored as a fast general-purpose hash like SHA-256.

Q

How do you choose SQL vs NoSQL for wallets, transactions & audit logs?

advanced

Tests whether you reach for a relational, ACID-compliant store for wallet balances and transactions (where strong consistency is non-negotiable) while recognizing audit logs are append-only and can tolerate a more horizontally-scalable, eventually-consistent store.

Q

Count employees department-wise (SQL)

intermediate

Tests whether you reach for GROUP BY on department_id with COUNT(*), and whether you remember to LEFT JOIN against the departments table so departments with zero employees aren't silently dropped.

Q

HLD: design a food-delivery homepage feed -- geohashing, schema design, SQL vs NoSQL trade-offs

advanced

Tests whether you reach for geospatial indexing (geohash buckets or a quadtree) to avoid scanning all restaurants by distance, and can justify a denormalized read-optimized schema over a normalized relational one for a feed that's read far more than written.

Q

What is the difference between LEFT JOIN and RIGHT JOIN? When do you use LEFT JOIN?

intermediate

Tests whether you understand both preserve the unmatched side of one table with NULLs for the other, and that LEFT JOIN is favored by convention because query authors read left-to-right from the table they care most about.

Q

Departments with zero employees query

intermediate

Tests whether you reach for a LEFT JOIN with a NULL check (or NOT EXISTS) on the employee side rather than an INNER JOIN, which would silently exclude the exact rows the question is asking for.

Q

Find duplicate rows (SQL)

intermediate

Tests whether you reach for GROUP BY on the candidate columns with HAVING COUNT(*) > 1, rather than a self-join, as the efficient way to surface duplicates.

Q

Write a SQL query to find the first name of the employee having the highest bonus (two tables given)

intermediate

Tests whether you join the two tables correctly and use ORDER BY bonus DESC LIMIT 1 (or a subquery with MAX()) rather than assuming the first row returned is naturally the highest.

Q

Is PostgreSQL SQL or NoSQL?

intermediate

Tests whether you know PostgreSQL is fundamentally relational but also a genuine hybrid, supporting JSONB columns with indexing that lets it serve many NoSQL-style document use cases without leaving ACID guarantees behind.

Q

What is InnoDB in MySQL?

intermediate

Tests whether you know InnoDB is MySQL's default storage engine, providing row-level locking, foreign keys, and crash-recovery via a transaction log -- unlike the older MyISAM engine it replaced.

Q

What is the difference between UNION and UNION ALL?

intermediate

Tests whether you know UNION implicitly deduplicates (forcing a sort/hash pass) while UNION ALL just concatenates results, and that you should default to UNION ALL unless you specifically need duplicates removed.

Q

How do you handle NULL values and conditional mapping in SQL, e.g. mapping values like A to Apple, B to Banana?

intermediate

Tests whether you reach for CASE WHEN (or COALESCE for defaults) to express conditional mapping declaratively, and know that NULL never equals NULL so comparisons need IS NULL rather than = NULL.

Q

How do you remove duplicates in SQL?

intermediate

Tests whether you know the difference between deleting duplicate rows (using a window function like ROW_NUMBER() partitioned by the duplicate key to isolate the rows to delete) versus just deduplicating a SELECT with DISTINCT.

Q

Explain joins and their use cases

intermediate

Tests whether you can map each join type to the shape of the question it answers -- INNER for matched pairs only, LEFT/RIGHT for preserving one side, FULL OUTER for the union of both, and CROSS for deliberate Cartesian products.

REST Fundamentals

Q

What is a REST API, and what are its core architectural constraints?

beginner

REST (Representational State Transfer) is an architectural style for designing networked APIs around resources identified by URIs. Its core constraints are: client-server separation, statelessness (each request contains everything needed to process it), cacheability, a uniform interface (standard HTTP verbs acting on resources), a layered system, and optionally code-on-demand — together these make REST APIs scalable, simple to reason about, and independently evolvable on client and server sides.

Q

What is a resource, a sub-resource, and a URI in REST API design?

beginner

A resource is any entity a client can interact with — a user, an order, a product — identified by a unique URI like /users/42. A sub-resource represents something that only exists in relation to a parent resource, expressed as a nested path, e.g. /users/42/orders for the orders belonging to user 42. The URI itself is the resource's address; well-designed REST APIs use nouns in URIs (resources) and HTTP verbs (actions) rather than encoding actions into the URI path.

Q

What are the main HTTP methods used in REST APIs, and what does each represent?

beginner

GET retrieves a resource without side effects (safe and idempotent); POST creates a new resource or triggers a non-idempotent action; PUT replaces an entire resource with the given representation (idempotent — calling it twice with the same body has the same effect as once); DELETE removes a resource (idempotent). Correctly matching intent to verb is what makes an API behave predictably for clients, caches, and retry logic.

Q

What is the difference between HTTP and HTTPS?

beginner

HTTP transmits data in plain text over the network, meaning anyone intercepting the traffic (a man-in-the-middle) can read or tamper with it. HTTPS wraps HTTP inside TLS, encrypting the data in transit and verifying the server's identity via a certificate — it's the mandatory baseline for any API handling credentials, tokens, or personal data.

Q

What is the difference between GET and POST in a REST API?

beginner

GET requests data and should never change server state — it's safe, idempotent, cacheable, and its parameters typically appear in the URL query string, which limits length and exposes them in logs/browser history. POST sends data in the request body to create a resource or trigger an action, is not idempotent (calling it twice may create two resources), and is not cached by default.

Q

What is the difference between POST and PUT in a REST API?

beginner

POST is used to create a new resource, and the server typically decides the new resource's identifier — calling it repeatedly with the same body creates multiple resources (not idempotent). PUT is used to replace an entire existing resource at a known URI, and calling it repeatedly with the same body produces the same end state (idempotent) — if the resource doesn't exist yet, some APIs treat PUT as an upsert.

Q

What is the difference between PUT and PATCH in a REST API?

beginner

PUT replaces the ENTIRE resource with the representation you send — any field you omit is typically treated as cleared/reset. PATCH applies a PARTIAL update, sending only the fields that actually changed, leaving everything else untouched — PATCH is the right choice when a client only wants to modify one or two fields without resending the whole object.

Q

What is the difference between REST and SOAP?

beginner

REST is an architectural style built on standard HTTP, using lightweight JSON/XML payloads and standard HTTP verbs/status codes — simple, cacheable, and the default choice for most modern web/mobile APIs. SOAP is a strict, XML-based protocol with a formal contract (WSDL), built-in security/transaction standards (WS-Security, WS-AtomicTransaction), and works over multiple transports beyond HTTP — it's heavier but still used in enterprise/financial systems that need those formal guarantees.

HikariCP & Connection Pool

Spring Boot Core

Q

What is Spring Boot and how is it different from the Spring Framework?

beginner

Tests whether you know Spring Boot is an opinionated, auto-configured layer on top of Spring, not a replacement for it.

Q

What does @SpringBootApplication do? What 3 annotations does it combine?

beginner

Tests whether you know this one annotation is really @Configuration + @EnableAutoConfiguration + @ComponentScan bundled together.

Q

What is Spring Actuator? Name 5 important endpoints it exposes.

intermediate

Tests whether you know how to expose health, metrics, and diagnostic data for a production Spring Boot application.

Q

How does Spring Boot handle multiple environments (dev, QA, prod) using profiles?

intermediate

Tests whether you know how to structure environment-specific configuration cleanly using @Profile and profile-specific property files.

Q

Why can @Async fail to execute asynchronously, and how do you fix it?

intermediate

@Async relies on an AOP proxy — calling the method from within the same class (self-invocation) bypasses the proxy and runs synchronously on the calling thread. Fix by calling it through an injected reference to the bean (from a different class) instead of `this`.

Q

Your Spring Boot application takes 60+ seconds to start — how do you optimize it?

advanced

Profile startup with `--debug` and Spring Boot's built-in startup tracking (ApplicationStartup/Micrometer), then look for slow auto-configurations, excessive component scanning scope, eager bean initialization that could be @Lazy, and heavy @PostConstruct work — often it's a small number of specific beans, not Spring itself, causing most of the delay.

Q

How do you process millions of records efficiently using Spring Batch?

advanced

Spring Batch structures work into Jobs made of Steps, each with a chunk-oriented ItemReader → ItemProcessor → ItemWriter pipeline that commits in configurable chunk sizes (not one giant transaction). Use partitioning or multi-threaded steps to parallelize across large datasets, and a JobRepository to track progress and support safe restarts after failure.

Q

How do you implement multi-tenancy in Spring Boot?

advanced

Three common strategies: a shared schema with a tenant_id column filtered on every query (cheapest, needs discipline or a Hibernate filter to enforce), a schema-per-tenant (moderate isolation), or a database-per-tenant (strongest isolation, most operational overhead) — resolved per-request via a tenant-identifying header/subdomain and a routing DataSource or Hibernate multi-tenancy config.

Q

How would you design an audit logging system for every database change?

advanced

For simple field-level tracking, Spring Data's @CreatedDate/@LastModifiedDate/@CreatedBy/@LastModifiedBy with @EnableJpaAuditing cover who/when. For a full change history, use Hibernate Envers (automatic revision tables) or write changes to a separate audit_log table inside the same transaction as the business write, capturing old/new values and the acting user.

OAuth & Identity Protocols

Database Transactions & Locking

Dependency Injection & Core

Spring MVC vs WebFlux vs Virtual Threads

DI & IoC Internals

Q

Dependency Inversion vs Dependency Injection?

intermediate

Tests whether you can separate the principle from the mechanism -- Dependency Inversion is the design rule that high-level modules depend on abstractions, Dependency Injection is just one technique (constructor/setter wiring) Spring uses to satisfy it.

Q

What is the difference between constructor injection and setter injection?

intermediate

Tests whether you know constructor injection enforces immutability and makes required dependencies impossible to forget, while setter injection allows optional dependencies and reconfiguration after construction -- and that Spring itself recommends constructor injection by default.

Q

How does Spring resolve autowiring when multiple beans of the same type exist?

intermediate

Tests whether you know Spring's resolution order -- a single @Primary bean wins, then a matching @Qualifier name, then a parameter name match -- before it gives up and throws NoUniqueBeanDefinitionException.

Q

Can Spring create a bean without calling its constructor in the normal way? When could this matter?

advanced

Tests whether you know CGLIB proxies can be instantiated via Objenesis, which allocates the object and bypasses the constructor entirely -- relevant when a proxied class's constructor has side effects you don't want running twice.

Q

Why can adding @Transactional change the actual object type returned by Spring?

advanced

Tests whether you know @Transactional triggers Spring to wrap the bean in a CGLIB subclass or JDK dynamic proxy, so getClass() on the injected reference no longer matches the original class -- which breaks naive instanceof or reflection-based code.

Q

Can two beans have the same name?

intermediate

Tests whether you know bean names must be unique within the ApplicationContext -- a duplicate name either overrides the earlier definition (if allowed) or throws a BeanDefinitionStoreException, depending on the registration order and overriding configuration.

Q

How do you exclude auto-configuration for a specific class?

intermediate

Tests whether you know to use @SpringBootApplication(exclude = ...) or the spring.autoconfigure.exclude property to suppress a specific auto-configuration class, rather than removing the dependency or disabling auto-config entirely.

Q

Can a class with a private constructor be used to create a Spring Bean?

advanced

Tests whether you know Spring can still instantiate a bean with a private constructor by calling setAccessible(true) via reflection, so encapsulation alone doesn't stop it -- though it signals the class wasn't designed to be a managed bean.

Q

What happens if you do not use @Autowired in Spring? How do you perform constructor injection without it?

intermediate

Tests whether you know Spring 4.3+ implicitly autowires a class's single constructor without needing @Autowired at all, and that the annotation only becomes mandatory once there's more than one candidate constructor.

Q

How is EJB different from Spring-managed components?

intermediate

Tests whether you can name the real difference -- EJB required a full Java EE container and heavyweight remote/local interfaces, while Spring beans are POJOs managed by a lightweight IoC container with no mandatory application server.

Spring Fundamentals

Q

What is the Spring IoC (Inversion of Control) Container?

beginner

The IoC container is the core of the Spring Framework — it's responsible for instantiating, configuring, and managing the complete lifecycle of application objects (beans), based on configuration metadata (annotations or XML). Instead of your code creating its own dependencies with `new`, you declare what a class needs and the container 'inverts control' by injecting them for you, which is the foundation Spring's dependency injection is built on.

Q

What is a Spring Bean?

beginner

A Spring Bean is simply an object that's instantiated, assembled, and managed by the Spring IoC container, rather than being created directly by application code with `new`. Any class annotated with @Component (or its specializations @Service/@Repository/@Controller) or declared via an @Bean method in a @Configuration class becomes a bean, making it eligible for dependency injection anywhere else in the application.

Q

What is the default scope of a Spring Bean, and what other scopes are available?

beginner

The default scope is singleton — the container creates exactly one shared instance of the bean for the entire application context, and every injection point receives that same instance. Other scopes include prototype (a new instance every time the bean is requested), and web-specific scopes like request and session that tie a bean's lifetime to an HTTP request or session.

Q

What is the difference between BeanFactory and ApplicationContext in Spring?

beginner

BeanFactory is the most basic container interface, providing lazy initialization (beans are created only when first requested) and the fundamental DI capability. ApplicationContext extends BeanFactory and adds enterprise features on top — eager singleton initialization at startup, event publishing, internationalization support, and easier integration with Spring AOP — which is why virtually every real Spring/Spring Boot application uses ApplicationContext rather than BeanFactory directly.

Spring MVC & Web

REST API Design

Q

What is HATEOAS and when would you use it?

advanced

Tests whether you understand HATEOAS means the response embeds the next valid actions as links so clients discover state transitions dynamically instead of hardcoding URLs -- and whether you can admit it's rarely worth the complexity outside public hypermedia APIs.

Q

What is the Richardson Maturity Model?

advanced

Tests whether you know the four levels -- plain RPC-over-HTTP, resources, HTTP verbs, and HATEOAS -- and can place your own APIs honestly on that scale instead of claiming 'full REST' for anything that returns JSON over HTTP.

Q

What functional and non-functional requirements would you clarify before developing a new REST API?

intermediate

Tests whether you'd probe for non-functional requirements -- expected throughput, latency SLA, auth model, idempotency needs, versioning strategy -- rather than jumping straight to endpoint design from the functional spec alone.

Q

Pros/cons of URI, query-parameter, header-based, and media-type versioning?

intermediate

Tests whether you can weigh the real trade-offs -- URI versioning is simplest but pollutes the resource identity, header/media-type versioning keeps URLs clean but is harder to test and cache, and you know which one plays well with HTTP caching and client tooling.

Q

How would you prevent an API response from accidentally exposing fields added to an entity later?

intermediate

Tests whether you default to explicit DTOs/response projections instead of serializing entities directly, since a new entity field otherwise gets exposed automatically the moment someone adds it, with no compile-time warning.

Q

Can PUT be used instead of DELETE?

intermediate

Tests whether you know PUT's idempotent full-replace semantics can model a soft delete (replacing a resource with a 'deleted' state) but can't replace DELETE's actual intent to remove the resource -- and that reusing PUT this way confuses API consumers.

Connection Pooling & Performance

Spring Boot Fundamentals

Q

What are Spring Boot Starters, and why do they exist?

beginner

Starters are curated dependency bundles — e.g. spring-boot-starter-web pulls in Spring MVC, an embedded Tomcat, and Jackson for JSON, all with versions that are known to work together. They exist to eliminate the manual, error-prone work of figuring out and aligning individual library versions for a common use case, letting you add one dependency instead of a dozen.

Q

What is spring-boot-starter-parent, and what does it provide?

beginner

It's a special parent POM that a Spring Boot Maven project inherits from, which centrally manages dependency versions (via a Bill of Materials), sensible default plugin configurations (like the Spring Boot Maven plugin for building executable JARs), and default Java/encoding settings — so individual dependencies in your own pom.xml don't need explicit version numbers, avoiding version-mismatch issues.

Q

What embedded servers does Spring Boot support, and how do you change the default?

beginner

Spring Boot ships with embedded Tomcat by default (via spring-boot-starter-web), and also supports Jetty and Undertow. To switch, exclude the default Tomcat starter dependency and add the starter for the server you want instead (e.g. spring-boot-starter-undertow) — the embedded-server model means the application itself is a runnable JAR with the server built in, rather than a WAR deployed into an externally-installed server.

Q

What is Spring Boot DevTools, and what does it do during development?

beginner

DevTools is a development-time-only dependency that speeds up the local feedback loop: it automatically restarts the application when it detects a classpath change (faster than a full manual restart, since it uses two classloaders and only reloads your own classes), enables LiveReload for the browser, and applies development-friendly default property overrides. It's automatically excluded from a production build/JAR, so it never adds overhead in a deployed environment.

Q

@Component vs @Service vs @Repository.

intermediate

Tests whether you know all three are functionally identical stereotypes of @Component (same bean registration behavior) that differ only in semantic intent and, for @Repository specifically, in triggering automatic persistence-exception translation into Spring's DataAccessException hierarchy.

Q

@Bean vs @Component.

intermediate

Tests whether you know @Component is a class-level annotation picked up by component scanning (for classes you own), while @Bean is a method-level annotation inside a @Configuration class used to register beans you don't control the source of, like third-party library classes.

Q

What is Dependency Injection? Explain IoC, the types of DI, and constructor vs field injection (which is preferred and why).

intermediate

Tests whether you argue for constructor injection -- it makes dependencies explicit and immutable (final fields), fails fast at startup if a dependency is missing, and makes the class testable without reflection, unlike field injection which hides the dependency graph and requires a DI framework even for unit tests.

Q

What are Spring Profiles and why are they used?

intermediate

Tests whether you describe profiles as a mechanism to activate environment-specific beans/configuration (dev, test, prod) at startup via spring.profiles.active, so the same codebase can swap datasources, logging levels, or mocked beans per environment without code changes.

Q

How do you handle exceptions globally in Spring Boot?

intermediate

Tests whether you reach for @RestControllerAdvice combined with @ExceptionHandler methods to centralize error-to-HTTP-status mapping in one place, instead of scattering try/catch blocks across every controller.

Q

How do you build a REST API in Spring Boot?

intermediate

Tests whether you describe the layered flow -- @RestController exposing endpoints, DTOs for request/response shaping (decoupled from entities), a service layer for business logic, and proper status codes/validation -- not just slapping @RequestMapping on a repository.

Kafka: Producer, Consumer & Idempotency

Q

How do you achieve Kafka producer idempotency and exactly-once processing?

advanced

Tests whether you know enable.idempotence alone only prevents duplicate writes at the broker, not end-to-end exactly-once.

Q

A database update succeeds, but publishing the corresponding Kafka event fails. How do you maintain consistency?

advanced

Tests whether you know this is the classic dual-write problem, and that the Outbox Pattern is the real fix, not a retry loop.

Q

What happens if a Kafka consumer processes a message successfully but crashes before committing the offset?

advanced

Tests whether you know the message will be redelivered, which is exactly why consumer-side idempotency is non-negotiable.

Q

Kafka consumer lag suddenly spikes in production. What do you check first?

advanced

Tests whether you know to check for GC pauses freezing poll(), slow downstream calls in the consumer, or an actual rebalance loop.

Q

One Kafka partition is overloaded while others sit idle. What could cause this?

advanced

Tests whether you know a poorly chosen partition key (like a low-cardinality field) creates a hot partition.

Q

Why do Kafka consumer groups keep rebalancing every few minutes, and how do you minimize the disruption?

advanced

Tests whether you know session timeouts, slow processing exceeding max.poll.interval.ms, and static membership all factor in.

Q

You have 10 consumers in a group but only 3 Kafka partitions. How many consumers actually process messages?

intermediate

Tests whether you know partition count is a hard ceiling on consumer parallelism within a group — the extra 7 sit idle.

Q

A Kafka message reaches the Dead Letter Topic. How do you safely reprocess it after fixing the underlying issue?

advanced

Tests whether you know to replay from the DLT deliberately rather than just deleting and hoping the source retries.

Q

What is enable.auto.commit=false and why do senior engineers prefer it over the default?

advanced

Tests whether you know manual commit lets you commit only after successful processing, avoiding silent message loss.

Q

How do you implement a transactional Kafka producer in Spring Boot for exactly-once semantics?

advanced

Tests whether you know transactional.id and KafkaTransactionManager, and what read_committed means for downstream consumers.

Q

What is the significance of max.poll.records and max.poll.interval.ms in preventing consumer rebalancing?

advanced

Tests whether you know a slow batch that exceeds max.poll.interval.ms triggers a rebalance even though the consumer is still alive.

Q

A payment service's Kafka consumer lag jumps from 500 to 2 million messages in 30 minutes with unchanged producer throughput, and your SLA requires 5-second processing. How do you diagnose and fix it?

advanced

Tests whether you can reason through a real high-stakes production incident, not just recite the theory around lag.

Q

Design exactly-once semantics for a fund-transfer payment microservice — no double debit, no lost credit.

expert

Tests whether you can combine idempotent producers, Kafka transactions, and a transactional outbox into one coherent design.

Spring MVC Annotations

Q

What does the @RequestMapping annotation do in Spring MVC?

beginner

@RequestMapping maps an HTTP request to a specific handler method (or an entire controller class), matching on URL path, HTTP method, headers, or parameters. It's the general-purpose mapping annotation that @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping are all built as method-specific shorthand for — e.g. @GetMapping("/users") is equivalent to @RequestMapping(value = "/users", method = RequestMethod.GET).

Q

What does @GetMapping do, and when would you use plain @RequestMapping instead?

beginner

@GetMapping is shorthand for @RequestMapping(method = RequestMethod.GET) — it maps HTTP GET requests to a handler method and is the standard choice for any read/retrieval endpoint. You'd fall back to plain @RequestMapping when a single handler needs to respond to multiple HTTP methods at once, or when matching on more complex conditions (headers, content negotiation) that the shorthand annotations don't directly expose.

Q

What do @PostMapping and @RequestBody do together in a Spring Boot REST controller?

beginner

@PostMapping maps an HTTP POST request to a handler method — typically used for creating a new resource. @RequestBody tells Spring to deserialize the incoming HTTP request body (usually JSON) directly into a Java object parameter, using Jackson under the hood — together they let a method like createUser(@RequestBody UserDto dto) receive a JSON payload as a fully-populated object with zero manual parsing code.

Q

What does @PutMapping do, and how does it fit REST semantics?

beginner

@PutMapping maps HTTP PUT requests to a handler method, matching REST's convention that PUT should fully replace an existing resource at a known URI in an idempotent way. A typical handler signature is updateUser(@PathVariable Long id, @RequestBody UserDto dto), where the ID identifies which resource to replace and the body supplies its complete new state.

Q

What does @DeleteMapping do in Spring MVC?

beginner

@DeleteMapping maps HTTP DELETE requests to a handler method, used for removing a resource identified by a path variable — e.g. deleteUser(@PathVariable Long id). DELETE is expected to be idempotent: calling it multiple times on the same (now already-deleted) resource should still result in the resource being absent, typically returning a 204 No Content on success or a 404 if it was already gone.

Q

What is the difference between @RequestParam and @PathVariable in Spring MVC?

beginner

@PathVariable extracts a value embedded directly in the URI path itself, e.g. /users/{id} binds {id} to a method parameter — used for identifying a specific resource. @RequestParam extracts a value from the query string, e.g. /users?status=active binds status to a parameter — used for optional filters, pagination, or sorting options that aren't part of the resource's identity.

Hibernate Internals

Kafka Reliability & Throughput

Q

How would you design a notification/event-driven system (Kafka + consumers) for payments?

advanced

Tests whether you partition by user/account ID to preserve per-user ordering, make consumers idempotent for safe retries, and separate the payment-processing topic from a fan-out notification topic so a slow email provider can't back up payment processing.

Q

How does event-driven architecture maintain high throughput when a broker fails?

advanced

Tests whether you know Kafka's replication (leader/follower partitions with in-sync replica sets) lets a new leader be elected automatically on broker failure, so producers and consumers keep flowing with only a brief reassignment pause, not a full outage.

Q

How would you design an idempotent Kafka consumer?

advanced

Tests whether you reach for a dedup mechanism keyed on a unique message ID -- an upsert with a unique constraint, a processed-IDs table/cache, or Kafka's transactional/exactly-once producer semantics -- rather than assuming at-least-once delivery is safe to process blindly.

Q

What metrics and alerts would you configure for consumer backlog?

advanced

Tests whether you'd alert on consumer lag trend (not just absolute value) alongside records-consumed-rate and time-since-last-commit, since a flat lag at a high number is healthy while a steadily rising lag at a low number is the real early warning.

Q

What happens when a database crashes while consuming data from Kafka, and how do you handle it?

advanced

Tests whether you know the consumer should not commit the offset until the DB write succeeds, so a crash mid-write just means the message is redelivered -- which is why the DB write must also be idempotent to avoid double-processing on replay.

Q

Design a highly scalable e-commerce system using Java, Spring Boot, Microservices, Kafka, AWS, caching, and a relational database -- how would you handle failures, traffic spikes, and data consistency?

advanced

Tests whether you can tie the pieces together coherently -- Kafka to decouple order placement from fulfillment and absorb spikes, caching for read-heavy catalog paths, and sagas/outbox for cross-service consistency -- rather than listing each technology in isolation.

Q

Given three microservices A -> B -> C, if C fails, how can you prevent failure propagation using Kafka (DLQ, asynchronous decoupling, backpressure)?

advanced

Tests whether you'd replace B's synchronous call to C with a Kafka topic so B can keep accepting work while C is down, route C's unprocessable messages to a dead-letter topic, and apply backpressure (pause/resume consumption) rather than letting B's queue grow unbounded.

Q

How would you handle Kafka poison messages, retries, DLT/DLQ and offsets?

advanced

Tests whether you'd cap retry attempts with backoff before routing an unprocessable message to a dead-letter topic, and that you only advance the offset after that decision -- never block the partition retrying the same poison message forever.

Q

How would you guarantee that a message is not lost?

advanced

Tests whether you'd set acks=all with a minimum in-sync replica count on the producer side and disable auto-commit on the consumer side until processing succeeds, rather than relying on Kafka's defaults, which favor throughput over durability.

Q

When would you use REST vs Kafka?

intermediate

Tests whether you pick REST for synchronous request/response where the caller needs an immediate answer, and Kafka for decoupled, fan-out, or high-volume event flows where the producer shouldn't block on every consumer being available.

Spring Core Annotations

Q

What does the @Qualifier annotation do in Spring, and when do you need it?

beginner

@Qualifier resolves ambiguity when multiple beans of the same type exist and Spring can't determine which one to autowire by type alone — you pass @Qualifier("beanName") alongside @Autowired to specify exactly which implementation to inject. Without it, Spring throws a NoUniqueBeanDefinitionException the moment more than one matching bean is found for a given injection point.

Q

What does the @Primary annotation do, and how does it differ from @Qualifier?

beginner

@Primary marks one bean as the default choice among multiple candidates of the same type — when Spring needs to autowire and finds several matches, it picks the @Primary one automatically without any extra hint at the injection point. @Qualifier, by contrast, is specified at the injection point itself and lets you pick a DIFFERENT (non-primary) bean explicitly when needed — @Primary sets a sensible default, @Qualifier overrides it case-by-case.

Q

What does the @Lazy annotation do in Spring?

beginner

@Lazy defers a bean's initialization until it's actually first requested/injected, rather than at application startup (Spring's default for singleton beans is eager initialization). It's useful for reducing startup time when a bean is expensive to create but rarely used, or for breaking certain circular-dependency situations where eager initialization would otherwise fail.

Q

What does the @Scope annotation do, and what scopes can you specify with it?

beginner

@Scope overrides a bean's default lifecycle/visibility — common values are "singleton" (one shared instance, the default), "prototype" (a new instance per request for the bean), and, in a web application, "request" or "session" (tied to the HTTP request or session lifetime). It's applied directly on a @Component class or an @Bean method when the default singleton behavior isn't what you want.

Q

What does the @Value annotation do in Spring?

beginner

@Value injects a single configuration value — from application.properties/yml, an environment variable, or a system property — directly into a field or constructor parameter, e.g. @Value("${server.port}") private int port. It also supports SpEL (Spring Expression Language) for computed values and can specify a default with @Value("${some.key:defaultValue}") if the property is missing.

Q

What do @PropertySource and @PropertySources do in Spring?

beginner

@PropertySource explicitly registers an additional .properties file (beyond the default application.properties) into Spring's Environment, so its keys become available for @Value injection or @ConfigurationProperties binding — e.g. @PropertySource("classpath:custom.properties"). @PropertySources is the container annotation that lets you specify multiple @PropertySource entries together on a single @Configuration class.

Q

What does @ConfigurationProperties do, and how is it different from @Value?

intermediate

@ConfigurationProperties binds an entire group of related, hierarchical configuration properties (e.g. everything under app.mail.*) into a single strongly-typed POJO with matching fields, all at once, with built-in validation support. @Value injects one individual property at a time into one field — @ConfigurationProperties is the better choice once you have more than a couple of related settings, since it avoids a long list of scattered @Value fields.

Kafka Partitions & Ordering

Q

What is consumer rebalancing?

intermediate

Tests whether you know rebalancing is the protocol that redistributes partitions across a consumer group's members when one joins, leaves, or is considered dead, and why a long-running poll without a heartbeat can trigger an unwanted rebalance.

Q

How does Kafka handle message retention?

intermediate

Tests whether you know retention is time- or size-based per topic (not tied to whether a message was consumed), and that log compaction is a separate retention strategy that keeps only the latest value per key instead of deleting by age.

Q

How can you change topic retention settings?

intermediate

Tests whether you know retention.ms and retention.bytes can be altered per-topic at runtime via kafka-configs.sh without restarting the broker, and that a lower retention takes effect only on the next log segment cleanup pass, not instantly.

Q

How many partitions can a Kafka topic have?

intermediate

Tests whether you know there's no hard protocol limit, but partition count is practically bounded by per-broker file-handle and replication overhead, and that increasing it later breaks existing per-key ordering guarantees.

Q

How do you decide the number of Kafka partitions?

advanced

Tests whether you size partitions from target throughput divided by per-partition throughput and expected max consumer parallelism, rather than picking an arbitrary round number, since partitions are costly to reduce later.

Q

How would you design Kafka-based credit/debit processing with ordering and high throughput?

advanced

Tests whether you partition by account ID so all debits/credits for one account land on the same partition in order, while still parallelizing across accounts for throughput -- rather than a single partition that would serialize everything.

Q

How does Kafka maintain message ordering? How would Kafka partitions help with ordering?

intermediate

Tests whether you know ordering is only guaranteed within a single partition (via the monotonic offset), not across a topic, and that keying messages consistently is what routes related events to the same partition to preserve their order.

Transactions & Concurrency

Redis & Caching

Q

How do you prevent a cache stampede when using Spring's @Cacheable annotation?

advanced

Tests whether you know @Cacheable alone doesn't coalesce concurrent misses, and what actually does (locking, soft TTL).

Q

Redis is down. Should your application also go down? How would you design the fallback?

advanced

Tests whether you know caching should degrade gracefully to the database, not become a hard dependency that takes down the app.

Q

How would you solve the cache invalidation problem when multiple service instances are running?

advanced

Tests whether you know local in-memory caches need a coordination mechanism (pub/sub or shared cache) to stay consistent across instances.

Q

What are the different Redis eviction policies and when would you choose each?

advanced

Tests whether you know the tradeoffs between allkeys-lru, volatile-lru, allkeys-lfu, and the noeviction default.

Q

How do you implement distributed locking using Redis — SETNX vs Redisson?

advanced

Tests whether you know the difference between a raw atomic SETNX-with-TTL lock and a library that handles renewal and edge cases for you.

Q

What is the problem with a distributed lock expiring before the job holding it completes?

advanced

Tests whether you know a second process can acquire the 'freed' lock while the first is still working, causing double-processing.

Q

What is a Redis pipeline and how does it improve performance?

advanced

Tests whether you know batching commands avoids paying a network round trip for every single Redis call.

Q

What is the difference between Redis Cluster and Redis Sentinel?

advanced

Tests whether you know one shards data across nodes for scale while the other provides high availability via failover for a single dataset.

Q

How do you handle cache warming after a deployment or Redis restart to avoid a cold-cache traffic spike hitting the database?

advanced

Tests whether you know to proactively pre-populate hot keys instead of letting production traffic discover the cold cache.

Q

What is cache penetration — requests for keys that don't exist, each falling through to the database? How do you fix it with a Bloom Filter?

advanced

Tests whether you know a Bloom Filter can cheaply reject requests for keys that provably don't exist, before they ever reach the DB.

Q

After enabling caching, your database load drops as expected, but memory usage keeps climbing. What might be wrong?

advanced

Tests whether you know unbounded cache growth (no TTL, no max size) silently turns a cache into a memory leak.

Spring Ecosystem

Q

What is the difference between Spring Boot and Spring Cloud?

beginner

Spring Boot is about building a SINGLE, standalone, production-ready application quickly — auto-configuration, embedded servers, and starters that remove boilerplate for one service. Spring Cloud is built ON TOP of Spring Boot and addresses concerns that only exist once you have MULTIPLE services talking to each other — service discovery (Eureka), API gateways, distributed config, circuit breakers, and client-side load balancing.

Q

What is the difference between Spring Boot and Microservices?

beginner

Spring Boot is a FRAMEWORK for building applications quickly with minimal configuration — it works equally well for a monolith or a single microservice. Microservices is an ARCHITECTURAL STYLE for structuring an entire system as a collection of small, independently deployable services — Spring Boot is simply a popular, convenient tool for implementing each individual microservice in that architecture, not a requirement of the architecture itself.

Q

What is the difference between synchronous and asynchronous communication in microservices?

intermediate

In synchronous communication (typically REST/gRPC over HTTP), the calling service blocks and waits for an immediate response, creating tight temporal coupling — if the downstream service is slow or down, the caller is directly affected. In asynchronous communication (typically via a message broker like Kafka or RabbitMQ), the caller publishes an event and moves on without waiting, decoupling the services in time — the consumer processes the message whenever it's ready, which improves resilience at the cost of not getting an immediate result.

Spring Security

Q

How does Spring Security's filter chain work?

intermediate

Tests whether you know a request passes through an ordered chain of filters before ever reaching your controller.

Q

What is JWT? How do you implement JWT-based authentication in Spring Boot?

intermediate

Tests whether you know how a stateless, signed token replaces server-side session storage for authentication.

Q

What is @PreAuthorize and @Secured? What is the difference?

intermediate

Tests whether you know @PreAuthorize supports full SpEL expressions while @Secured only supports simple role checks.

Q

What is CSRF protection? When should you disable it?

intermediate

Tests whether you know why CSRF matters for browser sessions but is usually irrelevant for stateless token-based APIs.

Q

What do you know about Spring Security?

intermediate

Tests whether you describe it as a filter-chain-based framework intercepting requests before they reach controllers, handling authentication and authorization declaratively, rather than a single library call you drop in.

Q

@PreAuthorize vs @Secured. Which annotation enables method-level security?

intermediate

Tests whether you know both enable method-level security (via @EnableMethodSecurity), but @PreAuthorize supports full SpEL expressions for fine-grained, dynamic checks (e.g. checking argument values), while @Secured only supports static role name lists.

Q

How does role-based authorization work?

intermediate

Tests whether you describe the GrantedAuthority/role model -- roles attached to the authenticated principal and checked against required roles on a resource via the SecurityContext -- rather than hand-rolled if-checks scattered through business logic.

Q

How are authentication and authorization implemented in your application?

intermediate

Tests whether you clearly separate the two concerns -- authentication verifies who the caller is (via a filter validating credentials/token), authorization checks what that verified identity is allowed to do (via role/permission checks) -- and can describe the concrete mechanism used, not just the theory.

Q

What is JWT? What is the structure of a JWT token?

intermediate

Tests whether you know the three dot-separated Base64Url parts -- header (algorithm/type), payload (claims, e.g. sub, exp, roles), and signature (verifies integrity) -- and that the payload is only encoded, not encrypted, so it must never hold sensitive data.

Q

API Gateway generates a JWT and forwards the request to microservice A. Should A validate the token again?

advanced

Tests whether you argue yes -- trusting the gateway blindly creates a security hole if internal network traffic is ever compromised or misrouted -- so each service should independently verify the signature/expiry, following a zero-trust internal-network posture rather than perimeter-only security.

Q

Stateless vs stateful authentication.

intermediate

Tests whether you know stateful auth (session IDs) requires the server to store session state (or share it via sticky sessions/a session store), while stateless auth (JWT) embeds all identity info in the token itself, letting any instance validate it without shared server-side state -- the key enabler for horizontal scaling.

Q

What is CORS?

intermediate

Tests whether you know CORS is a browser-enforced security mechanism (not a server restriction) that blocks a page's JavaScript from reading cross-origin responses unless the server explicitly allows it via Access-Control-* headers -- it doesn't stop the request from being sent, only from being read.

Q

How do you secure microservices and REST APIs?

intermediate

Tests whether you name a layered approach -- token-based auth (JWT/OAuth2) at the gateway, per-service re-validation, HTTPS everywhere, rate limiting, and input validation -- rather than relying on a single perimeter check.

Q

What changed in Spring Security 6 (Spring Boot 3)? What was removed?

advanced

WebSecurityConfigurerAdapter was removed — you define a SecurityFilterChain @Bean directly instead. antMatchers() was replaced by requestMatchers(), and authorizeRequests() by authorizeHttpRequests(). CSRF is commonly disabled for stateless REST APIs using SessionCreationPolicy.STATELESS.

Q

What is @HttpExchange in Spring Boot 3? How does it replace Feign?

advanced

@HttpExchange is Spring's own declarative HTTP client — define an interface with @GetExchange/@PostExchange annotations, register it via HttpServiceProxyFactory backed by WebClient or RestClient. Similar convenience to OpenFeign, but built into core Spring Framework with no extra dependency, and integrates natively with observability and virtual threads.

Q

What is RestClient (Spring Boot 3.2)? How does it differ from RestTemplate and WebClient?

intermediate

RestClient is a synchronous HTTP client with WebClient's fluent builder API — the blocking counterpart to WebClient. RestTemplate is older, less fluent, and effectively frozen for new code. WebClient is reactive/non-blocking. RestClient is Spring's recommended choice for new synchronous REST calls from Spring Boot 3.2 onward.

Q

What is Problem Details (RFC 9457) support in Spring Boot 3?

intermediate

Spring Boot 3 can auto-configure ProblemDetail as the standard error response shape (enable with spring.mvc.problemdetails.enabled=true) — structured JSON with type/title/status/detail/instance fields, replacing ad-hoc custom error response objects; @ExceptionHandler methods can return ProblemDetail directly.

Q

What is CRaC (Coordinated Restore at Checkpoint)? How does it complement native images?

advanced

CRaC checkpoints a fully warmed-up, already-JIT-optimized JVM process and restores it almost instantly — unlike Native Image (AOT, no JVM at all), CRaC keeps the real JVM, giving you full JIT performance AND fast startup. Spring Boot 3.2+ supports a Checkpointable lifecycle, aimed at serverless cold-start scenarios.

Q

What is SecurityContext and SecurityContextHolder? What are the storage strategies?

advanced

SecurityContext holds the current Authentication object. SecurityContextHolder stores it via a pluggable strategy: ThreadLocal (default, per-thread), InheritableThreadLocal (shared with child threads), or Global (one shared context, for desktop apps). With virtual threads, ThreadLocal still works correctly since each virtual thread gets its own.

Q

What is UserDetailsService? How does Spring Security authenticate a user?

intermediate

UsernamePasswordAuthenticationFilter extracts credentials, builds a token, and passes it to AuthenticationManager, which delegates to DaoAuthenticationProvider — that calls UserDetailsService.loadUserByUsername(), compares the password via PasswordEncoder.matches(), and on success sets the resulting Authentication into SecurityContext.

Q

What is PasswordEncoder? Why must you never store plain-text passwords?

beginner

PasswordEncoder hashes passwords before storage and verifies them on login without ever storing or comparing plain text. Default is BCryptPasswordEncoder (deliberately slow, adaptive cost factor); DelegatingPasswordEncoder's {bcrypt} prefix supports multiple algorithms. Never use NoOpPasswordEncoder in production.

Q

Where should you store JWT tokens on the client side? What are the security tradeoffs?

advanced

localStorage/sessionStorage are readable by any JS on the page (XSS-vulnerable). An HttpOnly cookie is safe from XSS but vulnerable to CSRF unless mitigated with SameSite=Strict/Lax or a CSRF token. Common best practice: keep the access token only in memory (a JS variable) and put the refresh token in an HttpOnly cookie.

Q

How do you handle JWT token expiry and refresh tokens?

advanced

Use a short-lived access token (e.g. 15 min) plus a long-lived refresh token (e.g. 7 days) stored server-side. On expiry, the client calls a dedicated refresh endpoint; the server validates the stored refresh token and issues a new pair, rotating (invalidating) the old refresh token to prevent replay. On logout, add the JWT to a denylist (Redis) until its natural expiry.

Q

What is the difference between authentication and authorization in Spring Security?

beginner

Authentication answers 'who are you' (verifying identity via password, JWT, OAuth2 token) and is handled by AuthenticationManager. Authorization answers 'what can you do' (checking permissions after identity is established) and is handled by AuthorizationManager, at both method and URL level.

Q

Explain the OAuth2 Authorization Code Flow. When is it used?

advanced

The user is redirected to the Authorization Server to authenticate and consent; it redirects back with a short-lived code; your backend exchanges that code (server-to-server, with a client secret that's never exposed to the browser) for an access + refresh token, then uses the access token to call the Resource Server. Used for server-side web apps — the most secure flow when you have a confidential backend.

Q

What is PKCE and why is it required for SPAs and mobile apps?

advanced

PKCE (Proof Key for Code Exchange) has the client generate a random code_verifier and send its hash (code_challenge) with the initial auth request; when exchanging the returned code, it sends the original verifier, which the server hashes and compares. Since SPAs and mobile apps can't safely hold a client secret, PKCE replaces it, preventing authorization-code interception attacks.

Q

What is the difference between oauth2Login() and oauth2ResourceServer() in Spring Security?

advanced

oauth2Login() is for apps acting as an OAuth2 CLIENT — it drives the Authorization Code flow and creates a session. oauth2ResourceServer() is for APIs acting as a RESOURCE SERVER — it validates incoming JWT Bearer tokens per request, stateless, no session. Most microservices use oauth2ResourceServer().

Q

How does Spring Security validate JWT tokens in an OAuth2 Resource Server?

advanced

Spring Security fetches the Authorization Server's public keys (JWK Set) from its jwks-uri, verifies the incoming JWT's signature against them, and validates standard claims (iss, aud, exp). Configure via spring.security.oauth2.resourceserver.jwt.jwk-set-uri.

Q

How do you integrate Spring Boot with Keycloak or Okta?

advanced

Add spring-boot-starter-oauth2-resource-server and set spring.security.oauth2.resourceserver.jwt.issuer-uri to the provider's realm URL — Spring auto-discovers the OIDC configuration and validates tokens automatically. For role mapping, customize JwtAuthenticationConverter to pull roles from Keycloak's non-standard realm_access.roles claim.

Apache Kafka

Q

What is a Kafka broker, and what is a Kafka cluster?

beginner

A broker is a single Kafka server that stores data and serves client requests (produce/consume). A cluster is a group of brokers working together, coordinated via a controller, which lets Kafka distribute topic partitions across multiple machines for both scalability (parallel throughput) and fault tolerance (if one broker fails, others still hold replicas of the data).

Q

What is Kafka replication, and why does it matter?

beginner

Each partition can be configured with a replication factor N, meaning N total copies of that partition's data are stored across different brokers — one is the leader (handles all reads/writes) and the rest are followers (passively replicate from the leader). If the leader broker fails, one of the in-sync followers is automatically promoted to leader, which is what gives Kafka its durability and fault tolerance without any data loss for committed messages.

Q

How does Kafka achieve fault tolerance?

intermediate

Fault tolerance comes from partition replication across multiple brokers (so losing one broker doesn't lose data), the ISR (in-sync replica) mechanism that only promotes a follower that's fully caught up to leader status, and configurable acknowledgment levels (acks=all waits for all in-sync replicas to confirm a write before considering it successful) — together these ensure the cluster keeps serving data correctly even when individual brokers fail.

Q

How does Kafka guarantee message durability?

intermediate

Kafka persists every message to disk (not just memory) as an append-only log, and with acks=all plus a replication factor greater than 1, a message is only considered successfully written once it's been copied to every in-sync replica — meaning it survives a single broker failure without loss. This combination of disk persistence, replication, and configurable acknowledgment is what lets Kafka be trusted for critical event data, not just best-effort messaging.

Q

How does Kafka achieve high throughput and low latency?

intermediate

Kafka uses sequential disk writes (append-only logs, which are much faster than random I/O), zero-copy transfer (sending data straight from disk to the network socket via the OS, bypassing the application's own memory), batching of messages on both the producer and consumer sides to reduce per-message network overhead, and partitioning to parallelize work across many brokers and consumers simultaneously.

Distributed Transactions & Saga

Q

What is the Two-Phase Commit (2PC) protocol and why is it not recommended for microservices?

advanced

Tests whether you know 2PC's blocking coordinator model doesn't scale and creates a single point of failure across services.

Q

When would you use the Saga pattern, and how would you handle a compensation transaction that itself fails?

advanced

Tests whether you've thought past the happy path — what happens when the undo step doesn't work either.

Q

Payment succeeds, but the Order Service crashes right after. How do you recover safely without losing money or the order?

advanced

Tests whether you can reason through a concrete Saga recovery scenario, not just define the pattern abstractly.

Q

How do you achieve exactly-once business processing on top of an at-least-once messaging system?

expert

Tests whether you know the trick isn't stopping duplicates from arriving — it's making processing idempotent so duplicates are harmless.

Q

What is the dual-write problem in microservices, and how does the Outbox Pattern solve it?

advanced

Tests whether you know writing to a DB and publishing an event are two separate operations that can't be made atomic without help.

Q

How does the Transactional Outbox Pattern work with Debezium or Change Data Capture (CDC)?

advanced

Tests whether you know CDC tails the database's own write-ahead log to publish outbox rows, instead of a fragile polling loop.

Q

How do you handle outbox table growth in a high-throughput system?

advanced

Tests whether you know to prune published rows and index the table correctly so it doesn't become its own bottleneck.

Q

What is eventual consistency, and how would you explain it to a non-technical business stakeholder?

advanced

Tests whether you can translate a technical consistency model into a concrete business-facing tradeoff.

Q

How do you test distributed transactions in a microservices architecture?

advanced

Tests whether you know this needs dedicated integration environments and event-assertion tooling, not just unit tests per service.

Q

What is the difference between the Outbox Pattern and the Saga Pattern — are they complementary or competing?

advanced

Tests whether you know Outbox solves reliable event publishing while Saga solves multi-step business transaction coordination — they're often used together.

Q

How do you implement the Inbox Pattern for idempotent message consumption?

advanced

Tests whether you know tracking processed message IDs in a dedicated table is the consumer-side mirror of the Outbox Pattern.

Microservices Patterns

Q

What is the API Composition pattern in microservices?

intermediate

API Composition solves the problem of a query that needs data spread across multiple services' own databases — a composer (often the API Gateway or a dedicated aggregator service) calls each relevant service, then combines their responses into a single result for the client. It's the straightforward alternative to CQRS's dedicated read-model approach, simple to implement but less efficient for very large datasets or complex joins across many services.

Q

What is Transaction Log Tailing, and how does it relate to the Transactional Outbox pattern?

intermediate

Transaction Log Tailing is a specific implementation strategy for the Outbox pattern: instead of a separate poller reading an outbox table (Polling Publisher), a Change-Data-Capture tool (like Debezium) directly tails the database's own transaction/replication log to detect new committed rows and publish them as events. It achieves the same reliable dual-write guarantee as polling but with much lower latency and no added load from repeated polling queries.

Q

What is the Polling Publisher pattern in the context of the Transactional Outbox?

intermediate

Polling Publisher is the simpler of the two common Outbox-pattern implementations: a scheduled background job periodically queries the outbox table for new, unpublished rows, publishes each one as an event to the message broker, and marks it as sent. It's easier to build than transaction-log tailing (no CDC infrastructure needed) but introduces publish latency equal to the polling interval and adds repeated read load on the database.

Q

What is Data Offloading in a distributed system, and why is it used?

intermediate

Data Offloading means moving large payloads OUT of the primary message/event itself and into cheaper, purpose-built storage (like S3 or a blob store), replacing the payload in the message with just a reference/pointer to that storage location. It's used because message brokers like Kafka have practical size limits and cost characteristics that make them a poor fit for large binary blobs (images, big JSON documents) — keeping messages small and fast while the actual data lives elsewhere.

Q

What is Semantic Monitoring in microservices, and how is it different from standard health checks?

intermediate

Semantic Monitoring continuously runs synthetic, business-level transactions against a live production system (e.g. actually placing a test order end-to-end) to verify the system behaves correctly from a user's perspective, not just that individual services report themselves healthy. A standard health check can report every service as 'up' while a business flow is silently broken due to a misconfiguration between services — semantic monitoring catches exactly that class of failure.

Q

What is the Scaling Cube, and how does it apply to microservices architecture?

intermediate

The Scaling Cube (from 'The Art of Scalability') describes three independent axes for scaling a system: the X-axis (running multiple identical instances behind a load balancer — horizontal duplication), the Y-axis (splitting the application by function/service — which is exactly what microservices architecture does), and the Z-axis (splitting data by a key, like sharding by customer ID or region). Microservices architecture is essentially applying Y-axis scaling at the system level, and each individual microservice can then be independently scaled further along the X and Z axes.

Microservices Resilience

Q

What is the Circuit Breaker pattern, and why do retries alone make an outage worse?

intermediate

Tests whether you know unbounded retries against a struggling downstream amplify load exactly when it can least absorb it, and that a circuit breaker's open state stops calling it entirely for a cooldown window so it gets room to recover.

Q

How would you break a monolith into microservices in a fintech ecosystem?

advanced

Tests whether you'd decompose along transactional boundaries that matter in fintech (ledger, payments, KYC) first, keep strongly-consistent operations like double-entry bookkeeping inside one service, and use the strangler fig pattern to migrate incrementally rather than a big-bang rewrite.

Q

Why is throttling required in a microservices architecture?

intermediate

Tests whether you know throttling protects a service from being overwhelmed by its own callers -- including well-behaved internal services during a traffic spike or retry storm -- not just external abuse, which is what rate limiting alone addresses.

Q

Where would you use Microservices and where would you avoid them?

intermediate

Tests whether you'd justify microservices by independent scaling/deployment needs and team boundaries, and avoid them for a small team or a domain where the data model is still too tightly coupled to split without introducing distributed-transaction pain.

Q

What is a circuit breaker, and how is it different from a bulkhead?

advanced

Tests whether you know a circuit breaker stops calls to a failing dependency entirely, while a bulkhead isolates resources (thread pools/connections) per dependency so one slow call can't exhaust capacity needed by unrelated calls -- they solve different failure modes and are often used together.

Microservices Architecture

Q

What is microservices architecture? How does it differ from monolithic architecture?

beginner

Tests whether you can explain the tradeoffs, not just the buzzword — independent deployability versus operational simplicity.

Q

What is the Database-per-Service pattern? Why is it important?

intermediate

Tests whether you understand why sharing one database across services quietly turns microservices back into a distributed monolith.

Q

What is the Strangler Fig pattern? How do you migrate from monolith to microservices?

intermediate

Tests whether you know how to incrementally carve services out of a monolith without a risky big-bang rewrite.

Q

Microservices vs monolith: why choose microservices?

intermediate

Tests whether you weigh independent deployability and scaling per service against the real costs -- network latency, distributed transactions, and operational complexity -- rather than treating microservices as a universally 'better' architecture.

Q

How do your microservices communicate with each other? Synchronous vs asynchronous: when do you pick which?

intermediate

Tests whether you pick sync (REST/gRPC) for request-response flows needing an immediate answer, and async (Kafka/message queue) when you need decoupling, buffering against downstream slowness, or eventual consistency across services -- not a default preference either way.

Q

What are Service Discovery and API Gateway? Which features does an API Gateway support?

intermediate

Tests whether you know Service Discovery (e.g. Eureka) lets services find each other's current network location dynamically, while an API Gateway centralizes routing, authentication, rate limiting, and request aggregation at the system's single entry point.

Q

What happens if a microservice fails, and how do you handle it?

advanced

Tests whether you reach for graceful degradation (fallback responses, circuit breakers) and isolation (bulkheads) to contain the blast radius, rather than letting one failing dependency cascade into a full system outage.

Q

What is the Saga pattern? How do you handle distributed transactions and partial failures?

intermediate

Tests whether you know Saga replaces a single ACID transaction with a sequence of local transactions plus compensating actions for rollback, and that handling partial failure means designing every step's compensation up front, not bolting it on after something breaks.

Q

How do you maintain data consistency between microservices?

advanced

Tests whether you accept eventual consistency as the norm (via events/sagas/outbox pattern) rather than chasing cross-service strong consistency, which requires distributed transactions that don't scale well in a microservices topology.

Q

Explain the 12 factors of a microservice (12-factor app).

intermediate

Tests whether you can name the ones that matter most in practice -- config via environment variables (not baked-in files), stateless processes, and treating backing services as attachable resources -- rather than reciting all 12 without understanding why each exists.

Q

What is the main infrastructure needed to support microservices?

intermediate

Tests whether you name the supporting pieces beyond the services themselves -- service discovery, centralized config, API gateway, distributed tracing/logging, and a message broker -- since microservices without this tooling become unobservable and unmanageable quickly.

Q

Traffic suddenly increases 10x across your microservices. What would you change to keep the system stable?

advanced

Tests whether you prioritize shedding load gracefully (rate limiting, queueing, autoscaling) over trying to serve every request -- and whether you'd check that downstream dependencies like the DB connection pool can actually absorb 10x before assuming the services alone need scaling.

Q

Multiple instances of a service run the same scheduled job (for example, after scaling from 1 pod to 5). How do you prevent duplicate execution?

advanced

Tests whether you reach for a distributed lock (via DB, Redis, or ShedLock) acquired before the job runs, so only one of the N replicas actually executes it -- a problem that only appears once you scale past a single instance, which is why it's easy to miss.

Service Communication & Discovery

Distributed Tracing & Observability

API Design, Performance & Resilience

Q

An API works perfectly with 100 concurrent users but times out at 10,000, even though CPU sits at only 40%. Why?

expert

Tests whether you know low CPU with high failure at scale usually points to thread pool or connection pool saturation, not compute.

Q

Average API latency is 200ms, but p99 is 8 seconds. What is the real problem, and why does average latency hide it?

advanced

Tests whether you know averages mask tail latency, and that a small fraction of very slow requests is often the actual production issue.

Q

Retries are making an outage worse instead of better. How does a retry storm actually happen, and how do you prevent it?

advanced

Tests whether you know synchronized retries without jitter can pile onto an already-struggling service and push it further down.

Q

When would you use a Circuit Breaker, a Retry, a Timeout, and a Bulkhead pattern — and how do they combine?

advanced

Tests whether you know these four resilience patterns solve different failure modes and are usually layered together, not chosen one at a time.

Q

Where would you store an idempotency key, and how do you handle two concurrent requests arriving with the same key?

advanced

Tests whether you've thought through the race condition of two identical requests landing at nearly the same instant.

Q

The same resource is updated from two devices simultaneously. How do you prevent one update from silently overwriting the other?

advanced

Tests whether you know optimistic locking (a version check) catches this cleanly without holding a lock the whole time.

Q

Two users try to book the last available seat at the exact same moment. How do you prevent double booking?

advanced

Tests whether you can pick correctly between optimistic locking, pessimistic locking, or an atomic decrement for this exact scenario.

Q

How would you process a 5GB CSV file upload without causing an OutOfMemoryError?

advanced

Tests whether you know to stream and process the file line by line instead of loading it entirely into memory first.

Q

How would you trace one request as it flows across five microservices and millions of log entries?

advanced

Tests whether you know a propagated correlation ID plus distributed tracing is what makes this actually possible.

Q

Your API's SLA is 1 second, but a downstream dependency's timeout is set to 2 seconds. What's wrong with this design?

advanced

Tests whether you know timeout budgets must cascade correctly — a downstream timeout longer than your own SLA guarantees you'll breach it.

Q

How do you implement API versioning — URI versioning vs header versioning vs media type versioning — and what are the tradeoffs of each?

advanced

Tests whether you know the practical implications each approach has for clients, caching, and backward compatibility.

Q

How would you rate-limit APIs differently for different customers or tenants?

advanced

Use a per-tenant key (API key, tenant ID) as the rate-limiter's bucket key instead of a single global limit — Resilience4j's RateLimiter or Redis-backed token buckets (as in Spring Cloud Gateway's RequestRateLimiter) both support a configurable KeyResolver so each tenant gets its own independent bucket and limit tier.

Distributed Transactions & Consistency

JPA & Hibernate Internals

Q

How can you skip one field from being persisted in the database using Spring Data JPA?

intermediate

Tests whether you reach for @Transient to mark a field as non-persistent, and know it's evaluated by JPA at the entity level, independent of whether the field is also excluded from serialization via @JsonIgnore.

Q

First-level vs Second-level cache

intermediate

Tests whether you know first-level cache is mandatory, per-Session, and cleared when the Session closes, while second-level cache is optional, shared across sessions/SessionFactory, and needs careful invalidation to avoid serving stale data across instances.

Q

persist() vs merge()

intermediate

Tests whether you know persist() only works on a transient entity and makes it managed in place, while merge() copies state from a detached entity onto a (possibly newly loaded) managed instance and returns that managed copy -- so the original reference you passed in is never the one you should keep using.

Q

Explain what happens internally when a request reaches a Spring Boot application (Controller, Service, Repository, Hibernate, JDBC, database)

intermediate

Tests whether you can trace the full path -- DispatcherServlet routing to the controller, the service layer's transaction boundary opening, Hibernate translating repository calls to SQL via the dialect, and JDBC executing against a pooled connection -- rather than stopping at the controller/service handoff.

Q

Design a product API supporting category filtering, price sorting, pagination, JPA Specification/Criteria filtering, and invalid-parameter exception handling

advanced

Tests whether you reach for JPA Specifications to compose optional filters dynamically (rather than branching native queries per filter combination), use Pageable for sorting/pagination, and validate parameters at the boundary so a bad filter value fails fast with a clear 400 instead of a confusing query error.

Q

When would you NOT use records, especially with JPA/Hibernate entities?

advanced

Tests whether you know JPA entities need a no-arg constructor, mutable fields, and identity based on a persistent ID -- all of which conflict with a record's immutability and value-based equals()/hashCode() -- so records are fine for DTOs but not for the entities themselves.

Q

Java transient vs JPA @Transient?

intermediate

Tests whether you know Java's transient keyword only affects native Java serialization, while JPA's @Transient annotation is what actually tells the persistence provider to skip the field -- a field can be excluded from one and still be picked up by the other.

Q

Why can returning JPA entities directly from REST controllers create unexpected problems?

advanced

Tests whether you know serializing a managed entity can trigger lazy-loading of associations outside the transaction (LazyInitializationException), cause infinite recursion on bidirectional relationships, and leak internal schema details that should be shaped by a DTO instead.

SOLID Principles in Practice

Q

Your PaymentService has 15 if-else branches for different payment types. Which SOLID principle is being violated, and how would you refactor it?

advanced

Tests whether you can spot an Open/Closed Principle violation in real code and know Strategy pattern is the standard fix.

Q

Can a class with only a single method still violate the Single Responsibility Principle?

advanced

Tests whether you know SRP is about reasons to change, not method count — a single method can still mix multiple concerns.

Q

When does implementing the Open/Closed Principle become over-engineering?

advanced

Tests whether you know abstracting for change that will never actually happen just adds indirection with no payoff.

Q

What happens when a child class compiles fine but returns unexpected results compared to its parent contract?

advanced

Tests whether you know this is a Liskov Substitution violation even without a compile error — the contract broke silently.

Q

What problems do 'fat interfaces' create in large systems, and how would you split one without breaking existing consumers?

advanced

Tests whether you know a bloated interface forces implementers to depend on methods they don't use, and how to migrate safely.

Q

What is the difference between Dependency Injection and Dependency Inversion? Does using @Autowired automatically guarantee DIP?

advanced

Tests whether you know DI is a mechanism while DIP is a design principle, and injecting a concrete class still violates DIP.

Q

How do SOLID principles apply at the microservice level, not just the class level — is SRP applicable to service boundaries?

advanced

Tests whether you can map object-oriented design principles onto architectural decisions about service decomposition.

Q

Looking at a 2000-line service class, which SOLID violations would you expect to find first, and how would you start refactoring it?

advanced

Tests whether you have a practical, prioritized approach to untangling a real legacy God class, not just theory.

Design Patterns for Distributed Systems

Kubernetes & Production Ops

Q

Your Kubernetes pod keeps restarting, but application logs show no clear error. How would you debug it?

advanced

Tests whether you know to check kubectl describe, previous container logs, OOMKilled status, and probe configuration.

Q

What is the difference between liveness, readiness, and startup probes in Kubernetes, and why does confusing liveness with readiness matter for Spring Boot?

intermediate

Tests whether you know a common pitfall: using the same health endpoint for both can cause unnecessary pod restarts.

Q

What is a CrashLoopBackOff and how do you debug it?

advanced

Tests whether you know Kubernetes' exponential backoff behavior for repeatedly-crashing containers and how to find the root cause fast.

Q

What is a PodDisruptionBudget and why is it important during rolling deployments?

advanced

Tests whether you know it prevents voluntary disruptions (like node drains) from taking down too many replicas at once.

Q

How do you implement graceful shutdown in a Spring Boot microservice running in Kubernetes so in-flight requests aren't dropped?

advanced

Tests whether you know server.shutdown=graceful, a SIGTERM handler, and a preStop hook all need to work together.

Q

One pod consistently receives 80% of the traffic while the remaining pods stay nearly idle. Why might this happen?

advanced

Tests whether you know client-side connection reuse or a misbehaving load-balancing algorithm can defeat even distribution.

Q

A scheduled job runs once locally but five times after scaling to five pods. How do you prevent this duplicate execution?

advanced

Tests whether you know a @Scheduled job needs a distributed lock (or ShedLock) to run exactly once across a clustered deployment.

Q

Your Spring Boot application takes 5 minutes to start in production but only 20 seconds locally. How do you debug it?

advanced

Tests whether you know to check DB connectivity latency, DNS resolution, and autoconfiguration scanning under production networking.

Q

What is the difference between resource requests and resource limits in Kubernetes, and what happens if limits are exceeded?

advanced

Tests whether you know exceeding a CPU limit throttles the pod while exceeding a memory limit gets it OOMKilled outright.

Database Migrations

Spring Internals — Bean Lifecycle & Proxies

Q

Why can returning a new object from a custom BeanPostProcessor silently remove @Transactional, @Cacheable, and @Secured proxies?

advanced

If postProcessAfterInitialization returns a brand-new object instead of the (possibly already-proxied) bean it was given, any AOP proxy Spring built for that bean is discarded — silently disabling every annotation-driven feature (transactions, caching, security) that depended on that proxy.

Q

Why does declaring a BeanFactoryPostProcessor as a non-static @Bean sometimes break @Value placeholder injection?

advanced

BeanFactoryPostProcessors must be instantiated very early, before normal bean instantiation and before @Value placeholders are resolved. A non-static @Bean method inside a @Configuration class can force that configuration class itself to be instantiated too early, before property sources are fully set up.

Q

How can a custom FactoryBean accidentally bypass Spring AOP proxy creation?

advanced

AOP proxies are normally applied via BeanPostProcessor around the OBJECT a bean definition produces. If a FactoryBean's getObject() constructs and returns its target manually instead of going through the full Spring-managed creation path, the proxy-creation BeanPostProcessors may never get a chance to wrap it.

Q

Why does a manually instantiated bean (new MyService()) never receive dependency injection or AOP advice?

intermediate

Dependency injection and AOP proxying both happen through Spring's container-managed bean creation lifecycle (BeanPostProcessors, autowiring). An object created with `new` bypasses the container entirely, so none of that machinery ever touches it.

Q

How does Spring decide between JDK Dynamic Proxy and CGLIB, and what production issues can that choice introduce?

advanced

JDK proxy requires the bean to implement an interface (the proxy implements that interface); CGLIB creates a runtime subclass and is used when there's no interface, or when proxyTargetClass=true (Spring Boot's default). CGLIB proxies can't proxy final classes/methods, and calling a proxied method from within the same class (self-invocation) bypasses either proxy type entirely.

Q

Why can SmartInitializingSingleton trigger expensive database calls before your application is actually ready?

advanced

SmartInitializingSingleton.afterSingletonsInstantiated() runs once ALL singleton beans are created, but before the application context is fully refreshed and ApplicationReadyEvent fires — code here that does eager DB warm-up can run before readiness probes or downstream dependencies expect traffic.

Q

What happens when two auto-configurations define the same bean with conflicting conditions?

advanced

Spring Boot evaluates auto-configuration classes in a defined order (via @AutoConfigureBefore/@AutoConfigureAfter and @ConditionalOnMissingBean); the first one whose conditions pass typically wins, and later ones back off. Running with --debug shows the exact Conditions Evaluation Report explaining which configuration was applied and why.

Q

Why can overriding an auto-configured bean unintentionally disable metrics, tracing, or health checks?

advanced

Many auto-configured beans (like a DataSource or RestTemplate) are automatically wrapped or instrumented by other auto-configurations (Micrometer metrics, tracing). Defining your own bean of the same type can suppress the @ConditionalOnMissingBean-guarded instrumentation that would have wrapped Spring Boot's default.

Q

How do ApplicationContextInitializer, BeanFactoryPostProcessor, and BeanPostProcessor execute during the Spring lifecycle?

advanced

ApplicationContextInitializer runs earliest, before the context is refreshed at all (can add property sources, register listeners). BeanFactoryPostProcessor runs after bean DEFINITIONS are loaded but before any bean is INSTANTIATED (can modify definitions). BeanPostProcessor runs around each individual bean's instantiation (can wrap the actual bean instances, e.g. for AOP proxies).

Q

Why does exposing JPA entities directly from REST APIs eventually become a production problem?

intermediate

Entities carry lazy associations (risking LazyInitializationException during JSON serialization), can leak internal/sensitive fields, tightly couple your API contract to your database schema, and make it hard to evolve either independently — DTOs decouple the two and let you control exactly what's exposed.

Q

How can Open Session in View hide performance bottlenecks until your database connection pool gets exhausted?

advanced

OSIV keeps the Hibernate session (and its DB connection) open for the entire HTTP request, including view rendering — lazy loading 'just works' anywhere in the request, but N+1 queries triggered by the view layer stay invisible, and every request holds a connection far longer than it needs to, exhausting the pool under load.

Q

Why can @TransactionalEventListener(AFTER_COMMIT) silently stop working in asynchronous event processing?

advanced

AFTER_COMMIT relies on the listener running within the SAME thread's transaction synchronization callbacks. If the listener is also marked @Async (running on a different thread) or the publishing transaction never actually commits (e.g., it's read-only or rolled back), the listener may never fire, with no obvious error.

Q

Why can a poorly written OncePerRequestFilter execute multiple times for a single request?

advanced

OncePerRequestFilter guards against re-execution using a request attribute flag — but internal dispatches (forward, include, async dispatch, error dispatch) with a DIFFERENT request object, or a filter registered under multiple filter-chain matches, can each re-trigger it since the 'already filtered' marker doesn't always carry over.

Q

How does @Configuration(proxyBeanMethods=false) improve startup performance, and what trade-offs does it introduce?

advanced

By default, @Configuration classes are CGLIB-proxied so that calling one @Bean method from another returns the SAME singleton instance. Setting proxyBeanMethods=false skips that proxy (faster startup, less CGLIB overhead) — but then calling one @Bean method directly from another creates a NEW instance instead of reusing the singleton, which only matters for configurations with inter-bean method calls.

Spring Transactions

Q

What is @Transactional and how does Spring manage transactions?

intermediate

Tests whether you know @Transactional works via an AOP proxy that wraps the method call to begin a transaction before and commit/rollback after, based on the PlatformTransactionManager -- and that this proxy-based mechanism is exactly why self-invocation bypasses it.

Q

REQUIRED vs REQUIRES_NEW. Give a practical use case for REQUIRES_NEW.

intermediate

Tests whether you know REQUIRED joins an existing transaction if one is active (or starts one), while REQUIRES_NEW always suspends the current transaction and starts a fresh one -- useful for audit logging that must persist even if the outer business transaction later rolls back.

Q

Why can @Transactional fail when a method is called from another method in the same class?

advanced

Tests whether you know @Transactional relies on a dynamic proxy around the bean, and calling 'this.method()' from within the same class bypasses the proxy entirely -- the call never passes through the AOP interceptor, so no transaction is ever started.

Q

@Transactional on a private method: what actually happens?

advanced

Tests whether you know proxy-based AOP can only intercept calls that go through the proxy's public/protected method dispatch -- a private method can't be overridden by a subclass proxy (or exposed by a JDK dynamic proxy interface), so the annotation is silently ignored.

Q

A @Transactional method calls a REQUIRES_NEW method in the same class. How many transactions run?

advanced

Tests whether you catch the same self-invocation trap -- since the inner call bypasses the proxy, only one transaction runs (the outer, if any), not two, because REQUIRES_NEW on the inner method never actually triggers.

Q

A checked exception is thrown inside a @Transactional method. Does it roll back?

intermediate

Tests whether you know Spring's default rollback rule only covers unchecked (RuntimeException and its subclasses) and Error -- a checked exception commits the transaction unless you explicitly list it via rollbackFor, a very common silent-bug source.

Virtual Threads & GraalVM

Q

What are Virtual Threads and how do they differ from platform (OS) threads?

intermediate

Platform threads map 1:1 to OS threads — expensive to create in large numbers. Virtual threads are lightweight, JVM-managed threads (not OS-backed 1:1), cheap enough to create millions of. They don't make code faster; they make blocking code scalable, since a blocked virtual thread doesn't tie up an OS thread.

Q

How do you enable Virtual Threads in Spring Boot 3.2+?

intermediate

Set `spring.threads.virtual.enabled=true` in application.properties — Spring Boot auto-configures Tomcat and the @Async task executor to run on virtual threads, with no code changes needed for typical blocking Spring MVC code.

Q

How do Virtual Threads interact with @Transactional and connection pools?

advanced

Each virtual thread holding a DB connection for a transaction's duration still consumes a real pooled connection — with thousands of concurrent virtual threads, HikariCP pool exhaustion can become the new bottleneck even though threads themselves are cheap, so pool sizing and keeping transactions short (@Transactional(readOnly=true) where possible) still matter.

Q

How does Spring Boot support GraalVM Native Image, and what are its limitations?

advanced

Spring Boot 3+ runs an AOT processing phase at build time that generates bean-definition source code and reflect/proxy/resource config hints GraalVM needs, replacing most runtime reflection. Limitations: no dynamic class loading, longer build times, and libraries with heavy runtime reflection may need manual @RegisterReflectionForBinding or RuntimeHintsRegistrar hints.

Resilience Patterns

Q

What is the Circuit Breaker pattern? How do you implement it and set thresholds?

intermediate

Tests whether you describe the CLOSED/OPEN/HALF-OPEN state machine and can articulate why thresholds (failure rate %, minimum call count, wait duration in open state) must be tuned to the downstream's actual failure characteristics, not left at arbitrary defaults.

Q

Retry vs Circuit Breaker.

intermediate

Tests whether you know Retry assumes the failure is transient and tries again (risking amplifying load on an already-struggling downstream), while Circuit Breaker detects sustained failure and stops calling altogether for a cooldown period -- and that the two should be combined, with the breaker wrapping the retry, not either alone.

Q

A microservice calls another service that takes 10 seconds to respond. How do you stop your app from getting stuck?

advanced

Tests whether you reach for an aggressive timeout well below 10 seconds combined with a circuit breaker, so your own threads aren't held hostage by a dependency's slowness -- fail fast and return a fallback rather than waiting it out.

Q

A microservice goes down while processing an order. How should the system handle it?

advanced

Tests whether you design for partial-failure recovery -- persisting state transitions so the order isn't lost, using a message queue for retry/replay, and compensating actions for any already-completed steps -- not assuming the in-flight request can just be retried as-is.

Q

One microservice becomes very slow and others start timing out. How do you stop cascading failure?

advanced

Tests whether you name bulkheads (isolating thread/connection pools per dependency) and circuit breakers together -- so slowness in one dependency can't consume the thread pool shared by calls to other, healthy dependencies.

Q

Service C succeeds but times out before B gets the response (A to B to C). Design an idempotent workflow for when B retries.

advanced

Tests whether you design C's endpoint to accept an idempotency key (generated once by A and passed through), so a retried call from B returns the already-recorded result instead of executing the side effect twice.

Q

A downstream API is unavailable and your retries generate even more traffic. How do you redesign the retry strategy?

advanced

Tests whether you reach for exponential backoff with jitter (to avoid synchronized retry storms) capped by a circuit breaker that stops retrying altogether once failures sustain, instead of fixed-interval retries that pile on load exactly when the dependency is already struggling.

Q

The same payment request reaches your API twice, or a client retries after a timeout. How do you guarantee one charge?

advanced

Tests whether you reach for a client-supplied idempotency key stored with a unique DB constraint, so a duplicate request is detected and short-circuited to return the original result instead of processing the charge a second time.

Q

How do you design resilient microservices?

advanced

Tests whether you name the full toolkit working together -- timeouts, retries with backoff, circuit breakers, bulkheads, and graceful degradation -- and understand each addresses a different failure mode rather than being redundant with the others.

Spring AI — Core, ChatClient & RAG

Q

What is Spring AI? How does it differ from LangChain? What is its core design principle?

beginner

Spring AI applies familiar Spring idioms (@Bean, starters, @Autowired, auto-configuration) to AI engineering, unlike LangChain's Python-first, chain-centric style. Its core principle is portability — swap AI providers with a config change and zero code changes.

Q

What is the ChatClient API? How is it similar to WebClient and RestClient?

intermediate

A fluent builder: chatClient.prompt().system("...").user("...").advisors(...).call().content(). Supports both synchronous (.call()) and streaming (.stream() returning Flux<String>), auto-configured via the starter, idiomatically mirroring WebClient's builder style.

Q

What is the Advisors API? Explain how the advisor chain works.

advanced

Advisors are interceptors wrapping ChatClient calls, ordered by getOrder(): Request → Advisor-1 pre → Advisor-2 pre → ChatModel → Advisor-2 post → Advisor-1 post → Response. Built-in ones include QuestionAnswerAdvisor (RAG), MessageChatMemoryAdvisor (memory), SimpleLoggerAdvisor (logging).

Q

What model types does Spring AI support? How are embeddings used?

beginner

ChatModel, EmbeddingModel, ImageModel, AudioTranscriptionModel, TextToSpeechModel, ModerationModel. Embeddings convert text into high-dimensional vectors for semantic similarity search — the foundation RAG is built on.

Q

How does Spring AI's structured output work? How do you map LLM responses to POJOs?

intermediate

Call .call().entity(MyClass.class) — Spring AI generates a JSON schema from the class, adds it as instructions in the prompt, and parses the response back into that type (backed by BeanOutputConverter). For lists, use .entity(new ParameterizedTypeReference<List<X>>(){}). Eliminates brittle manual string parsing.

Q

What AI providers does Spring AI support and how do you switch between them?

beginner

OpenAI, Anthropic Claude, Google Gemini/Vertex AI, Azure OpenAI, Amazon Bedrock, Mistral, and local Ollama. Switch by changing the starter dependency and updating properties (API key, model name) — the ChatModel interface itself is provider-agnostic, so application code doesn't change.

Q

What is RAG? Why does it exist and what problems does it solve?

beginner

RAG (Retrieval-Augmented Generation) solves an LLM's static training cutoff, hallucination on domain-specific facts, and lack of access to proprietary data — it embeds the query, does a vector similarity search, injects the top-k matching chunks into the prompt, and the LLM answers grounded in that retrieved context.

Q

Explain the full RAG ingestion pipeline in Spring AI.

intermediate

Load with a DocumentReader (Pdf/Text/Tika), split with TokenTextSplitter into chunks (512-1024 tokens with 10-20% overlap is a common starting point), embed each chunk with an EmbeddingModel, and store chunks+metadata+embedding via VectorStore.add(documents).

Q

What is the difference between QuestionAnswerAdvisor and RetrievalAugmentationAdvisor?

advanced

QuestionAnswerAdvisor is simple one-shot RAG — search the vector store, append context to the prompt. RetrievalAugmentationAdvisor is a modular pipeline supporting query transformers (rewrite/expand), multiple document retrievers, and document post-processors (re-ranking) — the production-grade, multi-step option.

Q

What vector stores does Spring AI support? How do you switch between them?

intermediate

PGVector, Chroma, Redis, Pinecone, Milvus, Weaviate, Qdrant, MongoDB Atlas, Elasticsearch, Neo4j and more, all behind one VectorStore abstraction (add(docs), similaritySearch(SearchRequest)) — switching is a dependency + config change, no application-code rewrite.

Q

What is query rewriting (RewriteQueryTransformer)? Why does it improve RAG quality?

advanced

Conversational follow-up queries ("what about its price?") are ambiguous to a vector search on their own. RewriteQueryTransformer uses an LLM to turn them into standalone, specific queries first; MultiQueryExpander generates several variants to improve recall — both plug into RetrievalAugmentationAdvisor.

Q

How do you implement conversation memory in Spring AI?

intermediate

Use MessageChatMemoryAdvisor with a ChatMemory implementation (InMemoryChatMemory for dev, a Redis/DB-backed one for production), passing a conversationId per session — the advisor appends prior messages to the prompt automatically. Order matters: add the memory advisor before any RAG advisor.

Q

What is the difference between RAG and fine-tuning? When do you use each?

advanced

RAG injects knowledge at inference time — cheaper, instantly updatable, and the answer is traceable to a source. Fine-tuning bakes knowledge into model weights — better for consistent tone/format, faster inference, but expensive and static. Use RAG for frequently-changing or proprietary knowledge; fine-tune when a consistent style/task format matters more.

Q

What are chunking strategies in RAG? How does chunk size affect quality?

intermediate

Fixed-size (split by token count), sentence-based (better coherence), recursive (paragraphs → sentences → words), and semantic (split on topic shifts, more expensive). Too small loses context; too large adds irrelevant noise — overlap between chunks preserves context across boundaries.

Q

What is hybrid search in RAG? How does it combine vector and keyword search?

advanced

Vector search finds conceptually similar chunks; keyword (BM25/full-text) search finds exact term matches. Hybrid search combines both scores (commonly via Reciprocal Rank Fusion) for better recall — important when users search using exact terms like error codes or product IDs that pure vector similarity can miss.

Q

How do you evaluate a RAG pipeline? What metrics matter?

advanced

Retrieval metrics: Precision@k, Recall@k, MRR. Generation metrics: ROUGE, BLEU, METEOR against reference answers. RAG-specific: Faithfulness (is the answer grounded in the retrieved context?), Answer Relevance, Context Precision — tools like RAGAS, Arize, and LangSmith automate this.

Kafka

Q

Explain Zero-Copy in Kafka.

intermediate

Tests whether you know zero-copy means Kafka transfers data straight from the page cache/disk to the network socket via the OS's sendfile() call, bypassing the JVM's user-space buffers entirely -- which is why Kafka can sustain such high throughput without CPU being the bottleneck.

Q

Do you know about the Kafka Schema Registry?

intermediate

Tests whether you know it enforces a shared contract (typically Avro/Protobuf) between producers and consumers, versioning schema evolution and rejecting incompatible changes -- preventing the classic distributed-system failure of a producer silently changing message shape and breaking every consumer.

Q

What happens when a database crashes while consuming data from Kafka, and how do you handle it?

advanced

Tests whether you know the offset must only be committed after the DB write succeeds -- if you commit before writing, a crash loses the message; if you never commit, the consumer reprocesses it on restart, which is why idempotent writes matter more than the commit timing alone.

Q

Have you worked with MQ or Kafka? How have you used Kafka for microservice communication?

intermediate

Tests whether you can describe a concrete event-driven use case -- decoupling a producer from consumers that process asynchronously, buffering load spikes, or fanning events out to multiple independent consumer groups -- rather than a generic 'we use it for messaging' answer.

Q

What is a Kafka partition? What is a consumer group?

intermediate

Tests whether you know a partition is the unit of parallelism and ordering (messages within one partition are strictly ordered), while a consumer group is a set of consumers that split a topic's partitions between them so each message is processed by exactly one consumer in the group.

Q

A consumer processes a message and saves to the DB, but crashes before committing the offset. What does the next consumer see, and how do you avoid duplicate effects such as double billing?

advanced

Tests whether you know the message will be redelivered since the offset was never committed, so the only real fix is making the DB write idempotent (e.g. a unique constraint on a message ID) -- at-least-once delivery is unavoidable, exactly-once processing has to be engineered at the consumer.

Q

How do you make Kafka consumers idempotent? Messages are processed twice after a consumer restart; what do you do?

advanced

Tests whether you reach for tracking processed message IDs (a dedup table with a unique constraint, or an upsert keyed by business ID) so reprocessing the same message after a restart is a no-op rather than a duplicate side effect.

Q

What is a Dead Letter Topic? How do you handle poison messages?

intermediate

Tests whether you know a DLT is where messages that repeatedly fail processing get routed after a retry limit, so one malformed 'poison' message can't block the partition forever -- letting the consumer move on while the bad message is quarantined for manual inspection.

Q

You add partitions to a live topic. What happens to per-key ordering?

advanced

Tests whether you know the key-to-partition mapping is a hash mod partition count, so increasing partition count changes that mapping -- keys that were co-located in one partition can now land in a different one, breaking the ordering guarantee for events produced before and after the resize.

Q

A producer retries after a timeout and the message lands twice. Which setting stops that?

intermediate

Tests whether you name enable.idempotence=true (which Kafka uses with producer sequence numbers to detect and drop duplicate retries at the broker level) rather than relying on the consumer alone to deduplicate.

Q

Consumer lag keeps increasing (consumers slower than the producer, or lag rises although consumers are running). How do you troubleshoot?

advanced

Tests whether you'd check per-partition lag to see if it's evenly distributed (processing is just too slow -- scale consumers up to partition count) or skewed to one partition (a hot key or a stuck consumer), rather than assuming more consumers always fixes it.

Q

Tuning Kafka throughput: find bottlenecks before Kafka, pick producer and consumer optimizations, and prove a 40% gain.

advanced

Tests whether you look upstream of Kafka first (serialization cost, network, the producing application itself) before tuning batch.size/linger.ms on the producer and fetch.min.bytes/max.poll.records on the consumer, and whether you'd benchmark before/after rather than just claiming an improvement.

Q

The DB update succeeds but Kafka publishing fails. How do you guarantee the event is not lost?

advanced

Tests whether you reach for the Transactional Outbox pattern -- writing the event to an outbox table in the same DB transaction as the business update, then a separate relay process publishes it to Kafka and marks it sent -- rather than a dual-write that can fail halfway.

Q

Kafka publishing succeeds but the DB transaction rolls back. How could consumers receive an event for data that does not exist?

advanced

Tests whether you identify this as the inverse dual-write hazard -- publishing before the DB commit is confirmed -- and that the fix is the same outbox pattern: only publish events that were committed in the same local transaction as the state change, never before.

Q

How do you design reliable Kafka consumers?

advanced

Tests whether you combine manual offset commits (after successful processing, not auto-commit), idempotent processing logic, and a dead letter topic for poison messages -- the three pieces that together give you effectively-once processing on top of Kafka's at-least-once delivery.

Q

What happens if the message queue goes down?

intermediate

Tests whether you know producers should buffer or fail gracefully (not block indefinitely) and that the broader design question is whether your system can tolerate delayed delivery -- a message queue outage degrades the async parts of your system, so critical sync paths shouldn't depend on it being up.

Spring AI — Tool Calling, Agents & Production

Q

What is tool/function calling in Spring AI? How do you register a Java method as a tool?

intermediate

Annotate a method with @Tool and pass its containing object to chatClient.prompt().tools(...). Spring AI generates a JSON schema for it and sends it to the LLM; when the LLM decides to call it, ToolCallingAdvisor intercepts, executes the real Java method, and feeds the result back for the LLM to finish its answer.

Q

What is an AI Agent? How do you build one with Spring AI?

advanced

An agent is an LLM that reasons over a goal, picks tools, executes them, observes results, and repeats (the ReAct loop) until done. In Spring AI: expose multiple @Tool methods and let the LLM orchestrate which to call, add MessageChatMemoryAdvisor for multi-turn state, and optionally use MCP for external tool ecosystems.

Q

What is MCP (Model Context Protocol)? How does Spring AI integrate with it?

advanced

MCP is an open protocol (from Anthropic) for connecting LLMs to external tools and data sources in a standardized, language-agnostic way. Spring AI provides both an MCP client and server — a Spring Boot app can expose its @Tool methods as an MCP server, discoverable by any MCP-compatible AI agent.

Q

What is the ToolCallingManager interface? How does it manage the tool execution lifecycle?

advanced

It's Spring AI's internal engine: receives a tool-call request from the LLM, resolves the matching ToolCallback (by name, via ToolCallbackResolver), executes it, and formats the result to send back — all automatically driven by ToolCallingAdvisor when you use ChatClient.

Q

What is GraphRAG? How does it differ from standard vector RAG?

advanced

Standard RAG retrieves flat chunks by vector similarity. GraphRAG stores knowledge as a graph (entities as nodes, relationships as edges, e.g. in Neo4j) enabling multi-hop reasoning ('subsidiaries of Apple's chip suppliers') that flat vector search can't express — Spring AI's Neo4j VectorStore supports hybrid graph+vector queries.

Q

What is re-ranking in RAG? How does a CrossEncoder improve retrieval quality?

advanced

Initial top-k vector retrieval can return chunks that are semantically similar but not truly relevant. A CrossEncoder jointly processes the query and each candidate chunk through a model to score real relevance, reordering results — plugged in via a DocumentPostProcessor in RetrievalAugmentationAdvisor.

Q

What are the agentic workflow patterns supported in Spring AI?

advanced

Prompt Chaining (output feeds the next call), Routing (LLM picks which tool/workflow to invoke), Parallelization (multiple calls in parallel, aggregated), Orchestrator-Subagent (a master LLM delegates to specialized agents), and Evaluator-Optimizer (one LLM generates, another critiques in a loop) — all composed from ChatClient calls and @Tool methods.

Q

How do you implement a multi-agent system in Spring AI?

advanced

Each agent is its own ChatClient with its own system prompt, tools, and memory. A supervisor agent routes a task to the right specialized agent (SearchAgent, DatabaseAgent, etc.) based on intent, and agents report results back to the supervisor — MCP can expose agents as tools to each other for full autonomous orchestration.

Q

What is the difference between zero-shot, few-shot, and chain-of-thought prompting?

intermediate

Zero-shot gives just the task, no examples. Few-shot includes 2-5 example input/output pairs to demonstrate the expected format. Chain-of-thought instructs the model to 'think step by step,' dramatically improving reasoning on complex tasks — in Spring AI, few-shot examples go in the system message, CoT is triggered in the user message or system instructions.

Q

What is @ToolParam and how does Spring AI generate tool schemas?

intermediate

@ToolParam(description="...") annotates a tool method's parameters; Spring AI uses this plus Jackson's schema generation to produce the JSON Schema sent to the LLM alongside the tool definition. Clear, descriptive parameter descriptions directly improve how accurately the LLM calls the tool.

Q

How do you implement tool call error handling and retries in Spring AI?

advanced

Wrap tool logic in try-catch and return a descriptive error STRING as the tool result — the LLM sees it and can decide to retry with different arguments or acknowledge failure. For HTTP-level retries, configure RetryTemplate on the ChatModel, or use Spring Retry's @Retryable on the @Tool method for transient failures.

Q

What is semantic caching and how can it reduce LLM costs in Spring AI?

advanced

Standard caching matches by exact prompt string. Semantic caching embeds the incoming prompt and searches a vector store for a similar-enough past query (above a similarity threshold), returning its cached answer instead of calling the LLM again — implemented as a custom CallAdvisor, useful for reducing cost on repeated or paraphrased questions.

Q

How do you handle LLM token limits in a production Spring AI application?

advanced

Each model has a fixed context window; if history + RAG context + system prompt exceeds it, the API errors out. Mitigate with a memory advisor that trims the oldest messages as the limit approaches, periodic summarization of old messages, and capping how many chunks RAG retrieval injects.

Q

What is the Guardrails pattern in Spring AI? How do you implement input/output validation?

advanced

Input guardrails check user input before it reaches the LLM (prompt injection, PII, off-topic queries); output guardrails check the LLM's response (hallucination, PII leakage, policy violations). Implement both as custom CallAdvisors — pre-advisors for input, post-advisors for output — using either an LLM-based moderation call or regex/NLP checks.

Q

What is prompt injection and how do you defend against it in Spring AI?

advanced

Prompt injection is malicious user input designed to override the system's instructions (e.g. 'ignore all previous instructions'). Defend by keeping system and user messages in separate roles rather than concatenating them into one string, sanitizing input, adding output guardrails, and requiring human-in-the-loop confirmation for sensitive tool actions.

Q

How do you implement streaming Server-Sent Events (SSE) with Spring AI in a REST controller?

intermediate

Return a Flux<String> from a controller method with produces = MediaType.TEXT_EVENT_STREAM_VALUE, backed by chatClient.prompt().user(message).stream().content() — Spring auto-configures SSE from the Flux return type, and the browser receives tokens as they're generated.

Q

What is the difference between ChatMemory and VectorStore for context management?

intermediate

ChatMemory stores the conversation's own messages in order — short-term, session-scoped continuity. VectorStore stores embedded knowledge-base chunks — long-term, shared domain knowledge. A production chatbot typically uses both together: memory for the conversation, RAG for facts.

Database

Q

Optimistic vs pessimistic locking. How does database optimistic locking differ from Java synchronization?

intermediate

Tests whether you know DB optimistic locking (a version column checked on update) assumes conflicts are rare and detects them after the fact, rejecting the write if the version changed -- unlike Java's synchronized, which proactively blocks other threads and only works within a single JVM, not across concurrent transactions from different instances.

Q

How do you configure a database connection pool, and how do you decide the pool size?

intermediate

Tests whether you know pool size should be derived from the DB's actual concurrent-connection capacity and typical query latency (per HikariCP's own sizing formula), not just set to a large round number -- an oversized pool can overwhelm the DB just as badly as an undersized one starves the app.

Q

Explain database indexes and the difference between clustered and non-clustered indexes.

intermediate

Tests whether you know a clustered index physically orders the table's rows on disk by the index key (only one per table), while a non-clustered index is a separate structure with pointers back to the actual rows -- which is why clustered-index lookups avoid an extra hop that non-clustered ones need.

Q

When a table is created, how is its storage allocated and managed on disk?

intermediate

Tests whether you know storage is organized into fixed-size pages/blocks grouped into extents, with the DB engine allocating new pages as rows are inserted -- and that understanding this explains why fragmentation and page splits affect performance over time.

Q

Stored procedure vs trigger.

intermediate

Tests whether you know a stored procedure is explicitly invoked by the caller when needed, while a trigger fires automatically in response to a DML event (insert/update/delete) on a table -- the key distinction is who controls when the logic runs.

Q

Difference between RANK(), DENSE_RANK() and ROW_NUMBER().

intermediate

Tests whether you know RANK() leaves gaps after ties (1,1,3), DENSE_RANK() doesn't (1,1,2), and ROW_NUMBER() ignores ties entirely, assigning a unique sequential number even to equal values -- a distinction that matters a lot for 'top N' queries with duplicate values.

Q

Write an SQL query to rank employees based on their experience.

intermediate

Tests whether you reach for a window function (RANK() OVER (ORDER BY experience DESC)) instead of a self-join or subquery-based ranking, which is both harder to read and far more expensive on larger tables.

Q

Explain the order of execution of SQL query clauses.

intermediate

Tests whether you know the logical execution order (FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT) differs from the written order -- which is exactly why you can't reference a SELECT alias in a WHERE clause but can in ORDER BY.

Q

INNER JOIN vs LEFT JOIN.

intermediate

Tests whether you know INNER JOIN returns only rows with matches in both tables, while LEFT JOIN returns every row from the left table regardless of a match, filling unmatched right-side columns with NULL -- a distinction that matters whenever you need to preserve rows with no related data.

Q

COUNT(*) vs COUNT(1) vs COUNT(column).

intermediate

Tests whether you know COUNT(*) and COUNT(1) are functionally identical (both count all rows, and most optimizers treat them the same), while COUNT(column) counts only non-NULL values in that specific column -- a subtle but important difference when the column is nullable.

Q

How would you optimize a slow query?

advanced

Tests whether you start with EXPLAIN/the execution plan to find the actual bottleneck (missing index, full table scan, bad join order) rather than guessing -- and whether you'd check if an existing index is even being used before adding a new one.

Q

Explain ACID properties.

intermediate

Tests whether you can tie each letter to a concrete guarantee -- Atomicity (all-or-nothing), Consistency (valid state transitions per constraints), Isolation (concurrent transactions don't interfere, per isolation level), Durability (committed data survives a crash) -- rather than reciting the acronym.

Q

What is database normalization?

intermediate

Tests whether you describe it as organizing data to eliminate redundancy and update anomalies by decomposing tables according to functional dependencies (1NF through 3NF+), and whether you can explain the real trade-off: fewer anomalies at the cost of more joins.

Q

WHERE vs HAVING. Can aggregate functions be used with HAVING? With WHERE?

intermediate

Tests whether you know WHERE filters rows before grouping/aggregation happens, so it can't reference an aggregate result, while HAVING filters groups after aggregation and is specifically built to filter on aggregate values like COUNT() or SUM().

Q

Write a query using WHERE, GROUP BY and HAVING.

intermediate

Tests whether you correctly sequence the three -- WHERE to filter rows before grouping, GROUP BY to aggregate, HAVING to filter the resulting groups -- a common query-writing exercise that reveals whether the execution order concept actually sank in.

Q

Write an SQL query to find the second-highest salary.

intermediate

Tests whether you reach for a window function (DENSE_RANK() OVER (ORDER BY salary DESC)) or a correlated subquery as the robust, portable solution, rather than LIMIT 1 OFFSET 1, which breaks silently on duplicate top salaries.

Q

Index on (status, created_at) and the query filters only on created_at. Does the index help?

advanced

Tests whether you know a composite index is only usable left-to-right -- filtering on created_at alone, without status, generally can't use this index efficiently (it would need a full scan or a separate index on created_at), because the leading column must be part of the filter.

Q

Two transactions read one row, both update it, and one update vanishes (or two threads update the same record). What prevents it?

advanced

Tests whether you name the lost-update problem by name and reach for either a higher isolation level/row locking (SELECT ... FOR UPDATE) or optimistic locking with a version column, rather than application-level synchronization, which doesn't protect DB state across instances.

Q

HikariCP reports a connection timeout although database connections are available. What could be happening?

advanced

Tests whether you check for connection leaks (connections checked out but never returned to the pool, e.g. missing try-with-resources), a pool misconfigured below actual demand, or long-held connections from slow transactions -- not assuming the DB itself is the bottleneck just because it reports availability.

Q

Database CPU hits 100% while application CPU stays low. How do you find the queries responsible?

advanced

Tests whether you'd pull the DB's slow-query log or active query view (pg_stat_activity, SHOW PROCESSLIST) to find long-running or frequently-executed queries, rather than looking at the application side where the symptom clearly isn't located.

Q

What happens if the database goes down?

intermediate

Tests whether you'd expect connection acquisition failures to surface as application errors immediately, and whether your design has a fallback (read replica failover, cached reads, graceful degradation) rather than every request hard-failing with no mitigation.

Q

How do you handle database replication lag?

advanced

Tests whether you know reads immediately after a write can hit a replica that hasn't caught up yet, and that the fix is routing read-your-own-write queries to the primary (or using a read-after-write consistency token) rather than assuming replicas are always current.

Company & Architect-Level

JPA & Hibernate

REST APIs

Q

PUT vs PATCH.

intermediate

Tests whether you know PUT replaces the entire resource (idempotent, full representation required), while PATCH applies a partial update to specific fields -- and that sending a partial body to PUT can unintentionally null out fields the client didn't include.

Q

Difference between POST and PUT. Any other differences?

intermediate

Tests whether you go beyond 'create vs update' to the deeper distinction -- PUT is idempotent (repeating it produces the same result) and the client typically determines the resource URI, while POST is not idempotent and the server usually assigns the new resource's identity.

Q

Difference between PUT and QUERY methods in HTTP.

intermediate

Tests whether you're aware QUERY is a newer, still-emerging HTTP method designed for safe, idempotent requests that need a body (unlike GET, which traditionally shouldn't carry one) -- distinct from PUT, which is specifically for replacing a resource, not retrieving data.

Q

When does a server return 429, and how would you handle it?

intermediate

Tests whether you know 429 Too Many Requests signals the client has hit a rate limit, and that the correct client-side handling is to respect the Retry-After header and back off, rather than retrying immediately and making the throttling worse.

Q

Common HTTP status codes.

intermediate

Tests whether you can map status code ranges to meaning precisely -- 2xx success, 3xx redirection, 4xx client error (caller's fault, don't retry blindly), 5xx server error (may be safe to retry) -- rather than only naming 200, 404, and 500.

Q

What is idempotency in REST APIs?

intermediate

Tests whether you define it precisely as 'repeating the same request produces the same end state as doing it once' -- true for GET/PUT/DELETE by spec, but POST requires an explicit idempotency key if you want that guarantee, since creation isn't naturally idempotent.

Q

How do you version an API, or change it without breaking existing clients?

advanced

Tests whether you weigh URI versioning (/v1/, /v2/) against header-based versioning, and whether you know additive changes (new optional fields) are generally safe without versioning, while removing or renaming fields is a breaking change that needs a new version or a deprecation window.

Q

How would you design a scalable REST API?

advanced

Tests whether you design for statelessness (no server-side session affinity), pagination on list endpoints, proper caching headers, and rate limiting -- the concrete decisions that let an API scale horizontally without rework later.