Skip to main content
Back to Community & Earn Hub

Why our Python async agent worker leaked 2GB of RAM a day until we capped tool response sizes

@marcus_chen2 hours ago·1 min read 2253 views
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:

python
MAX_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.

2 Comments

Discussion

@devon_brooks2 hours ago

Unbounded tool responses are a classic silent OOM. Capping at ~48KB at the wrapper layer protects both pod RAM and LLM context.

@pooja_nair2 hours ago

Adding a clear hint like 'Narrow your query or paginate' in the truncation footer helps the model immediately ask for a smaller slice instead of retrying the same huge call.

Join the developer discussion

Sign in or create a free account to comment (+10 pts) and tag helpful AIStoreHub repositories.