Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Services in your platform call each other in chains of three to five hops. When a user cancels or a gateway times out, downstream work keeps running for seconds and wastes capacity. Design a cancellation standard across services.

We propagate a deadline, not just a timeout: the edge sets an absolute time by which the answer is useless, each hop passes the remaining budget in a header, and each service sets its own downstream timeouts from what is left. Inside a service, deadline expiry and client disconnect cancel the request's tasks through interruption or future cancellation, using constructs that cancel sibling work on failure, such as structured concurrency where your JDK supports it. All blocking calls must be interruptible or time-bounded, and the whole standard ships in shared client libraries so every team gets the same behaviour.

Why this question is asked

In a chain of three to five services, every hop that keeps working after the user has gone burns threads, connections and database time for an answer nobody will read. Under load this waste is what turns a slowdown into an outage, because retries arrive while the abandoned work is still running. Interviewers ask senior engineers to design the cancellation standard because it touches protocols, threading and team practices at once. In this answer, we will look at why per-hop timeouts are not enough, design deadline propagation, map it to cancellation inside a service, make the work itself stoppable, and decide how to roll it out through shared libraries.

1Why Per-Hop Timeouts Waste Capacity

Suppose the gateway gives the user 2 seconds. Service A calls B with a 2-second timeout, B calls C with 2 seconds, and C calls D with 2 seconds, because each team picked a sensible-looking number. A user request arrives at 0 ms. A spends 300 ms before calling B, B spends 400 ms before calling C, and C waits on D. At 2,000 ms the gateway times out and returns an error. But C's timeout on D started at 700 ms, so it only fires at 2,700 ms, and D keeps working until it is done. For up to a second or more, three services do work whose result will be thrown away.

The deeper problem is that a timeout is relative to when a hop started, so it knows nothing about how much time the original caller has left. And when the gateway gives up or the user cancels, nothing tells the downstream services; they only find out when they try to write to a closed connection, if at all.

2Propagate Deadlines, Not Timeouts

A deadline is an absolute point in time after which the result is useless. The gateway converts its 2-second limit into a deadline and passes the remaining budget to the next hop in a header, for example X-Request-Deadline-Ms: 1700. Each service subtracts its own elapsed time and a small margin before calling the next one, and sets its client timeout to the remaining budget. If the budget is already gone, it fails fast instead of calling at all.

Java
long remainingMs = deadline.remaining().toMillis() - 50; // keep a margin for our own reply
if (remainingMs <= 0) throw new DeadlineExceededException(); // do not start work that cannot finish
HttpRequest req = HttpRequest.newBuilder(uri)
.timeout(Duration.ofMillis(remainingMs)) // our timeout comes from the budget
.header("X-Request-Deadline-Ms", Long.toString(remainingMs))
.build();
Step throughA deadline flowing down the chain
GatewayService AService BService C
budget 2000 ms
budget 1650 ms (A used 300 + margin)
budget 1200 ms (B used 400 + margin)
user cancels at 900 ms
connection closed
cancel: close outbound call
cancel: close outbound call
interrupt request tasks, stop work

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

Every hop knows the remaining budget, and cancellation travels down the same path.

Sending a remaining duration rather than a wall-clock timestamp avoids depending on synchronised clocks between machines; each service turns it back into a local deadline on arrival. gRPC works this way natively with its deadline propagation, and the same header idea works over HTTP and in message metadata.

3Map Expiry and Disconnect to Cancellation Inside a Service

When the deadline expires or the client disconnects, the service must stop the work belonging to that request, not just stop waiting for it. In Java that means cancelling the request's tasks: calling Future.cancel(true), which interrupts the thread running the task, or interrupting the request's thread directly. Closing our outbound HTTP connection is how the cancellation travels to the next hop, which sees its client disconnect and repeats the process.

For requests that fan out to several downstream calls, we want sibling work cancelled automatically when one part fails or the deadline passes. Structured concurrency gives exactly that: StructuredTaskScope runs subtasks in a scope, and when the scope fails or is shut down, it cancels the remaining subtasks. It is still a preview API in Java 25 and its shape has changed between releases, so check its status in your JDK. Until it is final, the shared library can offer the same behaviour with CompletableFuture and explicit cancellation.

Java
// Without a preview API: cancel the siblings ourselves
CompletableFuture<Price> price = CompletableFuture.supplyAsync(() -> pricing.get(id), executor);
CompletableFuture<Stock> stock = CompletableFuture.supplyAsync(() -> inventory.get(id), executor);
try {
CompletableFuture.allOf(price, stock).get(deadline.remainingMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException | ExecutionException e) {
price.cancel(true); // CompletableFuture.cancel does not interrupt the running thread,
stock.cancel(true); // so the clients also close their calls when the deadline fires
throw e;
}

Notice the comment: CompletableFuture.cancel(true) completes the future but does not interrupt the thread doing the work. That is a common surprise, and it is one more reason the library should own this code. Executor-submitted FutureTasks do interrupt, and so do structured concurrency scopes.

4Make All Blocking Calls Interruptible or Time-Bounded

Cancellation only helps if the work can actually stop. Every outbound call gets a timeout derived from the deadline. JDBC queries get a query timeout, set with Statement.setQueryTimeout() or the framework's equivalent, so the database stops working too. Loops over large data check Thread.currentThread().isInterrupted() at safe points, and code that catches InterruptedException restores it. Lock waits that can be long use tryLock with a timeout. Without these, cancellation stops at the first call that ignores it.

Work that changes state needs one more thought. If a cancellation can arrive half-way through, each step should be idempotent or transactional, so cancelling and retrying never leaves the system inconsistent.

5Ship It in Shared Client Libraries

If each team implements deadlines and cancellation by hand, we get five dialects and gaps at every boundary. So the standard is a library, provided with the platform's starter. It reads the deadline header on incoming requests and stores it in the request context, offers a Deadline object to application code, configures the HTTP and gRPC clients to set their timeouts and outgoing headers from it, sets JDBC query timeouts, hooks client disconnects to cancellation of the request's tasks, and exposes metrics such as requests failed fast because the budget was gone and work cancelled after disconnect.

The rollout can be gradual: services that do not understand the header still work with their own timeouts, and each service that adopts the library immediately stops wasting work for its callers. We measure success by the amount of downstream work done after the gateway's response, which should drop close to zero.

Step throughWhere cancellation is handled
  1. Gatewaysets the deadline, closes upstream on cancel
  2. Incoming filter (shared library)reads budget header, stores Deadline in context
  3. Request taskscancelled on expiry or disconnect
  4. Outbound clients (shared library)timeout and header from remaining budget
  5. Database and I/Oquery and read timeouts as the final bound

5 layers, from the top down. Step through them one at a time.

6Follow-up questions

Why send the remaining budget instead of an absolute timestamp?

Because clocks on different machines drift. A remaining duration is relative, so each service converts it to its own local deadline on arrival. The small error from network time only makes the budget slightly conservative, which is safe.

What about asynchronous work triggered by the request, such as publishing an event?

Deadlines apply to work whose result the caller is waiting for. Work that must happen regardless, like an audit event or an order placement once committed, should be handed to a durable queue and processed independently, with its own timeouts, so a cancelled request does not cancel a committed business action.

How do retries interact with deadlines?

A retry may only happen if the remaining budget allows it, and the library should check that before retrying. This stops retry storms in which every hop multiplies attempts long after the user has gone.

7Conclusion

In this answer, we saw that per-hop timeouts let downstream services keep working long after the caller has given up. We designed a standard that propagates a deadline as a remaining budget, maps expiry and client disconnect to cancellation of the request's tasks, uses constructs that cancel sibling work, makes every blocking call interruptible or time-bounded, and is delivered as a shared library so every team implements it the same way.

What to say in the interviewAbout 90 seconds aloud

Open with

The core problem is that each hop sets its own timeout relative to when it started, so it doesn't know the user has already given up, and nobody tells downstream services when the gateway times out.

Then, if they want more

My standard has four parts. First, propagate deadlines instead of timeouts: the gateway turns its limit into a deadline, and each hop passes the remaining budget in a header, minus a small margin, and sets its own client timeouts from what's left. If the budget is gone, the service fails fast instead of starting work.

I'd send a remaining duration rather than a timestamp so clock drift doesn't matter. Second, inside a service, deadline expiry or a client disconnect must cancel the request's tasks, for example by cancelling the futures, which interrupts the worker threads, and by closing outbound connections, so the next hop sees a disconnect and does the same.

For fan-out, structured concurrency cancels siblings automatically, but it's still preview in Java 25, so until then the library does explicit cancellation; note that CompletableFuture.cancel doesn't interrupt the running thread. Third, every blocking call must be interruptible or time-bounded, including JDBC query timeouts, and state-changing steps must be idempotent.

Fourth, all of this goes into the shared client and server libraries, with metrics on work done after the caller left, so teams get it by default.

About this answer

Last updated
12 November 2026
Versions it names
Java 25
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 "Services in your platform call each other in chains of three to five hops. When a user...": https://scrivio-interview-library.netlify.app/java/threads/71982e4034/