# HTTP 504 `gateway_timeout` — API Store Hub

> VI: HTTP 504 xảy ra khi chế độ non-streaming (`stream: false`) phải chờ model sinh trọn bộ câu trả lời lâu hơn ngưỡng timeout của client, Nginx hoặc CDN (thường 60–100 giây).
> EN: HTTP 504 occurs when non-streaming calls wait longer than the client, Nginx, or CDN idle timeout (often 60–100s) before receiving response bytes.

- Canonical VI: https://apistorehub.com/vi/loi-api/504-gateway-stream-timeout
- Canonical EN: https://apistorehub.com/en/loi-api/504-gateway-stream-timeout
- Retry Policy: Switch to `stream: true` before retrying and use idempotency keys on mutating workflows.

## Root Causes
- Using `stream: false` on deep reasoning models or multi-thousand-token generations.
- Application load balancer or Nginx defaulting to a 60-second `proxy_read_timeout`.
- Proxy buffering or gzip compression holding SSE bytes until the stream finishes.

## Step-by-Step Resolution
1. Enable `stream: true` on all reasoning, coding, and long-form generation requests.
2. Raise SDK read timeouts to 120–300 seconds while keeping `connect_timeout` around 10 seconds.
3. Set `proxy_buffering off; proxy_read_timeout 300s;` on intermediate Nginx proxies.
4. Break massive single-shot generations into staged smaller prompts.

## Diagnostic cURL
```bash
curl -N --max-time 180 https://apistorehub.com/v1/chat/completions \
  -H "Authorization: Bearer sk-ash-your_key" \
  -H "Content-Type: application/json" \
  -d '{"model":"claude-sonnet-5-5","stream":true,"messages":[{"role":"user","content":"Write a concise architecture checklist"}]}'
```

## Production Fix (Python)
```
import httpx, os
from openai import OpenAI

client = OpenAI(
    base_url="https://apistorehub.com/v1",
    api_key=os.environ["API_KEY"],
    timeout=httpx.Timeout(180.0, connect=10.0),
)
with client.chat.completions.stream(
    model="claude-sonnet-5-5",
    messages=[{"role": "user", "content": "Analyze this architecture."}],
) as stream:
    for event in stream:
        if event.type == "content.delta":
            print(event.delta, end="", flush=True)
```

## FAQ
- **Does `stream: true` cost extra ST credit?**: No. Pricing is identical while dramatically reducing timeout failures and improving perceived speed.
- **How does SSE streaming avoid Cloudflare's 100-second timeout?**: Cloudflare enforces an idle timeout between bytes; continuous SSE chunks keep the connection alive.
- **How is billing handled if a stream disconnects mid-way?**: Only actual generated usage is settled.
