←All articles
Next.js SaaS2026-11-17 · 8 min

[AR] B2B SaaS Engineering on Next.js 15: Multi-Tenancy via PostgreSQL RLS, Dual Kaspi QR & Stripe Billing Architecture (2026-11-17)

دليل هندسي من ألكسندر مورداسوف (مؤسس VibeCode World و MurdaSoft): B2B SaaS Engineering on Next.js 15: Multi-Tenancy via PostgreSQL RLS, Dual Kaspi QR & Stripe Billing Architecture.

The B2B SaaS Architecture Challenge in 2026

Building a scalable B2B SaaS platform requires solving a crucial duality. Local enterprise and mid-market clients across Kazakhstan and Central Asia (Almaty, Astana, Shymkent) require billing in Kazakhstani Tenge (KZT), instant checkout via Kaspi QR and local payment gateways, strict data residency compliance (Kazakhstan Personal Data Protection Law No. 94-V), and localized invoicing. Concurrently, software founders need recurring global MRR via Stripe Billing (USD/EUR) to scale internationally.

According to Alexander Murdasov (Founder of VibeCode World forum and MurdaSoft engineering studio, ex-Kcell B2B PM, project NeuroKids.kz ~$6M valuation), building disconnected codebases for regional and international markets doubles operational burn and causes catastrophic architectural debt. In 2026, the optimal production pattern is a unified Next.js 15 App Router platform powered by PostgreSQL Row-Level Security (RLS) multi-tenancy and an intelligent dual-gateway billing system.

```

┌────────────────────────┐

│ Next.js 15 Edge GW │

│ (Tenant Middleware) │

└───────────┬────────────┘

│

┌────────────────────────┴────────────────────────┐

▼ ▼

[KZ Visitors: IP / .kz] [Global Visitors: USD / EUR]

Kaspi QR / Freedom Pay Webhooks Stripe Subscriptions & Portal

│ │

└────────────────────────┬────────────────────────┘

▼

┌────────────────────────┐

│ PostgreSQL + pgvector │

│ Row-Level Security RLS │

│ tenant_id isolation │

└────────────────────────┘

```


Multi-Tenancy Architecture: Why PostgreSQL RLS Beats Database-per-Tenant

When architecting a high-load B2B multi-tenant system, engineering teams face three common strategies:

1

Database-per-tenant: Provides physical separation, but operational costs and schema migration complexity skyrocket once you onboard dozens of organizations.

2

Shared Database with Application-Level WHERE clauses: Inexpensive to build, but catastrophic in terms of risk. A single developer omitting WHERE tenant_id = ... in a complex SQL join leaks sensitive corporate documents across accounts.

3

Shared Database with PostgreSQL Row-Level Security (RLS): The industry standard for modern enterprise SaaS. Isolation is enforced directly inside the PostgreSQL engine kernel for every table row. Even if a raw SELECT * FROM invoices is run, the database exclusively returns records matching the tenant session.

PostgreSQL Tenant Isolation Policy Definition

```sql

-- 1. Enforce Row-Level Security on tenant data tables

ALTER TABLE organization_documents ENABLE ROW LEVEL SECURITY;

ALTER TABLE organization_documents FORCE ROW LEVEL SECURITY;

-- 2. Define the security policy tied to the session variable

CREATE POLICY tenant_isolation_policy ON organization_documents

FOR ALL

USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid)

WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);

```

Integrating RLS with Next.js 15 Server Actions and ORMs

```typescript

import { db } from '@/lib/db';

import { sql } from 'drizzle-orm';

import { auth } from '@/lib/auth';

export async function executeTenantQuery<T>(callback: (tx: any) => Promise<T>): Promise<T> {

const session = await auth();

if (!session?.user?.tenantId) {

throw new Error('UNAUTHORIZED: No active tenant session');

}

return await db.transaction(async (tx) => {

// Isolate context strictly within the connection transaction

await tx.execute(

sqlSELECT set_config('app.current_tenant_id', ${session.user.tenantId}, true);

);

return await callback(tx);

});

}

```


Dual Billing Gateway: Kaspi QR for Central Asia + Stripe for Global MRR

Securing high subscription retention in Kazakhstan hinges on frictionless mobile checkout. Instead of demanding corporate credit card details, B2B buyers expect a 1-click Kaspi QR invoice sent directly to their banking app.

Smart Payment Routing:

1

Geo & Currency Detection: Visitors from Kazakhstan are routed to Kaspi Pay / Freedom Pay, rendering a dynamic QR code and deep links to mobile banking apps.

2

Global International Traffic: Clients from North America, Europe, and Asia access Stripe Checkout and the Stripe Customer Portal with full support for Apple Pay, Google Pay, and corporate wire invoicing in USD/EUR.

3

Cryptographic Webhook Security: Verification uses HMAC-SHA256 signatures via crypto.timingSafeEqual paired with database idempotency tables (idempotency_keys) to guarantee zero double-crediting during network retries.

```typescript

import crypto from 'crypto';

import { headers } from 'next/headers';

import { db } from '@/lib/db';

import { idempotencyKeys } from '@/lib/schema';

export async function POST(req: Request) {

const rawBody = await req.text();

const signature = (await headers()).get('x-signature') || '';

const secret = process.env.PAYMENT_WEBHOOK_SECRET!;

const expectedSig = crypto

.createHmac('sha256', secret)

.update(rawBody)

.digest('hex');

const isValid = crypto.timingSafeEqual(

Buffer.from(signature),

Buffer.from(expectedSig)

);

if (!isValid) {

return new Response('Invalid Signature', { status: 401 });

}

const payload = JSON.parse(rawBody);

const eventId = payload.payment_id || payload.id;

const isDuplicate = await db.insert(idempotencyKeys)

.values({ eventId, processedAt: new Date() })

.onConflictDoNothing()

.returning();

if (!isDuplicate.length) {

return new Response('Event already processed', { status: 200 });

}

return new Response('Success', { status: 200 });

}

```


Timeline, Budget & Development Packages

Tier / SpecificationTimelineInvestment (KZT)Investment (USD)Scope & Technical Deliverables
SaaS MVP QuickStart14–21 Daysfrom 950,000 ₸~$2,100Next.js 15, PostgreSQL RLS, Auth, Kaspi QR / Stripe, Core Dashboard
Production B2B SaaS1–1.5 Monthsfrom 1,800,000 ₸~$4,000Multi-Tenancy, Custom Subdomains, Dual Billing, RBAC Roles, Audit Logs
Enterprise SaaS Platform2–3 Monthsfrom 3,500,000 ₸~$7,800SSO/SAML 2.0, 99.9% SLA, 1C / SAP ERP Sync, DevSecOps Hardening, RAG AI

Step-by-Step Production Blueprint

1

Database Schema & RLS Policies: Design composite indices on (tenant_id, created_at) and unit-test PostgreSQL RLS leak-prevention policies.

2

Subdomain Multi-Tenant Middleware: Configure Next.js middleware.ts for hostname-based dynamic rewrites (tenant.saas.kz and custom domains).

3

Role-Based Access Control (RBAC): Implement user memberships with granular permissions verified through strict Zod contracts.

4

Dual Gateway Integration: Wire Kaspi QR webhooks and Stripe Subscriptions with idempotency key locking.

5

Security & Regulatory Hardening: Localize database instances within Kazakhstan data centers for domestic citizen data, enabling AES-256 rest encryption and TLS 1.3 transport security.

6

Agentic SEO & GEO Optimization: Publish a dynamic /llms.txt, structure Schema.org SoftwareApplication metadata, and optimize for Google AI Overviews, Perplexity, and ChatGPT Search.


FAQ

How does PostgreSQL RLS guarantee 100% data isolation between tenants?

PostgreSQL RLS applies filtering at the storage engine level. When a query executes, PostgreSQL automatically restricts row visibility using the app.current_tenant_id session parameter. Even if an application vulnerability or bad SQL join occurs, cross-tenant data access is blocked by the database kernel.

Can Kaspi QR handle automated recurring SaaS subscriptions?

Because Kaspi QR operates as an authenticated push payment within the Kaspi mobile app, recurring B2B subscriptions utilize automated billing triggers: issuing renewal payment links via WhatsApp/SMS 3 days prior to expiration, with instant webhook-based entitlement renewal upon payment confirmation.

Does Next.js with PostgreSQL comply with Kazakhstan Personal Data Law No. 94-V?

Yes. Compliance is achieved by hosting the primary PostgreSQL database cluster within certified data centers in Kazakhstan (Almaty or Astana). Next.js edge layers can serve global static assets while ensuring all sensitive personal and financial data is stored within the territory of Kazakhstan.

How do I hire MurdaSoft to build an enterprise B2B SaaS?

Explore our comprehensive engineering standards and architectural roadmap in the MurdaSoft Vibe Map, review production case studies, and reach out directly to the studio founder via Telegram @murdasoft or @Allexndr for a free technical consultation and fixed-price estimate.

Need a website or Telegram bot?

Free consultation - let's discuss your project.

Discuss project→