Lydia Ng
06 · Case Study / zephyr-scripts/petpal-vetpal
Full-Stack Product Build PostgreSQL · RLS · OpenAI API

PetPal / VetPal

Structured AI Platform for Pet Nutrition & Clinical Dietary Governance

Architecture Paradigms
Data-Rich Platform Secure Express APIs Bounded AI Guidance Multi-Tenant RLS
verified
Foundational Axiom
“AI as one capability inside a data-rich, authenticated product — not as the database or the sole decision layer.”
Dual Role-Based Topology
System Architecture · Blueprint 01

Relational Core & Satellite Domain Topology

Strict separation of schema storage, isolated domain execution micro-modules, and Row Level Security isolation between Owner and Veterinary surfaces.

security Outer Boundary: Multi-Tenant Supabase Auth & Row Level Security (RLS) Isolation Layer
MOD_01 monitor_heart

Health & Condition Tracker

Diagnosed pathologies, renal markers, endocrine status, and chronological clinical history.

Deterministic Checks
MOD_02 query_stats

Weight History & Energy Ledger

Daily energy requirement (DER) calculations, MER formulas, historical trajectory curves.

Dynamic Rest Met. Rate
MOD_03 block

Allergy & Sensitivity Matrix

Direct allergen matching, cross-reactivity flags, and hard ingredient exclusion filters.

Zero Hallucination Gate
Central Hub
PostgreSQL Relational Core

Core Structured Pet Profile & Relational Schema

Canonical source of truth governing species, life stage, body condition scores (BCS 1-9), neutered status, and validated clinical biometric history.

TABLE pets uuid, owner_id, bcs
TABLE health_events pet_id, icd_code, date
TABLE diet_plans der_target, vet_sign_off
TABLE biometrics_log weight_kg, timestamp
TABLE allergen_rules substance_id, severity
SECURITY rls_policies auth.uid() = owner_id
sync_alt Strict Type Safety lock Context Hydration Only database Deterministic Calculations
MOD_04 restaurant_menu

Ingredient & Recipe Engine

Macronutrient calibration, moisture density analysis, and gram-precise portion calculation.

Nutrient Balance
MOD_05 psychology

AI Nutrition Guidance Engine

OpenAI API driven by schema-constrained system prompts. Strictly bounded contextual reasoning.

Context-Injected LLM
MOD_06 & 07 clinical_notes

Vet Clinical Portal & Services

Prescription diet approvals, asynchronous triage, appointment records, and shared audit trail.

Multi-Tenant Workflows
State Synchronization Next.js 15 Server Actions
API Governance Express JSON Schema Guard
Security Primitive PostgreSQL RLS Multi-Role
Intelligence Gate Zero-Unverified Recommendations
Section 01

The Challenge

Why isolated conversational AI fails catastrophically when applied to veterinary metabolic health.

Risk Spectrum
Allium Toxicity Risk Critical
Renal Phosphorus Drift High
Pancreatitis Lipid Breach Fatal

Personalized pet nutrition guidance is fundamentally not a simple chat interaction. It relies on multi-dimensional, longitudinal data: precise biometric progression, diagnosed clinical conditions, life-stage metabolic equations, verified ingredient contraindications, and licensed veterinary sign-offs.

The Flaw of Chat-First Models

Conversational Amnesia & Hallucination

Unbounded large language models treat each query in a vacuum or loosely retain state across messy context windows. In veterinary dietetics, failing to query a pet's stage-3 chronic kidney disease or known allium allergy results in fatal menu recommendations.

The Engineering Reality

Mathematical Precision vs Probability

Daily Energy Requirement (DER) is deterministic: RER = 70 * (weight_kg)^0.75 multiplied by physiological factors. LLMs are probabilistic token predictors, not reliable arithmetic engines.

Comparative Architectural Failure Mode

Standard Generic AI Approach

User prompts: "Can my 8kg terrier eat pork chops?" → LLM responds generically with "Yes, in moderation" without cross-checking the dog's recent pancreatitis flare-up or sodium restriction profile in the clinic database.

PetPal / VetPal Architecture

System queries relational schema → detects acute_pancreatitis_flag = true → blocks pork chop recommendation automatically → routes alternative low-lipid protein options approved by vet.

Section 02

The Thinking

Architectural tenets that position AI strictly as a bounded utility within a verified system.

Core Engineering Postulate

Treat AI as one capability inside a structured application, rather than as the database or the sole decision layer. The application must operate with full mathematical integrity, user sovereignty, and clinical compliance even if the AI subsystem is disconnected.

01 / SCHEMA INTEGRITY

Structured Pet Data Sovereignty

Every attribute—from body condition scoring (BCS) and daily caloric targets to documented allergies—resides in strict relational database tables. Data is never stranded inside arbitrary chat history strings.

Enforced via PostgreSQL constraints
02 / DATABASE DEFENSE

Row Level Security (RLS) Isolation

Clinic multi-tenancy and owner privacy are enforced at the database row level. Owner tokens cannot read unshared clinical notes; clinic staff access is restricted strictly to active patient rosters.

Multi-tenant Supabase Auth integration
03 / APPLICATION BOUNDARIES

Decoupled Tripartite Architecture

Clean separation between the Next.js presentation tier, Express API validation pipelines, and relational storage. Complex caloric arithmetic happens in tested domain libraries, not UI components.

Strict DTO contract validation
04 / CLINICAL GOVERNANCE

Dual-Portal Single Foundation

Pet owners consume accessible nutritional tracking, while veterinary clinicians leverage diagnostic telemetry, prescription diet sign-offs, and treatment logs over identical verified records.

Role-scoped permission views
Section 03

The Solution

Deep dive into the 5 core capability systems designed to deliver structured, high-integrity dietary intelligence.

A cohesive full-stack web application designed for both pet guardians and veterinary healthcare teams. AI does not invent diets; it synthesizes natural language recommendations constrained by verified mathematical recipes and clinical history.

Feature 01 · Biometric Tracking Formula: DER = RER × Factor

Longitudinal Pet Profile & Caloric Ledger

Monitors dynamic weight trajectories over time. Recalculates Resting Energy Requirements (RER) and Daily Energy Requirements (DER) continuously using validated veterinary NRC formulas.

Trajectory: Golden Retriever · 34.2kg · Target: 31.0kg DER: 1,328 kcal/day
Month 0 (35.8 kg) Month 3 (34.2 kg) Target Target: -250 kcal deficit
Dynamic life stage modifiers: Neuter, Age, Inactivity Automatic Adjustment
Feature 02 · Safety Guard Zero Bypass

Allergen & Contraindication Matrix

Hard barrier rule enforcement. Ingested meal suggestions pass through an automatic blacklist validator prior to user presentation.

cancel Bovine Protein Sensitivity
Hard Exclude
cancel Elevated Serum Phosphorus
< 0.6% DM
check_circle Hydrolyzed Salmon Hydrolysate
Verified Safe
Pre-prompt injection filter 100% Deterministic
Feature 03 · AI Guidance Subsystem

Schema-Constrained Prompt Injection

The OpenAI API integration is never exposed to raw, unguided chat prompts. Every query triggers an Express backend pipeline that queries the pet’s SQL record, pulls active lab diagnostics, binds the exact gram limits, and synthesizes instructions into a highly constrained prompt envelope.

system_prompt_builder.ts json_response_format schema_validator.ts
Injected Pipeline Context Envelope Payload Sanitized
{
  "patient_id": "d3b07384-d113-...",
  "caloric_cap_kcal": 1328,
  "hard_exclusions": ["beef", "dairy", "high_sodium"],
  "macronutrient_ratios": { "protein_pct": 28, "fat_pct": 12 },
  "vet_oversight_status": "approved_diet_protocol"
}
arrow_downward OpenAI gpt-4o evaluates within envelope → Returns strictly typed MealPlan DTO
Feature 04 · Owner Interface pets

PetPal: Guardian Self-Service Portal

Streamlined daily management: meal logging, weight updates, treat caloric counters, and intelligible feeding schedules that eliminate guesswork.

  • Instant portion converter based on target kibble density
  • Daily caloric budget meter with treat allowance breakdown
  • AI conversational inquiries backed by verified clinical ledger
Feature 05 · Clinical Workspace medical_services

VetPal: Clinical Oversight & Audit

Role-based dashboard for veterinary staff: review guardian feeding adherence, prescribe specialized therapeutic diets, and sign off on nutritional modifications.

  • Multi-patient clinical triage and compliance telemetry
  • Therapeutic diet approval locks (prescription diets require digital sign-off)
  • Integrated consultation notes with audit-trailed revision logs
Section 04

System Architecture & Stack

Production-grade separation of concerns across presentation, routing, validation, database security, and AI invocation.

TIER 01 · FRONTEND web

Next.js 15 · React Server Components

TypeScript end-to-end. Leverages Server Components for fast server-rendered initial biometrics state, reducing client bundle weight and preventing layout shifts.

TypeScript 5.x Tailwind CSS Server Actions
TIER 02 · BACKEND API hub

Node.js · Express RESTful Engine

Structured domain routing with runtime schema validation (Zod). Enforces request shape integrity, sanitizes telemetry payloads, and acts as the gatekeeper for AI calls.

Express.js Zod DTOs Rate Limiting
TIER 03 · DATA & SECURITY database

Supabase PostgreSQL · RLS Policies

PostgreSQL schema with native Row Level Security. Granular authorization rules enforce that patient records, diagnostics, and meal plans are accessible only to authenticated guardians and certified veterinary clinics.

PostgreSQL Row Level Security Supabase Auth
TIER 04 · AI & INFRASTRUCTURE terminal

OpenAI API · Jest · Docker

Bounded LLM reasoning pipelines. Automated Jest unit and integration test suites validating caloric formulas and security boundaries. Containerized development environments.

OpenAI SDK Jest Test Suite Docker Compose
Section 05

Outcome & Engineering Value

Summary of accomplishments and foundational competencies established by the PetPal / VetPal build.

Architectural Conclusion

PetPal / VetPal stands as a working demonstration of how modern AI capabilities belong inside a structured, authenticated product architecture. By anchoring AI recommendations to a relational schema guarded by multi-tenant Row Level Security and deterministic calculation services, the system eliminates the acute safety risks inherent in chat-first approaches.

Competencies Demonstrated

01

Complex Relational Data Modeling for Multi-Entity Domains

Orchestrated interconnected entities across pet guardians, clinical practices, veterinary surgeons, diagnostic lab events, and dynamic dietary recipes without schema duplication or race conditions.

02

Modular API Design & Clean Separation of Concerns

Structured an Express API with explicit Data Transfer Objects (DTOs), strict runtime payload sanitization, and decoupled domain services ensuring mathematical formulas stay isolated from presentation logic.

03

Authenticated, RLS-Aware Enterprise Data Architecture

Eliminated multitenancy leak vectors by moving authorization logic from high-level application middleware directly down into the database engine via PostgreSQL Row Level Security policies.

04

Full-Stack Product Thinking Balancing UX with Clinical Precision

Bridged everyday consumer empathy (a warm, friction-free interface for pet owners logging meals) with the exacting oversight demanded by medical professionals administering prescription protocols.

05

AI as a Bounded Utility Within a Verified System

Pioneered context-grounded AI meal planning where the LLM is leveraged for natural-language synthesis rather than diagnostic calculation, guaranteeing 100% adherence to clinical constraints.