Retrofit
Timeout
Networking
Android Development
API Integration

How to set timeout in Retrofit library?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Retrofit is a powerful type-safe HTTP client for Android and Java, used to manage web service API calls. Setting a timeout in Retrofit is crucial to ensure that your application remains responsive by handling cases when a network request takes too long to complete. Here’s how you can set timeouts in the Retrofit library.

Understanding Timeouts in APIs

Timeouts in an API signify the maximum amount of time to wait for a network operation to complete. If this time elapses without completion, the operation is aborted. Timeout configurations in Retrofit are accomplished via the HTTP client it uses, commonly OkHttpClient.

In Retrofit, there are three types of timeouts:

  • Connect Timeout: The time required to connect to a server.
  • Read Timeout: The time required to read received data.
  • Write Timeout: The time applied when sending data to the server.

Setting Up Timeouts in Retrofit

To configure timeouts, you need to customize the OkHttpClient and set it in the Retrofit builder. Here’s a step-by-step guide:

Step 1: Add Dependencies

Ensure your build.gradle file includes the necessary dependencies for Retrofit and OkHttp:

gradle
1dependencies {
2    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
3    implementation 'com.squareup.okhttp3:okhttp:4.9.2'
4}

Step 2: Configure OkHttpClient

The OkHttpClient can be configured with specific timeout values.

java
1import okhttp3.OkHttpClient;
2import java.util.concurrent.TimeUnit;
3
4public OkHttpClient createOkHttpClient() {
5    return new OkHttpClient.Builder()
6            .connectTimeout(30, TimeUnit.SECONDS)
7            .readTimeout(30, TimeUnit.SECONDS)
8            .writeTimeout(30, TimeUnit.SECONDS)
9            .build();
10}

In this example, each timeout is set to 30 seconds. You can adjust these values as needed.

Step 3: Build Retrofit Instance with Custom Client

Integrate the customized OkHttpClient with Retrofit:

java
1import retrofit2.Retrofit;
2import retrofit2.converter.gson.GsonConverterFactory;
3
4public Retrofit createRetrofit() {
5    return new Retrofit.Builder()
6            .baseUrl("https://api.yourservice.com")
7            .client(createOkHttpClient()) // Link the custom OkHttpClient
8            .addConverterFactory(GsonConverterFactory.create())
9            .build();
10}

Step 4: Service Declaration and API Calls

Declare your API service interface which outlines your HTTP operations.

java
1import retrofit2.Call;
2import retrofit2.http.GET;
3
4public interface ApiService {
5    @GET("data/endpoint")
6    Call<ResponseBody> fetchData();
7}

Step 5: Execute Requests with Configured Timeout

Finally, use your configured Retrofit instance to create and execute network requests:

java
1Retrofit retrofit = createRetrofit();
2ApiService service = retrofit.create(ApiService.class);
3
4Call<ResponseBody> call = service.fetchData();
5call.enqueue(new Callback<ResponseBody>() {
6    @Override
7    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
8        if(response.isSuccessful()) {
9            // Handle the response here
10        }
11    }
12
13    @Override
14    public void onFailure(Call<ResponseBody> call, Throwable t) {
15        // Handle the error here
16    }
17});

Timeout Configuration Table

Timeout TypeDescriptionDefault ValueCustom Configuration (Example)
Connect TimeoutTime allowed to establish a connection10 seconds30 seconds
Read TimeoutTime allowed to read data10 seconds30 seconds
Write TimeoutTime allowed to write data10 seconds30 seconds

Additional Considerations

  • Exception Handling: Timeouts will result in a SocketTimeoutException. Implement robust error handling to ensure the application handles these exceptions gracefully.
  • Environmental Factors: Network conditions widely influence optimal timeout settings. Consider varying timeouts based on the operating environment (development, testing, production).
  • Performance Implications: Higher timeout values may result in unresponsive applications if the network is slow or unresponsive. Carefully balance between acceptable wait times and user experience.

By configuring timeouts wisely, developers enhance the robustness and reliability of their application’s network communications, addressing varied network performances gracefully.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.