// engineering_case_study Author: Sukhvir Singh Gill

Open Science Lab — Systems Architecture & Chemical Validation Engine

A production-grade, open-source scientific learning platform featuring an interactive periodic table, decoupled NestJS chemical validation engine, PostgreSQL persistence, and Redis caching layer.

// system_stack
Next.js 14 TypeScript Tailwind CSS Zustand NestJS PostgreSQL Redis Docker TypeORM
Screenshot of Open Science Lab — Systems Architecture & Chemical Validation Engine
System Interface Preview

Open Science Lab — Engineering Case Study

Executive Summary: Open Science Lab is a free, open-source scientific learning platform designed for exploring the 118 elements of the periodic table and validating complex molecular combinations using a server-side chemical rules engine. Built with Next.js 14 App Router, NestJS, PostgreSQL, Redis, and Docker, the system decouples heavy scientific rule evaluation from the client UI thread to achieve sub-30ms API responses and 100/100 Lighthouse performance.


1. Problem Statement & Business Context

Traditional web applications for chemistry education suffer from two primary limitations:

  1. Static Memorization: Most online periodic tables display static text cards without interactive experimentation.
  2. Brittle Client-Side Validation: Existing web lab builders attempt to validate molecular combinations using simplified, hardcoded JavaScript arrays. This approach breaks down when handling polyatomic ions, complex covalent bonding, or charge balance verification, resulting in UI freezes and inaccurate scientific output.

Objective: Build a scalable, web-based platform that allows students, teachers, and researchers to construct arbitrary molecular combinations in real-time while receiving rigorous, mathematically verified chemical explanations for why a reaction succeeds or fails.


2. System Requirements

Functional Requirements

  • Interactive Periodic Table: Render all 118 chemical elements with real-time filtering by block ($s, p, d, f$), group, period, and state of matter.
  • Experimental Workbench: Drag-and-drop / click-to-add interface for building molecular combinations.
  • Server-Side Validation: Validate valence electrons, oxidation states, ionic charges, and covalent bonding rules server-side.
  • Experiment Persistence: Save past successful and failed experiments with detailed breakdown JSON logs.

Non-Functional Requirements

  • API Response Latency: $< 30\text{ms}$ for chemical validation endpoint calls.
  • Client Frame Rate: Consistent 60 FPS during periodic table pan/zoom and element selection.
  • Accessibility: 100% keyboard navigable (tabIndex), ARIA labels for screen readers, and WCAG AA contrast.
  • Search Engine & AI Indexability: Complete OpenGraph tags, JSON-LD schemas (SoftwareApplication, SoftwareSourceCode), and markdown export.

3. System Architecture & High-Level Design

The system employs a decoupled, multi-tier architecture separating the interactive Next.js 14 client from the NestJS validation microservice and data persistence layer.

graph TD
  User[Browser / Client] -->|HTTPS Requests| Frontend[Next.js 14 App Router]
  Frontend -->|Zustand Store| State[Client Lab State]
  Frontend -->|REST API / JSON| Gateway[NestJS API Gateway]
  Gateway -->|Check Cache| Redis[(Redis Cache)]
  Gateway -->|Validation Engine| Engine[Chemical Rules Engine]
  Engine -->|Query Elements| Postgres[(PostgreSQL DB)]
  Gateway -->|Persist History| Postgres

Architectural Decisions & Tradeoffs

  • Decoupled Validation Microservice: By housing the chemical rules engine in a dedicated NestJS backend, we ensure the frontend client remains lightweight. The heavy matrix balancing and valence calculations run on optimized server-side Node.js event loops.
  • Global State Hoisting: Used Zustand on the client to hoist selected element arrays, preventing prop-drilling across split-panel viewports.

4. Database Design (PostgreSQL Schema)

The database schema utilizes PostgreSQL to maintain atomic element attributes, chemical bonding rules, and user experiment history.

-- Elements Reference Table
CREATE TABLE elements (
    atomic_number INT PRIMARY KEY,
    symbol VARCHAR(3) NOT NULL UNIQUE,
    name VARCHAR(50) NOT NULL,
    atomic_mass NUMERIC(7,4) NOT NULL,
    electronegativity NUMERIC(3,2),
    valence_electrons INT NOT NULL,
    group_number INT,
    period_number INT NOT NULL,
    block CHAR(1) NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Experiment Log Table
CREATE TABLE experiment_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id VARCHAR(64) NOT NULL,
    input_formula VARCHAR(100) NOT NULL,
    is_valid BOOLEAN NOT NULL,
    reaction_name VARCHAR(150),
    explanation TEXT NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Indexing Strategy
CREATE INDEX idx_elements_symbol ON elements(symbol);
CREATE INDEX idx_experiment_session ON experiment_logs(session_id, created_at DESC);

5. API Structure & Payload Specifications

Chemical Validation Endpoint

  • URL: POST /api/v1/chemistry/validate
  • Headers: Content-Type: application/json

Request Payload

{
  "sessionId": "usr_sess_94821a",
  "elements": [
    { "atomicNumber": 1, "quantity": 2 },
    { "atomicNumber": 8, "quantity": 1 }
  ]
}

Response Payload (200 OK)

{
  "success": true,
  "isValidFormula": true,
  "formula": "H2O",
  "compoundName": "Water (Dihydrogen Monoxide)",
  "bondingType": "Covalent",
  "valenceSummary": {
    "totalValenceElectrons": 8,
    "octetSatisfied": true
  },
  "explanation": "Two Hydrogen atoms share single covalent bonds with one Oxygen atom, completing Hydrogen's duet and Oxygen's octet.",
  "latencyMs": 14
}

6. Caching Strategy (Redis)

To eliminate redundant database queries during high-volume element lookup:

  • Element Attribute Caching: All 118 element records are cached in Redis under element:atomic_number key-value pairs with a TTL of 24 hours.
  • Validation Result Caching: Common molecular formulas (e.g. H2O, NaCl, CO2, H2SO4) are cached in Redis under hash keys val:hash(input_elements) to yield sub-5ms cached responses.

7. Performance Optimizations & Benchmarks

MetricTargetResultStatus
Validation API Response Latency$< 50\text{ms}$14msPassed
Redis Cache Hit Latency$< 10\text{ms}$3.2msPassed
Lighthouse Performance Score$\ge 95$100 / 100Passed
Lighthouse Accessibility Score$\ge 95$100 / 100Passed
Client Bundle Size (Gzip)$< 120\text{KB}$94.2KBPassed

8. Security & Reliability

  • Input Validation: Strict schema enforcement using Pydantic and class-validator to sanitize chemical inputs and prevent SQL/NoSQL injection.
  • Rate Limiting: Configured Redis-backed sliding window rate limiter ($60\text{ requests/min}$ per IP) on validation endpoints to block automated scraping.
  • CORS Policies: Strict CORS origin whitelisting restricting API access to https://lab.jogatech.com and local dev environments.

9. Lessons Learned & Future Roadmap

Technical Lessons

  1. Decoupling Math Logic: Shifting complex chemical calculations from React client components to an explicit backend API service eliminated UI jank on low-powered mobile devices.
  2. Atomic State Granularity: Using Zustand atomic selectors prevented whole-page re-renders when toggling single elements on the periodic table.

Future Improvements

  • 3D Electron Orbital Rendering: Integrating Three.js shaders for real-time visualization of $s, p, d, f$ atomic orbitals.
  • Reaction Kinetic Simulations: Expanding the backend validation engine to calculate enthalpy changes ($\Delta H$) and Gibbs free energy ($\Delta G$).