Skip to content

Java and Spring in Production: Concepts for Mid/Senior Interviews

The Java and Spring production concepts mid and senior engineers are tested on, with concrete examples, failure modes and the traps interviewers look for.

13 min read7 conceptsTechnical testsJava and Spring in production

Situational questions about Java and Spring rarely test whether you remember an annotation. They test whether you can explain what happens at runtime when real traffic arrives: which transaction is open, which thread is blocked, which pool is exhausted, and why the container was killed. This guide covers seven areas that come up again and again for mid and senior roles. Each one explains the mechanism behind the behaviour, shows a short example from an invented system, and lists the traps that separate a strong answer from a textbook one. When you answer, name the mechanism first, such as a proxy, a pool, a queue or a heap limit. Then describe the symptom you would see in production and the fix you would apply. That structure works for almost every question in this area.

Study order

If time is short, go in this order.

  1. @Transactional is a proxy: boundaries, propagation and rollback

    This is the most frequently probed Spring topic. Self-invocation and rollback rules show whether you understand proxies or only annotations.

  2. Connection pools, timeouts and safe retries

    Pool exhaustion and missing timeouts cause most real outages, and situational questions often describe exactly that scenario.

  3. JPA fetching, N+1 queries and open-in-view

    N+1 queries and open-in-view are classic performance traps in almost every Spring Data codebase.

  4. Thread pools, @Async and virtual threads

    Executor queue semantics and virtual threads test your concurrency judgement and knowledge of current Java.

  5. Singleton beans, scopes and thread safety

    Shared mutable state in singleton beans is a common source of bugs that appear only under load.

  6. JVM memory, GC and containers

    Senior candidates are expected to diagnose OOMKilled pods versus OutOfMemoryError and know the right tools.

  7. Health probes, metrics and graceful shutdown

    Probes, metrics and shutdown behaviour show whether you have actually run services in Kubernetes.

@Transactional is a proxy: boundaries, propagation and rollback

Spring applies @Transactional through a proxy that wraps your bean. The transaction starts when a call enters the proxy and commits or rolls back when that call returns. This has a direct consequence: when a method calls another method on this, the call skips the proxy, so any annotation on the inner method is ignored. The same rule applies to @Async, @Cacheable and @Retryable.

By default, Spring rolls back only on unchecked exceptions (RuntimeException and Error). A checked exception commits whatever was written before it was thrown, unless you set rollbackFor. Propagation controls how nested calls behave. REQUIRED joins the existing transaction. REQUIRES_NEW suspends it and opens a separate one on a second database connection, which suits audit records that must survive a rollback of the outer work.

Imagine a refund service at a ticketing company called Stagepass. It writes a refund row, records an audit entry that must persist even if the refund fails, and then calls a payment gateway. Keep remote calls outside long transactions where you can. A 5-second gateway timeout inside a transaction holds a database connection and its row locks for 5 seconds.

Java

@Service
public class RefundService {
    private final RefundRepository refunds;
    private final RefundAuditService audit;
    private final PaymentGateway gateway;

    public RefundService(RefundRepository refunds, RefundAuditService audit, PaymentGateway gateway) {
        this.refunds = refunds;
        this.audit = audit;
        this.gateway = gateway;
    }

    @Transactional(rollbackFor = GatewayException.class)
    public void issueRefund(long ticketId, long amountCents) throws GatewayException {
        refunds.save(new Refund(ticketId, amountCents));
        audit.record(ticketId, "REFUND_REQUESTED"); // separate bean, so the proxy applies
        gateway.refund(ticketId, amountCents);      // checked exception now rolls back the refund row
    }
}

@Service
class RefundAuditService {
    private final AuditRepository auditLog;

    RefundAuditService(AuditRepository auditLog) {
        this.auditLog = auditLog;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void record(long ticketId, String event) {
        auditLog.save(new AuditEntry(ticketId, event));
    }
}

The audit entry commits in its own transaction. A gateway failure rolls back only the refund row.

Traps

  • Putting @Transactional on a private method or calling it through this: the proxy never sees the call, so no transaction is opened.
  • Assuming checked exceptions roll back. They commit by default unless you configure rollbackFor.
  • Catching an exception inside a REQUIRED inner method that has already marked the transaction rollback-only. The outer commit then fails with UnexpectedRollbackException.
  • Overusing REQUIRES_NEW under load. Each nested call needs a second pooled connection, and that can deadlock a small pool.
  • Calling slow HTTP services inside a transaction, which holds a connection and its locks for the whole duration of the call.

JPA fetching, N+1 queries and open-in-view

The N+1 problem happens when you load N parent entities in one query and then touch a lazy association on each of them. Hibernate fires one extra query per parent. In development, with 10 rows, nobody notices. In production, a page of 500 orders becomes 501 round trips.

The fixes are a fetch join in JPQL, an @EntityGraph on the repository method, or batch fetching (hibernate.default_batch_fetch_size), which turns N lazy loads into a few IN queries. For read-heavy endpoints, a DTO projection that selects only the columns you need is often the best option, because it skips entity management altogether.

Spring Boot enables spring.jpa.open-in-view by default. It keeps the persistence context open until the HTTP response is rendered, which lets lazy loading silently run during JSON serialisation. Disabling it makes N+1 queries fail loudly with LazyInitializationException inside the service layer, where you can fix them. Senior candidates are expected to mention it.

Java

public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, Long> {

    // One query: orders and their lines together
    @Query("select distinct o from PurchaseOrder o join fetch o.lines where o.supplierId = :supplierId")
    List<PurchaseOrder> findWithLinesBySupplier(@Param("supplierId") long supplierId);

    // Same effect, declared with an entity graph
    @EntityGraph(attributePaths = "lines")
    List<PurchaseOrder> findByStatus(OrderStatus status);

    // Read-only listing: a projection, no entities, no lazy loading
    @Query("select new com.greenbay.orders.OrderSummary(o.id, o.status, o.totalCents) from PurchaseOrder o where o.supplierId = :supplierId")
    List<OrderSummary> findSummaries(@Param("supplierId") long supplierId);
}

Three ways to load a supplier's purchase orders without one query per order.

Traps

  • Combining a collection fetch join with pagination. Hibernate logs a warning and paginates in memory after loading every row.
  • Fetch-joining two List collections at once, which throws MultipleBagFetchException or produces a Cartesian product.
  • Switching associations to FetchType.EAGER to hide N+1. That makes every query load the association and often still issues extra selects.
  • Leaving open-in-view enabled, so lazy loads run during serialisation and outside any transaction you control.

Connection pools, timeouts and safe retries

Most Spring production incidents are pool exhaustion caused by a slow dependency. HikariCP gives each request a database connection from a fixed pool. When every connection is busy, new callers wait up to connectionTimeout (30 seconds by default) and then fail. A bigger pool rarely helps, because the database itself has a limit on useful concurrency. Size the pool from measurements, keep transactions short, and set maxLifetime below any idle timeout enforced by the database or a proxy in between.

Every outbound HTTP call needs both a connect timeout and a read timeout. Without them, a hung upstream ties up your request threads until the whole service stops responding. Pick timeouts from the upstream's latency percentiles and your own SLA, not from defaults.

Retries help only with transient failures, and they multiply load. Use a small number of attempts with exponential backoff and jitter, retry only idempotent operations, and send an idempotency key when the operation has side effects, such as creating a shipment, so the server can deduplicate. A circuit breaker (for example Resilience4j) stops calling an upstream that keeps failing and gives it time to recover.

Java

@Configuration
public class CarrierClientConfig {

    @Bean
    RestClient carrierClient() {
        HttpClient http = HttpClient.newBuilder()
                .connectTimeout(Duration.ofMillis(500))
                .build();
        JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(http);
        factory.setReadTimeout(Duration.ofSeconds(2));

        return RestClient.builder()
                .baseUrl("https://carrier-api.parcelhub.internal")
                .requestFactory(factory)
                .build();
    }
}

@Service
class ShipmentClient {
    private final RestClient carrierClient;

    ShipmentClient(RestClient carrierClient) {
        this.carrierClient = carrierClient;
    }

    ShipmentResponse create(ShipmentRequest request, UUID idempotencyKey) {
        return carrierClient.post()
                .uri("/shipments")
                .header("Idempotency-Key", idempotencyKey.toString())
                .body(request)
                .retrieve()
                .body(ShipmentResponse.class);
    }
}

Explicit timeouts, plus an idempotency key that lets the caller retry the POST safely.

Traps

  • Relying on default HTTP client timeouts. Several clients default to no read timeout at all.
  • Retrying at every layer (gateway, service and client). Three layers of three attempts can produce 27 calls to a struggling upstream.
  • Retrying a non-idempotent POST without an idempotency key, which creates duplicate side effects.
  • Raising maximum-pool-size to fix connection timeouts when the real cause is long transactions or slow queries.

Thread pools, @Async and virtual threads

ThreadPoolExecutor grows in a specific order. It runs up to the core size, then queues tasks, and creates threads beyond the core only when the queue is full. With an unbounded queue, the maximum size is never reached and the backlog grows until memory runs out. Executors.newFixedThreadPool uses an unbounded queue. So does the executor Spring Boot auto-configures for @Async when you don't configure queue capacity.

A production executor needs a bounded queue, a rejection policy you chose on purpose, thread names you can find in a thread dump, and a graceful shutdown. CallerRunsPolicy applies backpressure: when the pool is saturated, the submitting thread runs the task itself, which slows producers down instead of dropping work.

Java 21 virtual threads make blocking I/O cheap. You can enable them in Boot 3.2+ with spring.threads.virtual.enabled=true. They do not raise your database's capacity, so the connection pool becomes the bottleneck instead, and you still need limits. On Java 21, blocking inside a synchronized block pins the carrier thread. JDK 24 removed most of that pinning, but ThreadLocal-heavy code and native calls still deserve review.

Java

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean(name = "invoicePdfExecutor")
    public ThreadPoolTaskExecutor invoicePdfExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(8);
        executor.setMaxPoolSize(16);          // used only once the queue is full
        executor.setQueueCapacity(200);       // bounded backlog
        executor.setThreadNamePrefix("invoice-pdf-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(30);
        return executor;
    }
}

@Service
class InvoicePdfService {
    @Async("invoicePdfExecutor")
    public CompletableFuture<byte[]> render(long invoiceId) {
        return CompletableFuture.completedFuture(PdfRenderer.render(invoiceId));
    }
}

A bounded executor for PDF rendering in a billing service, with backpressure and a clean shutdown.

Traps

  • Expecting maxPoolSize to kick in under load while the queue is unbounded. It never will.
  • Returning void from @Async methods, so exceptions disappear unless you register an AsyncUncaughtExceptionHandler.
  • Assuming ThreadLocal values such as security context, MDC or tenant ID carry over to async threads. Propagate them with a TaskDecorator.
  • Treating virtual threads as unlimited concurrency against a 20-connection database pool.

JVM memory, GC and containers

JVM memory is more than heap. Metaspace, thread stacks, the code cache, direct buffers (Netty, NIO) and GC structures all sit outside -Xmx. If you size the heap to the container limit, the kernel kills the process. You see OOMKilled with exit code 137, no Java stack trace and no heap dump. A java.lang.OutOfMemoryError is a different failure: the JVM itself ran out of a specific space, and the error message tells you which one.

Modern JVMs are container-aware. Prefer -XX:MaxRAMPercentage (often 60 to 75 percent) over a hard-coded -Xmx, so the heap follows the pod limit. G1 is the default collector and suits most services. ZGC, which is generational in recent JDKs, targets very low pause times on large heaps at some cost in CPU.

To diagnose problems, enable GC logging, write a heap dump on OOM to a persistent volume, and know your tools: jcmd <pid> GC.heap_info, jcmd <pid> Thread.print, jcmd <pid> GC.heap_dump, and Java Flight Recorder for low-overhead profiling. Heap usage that climbs after every full GC points to a leak. A sawtooth that returns to the same baseline is normal.

Shell

java \
  -XX:MaxRAMPercentage=70.0 \
  -XX:+HeapDumpOnOutOfMemoryError \
  -XX:HeapDumpPath=/dumps \
  -Xlog:gc*:file=/logs/gc.log:time,uptime:filecount=5,filesize=20m \
  -XX:+ExitOnOutOfMemoryError \
  -jar catalog-service.jar

# On a live pod
jcmd 1 GC.heap_info
jcmd 1 Thread.print > /dumps/threads.txt
jcmd 1 JFR.start duration=60s filename=/dumps/catalog.jfr

Container-friendly memory flags and the jcmd commands you would run during an incident.

Traps

  • Setting -Xmx equal to the container memory limit, which leaves no room for non-heap memory.
  • Confusing an OOMKilled pod with a Java OutOfMemoryError. They have different causes and different evidence.
  • Writing heap dumps to the container's ephemeral filesystem, where they are lost on restart.
  • Tuning GC flags before checking allocation rate and live set size in the GC logs.

Singleton beans, scopes and thread safety

Spring beans are singletons by default, and one instance serves every concurrent request. Any mutable instance field is shared state. A counter, a cached List, a reused SimpleDateFormat or a field that stores "the current user" will cause race conditions that only show up under load.

Write stateless beans: put dependencies in final fields through constructor injection, and keep request data in local variables or method parameters. When you need shared state, use thread-safe types (ConcurrentHashMap, AtomicLong, LongAdder) or immutable values, and keep the logic simple enough to reason about.

Scope mismatches are a related trap. If you inject a prototype or request-scoped bean into a singleton, the singleton receives one instance at startup and keeps it for good. Use ObjectProvider<T> to get a fresh instance on each call, or a scoped proxy for request and session scope.

Java

@Service
public class DeliveryWindowService {

    // Thread-safe and immutable, unlike SimpleDateFormat
    private static final DateTimeFormatter SLOT_FORMAT = DateTimeFormatter.ofPattern("EEE HH:mm");

    private final ConcurrentHashMap<String, LongAdder> bookingsPerZone = new ConcurrentHashMap<>();
    private final ObjectProvider<SlotAllocator> allocators; // prototype-scoped bean

    public DeliveryWindowService(ObjectProvider<SlotAllocator> allocators) {
        this.allocators = allocators;
    }

    public String book(String zone, ZonedDateTime requested) {
        SlotAllocator allocator = allocators.getObject(); // fresh instance per call
        ZonedDateTime slot = allocator.nearestFreeSlot(zone, requested);
        bookingsPerZone.computeIfAbsent(zone, z -> new LongAdder()).increment();
        return SLOT_FORMAT.format(slot);
    }
}

A grocery delivery service that keeps shared state thread-safe and gets a new prototype bean on every call.

Traps

  • Storing per-request data such as the user, tenant or order in a field of a singleton bean.
  • Sharing SimpleDateFormat, HashMap or ArrayList across threads without synchronisation.
  • Injecting a prototype bean into a singleton and expecting a new instance on each use.
  • Using check-then-act on a ConcurrentHashMap (containsKey followed by put) instead of computeIfAbsent or merge.

Health probes, metrics and graceful shutdown

Spring Boot Actuator exposes liveness and readiness groups at /actuator/health/liveness and /actuator/health/readiness. They mean different things. Liveness asks whether the process is broken beyond repair, so a failure should trigger a restart. Readiness asks whether the instance can take traffic right now. Put database or downstream checks only in readiness. If they sit in liveness, a database outage restarts every pod and turns a partial incident into a full one.

Micrometer metrics are only useful if tag cardinality stays bounded. Tag by outcome, endpoint template or region, never by user ID or raw URL. Every distinct tag combination creates a new time series in Prometheus. Add trace IDs to logs (Micrometer Tracing puts them in the MDC) so you can move from a slow metric to the exact request.

With server.shutdown=graceful, Boot stops accepting new requests on SIGTERM and lets in-flight requests finish within spring.lifecycle.timeout-per-shutdown-phase. Combine this with a readiness probe and a short pre-stop delay in Kubernetes, so the load balancer stops sending traffic before the app begins to drain.

Java

@Component
public class CheckoutMetrics {
    private final MeterRegistry registry;

    public CheckoutMetrics(MeterRegistry registry) {
        this.registry = registry;
    }

    public <T> T timeCheckout(String paymentMethod, Supplier<T> checkout) {
        Timer.Sample sample = Timer.start(registry);
        String outcome = "success";
        try {
            return checkout.get();
        } catch (RuntimeException e) {
            outcome = e.getClass().getSimpleName();
            throw e;
        } finally {
            sample.stop(Timer.builder("shop.checkout.duration")
                    .tag("method", paymentMethod)   // card, wallet, invoice: bounded
                    .tag("outcome", outcome)        // bounded set of exception types
                    .publishPercentileHistogram()
                    .register(registry));
        }
    }
}

A checkout timer whose tags have a small, fixed set of values. In application.yml, set server.shutdown: graceful alongside it.

Traps

  • Putting database or downstream checks in the liveness probe, which causes restart storms during dependency outages.
  • Tagging metrics with user IDs, order IDs or full URLs, which causes a cardinality explosion in the metrics backend.
  • Exposing every actuator endpoint publicly. heapdump and env can leak secrets.
  • Enabling graceful shutdown without a pre-stop delay, so the load balancer still routes requests to a pod that is draining.

Common questions

Short answers to the usual doubts.

How deep do I need to go on JVM internals for a mid-level Spring role?

You need the memory regions (heap, metaspace, thread stacks, direct memory), the difference between a container OOM kill and an OutOfMemoryError, and enough jcmd and GC log knowledge to collect evidence. GC algorithm internals matter more for senior and platform roles.

Should I recommend virtual threads in an interview answer?

Recommend them for blocking I/O-heavy services on Java 21 or later, and state the limits right away: they don't increase database capacity, pools and rate limits still apply, and on Java 21 pinning inside synchronized blocks can hurt throughput. That balanced answer is what interviewers look for.

Is it wrong to call a remote service inside a @Transactional method?

It is not always wrong, but it is risky. The database connection and any locks stay held for the whole remote call, and a rollback cannot undo what the remote side already did. Common alternatives are calling the service after commit, or writing an outbox row in the transaction and publishing it asynchronously.

What is the quickest way to spot N+1 queries before production?

Enable SQL logging or Hibernate statistics in tests and assert on query counts for key endpoints. Disabling open-in-view also makes missing fetches fail fast with LazyInitializationException instead of silently issuing extra queries.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide5 of 7 · Languages and runtimesPHP in Production: What Mid and Senior Engineers Must KnowRead the next one