[BUG] API Error: Connection closed mid-response — occurs immediately in new context window
Preflight Checklist
- [x] I have searched existing issues and this hasn't been reported yet
- [x] This is a single bug report (please file separate reports for different bugs)
- [x] I am using the latest version of Claude Code
What's Wrong?
During active conversations, Claude Code enters a "thinking" phase (tokens are visibly consumed), but instead of returning a response, the following error appears:
API Error: Connection closed mid-response. The response above may be incomplete.
The error occurs randomly — sometimes after a few seconds of thinking, sometimes after longer processing. No response is returned. The issue appears more frequently in long sessions with many tool calls and after cont
What Should Happen?
Claude should complete processing and return a full response. If the connection is
interrupted, it should recover gracefully or at minimum display a retry option —
not silently drop the response after consuming tokens.
Error Messages/Logs
API Error: Connection closed mid-response. The response above may be incomplete.
Observed behavior:
- Thinking indicator is visible (tokens being consumed)
- Response begins generating (sometimes 1-2 sentences appear)
- Connection drops mid-response with the above error
- No partial output is recoverable
- Happens randomly — not tied to response length
Steps to Reproduce
- Start Claude Code session (web chat via Agent SDK, self-hosted)
- Run a multi-step task involving multiple tool calls (file edits, bash commands, git operations)
- Allow the session to grow — especially after context summarization triggers
- Ask Claude to perform any task
- Observe thinking phase begins (tokens consumed)
- Error appears: "API Error: Connection closed mid-response"
Reproducibility: random, but significantly more frequent after context summarization.
Not reproducible on demand, but occurs multiple times per long session.
Claude Model
Sonnet (default)
Is this a regression?
Yes, this worked in a previous version
Last Working Version
no response
Claude Code Version
2.1.173
Platform
Anthropic API
Operating System
Ubuntu/Debian Linux
Terminal/Shell
VS Code integrated terminal
Additional Information
- Self-hosted Claude Code Agent SDK on Debian 13 (trixie), x86_64
- Claude Code version: 2.1.173
- Accessed via custom web chat over WebSocket (uvicorn/FastAPI)
- Error occurs both mid-generation and immediately at start of new context window
after summarization
- Workaround: starting a completely new conversation avoids the issue temporarily
- Tokens appear to be consumed during the failed thinking phase (no refund observed)
- No network instability on the host — other services unaffected
21 Comments
Found 3 possible duplicate issues:
This issue will be automatically closed as a duplicate in 3 days.
🤖 Generated with Claude Code
Same here
Same here
any fixes yet? it is getting more frequent
I am now having this issue on almost every message I send, even if it is the first one in a thread. I do not believe it is an issue with my own internet connection.
I recently started getting this error when I configured claude to use a gateway (litellm). It appears that the reverse proxy for my litellm docker has a timeout (60 seconds) and the responses through the gateway routinely take much longer than that. Anything over 60s gives me the API error. If I swap back to a bedrock inference profile or an Anthropic subscription the errors go away. I am not sure if the timeout is related and I haven't had a chance to change the ALB settings, but maybe it will help others debug the issue.
We are also using Litellm and some of our users are facing this issue. Is everyone here who is encountering this issue also using Litellm or does this issue also occur with other providers as well?
Same here, in my case i use claude code with litellm and this seems to be happening whenever claude code need to write down a big file, like a tech plan in one operation. Whenever it occurs in consistently happens to me, i have to instruct claude to write down the file in parts and then join it. its the only way i find to bypass the issue
Same here, and it happened more and more frequently. Windows. VS Code terminal / extension. v2.1.216-218.
Same here. Claude code is broken for me for days now.
Same here. v2.1.220
Constantly get this and it wastes so many tokens.
What is going on with this service? Doesn't matter if it is desktop or CLI
<img width="800" height="2804" alt="Image" src="https://github.com/user-attachments/assets/15e01a9d-5726-4499-9364-3f42269f6334" />
this issue is resolved? I'm getting stuck on using claude here
I resolved this issue by downgrading the Claude version to 2.1.220. So it's working now.
I originally wrote this as a comment on https://github.com/anthropics/claude-code/issues/69415 which was closed as a dupe. Repeating it here in case it is valuable for people:
I am also plagued by those frequent API connection errors (and was also able to trace it down to what looks like a NAT timeout, but it looks like it is on the Anthropic side, not on my side - and only for the Claude Code data connections, not for the remote control connections).
Eventually I added this to my
CLAUDE.md, which is a workaround that seems to work:This is obviously not an ideal solution (it isn't even a solution, it is just a workaround), but at least it keeps the agents alive despite them running into those API errors many times per hour.
I get this issue when I am using Gateway APIs hosted in AWS Bedrock. So, not through Anthropic. Increasing the timeout in my gateway helped to drastically reduce the problem, but I still see it occasionally. More recently the Claude Code agents seem to self recover from it somehow. I get the "Trying again in xxx seconds", but it usually recovers before the countdown.
Same error here. The failed turn is not the real cost. The session then sits waiting for a human.
Nothing in Claude Code recovers it. The loop returns
{reason: "api_error", isTransient: true}and does that before it reaches the Stop hook runner, soStopnever fires.PostToolUsedoes not fire because no tool failed.So the loop computes
isTransientand then discards it.I worked around it with a hook declared
asyncplusasyncRewake. Exiting 2 from such a hook wakes the model with the process stderr as the body, which is enough to rebuild the recovery outside the loop. A watcher polls the transcript and when the last entry is a transient stream failure that has sat for 25 seconds it asks the model to pick up where it stopped. Code at https://github.com/nnemirovsky/cc-resume-watchdog. It has fired on real drops and recovered the turns.One case is a free retry and needs no new machinery:
Your computer went to sleep mid-response. I confirmed againstpmsetthat the client was suspended and nothing had executed, so re-issuing carries no double-execution risk.For me this one started happening two days ago, but it's incredibly consisted. It's almost impossible to use claude for some long running tasks, i've had chat which was destroyed by this error i've found no way to continue, cause every request eventially ended with this error.
I am using Claude models in Bedrock using Claude Gateway. This happens when I am using auto-mode. Some digging (with Claude came up with this little "beauty" : Your "large prompts" observation is real and the docs corroborate it indirectly: there's an explicit failure mode where the conversation outgrows the classifier's context window.
Meaning when auto-mode commands gets checked with Sonnet it is to big for context. Working fine for me now (and also using a lot less tokens). My guess is that auto-mode context caching is a complete bust, so you get taxed for un-cached sonnet tokens.
Auto-mode turned off... all working fine now.
Filed #100353 for one cause of the errors in this thread. Since 2.1.213, a single connection error (ECONNRESET, EPIPE, ETIMEDOUT, a truncated stream, …) switches HTTP keep-alive off for the rest of the process, and nothing turns it back on. Before 2.1.213 the same code sat behind a server-side flag that was off by default. After the switch flipped, every stall in our logs became a byte-level stream-idle-watchdog abort, a rejected retry and a re-send of the whole conversation, until restart. That's why it gets worse the longer a session runs, and why restarting or running a version before 2.1.213 helps.
To check whether you're hitting it, run with
--debug-file <path>and look forStale connection — disabling keep-alive for retry. The issue has the before/after numbers, how we found the version, and a local workaround.Written by Claude (Opus 5.5); I've reviewed it.
For anyone still hitting this: in my case it was not Claude Code but my ISP, even though browsing worked fine.
The tell: errors from unrelated sessions (different projects, even Claude Code 2.1.289 and 2.1.296) fell on the same second of a 5-minute cycle. My router's WAN connection was dropping for 1–2 s every 300 s (hundreds of
WAN connection ... disconnectedentries in its log). Each drop resets NAT, and a streamed reply, where only the server is sending, gets silently black-holed. Claude Code then sees silence and eventually shows "The response stopped arriving" (its idle watchdog, 180 s by default) or "Connection lost mid-response". Browsing survives because the client speaks first, so nothing else looks broken.Quick check, which prints each stream error with its second in a 5-minute cycle:
The last column is your local project folder (e.g.
-Users-alex-Projects-myapp), which includes your username, so drop it before pasting output here.If the middle column repeats across unrelated projects, check the network: your router's "internet connection time" vs its uptime, or ping the router and the first ISP hop (from
traceroute) in parallel. Loss past the router but not to it is the pattern.What fixed it for me: a fresh DHCP lease (WAN switched to static and back to DHCP) landed in a different ISP address pool, and the drops stopped. Reports here have several causes (see #100353, #97593, gateway timeouts), so this is one more worth ruling out, not the answer for everyone.