Why our Python async agent worker leaked 2GB of RAM a day until we capped tool response sizes
For two weeks we chased what looked like a classic Python memory leak. Our asyncio agent worker pods would start at 220MB RSS, climb steadily all afternoon, and get OOM-killed overnight.
We checked tracemalloc, hunted for circular references in Pydantic models, and restarted Redis clients—nothing stood out.
Then we finally logged the byte size of every tool message appended to messages[]. Once every few hours, an agent would run a broad search_logs or fetch_url call that returned a 38MB unpaginated JSON dump. That single string got copied into messages[], serialized for checkpointing, and kept alive in glibc arenas long after the request finished.
Put a hard byte cap at the tool boundary
Never trust an upstream API or CLI command to stay small. Enforce a strict MAX_TOOL_BYTES ceiling in one central wrapper before the payload ever enters your agent loop:
pythonMAX_TOOL_BYTES = 48_000 def truncate_tool_output(raw: str, source: str) -> str: encoded = raw.encode("utf-8", errors="ignore") if len(encoded) <= MAX_TOOL_BYTES: return raw clipped = encoded[:MAX_TOOL_BYTES].decode("utf-8", errors="ignore") return f"{clipped}\n\n[Truncated {len(encoded) - MAX_TOOL_BYTES} bytes from {source}. Narrow your query or paginate.]"
Our pod RSS flattened out at ~260MB immediately, and as a bonus, agents stopped burning 100k tokens trying to read giant log dumps.