Last updated: Aug 4, 2025, 11:26 AM UTC

Technical Architecture Documentation

Status: Complete
Version: 5.0
Last Updated: 2024
Purpose: Comprehensive technical architecture documentation for NudgeCampaign v5

Executive Summary

NudgeCampaign is a modern, AI-first email marketing platform built on a serverless, multi-tenant architecture with enterprise-grade security. This document provides comprehensive technical documentation of the system architecture, infrastructure design, data flows, and integration patterns using the C4 model for architecture visualization.

Key Architectural Principles

  1. Security-First Design: Row Level Security (RLS) enforces complete data isolation between organizations
  2. AI-Native Platform: Maya AI assistant integrated at the core, not as an afterthought
  3. Serverless Scalability: Auto-scaling infrastructure with zero-cost idle state
  4. Real-Time Processing: Event-driven architecture for immediate response
  5. Multi-Tenant Isolation: Complete data and process separation between organizations
  6. API-First Development: All functionality exposed through RESTful APIs
  7. Cloud-Native Deployment: Container-based deployment with Kubernetes orchestration

Table of Contents

  1. System Architecture Overview
  2. C4 Model Architecture Diagrams
  3. Infrastructure Design
  4. Data Architecture
  5. Security Architecture
  6. Integration Architecture
  7. Deployment Architecture
  8. Performance Architecture
  9. Monitoring and Observability
  10. Disaster Recovery

System Architecture Overview

NudgeCampaign follows a microservices architecture pattern with clear separation of concerns, enabling independent scaling, deployment, and maintenance of different system components.

High-Level Architecture

graph TB subgraph "Client Layer" Web[Web Application
React/Next.js] Mobile[Mobile App
React Native] API_Client[API Clients
SDKs] end subgraph "API Gateway Layer" Gateway[API Gateway
Rate Limiting & Auth] LB[Load Balancer
Traffic Distribution] end subgraph "Application Layer" App[Application Server
Node.js/Express] Maya[Maya AI Service
LLM Integration] Worker[Background Workers
Job Processing] end subgraph "Data Layer" Cache[(Redis Cache
Session/Data)] DB[(PostgreSQL
Primary Data)] Queue[(Bull Queue
Job Queue)] Storage[(S3 Storage
Files/Assets)] end subgraph "External Services" Postmark[Postmark
Email Delivery] Stripe[Stripe
Payments] OpenRouter[OpenRouter
AI Models] end Web --> Gateway Mobile --> Gateway API_Client --> Gateway Gateway --> LB LB --> App App --> Maya App --> Worker App --> Cache App --> DB Worker --> Queue Worker --> Postmark Maya --> OpenRouter App --> Stripe Worker --> Storage style Maya fill:#22C55E,color:#fff style DB fill:#4A90E2,color:#fff style Gateway fill:#F59E0B,color:#fff

Architectural Layers

  1. Presentation Layer: Web and mobile applications providing user interfaces
  2. API Gateway Layer: Central entry point handling authentication, rate limiting, and routing
  3. Business Logic Layer: Core application services implementing business rules
  4. Data Access Layer: Abstraction for database operations with RLS enforcement
  5. Integration Layer: External service connectors and adapters
  6. Infrastructure Layer: Cloud services, containers, and orchestration

C4 Model Architecture Diagrams

The C4 model provides a hierarchical way to think about system architecture through four levels of abstraction.

Level 1: System Context Diagram

The system context shows NudgeCampaign's place in the broader ecosystem and its interactions with users and external systems.

graph TB subgraph "Enterprise Boundary" NC[NudgeCampaign
Email Marketing Platform

AI-powered email marketing
with multi-tenant SaaS architecture] end subgraph "Users" Marketer[Marketing Manager

Creates and manages
email campaigns] Admin[System Administrator

Manages organization
settings and users] Contact[Email Recipient

Receives and interacts
with email campaigns] end subgraph "External Systems" Email[Postmark
Email Service

Handles email delivery
and tracking] Payment[Stripe
Payment Service

Processes subscriptions
and billing] AI[OpenRouter
AI Service

Provides LLM capabilities
for Maya AI] Auth[Supabase Auth
Authentication

Manages user authentication
and sessions] Analytics[PostHog
Analytics

Tracks user behavior
and product metrics] end Marketer -->|Creates campaigns| NC Admin -->|Manages system| NC NC -->|Sends emails| Contact NC -->|Delivers email| Email NC -->|Processes payments| Payment NC -->|AI conversations| AI NC -->|Authenticates users| Auth NC -->|Tracks events| Analytics style NC fill:#22C55E,color:#fff style Email fill:#4A90E2,color:#fff style Payment fill:#F59E0B,color:#fff style AI fill:#9333EA,color:#fff

Level 2: Container Diagram

The container diagram shows the high-level technology choices and communication between containers.

graph TB subgraph "NudgeCampaign System Boundary" subgraph "Frontend Containers" SPA[Single Page Application
Container: React/Next.js

Provides user interface
for campaign management] Mobile[Mobile Application
Container: React Native

Mobile access to
core features] end subgraph "Backend Containers" API[API Application
Container: Node.js

Handles business logic
and API endpoints] Maya[Maya AI Service
Container: Node.js

Manages AI conversations
and content generation] Worker[Background Worker
Container: Node.js

Processes async jobs
and email sending] Scheduler[Scheduler Service
Container: Node.js

Manages scheduled
campaign sends] end subgraph "Data Containers" DB[(PostgreSQL Database
Container: PostgreSQL 14

Stores all application
data with RLS)] Cache[(Redis Cache
Container: Redis 7

Session storage and
temporary data)] Queue[(Job Queue
Container: Redis/Bull

Manages background
job processing)] Files[(File Storage
Container: S3/MinIO

Stores attachments
and assets)] end end subgraph "External Services" Postmark[Postmark API] Stripe[Stripe API] OpenRouter[OpenRouter API] end SPA -->|HTTPS/JSON| API Mobile -->|HTTPS/JSON| API API -->|SQL| DB API -->|Redis Protocol| Cache API -->|Enqueue Jobs| Queue Worker -->|Dequeue Jobs| Queue Worker -->|HTTPS| Postmark Maya -->|HTTPS| OpenRouter API -->|HTTPS| Stripe Scheduler -->|Trigger Jobs| Queue API -->|Store Files| Files style SPA fill:#61DAFB,color:#000 style API fill:#68A063,color:#fff style Maya fill:#22C55E,color:#fff style DB fill:#336791,color:#fff style Cache fill:#DC382D,color:#fff

Level 3: Component Diagram - API Application

The component diagram shows the internal structure of the API application container.

graph TB subgraph "API Application Container" subgraph "API Layer" REST[REST Controller

Handles HTTP requests
and responses] GraphQL[GraphQL Controller

Handles GraphQL
queries and mutations] WebSocket[WebSocket Controller

Real-time communication
for live updates] end subgraph "Business Logic Layer" CampaignService[Campaign Service

Campaign creation
and management] ContactService[Contact Service

Contact list
management] AnalyticsService[Analytics Service

Metrics and
reporting] BillingService[Billing Service

Subscription
management] AuthService[Auth Service

Authentication and
authorization] MayaService[Maya Service

AI assistant
integration] end subgraph "Data Access Layer" ORM[Prisma ORM

Database abstraction
and query builder] RLS[RLS Middleware

Row level security
enforcement] CacheManager[Cache Manager

Redis cache
operations] end subgraph "Integration Layer" EmailAdapter[Email Adapter

Postmark
integration] PaymentAdapter[Payment Adapter

Stripe
integration] AIAdapter[AI Adapter

OpenRouter
integration] end end REST --> CampaignService REST --> ContactService GraphQL --> AnalyticsService WebSocket --> MayaService CampaignService --> ORM ContactService --> ORM AnalyticsService --> CacheManager BillingService --> PaymentAdapter AuthService --> RLS MayaService --> AIAdapter ORM --> RLS style REST fill:#4A90E2,color:#fff style MayaService fill:#22C55E,color:#fff style RLS fill:#EF4444,color:#fff

Level 4: Code Diagram - Campaign Service

The code diagram shows the internal structure of a specific component.

classDiagram class CampaignService { -campaignRepository: CampaignRepository -contactRepository: ContactRepository -emailService: EmailService -analyticsService: AnalyticsService +createCampaign(data: CampaignDTO): Campaign +updateCampaign(id: string, data: CampaignDTO): Campaign +deleteCampaign(id: string): void +scheduleCampaign(id: string, date: Date): void +sendTestEmail(id: string, email: string): void +duplicateCampaign(id: string): Campaign -validateCampaign(data: CampaignDTO): ValidationResult -checkQuota(orgId: string): QuotaResult } class CampaignRepository { -prisma: PrismaClient +create(data: Campaign): Promise~Campaign~ +update(id: string, data: Campaign): Promise~Campaign~ +delete(id: string): Promise~void~ +findById(id: string): Promise~Campaign~ +findByOrganization(orgId: string): Promise~Campaign[]~ +findScheduled(date: Date): Promise~Campaign[]~ } class Campaign { +id: string +organizationId: string +userId: string +name: string +subject: string +content: string +status: CampaignStatus +scheduledAt: Date +sentAt: Date +metrics: CampaignMetrics } class CampaignDTO { +name: string +subject: string +content: string +recipientListId: string +scheduledAt?: Date +template?: string } class EmailService { -postmarkClient: PostmarkClient +sendEmail(to: string, campaign: Campaign): Promise~void~ +sendBatch(recipients: string[], campaign: Campaign): Promise~void~ +validateEmail(email: string): boolean } CampaignService --> CampaignRepository CampaignService --> EmailService CampaignRepository --> Campaign CampaignService --> CampaignDTO

Infrastructure Design

NudgeCampaign leverages cloud-native infrastructure for scalability, reliability, and cost-effectiveness.

Cloud Architecture

graph TB subgraph "AWS Cloud Infrastructure" subgraph "Network Layer" CloudFront[CloudFront CDN
Global content delivery] ALB[Application Load Balancer
Traffic distribution] WAF[Web Application Firewall
Security filtering] end subgraph "Compute Layer" subgraph "ECS Cluster" API_Task[API Service Tasks
Auto-scaling group] Worker_Task[Worker Service Tasks
Auto-scaling group] Maya_Task[Maya AI Tasks
GPU-enabled instances] end Lambda[Lambda Functions
Serverless compute] end subgraph "Data Layer" RDS[(RDS PostgreSQL
Multi-AZ deployment)] ElastiCache[(ElastiCache Redis
Cluster mode)] S3[(S3 Buckets
Object storage)] DynamoDB[(DynamoDB
Session storage)] end subgraph "Integration Layer" SQS[SQS Queues
Message queuing] SNS[SNS Topics
Event notifications] EventBridge[EventBridge
Event routing] end end CloudFront --> WAF WAF --> ALB ALB --> API_Task API_Task --> RDS API_Task --> ElastiCache Worker_Task --> SQS Worker_Task --> S3 Maya_Task --> Lambda Lambda --> DynamoDB EventBridge --> SNS style CloudFront fill:#FF9900,color:#fff style RDS fill:#4A90E2,color:#fff style Lambda fill:#FF9900,color:#fff

Network Architecture

graph TB subgraph "VPC - 10.0.0.0/16" subgraph "Public Subnets" NAT1[NAT Gateway
10.0.1.0/24] NAT2[NAT Gateway
10.0.2.0/24] ALB_Sub[ALB
10.0.3.0/24] end subgraph "Private Subnets - Application" App1[App Subnet AZ1
10.0.10.0/24] App2[App Subnet AZ2
10.0.11.0/24] end subgraph "Private Subnets - Database" DB1[DB Subnet AZ1
10.0.20.0/24] DB2[DB Subnet AZ2
10.0.21.0/24] end subgraph "Security Groups" SG_ALB[ALB Security Group
Port 443 from Internet] SG_App[App Security Group
Port 3000 from ALB] SG_DB[DB Security Group
Port 5432 from App] end end Internet[Internet] --> NAT1 Internet --> NAT2 Internet --> ALB_Sub ALB_Sub --> App1 ALB_Sub --> App2 App1 --> DB1 App2 --> DB2 style Internet fill:#FF6B6B,color:#fff style DB1 fill:#4A90E2,color:#fff style DB2 fill:#4A90E2,color:#fff

Container Orchestration

graph TB subgraph "Kubernetes Cluster" subgraph "Control Plane" Master[Master Node
API Server, Scheduler] ETCD[ETCD
Cluster state] end subgraph "Worker Nodes" subgraph "Node 1" Pod1[API Pod
3 replicas] Pod2[Worker Pod
2 replicas] end subgraph "Node 2" Pod3[Maya Pod
1 replica] Pod4[Redis Pod
1 replica] end subgraph "Node 3" Pod5[API Pod
3 replicas] Pod6[Monitoring Pod
Prometheus] end end subgraph "Services" SVC_API[API Service
LoadBalancer] SVC_Redis[Redis Service
ClusterIP] SVC_Maya[Maya Service
ClusterIP] end Ingress[Ingress Controller
NGINX] end Master --> ETCD Master --> Pod1 Master --> Pod3 Master --> Pod5 Ingress --> SVC_API SVC_API --> Pod1 SVC_API --> Pod5 SVC_Redis --> Pod4 SVC_Maya --> Pod3 style Master fill:#326DE6,color:#fff style Ingress fill:#009639,color:#fff

Data Architecture

The data architecture ensures efficient storage, retrieval, and processing of information while maintaining strict security boundaries.

Database Schema Design

erDiagram organizations ||--o{ users : contains organizations ||--o{ contacts : owns organizations ||--o{ campaigns : creates organizations ||--o{ templates : has organizations ||--o{ automation_workflows : defines organizations ||--o{ subscriptions : subscribes users ||--o{ campaigns : authors users ||--o{ ai_conversations : has users ||--o{ user_sessions : creates campaigns ||--o{ email_deliveries : sends campaigns ||--o{ campaign_stats : tracks campaigns ||--o{ campaign_recipients : targets contacts ||--o{ email_deliveries : receives contacts ||--o{ contact_events : generates contacts ||--o{ contact_tags : tagged automation_workflows ||--o{ workflow_triggers : has automation_workflows ||--o{ workflow_actions : contains ai_conversations ||--o{ ai_messages : contains organizations { uuid id PK string name string slug UK string domain jsonb settings timestamp created_at timestamp updated_at } users { uuid id PK uuid organization_id FK string email UK string role string full_name jsonb preferences timestamp last_login_at timestamp created_at } contacts { uuid id PK uuid organization_id FK string email string first_name string last_name jsonb custom_fields string status timestamp subscribed_at timestamp unsubscribed_at } campaigns { uuid id PK uuid organization_id FK uuid user_id FK string name string subject text html_content text text_content string status timestamp scheduled_at timestamp sent_at jsonb settings } email_deliveries { uuid id PK uuid campaign_id FK uuid contact_id FK string message_id string status timestamp delivered_at timestamp opened_at timestamp clicked_at timestamp bounced_at jsonb metadata }

Data Flow Architecture

flowchart TB subgraph "Data Ingestion" CSV[CSV Import] API[API Input] Form[Web Forms] Webhook[Webhooks] end subgraph "Processing Pipeline" Validate[Data Validation] Transform[Data Transformation] Enrich[Data Enrichment] Dedupe[Deduplication] end subgraph "Storage Layer" Hot[(Hot Storage
PostgreSQL)] Warm[(Warm Storage
S3 Parquet)] Cold[(Cold Storage
Glacier)] end subgraph "Analytics Pipeline" Stream[Stream Processing
Kinesis] Batch[Batch Processing
EMR] ML[ML Pipeline
SageMaker] end subgraph "Data Consumption" Dashboard[Analytics Dashboard] Reports[Reports] Export[Data Export] API_Out[API Output] end CSV --> Validate API --> Validate Form --> Validate Webhook --> Validate Validate --> Transform Transform --> Enrich Enrich --> Dedupe Dedupe --> Hot Hot --> Stream Hot --> Batch Batch --> Warm Warm --> Cold Stream --> ML ML --> Dashboard Batch --> Reports Hot --> API_Out Warm --> Export style Hot fill:#FF6B6B,color:#fff style ML fill:#22C55E,color:#fff

Data Partitioning Strategy

graph TB subgraph "Enterprise Boundary" NC[NudgeCampaign
Email Marketing Platform

AI-powered email marketing
with multi-tenant SaaS architecture] end subgraph "Users" Marketer[Marketing Manager

Creates and manages
email campaigns] Admin[System Administrator

Manages organization
settings and users] Contact[Email Recipient

Receives and interacts
with email campaigns] end subgraph "External Systems" Email[Postmark
Email Service

Handles email delivery
and tracking] Payment[Stripe
Payment Service

Processes subscriptions
and billing] AI[OpenRouter
AI Service

Provides LLM capabilities
for Maya AI] Auth[Supabase Auth
Authentication

Manages user authentication
and sessions] Analytics[PostHog
Analytics

Tracks user behavior
and product metrics] end Marketer -->|Creates campaigns| NC Admin -->|Manages system| NC NC -->|Sends emails| Contact NC -->|Delivers email| Email NC -->|Processes payments| Payment NC -->|AI conversations| AI NC -->|Authenticates users| Auth NC -->|Tracks events| Analytics style NC fill:#22C55E,color:#fff style Email fill:#4A90E2,color:#fff style Payment fill:#F59E0B,color:#fff style AI fill:#9333EA,color:#fff
0

Security Architecture

Security is built into every layer of the NudgeCampaign architecture, with defense in depth strategies.

Security Layers

graph TB subgraph "Security Perimeter" subgraph "Edge Security" CDN[CDN DDoS Protection] WAF[Web Application Firewall] RateLimit[Rate Limiting] end subgraph "Network Security" VPC[VPC Isolation] SG[Security Groups] NACL[Network ACLs] TLS[TLS 1.3 Encryption] end subgraph "Application Security" Auth[JWT Authentication] RBAC[Role-Based Access] RLS[Row Level Security] Audit[Audit Logging] end subgraph "Data Security" Encrypt[Encryption at Rest] Transit[Encryption in Transit] Backup[Encrypted Backups] PII[PII Protection] end subgraph "Compliance" GDPR[GDPR Compliance] PCI[PCI DSS] SOC2[SOC2 Type II] HIPAA[HIPAA Ready] end end Internet[Internet Traffic] --> CDN CDN --> WAF WAF --> RateLimit RateLimit --> VPC VPC --> Auth Auth --> RBAC RBAC --> RLS RLS --> Encrypt style WAF fill:#EF4444,color:#fff style RLS fill:#22C55E,color:#fff style GDPR fill:#4A90E2,color:#fff

Row Level Security Implementation

flowchart TB subgraph "RLS Flow" User[User Request] JWT[JWT Token] Validate[Validate Token] Extract[Extract Org ID] Policy[Apply RLS Policy] Filter[Filter Data] Return[Return Results] end subgraph "RLS Policies" OrgPolicy[Organization Policy
org_id = auth.org_id] UserPolicy[User Policy
user_id = auth.user_id] RolePolicy[Role Policy
role IN allowed_roles] end User --> JWT JWT --> Validate Validate --> Extract Extract --> Policy Policy --> OrgPolicy Policy --> UserPolicy Policy --> RolePolicy OrgPolicy --> Filter UserPolicy --> Filter RolePolicy --> Filter Filter --> Return style Policy fill:#EF4444,color:#fff style Filter fill:#22C55E,color:#fff

Authentication & Authorization Flow

sequenceDiagram participant User participant Frontend participant API participant Auth as Supabase Auth participant DB as PostgreSQL participant Cache as Redis User->>Frontend: Login Request Frontend->>Auth: Authenticate(email, password) Auth->>Auth: Validate Credentials Auth-->>Frontend: JWT Token + Refresh Token Frontend->>API: API Request + JWT API->>API: Validate JWT API->>Cache: Check Session alt Session Exists Cache-->>API: Session Data else Session Missing API->>Auth: Verify Token Auth-->>API: Token Valid API->>DB: Get User + Org DB-->>API: User Data API->>Cache: Store Session end API->>DB: Query with RLS Note over DB: RLS filters by org_id DB-->>API: Filtered Data API-->>Frontend: Response Frontend-->>User: Display Data

Integration Architecture

NudgeCampaign integrates with multiple external services to provide comprehensive functionality.

Integration Patterns

graph TB subgraph "Integration Layer" subgraph "Synchronous Integrations" REST[REST APIs
Request/Response] GraphQL[GraphQL
Flexible Queries] Webhook[Webhooks
Real-time Events] end subgraph "Asynchronous Integrations" Queue[Message Queue
Reliable Delivery] EventBus[Event Bus
Pub/Sub Pattern] Batch[Batch Processing
Scheduled Jobs] end subgraph "Adapters" PostmarkAdapter[Postmark Adapter] StripeAdapter[Stripe Adapter] OpenRouterAdapter[OpenRouter Adapter] n8nAdapter[n8n Adapter] end end API[API Server] --> REST API --> Queue REST --> PostmarkAdapter Queue --> StripeAdapter EventBus --> OpenRouterAdapter Batch --> n8nAdapter style Queue fill:#4A90E2,color:#fff style EventBus fill:#22C55E,color:#fff

Email Service Integration (Postmark)

sequenceDiagram participant Campaign as Campaign Service participant Queue as Job Queue participant Worker as Email Worker participant Postmark as Postmark API participant Webhook as Webhook Handler participant DB as Database Campaign->>Queue: Enqueue Send Job Queue->>Worker: Process Job Worker->>DB: Get Recipients loop For Each Batch Worker->>Postmark: Send Batch API Call Postmark-->>Worker: Message IDs Worker->>DB: Store Message IDs end Note over Postmark: Async Delivery Postmark->>Webhook: Delivery Event Webhook->>DB: Update Status Postmark->>Webhook: Open Event Webhook->>DB: Track Open Postmark->>Webhook: Click Event Webhook->>DB: Track Click

Payment Integration (Stripe)

flowchart TB subgraph "Subscription Flow" Start[User Selects Plan] Create[Create Customer] Session[Create Checkout Session] Payment[Process Payment] Confirm[Confirm Subscription] Provision[Provision Access] Webhook[Handle Webhooks] end subgraph "Webhook Events" SubCreated[subscription.created] SubUpdated[subscription.updated] SubDeleted[subscription.deleted] PaySuccess[payment.success] PayFailed[payment.failed] end Start --> Create Create --> Session Session --> Payment Payment --> Confirm Confirm --> Provision Webhook --> SubCreated Webhook --> SubUpdated Webhook --> SubDeleted Webhook --> PaySuccess Webhook --> PayFailed SubCreated --> Provision PayFailed --> Retry[Retry Logic] style Payment fill:#7A5FF5,color:#fff style Provision fill:#22C55E,color:#fff

AI Integration (OpenRouter)

graph TB subgraph "Maya AI Integration" subgraph "Request Flow" User[User Input] Context[Load Context] Enhance[Enhance Prompt] Route[Route to Model] end subgraph "OpenRouter" Claude[Claude 3 Opus] GPT4[GPT-4 Turbo] Mixtral[Mixtral 8x7B] Fallback[Fallback Model] end subgraph "Response Processing" Stream[Stream Response] Parse[Parse Output] Filter[Content Filter] Store[Store Conversation] end end User --> Context Context --> Enhance Enhance --> Route Route -->|Complex| Claude Route -->|General| GPT4 Route -->|Fast| Mixtral Route -->|Error| Fallback Claude --> Stream GPT4 --> Stream Mixtral --> Stream Fallback --> Stream Stream --> Parse Parse --> Filter Filter --> Store style Claude fill:#9333EA,color:#fff style GPT4 fill:#22C55E,color:#fff

Deployment Architecture

NudgeCampaign uses modern CI/CD practices for reliable, automated deployments.

CI/CD Pipeline

flowchart LR subgraph "Development" Dev[Developer
Local Environment] Test[Run Tests] Commit[Git Commit] end subgraph "CI Pipeline" GitHub[GitHub Actions] Build[Build Docker Images] UnitTest[Unit Tests] IntTest[Integration Tests] Security[Security Scan] Quality[Code Quality] end subgraph "CD Pipeline" Stage[Deploy to Staging] E2E[E2E Tests] Approve[Manual Approval] Prod[Deploy to Production] Monitor[Health Checks] Rollback[Rollback if Failed] end Dev --> Test Test --> Commit Commit --> GitHub GitHub --> Build Build --> UnitTest UnitTest --> IntTest IntTest --> Security Security --> Quality Quality --> Stage Stage --> E2E E2E --> Approve Approve --> Prod Prod --> Monitor Monitor -->|Failed| Rollback style GitHub fill:#333,color:#fff style Prod fill:#22C55E,color:#fff style Rollback fill:#EF4444,color:#fff

Blue-Green Deployment Strategy

graph TB subgraph "Load Balancer" ALB[Application Load Balancer] end subgraph "Current Production (Blue)" Blue1[App Instance 1] Blue2[App Instance 2] Blue3[App Instance 3] end subgraph "New Version (Green)" Green1[App Instance 1 v2] Green2[App Instance 2 v2] Green3[App Instance 3 v2] end subgraph "Database" DB[(PostgreSQL
Shared Database)] end ALB -->|100% Traffic| Blue1 ALB -->|0% Traffic| Green1 Blue1 --> DB Blue2 --> DB Blue3 --> DB Green1 --> DB Green2 --> DB Green3 --> DB style Blue1 fill:#4A90E2,color:#fff style Green1 fill:#22C55E,color:#fff

Infrastructure as Code

graph TB subgraph "NudgeCampaign System Boundary" subgraph "Frontend Containers" SPA[Single Page Application
Container: React/Next.js

Provides user interface
for campaign management] Mobile[Mobile Application
Container: React Native

Mobile access to
core features] end subgraph "Backend Containers" API[API Application
Container: Node.js

Handles business logic
and API endpoints] Maya[Maya AI Service
Container: Node.js

Manages AI conversations
and content generation] Worker[Background Worker
Container: Node.js

Processes async jobs
and email sending] Scheduler[Scheduler Service
Container: Node.js

Manages scheduled
campaign sends] end subgraph "Data Containers" DB[(PostgreSQL Database
Container: PostgreSQL 14

Stores all application
data with RLS)] Cache[(Redis Cache
Container: Redis 7

Session storage and
temporary data)] Queue[(Job Queue
Container: Redis/Bull

Manages background
job processing)] Files[(File Storage
Container: S3/MinIO

Stores attachments
and assets)] end end subgraph "External Services" Postmark[Postmark API] Stripe[Stripe API] OpenRouter[OpenRouter API] end SPA -->|HTTPS/JSON| API Mobile -->|HTTPS/JSON| API API -->|SQL| DB API -->|Redis Protocol| Cache API -->|Enqueue Jobs| Queue Worker -->|Dequeue Jobs| Queue Worker -->|HTTPS| Postmark Maya -->|HTTPS| OpenRouter API -->|HTTPS| Stripe Scheduler -->|Trigger Jobs| Queue API -->|Store Files| Files style SPA fill:#61DAFB,color:#000 style API fill:#68A063,color:#fff style Maya fill:#22C55E,color:#fff style DB fill:#336791,color:#fff style Cache fill:#DC382D,color:#fff
0

Performance Architecture

Performance optimization is critical for user experience and system efficiency.

Caching Strategy

graph TB subgraph "Multi-Level Cache" subgraph "Edge Cache" CDN[CDN Cache
Static Assets] end subgraph "Application Cache" Redis1[Session Cache
User Sessions] Redis2[Data Cache
Frequently Accessed] Redis3[Query Cache
Database Results] end subgraph "Database Cache" PGCache[PostgreSQL Cache
Query Plans] IndexCache[Index Cache
B-Tree Indexes] end end Request[User Request] --> CDN CDN -->|Miss| Redis1 Redis1 -->|Miss| Redis2 Redis2 -->|Miss| Redis3 Redis3 -->|Miss| PGCache PGCache -->|Miss| DB[(Database)] style CDN fill:#FF9900,color:#fff style Redis2 fill:#DC382D,color:#fff

Load Distribution

flowchart TB subgraph "Load Distribution" LB[Load Balancer] subgraph "API Servers" API1[API Server 1
CPU: 40%] API2[API Server 2
CPU: 35%] API3[API Server 3
CPU: 45%] end subgraph "Worker Pool" W1[Worker 1
Jobs: 150] W2[Worker 2
Jobs: 120] W3[Worker 3
Jobs: 130] end subgraph "Database" Primary[(Primary
Writes)] Replica1[(Replica 1
Reads)] Replica2[(Replica 2
Reads)] end end LB -->|Round Robin| API1 LB --> API2 LB --> API3 API1 -->|Write| Primary API2 -->|Read| Replica1 API3 -->|Read| Replica2 Queue[Job Queue] --> W1 Queue --> W2 Queue --> W3 style Primary fill:#EF4444,color:#fff style Replica1 fill:#22C55E,color:#fff

Performance Optimization Techniques

  1. Database Optimization

    • Index optimization for common queries
    • Query plan caching
    • Connection pooling
    • Read replicas for load distribution
    • Partitioning for large tables
  2. Application Optimization

    • Code splitting and lazy loading
    • Image optimization and WebP format
    • Gzip/Brotli compression
    • HTTP/2 and HTTP/3 support
    • Service worker caching
  3. Infrastructure Optimization

    • Auto-scaling based on metrics
    • Geographic distribution with CDN
    • Edge computing for latency reduction
    • Container resource limits
    • Efficient Docker image layers

Monitoring and Observability

Comprehensive monitoring ensures system health and enables rapid issue resolution.

Monitoring Stack

graph TB subgraph "Data Collection" App[Application Metrics] Infra[Infrastructure Metrics] Logs[Application Logs] Traces[Distributed Traces] Events[Business Events] end subgraph "Processing" Prometheus[Prometheus
Metrics Storage] Loki[Loki
Log Aggregation] Jaeger[Jaeger
Trace Analysis] Kafka[Kafka
Event Stream] end subgraph "Visualization" Grafana[Grafana
Dashboards] Kibana[Kibana
Log Analysis] Custom[Custom Dashboard
Business Metrics] end subgraph "Alerting" PagerDuty[PagerDuty
Incident Management] Slack[Slack
Notifications] Email[Email
Alerts] end App --> Prometheus Infra --> Prometheus Logs --> Loki Traces --> Jaeger Events --> Kafka Prometheus --> Grafana Loki --> Kibana Jaeger --> Grafana Kafka --> Custom Grafana --> PagerDuty Grafana --> Slack Kibana --> Email style Prometheus fill:#E6522C,color:#fff style Grafana fill:#F46800,color:#fff

Key Metrics and SLIs

graph LR subgraph "Service Level Indicators" subgraph "Availability" Uptime[Uptime
99.9% target] Error[Error Rate
<1% target] end subgraph "Performance" Latency[P95 Latency
<200ms] Throughput[Throughput
>1000 req/s] end subgraph "Business" Delivery[Email Delivery
>98% success] Conversion[Conversion Rate
>2.5%] end end style Uptime fill:#22C55E,color:#fff style Latency fill:#4A90E2,color:#fff style Delivery fill:#F59E0B,color:#fff

Distributed Tracing

sequenceDiagram participant User participant API participant Auth participant DB participant Cache participant Email Note over User,Email: Trace ID: abc-123-def User->>+API: POST /campaigns
Span: api-request API->>+Auth: Validate Token
Span: auth-check Auth-->>-API: Token Valid
Duration: 15ms API->>+Cache: Check Cache
Span: cache-lookup Cache-->>-API: Cache Miss
Duration: 5ms API->>+DB: Query Database
Span: db-query DB-->>-API: Results
Duration: 45ms API->>+Email: Queue Email
Span: email-queue Email-->>-API: Queued
Duration: 10ms API-->>-User: Response
Total: 75ms

Disaster Recovery

Comprehensive disaster recovery ensures business continuity in case of failures.

Backup Strategy

graph TB subgraph "Backup Types" Full[Full Backup
Weekly] Incremental[Incremental
Daily] Snapshot[Snapshots
Hourly] Continuous[Continuous
Real-time] end subgraph "Storage Locations" Primary[Primary Region
S3 Standard] Secondary[Secondary Region
S3 Cross-Region] Archive[Archive
Glacier] end subgraph "Recovery Points" RPO[RPO: 1 hour
Maximum data loss] RTO[RTO: 4 hours
Maximum downtime] end Full --> Primary Incremental --> Primary Snapshot --> Secondary Continuous --> Secondary Primary --> Archive Secondary --> Archive style Continuous fill:#22C55E,color:#fff style RPO fill:#F59E0B,color:#fff

Failover Architecture

graph TB subgraph "Primary Region (us-east-1)" Primary_ALB[ALB] Primary_App[Application] Primary_DB[(Primary DB)] Primary_Cache[(Redis)] end subgraph "Secondary Region (us-west-2)" Secondary_ALB[ALB - Standby] Secondary_App[Application - Standby] Secondary_DB[(Replica DB)] Secondary_Cache[(Redis - Standby)] end subgraph "Global Services" Route53[Route53
DNS Failover] CloudFront[CloudFront
Global CDN] end Route53 -->|Active| Primary_ALB Route53 -.->|Standby| Secondary_ALB Primary_ALB --> Primary_App Primary_App --> Primary_DB Primary_App --> Primary_Cache Secondary_ALB --> Secondary_App Secondary_App --> Secondary_DB Secondary_App --> Secondary_Cache Primary_DB -->|Replication| Secondary_DB CloudFront --> Route53 style Primary_ALB fill:#22C55E,color:#fff style Secondary_ALB fill:#FFA500,color:#fff

Recovery Procedures

flowchart TB Start[Incident Detected] Assess{Assess Severity} Minor[Minor Issue] Major[Major Outage] AutoRecover[Auto-Recovery
Self-healing] ManualFix[Manual Fix
Operations team] Failover[Initiate Failover] Validate[Validate Services] Switch[DNS Switch] Notify[Notify Users] PostMortem[Post-Mortem
Analysis] Start --> Assess Assess -->|Low| Minor Assess -->|High| Major Minor --> AutoRecover Minor --> ManualFix Major --> Failover Failover --> Validate Validate --> Switch Switch --> Notify AutoRecover --> PostMortem ManualFix --> PostMortem Notify --> PostMortem style Failover fill:#EF4444,color:#fff style PostMortem fill:#4A90E2,color:#fff

Scalability Patterns

NudgeCampaign implements various patterns to ensure seamless scaling.

Horizontal Scaling

graph TB subgraph "Auto-Scaling Groups" subgraph "API Tier" API_Min[Min: 2 instances] API_Desired[Desired: 4 instances] API_Max[Max: 20 instances] end subgraph "Worker Tier" Worker_Min[Min: 1 instance] Worker_Desired[Desired: 3 instances] Worker_Max[Max: 10 instances] end subgraph "Scaling Triggers" CPU[CPU > 70%] Memory[Memory > 80%] Queue[Queue Depth > 1000] Response[Response Time > 500ms] end end CPU --> API_Max Memory --> API_Max Queue --> Worker_Max Response --> API_Max style API_Desired fill:#22C55E,color:#fff style Worker_Desired fill:#4A90E2,color:#fff

Database Scaling

graph TB subgraph "API Application Container" subgraph "API Layer" REST[REST Controller

Handles HTTP requests
and responses] GraphQL[GraphQL Controller

Handles GraphQL
queries and mutations] WebSocket[WebSocket Controller

Real-time communication
for live updates] end subgraph "Business Logic Layer" CampaignService[Campaign Service

Campaign creation
and management] ContactService[Contact Service

Contact list
management] AnalyticsService[Analytics Service

Metrics and
reporting] BillingService[Billing Service

Subscription
management] AuthService[Auth Service

Authentication and
authorization] MayaService[Maya Service

AI assistant
integration] end subgraph "Data Access Layer" ORM[Prisma ORM

Database abstraction
and query builder] RLS[RLS Middleware

Row level security
enforcement] CacheManager[Cache Manager

Redis cache
operations] end subgraph "Integration Layer" EmailAdapter[Email Adapter

Postmark
integration] PaymentAdapter[Payment Adapter

Stripe
integration] AIAdapter[AI Adapter

OpenRouter
integration] end end REST --> CampaignService REST --> ContactService GraphQL --> AnalyticsService WebSocket --> MayaService CampaignService --> ORM ContactService --> ORM AnalyticsService --> CacheManager BillingService --> PaymentAdapter AuthService --> RLS MayaService --> AIAdapter ORM --> RLS style REST fill:#4A90E2,color:#fff style MayaService fill:#22C55E,color:#fff style RLS fill:#EF4444,color:#fff
0

Technology Stack Details

Core Technologies

Layer Technology Purpose Version
Frontend Next.js React framework 14.x
Frontend React UI library 18.x
Frontend TypeScript Type safety 5.x
Frontend Tailwind CSS Styling 3.x
Frontend shadcn/ui Component library Latest
Backend Node.js Runtime 20.x LTS
Backend Express Web framework 4.x
Backend Prisma ORM 5.x
Database PostgreSQL Primary database 14.x
Database Redis Cache & queues 7.x
Queue Bull Job queue 4.x
AI OpenRouter LLM gateway API v1
Email Postmark Email delivery API v1
Payments Stripe Subscriptions API v2023
Auth Supabase Authentication 2.x
Analytics PostHog Product analytics Cloud
Monitoring Datadog APM & logs Cloud
CDN CloudFront Content delivery AWS
Container Docker Containerization 24.x
Orchestration Kubernetes Container orchestration 1.28
CI/CD GitHub Actions Automation Cloud

Development Tools

Tool Purpose Configuration
ESLint Code linting Airbnb config
Prettier Code formatting Standard config
Jest Unit testing 29.x
Playwright E2E testing Latest
Husky Git hooks Pre-commit
Commitizen Commit standards Conventional
Swagger API documentation OpenAPI 3.0

API Architecture Patterns

RESTful API Design

graph TB subgraph "API Structure" subgraph "Resources" Campaigns[/campaigns] Contacts[/contacts] Templates[/templates] Analytics[/analytics] end subgraph "Operations" GET[GET - Read] POST[POST - Create] PUT[PUT - Update] DELETE[DELETE - Remove] PATCH[PATCH - Partial Update] end subgraph "Patterns" Pagination[Pagination
?page=1&limit=50] Filtering[Filtering
?status=active] Sorting[Sorting
?sort=-created_at] Expansion[Expansion
?expand=stats] end end Campaigns --> GET Campaigns --> POST Contacts --> PATCH Analytics --> GET GET --> Pagination GET --> Filtering GET --> Sorting GET --> Expansion style Campaigns fill:#4A90E2,color:#fff style GET fill:#22C55E,color:#fff

API Versioning Strategy

graph LR subgraph "Version Management" V1[API v1
Deprecated] V2[API v2
Stable] V3[API v3
Beta] V4[API v4
Development] end subgraph "Routing" Route1[/api/v1/*] Route2[/api/v2/*] Route3[/api/v3/*] Route4[/api/v4/*] end Client[API Clients] --> Route2 Route1 --> V1 Route2 --> V2 Route3 --> V3 Route4 --> V4 style V1 fill:#9CA3AF,color:#fff style V2 fill:#22C55E,color:#fff style V3 fill:#F59E0B,color:#fff

Conclusion

This technical architecture documentation provides a comprehensive overview of NudgeCampaign's system design, infrastructure, and implementation patterns. The architecture prioritizes:

  1. Security: Multi-layered security with RLS at its core
  2. Scalability: Horizontal scaling and serverless patterns
  3. Reliability: Multiple availability zones and disaster recovery
  4. Performance: Multi-level caching and optimization
  5. Maintainability: Clear separation of concerns and monitoring

The use of modern cloud-native technologies and best practices ensures that NudgeCampaign can scale to support thousands of organizations while maintaining security, performance, and reliability standards.

Key Takeaways

  • Multi-tenant architecture with complete data isolation
  • AI-first design with Maya integrated throughout
  • Serverless scalability for cost-effective operations
  • Enterprise security with GDPR and PCI compliance
  • Modern tech stack using proven technologies
  • Comprehensive monitoring for proactive issue resolution
  • Automated deployment with CI/CD pipelines
  • Disaster recovery with defined RPO/RTO targets

This architecture supports NudgeCampaign's mission to provide an innovative, secure, and scalable email marketing platform that leverages AI to deliver superior results for our customers.