Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Write a Micronaut declarative HTTP client for GET /customers/{id} on another service, and explain how you would add timeouts and retries.

A declarative client is an interface annotated with @Client(id = "customers") whose method carries @Get("/customers/{id}"); Micronaut generates the implementation at compile time and takes the base URL from micronaut.http.services.customers.url or from service discovery. Read and connect timeouts go in the same micronaut.http.services.customers configuration block, @Retryable(attempts = "3", delay = "200ms") adds retries for idempotent calls and @CircuitBreaker protects against a failing dependency. For non-blocking use the method returns a reactive type or CompletableFuture, because blocking calls must never run on the event loop.

Why this question is asked

Calling another service is something every microservice does, and the code around it, building URLs, decoding JSON, handling timeouts and retries, is repetitive and easy to get subtly wrong. Micronaut's declarative clients reduce it to an interface. Interviewers ask for this code to see whether we know where configuration lives and how resilience is added without hand-written loops. In this answer, we will write the client, configure its URL and timeouts, add retries and a circuit breaker, and choose between blocking and non-blocking return types.

1A Quick Recap of Declarative Clients

A declarative client means we describe the remote API as a Java interface, and the framework writes the class that performs the HTTP calls. Spring users know the idea from OpenFeign or Spring's HTTP interface clients. In Micronaut, the implementation is generated at compile time by the same annotation processors that handle dependency injection, so there is no runtime proxy and no reflection, and the client is a normal bean we can inject anywhere.

2Writing the Client Interface

The interface below describes one endpoint of the customers service.

Java
@Serdeable // lets Micronaut Serialization read and write it
public record Customer(Long id, String name, String email) {}
@Client(id = "customers")
public interface CustomerClient {
@Get("/customers/{id}")
Customer get(Long id); // {id} is filled from the parameter with the same name
}
// Usage: inject and call like any bean
@Singleton
public class InvoiceService {
private final CustomerClient customers;
InvoiceService(CustomerClient customers) { this.customers = customers; }
public Invoice create(Order o) {
Customer c = customers.get(o.customerId()); // GET http://customers:8080/customers/42
return Invoice.of(o, c); // Customer[id=42, name=Alice, email=...]
}
}

Notice that the URI template variable {id} matches the method parameter name, so no extra annotation is needed. The id in @Client(id = "customers") is not a URL; it is the name of a service, which Micronaut looks up in configuration or in a service discovery system such as Consul or Kubernetes. That indirection is what lets the same code point to different hosts in each environment.

3Configuring the URL and the Timeouts

Everything about where and how to connect lives in configuration under the service id.

YAML
# application.yml
micronaut:
http:
services:
customers:
url: http://customers:8080 # or several urls for client-side load balancing
connect-timeout: 500ms
read-timeout: 2s # give up if no response within 2 s
pool:
enabled: true
max-connections: 50
# A call to a customers service that hangs:
# after 2 s -> ReadTimeoutException, instead of waiting forever

The connect timeout limits how long we wait to open a TCP connection, which fails fast when the host is down. The read timeout limits how long we wait for the response, which protects us when the host is up but slow. Both should fit inside the time budget of our own endpoint: if our callers wait at most 3 seconds, a 2 second read timeout with retries on top already needs care. Exact property names can differ slightly between Micronaut versions, so check your version's configuration reference.

4Adding Retries and a Circuit Breaker

Micronaut's retry support adds both features with annotations, which work on declarative client methods because the client is a bean with compile-time AOP. In Micronaut 4 these annotations live in the micronaut-retry module, so we add that dependency.

Java
@Client(id = "customers")
@CircuitBreaker(reset = "30s") // after repeated failures, fail fast for 30 s
public interface CustomerClient {
@Get("/customers/{id}")
@Retryable(attempts = "3", delay = "200ms", multiplier = "2")
Customer get(Long id); // tries at 0 ms, +200 ms, +400 ms
@Post("/customers")
Customer create(@Body NewCustomer c); // no @Retryable: POST is not idempotent
}
// customers service returns 503 twice, then 200:
// attempt 1 -> 503, attempt 2 -> 503, attempt 3 -> 200, caller sees the Customer
// customers service down for a minute:
// first calls retry and fail, then the breaker opens and calls fail immediately
Step throughOne get() call with retry and circuit breaker
  1. Circuit breaker open?
    YesFail immediatelyNoSend the request
  2. Success within read timeout?
    YesReturn the CustomerNoCount a failed attempt
  3. Attempts left?
    YesWait 200 ms, then 400 ms, and retryNoFail and open the breaker

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

Only idempotent calls take the retry path.

Notice the rule about idempotency. A retry sends the same request again, which is only safe if doing it twice has the same effect as once. A GET of a customer is safe. A POST that creates a customer might create two if the first attempt actually succeeded and only the response was lost. So only the GET is retried. If we need to retry a POST, the server must accept an idempotency key that lets it recognise the duplicate.

The circuit breaker stops us from hammering a service that is already failing. When a call fails after its retries, the breaker opens, and for the reset period every call fails at once without network traffic. After that, one trial call goes through; if it succeeds, the breaker closes again. Retries and breaker together should still fit our time budget: 3 attempts with 2 seconds each plus delays is over 6 seconds, which is usually too much, so in practice we lower the read timeout for retried calls.

5Blocking or Non-Blocking Return Types

The method above returns Customer directly, which makes it a blocking call: the calling thread waits for the response. Micronaut's HTTP server runs on Netty event loop threads, and a blocking call on one of those stalls every other request on that thread. Micronaut detects the most obvious case and refuses a blocking client call on an event loop thread. So either the caller runs on a blocking thread pool, for example by annotating the controller with @ExecuteOn(TaskExecutors.BLOCKING), or the client returns a non-blocking type.

Java
@Client(id = "customers")
public interface CustomerClient {
@Get("/customers/{id}")
CompletableFuture<Customer> getAsync(Long id); // completes later, thread is not held
@Get("/customers/{id}")
Mono<Customer> getMono(Long id); // with micronaut-reactor
}
@Controller("/invoices")
@ExecuteOn(TaskExecutors.BLOCKING) // needed if we call the blocking get()
public class InvoiceController { /* ... */ }

Which default thread a controller runs on has changed across Micronaut versions, and with virtual threads on Java 21 and later Micronaut can also run blocking code on virtual threads; check your version's thread selection settings. The rule that matters is stable: blocking calls belong on a blocking pool or a virtual thread, and code on the event loop uses reactive or future types.

6Follow-up questions

What does the declarative client do on a 404?

By default, a declarative client method usually treats 404 as an absent result rather than an error, returning null, an empty Optional or an empty publisher, while other error statuses raise an HttpClientResponseException. Declaring the return type as Optional<Customer> makes the absent case explicit. Behaviour has been configurable across versions, so check yours.

How would you test code that uses CustomerClient?

In unit tests we replace the client with a mock bean, since it is just an interface. For the client itself, a @MicronautTest can start an embedded server with a controller that imitates the customers API and point micronaut.http.services.customers.url at it, which tests serialisation, paths and timeouts together.

Why not write the retry loop by hand?

Hand-written loops tend to forget backoff, retry on non-idempotent methods, retry on errors that will never succeed such as 400, or ignore the time budget. The annotations make the policy visible in one line, consistent across clients, and configurable, and they combine cleanly with the circuit breaker.

7Conclusion

In this answer, we wrote a Micronaut declarative client for GET /customers/{id}. The @Client(id = "customers") interface is implemented at compile time, its URL comes from micronaut.http.services.customers or service discovery, and connect and read timeouts live in the same block. @Retryable adds retries with backoff for idempotent calls only, @CircuitBreaker fails fast when the service is down, and returning CompletableFuture or a reactive type keeps blocking calls off the event loop.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd declare an interface annotated with @Client with id customers, and a method annotated @Get of /customers/{id} that takes a Long id and returns a Customer record marked @Serdeable.

Then, if they want more

Micronaut generates the implementation at compile time, so there's no runtime proxy, and I just inject the interface. The id is a service name, not a URL: the URL comes from micronaut.http.services.customers.url, or from service discovery.

In the same configuration block I'd set connect-timeout, say 500 milliseconds, and read-timeout, say 2 seconds, so a slow service can't hold my threads forever, and I'd keep those inside my own endpoint's time budget.

For retries I'd add @Retryable with attempts 3 and delay 200 milliseconds, with a multiplier for backoff, but only on idempotent methods like this GET, never on a POST unless the server supports idempotency keys. I'd add @CircuitBreaker with a reset of about 30 seconds so we fail fast when the service is down.

In Micronaut 4 those come from the micronaut-retry module. Finally, a method returning Customer blocks, so it must not run on the Netty event loop: either the caller uses @ExecuteOn blocking, or I return CompletableFuture or a Mono instead.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. 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 "Write a Micronaut declarative HTTP client for GET /customers/{id} on another service...": https://scrivio-interview-library.netlify.app/java/other-java-frameworks/07a4a26494/