Appendix: Configure dedicated gateway timeouts

更新时间:
复制 MD 格式

Configure idle connection and request timeouts for dedicated gateways in Java, Go, and EAS SDK clients, and troubleshoot common timeout issues.

Background

Why timeouts matter

In a distributed system, call chains between services can be long. A delay or failure at any point may cause requests to hang. Proper timeout configuration helps you:

  • Prevent resource exhaustion: Stop clients or gateways from holding connections and threads while waiting for an unresponsive backend service.

  • Improve user experience: Return failures promptly so callers can retry or fall back as needed.

  • Maintain system stability: Release resources early to prevent slow or unhealthy services from affecting the entire call chain.

Configure the idle connection timeout

The idle connection timeout closes a connection after a period of no data transfer. This mechanism manages connection pools and releases inactive resources.

Recommended configuration

The fully managed gateway uses the following fixed idle connection timeout values. These values can't be modified.

  • Gateway as server (facing clients): Fixed at 600 seconds. If a client-to-gateway connection is idle for longer than this period, the gateway closes it.

  • Gateway as client (facing backend inference services): Fixed at 30 seconds. If a gateway-to-backend connection is idle for longer than this period, the gateway closes it.

The following diagram illustrates the connection flow:

image

To ensure that the client manages and closes connections, configure each link as follows:

Link

Recommended configuration

Purpose

Client → Gateway

Client idle timeout < gateway server idle timeout

Prevent the client from reusing a connection the gateway has already closed

Gateway → Backend inference service

Gateway client idle timeout < backend inference service server idle timeout

Prevent the gateway from reusing a connection the backend inference service has already closed

Leave a safety margin between upstream and downstream values. Avoid setting related timeouts to the same value.

Important

The idle connection timeout isn't a request execution timeout. vLLM and SGLang use HTTP/1.1 Keep-Alive. With this mechanism, the engine's server idle timeout starts only after a response completes, waiting for the next request on the same connection. Setting it to 60 seconds doesn't interrupt a long-running or streaming inference request.

Default values by access method

The following table lists the default idle connection timeout for each access method, along with recommended client and backend inference service configurations.

Note

Gateway idle connection timeout values can't be modified. To request a change, submit a ticket.

Access method

Gateway server idle timeout

Gateway client idle timeout

Recommended client idle timeout

Recommended backend server idle timeout

Fully managed gateway (MSE gateway)

600 seconds

30 seconds

Less than 600 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

Model Gallery template defaults and NLB considerations

The backend inference service server idle timeout must be greater than the gateway client idle timeout.

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

Inference framework

Environment variable

Model Gallery template default

vLLM

VLLM_HTTP_TIMEOUT_KEEP_ALIVE

60 seconds

SGLang

SGLANG_TIMEOUT_KEEP_ALIVE

60 seconds

For the fully managed gateway and ALB dedicated gateway, the default configuration works as follows:

  • Model Gallery engine server idle timeout 60 seconds > ALB gateway client idle timeout 15 seconds

  • Model Gallery engine server idle timeout 60 seconds > fully managed gateway client idle timeout 30 seconds

The Model Gallery template default of 60 seconds meets the requirements for both the ALB dedicated gateway and the fully managed gateway.

NLB requires special attention:

Model Gallery engine server idle timeout 60 seconds < NLB client idle timeout 900 seconds

With this configuration, the backend inference service may close idle connections first, while NLB or upstream connection management still considers the connection available. Subsequent requests that reuse such a connection may encounter EOF, RST, connection resets, or intermittent 502/503 errors.

When using NLB with vLLM or SGLang services deployed through Model Gallery, set the backend inference service server idle timeout to a value greater than 900 seconds with a safety margin. For example:

# vLLM, example value
VLLM_HTTP_TIMEOUT_KEEP_ALIVE=1000

# SGLang, example value
SGLANG_TIMEOUT_KEEP_ALIVE=1000
Important

Modifying EAS service environment variables triggers a service rebuild or rolling update. Perform changes during off-peak hours and confirm replica capacity, graceful shutdown, and rollback procedures beforehand. Custom images and older engine versions might not support these environment variables. Check the image documentation for details.

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

These examples are for parameter reference only and aren't intended for direct use in production systems. Actual values depend on traffic patterns, load conditions, and client version characteristics.

Java

The Apache HttpClient 4.x connection manager 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 the fully managed gateway and ALB dedicated gateway, and also less than the 900-second NLB timeout.

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: max connections per route
        cm.setDefaultMaxPerRoute(20);
         // Example value: max total connections
        cm.setMaxTotal(100);

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

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

            // Start a background thread to clean up idle connections periodically
            Thread cleanerThread = new Thread(() -> {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        // Example value: check every 5 seconds
                        Thread.sleep(5000);
                        // Close connections idle for more than 500 seconds (less than gateway idle timeout of 600 seconds)
                        cm.closeIdleConnections(500, TimeUnit.SECONDS);
                        // Close expired connections (e.g., connections closed by the server)
                        cm.closeExpiredConnections();
                    }
                } catch (InterruptedException e) {
                    // Restore interrupted status
                    Thread.currentThread().interrupt();
                }
            });
            // Set as daemon thread so it exits when the main thread exits
            cleanerThread.setDaemon(true);
            cleanerThread.start();

            // Execute HTTP requests...
            // Example: httpClient.execute(new HttpGet("http://your-gateway-url"));

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

            // Stop the cleaner thread (in production, gracefully shut it down during application shutdown)
            cleanerThread.interrupt();

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

Go

Go's net/http library lets you set the client connection pool idle timeout 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, e.g. 500 seconds (less than 600 seconds)
        DisableKeepAlives:   false,            // Enable Keep-Alive
    }
}

EAS SDK (Java)

The 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();
        // Enable idle connection cleanup, in milliseconds. Set based on your client requirements.
        httpConfig.setConnectionCleanupInterval(5000);
        // Set the idle connection timeout to 500 seconds, less than the fully managed gateway idle timeout of 600 seconds
        httpConfig.setIdleConnectionTimeout(500000);
        ...
    }
}
Note

The preceding code configures only the client-to-gateway connection. It doesn't modify the gateway-to-model-service client idle timeout or the vLLM/SGLang server idle timeout.

Configure the request timeout

The request timeout is the maximum time allowed from TCP connection establishment and request submission to full response receipt. It's the most commonly configured client timeout.

Recommended configuration

Adjust the request timeout based on your business requirements. In production, balance fault tolerance, responsiveness, model processing time, and network jitter.

To prevent the client from timing out while the server is still processing, set the client request timeout slightly higher than the gateway request timeout.

  • A common formula: client timeout = server request timeout + 1–5 seconds.

  • For fast-fail scenarios, set a shorter client timeout and rely on idempotence and retry strategy to handle failures.

For long-running scenarios that exceed 10 minutes, use one of these approaches instead:

  • Streaming, such as AI content generation and large file downloads.

  • WebSocket, for persistent bidirectional communication.

  • Asynchronous inference or task polling.

The fully managed gateway has a default request timeout of 10 minutes (600 seconds). The following diagram illustrates the request timeout flow:

image

Request timeout by access method

Access method

Request timeout description

Fully managed gateway (MSE gateway)

Default request timeout: 600 seconds. You can customize the gateway request timeout for specific services through the metadata.rpc.keepalive field in the service configuration file. For details, see Metadata parameters.

ALB dedicated gateway

Can't be modified through metadata.rpc.keepalive. The actual request timeout follows the ALB dedicated gateway configuration.

NLB load balancing

NLB is a Layer 4 load balancer that doesn't parse HTTP requests, so it doesn't provide HTTP request-level timeout. Requests are still subject to client, upstream proxy, and backend service timeouts, as well as the NLB TCP idle timeout.

Important

Request timeout and HTTP Keep-Alive idle timeout are different parameters. An engine server idle timeout of 60 seconds doesn't mean a single inference is limited to 60 seconds. However, for non-streaming requests with no network data for an extended period, the NLB TCP idle timeout may still apply. Validate the timeout against the maximum time to first token (TTFT) and the actual response pattern.

Client configuration examples

The following examples show how to configure the client request timeout in different programming languages.

Important

These examples are for parameter reference only and aren't intended for direct use in production systems. Actual values depend on traffic patterns, load conditions, and client version characteristics.

Java

The following example shows how to configure the client request timeout. Adjust the actual value based on your gateway type and model processing time.

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

public class ApacheHttpClientTimeout {
    public static void main(String[] args) {
        // Set the client request timeout slightly above the gateway request timeout.
        // If the gateway default is 600 seconds, use 610 seconds here.
        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

Go's net/http library provides multiple ways to set request timeouts. The most common approach is to set Timeout on http.Client, or use context.WithTimeout for per-request timeouts.

package main

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

func main() {
    // Recommended: set client request timeout slightly greater than or equal to the gateway request timeout (default 600 seconds). Use 610 seconds here.
    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 individual requests
    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 if it 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 connection timeout and read timeout at both the global client level and the per-request level.

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. Set the client request timeout slightly above the gateway request timeout.
        // If the gateway default is 600 seconds, use 610 seconds here.
        httpConfig.setReadTimeout(610);

    }
}

Common issues

Idle connection timeout misconfiguration

Scenario 1: Client idle timeout exceeds gateway server idle timeout

Symptom: The client connection pool considers a connection valid, but the gateway has already closed it. Subsequent requests that reuse the connection 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 an HTTP 503, depending on when the connection was closed and the gateway processing logic.

Troubleshooting: Identify the gateway type and set the client idle timeout below the corresponding gateway server idle timeout. By default, the fully managed gateway and ALB dedicated gateway use 600 seconds, and NLB uses 900 seconds.

Scenario 2: Gateway client idle timeout exceeds backend inference service server idle timeout

Symptom: The gateway considers the backend connection reusable, but the backend inference service has already closed it due to idle timeout. When the gateway reuses the connection, it finds the connection dropped.

The client may receive HTTP 502, 503, or a connection reset. This issue is typically intermittent because the gateway can establish a new connection if it detects the close in time.

Troubleshooting:

  1. Identify the gateway type and its client idle timeout: fully managed gateway 30 seconds, ALB dedicated gateway 15 seconds, NLB 900 seconds.

  2. Check the backend inference engine server idle timeout.

  3. Make sure the backend inference service server idle timeout is greater than the gateway client idle timeout.

  4. For NLB, check the Model Gallery template default of 60 seconds and increase it to above 900 seconds.

  5. If needed, use packet capture to determine the order of FIN and RST packets after the previous response completes. This identifies which layer initiated the connection termination.

Request timeout misconfiguration

Scenario 1: Client request timeout set too short

The client may disconnect before the gateway or backend inference service finishes processing, producing 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 adjusted based on your fast-fail strategy. Not every scenario requires the client timeout to exceed the server request timeout.

Scenario 2: Gateway request timeout shorter than actual model processing time

The gateway stops waiting before the backend inference service finishes. The client typically receives HTTP 504, but may also get 502 or 500 depending on where the connection breaks. The backend inference service may continue processing, or detect the request cancellation after the gateway closes the connection.

Gather the following information for troubleshooting:

  1. Client error type, request duration, and retry history.

  2. Status codes, request duration, and backend response time from gateway access logs.

  3. Request status, model processing time, and connection interruption details from backend inference service logs.

  4. For non-streaming requests: time to first token (TTFT), total response time, and link TCP idle timeout.

Change and verification guidelines

  1. Confirm the access method: fully managed gateway, ALB dedicated gateway, or NLB.

  2. Record the client idle timeout, gateway server idle timeout, gateway client idle timeout, backend inference service server idle timeout, and request timeout.

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

  4. Modifying EAS inference engine environment variables triggers a service rebuild. Perform changes during off-peak hours.

  5. After changes, verify that the environment variables and actual HTTP server configuration have taken effect in the new instances.

  6. Test connections at intervals both below and above the target idle timeout to observe how connections are closed and re-established.

  7. Use client logs, gateway logs, and packet capture to identify which layer produces FIN, RST, and 502/503/504 errors.

  8. Monitor connection count, file descriptors, 5xx ratio, success rate, and request latency. Prepare a rollback plan.