Appendix: Description of Gateway Timeout Settings

Updated at:

The gateway involves two core types of timeouts: the idle connection timeout and the request timeout. Improper settings can cause connection resets and request backlogs, and can even trigger a service avalanche. This topic describes the configuration recommendations for both timeouts, provides client code examples for Java, Go, and the EAS SDK, and analyzes how to troubleshoot common timeout issues.

Background information

Why you need to configure timeouts

In a distributed system, the call chain between services can be long, and a delay or failure at any stage can cause a request to stall. Configuring timeouts properly allows you to:

  • Prevent resource exhaustion: Avoid having the client or the gateway wait a long time for an unresponsive backend service while continuously holding connections and threads.

  • Improve user experience: Let the caller obtain the failure result promptly and perform retries or degradation as needed.

  • Ensure system stability: Release resources promptly and prevent slow requests or faulty services from affecting the entire call chain.

Idle connection timeout

An idle connection timeout (Idle Connection Timeout) means that a connection is closed after no data is transferred on it for a period of time. This mechanism is used to manage connection pools and release inactive resources.

Configuration recommendations

The gateway configures a fixed idle connection timeout for the client side and for the model service side separately. These values cannot be modified by users:

  • Gateway as the server (facing the client): If the connection between the client and the gateway remains idle for longer than this period, the gateway closes the connection.

  • Gateway as the client (facing the model service): If the connection between the gateway and the backend model service remains idle for longer than this period, the gateway closes the connection.

Taking an ALB dedicated gateway as an example, the following figure shows the path:

image

To ensure that the client actively manages and closes connections, the recommended configuration for the complete path is as follows:

Path

Configuration recommendation

Purpose

Client → Gateway

Client Idle Timeout < Gateway Server Idle Timeout

Prevents the client from reusing a connection that the gateway has already closed

Gateway → Backend inference service

Gateway Client Idle Timeout < Backend inference service Server Idle Timeout

Prevents the gateway from reusing a connection that the model service has already closed

As a best practice, leave a safety margin between the upstream and downstream values and do not set the two values to be exactly the same.

Important

An idle connection timeout is not a request execution timeout. Take the HTTP/1.1 Keep-Alive used by vLLM and SGLang as an example: the Server Idle Timeout of the engine usually starts counting only after a response has completely finished, and is used to wait for the next request on the same connection. Setting it to 60 seconds does not directly interrupt a long-running inference request that is still being processed or is still returning data as a stream.

Default values for each access method

The following table lists the default gateway idle connection timeout for each access method, together with the recommended client and backend inference service configurations based on these default values.

Note

The gateway idle connection timeout cannot be modified by users. If you need to adjust it, submit a ticket for assistance.

Access method

Gateway Server Idle Timeout

Gateway Client Idle Timeout

Recommended client Idle Timeout

Recommended backend inference service Server Idle Timeout

Shared Gateway

180 seconds

30 seconds

Less than 180 seconds

Greater than 30 seconds

ALB dedicated gateway

600 seconds

15 seconds

Less than 600 seconds

Greater than 15 seconds

NLB load balancing

900 seconds

900 seconds

Less than 900 seconds

Greater than 900 seconds, with a safety margin reserved

Model Gallery template default values (NLB risk)

The Server Idle Timeout of the backend inference service must be greater than the Client Idle Timeout of the gateway.

When you use a Model Gallery template to deploy a vLLM or SGLang inference service, the template configures the engine HTTP Keep-Alive to 60 seconds by default.

Inference framework

Environment variable

Model Gallery template default value

vLLM

VLLM_HTTP_TIMEOUT_KEEP_ALIVE

60 seconds

SGLang

SGLANG_TIMEOUT_KEEP_ALIVE

60 seconds

For an ALB dedicated gateway, the default configuration relationship is as follows: Model Gallery engine Server Idle Timeout of 60 seconds > ALB gateway Client Idle Timeout of 15 seconds

Therefore, when you use the default ALB dedicated gateway, the 60 seconds configured by the Model Gallery template usually meets the requirement.

NLB scenarios require special attention:

Model Gallery engine Server Idle Timeout of 60 seconds < NLB Client Idle Timeout of 900 seconds

With this configuration, the backend inference service may close an idle connection first, while the NLB or the upstream connection management logic may still temporarily consider the connection available. If a subsequent request happens to reuse that connection, EOF, RST, connection reset, or occasional 502/503 errors may occur.

When you use an NLB to access a vLLM or SGLang service deployed from Model Gallery, set the Server Idle Timeout of the backend inference service to greater than 900 seconds and reserve a safety margin. For example:

# vLLM, example value
VLLM_HTTP_TIMEOUT_KEEP_ALIVE=1000

# SGLang, example value
SGLANG_TIMEOUT_KEEP_ALIVE=1000
Important

Modifying the environment variables of an EAS service triggers a service rebuild or a rolling update. Perform this operation during off-peak business hours, and confirm the replica capacity, graceful termination, and rollback plan in advance. Whether a custom runtime image or an older engine version supports the preceding environment variables depends on the actual image version and startup method.

Client configuration examples

The client Idle Timeout must be less than the gateway Server Idle Timeout. The following examples show how to manage or set the client idle connection timeout in different programming languages.

Important

The examples are for parameter setting reference only and cannot be used directly in production business systems. The actual settings must take service traffic, load conditions, and client version features into account.

Java

The connection manager of Apache HttpClient 4.x can clean up idle connections by periodically calling closeIdleConnections(). The following example sets the client idle connection timeout to 500 seconds, which is less than the 600-second Server Idle Timeout of an ALB dedicated gateway and also less than the 900 seconds of an NLB.

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.client.config.RequestConfig;
import java.util.concurrent.TimeUnit;

public class HttpClientIdleTimeout {
    public static void main(String[] args) throws InterruptedException {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // Example value: maximum number of connections per route
        cm.setDefaultMaxPerRoute(20); 
         // Example value: maximum total number of connections
        cm.setMaxTotal(100);

        RequestConfig requestConfig = RequestConfig.custom()
                // Example value: connection timeout of 5 seconds
                .setConnectTimeout(5000) 
                // Example value: data read timeout of 10 seconds
                .setSocketTimeout(10000) 
                .build();

        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .setDefaultRequestConfig(requestConfig)
                .build()) {

            // Start a background thread that cleans up idle connections at regular intervals
            Thread cleanerThread = new Thread(() -> {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        // Example value: check every 5 seconds
                        Thread.sleep(5000); 
                        // Close connections that have been idle for more than 500 seconds (less than the 600-second gateway idle timeout)
                        cm.closeIdleConnections(500, TimeUnit.SECONDS);
                        // Close expired connections (for example, connections that have been closed by the server)
                        cm.closeExpiredConnections();
                    }
                } catch (InterruptedException e) {
                    // Reset the interrupted status
                    Thread.currentThread().interrupt(); 
                }
            });
            // Set as a daemon thread, which exits when the main thread exits
            cleanerThread.setDaemon(true); 
            cleanerThread.start();

            // Execute the HTTP request...
            // For example: httpClient.execute(new HttpGet("http://your-gateway-url"));

            // Simulate the program running for a period of time. Example value: run for 1 minute
            Thread.sleep(60000); 

            // Stop the cleanup thread (in a real application, you need to stop it gracefully when the application shuts down)
            cleanerThread.interrupt();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Go

In Go, the net/http library lets you set the idle connection timeout of the client connection pool through Transport.IdleConnTimeout.

package main

import (
    "net/http"
    "time"
)

func main() {
    // Create a custom Transport
    tr := &http.Transport{
        MaxIdleConns:        100,              // Maximum number of idle connections
        IdleConnTimeout:     500 * time.Second, // Idle connection timeout, for example 500 seconds (less than 600 seconds)
        DisableKeepAlives:   false,            // Enable Keep-Alive
    }
}

EAS SDK (Java)

EAS SDK supports configuring the idle connection cleanup interval and the client idle connection timeout.

import com.aliyun.openservices.eas.predict.http.HttpConfig;

public class EasSdkTimeoutJava {
    public static void main(String[] args) {
        // 1. Global client configuration
        HttpConfig httpConfig = new HttpConfig();
        // Turn on the idle connection cleanup switch. The unit is milliseconds. Set the value based on your client conditions
        httpConfig.setConnectionCleanupInterval(5000);
        // Set the idle connection timeout to 500 seconds, which is less than the 600-second idle connection timeout of the gateway
        httpConfig.setIdleConnectionTimeout(500000);
        ...
    }
}
Note

The preceding code only configures the connection segment from the business client to the gateway. It does not modify the Client Idle Timeout from the gateway to the model service, nor does it modify the Server Idle Timeout of vLLM or SGLang.

Request timeout

A request timeout (Response Timeout) is the maximum allowed time from establishing the TCP connection and sending the request to receiving the complete response. It is the most commonly used timeout setting on the client.

Configuration recommendations

The request timeout should be adjusted based on actual business requirements. In a production environment, you need to consider fault tolerance, immediacy, model processing time, and network jitter together.

To avoid the situation where the client has already timed out while the server is still processing the request, the client request timeout can be slightly greater than the gateway request timeout.

  • As a best practice, Client timeout = Server request timeout + 1 to 5 seconds of buffer.

  • If your business requires fast failure, you can also set a shorter client timeout based on idempotence and the retry policy.

Important

Short-lived connections are constrained by both the request timeout and the idle connection timeout, so setting the request timeout greater than the idle connection timeout does not take effect. For long-running scenarios that exceed 10 minutes, the following approaches are recommended:

  • Streaming, for example, AI content generation and large file downloads.

  • WebSocket, for scenarios that require continuous two-way communication.

  • Asynchronous inference or task polling.

Assume that the request timeout of the dedicated gateway is 10 minutes (600 seconds). The path is shown in the following figure:

image

Request timeout for each access method

Access method

Request timeout description

Shared Gateway

The default request timeout is 600 seconds. You can customize the gateway request timeout for a specific service through the metadata.rpc.keepalive field in the service configuration file. For instructions, see metadata parameter descriptions.

ALB dedicated gateway

Modification through metadata.rpc.keepalive is not supported. The actual request timeout is subject to the configuration of the ALB dedicated gateway.

NLB load balancing

An NLB is Layer 4 load balancing and does not parse HTTP requests, so it does not provide HTTP request-level timeouts. Requests are still constrained by the timeouts of the client, the upstream proxy, and the backend service, and are also affected by the NLB TCP Idle Timeout.

Important

The request timeout and the HTTP keep-alive idle timeout are not the same parameter. An engine Server Idle Timeout of 60 seconds does not mean that a single inference can run for only 60 seconds. However, for non-streaming requests that have no network data for a long time, the TCP Idle Timeout of the NLB may still take effect. Validate this together with the maximum TTFT and the actual response method.

Client configuration examples

The following are examples of client request timeout configuration in different programming languages.

Important

The examples are for parameter setting reference only and cannot be used directly in production business systems. The actual settings must take service traffic, load conditions, and client version features into account.

Java

The following example only demonstrates how to configure the client request timeout. The actual values should be adjusted based on the gateway type and the model processing time.

import org.apache.http.client.config.RequestConfig;

public class ApacheHttpClientTimeout {
    public static void main(String[] args) {
        // The client request timeout should be slightly greater than or equal to the gateway request timeout (600 seconds if the default is used). Here it can be 610 seconds
        RequestConfig requestConfig = RequestConfig.custom()
                // Example value: connection timeout, in milliseconds
                .setConnectTimeout(5000) 
                // Data transfer timeout (read timeout), in milliseconds (610 seconds)
                .setSocketTimeout(610000) 
                .build();
    }
}

Go

The net/http library in Go provides multiple ways to set a request timeout. The most common approach is to set a timeout on http.Client by using the Timeout property, or to use context.WithTimeout to set a timeout for a single request.

package main

import (
    "context"
    "fmt"
    "io"
    "net/http"
    "time"
)

func main() {
    // The client request timeout should be slightly greater than or equal to the gateway request timeout (600 seconds if the default is used). Here it can be 610 seconds
    client := &http.Client{
        Timeout: 610 * time.Second, // Timeout for the entire request
    }

    req, err := http.NewRequest("GET", "http://your-gateway-url", nil)
    if err != nil {
        fmt.Println("Error creating request:", err)
        return
    }

    // You can also set a shorter timeout for a single request
    ctx, cancel := context.WithTimeout(req.Context(), 610*time.Second) // 610 seconds
    defer cancel()
    req = req.WithContext(ctx)

    resp, err := client.Do(req)
    if err != nil {
            fmt.Println("Error sending request:", err)
            // Check whether this is a timeout error
            if t, ok := err.(interface{ Timeout() bool }); ok && t.Timeout() {
                    fmt.Println("Request timed out!")
            }
            return
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Error reading response body:", err)
        return
    }
    fmt.Printf("Response Status: %s\n", resp.Status)
    fmt.Printf("Response Body: %s\n", body)
}

EAS SDK (Java)

The Alibaba Cloud EAS SDK supports setting the connection timeout and the read timeout separately in the global client configuration or in the per-request configuration.

import com.aliyun.openservices.eas.predict.http.HttpConfig;

public class EasSdkTimeoutJava {
    public static void main(String[] args) {
        // 1. Global client configuration
        HttpConfig httpConfig = new HttpConfig();
        // Connection timeout
        httpConfig.setConnectTimeout(5);
        // Read timeout. The client request timeout should be slightly greater than or equal to the gateway request timeout (600 seconds if the default is used). Here it can be 610 seconds
        httpConfig.setReadTimeout(610);  
       
    }
}

FAQ

Improper idle connection timeout settings

Scenario 1: The client idle connection timeout is greater than the gateway Server Idle Timeout

Problem description: The client connection pool still considers the connection valid, but the gateway has already closed it. When the client reuses the connection, the request may fail.

Common errors include:

  • Connection reset by peer

  • Broken pipe

  • java.net.SocketException: Connection reset

  • requests.exceptions.ConnectionError

  • read: connection reset by peer

The client may also receive HTTP 503, depending on when the connection is closed and on the gateway processing logic.

Troubleshooting and handling: Confirm the actual gateway type and set the client Idle Timeout to less than the Server Idle Timeout of that gateway. By default, an ALB dedicated gateway uses 600 seconds and an NLB uses 900 seconds.

Scenario 2: The gateway Client Idle Timeout is greater than the model service Server Idle Timeout

Problem description: The gateway still considers the backend connection reusable, but the model service has already closed the connection because of the idle timeout. When the gateway uses the connection again, it may find that the connection is disconnected.

The client may receive HTTP 502, 503, or a connection reset. This problem is usually intermittent, because if the gateway detects the connection closure in time, it can establish a new connection directly.

Troubleshooting and handling:

  1. Confirm the gateway type and its Client Idle Timeout: 15 seconds for an ALB dedicated gateway and 900 seconds for an NLB.

  2. Confirm the Server Idle Timeout of the backend inference engine.

  3. Ensure that the Server Idle Timeout of the backend inference service is greater than the Client Idle Timeout of the gateway.

  4. In NLB scenarios, pay special attention to the Model Gallery template default of 60 seconds, and adjust it to greater than 900 seconds.

  5. If necessary, use packet capture to confirm which layer sends the FIN or RST first after the previous response ends.

Improper request timeout settings

Scenario 1: The client request timeout is set too short

The client may actively disconnect before the gateway or the model service finishes processing, which produces a false timeout. Common errors include:

  • java.net.http.HttpTimeoutException

  • java.net.SocketTimeoutException: Read timed out

  • requests.exceptions.ReadTimeout

  • context deadline exceeded

The client request timeout can be set flexibly according to the fast-failure policy of your business. It does not have to be greater than the server-side request timeout in all scenarios.

Scenario 2: The gateway request timeout is less than the actual processing time of the model service

The gateway stops waiting before the model service finishes processing. The client usually receives HTTP 504, and may also receive 502 or 500 depending on the specific behavior of the path. The model service may still be processing the request, or may detect the request cancellation after the gateway closes the connection.

Use the following information to troubleshoot:

  1. The client exception type, request duration, and retry records.

  2. The status codes, request durations, and backend response durations in the gateway access logs.

  3. The request status, model processing duration, and connection interruption information in the model service logs.

  4. The TTFT and total response time of non-streaming requests, as well as the TCP Idle Timeout of the path.

Change and validation recommendations

  1. Confirm whether the access method is the Shared Gateway, an ALB dedicated gateway, or an NLB.

  2. Record the business client Idle Timeout, the gateway Server Idle Timeout, the gateway Client Idle Timeout, the Server Idle Timeout of the backend inference service, and the request timeout separately.

  3. Distinguish among the connection idle timeout, the request timeout, the read timeout, and the TCP Keep-Alive probe interval.

  4. Modifying the environment variables of the EAS inference engine triggers a service rebuild. Perform this operation during off-peak business hours.

  5. After the change, confirm that the environment variables and the actual HTTP Server configuration in the new instance have taken effect.

  6. Reuse a connection at points in time that are less than and greater than the target Idle Timeout, and observe the connection closure and reconnection behavior.

  7. Combine client logs, gateway logs, and packet captures to determine the layer that actually generates the FIN, RST, and 502/503/504 responses.

  8. Continuously observe the number of connections, file descriptors, the 5xx ratio, the success rate, and request latency, and prepare for a rollback.