Short answer: an agency's operating system is the path a client takes from first enquiry to signed-off deliverable. When that path runs through a CRM subscription, a payment platform, an automation tool, shared drives, email threads and one person's phone, nobody owns it end to end. We replaced ours with one Next.js 16 application on one Postgres database: a staff CRM at /crm, a client portal at /portal, and 19 tables, all 19 under row-level security. Payments, portal invites, drip email and creative approvals are automated inside the database with triggers, queues and signed webhooks, not glued together by a third-party workflow tool.
This is a teardown of our own production system at RapidGrowth, so every figure here is counted from the codebase: migrations, tables, policies, routes. It isn't a client claim. The SQL and TypeScript below are excerpts from the real files, trimmed for length.
The challenge: seven tools, no system
Before the rebuild, our client lifecycle had the shape most agencies will recognise:
- Leads landed in a CRM subscription, a form tool and a shared inbox, depending on where they came from.
- Billing went through a subscription payment platform, which suits SaaS businesses better than project-based agency work in India, where clients pay by UPI.
- Automations ran in an external workflow tool. When a step failed at 2am, the first sign was a client asking why they hadn't received their portal link.
- Deliverables and approvals lived in drive folders and email threads. "Which version did the client approve?" had no authoritative answer.
- WhatsApp conversations with clients happened on one team member's phone.
The cost wasn't the subscription fees. It was three structural failures:
- No single client record. The same client existed in five vendors' databases with five slightly different email addresses.
- No audit trail. Who changed a payment status, who approved a creative and when: unanswerable without screenshots.
- Silent automation failures. Every integration was an HTTP hop between vendors, each with its own retry semantics and none of them visible in one place.
The solution: one application, automation in the database
1. Two areas, one codebase, roles in Postgres
Staff and clients use the same application. The proxy sends each signed-in user to the right area (staff to /crm, clients to /portal). Authority, though, lives in the database: staff roles are rows in staff_profiles, checked by a helper that RLS policies call directly:
-- supabase/migrations/0004_rbac_audit.sql
create type public.staff_role as enum ('owner', 'manager', 'strategist');
-- security definer: reads staff_profiles without recursing through its own RLS.
-- stable + empty search_path: plan-cacheable and hijack-proof.
create or replace function private.has_staff_role(roles public.staff_role[])
returns boolean
language sql stable security definer set search_path = ''
as $$
select coalesce((select private.staff_role()) = any (roles), false);
$$;
-- Permissive policies are OR'd: clients still see only their own rows,
-- owners and managers see everything, strategists see none of it.
create policy "payments_select_staff" on public.payments
for select to authenticated
using ((select private.has_staff_role(array['owner', 'manager']::public.staff_role[])));
The rule we hold to: every table gets RLS on the day it's created. The count today is 19 tables across 18 migrations, with RLS enabled on all 19. Tables written only by server code (the drip queue, the audit log) have their insert, update and delete grants revoked from the API roles entirely, so the only writer is the service role or a trigger.
2. An audit log nobody can edit
Every privileged row change is captured by a trigger into audit_logs, which records the actor, their database role, and the before and after states. The table is append-only by construction:
-- No API role can write; the trigger function writes as its owner.
revoke all on public.audit_logs from public, anon, authenticated, service_role;
grant select on public.audit_logs to authenticated; -- RLS narrows to owner/manager
create or replace function private.audit_logs_immutable()
returns trigger language plpgsql set search_path = ''
as $$
begin
raise exception 'audit_logs is append-only (% blocked)', tg_op
using errcode = 'insufficient_privilege';
end;
$$;
create trigger audit_logs_no_update_delete
before update or delete on public.audit_logs
for each row execute function private.audit_logs_immutable();
That even stops accidental edits from the SQL editor. A retention purge has to disable the trigger explicitly, which is itself a deliberate, reviewable act.
3. Payments without a gateway: UPI links and a signed credit webhook
Our billing is project-based and paid by UPI, so migration 0006_remove_stripe dropped the subscription tables and constrained new payments to provider = 'upi'. Staff issue a UPI payment link from the CRM. Its tr reference identifies the payment. Whatever watches the payee account (a PSP callback or a bank-alert parser) reports each credit to a signed endpoint:
// app/api/webhooks/upi/route.ts
const MAX_CLOCK_SKEW_SECONDS = 300;
function verifySignature(rawBody: string, timestamp: string | null, signature: string | null, secret: string) {
if (!timestamp || !signature || !/^\d+$/.test(timestamp)) return false;
// Bounds replay: a captured request stops working after five minutes.
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > MAX_CLOCK_SKEW_SECONDS) return false;
const expected = createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest();
const given = Buffer.from(signature, "hex");
return given.length === expected.length && timingSafeEqual(given, expected);
}
/** "1000.5" -> 100050 paise, in integers so float rounding can't mismatch. */
function toPaise(amount: string) {
const [rupees, paise = ""] = amount.split(".");
return Number(rupees) * 100 + Number(paise.padEnd(2, "0"));
}
The response codes are a contract with the sender: 2xx means done, 4xx means don't retry, 5xx means retry later. Only a SUCCESS status for the right amount moves a payment forward. Failures and pending notices are acknowledged and leave the payment open for a later credit.
4. Automation as a database trigger, not a workflow tool
When a payment is verified, the client needs a portal sign-in link. Our first version (migration 0010) sent that event to an external workflow tool, which called back into the app. Migration 0011 removed the hop. A trigger now fires once, when a payment enters the verified set, and posts straight to our own route through pg_net:
-- supabase/migrations/0011_payment_verified_direct.sql
create trigger payments_notify_verified
after update of status on public.payments
for each row
when (
new.status in ('provisioning', 'paid')
and old.status not in ('provisioning', 'paid')
and new.portal_link_issued_at is null
)
execute function private.notify_payment_verified();
The design choices in that one statement:
- "Enters", not "is in". A UPI payment moves from
pendingtoprovisioningtopaid. Firing on both transitions would email the client twice. - After commit.
pg_netsends from a background worker after the transaction commits, so a rolled-back update never emails anyone. - Secrets in Vault. The route URL and shared secret are read from
vault.decrypted_secrets, not hard-coded in a trigger definition the way the dashboard's database webhooks store them. - Never block the payment. Any notification error is caught and logged as a warning. Money must never sit unprovisioned because an email failed.
The receiving route doesn't trust the payload. It re-reads the payment row, stamps portal_link_issued_at as an idempotency lock, mints the magic link, sends it, and never logs the link, because it's a live credential.
5. A drip queue that can't double-send
Nurture emails after a lead comes in go into a drip_logs queue, unique per address, sequence and step, so enqueueing twice is a no-op. A daily Vercel Cron drains it through one Postgres function that claims due rows with FOR UPDATE SKIP LOCKED:
-- supabase/migrations/0012_drip_queue.sql (claim step)
with due as (
select d.id
from public.drip_logs d
where d.status = 'pending'
and d.scheduled_for <= now()
and not exists (select 1 from public.email_suppressions s where s.email = d.to_email)
order by d.scheduled_for, d.id
limit greatest(1, least(coalesce(p_limit, 25), 100))
for update of d skip locked
)
update public.drip_logs d
set status = 'processing', locked_at = now(), claim_id = v_claim
from due
where d.id = due.id
returning d.*;
Two overlapping runs can never claim the same row. Each send carries an idempotency key (drip-log/<id>) to the email provider. Rows stuck in processing are never reclaimed automatically: if the function died between sending and recording, re-sending blind risks a duplicate, so a human decides. The cron route reports the stuck count on every run.
6. A creative review workspace with a real history
Campaign creatives go up to the client's private storage folder with a creative_assets row. The client approves or requests changes in /portal through one function, which updates the status and appends a timestamped creative_review_logs row in the same transaction:
-- supabase/migrations/0018_creative_assets.sql (excerpt)
-- security definer so a client can change review fields without UPDATE on the table
-- (which would also let them rewrite the copy). It only touches the caller's own rows.
update public.creative_assets
set review_status = p_decision,
review_note = v_note,
reviewed_at = now(),
reviewed_by = v_uid
where id = p_creative_id
and client_id = v_uid
returning * into v_row;
A "request changes" without a note is rejected by the database, not the UI. A check constraint also ensures a creative's image path sits inside its own client's folder, so a signed URL can never point at another client's file.
Measured: what the system is made of
| Measure | Value | Source |
|---|---|---|
| Tables with row-level security enabled | 19 of 19 | supabase/migrations/*.sql |
| Schema migrations, each safe to re-run | 18 | supabase/migrations/ |
| Staff roles enforced in Postgres | 3 (owner, manager, strategist) | 0004_rbac_audit.sql |
| External workflow hops between payment and portal invite | 0 (was 1) | 0010 → 0011 |
| Webhook replay window on UPI credits | 300 s | app/api/webhooks/upi/route.ts |
| Max drip rows claimed per call | 100, with SKIP LOCKED | 0012_drip_queue.sql |
| Writable paths into the audit log | 1 (the trigger) | 0004_rbac_audit.sql |
We deliberately don't quote "hours saved" or "tickets reduced" here. We haven't instrumented them against a pre-migration baseline, and invented productivity numbers are exactly the kind of claim this system exists to stop. What the table shows is structural: every client record, payment and approval now has one home, one access policy and one history.
The trade-offs, candidly
- You own the on-call. No vendor support line. When the cron route fails, it's our page to answer, which is why every failure path in this system logs and counts rather than retrying silently.
pg_netdelivers at most once. If our route is down when a payment is verified, the invite isn't retried. The mitigation is a delivery-check query, a manual resend, and the fact that the client can always sign in from/login.- "Self-hosted" means owned, not racked. The database is managed Postgres on Supabase and the app runs on Vercel. What we own is the schema, the code and the data, all of it standard Postgres and TypeScript that moves to any host without a rewrite.
- Building costs more up front than subscribing. It pays back when the workflows are specific to how you sell, as ours are with UPI-only, project-based billing and WhatsApp-first clients, and when owning the data matters to your clients.
Where to start if you're consolidating
- Map the client path, not the tools. Write down every hand-off from enquiry to sign-off, and mark the ones that cross a vendor boundary.
- Move the system of record first. Clients, payments and approvals into one database with RLS from day one; integrations come after.
- Replace workflow hops with triggers and queues. Each one you remove is a failure mode you can now see.
- Make every external input signed and idempotent. Signatures, timestamps, unique external ids.
- Log decisions, not just data. An approval without a timestamped, immutable record is an opinion.
We build this kind of owned operational software for clients too. Our custom invoicing and billing automation work comes from the same codebase, and the Regulatis case study shows the product side of a compliance-heavy SaaS.
Frequently asked questions
Should an agency build its own client portal or use SaaS tools?
Build when your workflows are specific to how you sell and owning client data matters; subscribe when off-the-shelf tools fit. A custom portal pays back when it removes hand-offs between vendors, such as payment confirmation triggering onboarding automatically, and gives you one audit trail. The cost is that you own maintenance and on-call, so build it on standard Postgres and TypeScript that any engineer can run.
How do you automate client onboarding after a payment without Zapier or n8n?
Use a database trigger. When the payment row's status enters the verified set, an AFTER UPDATE trigger posts to your own API route through pg_net, which sends only after the transaction commits. The route re-reads the payment, stamps an idempotency lock and emails the portal sign-in link. Firing on the transition rather than the state stops duplicate emails, and keeping secrets in Supabase Vault keeps them out of the trigger definition.
How do you stop a scheduled email job from sending the same email twice?
Make it a queue with three guards: a unique constraint per recipient, sequence and step so enqueueing twice is a no-op; a claim query using FOR UPDATE SKIP LOCKED so overlapping runs never pick the same row; and an idempotency key on each send to the email provider. Rows left in 'processing' after a crash should go to a human rather than be re-sent automatically.


