Problem — Claude API Calls Time Out in Unity During NPC Dialogue
You are building AI-driven NPC dialogue in Unity using the Claude API.
Requests work sometimes, but under load or on some networks you see:
- Requests taking 30+ seconds and then failing.
- Errors like
Request timed out,TaskCanceledException, or generic network timeouts. - Editor play mode works occasionally, but builds time out more often.
This article walks you through:
- Checking network and environment.
- Fixing HTTP client and timeout settings in Unity.
- Adding retry logic and backoff.
- Implementing safe fallbacks so your game does not freeze when Claude is slow.
By the end, your AI dialogue should fail gracefully instead of hanging or crashing.
Step 1 – Confirm the Problem Is Really a Timeout
Before changing code, verify that you are dealing with timeouts, not:
- Authentication errors (
401,403). - Rate limiting (
429). - Server-side errors (
5xx).
Check:
-
Unity Console / Logs
- Look for messages like:
TaskCanceledException: The operation was canceled.Request timed out after 30.00sCurl error 28: Operation timed out
- Look for messages like:
-
Response Status Codes
- If your code logs status codes, note:
0or “no response” → often a network/timeout problem.408 Request Timeoutor similar → explicit timeout.
- If your code logs status codes, note:
-
Compare Editor vs Build
- If it works in editor but fails in build:
- The build may run on a different network (firewall, proxy, mobile connection).
- Mobile or console platforms are often more sensitive to timeouts.
- If it works in editor but fails in build:
If you mostly see no response / operation canceled / curl timeout, continue with the steps below.
Step 2 – Test Network and Environment Outside Unity
Before blaming your code, test the Claude endpoint outside of Unity:
-
From the same machine, use:
curlor a REST client (Insomnia, Postman).- The same API key and same endpoint you use in Unity.
-
Send:
- A small, simple request (short prompt, low tokens).
- A couple of requests in a row.
-
Observe:
- If requests are also slow or time out here:
- You may have network issues (firewall, VPN, corporate proxy, unstable Wi‑Fi).
- If requests are fast outside Unity but slow inside:
- Focus on Unity’s HTTP client configuration (next steps).
- If requests are also slow or time out here:
If possible, temporarily:
- Disable VPNs, proxies, or aggressive firewalls.
- Switch to a different network (mobile hotspot vs office Wi‑Fi).
You want a baseline where Claude responds normally before tuning Unity code.
Step 3 – Fix Unity HTTP Client and Timeout Settings
The most common cause of timeouts inside Unity is misconfigured HTTP client code:
- Very low timeout values.
- Creating and disposing
HttpClientrepeatedly. - Using UnityWebRequest with defaults that do not suit long responses.
3.1 Use a Reusable HTTP Client (C#)
If you are using HttpClient:
- Create one static/shared instance.
- Configure a reasonable timeout (for example, 30–60 seconds).
Example:
public static class ClaudeClient
{
private static readonly HttpClient httpClient;
static ClaudeClient()
{
httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(45) // adjust as needed
};
httpClient.DefaultRequestHeaders.Add("x-api-key", "<YOUR_CLAUDE_API_KEY>");
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
}
public static async Task<string> SendClaudeRequestAsync(string jsonBody, CancellationToken token)
{
using var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
using var response = await httpClient.PostAsync("<CLAUDE_ENDPOINT_URL>", content, token);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
Key points:
- Do not create
new HttpClient()every request. - Set a timeout appropriate for your use case:
- Chat responses usually complete within 5–20 seconds.
- Leave headroom but avoid unlimited waits.
3.2 If Using UnityWebRequest
When using UnityWebRequest:
- On mobile and WebGL, network conditions can be worse.
- Some platforms have no explicit timeout setting, so you simulate it.
Pattern:
- Start the request with a coroutine.
- Track elapsed time yourself.
- If it exceeds your threshold, abort and treat it as timeout.
Step 4 – Add Retry Logic with Backoff (Without Spamming)
If timeouts are occasional, a simple retry strategy often fixes the user experience:
- Try once.
- On timeout, wait a short delay.
- Retry 1–2 times with increasing delay.
Guidelines:
- Maximum 2–3 attempts total.
- Use exponential backoff: 1s → 2s → 4s, etc.
- Respect API rate limits and terms of use.
Conceptual flow:
for attempt in 1..3:
try:
send request
if success:
break
catch timeout:
wait (2^(attempt-1)) seconds
continue
if still failed:
show fallback dialogue
This way, short hiccups do not immediately surface as failures, but persistent issues still resolve quickly for the player with a clear message.
Step 5 – Decouple NPC Dialogue from the Main Game Loop
A dangerous pattern is:
- Triggering a Claude request inside Update or deep in gameplay logic.
- Waiting synchronously or blocking gameplay until the response arrives.
Instead:
-
Fire-and-forget pattern
- Start an async task or coroutine to call Claude.
- Immediately show “thinking” or pre-written lines.
- Update the NPC dialogue when the result is ready.
-
Timeout-aware state
- Keep a timer per request.
- If it goes beyond your threshold, transition to a fallback state:
- Pre-written response.
- “I am having trouble reaching the archives right now, let us talk about something else.”
-
Avoid blocking UI
- Do not freeze the entire dialogue UI while waiting.
- Allow players to exit or skip if something goes wrong.
This ensures that even when Claude or the network is slow, your game remains responsive.
Step 6 – Use Smaller, More Focused Prompts
Very large prompts or responses can:
- Increase network transfer time.
- Take longer to process on the server.
- Raise the risk of hitting timeouts.
To reduce this risk:
-
Summarize history
- Instead of sending the entire dialogue history, send:
- A summary of recent events.
- A smaller set of the most relevant turns.
- Instead of sending the entire dialogue history, send:
-
Limit max tokens
- Set reasonable max output tokens when calling Claude.
- For short NPC lines, you rarely need huge outputs.
-
Trim metadata
- Remove unnecessary debug information from your prompts.
Smaller requests return faster and are less likely to time out.
Step 7 – Handle Timeouts Gracefully in the Player Experience
Even with good configuration, some timeouts will still happen.
Design the experience so they feel like a small hiccup, not a broken game.
Ideas:
- Show a short message when a timeout occurs:
- “The oracle is quiet for a moment. Try asking again.”
- “The network is unstable right now. I will answer briefly.”
- Use a fallback line:
- Pre-written responses that still fit the character.
- Log the event internally:
- Include timestamp, level, NPC, prompt type.
Make sure:
- The player can continue playing without restarting.
- Repeated timeouts do not trap them in a dialogue loop.
Step 8 – Verify the Fix
After adjusting your client and code, run this checklist:
- [ ] Claude requests complete within your timeout window under normal conditions.
- [ ] Editor and build behave similarly (test Windows, macOS, or target platform).
- [ ] NPC dialogue:
- [ ] Does not freeze gameplay while waiting.
- [ ] Shows a clear fallback line when a timeout occurs.
- [ ] Logs contain:
- [ ] Status codes and error messages for failed calls.
- [ ] Enough context (NPC name, scene, prompt type) to debug issues.
If everything passes, you can move on to refining prompt quality and character behavior instead of firefighting timeouts.
Prevention Tips and Best Practices
- Keep one reused HTTP client with a sensible timeout.
- Implement retry with backoff but cap attempts.
- Treat all network calls as potentially unreliable:
- Design your dialogue system to degrade gracefully.
- Keep prompts and responses compact when possible.
- Monitor logs or analytics to spot:
- Spikes in timeout rates.
- Specific scenes or NPCs causing problems.
Bookmark this article so you can quickly revisit the checklist the next time Claude API calls start timing out in Unity.
If you are still stuck, pair this guide with your engine’s networking documentation and Claude’s latest API guidance.