Open In App

Spring Boot - How to set a Request Timeout for a REST API

Last Updated : 05 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Microservice architecture, there are multiple microservices available for an application. For the application to work properly necessary services need to communicate with each other. There can be communication of messaging type or REST calls.

How does REST API Work?

In REST Calls the process is synchronous, which means suppose a service SERV1 is waiting for the response from SERV2 it will wait for an infinite time until it gets the response. Now the problem here is that if for some reason SERV2 is taking way too much time to give a response, so SERV1 keeps on waiting resulting in overall lag in the System or the Application. To overcome this type of situation we use something called Request Timed out. If Timed out time is defined as say 5 seconds, and the repose from a service didn't come in between that time it will wait no further for the response and terminate the process.

If you want to learn more about REST API visit the article on Rest API on GeeksForGeeks.

Steps to set Request Timeout for a REST API

Step 1: Create a Spring Boot Project

To create a spring boot project, go to start.spring.io, create a project with the following configurations, and add the dependencies mentioned.

Project Metadata

Set Project as Maven, Language as Java, Spring Boot version 3.2.1, Packaging as Jar and Java Version 17.
You can give Name and descriptions of your choice.

Dependencies

Add depencencies for

  • Spring Web
  • Lombok
  • Spring Boot Dev Tools

Now click on Generate button there to download the project as zip file, once downloaded unzip it.

Step 2: Open the project

Use any IDE of your choice to open the project folder and wait for some time for the IDE to configure it on it's own.

Note: Here we are using Intellij IDEA IDE.

Check the folder structure below,

Project Structure

Open the pom.xml file and add the following dependency:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>

Check the pom.xml file below,

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Geeks</groupId>
    <artifactId>Rest-Communication</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Rest-Communication</name>
    <description>Demo project for Rest Communication</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents.client5</groupId>
            <artifactId>httpclient5</artifactId>
            <version>5.2.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Now refresh your project to configure the dependency added.

Step 3: Create a Contoller

Let's a create a Rest Controller and name it as geekContoller

GeekController.java:

Java
package com.Geeks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping
public class geekController {
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/geek")
    public String getGeek(){
        try {
            ResponseEntity<String> response = restTemplate.getForEntity("", String.class);
            return response.getBody();
        }catch (ResourceAccessException e){
            e.printStackTrace();
            return null;
        }
    }
}

Here we have anotated it with RestController anotation, and used @Autowired for automatic object creation for RestTemplate. Here mapping done for "/geek" and we will put the URL of the other service from where we have to recieve response in restTemplate.getForEntity. We have surrounded the response.getBody() with a try and catch block and printing the stack Tree for timeout. You can define what the exception will do in your project.

Now this is the basic rest template which will wait for infinite time for response. Let's make the changes in the RestCommunicationApplication.java file to implement the timeout feature.

RestCommunicationApplication.java:

Java
package com.Geeks;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestCommunicationApplication {
    @Bean
    public RestTemplate restTemplate(){
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectTimeout(5000);
        return new RestTemplate(httpRequestFactory);
    }
    public static void main(String[] args) {
        SpringApplication.run(RestCommunicationApplication.class, args);
    }
}

Here we have configured the Bean of RestTemplate. This bean class is returning an object where the constructed takes ClientHttpRequestFactory for which we have created one object of HttpComponentsClientHttpRequestFactory class (for which we have added the dependency). We have set the connectTimeout as 5000 which indicates 5sec. In a real aplication, this time will be very less which is in milli seconds.

Step 4: Testing Request Timeout

Create a new Project.

To test if time out is happening or not let's create another spring boot project quickly with the same configuration of the previous one and name it GeekServer.

Spring Initializr

Configure Ports

Open this project in a separate window in your IDE. As our previously application will be running at default port which is 8080. let's change port no for this application in application.properties under resource folder and assign port no 9000 for this.

application.properties (highlighted)

In this file write,

server.port = 9000

Create a Controller

Create a controller and name it GeekServer which will return a message say, " Hello Geek".

GeekServer.java:

Java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping
public class GeekServer {
    @GetMapping("/geekserver")
    public String getMessage(){
        return "Hello Geek";
    }
}

Run this application and check output

Go to GeekServerApplication and run the project and in your web browser's url bar type localhost:9000/geekserver and check if the controller is working fine.

Output

Configure the Services

In the RestCoomunicationApplication project's GeekController put localhost:9000/geekserver as URL and check if the same response is coming in that route.

GeekController.java:

Java
package com.Geeks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping
public class geekController {
    @Autowired private RestTemplate restTemplate;
    @GetMapping("/geek") public String getGeek()
    {
        try {
            ResponseEntity<String> response
                = restTemplate.getForEntity(
                    "localhost:9000/geekserver",
                    String.class);
            return response.getBody();
        }
        catch (ResourceAccessException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Now run the RestCommunicationApplication project and in web browser check the output at localhost:8080/geek. Keep the other project running on background.

Output Screen with different port

Check Request timeout

Here we have stopped the application running on port 9000, and now try running our application named RestCommunicationApplication.

org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:9000/geekserver": Connect to http://localhost:9000 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: no further information
at org.springframework.web.client.RestTemplate.createResourceAccessException(RestTemplate.java:905)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:885)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:781)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:422)
at com.Geeks.GeekController.getGeek(GeekController.java:20)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)

So, we can observe that our application waited for 5sec and then gave the ResourceAccessException as there is no service running at port 9000.

Check Timeout when there is a delay

To test this let's create a delay of say 10sed on the GeekServer by modifying the GeekServer.java file.

GeekServer.java:

Java
package com.geekServer;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping
public class GeekServer {
    @GetMapping("/geek")
    public String getMessage() throws InterruptedException {
        Thread.sleep(10000);
        return "Hello Geek";
    }
}

We have added Thread.sleep(10000) which will create a delay of 10sec. Now run both the application and check what happens,

org.springframework.web.client.ResourceAccessException: I/O error on GET request for 
"http://localhost:9000/geekserver": Connect to http://localhost:9000 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1]
failed: Connection refused: no further information
at org.springframework.web.client.RestTemplate.createResourceAccessException(RestTemplate.java:905)

We can observe that instead of waiting for an infinite time the Application is throwing exception and timeout is working.

Now we can use this timeout feature in your Spring Boot application to overcome the problem of infinite waiting time and improve the lag in the Application significantly. This will make sure that the application doesn't stop operation and improves stability. We can give significantly lower time frame for timeout and try again after the timeout for better performance, this will not block your tread and system will not go down.


Similar Reads

How to create a REST API using Java Spring Boot
Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems
6 min read
JSON using Jackson in REST API Implementation with Spring Boot
Whenever we are implementing a REST API with Spring (Spring Boot), we would have come across the requirement to exclude NULLs in the JSON Response of the API. Also, there might be a requirement to externalize turning ON/OFF this feature: Exclude NULLS in the JSON Response, thereby allowing the consumer of the API to customize as per the need. In th
3 min read
Spring Boot - REST API Documentation using OpenAPI
For any application, API documentation is essential for both users and developers. How to use an API, what will be the request body, and what will the API's response be? API documentation is the answer to all of these questions, springdoc-openapi is a Java library that automates the generation of the API documentation in both JSON/YAML and HTML for
4 min read
Easiest Way to Create REST API using Spring Boot
Spring Boot is a powerful framework that makes it easy to create RESTful APIs. In this article, we will go through a step-by-step guide on how to create a RESTful API in Spring Boot with MySQL and JPA. We will start by creating a new Spring Boot project and configuring it for our needs. For developers eager to deepen their knowledge and expertise i
11 min read
Spring Boot - Versioning a REST API
API Versioning is a defined process of making or managing changes to an API. These changes can be made transparently without interrupting the clients. When users have permission to decide whether they can conveniently upgrade to the latest version of API and clearly state the changes made is known as a Good API Versioning Strategy. When to Version
3 min read
Spring Boot – REST API Documentation using Swagger
REST stands for Representational State Transfer. REST is an architectural design pattern that defines constraints that are used in web service development. Swagger is a framework in which we can test our REST APIs for different HTTP requests i.e. : GETPOSTPUTDELETEIn this article, we will be discussing using Swagger for documenting APIs in Spring B
5 min read
Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Boot – Handling Background Tasks with Spring Boot
Efficiently handling background tasks with Spring Boot is important for providing a smooth user experience and optimizing resource utilization. Background tasks refer to operations that are performed asynchronously or in the background, allowing the main application to continue processing other requests. In a Spring Boot application, background tas
5 min read
Spring Boot – Using Spring Boot with Apache Camel
Apache Camel and Spring Boot are two powerful frameworks that can be seamlessly integrated to build robust, scalable, and efficient applications. Apache Camel is an open-source integration framework that provides an extensive range of components and connectors, enabling developers to integrate different systems, APIs, and applications. It simplifie
5 min read
Spring Boot – Setting Up a Spring Boot Project with Gradle
Spring Boot is a Java framework designed to simplify the development of stand-alone, production-ready Spring applications with minimal setup and configuration. It simplifies the setup and development of new Spring applications, reducing boilerplate code. In this article, we will guide you through setting up a Spring Boot project using Gradle, a wid
4 min read
Migrate Application From Spring Boot 2 to Spring Boot 3
With the release of Spring Boot 3, significant changes and improvements have been introduced, particularly around Jakarta EE compliance, Java 17 support, and GraalVM native images. If you are using Spring Boot 2 and are considering migrating to Spring Boot 3, this article will walk you through the necessary steps, considerations, and potential pitf
5 min read
Spring Boot - Customizing Spring Boot Starter
Spring Boot Starters are specialized project types designed to encapsulate and distribute common functionality, simplifying the setup of Spring Boot applications. Official starters, like spring-boot-starter-web and spring-boot-starter-data-jpa, bundle dependencies, configurations, and pre-built beans for specific use cases. Creating a custom Spring
6 min read
Spring REST - Response for Access Denied Request
The Access Denied Request has an error code of 403. This is the error that is generated when the user tries to access certain resources that he is not authorized. The system displays a whitelabel error displaying the status code 403. In this article, let us regenerate this error using spring security and then handle the same effectively using sprin
5 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Migrating a Spring Boot Application from Spring Security 5 to Spring Security 6
Spring Security is a powerful authentication and access control framework for Java applications specially for those built with the Spring Framework. With the release of Spring Security 6, several enhancements and changes have been introduced to simplify the security configuration and provide better performance and security features. This article ai
4 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
How to Build a RESTful API with Spring Boot and Spring MVC?
RESTful APIs have become the standard for building scalable and maintainable web services in web development. REST (Representational State Transfer) enables a stateless, client-server architecture where resources are accessed via standard HTTP methods. This article demonstrates how to create a RESTful API using Spring Boot and Spring MVC. We will w
7 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Securing Spring Boot API With API Key and Secret
In Web applications, securing the APIs is critical. One of the common methods of securing the APIs is by using API keys and secrets. This ensures that only the authorized clients can access the API endpoints. This article can guide you through the process of securing the Spring Boot API using the API keys and secrets. Securing the Spring Boot API w
6 min read
Spring Boot - REST Example
We all know in today's world, most web app follows the client-server architecture. The app itself is the client or frontend part under the hood it needs to call the server or the backend to get or save the data this communication happens using HTTP protocol the same protocol is the power of the web. On the server, we expose the bunch of services th
4 min read
Spring Boot: Cannot access REST Controller on localhost (404)
The Spring Boot framework is one of the most famous in web application development, It can provide a lot of features to make development easy like dependency management, Spring Security, Spring Autoconfiguration, and other features provided by the Spring Framework. In this article, we will learn how a 404 error occurs while accessing the REST Contr
4 min read
Best Practices while Making Rest APIs in Spring Boot Application
API, or Application Programming Interface, is a communication gateway between frontend and backend code. A robust API is crucial for ensuring uninterrupted functionality. In this article, we will discuss how to achieve robustness in our REST API within the Spring Boot application. Rules : Use JSON as the Standard Message FormatError HandlingPaginat
7 min read
How to Generate Spring Boot REST Client with Swagger?
Spring Boot is a powerful framework for building Java applications, particularly RESTful web services. When developing the REST APIs, it can be crucial to provide documentation that is both user-friendly and interactive. Swagger is an open-source that simplifies this by generating the API documentation automatically. In this article, we will create
6 min read
Spring Boot – Building REST APIs with HATEOAS
In this article, we will explore how to build RESTful APIs using the Spring Boot with HATEOAS (Hypermedia as the Engine of Application State). HATEOAS is the key component of the REST application architecture, where each resource not only provides the data but also includes links to other actions that can be performed on the resource. This approach
5 min read
How to Make REST Calls using FeignClient in Spring Boot?
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. FeignClient also known as Spring Cloud OpenFeign is a Declarative REST Client in Spring Boot Web Application.
13 min read
Spring Boot - Rest Template
RestTemplate is a powerful synchronous client for handling HTTP communication in Spring Boot applications. It internally uses an HTTP client library i.e. java.net.HttpURLConnection, simplifying the process of making RESTful requests to external services and APIs, including convenience, along with integration, and flexibility for various HTTP commun
7 min read
How to Call REST Services with WebClient in Spring Boot?
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring WebClient is a non-blocking and reactive web client to perform HTTP requests. It is also the replaceme
11 min read
Spring Boot - 415 Unsupported Media Type Error for Post Request for @ManyToMany Relation
Spring Boot is a widely used Java-based framework that simplifies the process of building enterprise applications by providing an opinionated and flexible approach to development. It offers features such as auto-configuration, embedded servers, and a wide range of tools and libraries for building various types of applications. Spring Boot supports
4 min read
How to Make Put Request in Spring Boot?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the Java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every concept in the language to the real world with the hel
3 min read
How to Solve 403 Error in Spring Boot Post Request?
Spring Boot is one of the frameworks used in developing web applications, and it provides a lot of features to solve real-time problems in software industries. In this article, we will explain how to solve the 403 error in the Spring Boot post request. This error is raised due to security configuration, authentication and authorization, and other a
6 min read
Practice Tags :
three90RightbarBannerImg