PAISAPAIDCase study · Freelance client project

Multi-tenant loan distribution platform with white-label brands

A NestJS and Next.js platform where each white-label brand runs its own site and agent network on a shared, tenant-isolated backend.

By · Updated

Client
PAISAPAID
Role
Sole developer (freelance)
Timeline
Oct 2026 – present
Stack
  • TypeScript
  • NestJS 11
  • Next.js 16
  • PostgreSQL
  • Prisma
  • Redis
  • BullMQ
  • Nx
  • Caddy
  • Docker Compose
  • GitHub Actions

A note on the UI. The look and layout of every screen were set by the client, so this project doesn't represent my own UI design. The case study is about the engineering underneath.

Collage of the platform: the staff console dashboard with lead charts, a brand website, and two phone screens of a brand's website and an agent's panel.
Screens from the demo build, with invented brands and data. UI design set by the client.
01

Overview

Client
PAISAPAID, a loan and financial-products distribution business in India.
My role
Sole developer. I designed the architecture and built the backend, both frontends (to the client's UI design), the database, the CI/CD pipeline and the server setup.
Timeline
Six weeks so far, from the first commit on 12 October 2026 to 20 November 2026. It runs in production on a staging-first pipeline and is still in active development.
Stack
TypeScript across the board. NestJS 11 API and worker, two Next.js 16 apps, PostgreSQL with Prisma, Redis with BullMQ, an Nx monorepo, Caddy, Docker Compose and GitHub Actions.
02

The problem

PAISAPAID distributes loans through agents who bring in customers. The business wanted to let other companies run their own branded versions of it: their own domain, website and agents, while PAISAPAID's staff process every lead and pay commission down the chain.

That means one system holding many brands' customer data, KYC documents and money. A bug that shows one brand's lead to another brand, or one rounding error in a payout, would be a serious problem for the client.

03

What I built

There are five roles in two apps. Platform staff (a Root Super Admin and Employees with 11 switchable permissions) use a console on one fixed domain. Brand admins, agents and sub-agents use the brand app, which serves every brand's website and panels and picks the brand from the host name.

Agents submit leads through dynamic forms, or through a short Quick Apply form that shows only the lenders serving the customer's pincode. Employees work a queue limited to their products. They raise document queries, move statuses, record disbursements and enter commission. Lenders' Excel reports are reconciled against leads. Brand admins manage their website, agents, payouts and, where it is switched on, API keys and webhooks for their own systems.

The API has 751 routes in 156 controllers. A worker runs nine BullMQ queues for email, domain checks, webhooks, file retention and notifications.

Architecture: users reach Caddy on one Docker Compose server, which routes to two Next.js apps and the NestJS API. The API checks host, access policy and tenant scope before PostgreSQL. Redis and a worker handle jobs and webhooks, private files sit in an S3-compatible store, and backups go off-site.
Architecture: one Docker Compose server, two Next.js apps, the NestJS API and its worker.Open full size (SVG, new tab)
04

Three hard problems

1. Keeping brands apart

I didn't want isolation to depend on every developer remembering a where clause.

How it works

All database access goes through one helper with three entry points. The plain client refuses the 67 brand-owned tables outright. forTenant(id) is a Prisma extension that adds the brand to every read and write, and refuses nested writes and raw SQL, which it could not check. crossTenant() is for platform roles only. Below that, PostgreSQL enforces it too: 102 relations use composite foreign keys on (tenant_id, id), so a lead cannot point at another brand's agent even if code goes wrong.

Two tests guard the edges. One reads the schema and fails if a table with a tenant_id is not registered. The other walks every API route and fails if one has no access policy. A request for another brand's record answers 404 and writes an audit entry, and 32 integration test files check exactly that.

Simplified sketch, not the production codeTypeScript
// Plain client: brand-owned tables refused
db.client.lead.findMany();

// Brand-scoped: tenantId added to every read
// and write; nested writes and raw SQL refused
db.forTenant(brandId).lead.findMany();

// Platform roles only; the caller checks
// permission and writes an audit entry
db.crossTenant();
Five layers of tenant isolation, from brand resolution by host name down to PostgreSQL composite foreign keys, with the tests that guard three of them.
Five layers of tenant isolation and the tests that guard them.Open full size (SVG, new tab)

2. Custom domains with HTTPS on first visit

Each brand brings its own domain, so certificates can't be issued up front.

How it works

Caddy issues them on demand, but first asks the API whether the host belongs to a brand. The API only says yes for the console, a known brand domain or its www.. That check sits behind a shared token and is unreachable from outside.

Connecting a domain adds it to Cloudflare through its API, creates DNS-only records and checks every five minutes until the certificate is live, with clear states (Nameservers pending, DNS pending, Verified, Active, Failed).

Simplified sketch, not the production codeTypeScript
// Caddy asks before issuing a certificate
// for a new host (shared token, internal only):
// GET /api/v1/internal/tls/ask?domain=…
const allowed =
  host === CONSOLE_HOST ||
  isBrandDomain(host) ||
  (host.startsWith("www.") &&
    isBrandDomain(host.slice(4)));
// allowed → 204: HTTPS on first visit.
// Anything else gets no certificate.

3. Money that adds up

One rounding error in a payout would be a serious problem for the client.

How it works

Every amount is a BigInt in paise and every rate is in hundredths of a percent, rounded half up exactly. Commission is a ledger: one line per level (platform to brand, brand to agent, agent to sub-agent). The payee, rate and amount never change once written, which a database trigger enforces. A new rate cancels the line and writes another. Payouts record TDS, GST and recoveries, and every total is summed from the lines.

Lenders report outcomes in their own spreadsheets. A saved, versioned column mapping reads each file. Rows are matched by lead ID, tracking ID or mobile number, and flagged when unmatched, ambiguous, duplicated or suspicious. Nothing changes on a lead until an Employee reviews and applies the file.

Simplified sketch, not the production codeTypeScript
// Amounts: BigInt paise.
// Rates: hundredths of a percent.
const commissionPaise = (
  base: bigint,
  bps: bigint,
) => (base * bps + 5000n) / 10000n;
// exact, rounded half up
05

Security

  • Passwords use Argon2id, with a lockout after five failures.
  • Refresh tokens rotate on every use, live in httpOnly cookies scoped to each app, and reusing an old one ends the session.
  • Staff accounts have TOTP two-step sign-in with recovery codes, on by default.
  • KYC files never get a public URL: the API checks access, writes an audit entry and issues its own signed link that works for five minutes.
  • Logs redact PAN, Aadhaar, phone numbers, emails and tokens.
  • The audit log is append-only at the database level.
  • “Login as” uses a single-use, one-minute link and is audited.
  • Webhooks are signed with HMAC-SHA256 and tried up to eight times over about two days.
  • The policy assistant sends the Claude API text only: the policies of one product the user actually sells, with personal details removed.
06

Delivery and ops

The repo is an Nx monorepo with 11 projects. Work goes issue → branch → squash-merged PR into dev, then to staging and main by pull request. CI runs only on staging: a dependency advisory check, a check that no applied migration was edited, lint, typecheck, unit tests, build, database tests and the API integration tests in four parallel shards. It builds seven Docker images at the same time. Production deploys only images that passed on staging, found by matching the exact files, with no rebuild.

Everything runs on one server with Docker Compose; the data network has no route out. Nightly backups of the database and both file stores are encrypted with age and sent off-site, and every deploy takes a backup first. Runbooks cover deploy, rollback, restore, domains, incidents and secrets.

Release path: pull request to dev, dev to staging, CI checks and seven images on staging, the staging server, then main deploying the same images to production.
Release path: production deploys the images that passed on staging.Open full size (SVG, new tab)
07

Results

  • 742

    squash-merged commits on dev since 12 Oct 2026

  • 751

    API routes, none without an access policy

  • 139

    database tables

  • 177

    migrations

  • 485

    test files, 138 of them integration

  • 5

    roles across two apps

  • 742 squash-merged changes on the main development branch since 12 October 2026, 685 of them in the first 30 days.
  • 11 Nx projects, 139 database tables, 73 enums, 177 migrations.
  • 751 API routes: 706 with an explicit access policy, 45 deliberately public, none without one.
  • 485 test files: 138 integration tests against real PostgreSQL and Redis, and 347 unit and component tests, including a Playwright smoke suite for all five roles.
  • 67 brand-owned tables, guarded by the tenant extension and 102 composite foreign keys.
08

What I'd do next

  • Run the Playwright smoke suite in CI against a disposable stack. It runs by hand today.
  • Add PostgreSQL row-level security as one more layer under the Prisma extension.
  • Automate a monthly restore drill to a fresh server, and move file backups from nightly full archives to incremental encrypted sync as storage grows.
09

Screens

A note on the UI. The look and layout of every screen were set by the client, so this project doesn't represent my own UI design. The case study is about the engineering underneath.

Only a few screens are shown, to keep the client's product private. They come from a local database seeded with fake data: invented brands, demo lenders and placeholder documents. Select a screenshot to enlarge it.

  • Two brand websites from the same code
  • A lender report waiting to be applied
  • Audit trail, including refused cross-brand access

Have a multi-tenant SaaS, client portal or fintech backend to build?