Java backend developer interview questions and answers

Java backend developer interview questions test whether you can run Java services in production, not only write Java: how requests map to threads, how transactions and connection pools behave under load, how to make calls safe with timeouts, retries and idempotency, and how the JVM behaves inside a container. Expect a coding round, a design discussion for an API or a queue consumer, and debugging scenarios such as a pool that runs dry or latency that spikes after a deploy. Answers that name the failure mode and the metric that proves it score best.

By Published 8 min read

Backend Java teams build the APIs, jobs and consumers behind products: payments, orders, search, notifications. Interviews assume you know the language, collections and a framework, which Java developer interview questions, Spring Boot interview questions and Hibernate interview questions cover. The backend-specific rounds ask what happens when the code meets traffic, a database, a network and a deploy pipeline.

Interviewers listen for production instincts: a timeout on every remote call, a transaction kept short, a consumer that tolerates duplicates, a health check that means something, logs and metrics you can actually use at 3 a.m. For language-neutral backend topics such as caching and API design, backend developer interview questions is a good companion, and microservices interview questions covers service boundaries.

How Java backend interviews usually run

  1. ScreenThe services you have built, traffic and data sizes in rough terms, and the stack: framework, database, messaging and cloud.
  2. Coding roundOften a data structure problem in Java, or a small service task such as a rate limiter, an LRU cache or a REST endpoint with validation.
  3. Backend designDesign an API, a job or a consumer, with storage, consistency, failure handling and how you would observe it.
  4. Production and behavioralIncidents you handled, how you debug a slow endpoint, code review habits and working with other teams.

Threads, pools and concurrency in services

How requests become threads
QuestionWhat it testsWhat a strong answer shows
How does a servlet container handle a request?Thread modelA pool of worker threads takes connections; each request runs on one thread until it returns. Blocking calls hold that thread, so slow dependencies exhaust the pool.
What happens when the request thread pool is full?SaturationNew requests queue and then are rejected or time out. Latency climbs for everyone, not only for the slow path. Limits and timeouts on downstream calls protect the pool.
What are virtual threads, and when do they help?Modern JavaLightweight threads managed by the JVM, final since Java 21. They let blocking-style code scale to many concurrent I/O waits. They do not speed up CPU-bound work, and code that pins the carrier thread or relies on small pools for back-pressure needs care.
Why is a shared mutable field in a singleton bean dangerous?Thread safetyOne bean instance serves all requests on many threads. Mutable state needs synchronization or, better, should not exist; keep request data in local variables.
ExecutorService: fixed pool, cached pool or something else?ExecutorsFixed pools bound concurrency; cached pools can grow without limit under load. Size pools for the work type and always use a bounded queue with a rejection policy.
How do you run several remote calls in parallel and combine them?Async compositionCompletableFuture with an explicit executor and a timeout on each call, or structured concurrency patterns. Decide what happens if one call fails.
What is ThreadLocal used for, and what goes wrong?ContextPer-thread context such as a request ID. In pools it leaks between requests if not cleared, and it holds memory; clear it in a finally block.
How requests become threads. Scroll sideways on a small screen.

Data access, transactions and pools

void transfer(DataSource ds, long from, long to, long cents) throws SQLException {
    try (Connection c = ds.getConnection()) {
        c.setAutoCommit(false);
        try (PreparedStatement debit = c.prepareStatement(
                 "UPDATE account SET balance = balance - ? WHERE id = ? AND balance >= ?");
             PreparedStatement credit = c.prepareStatement(
                 "UPDATE account SET balance = balance + ? WHERE id = ?")) {
            debit.setLong(1, cents); debit.setLong(2, from); debit.setLong(3, cents);
            if (debit.executeUpdate() != 1) throw new SQLException("insufficient funds");
            credit.setLong(1, cents); credit.setLong(2, to);
            credit.executeUpdate();
            c.commit();
        } catch (SQLException e) {
            c.rollback();
            throw e;
        }
    }
}
A transfer in one JDBC transaction with try-with-resources. The conditional update stops an overdraft without a separate read. Not executed here; standard java.sql only.
  • Why check the update count instead of reading the balance first? A read then write leaves a gap where another transaction can change the balance. The conditional update is atomic for that row.
  • What does a connection pool do, and how do you size it? It reuses open connections because opening one is slow. Size it to what the database can serve well, not to the request thread count; more connections can make the database slower.
  • A request holds a connection while calling a slow external API. Why is that bad? The connection sits idle inside an open transaction, the pool drains and locks are held longer. Do remote calls outside the transaction.
  • What is the N+1 query problem? Loading a list and then one query per item for a relation. Spot it in SQL logs, and fix it with a join fetch, batch fetching or a query shaped for the screen.
  • Which isolation level does your database default to, and what anomalies remain? Many default to read committed, which allows non-repeatable reads. Name the anomaly your feature cannot tolerate and the level or lock that prevents it.
  • Optimistic or pessimistic locking? Optimistic uses a version column and retries on conflict, good when conflicts are rare. Pessimistic locks rows up front, good when conflicts are common and retries are expensive.
  • How do you change a large table without downtime? Additive changes first, backfill in batches, deploy code that handles both shapes, then remove the old column later. Migrations are versioned with a tool such as Flyway or Liquibase.

Resilience: timeouts, retries and idempotency

Calls between services
QuestionWhat it testsWhat a strong answer shows
Why must every HTTP client call have a timeout?DefaultsSome clients wait a very long time or forever by default. Without connect and read timeouts, a slow dependency ties up your threads and spreads the outage.
When is it safe to retry?Retry policyWhen the operation is idempotent or carries an idempotency key, the error is transient, and retries use backoff with jitter and a cap. Retrying everything multiplies load during an outage.
How do you make a POST idempotent?IdempotencyThe client sends a unique key; the server stores the key with the result and returns the stored result on a repeat, inside the same transaction as the effect.
What is a circuit breaker?IsolationAfter repeated failures it stops calling a dependency for a while and fails fast, then tests with a few calls before closing again. Pair it with a fallback where one makes sense.
How do you limit load from one client?Rate limitingA token bucket per key at the gateway or in the service, with clear 429 responses and retry hints.
How should errors look to API clients?API contractConsistent status codes and a structured error body, no stack traces, and a request ID the client can quote.
Calls between services. Scroll sideways on a small screen.

Messaging and background jobs

  • Your Kafka or queue consumer receives the same message twice. Why, and what do you do? At-least-once delivery redelivers after a crash before the offset or acknowledgment is saved. Make processing idempotent, for example with a processed-ID table updated in the same transaction.
  • How do you publish an event only if the database write succeeds? The outbox pattern: write the event to an outbox table in the same transaction, and a relay publishes it afterwards.
  • What do you do with a message that always fails? Retry a limited number of times, then move it to a dead-letter queue with the error, and alert. Do not block the partition forever.
  • How do you keep ordering where it matters? Partition by the entity key so its events go to one partition and one consumer at a time.
  • How do you run a scheduled job on several instances without running it twice? A lock in the database or a scheduler designed for clusters, and a job that is safe to repeat anyway.

JVM in production and observability

  • How does the JVM size its heap in a container? Modern JVMs read the container's memory limit. Set the heap as a percentage of it and leave room for metaspace, thread stacks and direct buffers, or the container is killed despite a healthy heap.
  • Latency spikes every few minutes. How do you investigate? GC logs for long pauses, allocation rate, heap after collection over time, and thread dumps during a spike. Check whether a scheduled job lines up.
  • The service runs out of memory after a day. What next? Capture a heap dump on out-of-memory, look at the largest retainers, and suspect caches without limits, listeners never removed and ThreadLocals in pools.
  • How do you shut down gracefully? Stop accepting new requests, let in-flight work finish within a timeout, stop consumers after committing offsets, then close pools. Readiness should fail before shutdown begins.
  • What is the difference between liveness and readiness checks? Liveness says the process should be restarted; readiness says it can take traffic. Putting database checks in liveness causes restart storms when the database is slow.
  • What do you log and measure for each endpoint? Structured logs with a request or trace ID, the rate, errors and latency percentiles, and pool usage for threads and connections. Tracing across services shows where time goes.

Behavioral questions for backend engineers

  • Tell me about a production incident you helped resolve. Detection, the first safe action, the root cause and the follow-up that stopped it recurring.
  • Describe a design decision you would change now. Show you learn from systems in use, not only from reviews.
  • How do you review a teammate's pull request on a data access change? Transactions, indexes and query plans, migrations and backwards compatibility, plus tests.
  • How do you work with frontend or mobile teams on an API? Agree a contract early, version carefully, and never break existing clients silently.

Fictional example

Answering "Our order API slows down every evening. What do you check?"
Interviewer
Every evening at peak, p99 latency on the order API goes from 200 ms to several seconds. Where do you start?
Candidate
I'd first look at where the time goes using tracing on a slow request. Suppose most of it is waiting to get a database connection. Then I'd check the pool metrics: active connections at the maximum and a queue of waiters. Next question is why connections are held so long. In this kind of case it's often a call to an external service inside the transaction, so the connection sits idle while we wait. I'd move that call outside the transaction, add a timeout to it, and check the slow query log for anything that got worse at peak volume. I wouldn't just raise the pool size, because that can push the database harder. After the fix I'd compare p99 and pool wait time for the next few peaks.

A ten-day preparation plan

  • Days 1 to 3: refresh core Java, collections and concurrency with the linked Java guide, and solve a few timed problems in Java.
  • Days 4 and 5: build a small service with one endpoint backed by a database, with a transaction, a timeout on an outbound call and an idempotency key.
  • Day 6: add a consumer for a queue in a local setup you already have, or reason it through on paper: duplicates, poison messages, ordering.
  • Day 7: read your own service's metrics or a sample dashboard and explain pool saturation and GC pauses aloud.
  • Days 8 to 10: practice one backend design out loud, prepare two incident stories, and run a mock interview.

If you are interviewing alongside mobile engineers who call your API, iPhone app developer interview questions shows what they are asked about releases and offline behavior.

Design and debugging rounds are judged on the path you take, which is easy to lose under pressure. Natively, an AI interview assistant for Mac and Windows, transcribes a mock backend round on your computer so you can check whether you measured before changing anything. During practice it can read a coding problem or a stack trace from a screenshot and offer coding help, and with Pro or the free trial it can work from the résumé and job description you add. The transcript and notes are saved for later review.

Questions people ask

What questions are asked in a Java backend developer interview?

Core Java and Spring are assumed; expect request threads and pools, virtual threads, transactions and connection pools, timeouts, retries and idempotency, message consumers, JVM memory in containers and production debugging.

Are virtual threads asked in Java interviews?

Increasingly. Know that they became final in Java 21, help blocking I/O code scale, do not speed up CPU-bound work, and still need limits on downstream resources.

How do I answer a slow endpoint question?

Find where time goes with tracing, check thread and connection pool saturation, look for remote calls inside transactions and slow queries, change one thing and compare latency percentiles.

How is a Java backend interview different from a Java developer interview?

A general Java interview leans on the language, collections and frameworks. A backend interview adds how services behave under load, with databases, queues and deploys.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP