Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • DSA
  • Practice Problems
  • C
  • C++
  • Java
  • Python
  • JavaScript
  • Data Science
  • Machine Learning
  • Courses
  • Linux
  • DevOps
  • SQL
  • Web Development
  • System Design
  • Aptitude
  • GfG Premium
Open In App
Next Article:
Easiest Way to Create REST API using Spring Boot
Next article icon

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

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Easiest Way to Create REST API using Spring Boot

S

subhadipjanacse24
Improve
Article Tags :
  • Springboot
  • Java-Spring-Boot
  • RESTful
  • Geeks Premier League 2023

Similar Reads

    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 RESTf
    7 min read
    How to set timeout for ajax by using jQuery?
    In web programming, the Ajax is used so that the resultant data is shown in the one part of the web page, without reloading the page. The user needs to perform the Ajax request and wants the result within a timeframe. In this scenario, the jquery timeout feature is used in the code. Session timeout
    4 min read
    How to set timeout for ajax by using jQuery?
    In web programming, the Ajax is used so that the resultant data is shown in the one part of the web page, without reloading the page. The user needs to perform the Ajax request and wants the result within a timeframe. In this scenario, the jquery timeout feature is used in the code. Session timeout
    4 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 configurat
    6 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. Creating a REST API using Spring Boot is one of the fastest and simplest ways to develop scalable and production-ready web services. Spring Boot simplifies REST API development by providing built-in features such as autom
    10 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 AP
    6 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences