Configure connection reuse for DashScope SDK
Without connection reuse, each API call opens a new TCP connection and performs a TLS handshake, adding latency. In high-concurrency scenarios, this overhead causes timeouts and resource waste. Connection reuse eliminates repeated setup, reducing latency and resource consumption.
Connection reuse
The DashScope SDK supports reducing resource consumption and improving request processing efficiency by reusing existing connections.
- Java SDK: Built-in connection pool mechanism that supports configuring parameters such as the number of connections and timeout durations, enabled by default.
- Python SDK: Supports connection reuse by passing a custom HTTP client, in both synchronous and asynchronous modes.
Java SDK
The DashScope Java SDK includes a built-in connection pool mechanism that is enabled by default. We recommend that you adjust the number of connections and the timeout durations of the connection pool based on your specific business needs to optimize connection reuse.
Configuration parameters
Parameter | Description | Default value | Unit | Notes |
|---|---|---|---|---|
connectTimeout | Timeout for establishing a connection. | 120 | seconds | In low-latency scenarios, a shorter connection timeout is typically required to reduce wait time and improve response speed. |
readTimeout | Timeout for reading data. | 300 | seconds | |
writeTimeout | Timeout for writing data. | 60 | seconds | |
connectionIdleTimeout | Timeout for idle connections in the connection pool. | 300 | seconds | In high-concurrency scenarios, appropriately extending the idle connection timeout helps avoid frequent connection creation and reduces resource consumption. |
connectionPoolSize | Maximum number of connections in the connection pool. | 32 | connections | In high-concurrency scenarios:
Adjust the configuration based on your business requirements. |
maximumAsyncRequests | Maximum number of concurrent requests. A global limit on the number of concurrent requests (including all hosts). It must be less than or equal to the maximum number of connections; otherwise, requests may block. | 32 | requests | |
maximumAsyncRequestsPerHost | Maximum number of concurrent requests for a single host. It must be less than or equal to the maximum number of concurrent requests. | 32 | requests |
Code example
Before running the code, configure the API key as an environment variable and install the latest SDK.
The following code example shows how to configure connection pool parameters (such as timeout durations and the maximum number of connections) and call a model service. You can adjust these parameters based on your actual needs to optimize concurrency performance and resource utilization.
// 建议DashScope SDK的版本 >= 2.12.0
import java.time.Duration;
import java.util.Arrays;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.ConnectionConfigurations;
import com.alibaba.dashscope.utils.Constants;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
Generation gen = new Generation();
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("You are a helpful assistant.")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("你是谁?")
.build();
GenerationParam param = GenerationParam.builder()
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
// 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 此处以qwen-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
System.out.println(userMsg.getContent());
return gen.call(param);
}
public static void main(String[] args) {
// 连接池配置
Constants.connectionConfigurations = ConnectionConfigurations.builder()
.connectTimeout(Duration.ofSeconds(10)) // 建立连接的超时时间, 默认 120s
.readTimeout(Duration.ofSeconds(300)) // 读取数据的超时时间, 默认 300s
.writeTimeout(Duration.ofSeconds(60)) // 写入数据的超时时间, 默认 60s
.connectionIdleTimeout(Duration.ofSeconds(300)) // 连接池中空闲连接的超时时间, 默认 300s
.connectionPoolSize(256) // 连接池中的最大连接数, 默认 32
.maximumAsyncRequests(256) // 最大并发请求数, 默认 32
.maximumAsyncRequestsPerHost(256) // 单个主机的最大并发请求数, 默认 32
.build();
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
// 使用日志框架记录异常信息
System.err.println("An error occurred while calling the generation service: " + e.getMessage());
}
System.exit(0);
}
}
Python SDK
The DashScope Python SDK supports connection reuse by passing a custom HTTP client (httpx.Client / httpx.AsyncClient). It provides two calling methods: asynchronous HTTP (coroutine-based) and synchronous HTTP.
Asynchronous HTTP calls
In asynchronous call scenarios, you can use httpx.AsyncClient with httpx.Limits to implement connection reuse. httpx.Limits supports configuring parameters such as connection limits:
Parameter | Description | Default value | Notes |
|---|---|---|---|
max_connections | Total connection limit | None (unlimited) | Controls the maximum number of connections. In high-concurrency scenarios, appropriately increasing this value can improve concurrency. |
max_keepalive_connections | Maximum number of keep-alive connections | None (unlimited) | Controls the number of connections kept active in the connection pool, preventing excessive pressure on a single server. |
keepalive_expiry | Keep-alive duration | 5.0 (seconds) | Timeout for idle keep-alive connections. Connections are closed automatically after this duration. |
Code example
Before running the code, configure the API key as an environment variable and install the latest SDK.
The following code example shows how to configure connection reuse in an asynchronous scenario and call a model service:
import asyncio
import httpx
import os
import dashscope
async def main():
# 配置连接参数
limits = httpx.Limits(
max_connections=100, # 总连接数限制
max_keepalive_connections=30, # 保持长连接的最大数量
)
# 创建自定义 HTTP 客户端并传入 Client 构造
async with httpx.AsyncClient(limits=limits) as http_client:
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key = "sk-xxx"
aclient = dashscope.AsyncClient(
api_key=os.getenv("DASHSCOPE_API_KEY"),
http_client=http_client, # 传入自定义 HTTP 客户端
)
response = await aclient.chat.completions.create(
model='qwen-plus',
messages=[{"role": "user", "content": '你好,请介绍一下你自己'}],
)
print(response)
asyncio.run(main())
Synchronous HTTP calls
In synchronous call scenarios, you can use httpx.Client to implement connection reuse. Multiple requests within the same HTTP client reuse the underlying TCP connection, avoiding the overhead of repeatedly establishing connections.
Code example
Before running the code, configure the API key as an environment variable and install the latest SDK.
The following code example shows how to configure connection reuse in a synchronous scenario and call a model service:
import httpx
import os
import dashscope
# 使用 with 语句确保 HTTP 客户端正确关闭
with httpx.Client() as http_client:
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key = "sk-xxx"
client = dashscope.Client(
api_key=os.getenv("DASHSCOPE_API_KEY"),
http_client=http_client, # 传入自定义 HTTP 客户端
)
response = client.chat.completions.create(
model='qwen-plus',
messages=[{"role": "user", "content": '你好'}],
)
print(response)
If you need to reuse the same HTTP client across multiple calls, you can use the following approach:
import httpx
import os
import dashscope
# 创建 HTTP 客户端对象,并配置连接复用参数
http_client = httpx.Client(
limits=httpx.Limits(
max_connections=100, # 总连接数限制
max_keepalive_connections=30, # 保持长连接的最大数量
),
)
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key = "sk-xxx"
client = dashscope.Client(
api_key=os.getenv("DASHSCOPE_API_KEY"),
http_client=http_client, # 传入自定义 HTTP 客户端
)
try:
# 多次调用复用同一个 HTTP 客户端
response1 = client.chat.completions.create(
model='qwen-plus',
messages=[{"role": "user", "content": '你好'}],
)
print(response1)
response2 = client.chat.completions.create(
model='qwen-plus',
messages=[{"role": "user", "content": '介绍一下你自己'}],
)
print(response2)
finally:
# 确保 HTTP 客户端正确关闭
http_client.close()
Best practices
- Java SDK: Configure parameters such as
connectionPoolSizeandmaximumAsyncRequestsbased on your business concurrency to avoid an excessively high or low number of connections. - Python SDK: We recommend using the
withstatement to automatically manage the lifecycle of the HTTP client and ensure that resources are released correctly. - Choose the appropriate calling method: If your application uses an asynchronous architecture (such as asyncio or FastAPI), we recommend the asynchronous calling method; for a traditional synchronous architecture, use the synchronous calling method.
Error codes
If a model call fails (the Python SDK raises a DashScopeError exception, and HTTP calls return an error message), see Error codes to resolve the issue.