Infrastructure & Supporting Systems

Content management, APIs, database architecture, and operational systems powering the platform

Production Infrastructure:

Status: ✅ Active | Coverage: Full-Stack | Monitoring: Real-time

Overview

Beyond the headline features (chatbot and booking system), Portfolio OS includes comprehensive supporting infrastructure that makes it a complete platform rather than just a collection of features. This infrastructure demonstrates understanding of what it takes to build and operate a production system: content management, API design, data persistence, monitoring, and operational tooling.

This document covers the supporting systems that make the platform functional, maintainable, and scalable.


Content Management System

Dashboard Application

The dashboard is a separate Next.js application within the monorepo, providing admin-only functionality for managing content. It shares authentication, database access, and UI components with the public site while maintaining independent deployment.

Key Capabilities

Article Editor

Rich markdown editor with live preview, MDX support, and syntax highlighting. Split-pane interface with real-time preview, auto-save drafts every 30 seconds, full-screen mode for distraction-free writing, and syntax highlighting for code blocks.

Image Management

Upload, optimize, and organize media with automatic processing. Drag-and-drop upload interface, automatic optimization and format conversion, WebP generation with fallbacks, and responsive image generation.

Publishing Workflow

Complete draft, review, and publish process with scheduling. Save as draft or publish immediately, schedule publication for specific date/time, preview before publishing, and version history for rollback.

SEO Tools

Optimize content for search engines with automated metadata. Meta description editing, Open Graph image generation, Schema.org structured data, and automatic sitemap updates.

Analytics Dashboard

Track content performance and engagement metrics. Page views per article, reading time analytics, popular pages report, and traffic sources and engagement data.

Why Custom CMS vs WordPress/Strapi?

WordPress Drawbacks

PHP rather than modern JavaScript, plugin dependencies and compatibility issues, security vulnerabilities requiring constant updates, performance overhead, and overkill for single-author blog.

Strapi/Contentful Drawbacks

External service dependency, monthly costs ($29-99+), API-only (must build all UI), and vendor lock-in for content storage.

Custom Dashboard Advantages

Complete control over features and UI, zero monthly costs, same technology stack as rest of platform, type-safe content models, direct database access for complex queries, and demonstrates full-stack capability.


Blog & Content Display

Article Rendering

MDX Processing

Markdown with React components. Standard markdown support (headings, lists, links, images), React components embedded in content, syntax highlighting via Prism.js, auto-generated table of contents, and reading time calculation.

Performance Optimization

Fast content delivery and rendering. Server-side rendering for instant display, incremental static regeneration (ISR), image lazy loading and responsive sizing, code splitting per page, and CDN caching at edge.

Reader Experience

Optimized for long-form content. Clean, readable typography, responsive design for all devices, dark mode support, progress indicator and scroll position tracking, and share buttons for social distribution.

Content Organization

Tagging System

Organize content by topic. Articles associated with multiple tags, tag pages show all related articles, most popular tags in sidebar, and tag cloud with frequency weighting.

Categories

Broader content grouping. Tutorials, Case Studies, Technical Deep-Dives. Category pages list all articles and help visitors navigate content types.

Search Functionality

Find content quickly. Full-text search across all articles, results ranked by relevance, highlights matching text snippets, and fast client-side search using Flexsearch.


API Architecture

The platform exposes REST and GraphQL APIs following standard conventions and best practices.

REST API Design

Consistent Structure

All responses follow same shape with data, error, and meta objects

Appropriate Status Codes

200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Server Error

Helpful Error Messages

Clear description of what went wrong and how to fix it

Endpoint Structure:

/api/articles           GET: List articles    POST: Create article
/api/articles/[id]      GET: Get article      PUT: Update          DELETE: Delete
/api/auth/session       GET: Check auth status
/api/chatbot/stream     POST: Stream chatbot response
/api/schedule/available POST: Get available time slots
/api/schedule/book      POST: Create booking

Request/Response Patterns:

Successful GET Response:

{
  "data": {
    "id": "abc123",
    "title": "Platform Architecture",
    "content": "...",
    "publishedAt": "2024-11-08T12:00:00Z"
  },
  "meta": {
    "timestamp": "2024-11-08T14:30:00Z"
  }
}

Successful POST Response:

{
  "data": {
    "id": "xyz789",
    "status": "created"
  },
  "meta": {
    "timestamp": "2024-11-08T14:30:00Z"
  }
}

Error Response:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Title is required",
    "details": {
      "field": "title",
      "constraint": "required"
    }
  },
  "meta": {
    "timestamp": "2024-11-08T14:30:00Z"
  }
}

GraphQL Endpoint

GraphQL provides flexible querying for complex data requirements.

Single Request

Fetch complex data requirements without multiple API calls

Client-Specified Fields

Request exactly what you need, preventing over-fetching

Strong Typing

GraphQL schema provides built-in type safety and documentation

Easy Evolution

Add fields without breaking changes, deprecate gradually

Example Queries:

Get Article with Author and Tags:

query GetArticle($slug: String!) {
  article(slug: $slug) {
    id
    title
    content
    publishedAt
    author {
      name
      avatar
      bio
    }
    tags {
      name
      slug
      articleCount
    }
  }
}

Get Recent Articles with Pagination:

query GetRecentArticles($limit: Int!, $offset: Int!) {
  articles(limit: $limit, offset: $offset, orderBy: PUBLISHED_DESC) {
    id
    title
    excerpt
    publishedAt
    tags {
      name
    }
  }
  articlesCount
}

Implementation:

  • Apollo Server for GraphQL endpoint
  • Resolvers map to Prisma database queries
  • DataLoader for N+1 query prevention
  • Query complexity limits prevent abuse

API Security & Rate Limiting

Authentication

JWT tokens for protected endpoints, API keys for programmatic access. Public endpoints (read articles, chatbot) require no auth, protected endpoints (create/edit) require JWT token, and session validation on every request.

Rate Limiting

Token bucket algorithm with Redis tracking. Anonymous: 100 req/15min and 1000 req/day. Authenticated: 1000 req/15min and 10k req/day. Per-endpoint limits for chatbot, booking, and search.

Security Headers

Comprehensive security headers for all responses. Content-Security-Policy, X-Frame-Options: DENY, Strict-Transport-Security, and X-Content-Type-Options: nosniff.


Database Architecture

Schema Design Philosophy

The database schema balances several concerns to ensure reliability, performance, and maintainability.

Normalization

Eliminate data duplication while maintaining query performance

Type Safety

Prisma generates TypeScript types ensuring compile-time correctness

Query Performance

Strategic indexes on frequently-queried columns

Audit Trail

Created/updated timestamps on all tables for tracking

Soft Deletes

Mark records as deleted rather than physical deletion

Core Tables

Users - Authentication and authorization

model User {
  id            String    @id @default(cuid())
  email         String    @unique
  name          String?
  avatar        String?
  role          Role      @default(VIEWER)
  articles      Article[]
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
}

enum Role {
  VIEWER   // Read-only
  EDITOR   // Can create/edit content
  ADMIN    // Full access
}

Articles - Blog posts and content

model Article {
  id            String     @id @default(cuid())
  title         String
  slug          String     @unique
  content       String     @db.Text
  excerpt       String?
  published     Boolean    @default(false)
  publishedAt   DateTime?
  views         Int        @default(0)
  authorId      String
  author        User       @relation(fields: [authorId], references: [id])
  tags          Tag[]
  createdAt     DateTime   @default(now())
  updatedAt     DateTime   @updatedAt
  
  @@index([slug])
  @@index([published, publishedAt])
  @@index([authorId])
}

Bookings - Scheduled meetings

model Booking {
  id                String    @id @default(cuid())
  name              String
  email             String
  date              DateTime
  duration          Int       @default(30)
  timezone          String
  notes             String?   @db.Text
  status            String    @default("confirmed")
  googleEventId     String?   @unique
  googleMeetLink    String?
  confirmationSent  Boolean   @default(false)
  createdAt         DateTime  @default(now())
  updatedAt         DateTime  @updatedAt
  
  @@index([email, date])
  @@index([date, status])
}

ChatAnalytics - Chatbot usage metrics

model ChatAnalytics {
  id              String    @id @default(cuid())
  sessionId       String
  messageCount    Int
  avgResponseTime Float
  userSatisfaction Float?
  topics          String[]
  createdAt       DateTime  @default(now())
  
  @@index([sessionId])
  @@index([createdAt])
}

Migration Management

Prisma Migrations handle schema changes:

# Create migration from schema changes
pnpm prisma migrate dev --name add_booking_status

# Apply migrations in production
pnpm prisma migrate deploy

# Generate TypeScript types
pnpm prisma generate

Version Control

All schema changes tracked in version control

Automatic Rollback

Failed migrations roll back automatically

Type Generation

TypeScript types stay in sync with schema

Safe Deployments

Tested migrations before production

Database Performance

Connection Pooling

Prisma manages connection pool automatically. Reuses connections instead of creating new ones, configurable pool size based on load, and prevents connection exhaustion.

Strategic Indexes

Fast lookups for common queries. articles(slug) for fast article lookup by URL, articles(published, publishedAt) for published articles, bookings(email, date) for fast booking lookups, and chatAnalytics(sessionId) for session analytics.

Query Optimization:

// BAD: N+1 query problem
const articles = await prisma.article.findMany();
for (const article of articles) {
  const author = await prisma.user.findUnique({ where: { id: article.authorId }});
  // This runs N queries!
}

// GOOD: Single query with include
const articles = await prisma.article.findMany({
  include: {
    author: true,
    tags: true
  }
});
// Single query fetches everything

External Service Integrations

OpenAI API

Powers the AI chatbot with GPT-4 Turbo. Streaming chat responses via SSE, context window management, cost tracking and limits, retry with exponential backoff, and circuit breaker for failures.

Google Calendar API

Real-time availability checking and event creation. Check free/busy information, create calendar events for bookings, generate Google Meet links automatically, and service account with OAuth 2.0.

Email Service

Transactional emails via SendGrid/Resend. Booking confirmations with .ics attachments, HTML email templates, delivery tracking, and bounce handling.


Monitoring & Observability

Error Tracking (Sentry)

Comprehensive error monitoring with full context. Frontend errors with component stack traces, backend API errors with request context, performance transaction tracing, user session replays (privacy-safe), and immediate alerts for new errors.

Performance Monitoring

Track Core Web Vitals and API response times. Core Web Vitals (LCP, FID, CLS, TTFB), page load times and API response times, segmentation by device, geography, and route, and build and deployment metrics.

Custom Analytics

Business-specific metrics and insights. Chatbot: conversations, satisfaction, topics. Booking: conversion rate, popular times. Content: views, engagement, popular articles. PostHog for privacy-focused event tracking.

Logging Infrastructure

Structured logging with aggregation. Structured logs with context, multiple log levels (DEBUG, INFO, WARN, ERROR), Vercel Logs with external retention, and searchable, filterable, alerting capabilities.

Structured Logging Example:

logger.info('Booking created', {
  bookingId: 'abc123',
  email: 'user@example.com',
  date: '2024-11-10T14:00:00Z',
  duration: 30,
  timezone: 'America/New_York'
});

Operational Tools

Deployment Pipeline

GitHub Actions Workflow

Automated CI/CD pipeline for quality assurance. Lint code (ESLint), type check (TypeScript), run unit tests (Jest), run integration tests (Playwright), build applications (Turborepo), deploy to Vercel, run smoke tests, and notify on failure.

Vercel Deployment

Automatic deployments with preview environments. Automatic on push to main, preview deployments for pull requests, rollback capability (redeploy previous version), environment variable management, and build caching for speed.

Database Management

Migration Scripts

Safe schema changes and data management. pnpm db:migrate to apply pending migrations, pnpm db:seed to seed database with sample data, and pnpm db:reset to reset database (dev only).

Backup Strategy

Comprehensive backup and recovery. Automated daily backups, point-in-time recovery (30 days), test restoration monthly, and encrypted backup storage.

Automation Scripts

PR Management

Automated pull request workflows. Create PRs with templates, auto-label based on file changes, request reviews from relevant team members, and track PR status and merge readiness.

Housekeeping

Maintenance and cleanup automation. Clean temporary files, archive old logs, update dependencies, and generate documentation.

Utilities

Helper scripts for common tasks. Database migration helpers, content import/export, analytics report generation, and health checks.


Conclusion

The supporting infrastructure demonstrates understanding that production systems require more than just headline features. Content management, API design, database architecture, monitoring, and operational tooling are essential for maintainability, reliability, and scalability.

Systems Thinking

Understanding how components fit together to create a cohesive platform

Production Operations

Monitoring, logging, and error handling for reliable service

Developer Experience

Tools and automation that make development efficient

Maintainability

Clean architecture that evolves gracefully over time

Key Takeaway:

These supporting systems may not be glamorous, but they're what separates a demo project from a production platform. They demonstrate the breadth of knowledge required for professional software development.