Kaprin
All insightsEngineering Briefs

Five Failure Modes of Vibe-Coded Software in Production

By Kaprin Engineering 10 min read

This is for CTOs and founders who have a prototype built with an AI assistant and are about to put real customers on it. Vibe coding is building software by prompting an AI assistant and accepting what it produces because it seems to work, with little review of the code itself.

That works well for finding out what to build. Running it with paying customers is where it gets risky. We practice forward deployed engineering (FDE), where senior engineers work inside a client's team, and these are the five failures we check first when we harden a prototype. For the architecture view, read our anti-vibe-coding post. This post is the field guide. The step-by-step plan is in the prototype-to-production playbook.

Which five failures do vibe-coded apps hit in production?

Five keep showing up: missing row-level security, synchronous model calls in the request path, missing indexes and unbounded queries, read-then-write race conditions, and unbounded context or retry loops. Each works in a demo and breaks under tenants, volume, concurrency or retries.

FailureWhat breaks at real loadFix in one line
1. No row-level securityOne tenant reads another's dataDatabase-enforced RLS policy plus a test
2. Model call in the request pathTimeouts, thread exhaustion, duplicate workQueue the job, return 202
3. Missing indexes, unbounded queriesLatency grows with table sizeComposite index, LIMIT, keyset pagination
4. Read-then-write racesDouble spends and oversold stockOne atomic conditional UPDATE
5. Unbounded context and retriesToken bills with no ceilingStep caps, pruning, spend caps, breaker

1. How does missing row-level security expose customer data?

If tenant isolation lives only in application code, one forgotten WHERE clause returns every customer's rows. AI-generated endpoints often filter by tenant in some queries and not others. Row-level security (RLS) moves the rule into PostgreSQL, so a query without a filter returns nothing instead of everything.

What happens at real load. A new endpoint, a background job or an admin script queries a table without the tenant filter. With one test user you never see it. With many tenants, the first customer who notices is reading someone else's invoices.

The fix. Enable RLS, force it so the table owner isn't exempt, and read the tenant from a setting scoped to the transaction:

ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
  WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);

-- In each request, inside a transaction:
BEGIN;
SELECT set_config('app.tenant_id', $1, true);  -- true = local to this transaction
-- ... run the request's queries ...
COMMIT;

Three details matter. If the setting is missing, the expression is NULL and the policy returns no rows, so the failure is closed. The application must connect as a role that is neither a superuser nor granted BYPASSRLS, because those roles ignore policies. And prove it with a test that sets tenant A, queries a tenant B id, and expects zero rows. On the FansChance UK stadium ticketing platform, we use row-level locks in the database for the same reason: the database enforces the rule. Our post on idempotent ticket minting with row-level security goes deeper.

2. Why are synchronous model calls in the request path a problem?

A model call can take seconds and sometimes much longer, and it can time out. If an HTTP handler waits for it, every slow call holds a connection and a worker. Under load the pool fills and healthy requests queue behind slow ones. Accept the work, queue it, and return 202.

At real load, a traffic spike or a slow provider stalls the whole app, including pages that never touch a model. Client retries then submit the same work again, so you pay twice as well.

The handler records a job and answers immediately. A worker does the slow part, and the client polls or receives a webhook.

app.post('/documents/:id/summarize', async (req, res) => {
  const key = req.header('Idempotency-Key') ?? crypto.randomUUID()
  const { rows } = await db.query(
    "INSERT INTO jobs (tenant_id, idempotency_key, kind, payload, status) " +
    "VALUES ($1, $2, 'summarize', $3, 'queued') " +
    "ON CONFLICT (tenant_id, idempotency_key) " +
    "DO UPDATE SET idempotency_key = EXCLUDED.idempotency_key " +
    "RETURNING id, status",
    [req.tenantId, key, { documentId: req.params.id }]
  )
  res.status(202).location('/jobs/' + rows[0].id).json(rows[0])
})

Each worker claims one job at a time. In PostgreSQL, SKIP LOCKED lets many workers pull from the same table without blocking each other, which is enough for modest volume. A dedicated queue works too.

UPDATE jobs
SET status = 'running', started_at = now(), attempts = attempts + 1
WHERE id = (
  SELECT id FROM jobs
  WHERE status = 'queued'
  ORDER BY created_at
  FOR UPDATE SKIP LOCKED
  LIMIT 1
)
RETURNING *;

Give the table an attempts ceiling and a failed state, so a poison job eventually stops. And because the tenant and idempotency key are unique, a client retry returns the same job and doesn't create a second one.

3. How do missing indexes and unbounded queries slow an app down?

Without an index, PostgreSQL scans the whole table to answer a filtered query, so latency grows with the data. Without a LIMIT, one request can pull every row into memory. Both are invisible with a few hundred test rows and painful at millions.

A list page that felt instant in development starts taking seconds, then times out. Database CPU climbs, and every other query slows with it.

Measure first with EXPLAIN ANALYZE:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, status, created_at
FROM orders
WHERE tenant_id = $1 AND status = 'open'
ORDER BY created_at DESC
LIMIT 50;

Warning signs in the output are a Seq Scan node on a large table and a separate Sort node, often with a large "Rows Removed by Filter" count. Then add a composite index with equality columns first and the sort column last:

CREATE INDEX CONCURRENTLY idx_orders_tenant_status_created
  ON orders (tenant_id, status, created_at DESC);

Re-run the same EXPLAIN. You should see an Index Scan on the new index and no Sort node, because the index already returns rows in order. Use CONCURRENTLY on a live table so the build doesn't block writes.

Two more habits help. Page with a keyset (WHERE created_at < $last ORDER BY created_at DESC LIMIT 50) instead of a growing OFFSET. And index foreign key columns yourself, since PostgreSQL doesn't do it for you.

4. What is a read-then-write race condition?

A race happens when code reads a value, decides, then writes, and two requests interleave between the read and the write. Both see the old value and both act. The fix is to make the check and the change one atomic statement in the database.

Picture two concurrent withdrawals that both see a balance of 100 and both subtract 80. The balance goes negative, or stock is oversold. It only shows up under concurrency, which a single tester never creates.

This is the bad pattern.

const { rows } = await db.query('SELECT balance FROM accounts WHERE id = $1', [id])
if (rows[0].balance >= amount) {
  // another request can run here
  await db.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, id])
}

The fix is to put the condition inside the UPDATE.

UPDATE accounts
SET balance = balance - $1
WHERE id = $2 AND balance >= $1
RETURNING balance;
-- 0 rows returned means insufficient funds. Nothing was changed.

In PostgreSQL's default isolation level, a concurrent UPDATE waits for the first to commit and then re-checks the WHERE clause against the new row, so the second request correctly fails. Add CHECK (balance >= 0) as a backstop. When the logic spans several rows, use SELECT ... FOR UPDATE or an advisory lock, and pair it with idempotency keys so retries don't repeat a payment. We cover these patterns in concurrency, locks and idempotency for AI agents.

5. How do unbounded context and retry loops burn tokens?

An agent that resends its full history on every step pays for the same tokens again each turn, so cost grows faster than the number of steps. An agent that retries on failure with no ceiling can loop all night. Both need hard limits enforced in code outside the model.

It goes wrong quietly. A tool starts returning errors, the agent keeps trying, and each attempt carries a longer history than the last. Nothing crashes, so nothing alerts. You find out from the invoice.

The fix. Four controls, in code the model can't override:

  1. Step cap. Set a fixed maximum number of model calls per run.
  2. Give each run a token budget, and stop with an error when the run exceeds it.
  3. Prune context: summarize or drop old turns and large tool outputs before each call.
  4. Add a circuit breaker and spend caps. After repeated failures, stop calling the provider for a cool-off period, and cap spend per user and organization per day.
const MAX_STEPS = 8
const MAX_TOKENS_PER_RUN = 60_000  // placeholder: set from your own cost model

async function runAgent(task: Task) {
  let spent = 0
  const history: Message[] = [systemPrompt, task.input]
  for (let step = 0; step < MAX_STEPS; step++) {
    const reply = await callModel(pruneContext(history, 12_000))
    spent += reply.usage.inputTokens + reply.usage.outputTokens
    if (spent > MAX_TOKENS_PER_RUN) throw new BudgetExceeded(task.id, spent)
    if (reply.done) return reply.output
    history.push(reply.message, await runTool(reply.toolCall))
  }
  throw new StepLimitExceeded(task.id)
}

This is a sketch, and callModel, pruneContext and runTool are yours to define. What matters is that every loop has an exit that doesn't depend on the model deciding it's finished. The full treatment, including shared spend counters in Redis and dead-letter queues, is in AI FinOps: preventing the overnight LLM token leak.

How do you check whether your app has these five problems?

Run a short audit against each failure before launch. For a small codebase it takes a day or two, and it tells you whether you need a patch or a rewrite.

  1. List every table with a tenant column. Confirm RLS is enabled and forced, and that the app role can't bypass it.
  2. Search the code for model or third-party calls inside HTTP handlers. Move each behind a queue.
  3. Pull the slowest queries from your database statistics and run EXPLAIN ANALYZE on the top ten.
  4. Search for any read followed by a conditional write. Convert each to a single conditional statement or a lock.
  5. Find every agent loop and retry. Confirm each has a step cap, a token budget and a spend cap.

If you'd like an outside view, Kaprin places senior engineers in your team to run this audit and fix what it finds, with weekly live demos. You keep 100% of the code, in your own cloud account. Tell us what you've built and we'll tell you whether it needs hardening or something bigger.

Questions readers ask

What is vibe coding?

Vibe coding is building software by prompting an AI assistant and accepting the output because it appears to work, with little review of the code itself. It is fast and fine for prototypes. The risk is shipping that code to production without the checks a prototype never needed.

Why does vibe-coded software pass the demo and fail in production?

A demo has one user, small data and a patient audience. Production has many tenants, large tables, concurrent requests and retries. The five failures here only appear under those conditions, so clicking through a demo never reveals them.

How do you stop one customer seeing another customer's data?

Put the isolation rule in the database as well as in application code. In PostgreSQL, enable row-level security on every tenant table, force it for the table owner, connect the app as a role that cannot bypass it, and write a test that proves tenant A cannot read tenant B.

Is it faster to rewrite a vibe-coded app or harden it?

Harden, in most cases. The five failures here are localized and fixable without a rewrite. Rewrite only when the data model itself is wrong. An audit of schema, queries, queues and spend controls tells you which case you are in.

How do you cap runaway LLM costs in an agent?

Set a maximum number of steps, a token budget per run and a spend cap per user and organization, prune context before every call, and trip a circuit breaker on repeated failures. Enforce the caps in code outside the model, so a looping agent cannot ignore them.

Bring us the broken prototype, the SaaS bill, or the manual process

Tell us what is stuck. We reply within 24 hours with a scoped plan, a fixed timeline and the one number we will move.

More insights

FDE = forward deployed engineering. Strict NDA protection. Senior architect review.