> ## Documentation Index
> Fetch the complete documentation index at: https://docs.baseten.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Configure HTTP clients

> Configure connection pooling, retries, and timeouts for reliable inference requests at scale.

Reuse HTTP connections and set timeouts for your workload when calling Baseten repeatedly. Investigate client, network, and server behavior together when requests fail; see [Inference errors](https://docs.baseten.co/inference/errors.md#errors-from-your-model-or-from-baseten).

> [!TIP]
>
> The [Performance Client](https://docs.baseten.co/reference/sdk/performance-client/overview.md) handles connection pooling, retries, and concurrency for batch inference.

## Reuse client sessions

Creating a new HTTP client per request prevents connection reuse. Repeated connection setup adds TCP and TLS overhead and can exhaust client or NAT resources under load.

A reused client maintains a pool of open connections that are ready for
subsequent requests. This reduces connection setup overhead. Match pool size and request concurrency to your workload.

> [tab] Recommended
>
> **To reuse a connection pool**:
>
> Set `BASETEN_MODEL_ID` and `BASETEN_API_KEY`, install `httpx` with `pip install httpx`, then run the following script. Replace the payload with your model's input. For an identity Truss, the request returns the input unchanged:
>
> ```python predict.py theme={"system"}
> import os
> import httpx
>
> with httpx.Client(
>     base_url=f"https://model-{os.environ['BASETEN_MODEL_ID']}.api.baseten.co",
>     headers={"Authorization": f"Bearer {os.environ['BASETEN_API_KEY']}"},
>     timeout=60,
> ) as client:
>     for prompt in ["Hello, world!", "Hello again!"]:
>         response = client.post("/environments/production/predict", json={"prompt": prompt})
>         response.raise_for_status()
>         print(response.json())
> ```
>
> ```text Output theme={"system"}
> {'prompt': 'Hello, world!'}
> {'prompt': 'Hello again!'}
> ```

> [tab] Anti-pattern
>
> Creating a new client session for each request opens a fresh TCP connection every time. Avoid this pattern:
>
> ```python predict.py theme={"system"}
> import os
> import httpx
>
> # Anti-pattern: new client per request
> def predict(payload):
>     response = httpx.post(
>         f"https://model-{os.environ['BASETEN_MODEL_ID']}.api.baseten.co/environments/production/predict",
>         json=payload,
>         headers={"Authorization": f"Bearer {os.environ['BASETEN_API_KEY']}"},
>     )  # New connection every time
>     return response.json()
> ```

## Choose an HTTP client

Your choice of HTTP client library determines which connection management
features are available to you. The [httpx](https://www.python-httpx.org/)
library is recommended over
[requests](https://requests.readthedocs.io/en/latest/) for Baseten workloads
because it provides built-in connection pooling, native async support, and
optional HTTP/2. The `requests` library can achieve connection reuse through its
[`Session`](https://requests.readthedocs.io/en/latest/user/advanced/#session-objects) object, but lacks async support and requires more manual
configuration.

The OpenAI Python SDK manages a client connection pool. Reuse the SDK client across requests and close it when your application shuts down.

**To configure a shared HTTP client**:

Set `BASETEN_MODEL_ID` and `BASETEN_API_KEY`, then configure [`httpx.Client`](https://www.python-httpx.org/api/#client). Close the client when your application shuts down:

```python client.py theme={"system"}
import os
import httpx

client = httpx.Client(
    base_url=f"https://model-{os.environ['BASETEN_MODEL_ID']}.api.baseten.co",
    headers={"Authorization": f"Bearer {os.environ['BASETEN_API_KEY']}"},
)
```

## Configure connection pooling

Connection pooling keeps a set of open TCP connections ready for reuse. When
your client sends a request, it draws from this pool instead of opening a new
connection. This reduces repeated TCP handshakes and TLS negotiations. Measure connection setup latency in your network before choosing pool settings.

By default, httpx allows 100 total connections and retains up to 20 idle keep-alive connections across its pool. The idle limit is not a per-host concurrency limit. A workload with more in-flight requests than available connections can exhaust the pool. When the pool is full, new
requests block until a connection becomes available, resulting in [`PoolTimeout`](https://www.python-httpx.org/exceptions/#pooltimeout)
errors or increased latency.

Increase the pool limits based on your peak concurrency using [`httpx.Limits`](https://www.python-httpx.org/advanced/resource-limits/). The
`max_keepalive_connections` setting controls how many idle connections stay
open, and `keepalive_expiry` controls how long idle connections persist before
closing. Choose an idle expiry for your workload and network, including any proxy or load balancer. Configure the limits when you create the client:

```python client.py theme={"system"}
import os
import httpx

limits = httpx.Limits(
    max_connections=256,
    max_keepalive_connections=128,
    keepalive_expiry=30,
)

client = httpx.Client(
    base_url=f"https://model-{os.environ['BASETEN_MODEL_ID']}.api.baseten.co",
    headers={"Authorization": f"Bearer {os.environ['BASETEN_API_KEY']}"},
    limits=limits,
)
```

### Recommended values

| Setting | Default (httpx) | Recommended |
| - | - | - |
| Max connections | 100 | 256 |
| Max keepalive connections | 20 | 128 |
| Keep-alive idle timeout | 5s | 30s |
| Keep-alives | Enabled | Enabled |

> [!NOTE]
>
> These values apply when calling a single Baseten model endpoint.
> If you call multiple models, increase max connections proportionally.

Keep-alives are always enabled on Baseten.

## Configure HTTP/2 streams

Baseten allows up to 100 concurrent streams on each HTTP/2 connection. For high-throughput workloads, configure your client to:

* **Use several connections.** Send each request on the busiest connection that has fewer than 100 active streams, and open a new connection when every connection is full.
* **Raise the receive windows.** HTTP/2 starts each stream with a 64 KiB flow-control window. Set the initial stream and connection windows to 1 MB, or 2 MB for long streaming responses, so the server doesn't pause for `WINDOW_UPDATE` frames.

Baseten can close a connection with a `GOAWAY` frame after 999 requests. Use a client that finishes in-flight requests and opens a new connection when it receives `GOAWAY`; otherwise, requests can fail with `REFUSED_STREAM`.

To use HTTP/2 with the [Performance Client](https://docs.baseten.co/reference/sdk/performance-client/overview.md), set `http_version=2`.

## Set timeouts

By default, httpx raises a timeout after 5 seconds of network inactivity. Many
inference requests need more time before the first response data arrives.
Without a longer read timeout, your client can close the connection before the
model finishes processing.

Set client timeouts based on your latency budget. Baseten applies
separate server-side timeouts before and after routing. A synchronous request
can wait for a replica for up to the 1200-second default parking timeout. After
Baseten forwards the request to a replica, a separate 1200-second default
predict timeout begins. A request that waits for capacity can therefore remain
open for longer than 1200 seconds. For details, see [Request lifecycle](https://docs.baseten.co/deployment/autoscaling/request-lifecycle.md#timeouts).

For a warm deployment, budget enough read time for the expected inference time
and a buffer. If the deployment can scale to zero or wait for capacity, also
include the expected wait and cold start time. To avoid scale-from-zero latency,
keep the deployment's minimum replicas greater than zero.

httpx lets you configure four separate timeout values with [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/). Separating connect and
read timeouts prevents slow network conditions from being confused with slow
model responses. Configure the timeouts when you create the client:

```python client.py theme={"system"}
import os
import httpx

# Replace these examples with observed values for your workload.
expected_wait_seconds = 180.0
expected_inference_seconds = 120.0
buffer_seconds = 30.0

timeout = httpx.Timeout(
    connect=10.0,  # Time to establish connection
    # Time to wait for capacity, inference, and response data for this workload
    read=expected_wait_seconds + expected_inference_seconds + buffer_seconds,
    write=30.0,  # Time to send request body
    pool=10.0,  # Time to acquire a connection from the pool
)

client = httpx.Client(
    base_url=f"https://model-{os.environ['BASETEN_MODEL_ID']}.api.baseten.co",
    headers={"Authorization": f"Bearer {os.environ['BASETEN_API_KEY']}"},
    timeout=timeout,
)
```

### Timeout guidance by use case

| Use case | Connect | Read |
| :- | :- | :- |
| Warm synchronous request | 10 seconds | Expected inference time plus a buffer |
| Synchronous request that can wait for capacity | 10 seconds | Expected wait and cold start time, plus inference time and a buffer |
| Async predict submission | 10 seconds | 30 seconds |
| Streaming | 10 seconds | Longest expected wait before headers or between response chunks, plus a buffer |

The `read` timeout limits how long httpx waits for incoming data. For a
non-streaming request, it must cover the wait before the response arrives. For
a streaming request, it applies while waiting for the response headers and
between response chunks. The default server-side parking and predict phases
can total 2400 seconds, but your client timeout should reflect how long your
client can wait.

For long-running requests that exceed sync timeouts, use [async inference](https://docs.baseten.co/inference/async.md)
with a webhook to receive the output. If needed, poll the status endpoint to
monitor the request lifecycle; it doesn't return model output.

## Implement retries

Retry transient failures with exponential backoff and jitter. If the response includes `Retry-After`, wait at least that long before retrying. Use a library such as [tenacity](https://tenacity.readthedocs.io/en/stable/) to limit retry attempts.

Set an overall deadline for the operation, including requests and backoff delays. Account for your SDK's automatic retries when adding application retries so nested retry loops don't multiply attempts.

For Model APIs, handle retryable errors in your client even when the routing layer retries internally. Don't depend on a fixed number of internal attempts. For failures after a streaming response starts, follow [Streaming responses](https://docs.baseten.co/inference/errors.md#streaming-responses).

Retry the following errors when the cause is transient. Repeated application errors or timeouts need investigation rather than more retries:

* **429** (rate limited)
* **500** (internal server error)
* **502** (bad gateway)
* **503** (service unavailable)
* **504** (gateway timeout)
* **529** (overloaded)
* Connection errors ([`ConnectError`](https://www.python-httpx.org/exceptions/), `ReadTimeout`)

Don't retry on these status codes:

* **400** (bad request)
* **401** (unauthorized)
* **403** (forbidden)
* **404** (not found)
* **422** (validation error)

**To retry a transient inference failure**:

Install `httpx` and `tenacity` with `pip install httpx tenacity`, then run the following script. It limits a non-streaming request to five attempts with exponential backoff and jitter. It doesn't implement an overall deadline or handle `Retry-After`; add those to match your application's retry budget:

```python retry_predict.py theme={"system"}
import os
import httpx
from tenacity import retry, stop_after_attempt, wait_random_exponential, retry_if_exception


def is_retryable(exception):
    if isinstance(exception, httpx.HTTPStatusError):
        return exception.response.status_code in (429, 500, 502, 503, 504, 529)
    return isinstance(exception, (httpx.ConnectError, httpx.ReadTimeout))


@retry(
    retry=retry_if_exception(is_retryable),
    wait=wait_random_exponential(multiplier=1, min=1, max=30),
    stop=stop_after_attempt(5),
)
def predict(client, payload):
    response = client.post("/environments/production/predict", json=payload)
    response.raise_for_status()
    return response.json()

with httpx.Client(
    base_url=f"https://model-{os.environ['BASETEN_MODEL_ID']}.api.baseten.co",
    headers={"Authorization": f"Bearer {os.environ['BASETEN_API_KEY']}"},
    timeout=60,
) as client:
    print(predict(client, {"prompt": "Hello, world!"}))
```

```text Output theme={"system"}
{'prompt': 'Hello, world!'}
```

## Handle errors

Use the exception type and request logs to identify which phase failed. A pool timeout points to local connection contention; a refused connection can originate at the destination, a proxy, or the network path.

| Error | What to investigate | Next action |
| - | - | - |
| `PoolTimeout` | Requests waiting for a free client connection. | Bound concurrency, release responses, and compare pool limits with active requests. |
| `ConnectTimeout` | DNS, network reachability, proxy behavior, or an unavailable destination. | Check connectivity and deployment status before retrying. |
| `ReadTimeout` | Waiting for capacity, model execution, or a stalled response. | Compare client timing with deployment logs and your read timeout. |
| `Connection refused` | Destination availability, proxy or firewall behavior, and local or NAT port usage. | Check the target endpoint and network path; inspect port usage if the error correlates with load. |

## Monitor connections

Connection problems tend to surface as intermittent failures rather than
complete outages, making them difficult to diagnose without proper monitoring. A
gradually exhausting connection pool won't cause errors until it's completely
full, at which point requests start failing unpredictably.

Watch for these signals:

* **Rising p99 latency** without changes to model performance, which can indicate pool contention; compare with model and network latency.
* **Sporadic `Connection refused` errors** under load, which warrant checking destination availability and client or NAT port usage.
* **TCP retransmits** increasing over time, which suggest connections are being dropped and recreated.

> [!WARNING]
>
> If you route traffic through a NAT gateway, monitor port utilization.
> Each outbound connection consumes a port, and high-concurrency workloads can exhaust the available port range, causing intermittent connection failures that are difficult to distinguish from server-side issues.

## Use with proxies

Enterprise deployments often route traffic through HTTP proxies for security, logging, or network policy enforcement. httpx supports proxy configuration at the client level, so connection pooling and keep-alives continue to work through the proxy.

You may need to increase your pool limits when using a proxy, since the additional network hop increases per-request latency, which means connections are held open longer and the pool drains faster under the same concurrency. Pass the proxy URL when you create the client:

```python client.py theme={"system"}
import os
import httpx

client = httpx.Client(
    base_url=f"https://model-{os.environ['BASETEN_MODEL_ID']}.api.baseten.co",
    headers={"Authorization": f"Bearer {os.environ['BASETEN_API_KEY']}"},
    proxy="http://corporate-proxy.example.com:8080",
    limits=httpx.Limits(max_connections=300),
)
```

## Further reading

* [Performance Client](https://docs.baseten.co/reference/sdk/performance-client/overview.md): Handles connection pooling, retries, and concurrency automatically.
* [Async inference](https://docs.baseten.co/inference/async.md): For long-running requests that exceed sync timeout limits.
* [Streaming](https://docs.baseten.co/inference/streaming.md): For streaming model responses.
