Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A hot code path uses lock.tryLock(200, MILLISECONDS) and on failure throws an exception that becomes an HTTP 500. During traffic spikes many requests fail this way. How would you treat the timeout and the underlying problem?

A tryLock timeout during a spike is not a random failure: it tells us the lock has become a bottleneck, and the 200 ms timeout simply turns waiting into errors. We should report it honestly as overload (503 with a Retry-After header, not a 500), count it as a metric with an alert, and then fix the real cause by doing less work under the lock or splitting the lock by key, while keeping the timeout inside the request's overall deadline.

Why this question is asked

This scenario is common in services that protect some shared state, such as an in-memory cache rebuild, a per-account balance or a file, with one ReentrantLock. Everything looks fine at normal traffic, then a spike arrives and the error rate jumps. Interviewers ask it because a weak answer tunes the timeout up or down, while a strong answer treats the timeout as a symptom and looks for the queue behind it. In this answer, we will recap what tryLock with a timeout does, work out why spikes produce failures with a little arithmetic, change the error into a proper overload response, add the metric that makes the problem visible, reduce the contention itself, and finally fit the timeout into the request's deadline.

1A Quick Recap of tryLock With a Timeout

A ReentrantLock is an explicit lock from java.util.concurrent.locks. Only one thread can hold it at a time; others wait until it is released. The plain lock() call waits forever, while tryLock(200, MILLISECONDS) waits at most 200 ms and then returns false, so the caller can do something else instead of hanging.

In our service the something else is throwing an exception. Because nothing maps that exception to a status code, Spring's default error handling turns it into an HTTP 500, which means 'the server has a bug'. That label is the first thing that is wrong, but not the most important one.

Java
if (!lock.tryLock(200, TimeUnit.MILLISECONDS)) { // waits up to 200 ms
throw new IllegalStateException("lock busy"); // becomes HTTP 500
}
try {
updateSharedState(request); // the critical section
} finally {
lock.unlock();
}

Notice that tryLock with a timeout can also throw InterruptedException, so the method must either declare it or restore the interrupt flag with Thread.currentThread().interrupt() before turning it into an error.

2What the Timeouts Are Really Telling Us

A lock lets through one thread at a time, so it has a fixed capacity. If the critical section takes 5 ms on average, the lock can serve at most 1000 / 5 = 200 requests per second, no matter how many threads or instances of the code wait for it. At 150 requests per second the waiting line stays short. During a spike of 300 requests per second, 100 more requests arrive every second than the lock can serve, so the line of waiting threads grows steadily.

Once the line is long enough that a new arrival would wait more than 200 ms, about 40 requests ahead of it at 5 ms each, its tryLock gives up. So the timeout does not cause the problem; it converts the extra demand into errors. Raising the timeout to 2 seconds would not create capacity. It would only make the line longer, hold more threads, and make every request slower before failing in the same way.

Step throughWhy a spike turns into tryLock failures
  1. Arrivals exceed lock capacity300 per second against 200 per second
  2. Waiting threads pile up100 more each second
  3. Wait for a new request passes 200 ms?
    YestryLock returns falseNoRequest gets the lock
  4. Exception throwntoday: HTTP 500
  5. Client retries immediatelyadds even more load

5 steps in order. Play them, or step through them one at a time.

The timeout only decides where the extra demand ends up; the capacity of the lock is the real limit.

3Returning 503 Instead of 500

A 500 tells the client and the on-call engineer that something is broken. Here nothing is broken; the server is busy. HTTP has a status for exactly that: 503 Service Unavailable, ideally with a Retry-After header so well-behaved clients wait before trying again rather than retrying at once and making the spike worse. In Spring we give the failure its own exception type and map it once.

Java
class LockBusyException extends RuntimeException {
LockBusyException(String what) { super(what + " is busy"); }
}
@RestControllerAdvice
class OverloadAdvice {
@ExceptionHandler(LockBusyException.class)
ResponseEntity<ProblemDetail> busy(LockBusyException e) {
ProblemDetail body = ProblemDetail.forStatusAndDetail(
HttpStatus.SERVICE_UNAVAILABLE, "Temporarily overloaded, retry shortly");
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.header(HttpHeaders.RETRY_AFTER, "1") // seconds
.body(body); // 503 + Retry-After: 1
}
}

Now load balancers, gateways and clients can treat the response as back pressure. A retry policy with jitter on the client side, and not counting 503s as bugs in error budgets that track defects, both follow from using the right status.

4Counting Timeouts and Alerting on Them

We cannot fix what we cannot see. Two measurements make this lock visible: a counter of tryLock failures and a timer of how long successful acquisitions waited. With Micrometer, which Spring Boot already configures, that is a few lines.

Java
Timer waitTimer = Timer.builder("lock.wait").tag("lock", "inventory").register(registry);
Counter timeouts = Counter.builder("lock.timeouts").tag("lock", "inventory").register(registry);
long start = System.nanoTime();
boolean got = lock.tryLock(200, TimeUnit.MILLISECONDS);
waitTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
if (!got) {
timeouts.increment(); // lock.timeouts goes up by 1
throw new LockBusyException("inventory");
}

An alert on the rate of lock.timeouts, for example more than 1 percent of requests over five minutes, warns us before customers notice. The wait timer's p99 is even more useful: it starts rising long before any timeout fires, so it shows the lock approaching its capacity during ordinary traffic growth.

5Fixing the Contention Itself

The lasting fix is to raise the lock's capacity. The first lever is the length of the critical section. Very often the code inside the lock does work that does not need it: a remote call, a database query, JSON parsing or logging. Moving that work before or after the locked region can turn 5 ms into 0.2 ms, which raises capacity from 200 to 5000 requests per second with no other change.

The second lever is partitioning. If the lock protects state for many independent keys, such as accounts or products, one global lock makes unrelated requests wait for each other. A lock per key, or a fixed set of striped locks chosen by the key's hash, lets requests for different keys run in parallel.

Java
private final ReentrantLock[] stripes = new ReentrantLock[64];
{ for (int i = 0; i < stripes.length; i++) stripes[i] = new ReentrantLock(); }
ReentrantLock lockFor(String accountId) {
return stripes[Math.floorMod(accountId.hashCode(), stripes.length)]; // same key -> same lock
}

With 64 stripes and well-spread keys, contention drops by roughly that factor. Sometimes the best change is to remove the lock entirely, for example with a ConcurrentHashMap.compute call per key or an atomic update, but that depends on what the critical section does.

6Fitting the Timeout Into the Request's Deadline

The 200 ms should not be a number someone picked once. Every request has an overall budget: if the gateway times out after 1 second and the database call after the lock takes up to 300 ms, the lock wait plus the work must leave room for that. A timeout larger than the remaining budget is pointless, because the client has already given up when the lock is finally acquired, and the work is wasted.

So we derive the wait from the deadline: compute the time left for this request, subtract the expected work, and wait at most that, with an upper bound. A short wait that fails fast under overload is usually kinder than a long wait, because it frees the thread and gives the client a clear signal while it can still retry elsewhere.

7Follow-up questions

Should we just remove the timeout and use lock()?

No. Without a timeout, threads wait without limit during a spike, the request thread pool fills up, and the service stops answering even health checks. The timeout is a useful safety valve; it only needs the right response, a metric and a size that fits the deadline.

Would a fair lock help?

A fair ReentrantLock hands the lock to the longest-waiting thread, which makes waits more predictable, but it lowers throughput because it gives up barging. It does not add capacity, so it would not stop timeouts during a spike, and it can make them a little more frequent.

How would you test the fix?

With a load test that reproduces the spike rate and records the lock wait timer, the timeout counter and the response codes. Before the fix we should see 500s; after it, fewer timeouts, and the ones left should appear as 503s with Retry-After.

8Conclusion

In this answer, we saw that tryLock timeouts during traffic spikes mean the lock has reached its capacity, which we can estimate from the time spent inside it. We changed the failure from a 500 into a 503 with Retry-After, added a counter and a wait timer with an alert, raised capacity by shrinking the critical section and striping the lock by key, and sized the wait from the request's deadline instead of a fixed guess.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd start by treating the timeout as a symptom. A lock serves one request at a time, so if the critical section takes 5 milliseconds, that lock tops out at about 200 requests per second.

Then, if they want more

During a spike, arrivals exceed that, a queue builds, and once the wait passes 200 milliseconds tryLock fails. The timeout isn't the bug; it's converting overload into errors. So first, I'd stop calling it a 500.

I'd throw a specific exception and map it to a 503 with a Retry-After header, so clients and gateways back off instead of retrying immediately, and so our error budget doesn't count load as a defect. Second, I'd measure it: a counter for timeouts and a timer for how long acquisitions wait, with an alert on the timeout rate.

The wait p99 usually rises well before timeouts start. Third, the real fix is capacity. I'd look at what runs inside the lock and move out anything that doesn't need it, especially remote calls, queries and logging.

If the lock protects independent keys, I'd partition it, a lock per key or a set of striped locks, so unrelated requests don't wait for each other. Finally, I'd make sure the 200 milliseconds fits the request's deadline: wait no longer than the time left minus the work, because a lock acquired after the client gave up is wasted work.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A hot code path uses lock.tryLock(200, MILLISECONDS) and on failure throws an exception...": https://scrivio-interview-library.netlify.app/java/locks/24f06411d2/