RippleCore
Project

RippleCore Product Requirements Document

Comprehensive PRD for the RippleCore social impact evidence platform

RippleCore: Comprehensive Product Requirements Document

Unified Social Impact Evidence Platform

Version 4.1 - Updated Technical Implementation
Document Type: Master PRD with Technical Specifications
Date: October 2025 Classification: Confidential - Development & Leadership Teams


Executive Summary

Product Vision

RippleCore transforms employee wellbeing and community engagement into verified, compliance-ready evidence packages through radical simplicity and inclusive design. The platform uniquely balances internal culture health (kindness, wellbeing, engagement) with external social impact (volunteering, donations, community benefit), creating authentic evidence for ESG compliance while making social impact measurement a natural part of daily work life.

Core Value Proposition

"When people feel good inside, they do good outside. When companies have good culture, they create compliance-ready evidence."

Key Differentiators

  1. Evidence, Not Documents: We collect and verify data; experts build compliance strategy
  2. 30-Second Rule: Any action completes in under 30 seconds
  3. All We Can Integration: 10% of revenue funds global school programmes
  4. Multi-Stakeholder Ecosystem: Companies, consultants, charities, councils on one platform
  5. AI-Powered Localisation: 23+ languages with culturally-intelligent adaptation

Target Outcomes

  • For Employees: Simple, meaningful engagement that takes seconds, not minutes
  • For Companies: Authentic compliance evidence without administrative burden
  • For Consultants: Portfolio-wide insights with white-label capabilities
  • For Society: Verified social impact with global reach through All We Can

1. Product Strategy & Market Position

1.1 Market Opportunity

Market Size:

  • Total Addressable Market: €15B (European ESG software market)
  • Serviceable Addressable Market: €3B (Social impact measurement)
  • Serviceable Obtainable Market: €300M (5-year target)

Regulatory Drivers:

  • CSRD affecting 50,000+ EU companies from 2024
  • UK Social Value Act requiring public sector suppliers to demonstrate impact
  • B-Corp certification growing 30% annually
  • Section 172 requiring stakeholder consideration evidence

1.2 Competitive Landscape

Current Solutions Fall Short:

  • Enterprise ESG Platforms: Complex, expensive, focused on reporting not engagement
  • Survey Tools: Create fatigue, lack verification, miss daily impact
  • Volunteer Platforms: Single-purpose, no holistic view
  • Wellbeing Apps: Consumer-focused, lack compliance framework

RippleCore's Unique Position:

  • Only platform balancing internal culture with external impact
  • Evidence-first approach vs document generation
  • Multi-stakeholder verification ecosystem
  • Global impact connection through All We Can

1.3 Product Strategy

Phase 1: Foundation (Months 1-6)

  • Core evidence modules (kindness, volunteering, donations)
  • 5 languages, UK + DACH markets
  • 25 enterprise clients, €2M ARR

Phase 2: Expansion (Months 7-12)

  • Full compliance frameworks
  • 15 languages, EU-wide coverage
  • 100 clients, €10M ARR

Phase 3: Intelligence (Months 13-18)

  • Predictive analytics and AI insights
  • 23+ languages, global capability
  • 300 clients, €30M ARR

Phase 4: Leadership (Months 19-24)

  • Market-leading platform
  • Advanced verification (blockchain optional)
  • 500+ clients, €50M ARR

2. User Personas & Journey Maps

2.1 Primary Personas

Emma - Employee (Evidence Generator)

  • Context: Marketing manager, hybrid worker, limited time
  • Needs: Quick logging, meaningful impact, no training required
  • Journey: Morning kindness → lunch volunteering → evening reflection
  • Success: <30 seconds per interaction, visible impact

James - ESG Champion (Evidence Consumer)

  • Context: Sustainability lead, compliance pressure, multiple frameworks
  • Needs: Quality evidence, one-click reports, audit-ready data
  • Journey: Weekly monitoring → monthly reports → quarterly compliance
  • Success: 90% automation, zero audit findings

Sarah - HR Director (Platform Administrator)

  • Context: 500+ employees, wellbeing focus, limited budget
  • Needs: Easy setup, user adoption, license management
  • Journey: 10-minute setup → automated onboarding → insights dashboard
  • Success: 80% adoption, positive culture metrics

Michael - Consultant (Portfolio Manager)

  • Context: 20+ clients, benchmarking needs, white-label requirements
  • Needs: Multi-client view, branded exports, strategic insights
  • Journey: Client onboarding → portfolio monitoring → strategic recommendations
  • Success: 50% time saved, premium positioning

2.2 User Journey Simplification

interface SimplifiedUserJourneys {
  employee: {
    firstUse: {
      duration: "3 minutes";
      steps: ["SSO login", "Choose preferences", "Log first kindness"];
      friction: "zero";
    };
    dailyUse: {
      duration: "30 seconds";
      touchpoints: [
        "Morning notification",
        "One-tap logging",
        "Evening summary",
      ];
      value: "Immediate gratification + long-term impact visibility";
    };
  };

  admin: {
    setup: {
      duration: "10 minutes";
      steps: ["Company details", "Connect HRIS", "Launch"];
      automation: "90% pre-configured";
    };
    monitoring: {
      frequency: "Weekly 5-minute check";
      insights: ["License usage", "Culture health", "Compliance readiness"];
      alerts: "Exception-based only";
    };
  };
}

3. Core Product Features

3.1 Evidence Generation Modules

Kindness & Recognition Module

Purpose: Transform daily kindness into culture evidence

Features:

  • One-tap logging with photo/voice/text
  • Peer recognition with ripple visualization
  • Cultural sentiment analysis
  • All We Can global sync

Evidence Value:

  • B-Corp community/worker scores
  • CSRD S1 employee treatment
  • Section 172 stakeholder consideration

Volunteer Management System

Purpose: Verify and quantify community impact

Features:

  • Skills-based opportunity matching
  • QR + GPS check-in/out
  • Multi-tier verification (charity, manager, peer, photo, self)
  • Outcome measurement beyond hours

Verification Hierarchy:

  • Tier 1: System verified (100% audit weight)
  • Tier 2: Manager approved (90% weight)
  • Tier 3: Peer confirmed (70% weight)
  • Tier 4: Photo evidence (50% weight)
  • Tier 5: Self-reported (30% weight)

Donation Tracking Platform

Purpose: Payment-agnostic donation verification

Features:

  • Multi-source capture (payroll, cards, receipts)
  • Company match management
  • Multi-currency with live exchange rates
  • Charity risk assessment

Integrations:

  • JustGiving, CAF webhooks
  • HRIS payroll systems
  • Bank transaction APIs
  • Charity Commission verification

Wellbeing Measurement System

Purpose: Predictive wellbeing with crisis prevention

Features:

  • AI-orchestrated surveys (max 12/year/employee)
  • Cultural adaptation for global teams
  • Predictive risk analytics
  • Anonymous crisis pathways
  • Emergency survey override

Intelligence:

  • Sentiment trajectory analysis
  • Department heat mapping
  • Early warning indicators
  • Intervention recommendations

3.2 Simplification & Automation Layer

Auto-Magic Features

interface AutoMagicCapabilities {
  intelligentCapture: {
    calendar: "Detects volunteer events, prompts logging";
    email: "Recognizes donation receipts, auto-logs";
    slack: "Identifies kudos, converts to kindness";
    location: "Geo-fences charity locations for check-in";
  };

  smartSuggestions: {
    contextual: "Weather-based kindness prompts";
    temporal: "End-of-week reflection nudges";
    social: "Team activity inspiration";
    personal: "Based on past behavior patterns";
  };

  voiceFirst: {
    commands: [
      "Log kindness for helping Sarah",
      "Check in at food bank",
      "Show my impact this month",
    ];
    languages: 23;
    accuracy: ">95% with accent adaptation";
  };
}

Progressive Disclosure

Week 1: Kindness only - build habit Month 1: Add volunteering - expand impact Month 3: Enable wellbeing - complete picture Month 6: Full platform - power features

Always maintaining simple mode option for all users.

3.3 Evidence Packaging & Export

Compliance Frameworks Supported

  • B-Corp: Full assessment support
  • CSRD/ESRS: S1-S4 social standards
  • UN SDGs: All 17 goals mapped
  • Social Value Act: TOMs framework
  • Section 172: Stakeholder evidence
  • Modern Slavery: Policy compliance

One-Click Evidence Generation

interface EvidenceExport {
  wizard: {
    step1: "What framework? (auto-detected)";
    step2: "What period?";
    step3: "Generate (10 seconds)";
  };

  output: {
    summary: "Executive overview";
    evidence: "Detailed data tables";
    narrative: "Impact stories";
    audit: "Complete verification trail";
  };

  format: {
    pdf: "Branded report";
    excel: "Data workbook";
    api: "System integration";
    dashboard: "Live view";
  };
}

4. Technical Architecture

4.1 System Architecture

Architecture Philosophy: Phase 1 implements a sophisticated modular monolith with microservice authentication. This approach balances development velocity with enterprise-grade security, multi-tenant data isolation, and clear service boundaries for critical authentication flows.

┌─────────────────────────────────────────┐
│          Frontend Layer                  │
│  - Next.js 16.0.1 App Router            │
│  - React 19.2.0 Server Components       │
│  - Vite Admin Dashboard (port 5173)     │
│  - Progressive Web App                   │
└─────────────────┬───────────────────────┘

┌─────────────────▼───────────────────────┐
│        API Gateway Layer                │
│  - Hono.js Backend (port 3004)          │
│  - 190+ API routes                      │
│  - Rate limiting (Redis-backed)         │
│  - Authentication proxy to auth-service │
└─────────────────┬───────────────────────┘

┌─────────────────▼───────────────────────┐
│      Authentication Service             │
│  - better-auth microservice (port 3002) │
│  - PostgreSQL auth database             │
│  - JWT token management                 │
│  - OAuth integration                    │
│  - DualWrite sync to main database      │
└─────────────────┬───────────────────────┘

┌─────────────────▼───────────────────────┐
│         Service Layer                   │
│  - Core Services (121 services across 6 categories) │
│    • Evidence Modules: 4 services (kindness, volunteer,  │
│      donation, wellbeing)               │
│    • Consultant Management: 15 services (portfolio,          │
│      white-label, audit, management)    │
│    • Compliance & Licensing: 12 services (compliance,            │
│      licensing, audit, reporting)                      │
│    • Core Business Logic: 25 services (company, user,            │
│      onboarding, analytics)              │
│    • Infrastructure: 35 services (cache, metrics,            │
│      notifications, background jobs)              │
│    • Background Workers: 30+ Bull queue workers (bulk ops,            │
│      compliance, GDPR, retention)       │
│  - BaseService Pattern: 62/107 services migrated (58%) │
│  - Business Logic Layer                 │
│  - Redis Caching (SCAN-based)           │
│  - Type-safe with Zod validation        │
│  - Business Logic Layer                 │
│  - Redis Caching (SCAN-based)           │
│  - Type-safe with Zod validation        │
└─────────────────┬───────────────────────┘

┌─────────────────▼───────────────────────┐
│          Data Layer                     │
│  - PostgreSQL 18 (Primary)              │
│  - Drizzle ORM (type-safe SQL)          │
│  - Redis 7 (Sessions/Cache)             │
│  - Row-Level Security (RLS)             │
│  - Auth Bypass Architecture             │
└─────────────────────────────────────────┘

Architecture Evolution Roadmap:

  • Phase 1-2 (Current): Modular monolith with auth microservice, suitable for 100-500 companies ✅
  • Phase 3: Enhanced scalability with service extraction, 500-1000 companies 🔄
  • Phase 4: Full microservices with event-driven architecture, 1000+ companies 📋
  • Phase 5: Advanced microservices with service mesh and AI integration

Rationale for Current Architecture:

  1. Security First: Authentication isolated in separate service with its own database
  2. Multi-Tenant Isolation: PostgreSQL Row-Level Security (RLS) for database-level tenant separation
  3. Development Velocity: Monolithic core enables rapid feature development with 121 services
  4. Type Safety: End-to-end TypeScript with shared types across layers
  5. Event-Driven Sync: DualWrite pattern keeps auth and main databases synchronized
  6. Production Ready: Enhanced Docker setup with health checks, monitoring, and automated backups
  7. Scalability: Clear boundaries for future service extraction, proven at 100-500 company scale

4.2 Multi-Tenant Architecture

interface TenantArchitecture {
  isolation: {
    database: "Row-level security (RLS) with company_id session variable";
    storage: "Dedicated S3 buckets per company";
    cache: "Redis namespace isolation with company-scoped keys";
    search: "Separate Elasticsearch indices";
  };

  dualConnection: {
    rlsEnabled: "getDb(companyId) - automatic tenant filtering";
    rlsBypass: "getAuthDb() - cross-tenant operations only";
    security: "Defense-in-depth with application + database layers";
  };

  customization: {
    branding: "Company-specific themes";
    features: "Tier-based feature flags";
    integrations: "Custom webhooks/APIs";
    whiteLabel: "Consultant/partner branding";
  };

  scaling: {
    current: "100-500 companies (Phase 1-2) ✅";
    phase3: "500-1000 companies with service extraction 🔄";
    phase4: "1000+ companies with full microservices 📋";
    performance: "Sub-200ms response times with 2-5ms RLS overhead";
  };
}

4.3 Technology Stack

Frontend:

  • Next.js 16.0.1 with App Router
  • React 19.2.0 (Server Components)
  • Vite 7.1.12 for admin dashboard
  • TypeScript 5.9.3 (strict mode)
  • Tailwind CSS 4.1.16 design system
  • Radix UI component library (@ripplecore/ui)
  • Progressive Web App capability
  • TanStack Router/Query/Table for state management

Backend & Services:

  • Node.js 20.x LTS
  • Hono.js 4.10.4 API backend (port 3004)
  • better-auth 1.3.34 microservice (port 3002)
  • 121 services across 6 categories in @ripplecore/core
  • BaseService pattern for consistent logging, caching, error handling
  • Zod 3.25.76 (runtime validation)
  • Bull queues for background processing (30+ workers)

Database & Storage:

  • PostgreSQL 18 (Production), 18 (Development)
  • Drizzle ORM 0.44.7 (chosen over Prisma for better RLS support)
  • Redis 7 for sessions, caching, rate limiting
  • ioredis 5.8.2 client with SCAN-based operations

Development Infrastructure:

  • Turbo 2.5.8 monorepo orchestration
  • pnpm 10.20.0 workspace package manager
  • Docker Compose with enhanced development tooling (pgAdmin, Redis Commander)
  • Testcontainers for integration tests with real PostgreSQL/Redis
  • Three-tier testing approach (unit, integration, E2E) with 87% coverage

Testing & Quality:

  • Vitest 4.0.5 for unit/integration tests (87% current coverage, 95% target)
  • Playwright 1.56.1 for E2E tests (100% critical path coverage)
  • TestContainers for production-like integration testing
  • axe-core for WCAG 2.1 AA accessibility validation
  • TypeScript compiler for type-safety enforcement (100% pass rate)

Monitoring & Observability:

  • Sentry for error tracking and performance monitoring
  • Pino structured logging with JSON output
  • Custom metrics for license usage, evidence generation
  • Redis for performance metrics caching

Deployment:

  • Docker Compose with production optimizations (enhanced security, monitoring)
  • Environment-based configuration with validation scripts
  • Automated health checks and structured logging
  • Rolling updates with zero-downtime capability
  • BuildKit optimization for 70-95% faster builds
  • Automated backup services with 7-day retention

Infrastructure:

  • Dokploy for deployment orchestration
  • PostgreSQL and Redis production configurations
  • Automated backup services
  • Network isolation and security hardening

Key Technology Decisions:

  1. Drizzle over Prisma: Better PostgreSQL support, type-safe SQL, easier RLS integration
  2. Hono.js over Next.js API: Better performance, smaller bundle, purpose-built for APIs
  3. better-auth microservice: Security isolation, scalability, OAuth complexity management
  4. PostgreSQL 18: Stable, proven RLS features, excellent performance
  5. Docker-first development: Consistent environments, easy onboarding, production parity
  6. DualWrite Event Pattern: Reliable auth-to-main database synchronization
  7. BaseService Pattern: Consistent service behavior across 121 services
  8. TestContainers Integration: Production-like testing with real infrastructure

4.4 Port Assignments & Service Architecture

Development Environment:

  • 3000 - Next.js web application (public website)
  • 3004 - Hono.js API backend (main API)
  • 3002 - better-auth microservice (authentication)
  • 5173 - Vite admin dashboard
  • 5432 - PostgreSQL database
  • 6379 - Redis cache
  • 5050 - pgAdmin (database web UI)
  • 8081 - Redis Commander (cache web UI)

Production Environment:

  • 3000 - Next.js web application
  • 3004 - Hono.js API backend
  • 3005 - better-auth microservice
  • 3001 - Admin dashboard (Nginx)

Service Communication:

  • Web app connects to API (3004) and auth service (3002/3005)
  • Admin dashboard connects to API (3004)
  • API proxies authentication to auth service
  • Auth service syncs user data to main database via DualWrite pattern

4.5 Docker & Infrastructure

Development Environment:

  • Docker Compose with 4 infrastructure services + 3 development tools
  • Resource limits to prevent runaway usage
  • Network isolation between service tiers (data, tooling, backend)
  • Automated database initialization with seeding system
  • Health checks and structured logging
  • Configuration validation scripts
  • Enhanced PostgreSQL and Redis configurations

Production Environment:

  • Docker Compose with 6 application services
  • Rolling updates with zero-downtime deployment
  • Automated backup services (7-day retention)
  • Enhanced security with network isolation and SSL/TLS
  • Resource limits and monitoring with structured logging
  • Environment variable standardization and validation
  • Production-optimized PostgreSQL and Redis configurations

Infrastructure Features:

  • Environment-based configuration validation with automated scripts
  • Structured logging with JSON output and rotation
  • Automated health checks and monitoring across all services
  • Backup and recovery capabilities with automated scheduling
  • Security hardening and SSL/TLS support
  • BuildKit cache optimization for faster deployments
  • Comprehensive documentation (5,000+ lines across guides)

5. User Licensing & Commercial Model

5.1 Licensing Tiers

Starter (€15/user/month)

  • Up to 50 users
  • Core modules
  • 5 language support
  • Email support

Growth (€10/user/month)

  • 50-500 users
  • All modules
  • 15 language support
  • Priority support

Enterprise (€7/user/month)

  • 500+ users
  • Advanced features
  • 23+ languages
  • Dedicated support
  • White-label options

5.2 License Monitoring System

interface LicenseEnforcement {
  monitoring: {
    activeUsers: "Real-time tracking";
    usageAlerts: "Proactive notifications at 80%, 90%, 100%";
    inactiveDetection: "30-day threshold";
    suggestions: "Automated optimization recommendations";
  };

  enforcement: {
    soft: "Allow overage, adjust billing";
    strict: "Block new users at limit";
    grace: "5% buffer for flexibility";
    suspended: "Inactive user management";
  };

  billing: {
    monthly: "Pay as you grow";
    annual: "2 months free";
    overage: "Pro-rated additional users";
    trueUp: "Quarterly reconciliation";
  };
}

6. All We Can Integration

6.1 Partnership Model

Revenue Allocation:

  • 10% of all subscription revenue to All We Can
  • Funds school programmes globally
  • Creates tangible impact metrics

Data Exchange:

  • Anonymous kindness acts synced globally
  • School support calculations
  • Global impact dashboard
  • Country/company rankings

6.2 Impact Metrics

interface AllWeCanImpact {
  company: {
    kindnessShared: number;
    schoolsSupported: number; // €50 = 1 school/month
    childrenReached: number;
    globalRank: number;
  };

  global: {
    totalKindnessActs: number;
    countriesActive: number;
    schoolsFunded: number;
    livesImpacted: number;
  };

  visibility: {
    employeeDashboard: "Personal contribution to global impact";
    companyDashboard: "Organization impact metrics";
    publicWebsite: "Optional public impact page";
    widgets: "Embeddable impact counters";
  };
}

7. Implementation Roadmap

7.1 Development Phases

Phase 1: MVP (Months 1-3)

  • Core modules development
  • UK market focus
  • 5 pilot companies
  • Basic All We Can integration

Phase 2: Market Entry (Months 4-6)

  • DACH expansion
  • German + French languages
  • 25 paying customers
  • Consultant portal

Phase 3: Scale (Months 7-12)

  • EU-wide launch
  • 15 languages
  • 100 customers
  • Charity partner portal
  • Advanced analytics

Phase 4: Intelligence (Months 13-18)

  • AI-powered insights
  • Predictive analytics
  • Voice interface
  • 300 customers

7.2 Success Metrics

Product Metrics:

  • User adoption: >80% monthly active
  • Engagement: >40% daily active
  • Time to value: <3 minutes to first action
  • Evidence quality: >90% Tier 1-3 verification

Business Metrics:

  • MRR growth: 20% month-on-month
  • Customer retention: >95% annual
  • CAC payback: <12 months
  • NPS: >50

Impact Metrics:

  • Kindness acts: 1M+ annually
  • Volunteer hours: 500K+ verified
  • Schools supported: 500+ via All We Can
  • Lives impacted: 10M+ beneficiaries

8. Risk Management

8.1 Technical Risks

Risk: Integration complexity with HRIS systems Mitigation: CSV fallback, phased rollout, extensive testing

Risk: Data quality and verification accuracy Mitigation: Multi-tier verification, photo evidence, audit trails

Risk: Scalability challenges Mitigation: Kubernetes auto-scaling, database sharding, CDN

8.2 Market Risks

Risk: Slow adoption due to change resistance Mitigation: 30-second rule, zero training, progressive disclosure

Risk: Competition from established platforms Mitigation: Evidence quality focus, All We Can differentiation

Risk: Regulatory changes Mitigation: Flexible framework, regular updates, expert network

8.3 Operational Risks

Risk: License compliance violations Mitigation: Real-time monitoring, automated enforcement, grace periods

Risk: Data privacy concerns (especially DEI) Mitigation: Encryption, aggregation-only reporting, explicit consent

Risk: Language/cultural adaptation failures Mitigation: AI + human validation, local experts, continuous improvement


9. Design & Brand Guidelines

9.1 Visual Identity

Color Palette:

  • Primary: #0d1594 (Ripple Purple)
  • Energy: #805bed (Lilac)
  • Future: #26dbd9 (Teal)
  • Kindness: #ff66c4 (Pink)
  • Neutral: #121212 (Ink), #F5F5F7 (Soft Grey)

Typography:

  • Headings: Helvetica Bold
  • Body: Helvetica Regular
  • Minimum size: 14px for accessibility

Components:

  • 20px border radius (friendly, approachable)
  • Soft shadows for depth
  • Ripple animations for feedback
  • High contrast for accessibility

9.2 Voice & Tone

Principles:

  • Clear, not corporate
  • Warm, not fluffy
  • Empowering, not preachy
  • Expert, not academic

Key Messages:

  • "Track. Report. Amplify your ESG impact."
  • "Every act of kindness creates ripples"
  • "Where kindness meets compliance"

10. Development Guidelines

10.1 Code Standards

TypeScript First:

  • Strict mode enabled
  • Full type coverage
  • No any types without justification

Testing Requirements:

  • Unit test coverage >95% (current: 87% overall)
  • Integration tests for all APIs (TestContainers with real PostgreSQL/Redis)
  • E2E tests for critical paths (Playwright)
  • Accessibility tests for all components (axe-core WCAG 2.1 AA)
  • Three-tier testing approach with production-like infrastructure

Performance Budgets:

  • API response: <200ms
  • Page load: <2 seconds
  • Interaction: <100ms
  • Bundle size: <200KB

10.2 Security Requirements

Data Protection:

  • GDPR compliant by design
  • End-to-end encryption for sensitive data
  • Row-level security in database
  • Regular security audits

Authentication:

  • Multi-factor authentication
  • SSO integration (SAML, OAuth)
  • Session management
  • Role-based access control

Compliance:

  • SOC 2 Type II
  • ISO 27001
  • WCAG 2.1 AA accessibility (Phase 1), 2.2 AA (Phase 3), 2.2 AAA evaluation (Phase 4)
  • Regular penetration testing

10.3 Redis Best Practices

Critical Rule: NEVER use redis.keys() in production - it's O(N) and blocks Redis, causing production outages.

SCAN-Based Operations (Required):

// From packages/core/src/utils/redis-helpers.ts
import {
  deleteKeysByPattern,
  getKeysByPattern,
  countKeysByPattern,
} from "@ripplecore/core";

// ✅ CORRECT: Non-blocking cache invalidation
await deleteKeysByPattern(redis, "company:123:*");

// ✅ CORRECT: Safe key listing for diagnostics
const keys = await getKeysByPattern(redis, "session:*");

// ✅ CORRECT: Efficient key counting for metrics
const count = await countKeysByPattern(redis, "cache:*");

// ❌ WRONG: Blocks Redis, causes outages
const keys = await redis.keys("company:*"); // NEVER USE THIS

Cache Strategy Standards:

  • Service methods MUST implement Redis caching for frequently-read data
  • Cache keys MUST include company ID for tenant isolation: company:{companyId}:{resource}:{id}
  • Cache TTL MUST be explicit (no infinite caching): typically 5-60 minutes
  • Cache invalidation MUST be synchronous with data mutations
  • Use redis.pipeline() for batch operations to reduce round-trips

Redis Architecture:

  • Session Storage: better-auth sessions with 8-hour expiry
  • Rate Limiting: Request counting per IP/user with sliding windows
  • Caching Layer: Frequently-accessed data (user profiles, company settings)
  • Performance Metrics: Real-time usage statistics
  • Background Jobs: Bull queues for asynchronous processing

Rationale: redis.keys() is O(N) and blocks all Redis operations during execution. The project migrated all services to SCAN-based patterns after identifying this anti-pattern. Redis downtime impacts authentication (session storage) and rate limiting, making this a production-critical requirement.

10.4 Type-Safe Development

TypeScript Strict Mode (Non-Negotiable):

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true
  }
}

Type Organization: All types defined in packages/core/src/types/ with clear domain separation:

  • user.ts - User, roles, permissions (35 types)
  • company.ts - Company management (25 types)
  • license.ts - License tracking (39 types)
  • consultant.ts - Consultant features (19 types)
  • kindness.ts - Evidence module types
  • volunteer.ts - Volunteer management types
  • donation.ts - Donation tracking types
  • wellbeing.ts - Wellbeing survey types

Zod Runtime Validation (Required at API Boundaries):

import { z } from "zod";

// Define schema for runtime validation
const createKindnessSchema = z.object({
  description: z.string().min(1).max(500),
  recipientId: z.string().uuid(),
  companyId: z.string().uuid(),
  timestamp: z.string().datetime().optional(),
});

// Validate at API route boundary
export async function POST(request: NextRequest) {
  const body = await request.json();
  const validated = createKindnessSchema.parse(body); // Throws on invalid input

  // TypeScript now knows validated is correctly typed
  const result = await kindnessService.create(validated);
  return success(result);
}

Type Safety Standards:

  • Define explicit types for all service inputs/outputs (no any without justification comments)
  • Use Zod schemas for runtime validation at API boundaries (untrusted input)
  • Export types from packages/core/src/types/ for cross-package usage
  • Maintain separate type files per domain for clarity
  • Use discriminated unions for polymorphic types
  • Prefer interface for object shapes, type for unions/intersections

Rationale: Type safety prevents runtime errors in production, especially for multi-tenant data access where incorrect types could lead to data leakage. Zod provides runtime validation for untrusted inputs (API requests, user forms). The codebase maintains 100% type-check success rate enforced by Turbo.

10.5 Session Management & Authentication

better-auth Microservice Architecture:

  • Separate Service: Authentication runs as isolated microservice (port 3002/3005)
  • Dedicated Database: Separate PostgreSQL database for auth data
  • DualWrite Sync: Event-driven synchronization with main database
  • OAuth Integration: Google, Microsoft OAuth support
  • MFA Support: Multi-factor authentication capabilities

Auth Bypass Architecture (Critical for Multi-Tenant Security):

  • Two Database Systems:
    • auth-service database: Isolated authentication data with full access
    • main database: Tenant-scoped data with RLS enforcement
  • Security Model:
    • Auth service manages user identities and sessions
    • DualWrite events sync user profiles to main database
    • RLS policies enforce tenant isolation in main database
  • Why Required: Prevents authentication conflicts while maintaining multi-tenant data isolation

RLS Context Enforcement: All tenant-scoped API routes MUST use withRLSContext helper:

import { withRLSContext } from "@ripplecore/core";

export async function GET(request: NextRequest) {
  return await withRLSContext(request, async (context) => {
    // RLS context automatically set here
    // context.userId and context.companyId available
    const data = await someService.getData(context.companyId);
    return success(data);
  });
}

Session Security:

  • 8-hour session expiry with automatic refresh
  • Redis-backed sessions for horizontal scalability
  • Rate limiting for all authentication endpoints
  • Device tracking for suspicious activity detection
  • MFA support via better-auth plugins
  • Secure cookie configuration

Environment Variables (Required):

# Auth Service
PORT=3002
JWT_SECRET="your_jwt_secret_here_minimum_32_chars"
JWT_REFRESH_SECRET="your_jwt_refresh_secret_here_minimum_32_chars"
BETTER_AUTH_SECRET="your_better_auth_secret_here"
AUTH_SYSTEM_PASSWORD="your_auth_system_password_here"

# Database
DATABASE_URL="postgresql://user:password@host:5432/database"

# Redis
REDIS_URL="redis://password@host:6379"

Rationale: The microservice architecture provides security isolation for authentication while DualWrite synchronization ensures data consistency. This pattern enables secure multi-tenant operation without compromising authentication flows.


11. Conclusion

RippleCore represents a transformational approach to social impact measurement, proving that when companies prioritize both employee wellbeing and community impact, they create authentic, compliance-ready evidence that demonstrates genuine social value creation.

The RippleCore Promise

Through radical simplicity, inclusive design, and global impact connection via All We Can, we transform everyday workplace kindness and community engagement into the verified evidence that proves your organization's authentic social impact.

Key Success Factors

  1. 30-Second Rule: If it takes longer, we've failed
  2. Evidence Quality: Multi-tier verification for audit confidence
  3. Global Impact: Local actions creating worldwide change
  4. Inclusive Design: Accessible to every employee regardless of ability
  5. Continuous Evolution: Platform that learns and adapts

Call to Action

This PRD provides the complete blueprint for building RippleCore as the market-leading social impact evidence platform. With clear technical specifications, detailed user journeys, and comprehensive implementation guidance, the development team has everything needed to begin immediate implementation.


Document Control:

  • Version: 4.2 - Updated Architecture & Implementation Status
  • Status: Approved for Development
  • Review Cycle: Monthly
  • Owner: Product Team
  • Last Updated: BaseService migration (58%), Docker enhancements, 121 services architecture

Contact Information:


"When people feel good inside, they do good outside. When companies have good culture, they create compliance-ready evidence."

RippleCore - The Social Impact Evidence Platform