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 & Veterinary Workflow Exploration

Architecture Paradigms
Data-Rich Platform Validated Express APIs Bounded AI Guidance Multi-Tenant RLS
rule
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
BUSINESS SUMMARY

The workflow problem and what changed

Technical architecture follows below

Organisation & workflow

A full-stack product exploring personalised pet-nutrition guidance and related guardian and veterinary workflows.

What was difficult

Useful guidance depends on structured profiles, conditions, weight, allergies, ingredients, recipes and role-based access—not a single chat exchange.

What changed

The product organises these data and workflow modules inside an authenticated application, with AI used as one bounded capability.

Why it mattered

Recommendations could be connected to structured information, rules and user roles rather than relying on an unguided chatbot as the product.

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

Recorded health conditions, relevant markers and chronological health 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.

Ingredient Exclusion Rules
Central Hub
PostgreSQL Relational Core

Core Structured Pet Profile & Relational Schema

Structured profile record covering species, life stage, body condition scores, neutered status and recorded 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 Rule-Checked Recommendation Inputs
Section 01

The Challenge

Why isolated conversational AI is a poor fit for structured pet-health and nutrition workflows.

Risk Spectrum
Allium Ingredient Conflict Flagged
Renal Phosphorus Threshold Review
Lipid Threshold Conflict Blocked by rule

Personalized pet-nutrition guidance is not a simple chat interaction. It depends on structured profile history, recorded conditions, life-stage calculations, ingredient constraints and review status.

The Flaw of Chat-First Models

Conversational Amnesia & Hallucination

General language models may treat each query in isolation or rely on incomplete conversational context. A nutrition workflow therefore needs to check recorded conditions and ingredient constraints before presenting a suggestion.

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 the structured profile → detects a recorded condition flag → blocks a conflicting suggestion → routes the item for an alternative or review.

Section 02

The Thinking

Architectural principles that position AI as a bounded utility within a structured system.

Core Engineering Postulate

Treat AI as one capability inside a structured application, rather than as the database or sole decision layer. Core calculations, access rules and structured data remain separate from the AI subsystem.

01 / SCHEMA INTEGRITY

Structured Pet Data Sovereignty

Key attributes—from body condition scoring and caloric targets to documented allergies—are stored in relational tables rather than relying only on chat history.

Enforced via PostgreSQL constraints
02 / DATABASE DEFENSE

Row Level Security (RLS) Isolation

Row-level access policies scope guardian access to their records and clinic-role access to assigned records.

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 use nutritional tracking while vet-facing roles can review health notes, diet-related workflows and activity history over the same structured records.

Role-scoped permission views
Section 03

The Solution

Deep dive into five capability areas designed to support structured pet-nutrition guidance workflows.

A full-stack web application designed for pet guardians and vet-facing workflows. AI synthesis is prompted with stored recipe rules and profile history, while calculations remain outside the language model.

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

Longitudinal Pet Profile & Caloric Ledger

Tracks weight history over time and applies stored Resting Energy Requirement (RER) and Daily Energy Requirement (DER) 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 Backend Validation

Allergen & Contraindication Matrix

Rule-based exclusion checks compare meal suggestions with stored ingredient and allergy constraints before presentation.

cancel Bovine Protein Sensitivity
Hard Exclude
cancel Elevated Serum Phosphorus
< 0.6% DM
check_circle Hydrolyzed Salmon Hydrolysate
Allowed by stored rule
Pre-prompt injection filter Rule-based filter
Feature 03 · AI Guidance Subsystem

Schema-Constrained Prompt Injection

Requests pass through an Express backend that retrieves the relevant profile record, applies stored limits and supplies structured context to the language model.

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

Daily management features include meal logging, weight updates, treat counters and feeding schedules based on stored profile information.

  • Portion converter based on target kibble density
  • Daily caloric budget meter with treat allowance breakdown
  • AI conversational inquiries backed by stored profile and health data
Feature 05 · Clinical Workspace medical_services

VetPal: Clinical Oversight & Audit

Role-based dashboard concept for vet-facing users to review feeding records, diet-plan information and proposed nutritional modifications.

  • Multi-patient review and activity tracking
  • Diet-plan review states and approval workflow concepts
  • Integrated notes with timestamped revision history
Section 04

System Architecture & Stack

Separation of concerns across presentation, routing, validation, database access 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 scope records and meal plans to authenticated guardians and authorised clinic roles.

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

OpenAI API · Jest · Docker

Bounded AI request pipelines. Jest unit and integration tests cover stored formulas and authorization behaviour. Containerized development environments support repeatable setup.

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

Modelled related entities across pet guardians, clinic roles, health events and dietary recipes using relational schemas and scoped services.

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 Data Architecture

Moves record-access rules closer to the data layer through PostgreSQL Row Level Security policies.

04

Full-Stack Product Thinking Balancing UX with Structured Domain Rules

Combined an approachable interface for pet owners logging meals with structured review workflows for vet-facing roles.

05

AI as a Bounded Utility Within a Structured System

Demonstrates context-grounded meal-planning guidance where the language model supports natural-language synthesis while calculations and stored constraints remain outside the model.

NEXT STEP

Have a similar workflow or systems problem?

If AI needs to work inside a structured, authenticated product rather than as a standalone chatbot, we can map the data, rules, and user workflows first.

Discuss a workflow problem