How to stop AI agents from looping on database queries
When we first put multi-step AI agents to work handling backend customer queries our biggest surprise wasn't getting wrong answers. It was loops. An agent got stuck trying to fix a syntax error in a SQL query running the failing command thirty times in two minutes.
The fix wasn't changing the way we wrote prompts. We added a limit, on how many times something could run and a way to stop everything. Now if any agent makes the mistake twice the system stops running and sends the problem to a Slack channel for a person to check.
This simple rule cut our cloud computing costs by forty percent in the month. Better it stopped users from waiting ten minutes for a request that would never finish.
If you use loops don't trust the model to know when to stop. Put limits outside the LLM part of the system.
How times do you usually let your automation scripts try before sending an alert?
Replies
The number matters less to me than what kind of failure it is. In my song pipeline a network or provider error gets up to three attempts, because the same request can succeed a minute later. A refusal from the model is never retried as is, it gets reworded exactly once and then the job fails with a reason the user can read. Repeating the same input and expecting a different answer is the loop you describe, just slower. So my rule is: retry what can change by itself, change what cannot, and cap both outside the model, the same as you. And the failure has to land somewhere a person looks, a stuck job nobody sees costs more than a failed one.