Software Engineering
An AI agent that writes to the database: the confirm click can't go through the model
How I let an LLM agent write to a production database without a framework: previews, REST confirmation outside the model loop, a stale-preview guard, and undo with conflict checks.
Rodrigo Lucas · · 13 min read
Series: AI agent in productionpart 1 of 5
- 01An AI agent that writes to the database: the confirm click can't go through the model
- 02Rules belong in code, not in the prompt: when a better prompt makes the agent worse
- 03Your agent eval moves more than your improvement
- 04Reasoning used up the output limit and the answer came back empty
- 05Prompt caching in practice: the obvious cut that would have saved 4%
Over the past months I built and operated, in a B2B SaaS in production, an LLM agent that creates, updates, and deletes subscription records, without an agent framework. The obvious worry is what happens if the model hallucinates an ID and deletes the wrong account. The answer I found isn't in the prompt or in the tool schema. The model can propose any change, but the click that approves the change arrives through a REST endpoint the model has no way to call.
Today the agent has dozens of write tools (preview_update_subscription, preview_create_coupon, preview_delete_account...) and the whole design fits in three pieces: a mutation base class, a dispatcher that executes the approved mutation, and an agent actions table. None of it depends on a language or framework.
Why the tool can't execute directly#
The naive design gives the LLM an update_subscription(id, seats) tool that writes immediately. That goes wrong in three ways. The model confuses account 100 with 110 and the user only finds out later. The request "add 3 seats" becomes seats: 3. And if the defense is asking the model to say "are you sure?" before calling the tool, the confirmation becomes theater, because the model can skip the question and the user's "yes" comes back through the same probabilistic channel that caused the error.
That is what guided the rest of the design. The user decides, and that decision has to travel through a channel the LLM doesn't control.
The tool only returns a preview#
Every write tool inherits from a Mutation base class and implements three hooks (in pseudocode):
class Mutation extends Tool {
kind() // update | action | create | delete
category() // subscription, coupon, account...
buildDiff(user, input) // what will change
renderSummary(diff) // how to show it to the human
apply(user, input, action) // the mutation itself, called only after confirm
}
When the LLM calls preview_update_subscription, the base call doesn't touch the record. It builds the diff ([{ field: "seats", before: 12, after: 15 }]), writes a row to agent_actions with status: "previewed", the normalized input, the user, and the tool name, and returns to the runtime a special content part, action_preview, which the frontend draws as a confirmation card.
The card changes with the kind. For an update, it shows before and after, field by field. For a create, it shows the list of new fields, since there is no "before". For a delete, it shows what goes along in the cascade ("14 invoices and 8 users will be affected") and, for high-impact deletes, asks for a GitHub-style confirmation token, where the Confirm button only enables after the user types the account identifier.
The hallucinated ID stops here, because buildDiff can't find the record, the base returns an ordinary tool error, and the model tries again with corrected input, so a broken preview never becomes a card.
The click goes through REST, outside the model loop#
This is the most important decision in the design. The click on "Confirm" doesn't go back to the chat and hits a dedicated endpoint:
POST /api/v1/conversations/:cid/actions/:id/confirm
Body: { idempotency_key: <uuid> }
That endpoint is an ordinary HTTP handler, with the authentication and authorization of any route in the app, and the model has no way to invoke it. A misbehaving LLM can build an absurd preview, but it can't approve anything the user didn't click, and the architecture is what guarantees that.
The endpoint moves the action from previewed to confirmed and calls the dispatcher. The whole dispatch runs in a transaction, under a row lock (SELECT ... FOR UPDATE followed by a reload), so a second request arriving for the same action waits in line and, when it gets in, rereads the already updated state:
# ActionDispatcher (essence)
def dispatch():
action.withLock { lockedDispatch() }
return action
def lockedDispatch():
if action.status in [executed, failed, cancelled]: return # replay becomes a no-op
record = tool.findRecordForRollback(user: action.user, input: action.input)
rollbackPayload = tool.captureRollbackPayload(record, action.input)
detectStalePreview(record)
result = tool.apply(user: action.user, input: action.input, action: action)
action.update(status: "executed", executed_at: now(),
output: { result: result, rollback: rollbackPayload })
The frontend generates an idempotency_key for each attempt to confirm. The same key arriving again, from a network retry or a double-click, returns the previous result with 200, and a different key on an already finished action returns 409 "this preview is no longer open". The key covers sequential retries and the lock covers the concurrent case, where two tabs confirming together get in one at a time and the second becomes a no-op or a 409. Confirm, cancel, and undo use the same scheme.
Authorization is the same as in the rest of the app, with the usual policies and per-user scoping. Trying to confirm someone else's action returns 404, not 403, so the response doesn't reveal that the action exists.
A stale preview doesn't execute#
The user approves a diff and a cascade list that were computed at preview time, but apply runs at confirm time, seconds or minutes later. If a colleague changed the subscription in the meantime, what the user approved no longer holds. This is the classic TOCTOU bug, and the most dangerous case is the delete, where "14 invoices will be deleted" may have become 20 by the time of the click.
So the dispatcher checks the record again before applying:
def detectStalePreview(record):
if record is null or record.updated_at is null: return
if record.updated_at <= action.created_at: return # created_at = preview time
raise StalePreview, "record was edited after the preview was generated"
If the record changed after the preview, the action becomes failed, the endpoint returns 409 stale_preview, and the user asks the agent for a new preview. It's three lines, and they close the window between what the user saw and what will run.
Undo, the part almost nobody builds#
Preview and confirmation catch the error before it happens, but people confirm the wrong thing, because they read the diff too fast or because it was another field. So every executed card gets an "Undo" button, valid for a period that depends on the operation type (days for updates and creates, weeks for deletes).
What makes undo possible happens in the dispatch. Before apply, inside the same transaction, the dispatcher writes a rollback_payload into the action's own output. Create is the exception, because the record id only exists after apply, so it is captured right after, still inside the transaction. The format changes with the kind:
| kind | Snapshot | Rollback |
|---|---|---|
| update / action | record attributes before + model name, explicit | restore attributes + save |
| create | id of the created record (captured after apply) + model | soft delete or destroy the new record |
| delete (model with soft delete) | id of the discarded record + model | restore the flag, dependents never left |
| delete (leaf model, hard delete) | full attributes + dependents | recreate from the snapshot |
The model name is stored in the payload, so undo never guesses anything from naming conventions. When a create returns something without a recognizable id, the capture logs a warning, leaves the payload empty, and marks the action as non-reversible, and the Undo button doesn't show up, instead of faking an undo that does nothing.
For deletes, I adopted soft delete on the central entities that group many dependents, like the account. Instead of disappearing from the database, the record gets a discarded flag and drops out of every query. Undoing "delete account 100" means restoring that flag, and the account comes back with its invoices, users, and history. Two cron jobs close the loop: one does the permanent purge when the delete window expires, and the other deletes the rollback_payload of expired actions, keeping the audit metadata.
When someone edited after the confirm#
The tricky scenario is this: the agent changes the seats to 15, the user confirms and, ten minutes later, a colleague sets it to 20 through the app's normal screen. If Undo restores the snapshot blindly, it wipes out the colleague's work, and that silent bug is worse than the original error.
The fix was optimistic detection, with no new column:
# dispatcher.detectConflict (essence)
if record.updated_at > action.executed_at:
raise ConflictDetected,
"record was edited (manually or by another action) after this action ran"
If the record's updated_at is newer than the action's executed_at, the rollback is blocked with 409 and the card shows a notice explaining why. I'd rather block than guess at a merge. It's the same idea as the stale-preview guard applied at the other end, comparing timestamps before applying and again before restoring.
How long the undo window should be#
The first version used 30 days for everything, a round number picked by guesswork. Later it became clear that the right window depends on how long each kind of error takes to be discovered. With many users editing, an update undo requested days later tends to hit the 409 anyway, and the long window only adds cost (payload kept, personal data exposed for longer).
In updates and creates, the error usually shows up right away, in the card itself, or within the same workday, and 7 days is a generous ceiling. In deletes, discovery is slow, because nobody notices an absence, and "where is account X?" can take weeks. There 30 days make sense and are cheap, since undo means restoring a flag and a discarded record doesn't receive edits that would create a conflict.
If the domain has a period that closes (an invoice already issued, for example), that closing should be a hard limit for undo, regardless of the window.
Since every action is a row in the table, the window can come from data instead of a guess, by looking at the distribution of rolled_back_at - executed_at across real undos and the 409 rate by action age. That is the decision criterion, not a measurement I already have: if the p99 of undos lands at 48 hours, for example, 7 days is plenty and the discussion is over.
Undo is recorded too#
Every undo creates a new agent_action(tool_name: "rollback", status: "executed") row pointing to the original, which gets rolled_back_at and rolled_back_by_action_id, and the table can then answer who changed, who confirmed, and who undid. The rollback uses the same key (a different key returns 409 already_rolled_back) and the same row lock, so two simultaneous undos don't revert twice. And undo doesn't call the LLM, it's plain REST, with the latency of an UPDATE.
When a field is missing, the agent asks#
The base class ended up solving another problem. When the user asks "create a discount coupon" without saying for which account, the model tends to guess an account_id. The base intercepts first:
if (missing = detectMissingField(input)):
prompt = missingFieldPrompts[missing] || defaultPrompt(missing)
return missingFieldResponse(missing, prompt)
The tool returns { missing_field: "account_id", prompt: "Which account is this coupon for?" } and the system prompt tells the model to just relay the question and call again with the accumulated input. The state of the collection lives in the conversation history, with no state machine.
What frameworks already do, and what's left out#
Human approval already comes built into the frameworks. LangGraph pauses the graph with interrupt, stores the state in a checkpointer, and lets the human edit the arguments, the OpenAI Agents SDK uses needs_approval and returns the serialized state, Cloudflare suspends a durable workflow for weeks if needed, and HumanLayer adds a decorator that won't let the function run without approval. In my case, the "paused state" is a row in agent_actions with status: previewed, which was already the audit trail, and I didn't need a checkpointer. Each tool has to know how to build its own diff, and in return the card shows "seats: 12 → 15" instead of a JSON blob. I also don't allow editing arguments on the card, so the approved diff is always the executed one.
What comes after approval, though, is left out of all of them, and for an architectural reason: what these frameworks version is the agent's state, not your data. LangGraph gets closest with time travel, but the docs warn that update_state "does not roll back a thread" and that replay re-executes the nodes, including LLM and API calls. Rewinding the graph rewinds the conversation, and the row the tool wrote to the database is still there. That makes sense, because the inverse of a write depends on business rules a generic runtime doesn't know. What has been published about the after comes from other fields, like saga and compensation (well summarized in The Data Rollback Problem), IBM's STRATUS, and Rubrik Agent Rewind. My undo is compensation with a per-record snapshot, stored in the action itself, and I didn't find the conflict check before undo in any of those references, which assume the world stood still between executing and undoing.
Building without a framework wasn't reinventing the wheel. Atomicity, locking, idempotency, and auditing stayed with the relational database (transactions, row locks, unique indexes), with the authorization framework, and with the soft delete the app already used. I only wrote the domain layer by hand, which is the preview, the diff, the snapshot, and the two timestamp guards. What I gave up was argument editing, approvals that last weeks, and a resume path already tested by a lot of people, and every rough edge a mature runtime would have smoothed out I had to find on my own.
Where the design still has holes#
Some limits I accept, others are in the queue.
- The snapshot doesn't capture effects outside the database. A sent email doesn't come back, the same limitation the saga literature points out, and a tool with external effects would need its own compensation.
- Update rollback restores the whole record, not just the fields the agent changed. Conflict detection holds the risk down, but storing only the
{field: value_before}pairs from the diff would shrink the blast radius and allow checking conflicts per field. - Detection by
updated_atis coarse. Any edit blocks the undo, even on an unrelated field. It's a safe false positive, because the user reviews, but per-field conflicts would remove those blocks. - The conflict check on undo covers updates, not creates and deletes. Restoring the flag on a delete is safe by nature, since nothing was changed, but those paths still deserve a formal review.
- Restoring while skipping validations trusts that the snapshot was valid when it was taken, which is necessary because validations may have changed.
- The undo window with payload purge is a privacy (LGPD, Brazil's data protection law) and cost choice, with permanent auditing and temporary reversibility.
- Recreating a hard delete uses the original id. Since the id came from the same sequence in the same database, there's no collision in this flow, but restoring a snapshot across databases (from a dump into another environment) would require handling the sequence.
The next step I care most about is per-field rollback, because it solves items two and three at once. What I don't know yet is whether the 7-day window for updates is too wide or too tight, and that answer comes from the distribution of real undos, which is the next query I'll run on the actions table.
References#
- LangChain/LangGraph: Human-in-the-loop
- LangGraph: Use time-travel
- OpenAI Agents SDK: Human-in-the-loop
- Cloudflare Agents: Human in the Loop
- HumanLayer: require_approval and 12-Factor Agents
- The Data Rollback Problem: Undoing What Your AI Agent Wrote to Production
- IBM Research: An 'undo-and-retry' mechanism for agents (STRATUS)
- Rubrik Agent Rewind
- CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition
updated on
01 blog
related
software engineering
A perfect Lighthouse SEO score does not prove SEO, the HTML your site serves does
Lighthouse gave my site an SEO score of 100 while the canonical pointed to a domain that returned 404. What the audit checks, what it cannot check and a 40-line checker that catches the defect.
software engineering
42 green checks and no citations: the index decides what AI cites
A site passed every SEO check and did not show up in any search engine. Blocking the training bot does not take anyone out of ChatGPT, but staying out of the index does.
software engineering
Tests that pass without protecting anything: watch the test fail before you trust it
A green CI that ran no tests, a spec that never saw the template, and another that breaks between midnight and 1 a.m. I only trust a test after seeing it fail for the right reason.
02 blog
Who writes
Contact
Let's swap ideas
Get the next articles
No spam, one email when a new article ships. Unsubscribe anytime.