How an AI agent runs thousands of operations without duplicates

Per-row state in Postgres, claims with SKIP LOCKED, one idempotency key per row, heartbeats and adaptive pacing: the design that lets a batch stop anywhere and resume without applying a row twice.

Authors Qaalia Team ·


Short answer: the model should not be the loop. In Qaalia the agent declares a bulk operation once (which tool, and which file columns map to which fields) and the platform executes the rows itself. Every row is stored in Postgres with its own status, claimed with FOR UPDATE SKIP LOCKED, sent with an idempotency key that never changes between retries, and saved before the next stretch starts. The worker runs for about 110 seconds, requeues itself and continues, so a batch of up to 100,000 rows survives time limits, crashes and rate limits without sending a finished row again.

This post is the engineering deep dive: the tables, the claim query, the time budgets and the failure cases, all taken from Qaalia's source code as of November 23, 2026. For the practical side, read How to import Excel or CSV into your app through its API and AI agents for bulk operations.

Why does a normal agent loop break on bulk work?

A chat agent works in rounds: the model reads the conversation, emits tool calls, receives results and decides what to do next. That is fine for "create this customer". It fails for "enroll these 1,000 students", for four separate reasons:

  • Output tokens. The model would write 1,000 tool calls and read 1,000 results back: slow, expensive, and rows get lost long before the end.
  • Function lifetime. Qaalia runs on Supabase Edge Functions, which live at most 150 seconds on the Free plan and 400 seconds on Pro. No single request can hold a job that takes twenty minutes.
  • Ambiguous failures. If a request times out, the row may or may not have been saved. A naive retry is exactly how duplicates are made.
  • The other system's limits. Your API may accept fifteen writes per minute. A loop that ignores 429 either fails or hammers it.

The fix for the first is to let the model plan and the platform iterate. The fix for the other three is to keep the batch as durable state in a database, not in a running process.

How does the agent hand a batch to the platform?

Qaalia gives every agent with business operations an internal tool, qaalia_ejecutar_lote. Its instructions tell the model to use it whenever the same operation must run more than 10 times, and never to copy a file's data by hand. The model sends the operation name, a short description, arguments shared by every row (such as a course ID) and either up to 100 inline rows or a desde_archivo mapping: a sheet, a row range and a column map with templates like {first} {last}. For text files it sends a regular expression with named groups instead.

Before anything reaches your system, the rows are built from the attachment, converted to the types the operation declares and checked. If half or more of the rows lack a required field, the batch is refused with examples, because that pattern means the mapping is wrong, not the data. The valid batch is then registered: the first 5,000 rows go in with the batch itself and the rest in stretches of 5,000, up to 100,000 rows. Registration is idempotent too. The batch is unique per conversation and tool call, and extra stretches use ON CONFLICT DO NOTHING, so a retried turn finishes the registration instead of duplicating it.

The action that comes back to the orchestrator carries only the batch ID and totals. The conversation history never holds thousands of rows, which keeps every later model call small.

What is stored for each row?

Two tables. qaalia_lotes holds the batch: tool, description, totals, state and the current pacing. qaalia_lote_items holds one row per item, keyed by (lote_id, idx):

ColumnWhat it is for
argumentosThe arguments for this row, already mapped and typed
estadopendiente, procesando, ok or error; only pending or abandoned rows can be claimed
intentosHow many times the row was claimed; caps retries after rate limits at 40
bloqueado_enWhen the row was claimed; a row stuck in procesando for 3 minutes is offered again
resultadoYour system's answer, truncated to 2,000 characters

Totals are updated incrementally, and each state has its own range in the index (lote_id, estado, idx), so a claim near the end of a 100,000-row batch does not walk the 95,000 finished rows.

How are rows claimed without two workers taking the same one?

With Postgres row locks. The claim function selects the next pending rows and, separately, rows abandoned for more than three minutes, each with FOR UPDATE SKIP LOCKED, then marks the chosen ones as processing in the same statement. A second process running the same query skips locked rows instead of waiting for them, so two workers can never hold the same row:

WITH pendientes AS (
  SELECT lote_id, idx FROM qaalia_lote_items
  WHERE lote_id = p_lote_id AND estado = 'pendiente'
  ORDER BY idx LIMIT v_limite
  FOR UPDATE SKIP LOCKED
),
abandonadas AS (
  SELECT lote_id, idx FROM qaalia_lote_items
  WHERE lote_id = p_lote_id AND estado = 'procesando'
    AND bloqueado_en < NOW() - INTERVAL '3 minutes'
  ORDER BY idx LIMIT v_limite
  FOR UPDATE SKIP LOCKED
)
-- then: UPDATE ... SET estado = 'procesando', bloqueado_en = NOW(), intentos = intentos + 1

A normal stretch claims 24 rows (the SQL caps any claim at 100). Afterwards, finished rows are saved as ok or error, and rows to retry go back to pendiente with the same index, so the same key.

Diagram of a durable batch. The agent declares the batch once; rows are registered in Postgres; the worker claims rows with SKIP LOCKED, calls your system with one idempotency key per row and saves each result. Rows move from pending to processing to ok or error; rate-limited rows go back to pending; rows abandoned for 3 minutes are offered again. The worker job sends a heartbeat every 30 seconds, requeues itself after 110 seconds and is reclaimed by another process after 3 minutes without a heartbeat.
The life of a batch. The model appears only at the start and the end. Everything in between is rows in Postgres, claimed and saved by a worker that can die at any moment without losing a row.

What makes a retry safe?

Every row is sent as an ordinary action whose tool call ID is the batch's own ID plus the row number, <tool_call_id>#<idx>. Its idempotency key is derived from that: qaalia:<conversation>:<tool_call_id>#<idx>. A row released and claimed again an hour later produces exactly the same key. Inside a durable task there is a second guard: before calling your system, the executor records the call per task and tool call ID. If that call already succeeded, the stored result is returned and your system is not called again; if another process started it less than three minutes ago, this process stays out of the way.

How the key reaches your system depends on how the system is connected. Operations called by Qaalia's HTTP operation executor send it as an Idempotency-Key header, and the Qaalia Connector sends Idempotency-Key: qaalia:<call id> to your local API, where each call is unique per conversation and tool call. Systems connected through MCP, including the MCP server Qaalia creates for an API on the internet, do not get that header today, so for those give the operation a natural unique key (an email, an external ID) and answer 409 when the record already exists.

Two rules keep the retry logic honest. A timeout is never retried automatically, because your system may have applied the write before the connection dropped; the row is saved as an error that says so. And a 409 or an "already exists" answer is not counted as a plain failure: when the batch completes, rows whose error matches 409, "already exist" or "duplicate" are reported separately as ya_existian, already existing.

How does the batch slow down when your API pushes back?

Pacing is adaptive and stored in the database, so it survives from one worker invocation to the next. Concurrency starts at 4 calls at a time and grows by one after every clean stretch, up to 8. A timeout halves it. A rate limit (429, 503, or a body that says "rate limit exceeded" or "too many requests") means your system did not process those rows, so they go back to the queue untouched, concurrency drops to 1, stretches shrink to max(2, concurrency × 2) rows and the batch pauses:

const pausa = Math.min(Math.max(pedida, PAUSA_BASE_MS * 2 ** (pausas - 1)), PAUSA_MAX_MS)
// PAUSA_BASE_MS = 2_000, PAUSA_MAX_MS = 60_000; "pedida" comes from Retry-After
Pause after consecutive rate-limited stretches
Pause after consecutive rate-limited stretches (seconds)
1st2
2nd4
3rd8
4th16
5th32
6th and later60

Source: PAUSA_BASE_MS and PAUSA_MAX_MS in Qaalia's agent-chat/lotes.ts, as of November 23, 2026. A longer Retry-After from your API takes precedence, still capped at 60 seconds.

Each clean stretch lowers the pause counter by one, so the batch speeds up gradually. A row can be claimed up to 40 times under rate limits before it is saved as an error. A system that accepts fifteen writes a minute still receives all 1,000 rows; it just takes longer.

How does a batch outlive a 150-second function?

In Qaalia Chat a request starts interactively. When a batch cannot finish inside the turn, or the turn passes 5 tool rounds or 90 seconds, the orchestrator creates a durable task with the pending round attached and returns at once. The same happens for requests from your app through an API key and for triggers: all three use the same worker and the same executors. From there, every invocation of the worker follows a fixed set of time budgets:

Time budgets of the durable worker
Time budgets of the durable worker (seconds)
Webhook call timeout30
Heartbeat interval30
Chat turn budget90
Worker invocation budget110
Edge Function lifetime (Free)150
Reclaim without heartbeat180

Source: Defaults in Qaalia's agent-chat/limites.ts and SQL update 33, as of November 23, 2026. The chat turn budget, the worker invocation budget and the Edge Function lifetime can be changed with environment variables.

  • No call starts if it cannot finish. A webhook call is not started after 110 seconds (150 of lifetime, minus the 30-second call timeout, minus a 10-second margin), a stretch is not started with less than 8 seconds of budget left, and a model call is not started with less than 35. A row that was not sent returns to the queue as "not started", never as an error.
  • Requeue and chain. When the budget runs out, the worker requeues the task and immediately triggers the next invocation. A pg_cron job that runs every minute is only the safety net.
  • Long pauses do not burn invocations. If your API asks for more than 15 seconds, the task is postponed to that exact time instead of sleeping inside a function.
  • Transient failures are retried. If the model provider or the network fails, the task waits 15 seconds, doubling up to 300, for up to 6 consecutive failures before it stops. A stopped task keeps its state and can be continued from the same point.
  • Runaway protection. A task may make at most 1,000 model rounds. Batch rows do not count as rounds, so a 10,000-row batch costs a few rounds, not 10,000.

What happens when a worker dies mid-batch?

The job queue uses the same lock pattern as the rows. Claiming a job runs FOR UPDATE SKIP LOCKED and stamps it with a random locked_by token. While the worker processes the task, it sends a heartbeat every 30 seconds that refreshes locked_at only if the token still matches. If the heartbeat returns false, the worker knows another process owns the job and stops. If the worker disappears, the next claim resets any job without a heartbeat for 3 minutes back to queued.

With a heartbeat, the expiry no longer has to exceed the function lifetime: three minutes works with both 150 and 400 seconds, and a crashed worker is replaced sooner. Row claims and tool-call claims expire at the same 3 minutes, so all three layers agree on when work is abandoned.

Is that exactly-once delivery? No, and no system that calls another over a network can promise it. If a worker dies after your API saved a row but before Qaalia stored the answer, that row is offered again with the same key. The guarantee is at-least-once delivery with a stable key, plus no blind retry on timeouts. Your API honoring the key, or a unique constraint that answers 409, turns that into a single effect.

What does the agent see when the batch ends?

A summary, never a thousand results. While the batch runs, it emits a progress step after every stretch with the batch description and the rows done out of the total, or the pause and its countdown when your API asked for one, which you can watch live in Qaalia Chat. When it ends, the model receives:

FieldContent
total, ok, erroresCounts for the whole batch, kept incrementally
ya_existianErrors that were really "already exists": 409, "duplicate" or "already exist" in the answer
errores_detalleUp to 25 failed rows, in order, with their arguments and the first 400 characters of the error
muestra_okThe first 3 successful rows, so the model can confirm the shape of a good answer

The model is told to report exact figures and not to resend registered rows. Plan usage follows the same keys: each real execution against your system counts once, so a retried row never counts twice. Finished batches are deleted after 30 days.

Can you apply this design to your own agent?

The pattern does not depend on Qaalia. If you run bulk work behind any agent, these are the pieces that matter:

  1. Let the model plan, not iterate. One tool call declares the operation and the mapping; code builds and runs the rows.
  2. Store state per row, outside the process. A process is something that will die; a row in Postgres is not.
  3. Claim with `SKIP LOCKED` and an expiry. Concurrency without double processing, and automatic recovery of abandoned work.
  4. Derive the idempotency key from stable IDs. Never from a timestamp or an attempt number.
  5. Separate "rejected" from "unknown". Requeue 429 and 503; report timeouts for review.
  6. Heartbeat instead of long timeouts. Ownership expires quickly when a worker dies, and never while it is alive.
  7. Return a summary. Totals, already-existing rows and a bounded error sample are all the model needs.