DEV Community

Moiz OpulCloud
Moiz OpulCloud

Posted on

How I solved safe Python code execution and infinite loops for AI agents without Kubernetes (Firecracker + pgvector architecture)

Hey everyone,
While building AI agents over the last few months, I kept running into the same architectural bottleneck: letting an LLM execute untrusted Python code safely without maintaining a heavy Docker/Kubernetes cluster or risking a runaway cloud bill if an agent gets stuck in an infinite loop.
Existing setups felt overly complex or split across too many services (separate vector DBs, separate sandbox runners, custom orchestration). To solve this for my own agents, I put together a lightweight execution layer using Firecracker microVMs and Postgres, and wanted to share the architecture and trade-offs I ran into:
• MicroVM Isolation & Hard Timeouts: Instead of standard containers, each execution spins up inside an isolated Firecracker microVM. To prevent infinite loops (while True: pass) from eating compute, I enforced a hard 4-second execution cutoff at the hypervisor/runner level that kills the instance immediately.
• Unified State with Postgres (pgvector): Rather than managing a separate Pinecone or Weaviate instance alongside the execution environment, I used native pgvector inside Postgres so agents can store and retrieve session context directly next to their execution state.
• MCP & OpenAI SDK Compatibility: To avoid rewriting agent loops, I exposed the sandbox and memory layer as an MCP server (so tools like Claude Desktop and Cursor can call it natively) and mapped the inference/execution routing behind an OpenAI-compatible baseURL.
A few trade-offs and open questions I'm still working through:
• A hard 4-second timeout stops runaway loops cold, though it breaks legitimate data-processing scripts that take 5–10 seconds to run.
• Keeping memory and sandbox state tightly coupled simplifies the stack, though scaling them independently later requires careful connection pooling.
For those of you giving your agents code-execution access in production: how are you handling timeouts, sandboxing, and persistent memory right now? Would love to hear what stacks are working for you.

Top comments (0)