VitaSetu / CareWell — Healthcare Platform

A patient-owned healthcare platform where records travel with the patient between clinics, so tenant isolation and patient consent are enforced by PostgreSQL row-level security instead of relying on every query remembering a where clause.

Stack:
NestJS 11, Fastify 5, Next.js 15, Expo 57, TypeScript, PostgreSQL 17, Prisma 6, Zod
Status:
In development
Deep Dive:
Read DB Boundaries Blog

Overview

Most multi-tenant apps filter tenant rows in application services, trusting that every developer writes the exact filter under every future deadline. For medical records owned by a patient rather than a single clinic, that assumption is fragile.

In VitaSetu / CareWell, clinical data keys on the patient and moves across organizations. A patient who shares "medications and allergies only" with a clinic must expose exactly that scope, while the UI must clearly distinguish "withheld by consent" from "none recorded" so a prescribing clinician never mistakes hidden history for an empty chart.

191 RLS PostgreSQL row-level security policies across 36 migrations
1,144 Passing Vitest & Playwright checks (as non-owner role)
4 Layers Session JWT → Org verify → Permission keys → DB RLS
14 ADRs Canonical decision records + 5-state honest feature tracking

My contribution

  • Two-connection database split & boot refusal: Table-owner connection for migrations, identity, audit, and outbox draining; non-bypass app_user connection for every request query, with a boot check that refuses startup if BYPASSRLS is present.
  • Consent inside SQL predicates: app.has_consent_for(patient, org, category) evaluated directly in row-level policies alongside organization/facility/unit hierarchy scopes.
  • Four-layer authorization: Session-backed tokens, server-verified organization membership, central permission keys, and row-level security underneath.
  • Race-safe scheduling: Shared pure-function slot calculation across API, Next.js, and Expo, paired with pg_advisory_xact_lock to serialize overlapping slot writes.
  • Brokerless transactional outbox: Events written inside the same Postgres transaction as domain changes and drained with SELECT ... FOR UPDATE SKIP LOCKED, exponential backoff, and dead-lettering.
  • Hardened identity & append-only audit: Hashed OTPs, scrypt passwords with constant-time comparison, rotating refresh tokens with reuse chain revocation, and atomic audit commits.

Architecture

1. Four-Layer Defense & Two-Connection Split

Diagram 1: Request Authorization Path & PostgreSQL Role Isolation Boot-Time BYPASSRLS Refusal
VitaSetu Four-Layer Authorization and Two-Connection Postgres Split Shows Next.js web and Expo mobile clients sending context headers into NestJS Fastify API which enforces rate limiting, session-backed JWT, server-verified org membership, permission keys, and Zod schemas, then queries PostgreSQL via non-owner app_user enforcing 191 RLS policies and consent predicates, while a separate owner connection handles migrations, append-only audit, and the SKIP LOCKED outbox worker. Web & Mobile Next.js (httpOnly) Expo (Keychain) NestJS API (22 Modules) 1. JWT + Live Session Row 2. Server-Verified Org + Context 3. @RequirePermissions + Zod app_user 4. POSTGRESQL 17 RLS (NO BYPASSRLS) set_config(person_id, org_id, is_local) 191 Row-Level Security Policies app.has_consent_for(patient, org, category) Forgotten WHERE clause returns 0 rows PRIVILEGED OWNER CONNECTION (ISOLATED) Migrations · Pre-Actor Auth · Append-Only Audit · SKIP LOCKED Outbox Worker Pre-signed S3/MinIO URLs move files directly from browser/device, never through API memory.
Splitting DATABASE_URL (non-bypass app_user) from DATABASE_OWNER_URL guarantees that application queries can never silently disable row-level policies.
Clinical Hazard

Silent empty list for withheld allergies

If an API returns [] for both "patient has zero allergies" and "patient withheld allergy records", a clinician may prescribe a dangerous medication.

Clinical Safety UI

Explicit "withheld" vs "none recorded" state

Consent scope checks surface an explicit withheld signal distinct from absent records so doctors know data exists behind patient consent.

2. Race-Safe Booking & Brokerless Outbox

Diagram 2: Advisory-Lock Booking & Single-Transaction Outbox Zero Message-Broker Drift
VitaSetu Booking Concurrency and Transactional Outbox Shows concurrent patients requesting same slot, pure slot calculator from shared Zod contracts, transaction-scoped advisory lock per practitioner and window, single Postgres commit writing appointment, fee snapshot, audit row, and outbox row, and SKIP LOCKED worker draining reminders and notifications with exponential backoff. Shared Pure Slots Packages/contracts Web · Expo · API Tested in ms without a database Advisory Lock pg_advisory_xact_lock Keyed to practitioner + time window only Second writer waits, then sees slot taken Atomic Commit 1. Appointment + Fee 2. Audit Row 3. Outbox Event (available_at reminders) Outbox Worker SKIP LOCKED Exponential backoff Dead-letter queue Backlog metrics
Using Postgres for both concurrency locking and event outbox removes an entire external broker failure seam at this platform's scale.

Engineering decisions

Enforce access in the database, not in every query

Problem: Application-level tenant filters hold only until someone writes one new endpoint under deadline without reading the threat model.

Approach: 191 PostgreSQL row-level security policies evaluated against actor identifiers set on the transaction, driven by a non-bypass app_user role with a boot-time refusal if misconfigured. A forgotten filter returns zero rows.

Tradeoff: Policy SQL requires careful migration reviews and tests must run as app_user, paying engineering discipline upfront for a database-level guarantee.

Prevent double bookings with a lock, not a check

Problem: Read-then-write availability checks fail under concurrent taps, and unique keys alone cannot express overlapping appointment intervals.

Approach: Shared pure-function slot generation plus a transaction-scoped advisory lock (pg_advisory_xact_lock) keyed to practitioner and time window, paired with effective-dated fee snapshots.

Tradeoff: Serializes writes per practitioner window only, verified by an integration test executing concurrent database transactions.

Publish events through a Postgres outbox instead of adding Kafka

Problem: Dual-writing to a DB and an external message broker creates the "committed but unpublished" split-brain failure.

Approach: Write outbox events in the same transaction as business mutations and drain them via SELECT ... FOR UPDATE SKIP LOCKED, reusing available_at for scheduled appointment reminders.

Tradeoff: Polling introduces slight latency and does not target Kafka-scale throughput, which is explicitly documented as an architectural decision record.

Tips & tricks from building VitaSetu

TIP 01 · RLS TESTING

Never run RLS tests as the table owner

Table owners bypass PostgreSQL row-level security silently, making green integration suites meaningless.

Rule: Run every isolation test as app_user and assert API boot refusal if BYPASSRLS is detected.

TIP 02 · AUTH TOKENS

Revoke the whole refresh chain on token reuse

If an old rotated refresh token appears again, either the user or an attacker replayed a stolen token.

Rule: Revoke the entire session chain on reuse detection and return byte-identical responses for wrong password vs unknown account.

TIP 03 · SHARED DOMAIN

Put pure time/slot/fee math in one shared package

Duplicating slot math across web, mobile, and API guarantees calendar drift and edge-case bugs.

Rule: Share Zod schemas and pure domain functions across NestJS, Next.js, and Expo so breaking contract edits fail CI at compile time.

TIP 04 · HONEST STATUS

Track work with a five-state evidence vocabulary

Marking UI screens "done" when their downstream adapters are still mocked hides integration debt.

Rule: Label every component explicitly as Implemented, Mocked, Scaffolded, Deferred, or Blocked.

Validation

  • 1,144 checks across shared Zod contracts, database isolation (21 DB + 30 API cross-tenant tests), NestJS unit/integration suites, Next.js web tests, and Playwright E2E journeys.
  • Cross-tenant consent verified across four states: before consent, active consent, after revocation, and after expiry.
  • Negative structural matrix covers wrong facility, sibling unit, expired staff assignment, suspended facility, and dropped work-context headers.
  • Concurrent booking race tested with genuine simultaneous transactions.

Scope of the claim. These checks verify that the written RLS policies, authorization rules, and booking locks hold for tested cases. They are not an external security audit, penetration test, or regulatory healthcare compliance certification.

Outcome

  • Tenant isolation and consent boundaries hold even for newly added queries.
  • Patient records move across clinics while keeping withheld clinical data clearly labeled as withheld rather than missing.
  • Outpatient consultations, signed versioned prescriptions, laboratory loops, and invoice settlements run end-to-end across web and mobile contracts.
  • Deployed on Render and Vercel with owner/app connection splits preserved and migrations applied on boot.

Current status and limitations

  • Identity currently runs on a development provider; production IdP sits behind a port as a mock.
  • Payment gateway adapter is mocked; billing invoices and settlements are real, while live money collection awaits commercial gateway selection.
  • Video consultation is deferred with candidate providers only listed.
  • Notification outbox handlers run, while live email/SMS channels remain unwired (SMS blocked on DLT registration).
  • Laboratory and settlement modules carry unit tests; full integration suites remain pending.
  • The 57-screen Expo app typechecks and hits tested API contracts, but has not been launched on a physical device from this repository.
  • Privileged-role MFA, re-authentication before irreversible clinical actions, distributed rate limiting, and break-glass emergency access remain open security tasks.

Private repository; no public demo. I am happy to walk through the 191 RLS policies, two-connection split, or transactional outbox in an interview.

Related reading & case studies

Email Sunny.work70@gmail.com or connect on LinkedIn.

Back to selected projects Download resume (PDF)