
004 Case study
All workAutomation Infrastructure
- Category
- Backend / Integrations / Systems
- Year
- 2025 — 2026
- Role
- Own product, co-developed product and in-house automation work
- Status
- In production
Authorship & scope
My own project
Núcleo
The event and automation engine this case is built around; architecture and code are mine. Its repository holds two snapshot commits, so the before-and-after stories below come from code comments and migration notes, not from commit history.
Co-developed · my parts only
Agente SDR
Another engineer owns the production baseline and most of the code: the original conversation and AI engines, the triager, campaigns, deploy, the CRM mirror-webhook delivery and its retry cron. Mine: the CadenceFlow WhatsApp ingress, the outbound router, the conversation-event contract, the handoff SLA queue and the single-run cron lock.
2025 role · CV only
1 Call Closers
A remote role (California, January to September 2025): n8n, Zapier and Make integrations over REST APIs for sales, scheduling and operational metrics reporting. No repository or public code stands behind it.
- Where n8n fits
- The code in this case is TypeScript. The n8n work comes from the 1 Call Closers role and from landing pages that post leads to n8n webhooks; no n8n workflow export in the repositories is attributed to me.
- Where Supabase fits
- Núcleo uses it as hosted Postgres plus pg_cron and pg_net scheduling, with its own JWT auth. Agente SDR runs on its own schema in a PostgreSQL database it shares with CadenceFlow.
- In production
- Núcleo is live at nucleoaut.vercel.app and Agente SDR runs at sdr.cadenceflow.pro. Núcleo's pg_cron schedule exists as runbook SQL; nothing in the repo records it as applied.
Overview
Integration work built around one goal: an automation may wait, retry or fail loudly, but it should not silently lose an event or act on it twice. The core is Núcleo's event engine, a transactional outbox on Supabase Postgres drained by a worker behind an HTTP endpoint that a pg_cron schedule, defined in the runbook, calls. Around it sit my parts of Agente SDR (WhatsApp ingress, one outbound router, a conversation event contract) and the n8n, Zapier and Make integrations from my 2025 role at 1 Call Closers, which have no public code.
Spec · from the code and docs, not live metrics
- outbox claim
- SKIP LOCKED · 20 per batch
- retries
- 30 s doubling, 1 h cap · DEAD at 5
- clock
- pg_cron → /api/cron/tick · 45 s daily budget
- ingress
- token check · 60 s dedup · 200, then async
Problem
Small service firms and sales teams run on events that cross systems: a contract is signed, a PIX payment clears, a lead replies on WhatsApp. Wired by hand or with fire-and-forget calls, those hand-offs fail quietly: a crash between two writes loses the event, a redelivered webhook triggers a second reply, and a send skipped by a stale guard leaves a reply in the database that never reaches the lead. Serverless time limits and provider outages add their own failure modes.
Architecture
State changes commit together with their event in a Postgres outbox. A worker claims due events with FOR UPDATE SKIP LOCKED and runs the matching 'when X, do Y' automations, recording every step. On Vercel, a Supabase pg_cron schedule defined in the runbook calls a secret-protected /api/cron/tick to drive it. In Agente SDR, an authenticated ingress deduplicates and answers before processing, and free-text WhatsApp replies leave through one outbound router.
System map · Automation Infrastructure
Scroll sideways for the whole system →
- sync
- async · queue · cron
- external
- built by me
Núcleo · my own project
01 · Sources
The CRON.md runbook has Supabase pg_cron post through pg_net to /api/cron/tick every minute, every five minutes and once a day. It exists as runbook SQL; nothing in the repo records it as applied.
02 · Ingress
The Express API moved to Vercel without rewriting routes: a catch-all function serves createApp(). Mercado Pago notifications are verified here by HMAC-SHA256 over the id, request-id and ts manifest.
Secret-protected (timingSafeEqual, and a 404 without CRON_SECRET). It requeues rows held in PROCESSING for more than five minutes and claims up to 20 due events with FOR UPDATE SKIP LOCKED.
03 · Core
contract.signed, payment.paid and payment.expired are emitted inside the same Prisma transaction as the state change, with an idempotencyKey built from a domain id; a duplicate key is ignored.
OutboxEvent rows on Supabase Postgres move PENDING → PROCESSING → DONE. A failure returns the row to PENDING with a later availableAt, the fifth marks it DEAD, and a reaper recovers rows orphaned by a crash.
04 · Dispatch
Automations read as sentences: one trigger, AND/OR conditions, ordered steps. One run per automation and event, finished steps skipped on any re-run, and a dry-run that executes steps without sending, charging or writing.
05 · Outputs
PIX and boleto charges. A five-minute job polls up to 50 pending charges past the webhook window; the code notes that the webhook's signed field names still need confirming against the sandbox.
Two of the engine's 14 action types: email, and WhatsApp through the Meta Cloud API or Evolution API.
Agente SDR · co-developed · my parts only
01 · Sources
Relays WhatsApp messages to Agente SDR with an internal token.
02 · Ingress
Compares SHA-256 digests of the internal token in constant time, drops an identical message from the same conversation within 60 s, answers 200 and hands the message to the conversation engine.
03 · Core
Serializes work per conversation. The original conversation and AI engines are the other engineer's, as are the triager and campaigns.
04 · Dispatch
About nine copies of the send logic became sendLeadText: it picks Chatwoot or CadenceFlow and returns success or a classified error with a retryable flag. sendLeadTemplate sends approved templates through CadenceFlow, pinned to the official number.
One conversation-event contract with eight types; deal_created, meeting_scheduled, handed_off and not_interested go to the client's CRM mirror webhook for email and LinkedIn. WhatsApp keeps the engine's inline sync to avoid duplicates.
05 · Outputs
Chatwoot keeps precedence, so tenants already on Chatwoot stay on the same channel.
The client's CRM mirror webhook. Its delivery and retry cron are the other engineer's work.
built by me · tap a node to see its role
Connections in Automation Infrastructure architecture:
- Núcleo API to Domain writes: synchronous.
- Domain writes to Outbox: synchronous.
- pg_cron to Worker: asynchronous, pg_net.
- Worker to Outbox: synchronous, claim.
- Worker to Automation engine: synchronous.
- Automation engine to Mercado Pago: external integration, PIX charge.
- Automation engine to Email · WhatsApp: external integration.
- Mercado Pago to Núcleo API: external integration, signed webhook.
- CadenceFlow to WhatsApp ingress: external integration.
- WhatsApp ingress to Conversation engine: asynchronous.
- Conversation engine to Outbound router: synchronous.
- Outbound router to Send channels: external integration.
- Conversation engine to Event contract: synchronous.
- Event contract to Client CRM: external integration.
Layers
Producers
Núcleo
Domain writes (contract.signed, payment.paid, payment.expired) call emit(tx, ...) inside the same Prisma transaction, with an idempotencyKey built from a domain id. A duplicate key (P2002) is ignored, so a replayed write does not publish twice.
Outbox on Supabase Postgres
Núcleo
OutboxEvent rows move PENDING → PROCESSING → DONE. A failure puts the row back in PENDING with a later availableAt, and the fifth failure marks it DEAD. lockedAt lets a reaper recover rows orphaned by a crash, and an index on (status, availableAt) serves the claim.
Clock
Núcleo
The CRON.md runbook has Supabase pg_cron post through pg_net to /api/cron/tick on three schedules: every minute it drains the outbox and expires stale PIX charges, every five minutes it reconciles payments with the gateway, and once a day it runs deadlines, expiring contracts and proposals, recurring automations and monthly charges. Locally the same functions run on setInterval.
Automation engine
Núcleo
Automations read as sentences, not node graphs: one trigger, AND/OR conditions, ordered steps. Runs and step results are stored per event, and a health view groups failures by error over 30 days. A dry-run executes steps without sending, charging or writing.
Channel ingress
Agente SDR
CadenceFlow, which owns the Meta webhook, relays WhatsApp messages with an internal token. The route checks the token, drops repeats inside 60 s, answers 200 and hands the message to the conversation engine, which serializes work per conversation.
Outbound router and event contract
Agente SDR
sendLeadText picks Chatwoot or CadenceFlow and returns a classified result; sendLeadTemplate sends approved templates through CadenceFlow, pinned to the official number. One conversation-event contract has eight types, and four of them (deal_created, meeting_scheduled, handed_off, not_interested) go to the client's CRM mirror webhook for email and LinkedIn. WhatsApp keeps the engine's inline sync to avoid duplicates.
Edge capture
Landing pages
18 landing pages in my catalogue send leads to n8n webhooks. On CODA Inventory, WhatsApp CTAs post the lead with navigator.sendBeacon, form-encoded to avoid a CORS preflight, before opening WhatsApp. They fall back to a keepalive fetch and keep PII out of the dataLayer.
Data flow · step by step
In Núcleo, a client signs: the signature row, the contract status and a contract.signed event commit in one transaction.
pg_cron calls /api/cron/tick; the worker requeues stale PROCESSING rows and claims up to 20 due events with SKIP LOCKED.
The engine checks the plan gate, loads active automations for the event, evaluates conditions and upserts one run per automation and event.
In the contract-signed recipe, steps run in order (open the project, create the PIX charge, email the client, tag the client, notify the team); finished steps are skipped on any re-run.
A failing step marks the run FAILED and rethrows; the event retries with backoff doubling from 30 s (capped at 1 h) and turns DEAD after five attempts.
Payment confirmation arrives by signed Mercado Pago webhook or the five-minute reconciliation, and markPaid emits payment.paid for the next automation.
Technical decisions
01Núcleo
A Postgres outbox instead of a broker
Events are written in the same transaction as the state change and claimed with FOR UPDATE SKIP LOCKED. A crash cannot commit 'contract signed' without the event that triggers the charge, and overlapping invocations never claim the same row. The code defers BullMQ or SQS until volume requires it.
02Núcleo
Idempotency per event and per step
A unique (automationId, outboxEventId) turns run creation into an upsert, and steps already marked SUCCESS or SKIPPED are skipped on replay. That made it safe for the engine to rethrow failures into backoff and the dead-letter state.
03Núcleo
An external clock for serverless
On Vercel a setInterval dies with the response, so the runbook has Supabase pg_cron call /api/cron/tick through pg_net. The secret is compared with timingSafeEqual, and without CRON_SECRET configured the route answers 404 rather than run open.
04Agente SDR
Authenticate, deduplicate, then answer
The ingress compares SHA-256 digests of the internal token in constant time. It drops an identical message from the same conversation within 60 s, returns 200 and processes in the background. Its documented ceiling: the same text sent twice inside 60 s is dropped; the upgrade is a unique provider message id.
05Agente SDR
One outbound router with explicit results
About nine copies of the send logic became sendLeadText. It returns success or a classified error with a retryable flag instead of skipping in silence. Chatwoot keeps precedence, so tenants already on Chatwoot stay on the same channel.
Challenges
Challenge 01Núcleo
Retries that resent, failures marked done
Each reprocess created a new run, so the step check found nothing and email and WhatsApp went out again. Meanwhile the engine swallowed step errors and the worker marked the event DONE. A unique (automationId, outboxEventId), upserted runs and a rethrow fixed both. engine.check.ts asserts the contract on a replica of the step loop.
Challenge 02Núcleo
A 60-second function ceiling
The daily sweep covered every organization in one request and could be killed mid-run, leaving the month's charges unbilled. The daily scans now share a 45 s budget, stop starting new work when it runs out and report truncado. Monthly charges are selected as due or overdue with a once-a-month guard, so a charge cut off by the budget goes out on a later run, and only once. Exact-date scans cut off by the budget are not resumed.
Challenge 03Agente SDR
Telling a refusal from an outage
The revive cron, created by the other engineer, resent the same text every five minutes for up to 24 hours, even to leads who had opted out. The cause: CadenceFlow's refusal codes only reached a log line. They now map to local actions: close the conversation and record the opt-out, or flag the number. Definitive refusals stop retries, and a 20 s timeout is recorded as unconfirmed rather than failed.
Challenge 04Agente SDR
Handoffs nobody was told about
Conversations stayed HANDED_OFF after a person replied, and the only signal was a counter on a screen. The fix: a handoffAt column with a backfill migration (marked in the repo as not yet applied) and a wait clock built from the last lead and human messages, feeding a cron route documented for weekdays at 9:00. Past a 4-hour SLA it sends the account owner a WhatsApp alert, or logs the queue when the tenant has no notification channel.
Implementation
Núcleo event bus: emit(tx) writes OutboxEvent rows inside Prisma transactions, and the worker claims 20 at a time with UPDATE ... WHERE id IN (SELECT ... FOR UPDATE SKIP LOCKED) RETURNING. A reaper requeues rows held in PROCESSING for more than five minutes.
Núcleo automation engine: a catalog of 22 events (17 with a live producer; the rest are shown as unavailable) and 14 action types, among them email, WhatsApp (Meta Cloud API or Evolution API), PIX and boleto via Mercado Pago, NFS-e, tasks, projects and an outbound webhook with a 10 s timeout. The scheduler skips any recurring automation with a charge step that would fan out over more than 50 contracts, and the preview flags it.
Núcleo on serverless: the Express API moved to Vercel without rewriting routes. A catch-all function serves createApp(), and the four in-process jobs became tick, reconcile and daily sets behind /api/cron/tick. The runbook checks net._http_response rather than cron status alone.
Núcleo payments: Mercado Pago notifications are verified by HMAC-SHA256 over the id, request-id and ts manifest (the code notes its field names still need confirming against the sandbox). markPaid transitions once under concurrent deliveries and emits payment.paid in the same transaction, and a five-minute job polls the gateway for up to 50 pending charges past the webhook window.
Agente SDR, my parts: the CadenceFlow WhatsApp ingress, the outbound router (sendLeadText, plus sendLeadTemplate for approved templates outside the 24-hour window), the conversation event contract, the handoff SLA queue, and a single-run lock now used by five crontab-driven cron routes.
1 Call Closers (2025, CV only): designed and implemented n8n, Zapier and Make integrations over REST APIs for sales, scheduling and operational metrics reporting.
Technologies
- Node.js
- TypeScript
- Express
- Next.js
- Prisma
- PostgreSQL
- Supabase pg_cron · pg_net
- Vercel Functions
- REST APIs
- Webhooks
- WhatsApp Cloud API
- Evolution API
- Mercado Pago
- Chatwoot
- n8n
- Zapier
- Make
- Zod
- GitHub Actions
Results
Núcleo live at nucleoaut.vercel.app.
Agente SDR in production at sdr.cadenceflow.pro (co-developed).
29 versioned SQL migrations in Núcleo, including run idempotency and indexes for the periodic jobs.
36 node:assert self-check files in the Núcleo monorepo, run by npm run check in a GitHub Actions workflow on push; engine.check.ts asserts the idempotency contract.
Test files I wrote in Agente SDR for the outbound router, transport error classification, cron lock and handoff queue, run by npm test (tsx --test).

001 Next caseCadenceFlow
SaaS / Automation / AI
Case 004 of 004