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
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.
What's the difference between BeanFactoryPostProcessor and BeanPostProcessor?
intermediateA 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.
When should you use @Lazy, and what are its trade-offs?
intermediateUse @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.
What happens internally during the Spring Boot application startup lifecycle?
advancedSpringApplication.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.
What's the difference between ApplicationContextInitializer, ApplicationRunner, and CommandLineRunner?
intermediateApplicationContextInitializer 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).
How does Spring Boot Actuator expose metrics, and how would you secure them in production?
intermediateActuator'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.
What does @SpringBootApplication do, and which annotations does it combine?
intermediateTests 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.
How does Spring Boot auto-configuration work? How does @EnableAutoConfiguration work internally?
intermediateTests 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.
Explain the Spring bean lifecycle.
intermediateTests 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.
Two beans need each other through constructor injection. What does Spring Boot 3 do at startup?
advancedTests 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.
500 outbound HTTP calls per second: RestTemplate or WebClient, and what breaks with the other?
advancedTests 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
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?
intermediateTests 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.
How do you store passwords in the database?
intermediateTests 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.
How do you choose SQL vs NoSQL for wallets, transactions & audit logs?
advancedTests 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.
Count employees department-wise (SQL)
intermediateTests 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.
HLD: design a food-delivery homepage feed -- geohashing, schema design, SQL vs NoSQL trade-offs
advancedTests 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.
What is the difference between LEFT JOIN and RIGHT JOIN? When do you use LEFT JOIN?
intermediateTests 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.
Departments with zero employees query
intermediateTests 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.
Find duplicate rows (SQL)
intermediateTests 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.
Write a SQL query to find the first name of the employee having the highest bonus (two tables given)
intermediateTests 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.
Is PostgreSQL SQL or NoSQL?
intermediateTests 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.
What is InnoDB in MySQL?
intermediateTests 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.
What is the difference between UNION and UNION ALL?
intermediateTests 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.
How do you handle NULL values and conditional mapping in SQL, e.g. mapping values like A to Apple, B to Banana?
intermediateTests 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.
How do you remove duplicates in SQL?
intermediateTests 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.
Explain joins and their use cases
intermediateTests 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
What is a REST API, and what are its core architectural constraints?
beginnerREST (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.
What is a resource, a sub-resource, and a URI in REST API design?
beginnerA 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.
What are the main HTTP methods used in REST APIs, and what does each represent?
beginnerGET 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.
What is the difference between HTTP and HTTPS?
beginnerHTTP 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.
What is the difference between GET and POST in a REST API?
beginnerGET 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.
What is the difference between POST and PUT in a REST API?
beginnerPOST 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.
What is the difference between PUT and PATCH in a REST API?
beginnerPUT 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.
What is the difference between REST and SOAP?
beginnerREST 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
What are the key HikariCP configuration properties — maximumPoolSize, minimumIdle, connectionTimeout, idleTimeout, maxLifetime — and what happens if each is misconfigured?
advancedTests whether you actually understand what each pool setting controls, not just that HikariCP exists.
How do you troubleshoot HikariCP connection pool exhaustion in production?
advancedTests whether you know to check for connection leaks, undersized pools, and long-running queries holding connections.
How do you detect connection pool leaks in production before they exhaust the pool entirely?
advancedTests whether you know HikariCP's leakDetectionThreshold setting and how to act on the warnings it logs.
What is the difference between connectionTimeout and socketTimeout in HikariCP?
advancedTests whether you know one bounds waiting for a pooled connection and the other bounds waiting for the database itself to respond.
How do you size your database connection pool correctly for a given workload?
advancedTests whether you know the counterintuitive rule that a smaller, correctly-sized pool often outperforms a large one.
Why should you never hold a database connection open while making an external API call?
advancedTests whether you know a slow downstream call while holding a pooled connection can exhaust the whole pool for every other request.
Spring Boot Core
What is Spring Boot and how is it different from the Spring Framework?
beginnerTests whether you know Spring Boot is an opinionated, auto-configured layer on top of Spring, not a replacement for it.
What does @SpringBootApplication do? What 3 annotations does it combine?
beginnerTests whether you know this one annotation is really @Configuration + @EnableAutoConfiguration + @ComponentScan bundled together.
What is Spring Actuator? Name 5 important endpoints it exposes.
intermediateTests whether you know how to expose health, metrics, and diagnostic data for a production Spring Boot application.
How does Spring Boot handle multiple environments (dev, QA, prod) using profiles?
intermediateTests whether you know how to structure environment-specific configuration cleanly using @Profile and profile-specific property files.
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`.
Your Spring Boot application takes 60+ seconds to start — how do you optimize it?
advancedProfile 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.
How do you process millions of records efficiently using Spring Batch?
advancedSpring 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.
How do you implement multi-tenancy in Spring Boot?
advancedThree 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.
How would you design an audit logging system for every database change?
advancedFor 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.
Authentication Strategy
JWT vs Session-based authentication — design & trade-offs
intermediateTests whether you can articulate the real trade-off -- JWT's statelessness and horizontal scalability versus the loss of server-side revocation, against sessions' easy invalidation but sticky-session/shared-store cost.
Access vs Refresh Token
intermediateTests whether you know access tokens are short-lived and sent on every request while refresh tokens are long-lived, stored securely, and used only to mint new access tokens -- and why that split limits blast radius on theft.
OAuth & Identity Protocols
OAuth 2.0 & PKCE
advancedTests whether you understand PKCE closes the authorization-code-interception hole in public clients (SPAs, mobile apps) by binding the token exchange to a code_verifier the client alone holds, since those clients can't keep a client_secret.
Difference between OAuth and OAuth 2.0
intermediateTests whether you know OAuth 2.0 is not backward compatible with OAuth 1.0 -- it dropped request signing for bearer tokens over HTTPS and introduced distinct grant types, trading cryptographic complexity for simplicity at the cost of relying entirely on transport security.
How would you implement OAuth2 authentication in Spring Boot?
intermediateTests whether you know to use spring-boot-starter-oauth2-client/resource-server rather than hand-rolling the authorization code flow, and can explain the split between the client role (login) and resource server role (validating incoming tokens).
Difference/relationship between OAuth 2.0, JWT and OpenID Connect
advancedTests whether you can place the three correctly -- OAuth 2.0 is an authorization framework for delegated access, JWT is just a token format OAuth2 and OIDC often use, and OIDC is an identity layer built on top of OAuth2 that adds the ID token for authentication.
Security Internals & Crypto
What is RSA, and where is it used?
intermediateTests whether you know RSA is asymmetric encryption built on the difficulty of factoring large primes, and can name its real uses -- JWT RS256 signing, TLS key exchange, digital signatures -- rather than confusing it with symmetric ciphers like AES.
What is the role of AuthenticationManager and AuthenticationProvider?
advancedTests whether you know AuthenticationManager is the entry point that delegates to one or more AuthenticationProviders, each of which actually validates a specific credential type -- and that you can plug in a custom provider without touching the manager.
Database Transactions & Locking
How would you manage transactions in a distributed system?
advancedTests whether you move past a single ACID transaction mental model toward sagas, the outbox pattern, or 2PC/3PC, and can articulate the consistency vs. availability trade-off each one makes.
What is the 2-Phase Commit (2PC) protocol?
advancedTests whether you understand the prepare/commit split and why a coordinator crash between phases can leave participants blocked holding locks -- the core reason most distributed systems avoid 2PC in favor of sagas.
How does PostgreSQL handle concurrency?
advancedTests whether you know PostgreSQL uses MVCC -- readers see a consistent snapshot via row versions rather than blocking on writers -- and can explain how that avoids read locks at the cost of needing VACUUM to reclaim dead tuples.
Dependency Injection & Core
What is Dependency Injection? What are the 3 types in Spring?
beginnerTests whether you know constructor, setter, and field injection, and can explain the core DI concept itself.
What is the difference between @Component, @Service, @Repository, and @Controller?
beginnerTests whether you know these are semantically distinct despite all being stereotypes of @Component under the hood.
What is the difference between constructor injection and field injection? Which is preferred?
intermediateTests whether you know why constructor injection is the recommended default for immutability and testability.
What is the Bean lifecycle in Spring? Explain all phases.
intermediateTests whether you can trace a bean from instantiation through initialization callbacks to destruction.
What is circular dependency in Spring? How do you resolve it?
advancedTests whether you understand Spring's three-level cache trick for singletons, and why constructor injection can't use it.
Spring MVC vs WebFlux vs Virtual Threads
Spring MVC vs WebFlux vs Java Virtual Threads — when would you choose each?
advancedTests whether you understand the actual tradeoffs instead of defaulting to 'reactive is always better.'
What is the fundamental difference between the thread-per-request model and the reactive model?
advancedTests whether you know one thread blocks per request while the other multiplexes many requests over a few threads via callbacks.
What is backpressure in reactive streams and why does it matter?
advancedTests whether you know a fast producer can overwhelm a slow consumer without an explicit mechanism to signal capacity back upstream.
Can you mix blocking code inside a WebFlux pipeline? What happens if you do?
advancedTests whether you know a single blocking call can stall an entire event-loop thread serving many other requests.
When should you NOT use Virtual Threads — what are their limitations?
advancedTests whether you know CPU-bound work and code with synchronized blocks don't benefit the way I/O-bound work does.
What is Mono vs Flux in Project Reactor?
advancedTests whether you know the distinction between a zero-or-one-element stream and a multi-element async stream.
How do you handle errors in a reactive pipeline — onErrorReturn, onErrorResume, retry?
advancedTests whether you know when to substitute a fallback value versus swap in a whole fallback publisher versus simply retry.
DI & IoC Internals
Dependency Inversion vs Dependency Injection?
intermediateTests 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.
What is the difference between constructor injection and setter injection?
intermediateTests 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.
How does Spring resolve autowiring when multiple beans of the same type exist?
intermediateTests 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.
Can Spring create a bean without calling its constructor in the normal way? When could this matter?
advancedTests 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.
Why can adding @Transactional change the actual object type returned by Spring?
advancedTests 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.
Can two beans have the same name?
intermediateTests 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.
How do you exclude auto-configuration for a specific class?
intermediateTests 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.
Can a class with a private constructor be used to create a Spring Bean?
advancedTests 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.
What happens if you do not use @Autowired in Spring? How do you perform constructor injection without it?
intermediateTests 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.
How is EJB different from Spring-managed components?
intermediateTests 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
What is the Spring IoC (Inversion of Control) Container?
beginnerThe 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.
What is a Spring Bean?
beginnerA 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.
What is the default scope of a Spring Bean, and what other scopes are available?
beginnerThe 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.
What is the difference between BeanFactory and ApplicationContext in Spring?
beginnerBeanFactory 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
What is the purpose of Interceptors in Spring Boot?
intermediateTests whether you know interceptors hook into the DispatcherServlet's pre/post-handle lifecycle for cross-cutting request concerns like logging or auth checks, and can explain why that's a different layer than a Filter (servlet-level) or AOP (bean-method-level).
What happens when a REST endpoint streams a large response instead of returning the entire payload at once?
advancedTests whether you know streaming (StreamingResponseBody or a reactive WebFlux Flux) sends data incrementally and keeps memory flat for large responses, versus buffering the entire payload in memory before the first byte goes out.
RestTemplate vs FeignClient vs WebClient — when would you use each?
intermediateTests whether you know RestTemplate is blocking and now in maintenance mode, FeignClient trades flexibility for declarative interface-based calls, and WebClient is the reactive, non-blocking choice -- and you'd pick based on throughput needs, not habit.
REST API Development
What is the difference between @Controller and @RestController?
beginnerTests whether you know @RestController implicitly adds @ResponseBody to every handler method.
How do you return proper HTTP status codes in Spring Boot? Explain ResponseEntity.
intermediateTests whether you know how to control status codes, headers, and body together instead of always returning 200.
How do you handle global exceptions in Spring Boot? Explain @ControllerAdvice.
intermediateTests whether you know how to centralize error handling instead of wrapping every controller method in try-catch.
How do you implement pagination and sorting with Spring Data JPA?
intermediateTests whether you know Pageable and Sort, and how to avoid returning an unbounded result set from an API.
REST API Design
What is HATEOAS and when would you use it?
advancedTests 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.
What is the Richardson Maturity Model?
advancedTests 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.
What functional and non-functional requirements would you clarify before developing a new REST API?
intermediateTests 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.
Pros/cons of URI, query-parameter, header-based, and media-type versioning?
intermediateTests 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.
How would you prevent an API response from accidentally exposing fields added to an entity later?
intermediateTests 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.
Can PUT be used instead of DELETE?
intermediateTests 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
What happens if a JDBC connection is not explicitly closed? How does connection pooling help in such a scenario?
intermediateTests whether you know an unclosed connection isn't released back to the pool and eventually exhausts it under load, and that pooling mitigates -- but doesn't eliminate -- the need for try-with-resources to guarantee release.
Redis caching is working, but database load remains at 100 percent. What could be wrong?
advancedTests whether you'd check for a hot key causing cache stampede on expiry, a cache that's bypassed for a large share of queries (wrong TTL, cache-aside gaps), or background jobs/reports hitting the DB directly outside the cached code path.
Why can pagination with OFFSET become increasingly expensive for very large tables, and when would you choose cursor/keyset pagination instead?
advancedTests whether you know OFFSET forces the database to scan and discard all preceding rows before returning a page, and that keyset pagination (WHERE id > last_seen_id) turns that into a constant-cost index seek.
Spring Boot Fundamentals
What are Spring Boot Starters, and why do they exist?
beginnerStarters 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.
What is spring-boot-starter-parent, and what does it provide?
beginnerIt'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.
What embedded servers does Spring Boot support, and how do you change the default?
beginnerSpring 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.
What is Spring Boot DevTools, and what does it do during development?
beginnerDevTools 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.
@Component vs @Service vs @Repository.
intermediateTests 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.
@Bean vs @Component.
intermediateTests 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.
What is Dependency Injection? Explain IoC, the types of DI, and constructor vs field injection (which is preferred and why).
intermediateTests 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.
What are Spring Profiles and why are they used?
intermediateTests 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.
How do you handle exceptions globally in Spring Boot?
intermediateTests 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.
How do you build a REST API in Spring Boot?
intermediateTests 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
How do you achieve Kafka producer idempotency and exactly-once processing?
advancedTests whether you know enable.idempotence alone only prevents duplicate writes at the broker, not end-to-end exactly-once.
A database update succeeds, but publishing the corresponding Kafka event fails. How do you maintain consistency?
advancedTests whether you know this is the classic dual-write problem, and that the Outbox Pattern is the real fix, not a retry loop.
What happens if a Kafka consumer processes a message successfully but crashes before committing the offset?
advancedTests whether you know the message will be redelivered, which is exactly why consumer-side idempotency is non-negotiable.
Kafka consumer lag suddenly spikes in production. What do you check first?
advancedTests whether you know to check for GC pauses freezing poll(), slow downstream calls in the consumer, or an actual rebalance loop.
One Kafka partition is overloaded while others sit idle. What could cause this?
advancedTests whether you know a poorly chosen partition key (like a low-cardinality field) creates a hot partition.
Why do Kafka consumer groups keep rebalancing every few minutes, and how do you minimize the disruption?
advancedTests whether you know session timeouts, slow processing exceeding max.poll.interval.ms, and static membership all factor in.
You have 10 consumers in a group but only 3 Kafka partitions. How many consumers actually process messages?
intermediateTests whether you know partition count is a hard ceiling on consumer parallelism within a group — the extra 7 sit idle.
A Kafka message reaches the Dead Letter Topic. How do you safely reprocess it after fixing the underlying issue?
advancedTests whether you know to replay from the DLT deliberately rather than just deleting and hoping the source retries.
What is enable.auto.commit=false and why do senior engineers prefer it over the default?
advancedTests whether you know manual commit lets you commit only after successful processing, avoiding silent message loss.
How do you implement a transactional Kafka producer in Spring Boot for exactly-once semantics?
advancedTests whether you know transactional.id and KafkaTransactionManager, and what read_committed means for downstream consumers.
What is the significance of max.poll.records and max.poll.interval.ms in preventing consumer rebalancing?
advancedTests whether you know a slow batch that exceeds max.poll.interval.ms triggers a rebalance even though the consumer is still alive.
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?
advancedTests whether you can reason through a real high-stakes production incident, not just recite the theory around lag.
Design exactly-once semantics for a fund-transfer payment microservice — no double debit, no lost credit.
expertTests whether you can combine idempotent producers, Kafka transactions, and a transactional outbox into one coherent design.
JPA Basics
What is JPA? How is it different from Hibernate?
beginnerTests whether you know JPA is a specification and Hibernate is one implementation of it, among others.
What is an Entity in JPA? Explain @Entity, @Table, @Id, @Column.
beginnerTests whether you know the basic annotations that map a Java class onto a database table.
What is JpaRepository? How does it differ from CrudRepository?
beginnerTests whether you know the extra JPA-specific and pagination/sorting capabilities JpaRepository adds on top.
What are derived query methods in Spring Data JPA? Give 5 examples.
intermediateTests whether you know how Spring Data JPA generates SQL just from a method name's naming convention.
Spring Security Practices
How do you securely handle passwords in Spring Boot?
intermediateTests whether you know to hash with a salted, slow algorithm like BCrypt via PasswordEncoder rather than reversible encryption or a fast general-purpose hash like SHA-256, since password storage needs to resist brute-force, not just obfuscate.
How would you debug a 401 Unauthorized error?
intermediateTests whether you'd check the request's actual Authorization header first -- missing/expired/malformed token, wrong signing key, clock skew on expiry, or a misconfigured SecurityFilterChain rejecting it before it reaches the resource -- rather than guessing at the business logic.
Spring MVC Annotations
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).
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.
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.
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.
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.
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.
JPA Relationships & Mapping
Explain @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany with examples.
beginnerTests whether you can correctly model and annotate all four core JPA relationship types.
What is the owning side of a relationship? What does mappedBy mean?
intermediateTests whether you know which side of a bidirectional relationship actually controls the foreign key column.
How do you handle the N+1 problem in JPA?
advancedOne of the most common Spring/JPA production bugs — tests whether you know how to spot and fix it with fetch joins or EntityGraph.
What is FetchType.LAZY vs FetchType.EAGER? Which should you prefer and why?
intermediateTests whether you know why lazy loading is the safer default and what breaks when you get it wrong (LazyInitializationException).
Bean Lifecycle & Thread Safety
Can a Spring bean be thread-safe simply because it is a singleton?
intermediateTests whether you know singleton scope only guarantees one shared instance, not thread safety -- any mutable state on that instance is still subject to race conditions across concurrent requests unless you synchronize or avoid shared mutable fields.
What happens if a singleton bean contains a non-thread-safe HashMap and multiple requests access it simultaneously?
advancedTests whether you'd identify the concrete failure mode -- lost updates, infinite loops from HashMap's internal resizing under concurrent writes, or ConcurrentModificationException -- and fix it with ConcurrentHashMap rather than just adding synchronized broadly.
Hibernate Internals
What are the different entity states in Hibernate: Transient, Persistent, Detached, Removed?
intermediateTests whether you know how Hibernate tracks an entity's lifecycle relative to the persistence context.
What is the First-Level Cache in Hibernate? Can you disable it?
intermediateTests whether you know the session-scoped cache is mandatory and always on, unlike the optional second-level cache.
What is the Second-Level Cache? How do you configure it with EhCache?
advancedTests whether you know how to share cached entities across sessions and the staleness risk that comes with it.
What is dirty checking in Hibernate? How does it work automatically?
intermediateTests whether you know Hibernate auto-detects field changes on a managed entity and flushes UPDATE statements without an explicit save call.
What is the difference between session.get() and session.load()?
intermediateTests whether you know one returns null and the other a lazy proxy when the record doesn't exist.
Kafka Reliability & Throughput
How would you design a notification/event-driven system (Kafka + consumers) for payments?
advancedTests 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.
How does event-driven architecture maintain high throughput when a broker fails?
advancedTests 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.
How would you design an idempotent Kafka consumer?
advancedTests 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.
What metrics and alerts would you configure for consumer backlog?
advancedTests 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.
What happens when a database crashes while consuming data from Kafka, and how do you handle it?
advancedTests 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.
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?
advancedTests 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.
Given three microservices A -> B -> C, if C fails, how can you prevent failure propagation using Kafka (DLQ, asynchronous decoupling, backpressure)?
advancedTests 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.
How would you handle Kafka poison messages, retries, DLT/DLQ and offsets?
advancedTests 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.
How would you guarantee that a message is not lost?
advancedTests 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.
When would you use REST vs Kafka?
intermediateTests 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
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.
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.
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.
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.
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.
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.
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
What is consumer rebalancing?
intermediateTests 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.
How does Kafka handle message retention?
intermediateTests 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.
How can you change topic retention settings?
intermediateTests 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.
How many partitions can a Kafka topic have?
intermediateTests 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.
How do you decide the number of Kafka partitions?
advancedTests 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.
How would you design Kafka-based credit/debit processing with ordering and high throughput?
advancedTests 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.
How does Kafka maintain message ordering? How would Kafka partitions help with ordering?
intermediateTests 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
What is @Transactional? Where can you apply it — class vs method level?
beginnerTests whether you know the basics of Spring's declarative transaction management and its annotation scope rules.
What are transaction propagation types? Explain REQUIRED, REQUIRES_NEW, NESTED.
intermediateTests whether you know how nested @Transactional calls decide whether to join, suspend, or start a new transaction.
What is transaction isolation? Explain the 4 isolation levels.
intermediateTests whether you know how READ_UNCOMMITTED through SERIALIZABLE trade off consistency against concurrency.
When does @Transactional NOT work? Give 3 common pitfalls.
advancedOne of the most-asked Spring gotchas — tests whether you know self-invocation, private methods, and proxy limitations break it silently.
What is optimistic locking in JPA? How do you implement it with @Version?
advancedTests whether you know how version-column-based conflict detection avoids holding a database lock for the whole transaction.
Redis & Caching
How do you prevent a cache stampede when using Spring's @Cacheable annotation?
advancedTests whether you know @Cacheable alone doesn't coalesce concurrent misses, and what actually does (locking, soft TTL).
Redis is down. Should your application also go down? How would you design the fallback?
advancedTests whether you know caching should degrade gracefully to the database, not become a hard dependency that takes down the app.
How would you solve the cache invalidation problem when multiple service instances are running?
advancedTests whether you know local in-memory caches need a coordination mechanism (pub/sub or shared cache) to stay consistent across instances.
What are the different Redis eviction policies and when would you choose each?
advancedTests whether you know the tradeoffs between allkeys-lru, volatile-lru, allkeys-lfu, and the noeviction default.
How do you implement distributed locking using Redis — SETNX vs Redisson?
advancedTests whether you know the difference between a raw atomic SETNX-with-TTL lock and a library that handles renewal and edge cases for you.
What is the problem with a distributed lock expiring before the job holding it completes?
advancedTests whether you know a second process can acquire the 'freed' lock while the first is still working, causing double-processing.
What is a Redis pipeline and how does it improve performance?
advancedTests whether you know batching commands avoids paying a network round trip for every single Redis call.
What is the difference between Redis Cluster and Redis Sentinel?
advancedTests whether you know one shards data across nodes for scale while the other provides high availability via failover for a single dataset.
How do you handle cache warming after a deployment or Redis restart to avoid a cold-cache traffic spike hitting the database?
advancedTests whether you know to proactively pre-populate hot keys instead of letting production traffic discover the cold cache.
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?
advancedTests whether you know a Bloom Filter can cheaply reject requests for keys that provably don't exist, before they ever reach the DB.
After enabling caching, your database load drops as expected, but memory usage keeps climbing. What might be wrong?
advancedTests whether you know unbounded cache growth (no TTL, no max size) silently turns a cache into a memory leak.
Spring Ecosystem
What is the difference between Spring Boot and Spring Cloud?
beginnerSpring 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.
What is the difference between Spring Boot and Microservices?
beginnerSpring 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.
What is the difference between synchronous and asynchronous communication in microservices?
intermediateIn 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
How does Spring Security's filter chain work?
intermediateTests whether you know a request passes through an ordered chain of filters before ever reaching your controller.
What is JWT? How do you implement JWT-based authentication in Spring Boot?
intermediateTests whether you know how a stateless, signed token replaces server-side session storage for authentication.
What is @PreAuthorize and @Secured? What is the difference?
intermediateTests whether you know @PreAuthorize supports full SpEL expressions while @Secured only supports simple role checks.
What is CSRF protection? When should you disable it?
intermediateTests whether you know why CSRF matters for browser sessions but is usually irrelevant for stateless token-based APIs.
What do you know about Spring Security?
intermediateTests 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.
@PreAuthorize vs @Secured. Which annotation enables method-level security?
intermediateTests 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.
How does role-based authorization work?
intermediateTests 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.
How are authentication and authorization implemented in your application?
intermediateTests 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.
What is JWT? What is the structure of a JWT token?
intermediateTests 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.
API Gateway generates a JWT and forwards the request to microservice A. Should A validate the token again?
advancedTests 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.
Stateless vs stateful authentication.
intermediateTests 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.
What is CORS?
intermediateTests 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.
How do you secure microservices and REST APIs?
intermediateTests 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.
What changed in Spring Security 6 (Spring Boot 3)? What was removed?
advancedWebSecurityConfigurerAdapter 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.
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.
What is RestClient (Spring Boot 3.2)? How does it differ from RestTemplate and WebClient?
intermediateRestClient 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.
What is Problem Details (RFC 9457) support in Spring Boot 3?
intermediateSpring 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.
What is CRaC (Coordinated Restore at Checkpoint)? How does it complement native images?
advancedCRaC 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.
What is SecurityContext and SecurityContextHolder? What are the storage strategies?
advancedSecurityContext 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.
What is UserDetailsService? How does Spring Security authenticate a user?
intermediateUsernamePasswordAuthenticationFilter 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.
What is PasswordEncoder? Why must you never store plain-text passwords?
beginnerPasswordEncoder 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.
Where should you store JWT tokens on the client side? What are the security tradeoffs?
advancedlocalStorage/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.
How do you handle JWT token expiry and refresh tokens?
advancedUse 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.
What is the difference between authentication and authorization in Spring Security?
beginnerAuthentication 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.
Explain the OAuth2 Authorization Code Flow. When is it used?
advancedThe 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.
What is PKCE and why is it required for SPAs and mobile apps?
advancedPKCE (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.
What is the difference between oauth2Login() and oauth2ResourceServer() in Spring Security?
advancedoauth2Login() 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().
How does Spring Security validate JWT tokens in an OAuth2 Resource Server?
advancedSpring 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.
How do you integrate Spring Boot with Keycloak or Okta?
advancedAdd 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
What is a Kafka broker, and what is a Kafka cluster?
beginnerA 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).
What is Kafka replication, and why does it matter?
beginnerEach 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.
How does Kafka achieve fault tolerance?
intermediateFault 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.
How does Kafka guarantee message durability?
intermediateKafka 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.
How does Kafka achieve high throughput and low latency?
intermediateKafka 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.
Caching, AOP & Testing
What is Spring Cache? How do you enable it with @EnableCaching?
beginnerTests whether you know the basics of Spring's caching abstraction layer over providers like EhCache or Redis.
What is the difference between @Cacheable, @CacheEvict, and @CachePut?
intermediateTests whether you know when to read from cache, remove from cache, or always update the cache regardless of a hit.
What is AOP? What problems does it solve?
beginnerTests whether you know how aspect-oriented programming pulls cross-cutting concerns like logging and security out of business logic.
Distributed Transactions & Saga
What is the Two-Phase Commit (2PC) protocol and why is it not recommended for microservices?
advancedTests whether you know 2PC's blocking coordinator model doesn't scale and creates a single point of failure across services.
When would you use the Saga pattern, and how would you handle a compensation transaction that itself fails?
advancedTests whether you've thought past the happy path — what happens when the undo step doesn't work either.
Payment succeeds, but the Order Service crashes right after. How do you recover safely without losing money or the order?
advancedTests whether you can reason through a concrete Saga recovery scenario, not just define the pattern abstractly.
How do you achieve exactly-once business processing on top of an at-least-once messaging system?
expertTests whether you know the trick isn't stopping duplicates from arriving — it's making processing idempotent so duplicates are harmless.
What is the dual-write problem in microservices, and how does the Outbox Pattern solve it?
advancedTests whether you know writing to a DB and publishing an event are two separate operations that can't be made atomic without help.
How does the Transactional Outbox Pattern work with Debezium or Change Data Capture (CDC)?
advancedTests whether you know CDC tails the database's own write-ahead log to publish outbox rows, instead of a fragile polling loop.
How do you handle outbox table growth in a high-throughput system?
advancedTests whether you know to prune published rows and index the table correctly so it doesn't become its own bottleneck.
What is eventual consistency, and how would you explain it to a non-technical business stakeholder?
advancedTests whether you can translate a technical consistency model into a concrete business-facing tradeoff.
How do you test distributed transactions in a microservices architecture?
advancedTests whether you know this needs dedicated integration environments and event-assertion tooling, not just unit tests per service.
What is the difference between the Outbox Pattern and the Saga Pattern — are they complementary or competing?
advancedTests whether you know Outbox solves reliable event publishing while Saga solves multi-step business transaction coordination — they're often used together.
How do you implement the Inbox Pattern for idempotent message consumption?
advancedTests whether you know tracking processed message IDs in a dedicated table is the consumer-side mirror of the Outbox Pattern.
Microservices Patterns
What is the API Composition pattern in microservices?
intermediateAPI 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.
What is Transaction Log Tailing, and how does it relate to the Transactional Outbox pattern?
intermediateTransaction 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.
What is the Polling Publisher pattern in the context of the Transactional Outbox?
intermediatePolling 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.
What is Data Offloading in a distributed system, and why is it used?
intermediateData 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.
What is Semantic Monitoring in microservices, and how is it different from standard health checks?
intermediateSemantic 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.
What is the Scaling Cube, and how does it apply to microservices architecture?
intermediateThe 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
What is the Circuit Breaker pattern, and why do retries alone make an outage worse?
intermediateTests 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.
How would you break a monolith into microservices in a fintech ecosystem?
advancedTests 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.
Why is throttling required in a microservices architecture?
intermediateTests 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.
Where would you use Microservices and where would you avoid them?
intermediateTests 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.
What is a circuit breaker, and how is it different from a bulkhead?
advancedTests 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
What is microservices architecture? How does it differ from monolithic architecture?
beginnerTests whether you can explain the tradeoffs, not just the buzzword — independent deployability versus operational simplicity.
What is the Database-per-Service pattern? Why is it important?
intermediateTests whether you understand why sharing one database across services quietly turns microservices back into a distributed monolith.
What is the Strangler Fig pattern? How do you migrate from monolith to microservices?
intermediateTests whether you know how to incrementally carve services out of a monolith without a risky big-bang rewrite.
Microservices vs monolith: why choose microservices?
intermediateTests 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.
How do your microservices communicate with each other? Synchronous vs asynchronous: when do you pick which?
intermediateTests 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.
What are Service Discovery and API Gateway? Which features does an API Gateway support?
intermediateTests 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.
What happens if a microservice fails, and how do you handle it?
advancedTests 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.
What is the Saga pattern? How do you handle distributed transactions and partial failures?
intermediateTests 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.
How do you maintain data consistency between microservices?
advancedTests 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.
Explain the 12 factors of a microservice (12-factor app).
intermediateTests 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.
What is the main infrastructure needed to support microservices?
intermediateTests 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.
Traffic suddenly increases 10x across your microservices. What would you change to keep the system stable?
advancedTests 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.
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?
advancedTests 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 Discovery (Eureka)
What is service discovery? Why is it needed in microservices?
beginnerTests whether you understand why hardcoded service IPs break down once instances scale and move dynamically.
What is Eureka Server? How do microservices register with it?
beginnerTests whether you know the registration and heartbeat mechanism behind Netflix Eureka.
What is the difference between client-side and server-side service discovery?
intermediateTests whether you know who's responsible for load-balancing the lookup result — the calling client or an intermediary.
Service Communication & Discovery
Service A to Service B: how will an exception thrown from Service B be handled?
intermediateTests whether you know a thrown exception in B surfaces to A only as an HTTP error status/body (or a timeout), and that A must explicitly map that response to its own exception handling rather than expecting the Java exception itself to propagate across the network.
How would you design service discovery in a microservices architecture?
advancedTests whether you can reason about the trade-off between client-side discovery (a registry like Eureka plus client-side load balancing) and server-side discovery (a load balancer or service mesh sidecar), and how health checks keep the registry from routing to dead instances.
How would you design an API Gateway for microservices?
advancedTests whether you'd centralize cross-cutting concerns -- auth, rate limiting, routing, request aggregation -- at the gateway while keeping it thin enough that it doesn't become a bottleneck or a single point of business logic that couples all downstream services together.
What code is required to make service-to-service communication asynchronous?
intermediateTests whether you reach for @Async with a configured executor, a CompletableFuture-returning method, or publishing to a message broker -- and know that forgetting @EnableAsync or calling an @Async method from within the same class silently makes it run synchronously anyway.
Distributed Tracing & Observability
How would you implement observability across Microservices?
advancedTests whether you reach for the three pillars together -- structured logs correlated by trace ID, metrics for the RED/USE signals, and distributed traces -- rather than treating logging alone as sufficient observability in a distributed system.
How would you determine whether the issue is with the application, database, infrastructure, network, or downstream services?
advancedTests whether you'd triage top-down using distributed traces to localize which hop in the call chain is slow or erroring, then correlate with each layer's own metrics (DB query time, infra CPU/network, downstream SLA) instead of guessing based on symptoms alone.
How do you trace a request across Service A -> Service B -> Service C?
intermediateTests whether you know this requires a tracing framework (Sleuth/Micrometer Tracing, Zipkin, Jaeger) that creates spans per hop under one trace, rather than trying to stitch together independent service logs after the fact.
How is the Trace ID propagated between services?
intermediateTests whether you know the trace ID travels as an HTTP header (or message header for async calls) that each service must explicitly read and forward -- it isn't automatic across network boundaries, which is exactly where traces silently break if a client or filter drops the header.
API Gateway
What is an API Gateway? What responsibilities does it have?
beginnerTests whether you know the gateway's role in routing, auth, rate limiting, and shielding internal services from clients.
How do you implement rate limiting in Spring Cloud Gateway?
intermediateTests whether you know how to configure a request-rate-limiter filter backed by Redis to throttle abusive clients.
API Design, Performance & Resilience
An API works perfectly with 100 concurrent users but times out at 10,000, even though CPU sits at only 40%. Why?
expertTests whether you know low CPU with high failure at scale usually points to thread pool or connection pool saturation, not compute.
Average API latency is 200ms, but p99 is 8 seconds. What is the real problem, and why does average latency hide it?
advancedTests whether you know averages mask tail latency, and that a small fraction of very slow requests is often the actual production issue.
Retries are making an outage worse instead of better. How does a retry storm actually happen, and how do you prevent it?
advancedTests whether you know synchronized retries without jitter can pile onto an already-struggling service and push it further down.
When would you use a Circuit Breaker, a Retry, a Timeout, and a Bulkhead pattern — and how do they combine?
advancedTests whether you know these four resilience patterns solve different failure modes and are usually layered together, not chosen one at a time.
Where would you store an idempotency key, and how do you handle two concurrent requests arriving with the same key?
advancedTests whether you've thought through the race condition of two identical requests landing at nearly the same instant.
The same resource is updated from two devices simultaneously. How do you prevent one update from silently overwriting the other?
advancedTests whether you know optimistic locking (a version check) catches this cleanly without holding a lock the whole time.
Two users try to book the last available seat at the exact same moment. How do you prevent double booking?
advancedTests whether you can pick correctly between optimistic locking, pessimistic locking, or an atomic decrement for this exact scenario.
How would you process a 5GB CSV file upload without causing an OutOfMemoryError?
advancedTests whether you know to stream and process the file line by line instead of loading it entirely into memory first.
How would you trace one request as it flows across five microservices and millions of log entries?
advancedTests whether you know a propagated correlation ID plus distributed tracing is what makes this actually possible.
Your API's SLA is 1 second, but a downstream dependency's timeout is set to 2 seconds. What's wrong with this design?
advancedTests whether you know timeout budgets must cascade correctly — a downstream timeout longer than your own SLA guarantees you'll breach it.
How do you implement API versioning — URI versioning vs header versioning vs media type versioning — and what are the tradeoffs of each?
advancedTests whether you know the practical implications each approach has for clients, caching, and backward compatibility.
How would you rate-limit APIs differently for different customers or tenants?
advancedUse 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.
Config Server
What is Spring Cloud Config Server? What problems does it solve?
beginnerTests whether you know how to centralize configuration across many microservices instead of duplicating property files.
What is @RefreshScope? How does it enable dynamic config refresh without restart?
intermediateTests whether you know how to pick up new config values live without redeploying a running service.
Inter-Service Communication
What is OpenFeign? How does it simplify REST calls between microservices?
beginnerTests whether you know how a declarative HTTP client interface replaces manually built RestTemplate calls.
What is WebClient? How is it better than RestTemplate for reactive calls?
intermediateTests whether you know WebClient supports non-blocking reactive calls while RestTemplate is fundamentally blocking (and now deprecated).
Distributed Transactions & Consistency
Explain Saga, Transactional Outbox, CDC and Distributed Locking
advancedTests whether you can place each pattern correctly: Saga coordinates a multi-step business transaction, the Outbox pattern makes publishing an event atomic with a local DB write, CDC streams those DB changes without the app publishing explicitly, and distributed locking serializes access to a shared resource across instances -- and that they're complementary, not alternatives.
Explain how the Saga pattern can be used for fund transfer, including the architecture/flow of a Saga-based fund transfer system
advancedTests whether you can walk through the debit-then-credit sequence as local transactions with compensating actions (refund the debit if the credit fails), and whether you'd choose orchestration for the stronger consistency guarantees fund transfer needs over choreography's looser coupling.
How do you ensure data consistency across multiple services without distributed transactions?
advancedTests whether you reach for eventual consistency via sagas or the outbox pattern plus idempotent consumers, rather than trying to simulate a cross-service ACID transaction, which doesn't scale and creates tight coupling through 2PC-style locking.
Resilience Patterns (Resilience4j)
What is the Circuit Breaker pattern? Explain Open, Closed, and Half-Open states.
beginnerTests whether you know how a circuit breaker stops hammering a failing downstream service and how it decides to retry.
How do you implement a Circuit Breaker in Spring Boot using Resilience4j?
intermediateTests whether you can actually wire up the annotation-based Resilience4j circuit breaker with a fallback method.
What is the Bulkhead pattern? How does Resilience4j implement it?
intermediateTests whether you know how isolating resource pools per dependency stops one slow service from starving all the others.
Messaging (Kafka & RabbitMQ)
What is Apache Kafka? How does it differ from RabbitMQ?
beginnerTests whether you know the log-based streaming model versus traditional message-queue broker model, and when each fits.
What are Kafka Topics, Partitions, Producers, Consumers, and Consumer Groups?
beginnerTests whether you know Kafka's core vocabulary and how partitions enable parallel consumption within a consumer group.
JPA & Hibernate Internals
How can you skip one field from being persisted in the database using Spring Data JPA?
intermediateTests 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.
First-level vs Second-level cache
intermediateTests 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.
persist() vs merge()
intermediateTests 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.
Explain what happens internally when a request reaches a Spring Boot application (Controller, Service, Repository, Hibernate, JDBC, database)
intermediateTests 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.
Design a product API supporting category filtering, price sorting, pagination, JPA Specification/Criteria filtering, and invalid-parameter exception handling
advancedTests 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.
When would you NOT use records, especially with JPA/Hibernate entities?
advancedTests 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.
Java transient vs JPA @Transient?
intermediateTests 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.
Why can returning JPA entities directly from REST controllers create unexpected problems?
advancedTests 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.
Distributed Tracing & Security
What is distributed tracing? Why is it important in microservices?
beginnerTests whether you know how a trace ID follows a request across service boundaries to make debugging possible at all.
What is mutual TLS (mTLS)? How do microservices use it for service-to-service trust?
advancedTests whether you know both sides of a connection verify each other's certificate, not just the client verifying the server.
SOLID Principles in Practice
Your PaymentService has 15 if-else branches for different payment types. Which SOLID principle is being violated, and how would you refactor it?
advancedTests whether you can spot an Open/Closed Principle violation in real code and know Strategy pattern is the standard fix.
Can a class with only a single method still violate the Single Responsibility Principle?
advancedTests whether you know SRP is about reasons to change, not method count — a single method can still mix multiple concerns.
When does implementing the Open/Closed Principle become over-engineering?
advancedTests whether you know abstracting for change that will never actually happen just adds indirection with no payoff.
What happens when a child class compiles fine but returns unexpected results compared to its parent contract?
advancedTests whether you know this is a Liskov Substitution violation even without a compile error — the contract broke silently.
What problems do 'fat interfaces' create in large systems, and how would you split one without breaking existing consumers?
advancedTests whether you know a bloated interface forces implementers to depend on methods they don't use, and how to migrate safely.
What is the difference between Dependency Injection and Dependency Inversion? Does using @Autowired automatically guarantee DIP?
advancedTests whether you know DI is a mechanism while DIP is a design principle, and injecting a concrete class still violates DIP.
How do SOLID principles apply at the microservice level, not just the class level — is SRP applicable to service boundaries?
advancedTests whether you can map object-oriented design principles onto architectural decisions about service decomposition.
Looking at a 2000-line service class, which SOLID violations would you expect to find first, and how would you start refactoring it?
advancedTests whether you have a practical, prioritized approach to untangling a real legacy God class, not just theory.
Design Patterns for Distributed Systems
What is the SAGA pattern? Explain Choreography vs Orchestration.
intermediateTests whether you know how to maintain consistency across services without a distributed transaction, and the two coordination styles.
What is CQRS (Command Query Responsibility Segregation)?
intermediateTests whether you know why separating the write model from the read model can simplify a complex domain.
What is Event Sourcing? How does it differ from traditional CRUD?
intermediateTests whether you know how storing every state-changing event (instead of just current state) enables replay and audit.
What is CAP theorem? How does it apply to distributed microservices?
advancedTests whether you know why you can't have Consistency, Availability, and Partition tolerance all at once, and what tradeoff you'd pick.
JPA Performance & Mapping
LazyInitializationException occurs in production but not in development. Why?
advancedTests whether you'd suspect an environment difference like Open Session in View being enabled in dev (masking the problem by keeping the session open through rendering) but disabled or configured differently in prod, or a transaction boundary that only gets exercised under prod request patterns.
A JPA query performs well at 100 rows but takes 45 seconds at 1 million. What is wrong?
advancedTests whether you'd suspect a missing index that only becomes a full table scan bottleneck at scale, an N+1 fetch triggered per row, or in-memory pagination/filtering on the entity list instead of pushing the filter down into the SQL.
Kubernetes & Production Ops
Your Kubernetes pod keeps restarting, but application logs show no clear error. How would you debug it?
advancedTests whether you know to check kubectl describe, previous container logs, OOMKilled status, and probe configuration.
What is the difference between liveness, readiness, and startup probes in Kubernetes, and why does confusing liveness with readiness matter for Spring Boot?
intermediateTests whether you know a common pitfall: using the same health endpoint for both can cause unnecessary pod restarts.
What is a CrashLoopBackOff and how do you debug it?
advancedTests whether you know Kubernetes' exponential backoff behavior for repeatedly-crashing containers and how to find the root cause fast.
What is a PodDisruptionBudget and why is it important during rolling deployments?
advancedTests whether you know it prevents voluntary disruptions (like node drains) from taking down too many replicas at once.
How do you implement graceful shutdown in a Spring Boot microservice running in Kubernetes so in-flight requests aren't dropped?
advancedTests whether you know server.shutdown=graceful, a SIGTERM handler, and a preStop hook all need to work together.
One pod consistently receives 80% of the traffic while the remaining pods stay nearly idle. Why might this happen?
advancedTests whether you know client-side connection reuse or a misbehaving load-balancing algorithm can defeat even distribution.
A scheduled job runs once locally but five times after scaling to five pods. How do you prevent this duplicate execution?
advancedTests whether you know a @Scheduled job needs a distributed lock (or ShedLock) to run exactly once across a clustered deployment.
Your Spring Boot application takes 5 minutes to start in production but only 20 seconds locally. How do you debug it?
advancedTests whether you know to check DB connectivity latency, DNS resolution, and autoconfiguration scanning under production networking.
What is the difference between resource requests and resource limits in Kubernetes, and what happens if limits are exceeded?
advancedTests whether you know exceeding a CPU limit throttles the pod while exceeding a memory limit gets it OOMKilled outright.
CORS & Cross-Origin Requests
What is CORS (Cross-Origin Resource Sharing), and what triggers a preflight OPTIONS request versus a simple request?
intermediateTests whether you know only certain request types (non-simple methods, custom headers) force the browser to preflight first.
What are the key CORS HTTP headers, and how do you configure CORS correctly in a Spring Boot application?
intermediateTests whether you know Access-Control-Allow-Origin, -Credentials, and -Methods and how to configure them without accidentally opening your API to everyone.
Pagination Strategies
What is the difference between offset-based pagination and cursor-based pagination, and why does offset pagination break under fast-changing data?
advancedTests whether you know inserts during scrolling shift offsets and cause skipped or duplicated rows, which cursors avoid entirely.
How do you encode a pagination cursor as an opaque token so clients can't reverse-engineer your implementation details?
advancedTests whether you know to base64-encode the actual sort key values instead of exposing raw IDs or offsets directly.
Database Migrations
What is Flyway and what is the difference between Flyway and Liquibase? When would you choose each?
intermediateTests whether you know Flyway's plain-SQL-first philosophy versus Liquibase's changelog-based, database-agnostic approach.
How do you change a database schema without breaking the older version of your application that's still running (expand-contract pattern)?
advancedTests whether you know to add new columns first, deploy dual-compatible code, migrate data, and only remove old columns in a later release.
How do you perform zero-downtime database migrations using Flyway when your service is deployed with rolling updates?
advancedTests whether you know old and new pod versions run against the same schema simultaneously during a rollout, so migrations must be backward-compatible.
gRPC & Alternative Protocols
What is gRPC and when would you choose it over REST for inter-service communication?
advancedTests whether you know gRPC's binary Protobuf format and HTTP/2 multiplexing pay off specifically for low-latency internal service calls.
What are the four types of gRPC communication — Unary, Server Streaming, Client Streaming, Bidirectional Streaming?
advancedTests whether you know when a simple request-response isn't enough and one side (or both) needs to stream data continuously.
Server-Sent Events & Real-Time
What is the difference between Server-Sent Events (SSE), WebSocket, and polling — when should you use each?
advancedTests whether you know SSE fits one-way server-to-client streaming, while WebSocket is needed for genuine bidirectional communication.
How does SSE scale across multiple server instances? What's the challenge and how do you solve it with Redis Pub/Sub?
advancedTests whether you know a client's SSE connection is pinned to one server instance, so events must be fanned out to whichever instance holds that connection.
Production Logging & Observability
What is structured logging (JSON logs), and why is it better than plain text logs for production observability?
advancedTests whether you know structured fields let log aggregation tools query and filter logs instead of grepping through text.
What is MDC (Mapped Diagnostic Context) and how do you use it to attach a request ID to every log line for a request?
advancedTests whether you know how to thread a correlation ID through every log statement without passing it as a parameter everywhere.
What are the three pillars of observability, and how do you implement each in a Java microservice?
advancedTests whether you can name logs, metrics, and traces and connect each to a concrete Java tool (structured logs, Micrometer, OpenTelemetry).
Spring Internals — Bean Lifecycle & Proxies
Why can returning a new object from a custom BeanPostProcessor silently remove @Transactional, @Cacheable, and @Secured proxies?
advancedIf 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.
Why does declaring a BeanFactoryPostProcessor as a non-static @Bean sometimes break @Value placeholder injection?
advancedBeanFactoryPostProcessors 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.
How can a custom FactoryBean accidentally bypass Spring AOP proxy creation?
advancedAOP 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.
Why does a manually instantiated bean (new MyService()) never receive dependency injection or AOP advice?
intermediateDependency 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.
How does Spring decide between JDK Dynamic Proxy and CGLIB, and what production issues can that choice introduce?
advancedJDK 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.
Why can SmartInitializingSingleton trigger expensive database calls before your application is actually ready?
advancedSmartInitializingSingleton.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.
What happens when two auto-configurations define the same bean with conflicting conditions?
advancedSpring 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.
Why can overriding an auto-configured bean unintentionally disable metrics, tracing, or health checks?
advancedMany 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.
How do ApplicationContextInitializer, BeanFactoryPostProcessor, and BeanPostProcessor execute during the Spring lifecycle?
advancedApplicationContextInitializer 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).
Why does exposing JPA entities directly from REST APIs eventually become a production problem?
intermediateEntities 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.
How can Open Session in View hide performance bottlenecks until your database connection pool gets exhausted?
advancedOSIV 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.
Why can @TransactionalEventListener(AFTER_COMMIT) silently stop working in asynchronous event processing?
advancedAFTER_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.
Why can a poorly written OncePerRequestFilter execute multiple times for a single request?
advancedOncePerRequestFilter 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.
How does @Configuration(proxyBeanMethods=false) improve startup performance, and what trade-offs does it introduce?
advancedBy 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
What is @Transactional and how does Spring manage transactions?
intermediateTests 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.
REQUIRED vs REQUIRES_NEW. Give a practical use case for REQUIRES_NEW.
intermediateTests 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.
Why can @Transactional fail when a method is called from another method in the same class?
advancedTests 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.
@Transactional on a private method: what actually happens?
advancedTests 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.
A @Transactional method calls a REQUIRES_NEW method in the same class. How many transactions run?
advancedTests 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.
A checked exception is thrown inside a @Transactional method. Does it roll back?
intermediateTests 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
What are Virtual Threads and how do they differ from platform (OS) threads?
intermediatePlatform 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.
How do you enable Virtual Threads in Spring Boot 3.2+?
intermediateSet `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.
How do Virtual Threads interact with @Transactional and connection pools?
advancedEach 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.
How does Spring Boot support GraalVM Native Image, and what are its limitations?
advancedSpring 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
What is the Circuit Breaker pattern? How do you implement it and set thresholds?
intermediateTests 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.
Retry vs Circuit Breaker.
intermediateTests 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.
A microservice calls another service that takes 10 seconds to respond. How do you stop your app from getting stuck?
advancedTests 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.
A microservice goes down while processing an order. How should the system handle it?
advancedTests 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.
One microservice becomes very slow and others start timing out. How do you stop cascading failure?
advancedTests 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.
Service C succeeds but times out before B gets the response (A to B to C). Design an idempotent workflow for when B retries.
advancedTests 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.
A downstream API is unavailable and your retries generate even more traffic. How do you redesign the retry strategy?
advancedTests 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.
The same payment request reaches your API twice, or a client retries after a timeout. How do you guarantee one charge?
advancedTests 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.
How do you design resilient microservices?
advancedTests 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.
Production Debugging
A microservice has slow DB calls that hurt the overall flow. How do you stabilize it while you investigate the bottleneck?
advancedTests whether you'd add a timeout and bulkhead immediately to stop the slow calls from exhausting the whole service's thread pool, buying time to investigate the query/index/connection-pool issue without the symptom cascading further.
A microservice frequently runs out of memory and restarts. How do you debug the root cause?
advancedTests whether you'd capture a heap dump just before the crash (via -XX:+HeapDumpOnOutOfMemoryError) and analyze retained object graphs for growing collections or caches, rather than just bumping the memory limit and hoping it goes away.
Spring AI — Core, ChatClient & RAG
What is Spring AI? How does it differ from LangChain? What is its core design principle?
beginnerSpring 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.
What is the ChatClient API? How is it similar to WebClient and RestClient?
intermediateA 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.
What is the Advisors API? Explain how the advisor chain works.
advancedAdvisors 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).
What model types does Spring AI support? How are embeddings used?
beginnerChatModel, EmbeddingModel, ImageModel, AudioTranscriptionModel, TextToSpeechModel, ModerationModel. Embeddings convert text into high-dimensional vectors for semantic similarity search — the foundation RAG is built on.
How does Spring AI's structured output work? How do you map LLM responses to POJOs?
intermediateCall .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.
What AI providers does Spring AI support and how do you switch between them?
beginnerOpenAI, 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.
What is RAG? Why does it exist and what problems does it solve?
beginnerRAG (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.
Explain the full RAG ingestion pipeline in Spring AI.
intermediateLoad 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).
What is the difference between QuestionAnswerAdvisor and RetrievalAugmentationAdvisor?
advancedQuestionAnswerAdvisor 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.
What vector stores does Spring AI support? How do you switch between them?
intermediatePGVector, 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.
What is query rewriting (RewriteQueryTransformer)? Why does it improve RAG quality?
advancedConversational 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.
How do you implement conversation memory in Spring AI?
intermediateUse 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.
What is the difference between RAG and fine-tuning? When do you use each?
advancedRAG 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.
What are chunking strategies in RAG? How does chunk size affect quality?
intermediateFixed-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.
What is hybrid search in RAG? How does it combine vector and keyword search?
advancedVector 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.
How do you evaluate a RAG pipeline? What metrics matter?
advancedRetrieval 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
Explain Zero-Copy in Kafka.
intermediateTests 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.
Do you know about the Kafka Schema Registry?
intermediateTests 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.
What happens when a database crashes while consuming data from Kafka, and how do you handle it?
advancedTests 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.
Have you worked with MQ or Kafka? How have you used Kafka for microservice communication?
intermediateTests 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.
What is a Kafka partition? What is a consumer group?
intermediateTests 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.
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?
advancedTests 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.
How do you make Kafka consumers idempotent? Messages are processed twice after a consumer restart; what do you do?
advancedTests 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.
What is a Dead Letter Topic? How do you handle poison messages?
intermediateTests 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.
You add partitions to a live topic. What happens to per-key ordering?
advancedTests 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.
A producer retries after a timeout and the message lands twice. Which setting stops that?
intermediateTests 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.
Consumer lag keeps increasing (consumers slower than the producer, or lag rises although consumers are running). How do you troubleshoot?
advancedTests 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.
Tuning Kafka throughput: find bottlenecks before Kafka, pick producer and consumer optimizations, and prove a 40% gain.
advancedTests 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.
The DB update succeeds but Kafka publishing fails. How do you guarantee the event is not lost?
advancedTests 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.
Kafka publishing succeeds but the DB transaction rolls back. How could consumers receive an event for data that does not exist?
advancedTests 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.
How do you design reliable Kafka consumers?
advancedTests 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.
What happens if the message queue goes down?
intermediateTests 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
What is tool/function calling in Spring AI? How do you register a Java method as a tool?
intermediateAnnotate 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.
What is an AI Agent? How do you build one with Spring AI?
advancedAn 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.
What is MCP (Model Context Protocol)? How does Spring AI integrate with it?
advancedMCP 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.
What is the ToolCallingManager interface? How does it manage the tool execution lifecycle?
advancedIt'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.
What is GraphRAG? How does it differ from standard vector RAG?
advancedStandard 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.
What is re-ranking in RAG? How does a CrossEncoder improve retrieval quality?
advancedInitial 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.
What are the agentic workflow patterns supported in Spring AI?
advancedPrompt 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.
How do you implement a multi-agent system in Spring AI?
advancedEach 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.
What is the difference between zero-shot, few-shot, and chain-of-thought prompting?
intermediateZero-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.
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.
How do you implement tool call error handling and retries in Spring AI?
advancedWrap 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.
What is semantic caching and how can it reduce LLM costs in Spring AI?
advancedStandard 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.
How do you handle LLM token limits in a production Spring AI application?
advancedEach 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.
What is the Guardrails pattern in Spring AI? How do you implement input/output validation?
advancedInput 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.
What is prompt injection and how do you defend against it in Spring AI?
advancedPrompt 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.
How do you implement streaming Server-Sent Events (SSE) with Spring AI in a REST controller?
intermediateReturn 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.
What is the difference between ChatMemory and VectorStore for context management?
intermediateChatMemory 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
Optimistic vs pessimistic locking. How does database optimistic locking differ from Java synchronization?
intermediateTests 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.
How do you configure a database connection pool, and how do you decide the pool size?
intermediateTests 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.
Explain database indexes and the difference between clustered and non-clustered indexes.
intermediateTests 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.
When a table is created, how is its storage allocated and managed on disk?
intermediateTests 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.
Stored procedure vs trigger.
intermediateTests 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.
Difference between RANK(), DENSE_RANK() and ROW_NUMBER().
intermediateTests 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.
Write an SQL query to rank employees based on their experience.
intermediateTests 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.
Explain the order of execution of SQL query clauses.
intermediateTests 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.
INNER JOIN vs LEFT JOIN.
intermediateTests 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.
COUNT(*) vs COUNT(1) vs COUNT(column).
intermediateTests 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.
How would you optimize a slow query?
advancedTests 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.
Explain ACID properties.
intermediateTests 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.
What is database normalization?
intermediateTests 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.
WHERE vs HAVING. Can aggregate functions be used with HAVING? With WHERE?
intermediateTests 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().
Write a query using WHERE, GROUP BY and HAVING.
intermediateTests 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.
Write an SQL query to find the second-highest salary.
intermediateTests 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.
Index on (status, created_at) and the query filters only on created_at. Does the index help?
advancedTests 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.
Two transactions read one row, both update it, and one update vanishes (or two threads update the same record). What prevents it?
advancedTests 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.
HikariCP reports a connection timeout although database connections are available. What could be happening?
advancedTests 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.
Database CPU hits 100% while application CPU stays low. How do you find the queries responsible?
advancedTests 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.
What happens if the database goes down?
intermediateTests 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.
How do you handle database replication lag?
advancedTests 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
How would you design a high-availability Spring Boot microservice? What are the key concerns?
advancedStateless design, externalized config, liveness/readiness health probes, circuit breakers, distributed tracing, structured JSON logging, horizontal autoscaling, graceful shutdown, tuned connection pooling, and idempotent APIs — each addresses a specific way a single-instance, tightly-coupled service fails under real production load.
What is graceful shutdown in Spring Boot? How do you configure it?
intermediateSet server.shutdown=graceful and spring.lifecycle.timeout-per-shutdown-phase=30s — on SIGTERM, Spring Boot stops accepting new requests but waits for in-flight ones to finish (up to the timeout) before shutting down. Align this timeout with Kubernetes' terminationGracePeriodSeconds so the two don't fight each other.
JPA & Hibernate
LAZY vs EAGER loading.
intermediateTests whether you know LAZY defers fetching an association until it's actually accessed (risking a LazyInitializationException outside a transaction), while EAGER fetches it immediately with the parent -- and whether you default to LAZY to avoid over-fetching unused associations.
200 orders on a page but 201 queries in the log. Name the problem and give fixes (including JOIN FETCH).
advancedTests whether you identify the N+1 problem precisely -- one query loads 200 orders, then a lazy association fires a separate query per order -- and fix it with JOIN FETCH, @EntityGraph, or batch fetching rather than just switching to EAGER everywhere, which creates its own over-fetching issue.
save() vs saveAndFlush().
intermediateTests whether you know save() just schedules the write in Hibernate's session (flushed later, typically at transaction commit or the next query), while saveAndFlush() forces the write to the DB immediately -- useful when you need the generated ID or DB-side effects right away within the same transaction.
Hibernate second-level cache with two app instances: why does instance B serve stale data?
advancedTests whether you know the second-level cache is local to each JVM by default -- instance A updating an entity invalidates only its own cache, leaving instance B's cached copy stale unless you configure a distributed/shared cache provider that propagates invalidation across instances.
REST APIs
PUT vs PATCH.
intermediateTests 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.
Difference between POST and PUT. Any other differences?
intermediateTests 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.
Difference between PUT and QUERY methods in HTTP.
intermediateTests 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.
When does a server return 429, and how would you handle it?
intermediateTests 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.
Common HTTP status codes.
intermediateTests 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.
What is idempotency in REST APIs?
intermediateTests 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.
How do you version an API, or change it without breaking existing clients?
advancedTests 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.
How would you design a scalable REST API?
advancedTests 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.