
001 Case study
All workCadenceFlow
- Category
- SaaS / Automation / AI
- Year
- 2026
- Role
- Solo · full stack
- Status
- Live
Authorship & scope
What I built
The LinkedIn module on Unipile: one outbox per account with idempotent enqueue, the invite-safety rules, burst control and a circuit breaker. Since October 2026 the invite cap runs on a v2 maturity table, with the first function as the fallback.
Official WhatsApp as a Meta Tech Provider: Embedded Signup, Cloud API send and receive, encrypted token custody and the signed Meta webhook.
Team seats and permissions: roles read from the database, per-author scoping, optional per-member quotas and the middleware route-rule table.
Email signal quality: the scanner classifier behind human open counts, and bounce diagnosis read from the raw delivery report.
Deploy safety: hardlink build snapshots with scripted rollback, the staging health gate on /api/health and an explicit pg pool with timeouts.
Metering and access: per-plan AI credits with idempotent debits, and the MCP client login with an entitlement check on every request.
- The rest of the product
- I also built the cadence executor, the lead generator, the qualifier, the automations, the CRM adapter, the n8n trial-funnel hook and, later, the LinkedIn v2 invite engine.
- In production
- Live at cadenceflow.pro, with the app at app.cadenceflow.pro; the private repository was still receiving commits in November 2026.
- CRM integrations
- One CRM adapter today, for FunnelsFlow, the agency's own CRM. The other outlets are HMAC-signed outgoing webhooks, Google Sheets, Google Calendar and legacy Chatwoot.
Overview
CadenceFlow is a multi-tenant B2B prospecting platform in production. It builds lead lists, qualifies them by crawling company sites and summarizing them with an LLM, and runs email, WhatsApp and LinkedIn cadences with a reply inbox and plan-based billing. I am its developer, from lead generation and the cadence engine to the LinkedIn module, the official WhatsApp integration, team seats and permissions, the email open and bounce accuracy work, and deploy safety.
Spec · from the code and docs, not live metrics
- instances
- 3 × PM2 · Nginx least_conn
- queues
- inside Postgres
- Meta webhook
- X-Hub-Signature-256
- deploy
- build rollback in seconds
Problem
B2B sales teams need to build lists, qualify leads and reach them by email, WhatsApp and LinkedIn without burning domains, numbers and profiles, and without spreading the process across disconnected tools. Each channel punishes excess in its own way, and on LinkedIn the penalty lands on a salesperson's personal profile. Security scanners and mail privacy proxies also open emails before people do, so the open rates teams steer by are misleading.
Architecture
One Next.js 16 codebase serves the React 19 UI and over 500 API route files. It runs as three PM2 processes behind Nginx, with least_conn balancing and failover. PostgreSQL, through Prisma 7, holds the tenant data and doubles as the queue: the LinkedIn outbox is a table, and Meta webhook deliveries are deduplicated by a unique key. The server crontab calls the /api/cron routes. Email, WhatsApp, LinkedIn, LLM and billing providers sit at the edge.
System map · CadenceFlow
Scroll sideways for the whole system →
- sync
- async · queue · cron
- external
- built by me
01 · Client
The product UI, served by the same Next.js codebase.
02 · Edge · ops
Balances three PM2 processes. max_fails takes a failing one out of rotation, and proxy_next_upstream retries the request on the next.
The server crontab calls /api/cron/* (cadences, LinkedIn, IMAP sync, reconciliation): 46 handlers, a few of them one-off jobs, all behind a fail-closed, constant-time secret check.
Each deploy snapshots .next with hardlinks before replacing it; rollback swaps the builds, restarts PM2 and smoke-tests the login route. Staging waits on /api/health and rolls back on failure.
03 · Core
For seat members, the middleware checks a route-rule table before any write; an unlisted seat write requires MEMBER. Gated routes read roles from the database, not from the seven-day JWT.
One Next.js 16 App Router monolith, the React 19 UI and over 500 API route files, run as three PM2 processes.
126 models and 102 hand-written additive migrations. The LinkedIn outbox is a table with a unique dedupeKey; Meta webhook deliveries are deduplicated under a unique key.
04 · Services
Hits within 30 s (open) or 120 s (click) of the send, and Gmail and Apple prefetch agents, count as scanner hits; open reports read humanOpenCount. Bounces are parsed from the raw delivery report into six buckets that drive blacklist and stop decisions.
Picks each lead's next step, keeps to per-mailbox and per-number daily limits and can personalize a step with an LLM.
Campaigns, warm-up, cadences and manual use all enqueue an intent; one dispatcher per account drains it toward Unipile within quota and send window. Since October 2026 the weekly invite cap comes from a v2 maturity table, with the first function as the fallback.
Fetches up to 8 internal pages of each site over plain HTTP for emails and phones, then writes an LLM summary. Puppeteer belongs to the CNPJ extractor, not to the qualifier.
05 · Integrations
Email leaves through Nodemailer; replies and bounces come back through IMAP sync.
Meta Tech Provider integration: Embedded Signup, Cloud API send and receive routed by phone_number_id, key-versioned AES-256-GCM tokens, and a webhook that checks X-Hub-Signature-256, records each event under a unique key and acknowledges at once.
Outgoing LinkedIn actions reach it through the outbox dispatcher. Reads (search, profiles, posts, network import) and warm-up's invitation accepts call it directly.
OpenAI over HTTPS with platform keys for qualification, personalization and reply classification; Gemini as an alternative provider; the Anthropic SDK for the SDR agent v2. AI credits are allotted per plan.
built by me · tap a node to see its role
Connections in CadenceFlow architecture:
- Web app to Nginx: synchronous.
- Nginx to Seats & roles: synchronous.
- Seats & roles to Next.js ×3: synchronous.
- Next.js ×3 to PostgreSQL: synchronous, Prisma.
- Crontab to Next.js ×3: asynchronous.
- Deploy safety to Next.js ×3: asynchronous.
- Next.js ×3 to Cadence executor: asynchronous.
- Next.js ×3 to LinkedIn outbox: asynchronous, enqueue.
- Next.js ×3 to Qualifier: asynchronous.
- Next.js ×3 to Unipile: external integration, reads.
- Cadence executor to SMTP · IMAP: external integration.
- Cadence executor to WhatsApp Official: external integration.
- SMTP · IMAP to Opens & bounces: external integration.
- LinkedIn outbox to Unipile: external integration, outgoing.
- Qualifier to LLMs: external integration.
Layers
Edge
Nginx upstream with least_conn across three PM2 processes. max_fails and fail_timeout take a failing instance out of rotation, and proxy_next_upstream retries the request on the next one.
Application
Next.js 16 App Router monolith: the React 19 UI plus over 500 API route files. Middleware checks the session and, for seat members, a pure route-rule table before any write.
Jobs
The server crontab calls /api/cron/* (cadences, LinkedIn, IMAP sync, reconciliation): 46 handlers, a few of them one-off jobs, all behind a fail-closed, constant-time secret check. Long cadence runs send a heartbeat, so a dead run stops blocking the next one.
Data and queues
PostgreSQL via Prisma 7 and the pg adapter: 126 models and 102 hand-written additive migrations. LinkedInOutbox is a durable per-account queue with a unique dedupeKey; WhatsAppWebhookEvent records each Meta delivery under a unique key to drop redeliveries.
Channels
Nodemailer and ImapFlow for email. WhatsApp runs on the Meta Cloud API plus QR gateways (Z-API, WAHA, Evolution). LinkedIn runs on Unipile: outgoing actions go through the per-account outbox dispatcher, while reads (search, profiles, posts, network import) and warm-up's invitation accepts call it directly.
AI, billing and MCP
OpenAI, called over HTTPS with platform keys, handles qualification, personalization and reply classification, with Gemini as an alternative provider; the Anthropic SDK powers the SDR agent v2. AI credits are allotted per plan. Stripe and Asaas handle billing, and a separate MCP server exposes account operations.
Data flow · step by step
Lead generators and automations pull companies and contacts from Google Maps, Google Search, the CNPJ registry and Apollo into deduplicated lists.
The qualifier crawls each site, up to 8 internal pages, for emails and phones and writes an LLM summary.
Leads join a cadence; the cron-driven executor picks the next step and can personalize it with an LLM.
Sends respect per-mailbox and per-number daily limits; LinkedIn actions wait in the account's outbox for quota and send window.
Replies arrive through IMAP sync and provider webhooks, stop the cadence and are classified by an LLM.
Outcomes go out through the CRM adapter, Google Sheets and HMAC-signed outgoing webhooks.
Technical decisions
01
One outbox per LinkedIn account
Outgoing actions from campaigns, warm-up, cadences and manual use all enqueue an intent, and one dispatcher per account drains it toward Unipile. Two engines that each kept to their own cap had together gone past the account's safe invite budget, so quota has to belong to the account.
02
Invite ceiling derived, not configured
The weekly cap was a pure, unit-tested function of acceptance rate (only invites at least three days old count) and lifetime volume, clamped to 50–200, minus a reserve for the seller's manual use. Usage is a COUNT over the outbox, never an incremented counter. Since October 2026 production uses a v2 maturity table (60 to 200 a week), with this function as the fallback.
03
Roles read from the database, not the JWT
Sessions are seven-day JWTs, so roles baked into the token could stay valid for a week after revocation. Gated routes do one indexed membership lookup instead. A middleware table makes any unlisted seat write require MEMBER, so new routes start closed.
04
Persist, acknowledge, then process
The Meta webhook verifies X-Hub-Signature-256 over the raw body, records each event under a unique dedupe key, returns 200 at once and processes in Next.js after(). The dedupe row lives in Postgres rather than memory, so it survives restarts and a Meta redelivery hits the unique constraint. The row holds no payload, so retries are not built yet; the code plans pg-boss for them.
05
Undo a deploy by swapping builds
An environment flag cannot revert compiled chunks, so the deploy snapshots .next with hardlinks (cp -al, no extra disk space) before replacing it. Rollback swaps the directories, restarts PM2 and smoke-tests a POST to the login route, which exercises Prisma.
Challenges
Challenge 01
Security scanners counted as readers
Safe Links and Proofpoint open links in a real browser seconds after sending, before the person sees the email. Hits within 30 s (open) or 120 s (click) of the send, and Gmail and Apple prefetch agents, are labelled scanner hits. A backfilled humanOpenCount column switched every open report at once, history included; clicks still count scans.
Challenge 02
Deploys that passed checks while broken
The login page returned 200 even with Prisma broken, so the checks passed. Staging deploys now wait on /api/health, which runs a raw query and a findFirst to catch a stale client or a missing column. On failure they roll back and keep the failed build for diagnosis.
Challenge 03
Forged lead replies on unsigned callbacks
Z-API does not sign callbacks, so a forged POST could stop cadences and open CRM deals. An origin proof checks that the body's instanceId matches the credential named in the URL, or the only credential holding that instance. It ships in a log-only measure mode, with an env switch to reject with 401. The dedicated Meta webhook rejects any event without a valid HMAC.
Challenge 04
Requests hanging past the proxy timeout
With pg defaults, a query waiting for a pooled connection could wait forever, outlasting Nginx's 120 s limit and causing intermittent 502/504s. Now an explicit pool (15 per process, three processes) with an 8 s connection timeout and a 90 s statement timeout limits every wait.
Implementation
LinkedIn module on Unipile: a LinkedInOutbox table as the single per-account queue, idempotent enqueue on a unique dedupeKey and an optimistic PENDING-to-SENT claim before each provider call. It also adds burst control after backlogs and a circuit breaker after three consecutive errors.
Official WhatsApp as a Meta Tech Provider: Embedded Signup onboarding, Cloud API send and receive routed by phone_number_id, Meta tokens under key-versioned AES-256-GCM, and one signed webhook that also accepts legacy clients' own app secrets.
Team seats: members act under the owner's userId while actorId keeps their identity. Each role gets a few broad capabilities, per-author scoping compiles into createdByMemberId filters, and a member can get a monthly quota inside the account's limits.
Email signal quality: the isScannerHit classifier feeds humanOpenCount. A DSN parser reads the raw RFC 822 source, extracts the status code and diagnostic, and sorts bounces into six buckets that drive blacklist and stop decisions.
Deploy safety: a hardlink build snapshot with scripted rollback, a Prisma schema guard that regenerates the client when the schema changes, the staging health gate on /api/health, and an explicit pg pool with connection and statement timeouts.
Metering and access: per-plan AI credits with idempotent debits (the usage row is written first under a unique key), and MCP client login against the app's own credentials, with an entitlement check repeated on every request.
Technologies
- Next.js 16
- React 19
- TypeScript
- Prisma 7
- PostgreSQL
- Nginx
- PM2
- Meta Cloud API
- Unipile
- Nodemailer
- ImapFlow
- Puppeteer
- OpenAI API
- Gemini API
- Anthropic SDK
- Stripe
- Asaas
- MCP
Results
Live at cadenceflow.pro (checked 24 November 2026).
A 126-model Prisma schema with 102 versioned SQL migrations, written by hand under an additive-only rule (db:push is blocked).
292 assertion-based *.test.ts files under saas/src and 135 scripts/check-*.ts, without a test framework; npm run check chains 177 of the 220 check:* scripts.

002 Next caseFinance Platform
Fintech / Full Stack / Product Engineering
Case 001 of 004