> For the complete documentation index, see [llms.txt](https://www.pranaypourkar.co.in/the-programmers-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.pranaypourkar.co.in/the-programmers-guide/spring/spring-features/inter-service-communication/rest-communication/resttemplate/asynchronous-execution.md).

# Asynchronous Execution

## About

While `RestTemplate` itself is **synchronous by design**, it can be **used asynchronously** by **wrapping it with concurrency mechanisms** such as `CompletableFuture`, `ExecutorService`, or integrating with Spring’s `@Async` support.

This allows a system to make **non-blocking parallel HTTP calls**—improving **throughput**, **latency**, and **resource utilization**, especially in IO-bound service-to-service communication.

In modern microservices and cloud-native systems:

* Services often call **multiple downstream APIs**.
* Waiting sequentially for all responses can become a **performance bottleneck**.
* Asynchronous execution allows **concurrent invocations**, reducing **overall response time**.
* It enables use cases like **parallel data fetching**, **timeout-based fallbacks**, and **circuit breaker integration**.

## **1. Using CompletableFuture with Custom Executor**

This is the most popular pattern in enterprise applications for parallel execution.

```java
@Async("customExecutor")
public CompletableFuture<UserResponse> getUserAsync(String userId) {
    String url = "http://userservice/api/users/" + userId;
    UserResponse response = restTemplate.getForObject(url, UserResponse.class);
    return CompletableFuture.completedFuture(response);
}
```

We must annotate our class with `@EnableAsync` and define an executor:

```java
@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean(name = "customExecutor")
    public Executor taskExecutor() {
        return new ThreadPoolTaskExecutorBuilder()
            .corePoolSize(10)
            .maxPoolSize(50)
            .queueCapacity(100)
            .threadNamePrefix("async-rest-")
            .build();
    }
}
```

Then use it:

```java
CompletableFuture<UserResponse> user1 = service.getUserAsync("123");
CompletableFuture<UserResponse> user2 = service.getUserAsync("456");

CompletableFuture.allOf(user1, user2).join();

UserResponse result1 = user1.get();
UserResponse result2 = user2.get();
```

## **2. Manual ExecutorService Wrapping**

For fine-grained control (without `@Async`), wrap the calls manually:

```java
ExecutorService executor = Executors.newFixedThreadPool(10);

Callable<UserResponse> task = () -> restTemplate.getForObject(url, UserResponse.class);
Future<UserResponse> future = executor.submit(task);
```

Use `invokeAll` to parallelize multiple calls.

## **3. Combining with Retry or Timeout Logic**

To prevent indefinite blocking:

```java
CompletableFuture<UserResponse> future = CompletableFuture
    .supplyAsync(() -> restTemplate.getForObject(url, UserResponse.class), executor)
    .orTimeout(3, TimeUnit.SECONDS)
    .exceptionally(ex -> {
        log.warn("Timeout or failure for user call", ex);
        return fallbackResponse();
    });
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://www.pranaypourkar.co.in/the-programmers-guide/spring/spring-features/inter-service-communication/rest-communication/resttemplate/asynchronous-execution.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
