← AI Shouldn't Handle the Money: Modeling RetomaVenda with Ledgers, Leases, and Idempotency
AI Shouldn't Handle the Money: Modeling RetomaVenda with Ledgers, Leases, and Idempotency
English ↔ Español
The problem was not “using AI”
RetomaVenda started with a simple product idea: paste a stalled sales conversation, receive a diagnosis backed by evidence, and get a concise message to try to restart the deal.
It would have been easy to build this as a form connected to a model: user sends text, backend calls an API, response appears on screen. The prototype would be fast.
But that design hides the problems I actually cared about.
A conversation may contain phone numbers, email addresses, tax IDs, names, URLs, and commercial details. The user pays for a finite number of analyses. A model call can fail after consuming resources. The browser can repeat a request. The provider can return valid JSON and still produce a bad diagnosis. And a response lost on the network cannot become a double charge.
So the architectural question stopped being “how do I call the AI?” and became:
how do I place a probabilistic component inside a financial flow without allowing it to control the product’s invariants?
That became the most valuable part of RetomaVenda.
The architecture I chose
The main flow looks like this:
Browser
↓
Edge Function: authentication + sanitization
↓
Credit reservation with lease
↓
Model with structured output
↓
Validation + result sanitization
↓
Transaction: persist result + debit credit
↓
Response to the user
The application uses Next.js 16 with App Router, TypeScript, React 19, and Tailwind 4. Authentication, database, RLS, and Edge Functions live in Supabase. The browser never calls the model directly.
That sounds like a small choice, but it establishes an important boundary: the browser is an untrusted origin. It may request an analysis; it cannot decide balances, mark a purchase as paid, write privileged results, or call the model with backend secrets.
In the database, the balance is not a mutable number in profiles either. It is derived from a ledger: credit_transactions.
That difference matters. Instead of trying to keep one counter perfectly synchronized, I store accounting events and derive the balance from their sum.
AI is not the authority
I use a small provider interface and an implementation of the Responses API with a strict JSON Schema.
Structured Outputs is useful because the contract stops being “hopefully the model returns JSON that looks roughly like this.” With strict: true, the output must follow the supported schema. OpenAI’s current documentation recommends Structured Outputs instead of the older JSON mode when the use case supports that contract.
But a structurally valid response is not necessarily a correct decision.
That distinction should not disappear behind types.
A model can produce:
{
"status": "recoverable",
"objection": "price",
"evidence": ["..."],
"message": "..."
}
and still be wrong about the objection.
That is why the system rejects evidence that does not exist, does not automatically interpret quote value as evidence of price objection, and treats an explicit refusal or an already-completed purchase as states that remove recovery and follow-up suggestions.
Structural validation removes one class of errors. Evals reduce another. Explicit business rules reduce a third.
None replaces the others.
A credit must survive retries
The most interesting case appears when the network fails.
Imagine the user clicks “analyze.” The backend reserves a credit, calls the model, stores the result, and returns it. But the connection drops before the browser receives the response.
The user clicks again.
If the system treats that as a brand-new operation, I may charge twice for the same intent.
The solution was to make each request identifiable. The client sends a requestId; the backend stores a fingerprint of the payload and the state of the request.
If the same requestId already completed, the previous result is returned without another debit.
If someone reuses that requestId with different content, the fingerprint exposes the collision.
This kind of idempotency is more important than adding automatic retry everywhere.
For the model call, I deliberately chose not to perform silent retries. When the outcome is unknown, preserving the identifier and checking the operation state is safer than firing another expensive request and trying to reconcile billing later.
A reservation cannot lock credit forever
Idempotency alone does not solve a worker dying mid-execution.
That is why the reservation has a lease.
When an analysis starts, one credit becomes temporarily unavailable for a window. If the process completes, the result and debit are finalized. If the worker dies, the lease expires and the work can be recovered.
There is also a leaseToken: an old worker cannot wake up later and finalize a reservation that has already been taken over by another execution.
That small mechanism covers a common distributed-systems sequence:
reserve
→ work
→ process dies
→ lease expires
→ new worker takes ownership
→ old worker comes back late
Without an ownership token, both workers may still believe they have authority.
Result and debit belong to the same transaction
Another decision was to avoid separating “save analysis” and “charge credit” into independent operations.
If I store the result and crash before debiting, I delivered value without registering consumption.
If I debit and crash before storing, I charged for a result the user may not be able to recover.
The rule is simple: result and debit must close together.
This is exactly the kind of invariant I prefer to keep close to the database instead of coordinating with a sequence of TypeScript calls.
The model can be probabilistic. Accounting cannot.
Privacy starts before the model call
It is easy to think of privacy only as “do not store prompts.”
In RetomaVenda, the raw conversation is designed to exist only in memory while processing. It does not go to the database, URL, browser storage, analytics, or application logs.
Before the model call, basic filtering removes phone numbers, email addresses, Brazilian CPF/CNPJ identifiers, and URLs.
That is not perfect anonymization. Names and context can still identify people. A final report, even after sanitization, may still contain personal information.
That limitation must be explicit.
The model call also uses store: false in the Responses API. OpenAI documents that this disables storage of the Response state, but I do not translate that configuration into “zero retention.” Provider data controls have their own rules, and responsible architecture starts by not promising more than the actual setting guarantees.
Analytics without copying the product into analytics
The same principle applies to metrics.
It is tempting to install an SDK, enable autocapture, and only later discover that sensitive fields ended up in events, session data, or properties.
Here the events are explicit.
Analytics needs to know things such as:
analysis_started;analysis_completed;analysis_failed;recovery_message_copied;second_analysis_started;credits_exhausted.
It does not need the conversation.
It does not need the generated message.
It does not need the quote amount, name, phone number, or email.
That makes instrumentation more manual than “capture everything,” but it also makes one question much easier to answer: what data actually leaves the product?
RLS does not replace privilege design
Supabase makes per-user isolation practical with Row Level Security, but I did not want RLS to become an excuse for exposing administrative operations.
Users can read their own profile, purchases, ledger, and analyses. The browser cannot write credits, purchases, or privileged results.
Sensitive RPCs and administrative operations remain restricted to the privileged server context.
This combines two ideas:
- RLS limits what an authenticated session can see.
- Some operations should not exist for the browser session at all.
Supabase’s current documentation also distinguishes RLS-scoped clients from administrative clients that bypass those policies. That second capability is too powerful to cross the wrong boundary.
Cost limits are business rules
When a feature depends on an LLM, per-call cost becomes part of the product domain.
RetomaVenda calculates a conservative estimate based on token counts and configured rates, and it limits input length, output size, frequency, timeout, and maximum cost per analysis.
If a different model is selected, the rates must be explicit.
The backend is the authority.
This prevents two different failures: a user generating far more load than the offer can support, and a model configuration change multiplying cost without anyone noticing.
I would rather reject an analysis clearly because it exceeded a cost boundary than make the system “resilient” through hidden expensive retries.
A mock test does not prove concurrency
The test suite uses Vitest, PGlite, and Playwright for schemas, privacy, commercial rules, HMAC, analytics, ledger behavior, leases, idempotency, rollback, and browser flows.
That is useful coverage, but one boundary matters: PGlite over one connection does not prove real contention across multiple PostgreSQL connections.
That is why the repository also includes an ephemeral PostgreSQL 17 test in CI with independent connections.
This is a reusable lesson: a test can execute real SQL and still fail to reproduce the concurrency property you think you are testing.
Mocks, embedded databases, and a real database answer different questions.
What is not proven yet
The product has not been commercially launched.
Real payment remains pending; Stripe is still a placeholder. Production SMTP and callbacks need configuration. Real model evals must run before selling. The recommended domain is not yet published.
That does not make the case study weaker. It makes the boundary between validation and hypothesis clearer.
Today I can say that the local architecture, invariants, and tests are designed around the important failure modes.
I cannot yet say that strangers will pay, that the diagnosis will recover sales, or that the production operation will behave as expected under real traffic.
What I would carry into other AI products
The main RetomaVenda lesson was not about prompting.
It was about surrounding AI with deterministic systems.
If I reduce the architecture to reusable rules:
- the model never decides balances;
- the model never receives tools it does not need;
- user input is untrusted data;
- structured output still needs business rules;
- billable operations need idempotency;
- asynchronous work needs recoverable temporary ownership;
- delivery and debit should share consistency;
- logs and analytics need allowlists, not “capture everything”;
- cost limits belong in the backend;
- tests must prove the actual property, not merely run similar code.
LLMs may improve dramatically. Structured Outputs may become stronger. Providers may change.
Those invariants remain useful.
That is the AI architecture I care about most: do not try to make a probabilistic model act as database, queue, ledger, ACL, and business rule engine at the same time.
Let the model do what it is good at — interpreting language — and let the rest of the system make it difficult for a wrong interpretation to become a financial, privacy, or consistency failure.
References
El problema no era “usar IA”
RetomaVenda nació de una idea de producto sencilla: pegar una negociación que se enfrió, recibir un diagnóstico con evidencias y obtener un mensaje breve para intentar retomar la conversación.
Habría sido fácil construirlo como un formulario conectado a un modelo: el usuario envía texto, el backend llama a una API y la respuesta aparece en pantalla. El prototipo saldría rápido.
Pero ese diseño esconde precisamente los problemas que más me interesaban.
Una conversación puede contener teléfonos, correos, CPF/CNPJ, nombres, URLs y detalles comerciales. El usuario paga por una cantidad finita de análisis. Una llamada al modelo puede fallar después de consumir recursos. El navegador puede repetir una petición. El proveedor puede devolver JSON válido y aun así producir un diagnóstico incorrecto. Y una respuesta perdida en la red no puede convertirse en un cobro duplicado.
La pregunta arquitectónica dejó de ser “¿cómo llamo a la IA?” y pasó a ser:
¿cómo coloco un componente probabilístico dentro de un flujo financiero sin permitir que controle las invariantes del producto?
Esa terminó siendo la parte más valiosa de RetomaVenda.
La arquitectura que elegí
El flujo principal quedó así:
Browser
↓
Edge Function: autenticación + sanitización
↓
Reserva de crédito con lease
↓
Modelo con salida estructurada
↓
Validación + sanitización del resultado
↓
Transacción: persistir resultado + debitar crédito
↓
Respuesta al usuario
La aplicación usa Next.js 16 con App Router, TypeScript, React 19 y Tailwind 4. Autenticación, banco, RLS y Edge Functions viven en Supabase. El navegador nunca llama al modelo directamente.
Parece una decisión pequeña, pero crea una frontera importante: el browser es un origen no confiable. Puede solicitar un análisis; no puede decidir saldo, marcar una compra como pagada, escribir resultados privilegiados ni llamar al modelo con secretos del backend.
En el banco, el saldo tampoco es un número mutable dentro de profiles. Se deriva de un ledger: credit_transactions.
La diferencia es importante. En lugar de intentar mantener un contador siempre sincronizado, guardo eventos contables y calculo el saldo por su suma.
La IA no es la autoridad
Uso una interfaz pequeña de provider y una implementación de Responses API con JSON Schema estricto.
Structured Outputs ayuda porque el contrato deja de ser “ojalá el modelo devuelva un JSON parecido”. Con strict: true, la salida debe adherirse al schema soportado. La documentación actual de OpenAI recomienda Structured Outputs frente al antiguo JSON mode cuando el caso permite ese contrato.
Pero una respuesta estructuralmente válida no es necesariamente una decisión correcta.
No quiero esconder esa diferencia detrás de los tipos.
Un modelo puede producir:
{
"status": "recuperable",
"objection": "precio",
"evidence": ["..."],
"message": "..."
}
y aun así estar equivocado sobre la objeción.
Por eso el sistema rechaza evidencia inexistente, no interpreta automáticamente el valor del presupuesto como señal de objeción de precio y trata un rechazo explícito o una compra ya concluida como estados que eliminan una propuesta de retomada.
La validación estructural elimina una clase de error. Los evals reducen otra. Las reglas de negocio explícitas reducen una tercera.
Ninguna sustituye a las demás.
El crédito tiene que sobrevivir a los retries
El caso más interesante aparece cuando falla la red.
Imagina que el usuario pulsa “analizar”. El backend reserva un crédito, llama al modelo, guarda el resultado y responde. Pero la conexión cae antes de que el navegador reciba la respuesta.
El usuario vuelve a pulsar.
Si el sistema interpreta esto como una operación nueva, puedo cobrar dos veces por la misma intención.
La solución fue hacer cada petición identificable. El cliente envía un requestId; el backend guarda un fingerprint del payload y el estado de la petición.
Si ese requestId ya terminó, devuelve el resultado anterior sin nuevo débito.
Si alguien reutiliza el mismo requestId con contenido diferente, el fingerprint detecta la colisión.
Este tipo de idempotencia es más importante que colocar retry automático en todas partes.
Para la llamada al modelo elegí no hacer retries silenciosos. Si el resultado es desconocido, preservar el identificador y consultar el estado es más seguro que lanzar otra operación cara y reconciliar el billing después.
Una reserva no puede bloquear crédito para siempre
La idempotencia por sí sola no resuelve un worker que muere durante el procesamiento.
Por eso la reserva usa lease.
Cuando empieza el análisis, un crédito queda temporalmente indisponible. Si el proceso termina, resultado y débito se cierran. Si el worker muere, el lease expira y el trabajo puede recuperarse.
También existe un leaseToken: un worker viejo no puede despertarse más tarde y finalizar una reserva que ya fue asumida por otra ejecución.
Ese mecanismo cubre una secuencia frecuente en sistemas distribuidos:
reservar
→ trabajar
→ el proceso muere
→ expira el lease
→ otro worker asume
→ el worker viejo vuelve tarde
Sin un token de propiedad, ambos pueden creer que todavía tienen autoridad.
Resultado y débito pertenecen a la misma transacción
Otra decisión fue no separar “guardar análisis” y “cobrar crédito” en operaciones independientes.
Si guardo el resultado y caigo antes de debitar, entregué valor sin registrar consumo.
Si debito y caigo antes de guardar, cobré por un resultado que quizá el usuario no puede recuperar.
La regla es sencilla: resultado y débito deben cerrar juntos.
Es una de esas invariantes que prefiero dejar cerca del banco de datos en vez de coordinar con una secuencia de llamadas TypeScript.
El modelo puede ser probabilístico. La contabilidad no.
La privacidad empieza antes de llamar al modelo
Es fácil pensar en privacidad solo como “no guardar prompts”.
En RetomaVenda, la conversación bruta debe existir únicamente en memoria durante el procesamiento. No va al banco, URL, localStorage, analytics ni logs.
Antes de llamar al modelo, una sanitización básica elimina teléfono, correo, CPF, CNPJ y URL.
Eso no es anonimización perfecta. Nombres y contexto todavía pueden identificar personas. El informe final, incluso sanitizado, todavía puede contener datos personales.
Ese límite debe quedar claro.
La llamada también usa store: false en Responses API. OpenAI documenta que eso desactiva el almacenamiento del estado de la Response, pero no convierto esa configuración en la frase “retención cero”. Los controles de datos del proveedor tienen sus propias reglas, y una arquitectura responsable empieza por no prometer más de lo que la configuración realmente garantiza.
Analytics sin copiar el producto dentro del analytics
El mismo principio sirve para métricas.
Es tentador instalar un SDK, activar autocapture y descubrir después que campos sensibles llegaron a eventos o propiedades.
Aquí los eventos son explícitos.
Analytics necesita conocer cosas como:
analysis_started;analysis_completed;analysis_failed;recovery_message_copied;second_analysis_started;credits_exhausted.
No necesita la conversación.
Ni el mensaje generado.
Ni presupuesto, nombre, teléfono o correo.
La instrumentación es más manual que “capturar todo”, pero hace mucho más fácil responder una pregunta: ¿qué datos realmente salen de aquí?
RLS no sustituye el diseño de privilegios
Supabase hace práctico el aislamiento por usuario con Row Level Security, pero no quise convertir RLS en una excusa para exponer operaciones administrativas.
El usuario puede leer su propio perfil, compras, ledger y análisis. El browser no escribe créditos, compras ni resultados privilegiados.
Las RPC sensibles y operaciones administrativas permanecen restringidas al contexto privilegiado.
Eso combina dos ideas:
- RLS limita lo que una sesión autenticada puede ver.
- Algunas operaciones simplemente no deberían existir para una sesión del navegador.
La documentación actual de Supabase también diferencia clientes limitados por RLS de clientes administrativos que pueden saltarse esas políticas. Esa segunda capacidad es demasiado poderosa para cruzar una frontera equivocada.
Los límites de coste son reglas de negocio
Cuando una feature depende de un LLM, el coste por llamada forma parte del dominio del producto.
RetomaVenda calcula una estimación conservadora por tokens y tasas configuradas, y limita caracteres de entrada, salida, frecuencia, timeout y coste máximo por análisis.
Si se selecciona otro modelo, las tasas deben ser explícitas.
El backend manda.
Esto evita dos tipos de accidente: que un usuario genere mucha más carga de la que soporta la oferta y que un cambio de modelo multiplique el coste sin que nadie lo note.
Prefiero que un análisis falle claramente por superar un límite que construir una “resiliencia” basada en retries caros y ocultos.
Un test con mock no prueba concurrencia
La suite usa Vitest, PGlite y Playwright para schemas, privacidad, reglas comerciales, HMAC, analytics, ledger, leases, idempotencia, rollback y flujo de navegador.
Es una buena cobertura, pero hay una frontera: PGlite con una sola conexión no demuestra contención real entre varias conexiones PostgreSQL.
Por eso el proyecto también incluye en CI un PostgreSQL 17 efímero con conexiones independientes.
El aprendizaje generalizable es: un test puede ejecutar SQL real y aun así no reproducir la propiedad de concurrencia que crees estar probando.
Mocks, banco embebido y banco real responden preguntas distintas.
Lo que todavía no está probado
El producto todavía no se lanzó comercialmente.
El pago real sigue pendiente; Stripe continúa como placeholder. SMTP y callbacks de producción necesitan configuración. Los evals reales del modelo deben ejecutarse antes de vender. El dominio recomendado todavía no está publicado.
Esto no debilita el estudio de caso. Hace más clara la frontera entre lo validado y lo que sigue siendo hipótesis.
Hoy puedo afirmar que la arquitectura local, las invariantes y los tests están diseñados alrededor de los fallos importantes.
No puedo afirmar todavía que desconocidos pagarán, que el diagnóstico recuperará ventas o que producción se comportará como espero bajo tráfico real.
Lo que llevaría a otros productos con IA
El principal aprendizaje de RetomaVenda no fue sobre prompting.
Fue sobre rodear la IA de sistemas deterministas.
Si reduzco la arquitectura a reglas reutilizables:
- el modelo nunca decide saldos;
- el modelo no recibe herramientas que no necesita;
- la entrada del usuario es dato no confiable;
- una salida estructurada todavía necesita reglas de negocio;
- las operaciones cobrables necesitan idempotencia;
- el trabajo asíncrono necesita propiedad temporal recuperable;
- entrega y débito deben compartir consistencia;
- logs y analytics necesitan allowlist, no “capturar todo”;
- los límites de coste pertenecen al backend;
- los tests deben demostrar la propiedad real, no solo ejecutar código parecido.
Los LLM pueden mejorar muchísimo. Structured Outputs puede volverse más fuerte. Los proveedores pueden cambiar.
Estas invariantes siguen siendo útiles.
Esa es la arquitectura con IA que más me interesa: no intentar que un modelo probabilístico sea al mismo tiempo banco de datos, cola, ledger, ACL y motor de reglas.
Dejar que el modelo haga lo que hace bien — interpretar lenguaje — y construir el resto del sistema para que una interpretación equivocada tenga difícil convertirse en un fallo financiero, de privacidad o consistencia.