Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A request passes through a gateway, service A and service B, then the database. The user-facing timeout is 2 seconds. How would you set timeouts at each hop, and what is deadline propagation?

Each hop's timeout must be shorter than its caller's, otherwise the caller gives up while the work continues below it, so we budget from the outside in: for example gateway 2 s, service A 1.5 s, service B 1 s and the database query 500 ms. Deadline propagation goes further: the caller passes the remaining time in a header, and each service uses what is left instead of a fixed value. Retries must fit inside the budget, or inner hops should not retry at all, and downstream work should be cancelled when the caller's deadline passes, where the stack supports it.

Why this question is asked

In a chain of services, timeouts that make sense on their own can make no sense together. If the gateway gives up after 2 seconds but service B is allowed 5 seconds for its database call, the user has already seen an error while B is still working, using a connection and maybe writing data nobody will read. Interviewers ask this design question to see whether we can think about the whole request path. In this answer, we will see what goes wrong with independent timeouts, build a budget from the outside in, make retries fit in it, explain deadline propagation with code, and finish with cancellation.

1What Goes Wrong With Independent Timeouts

Picture the chain with each team's own choice: gateway 2 seconds, A calls B with a 3 second read timeout, B's database query has a 5 second timeout. The database is slow today and takes 4 seconds. At 2 seconds the gateway returns 504 to the user. A keeps waiting for B until 3 seconds, then fails. B keeps waiting for the database until 4 seconds and succeeds, then sends a response to A, which has already given up.

So for 2 seconds after the user saw the error, three services kept doing work that could never be used. Under load, this wasted work is what makes a slow system slower, and a user retry doubles it.

Step throughIndependent timeouts: work continues after the user gave up
Gateway (2 s)Service A (3 s to B)Service B (5 s to DB)Database
request at t=0
call B
query (takes 4 s)
t=2 s: timeout, 504 to the user
t=3 s: timeout waiting for B
t=4 s: result
t=4 s: response nobody reads

7 messages in order. Play them, or step through them one at a time.

2Budgeting From the Outside In

The fix starts at the edge. The user-facing timeout is 2 seconds, so that is the whole budget. Each inner hop gets a timeout shorter than its caller's, leaving room for the caller's own work and for the network. A simple, workable budget is gateway 2 s, A's call to B 1.5 s, B's call to the database 1 s, and the query itself limited to 500 ms by a statement timeout.

Java
# Gateway: route timeout 2 s
spring.cloud.gateway.server.webflux.httpclient.response-timeout=2s # prefix varies by version
# Service A: read timeout for calls to B
clients.b.read-timeout=1500ms
# Service B: database call limits
spring.datasource.hikari.connection-timeout=250ms # wait for a pooled connection
spring.jpa.properties.jakarta.persistence.query.timeout=500 # milliseconds, per query
# or in PostgreSQL for B's role: ALTER ROLE b_app SET statement_timeout = '500ms';
// The database is slow (4 s):
// t=0.5 s B: query cancelled by statement timeout -> B returns 503 to A
// t=0.5 s A: gets the error quickly, returns a fallback or an error to the gateway
// t=0.5 s user sees a clear error well inside the 2 s budget, nobody works for nothing
A timeout budget for the chain
HopTimeoutLeft for this layer's own work
Gateway -> A2.0 s (user-facing)about 0.5 s around A's call
A -> B1.5 sabout 0.5 s around B's call
B -> database1.0 s connection and querypool wait 250 ms
Query itself500 ms statement timeout-
Each hop is shorter than its caller, so failures surface in time to be handled.

Notice that the inner timeouts are not just shorter; they also leave each layer time to react. When B's query is cut at 500 ms, B still has time to return an error, and A still has time to return a fallback, such as cached data, before the gateway's 2 seconds run out. The exact numbers come from measured latency: the database timeout should sit above the query's normal p99, and each outer layer adds its own processing time and a margin.

3Fitting Retries Inside the Budget

Retries consume budget. If A retries its call to B once after a 1.5 second timeout, the second attempt starts at 1.5 s and cannot finish before the gateway gives up at 2 s, so the retry only adds load. There are two reasonable options. Either we retry only where the budget allows a full attempt, which means shorter per-attempt timeouts, for example two attempts of 600 ms each from A to B, or we do not retry at inner hops at all and let only one layer, often the outermost client, retry.

Retries at several layers also multiply, so choosing a single retry layer, and making retries check the remaining time before starting, keeps the system calm when it is under stress.

4Deadline Propagation

Fixed timeouts per hop are a good start, but they waste information. If A spent 1.2 seconds on other work before calling B, B's fixed 1.5 second budget is now longer than the 0.8 seconds the user actually has left. Deadline propagation fixes this: each request carries the remaining time, and each service uses the smaller of its own limit and what is left. gRPC does this natively with its deadline and the grpc-timeout header. Over HTTP, we can do it with a header of our own and a little code.

Java
// Service A: a filter reads the incoming budget; a client interceptor passes on what is left
static final String HEADER = "X-Request-Timeout-Ms"; // remaining time, relative, avoids clock skew
class DeadlineFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
long budget = Optional.ofNullable(req.getHeader(HEADER)).map(Long::parseLong).orElse(2000L);
Deadline.set(System.nanoTime() + Duration.ofMillis(budget).toNanos());
try { chain.doFilter(req, res); } finally { Deadline.clear(); }
}
}
ClientHttpRequestInterceptor propagate = (request, body, execution) -> {
long left = Deadline.remainingMillis() - 50; // keep 50 ms to handle the reply
if (left <= 0) throw new DeadlineExceededException(); // do not even start the call
request.getHeaders().set(HEADER, Long.toString(left));
return execution.execute(request, body);
};
// Gateway sends 2000 -> A works 1200 ms -> A calls B with 750 -> B limits its query to < 750 ms

Deadline here is a small class of our own that keeps the deadline for the current request, in a ThreadLocal or a scoped value. Notice that we pass the remaining time as a relative number of milliseconds rather than an absolute clock time, because the clocks of different machines may differ by tens of milliseconds. Each service applies the remaining time as the timeout for its own outgoing calls and, where possible, for its queries.

5Cancelling Work When the Deadline Passes

The last part is to stop work that can no longer help. Some stacks support this well. In reactive code, when the caller's subscription is cancelled, for example by a timeout operator, the cancellation travels down the chain and the outgoing HTTP request is aborted. JDBC queries can be cancelled through the statement timeout, which on PostgreSQL sends a cancel request to the server, so the database stops working too.

Blocking servlet code is weaker: when the gateway gives up, service A's thread usually does not notice until it next tries to write the response. That is why the explicit checks matter, refusing to start an outgoing call when the deadline has passed, and setting timeouts from the remaining budget.

Step throughHandling one request with a propagated deadline
  1. Read the remaining time from the headeror use the edge default of 2 s
  2. Do local work
  3. Time left above the minimum for the next call?
    YesCall downstream with the remaining timeNoFail fast or return a fallback
  4. Set query timeout from what is leftnever above the fixed maximum
  5. Deadline passed while waiting?
    YesCancel and release resourcesNoReturn the result

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

6Follow-up questions

What if a downstream service ignores the deadline header?

Then it falls back to its own fixed timeouts, which is why the outside-in budget is still needed. Deadline propagation is an improvement on top of correct fixed limits, not a replacement. A shared starter that reads and passes the header makes adoption across services consistent.

Should a write operation also be cut by the deadline?

Carefully. Cancelling a write half-way can leave the outcome unknown to the caller, even if the database rolled back cleanly. For writes, we prefer idempotent operations with request ids, so the client can safely ask again or check the result, and we avoid starting a write when too little time is left.

7Conclusion

In this answer, we saw that independent timeouts let inner services keep working after the user has given up, so we budgeted from the outside in, with each hop shorter than its caller: gateway 2 s, A 1.5 s, B 1 s and a 500 ms query. We fitted retries inside the budget or removed them from inner hops, propagated the remaining time in a header so each service uses what is left, and cancelled downstream work when the deadline passed where the stack supports it.

What to say in the interviewAbout 90 seconds aloud

Open with

The basic rule is that each hop's timeout must be shorter than its caller's. If the gateway gives up at 2 seconds but B waits 5 seconds for the database, the user already has an error while B, A and the database keep doing work nobody will use, which makes a slow system slower.

Then, if they want more

So I would budget from the outside in: gateway 2 seconds, A's call to B 1.5 seconds, B's database call 1 second including the pool wait, and the query itself 500 milliseconds with a statement timeout. That leaves each layer time to react, return a fallback or a clear error, inside the user's budget.

Retries have to fit in that budget: either shorter per-attempt timeouts so two attempts fit, or no retries at inner hops and a single layer that retries, otherwise retries both waste time and multiply load.

Fixed values still waste information, so deadline propagation is the next step: the caller sends the remaining time in a header, as relative milliseconds to avoid clock skew, and each service uses the smaller of its own limit and what is left, refusing to start a call when too little time remains. gRPC does this natively with deadlines.

Finally, cancel downstream work when the deadline passes, which reactive stacks, JDBC statement timeouts and gRPC support; for blocking code, the explicit checks before each call do most of that job.

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 request passes through a gateway, service A and service B, then the database. The...": https://scrivio-interview-library.netlify.app/spring-boot/resilience/7f30db387e/