Skip to main content

System Architecture

Millenium Potters is built as a modern, scalable microfinance management platform using a client-server architecture with separate frontend and backend services.

High-Level Architecture

┌─────────────────────────────────────────────────────────────┐
│                        Client Layer                          │
│  ┌────────────────────────────────────────────────────┐    │
│  │         Next.js 14 Frontend Application             │    │
│  │  (React 19, Tailwind CSS, Aceternity UI)            │    │
│  └────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────┘
                            ↕ HTTP/REST API
┌─────────────────────────────────────────────────────────────┐
│                      Application Layer                       │
│  ┌────────────────────────────────────────────────────┐    │
│  │       Node.js/Express Backend Server                │    │
│  │  (Prisma ORM, JWT Auth, Express Middleware)         │    │
│  └────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│                      Data Layer                              │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐     │
│  │ CockroachDB  │  │   Supabase   │  │  Cloudinary  │     │
│  │  (Production)│  │    (Auth)    │  │  (Storage)   │     │
│  │ PostgreSQL   │  │              │  │              │     │
│  │    (Local)   │  │              │  │              │     │
│  └──────────────┘  └──────────────┘  └──────────────┘     │
└─────────────────────────────────────────────────────────────┘

Technology Stack

Frontend Technologies

The client application is built with Next.js 14 and modern React patterns:
TechnologyVersionPurpose
Next.js16.0.10React framework with App Router
React19.1.0UI library
TypeScript5.xType safety
Tailwind CSS4.xUtility-first styling
Radix UIVariousAccessible component primitives
Framer Motion12.25.0Animation library
Axios1.11.0HTTP client
Shepherd.js14.5.1Interactive user tours
Recharts3.1.2Data visualization
date-fns4.1.0Date manipulation
Sonner2.0.7Toast notifications
See: ~/workspace/source/frontend/package.json:11-66

UI Component Libraries

Aceternity UI

Beautiful animated components for modern interfaces

Radix UI

Unstyled, accessible primitives for alerts, dialogs, dropdowns, etc.

Lucide Icons

Consistent icon library with 500+ icons

Key Features

  • Server-Side Rendering (SSR): Fast initial page loads with Next.js App Router
  • TypeScript: Full type safety across the application
  • Responsive Design: Mobile-first design with Tailwind breakpoints
  • Real-time Updates: Automatic data refresh on mutations
  • Error Monitoring: Sentry integration for production error tracking
  • Interactive Tours: Shepherd.js guides for onboarding
See: ~/workspace/source/frontend/package.json:27 (Sentry)

Authentication Flow

Session Management

  1. Login: User credentials verified via Supabase, JWT generated with user ID and role
  2. Token Storage: JWT stored in HTTP-only cookie (production) or localStorage (development)
  3. Request Authorization: Frontend includes JWT in Authorization header for API requests
  4. Token Validation: Backend middleware verifies JWT signature and expiry
  5. Role Check: Endpoint permissions checked against user role
  6. Session Tracking: Active sessions tracked in database with JWT ID
  7. Logout: Session revoked in database, token blacklisted
See: ~/workspace/source/backend/prisma/schema.prisma:506-522

Data Flow Examples

Creating a Loan

1

Credit Officer creates draft

POST /api/loans
{
  unionMemberId: "...",
  principalAmount: 50000,
  termCount: 12,
  termUnit: "MONTH"
}
Backend:
  • Validates user has CREDIT_OFFICER role
  • Checks member belongs to officer’s union
  • Creates loan with status DRAFT
  • Generates unique loan number
2

Officer submits for approval

PATCH /api/loans/:id/submit
Backend:
  • Updates status to PENDING_APPROVAL
  • Notifies supervisor via email
  • Creates audit log entry
3

Supervisor reviews and approves

PATCH /api/loans/:id/approve
{
  notes: "Approved after document review"
}
Backend:
  • Validates user has SUPERVISOR or ADMIN role
  • Updates status to APPROVED
  • Creates audit log entry
  • Notifies credit officer
4

Loan disbursement

POST /api/loans/:id/disburse
{
  disbursedAt: "2026-03-11",
  method: "TRANSFER",
  reference: "TXN123456"
}
Backend:
  • Updates status to ACTIVE
  • Generates repayment schedule
  • Creates schedule items in database
  • Calculates due dates based on term unit

Recording a Repayment

1

Credit officer records payment

POST /api/repayments
{
  loanId: "...",
  amount: 5000,
  paidAt: "2026-03-11",
  method: "CASH"
}
2

Backend allocates payment

  • Find oldest unpaid/partial schedule item
  • Apply to interest first, then principal
  • Update schedule item status (PAID, PARTIAL, or PENDING)
  • Create RepaymentAllocation records
  • Update loan status if fully paid
3

Frontend updates UI

  • Refresh repayment schedule
  • Update payment history
  • Recalculate outstanding balance
  • Show success notification

Backup & Recovery

Automated Backups

CockroachDB Managed

  • Hourly automatic backups
  • 30-day retention period
  • Point-in-time recovery
  • Managed by CockroachDB service

Application-Level

  • Manual or scheduled exports
  • JSON/CSV format exports
  • Cloudinary storage
  • Configurable frequency and retention

Backup Schedule Settings

model BackupScheduleSettings {
  id               String    @id @default("default")
  frequency        String    @default("disabled")  // daily, weekly, monthly
  location         String    @default("cloud")      // local, cloud, both
  retentionDays    Int       @default(30)
  includeAuditLogs Boolean   @default(false)
  lastBackupAt     DateTime?
  nextBackupAt     DateTime?
}
See: ~/workspace/source/backend/prisma/schema.prisma:661-673

Deployment Architecture

Production Deployment

┌─────────────────────────────────────────────┐
│              Vercel Edge Network             │
│  ┌────────────────────────────────────┐    │
│  │   Next.js Frontend (SSR/SSG)        │    │
│  └────────────────────────────────────┘    │
└─────────────────────────────────────────────┘

┌─────────────────────────────────────────────┐
│           Backend API Server                 │
│  (Render/Railway/AWS/DigitalOcean)          │
└─────────────────────────────────────────────┘
         ↕              ↕              ↕
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ CockroachDB  │ │   Supabase   │ │  Cloudinary  │
│  Serverless  │ │    (Auth)    │ │  (Storage)   │
└──────────────┘ └──────────────┘ └──────────────┘

Environment Configuration

NODE_ENV=development
DATABASE_URL=postgresql://localhost:5432/millenium_local
NEXT_PUBLIC_API_URL=http://localhost:5000/api

Maintenance Mode

Safe deployment with user lockout:
model CompanySetting {
  maintenanceMode Boolean @default(false)
  // ... other settings
}
When enabled:
  • All API requests return 503 Service Unavailable
  • Frontend shows maintenance page
  • Admin users can still access the system
  • Scheduled for deployments and database migrations
See: ~/workspace/source/backend/prisma/schema.prisma:352-369

Performance Considerations

Database Optimization

  • Connection Pooling: 20-30 connections for 50-100 concurrent users
  • Strategic Indexes: All foreign keys and frequently queried fields
  • Pagination: Limit query results to prevent memory issues
  • Soft Deletes: Use deletedAt field instead of hard deletes

Frontend Optimization

  • Server-Side Rendering: Fast initial page loads
  • Code Splitting: Automatic with Next.js
  • Image Optimization: Next.js Image component
  • Static Generation: Pre-render pages when possible
  • API Response Caching: React Query for client-side caching

API Optimization

  • Rate Limiting: Prevent abuse with express-rate-limit
  • Response Compression: Gzip/Brotli compression
  • Query Optimization: Prisma select for specific fields only
  • Batch Operations: Reduce database round trips
See: ~/workspace/source/backend/package.json:42 (rate limiting)

Scalability

Horizontal Scaling

  • Stateless Backend: Multiple API server instances
  • Load Balancing: Distribute requests across servers
  • Database: CockroachDB scales horizontally
  • CDN: Cloudinary for global file delivery

Vertical Scaling

  • Database: Increase CockroachDB resources as needed
  • Server: Scale up API server memory/CPU
  • Connection Pool: Adjust based on concurrent users
The current architecture supports 50-100 concurrent users. For larger deployments, consider implementing Redis caching, message queues, and horizontal API scaling.

Security Best Practices

Authentication

  • JWT tokens with expiration
  • HTTP-only cookies in production
  • Session tracking and revocation
  • Password reset with time-limited tokens

Authorization

  • Role-based access control (RBAC)
  • Endpoint-level permission checks
  • Resource ownership validation
  • Supervisor-officer hierarchy enforcement

Data Protection

  • Password hashing with bcrypt
  • Sensitive data encryption at rest
  • HTTPS enforced in production
  • Regular automated backups

Monitoring

  • Audit logs for all critical actions
  • Login history tracking
  • Error monitoring with Sentry
  • Session activity monitoring

What’s Next?

API Reference

Explore detailed API endpoint documentation

User Guide

Learn how to use all platform features

Deployment Guide

Deploy to production with best practices

Development

Contribute to the codebase

Build docs developers (and LLMs) love