Momentum Architecture Diagrams
This document provides comprehensive architecture diagrams for the Momentum Learning Management Platform. All diagrams are created using Mermaid syntax and can be rendered in any Mermaid-compatible viewer (GitHub, GitLab, VS Code with Mermaid extension, etc.).
Table of Contents
- High-Level System Architecture
- Data Flow Diagram
- Database Schema
- AI Content Generation Workflow
- Authentication & Authorization Flow
- Deployment Architecture
- Payment Flow
- Real-time Subscriptions
1. High-Level System Architecture
Purpose: Shows the main components of the Momentum platform and how they interconnect across the AWS cloud infrastructure.
Key Components:
- Client Layer: Web browsers and mobile devices accessing the platform
- AWS Amplify Hosting: Next.js frontend with built-in CDN for global content delivery
- API Layer: AWS API Gateway (REST) with API key and Cognito authentication
- Compute Layer: Lambda functions for business logic, ECS Fargate for long-running jobs, Step Functions for AI workflows
- Database & Cache: Aurora Serverless PostgreSQL and ElastiCache Redis (provisioned but unused in MVP)
- Storage & AI: S3 for files, Amazon Bedrock for AI text generation, HeyGen for video generation
- Supporting Services: SQS, SNS, SES, EventBridge, Secrets Manager
- Payment & Monitoring: Stripe integration, CloudWatch, X-Ray
File: docs/diagrams/01-high-level-architecture.mmd
graph TB
subgraph "Client Layer"
WEB[Web Browser]
MOBILE[Mobile Device]
end
subgraph "AWS Amplify Hosting"
NEXTJS[Next.js Frontend]
CDN[Built-in CDN]
end
subgraph "API Layer"
APIGATEWAY[AWS API Gateway REST API]
APICACHE[API Gateway Cache]
COGNITO[AWS Cognito User Pools]
end
subgraph "Compute Layer"
LAMBDA[AWS Lambda Functions]
ECS[ECS Fargate Workers]
STEPFN[Step Functions Workflows]
end
subgraph "Database & Cache"
AURORA[(Aurora Serverless PostgreSQL)]
REDIS[(ElastiCache Redis)]
end
subgraph "Storage & AI"
S3[S3 Storage]
BEDROCK[Amazon Bedrock Claude]
VIDEOAPI[Video AI APIs Synthesia/D-ID/HeyGen]
end
subgraph "Supporting Services"
SQS[Amazon SQS]
SNS[Amazon SNS]
SES[Amazon SES]
SECRETS[Secrets Manager]
OPENSEARCH[OpenSearch Serverless]
EVENTBRIDGE[EventBridge]
end
subgraph "Payment & Monitoring"
STRIPE[Stripe Payment API]
CLOUDWATCH[CloudWatch Logs/Metrics]
XRAY[X-Ray Tracing]
end
WEB --> CDN
MOBILE --> CDN
CDN --> NEXTJS
NEXTJS --> APIGATEWAY
NEXTJS --> COGNITO
APIGATEWAY --> APICACHE
APIGATEWAY --> LAMBDA
APIGATEWAY --> COGNITO
LAMBDA --> AURORA
LAMBDA --> REDIS
LAMBDA --> S3
LAMBDA --> BEDROCK
LAMBDA --> SQS
LAMBDA --> SECRETS
LAMBDA --> STRIPE
LAMBDA --> OPENSEARCH
STEPFN --> LAMBDA
STEPFN --> BEDROCK
STEPFN --> VIDEOAPI
STEPFN --> S3
ECS --> AURORA
ECS --> S3
ECS --> VIDEOAPI
SQS --> LAMBDA
SQS --> ECS
EVENTBRIDGE --> LAMBDA
EVENTBRIDGE --> STEPFN
SNS --> SES
LAMBDA --> CLOUDWATCH
ECS --> CLOUDWATCH
STEPFN --> CLOUDWATCH
APPSYNC --> CLOUDWATCH
LAMBDA --> XRAY
APPSYNC --> XRAY
style NEXTJS fill:#FF9900
style APPSYNC fill:#FF9900
style LAMBDA fill:#FF9900
style AURORA fill:#527FFF
style S3 fill:#569A31
style BEDROCK fill:#FF9900
Reference: CLAUDE.md - Technical Architecture
2. Data Flow Diagram
Purpose: Illustrates how data flows through the system for key user journeys including authentication, course enrollment, AI content generation, and progress tracking.
Key Flows:
- Authentication Flow: User login → Cognito → JWT token issuance
- Course Enrollment Flow: Browse courses → Payment → Enrollment creation → Email confirmation
- Content Generation Flow: Admin creates course → Step Functions → Bedrock/Video AI → S3 storage → Database update
- Progress Tracking Flow: User completes lesson → Progress update → Real-time subscription notification
File: docs/diagrams/02-data-flow-diagram.mmd
graph TB
subgraph "Authentication Flow"
A1[User Login Request]
A2[Cognito User Pools]
A3[JWT Token Issued]
A4[Token Stored in Frontend]
A1 --> A2
A2 --> A3
A3 --> A4
end
subgraph "Course Enrollment Flow"
B1[User Browses Courses]
B2[API Gateway: GET /courses]
B3[Lambda Handler]
B4[Aurora PostgreSQL]
B5[Course Data Returned]
B6[User Clicks Enroll]
B7[Payment Process via Stripe]
B8[API Gateway: POST /enrollments]
B9[Enrollment Record Created]
B10[Confirmation Email via SES]
B1 --> B2
B2 --> B3
B3 --> B4
B4 --> B5
B5 --> B1
B1 --> B6
B6 --> B7
B7 --> B8
B8 --> B9
B9 --> B10
end
subgraph "Content Generation Flow"
C1[Admin Creates Course]
C2[API Gateway: POST /ai-generation/generate-course]
C3[Step Functions Workflow Triggered]
C4[Bedrock Generates Lesson Text]
C5[Bedrock Generates Action Items]
C6[HeyGen Video API Request]
C7[Content Stored in S3]
C8[Database Updated with URLs]
C9[SNS Notification to Admin]
C10[Course Published]
C1 --> C2
C2 --> C3
C3 --> C4
C3 --> C5
C3 --> C6
C4 --> C7
C5 --> C7
C6 --> C7
C7 --> C8
C8 --> C9
C9 --> C10
end
subgraph "Progress Tracking Flow"
D1[User Completes Lesson]
D2[API Gateway: POST /progress]
D3[Lambda Updates Progress]
D4[Aurora Progress Table]
D5[Update User Statistics]
D6[Calculate Badges/Achievements]
D7[Frontend UI Updates]
D1 --> D2
D2 --> D3
D3 --> D4
D3 --> D5
D5 --> D6
D6 --> D7
end
A4 -.JWT Auth.-> B2
A4 -.JWT Auth.-> C2
A4 -.JWT Auth.-> D2
style A2 fill:#FF6B6B
style B4 fill:#4ECDC4
style C3 fill:#95E1D3
style D5 fill:#F38181
Reference: CLAUDE.md - REST API Endpoints
3. Database Schema
Purpose: Visualizes the PostgreSQL database schema with relationships between all core entities.
Key Tables:
- users: User accounts synchronized from Cognito
- categories: Course categorization
- courses: Course metadata and configuration
- lessons: Individual lesson content within courses
- enrollments: User-course enrollment records
- progress: Lesson completion tracking
- payments: Payment transaction records
Relationships:
- Users have many enrollments, progress records, and payments
- Categories contain many courses
- Courses have many lessons and enrollments
- Lessons are tracked by progress records
- Enrollments may be associated with payments
File: docs/diagrams/03-database-schema.mmd
erDiagram
USERS ||--o{ ENROLLMENTS : "enrolls in"
USERS ||--o{ PROGRESS : "tracks"
USERS ||--o{ PAYMENTS : "makes"
CATEGORIES ||--o{ COURSES : "contains"
COURSES ||--o{ LESSONS : "has"
COURSES ||--o{ ENROLLMENTS : "enrolled by"
LESSONS ||--o{ PROGRESS : "tracked by"
ENROLLMENTS ||--o| PAYMENTS : "paid via"
USERS {
uuid id PK
varchar cognito_sub UK
varchar email UK
varchar name
varchar role
text avatar_url
timestamp created_at
timestamp updated_at
}
CATEGORIES {
uuid id PK
varchar name
varchar slug UK
text description
text icon_url
timestamp created_at
}
COURSES {
uuid id PK
varchar title
text description
uuid category_id FK
integer duration_days
decimal price
text thumbnail
varchar status
jsonb metadata
timestamp created_at
timestamp updated_at
}
LESSONS {
uuid id PK
uuid course_id FK
integer day
varchar title
text content
text video_url
jsonb action_items
jsonb resources
integer order_index
timestamp created_at
timestamp updated_at
}
ENROLLMENTS {
uuid id PK
uuid user_id FK
uuid course_id FK
timestamp enrolled_at
timestamp completed_at
varchar payment_id
varchar stripe_subscription_id
varchar status
}
PROGRESS {
uuid id PK
uuid user_id FK
uuid lesson_id FK
boolean completed
timestamp completed_at
integer time_spent_seconds
timestamp created_at
timestamp updated_at
}
PAYMENTS {
uuid id PK
uuid user_id FK
decimal amount
varchar currency
varchar stripe_payment_id UK
varchar status
jsonb metadata
timestamp created_at
}
Reference: CLAUDE.md - Database Schema (PostgreSQL)
4. AI Content Generation Workflow
Purpose: Shows the Step Functions workflow for automated course content generation using Amazon Bedrock and third-party video AI APIs.
Workflow Steps:
- Admin triggers course generation via REST API (POST /ai-generation/generate-course)
- Validate course input and admin permissions
- Initialize Step Functions Express Workflow
- Generate course outline via Bedrock (Claude model)
- Sequential Lesson Generation: For each lesson in outline
- Generate lesson content (text) via Bedrock
- Generate action items via Bedrock
- Trigger video generation via HeyGen API
- Poll HeyGen for video completion (30-60 second intervals)
- Generate thumbnail image via Bedrock Stability AI
- Store all generated content in S3
- Update database with course, lessons, and asset URLs
- Send SNS notification to admin
- Course saved as draft for admin review before publishing
Error Handling:
- Validation errors logged to CloudWatch
- Bedrock requests retry up to 3 times
- Video generation falls back to placeholder on failure
- Admin alerts sent via SNS
File: docs/diagrams/04-ai-content-generation.mmd
graph TB
START([Admin Triggers Course Generation])
START --> VALIDATE[Validate Course ID & Permissions]
VALIDATE --> INITSTEP[Initialize Step Functions Workflow]
INITSTEP --> PARALLEL{Parallel Processing}
subgraph "Lesson Generation"
PARALLEL --> L1[Generate Lesson 1]
PARALLEL --> L2[Generate Lesson 2]
PARALLEL --> LN[Generate Lesson N]
L1 --> B1[Bedrock: Generate Text Content]
L2 --> B2[Bedrock: Generate Text Content]
LN --> BN[Bedrock: Generate Text Content]
B1 --> A1[Bedrock: Generate Action Items]
B2 --> A2[Bedrock: Generate Action Items]
BN --> AN[Bedrock: Generate Action Items]
A1 --> V1[Video API: Generate Video]
A2 --> V2[Video API: Generate Video]
AN --> VN[Video API: Generate Video]
end
V1 --> STORE[Store Content in S3]
V2 --> STORE
VN --> STORE
STORE --> TRANSCODE[MediaConvert: Transcode to HLS/DASH]
TRANSCODE --> DBUPDATE[Update Database with URLs]
DBUPDATE --> CACHE[Clear API Gateway Cache if enabled]
CACHE --> NOTIFY[Send SNS Notification]
NOTIFY --> DECISION{Auto-Publish?}
DECISION -->|Yes| PUBLISH[Publish Course]
DECISION -->|No| DRAFT[Save as Draft]
PUBLISH --> END([Workflow Complete])
DRAFT --> END
subgraph "Error Handling"
VALIDATE -.Error.-> ERRLOG[Log to CloudWatch]
B1 -.Retry 3x.-> B1
V1 -.Fallback.-> PLACEHOLDER[Use Placeholder Video]
ERRLOG --> ALERT[SNS Alert to Admin]
end
style START fill:#4CAF50
style END fill:#4CAF50
style PARALLEL fill:#2196F3
style STORE fill:#FF9800
style PUBLISH fill:#9C27B0
Reference: CLAUDE.md - AI Content Generation Workflow
5. Authentication & Authorization Flow
Purpose: Diagrams the complete authentication and authorization flow using AWS Cognito, including sign-up, sign-in, token management, and role-based access control.
Key Flows:
- User Sign-Up: Registration → Email verification → User record creation in database
- User Sign-In: Credential validation → JWT token issuance → Token storage in frontend
- Authenticated API Request: JWT validation → Authorization check → Business logic execution
- Token Refresh: Automatic token renewal using refresh token
- Admin-Only Operation: Role-based access control using
cognito:groups
JWT Token Contents:
sub: User unique identifieremail: User email addresscognito:groups: User roles (admin, premium, free)
File: docs/diagrams/05-authentication-flow.mmd
sequenceDiagram
participant User
participant Frontend as Next.js Frontend
participant Cognito as AWS Cognito
participant APIGateway as API Gateway
participant Lambda as Lambda Handler
participant Aurora as Aurora PostgreSQL
rect rgb(200, 220, 240)
Note over User,Aurora: User Sign-Up Flow
User->>Frontend: Enter email/password
Frontend->>Cognito: signUp(email, password)
Cognito->>Cognito: Create user account
Cognito->>Frontend: Return user (unconfirmed)
Cognito->>User: Send verification email
User->>Frontend: Enter verification code
Frontend->>Cognito: confirmSignUp(code)
Cognito->>Frontend: User confirmed
Cognito->>Lambda: Post-Confirmation Trigger
Lambda->>Aurora: INSERT INTO users (cognito_sub, email, role='FREE')
Aurora->>Lambda: User record created
end
rect rgb(220, 240, 220)
Note over User,Aurora: User Sign-In Flow
User->>Frontend: Enter credentials
Frontend->>Cognito: signIn(email, password)
Cognito->>Cognito: Validate credentials
Cognito->>Frontend: Return JWT tokens (ID, Access, Refresh)
Frontend->>Frontend: Store tokens in memory/localStorage
Note over Frontend: Token contains: sub, email, cognito:groups
end
rect rgb(240, 220, 220)
Note over User,Aurora: Authenticated API Request
User->>Frontend: Click "Enroll in Course"
Frontend->>Frontend: Get JWT from storage
Frontend->>APIGateway: POST /enrollments + JWT + x-api-key
APIGateway->>APIGateway: Validate API key
APIGateway->>Cognito: Validate JWT signature
Cognito->>APIGateway: Token valid, return claims
APIGateway->>Lambda: Invoke handler with user context
Lambda->>Lambda: Extract user info from event.requestContext
Lambda->>Aurora: INSERT INTO enrollments (user_id, course_id)
Aurora->>Lambda: Enrollment created
Lambda->>APIGateway: Return { success: true, data: enrollment }
APIGateway->>Frontend: JSON response
Frontend->>User: Show enrollment confirmation
end
rect rgb(240, 240, 200)
Note over User,Aurora: Token Refresh Flow
Frontend->>Frontend: Detect token expiry (1 hour)
Frontend->>Cognito: refreshSession(refreshToken)
Cognito->>Cognito: Validate refresh token
Cognito->>Frontend: New ID & Access tokens
Frontend->>Frontend: Update stored tokens
end
rect rgb(220, 200, 240)
Note over User,Aurora: Admin-Only Operation
User->>Frontend: Admin creates course
Frontend->>APIGateway: POST /courses + JWT + x-api-key
APIGateway->>Cognito: Validate JWT
Cognito->>APIGateway: Return user claims
alt User is Admin (cognito:groups contains "admin")
APIGateway->>Lambda: Invoke handler
Lambda->>Aurora: INSERT INTO courses
Aurora->>Lambda: Course created
Lambda->>APIGateway: Return { success: true, data: course }
APIGateway->>Frontend: Success response
else User is NOT Admin
APIGateway->>Frontend: 403 Forbidden Error
Frontend->>User: Access Denied
end
end
Reference: CLAUDE.md - Authentication & Authorization
6. Deployment Architecture
Purpose: Shows the AWS infrastructure components and the CI/CD deployment pipeline from developer workstation to production.
Infrastructure Layers:
- Developer Workstation: Git repository for version control
- CI/CD Pipeline: GitHub Actions for automation, Terraform for infrastructure provisioning
- Frontend Infrastructure: AWS Amplify Hosting with global CDN and build environment
- API & Auth: API Gateway (REST), Cognito User Pools
- Compute Services: Lambda functions (Auth, Courses, Payments, AI), ECS Fargate, Step Functions
- Data Layer: Aurora Serverless with Data API (no VPC required), ElastiCache Serverless
- Storage & AI: S3 buckets, Amazon Bedrock, OpenSearch Serverless
- Messaging & Events: SQS, SNS, EventBridge
- Monitoring & Security: CloudWatch, X-Ray, Secrets Manager, WAF
- External Services: Stripe, Video AI APIs
Deployment Flow:
- Git push triggers GitHub Actions
- Infrastructure changes deployed via Terraform
- Frontend changes trigger automatic Amplify build and deployment
- All services monitored via CloudWatch and X-Ray
File: docs/diagrams/06-deployment-architecture.mmd
graph TB
subgraph "Developer Workstation"
DEV[Developer]
GIT[Git Repository]
end
subgraph "CI/CD Pipeline"
GITHUB[GitHub Actions]
TERRAFORM[Terraform Cloud/CLI]
end
subgraph "AWS Cloud - US-East-1"
subgraph "Frontend Infrastructure"
AMPLIFY[AWS Amplify Hosting]
AMPCDN[Amplify CDN Global Edge]
AMPBUILD[Build Environment]
end
subgraph "API & Auth"
APIGATEWAY[API Gateway REST]
COGNITO[Cognito User Pools]
end
subgraph "Compute Services"
LAMBDA1[Lambda: Auth Functions]
LAMBDA2[Lambda: Course Functions]
LAMBDA3[Lambda: Payment Functions]
LAMBDA4[Lambda: AI Functions]
ECS[ECS Fargate Cluster]
STEPFN[Step Functions Workflows]
end
subgraph "Data Layer - No VPC Required"
AURORA[(Aurora Serverless v2 Data API)]
REDIS[(ElastiCache Serverless)]
end
subgraph "Storage & AI"
S3CONTENT[S3: Course Content]
S3MEDIA[S3: Video Media]
BEDROCK[Amazon Bedrock]
OPENSEARCH[OpenSearch Serverless]
end
subgraph "Messaging & Events"
SQS[SQS Queues]
SNS[SNS Topics]
EVENTBRIDGE[EventBridge]
end
subgraph "Monitoring & Security"
CLOUDWATCH[CloudWatch Logs/Metrics]
XRAY[X-Ray Tracing]
SECRETS[Secrets Manager]
WAF[AWS WAF]
end
subgraph "External Services"
STRIPE[Stripe API]
VIDEOAPI[Video AI APIs]
end
end
DEV -->|git push| GIT
GIT -->|webhook| GITHUB
GITHUB -->|Infrastructure Changes| TERRAFORM
GITHUB -->|Frontend Changes| AMPLIFY
TERRAFORM -->|Deploy| APPSYNC
TERRAFORM -->|Deploy| COGNITO
TERRAFORM -->|Deploy| LAMBDA1
TERRAFORM -->|Deploy| LAMBDA2
TERRAFORM -->|Deploy| LAMBDA3
TERRAFORM -->|Deploy| LAMBDA4
TERRAFORM -->|Deploy| ECS
TERRAFORM -->|Deploy| STEPFN
TERRAFORM -->|Deploy| AURORA
TERRAFORM -->|Deploy| REDIS
TERRAFORM -->|Deploy| S3CONTENT
TERRAFORM -->|Deploy| S3MEDIA
TERRAFORM -->|Deploy| SQS
TERRAFORM -->|Deploy| SNS
TERRAFORM -->|Deploy| EVENTBRIDGE
AMPLIFY -->|Build| AMPBUILD
AMPBUILD -->|Deploy| AMPCDN
AMPCDN -.HTTPS.-> APPSYNC
APPSYNC --> LAMBDA1
APPSYNC --> LAMBDA2
APPSYNC --> COGNITO
APIGATEWAY --> LAMBDA3
LAMBDA2 -->|Data API| AURORA
LAMBDA2 --> REDIS
LAMBDA2 --> S3CONTENT
LAMBDA2 --> OPENSEARCH
LAMBDA3 -->|HTTPS| STRIPE
LAMBDA3 --> SECRETS
LAMBDA4 --> STEPFN
STEPFN --> BEDROCK
STEPFN --> VIDEOAPI
STEPFN --> S3MEDIA
ECS --> S3MEDIA
ECS --> VIDEOAPI
SQS --> LAMBDA4
SQS --> ECS
EVENTBRIDGE --> LAMBDA4
EVENTBRIDGE --> STEPFN
WAF --> APPSYNC
WAF --> APIGATEWAY
LAMBDA1 --> CLOUDWATCH
LAMBDA2 --> CLOUDWATCH
LAMBDA3 --> CLOUDWATCH
LAMBDA4 --> CLOUDWATCH
ECS --> CLOUDWATCH
APPSYNC --> CLOUDWATCH
LAMBDA2 --> XRAY
APPSYNC --> XRAY
style AMPLIFY fill:#FF9900,stroke:#232F3E,stroke-width:2px
style APPSYNC fill:#FF9900,stroke:#232F3E,stroke-width:2px
style AURORA fill:#527FFF,stroke:#232F3E,stroke-width:2px
style S3CONTENT fill:#569A31,stroke:#232F3E,stroke-width:2px
style BEDROCK fill:#FF9900,stroke:#232F3E,stroke-width:2px
style TERRAFORM fill:#7B42BC,stroke:#232F3E,stroke-width:2px
Reference: CLAUDE.md - Deployment Process
7. Payment Flow
Purpose: Detailed sequence diagram showing payment processing flows for one-time purchases, subscriptions, payment failures, and refunds.
Payment Flows:
- One-Time Course Purchase:
- User initiates enrollment
- Frontend creates Stripe Payment Intent
- User enters card details and confirms payment
- Backend verifies payment and creates enrollment
- Confirmation email sent
- Subscription Flow (Future):
- User subscribes via Stripe Checkout
- Webhook processes subscription creation
- User upgraded to PREMIUM role
- Enrolled in all courses
- Welcome email sent
- Payment Failure Handling:
- Stripe sends payment failure webhook
- Payment status updated in database
- Failure notification email sent to user
- Refund Flow:
- User requests refund
- Backend processes refund via Stripe API
- Enrollment cancelled
- Refund confirmation email sent
File: docs/diagrams/07-payment-flow.mmd
sequenceDiagram
participant User
participant Frontend as Next.js Frontend
participant AppSync as AWS AppSync
participant Lambda as Payment Lambda
participant Stripe as Stripe API
participant Aurora as Aurora PostgreSQL
participant Webhook as API Gateway Webhook
participant SNS as Amazon SNS
participant SES as Amazon SES
rect rgb(240, 248, 255)
Note over User,SES: One-Time Course Purchase Flow
User->>Frontend: Click "Enroll in Course"
Frontend->>Frontend: Load Stripe.js
Frontend->>Stripe: Create Payment Intent
Stripe->>Frontend: Return client_secret
Frontend->>User: Show Stripe Payment Form
User->>Frontend: Enter card details
Frontend->>Stripe: Confirm Payment
Stripe->>Stripe: Process payment
Stripe->>Frontend: Payment succeeded
Frontend->>AppSync: enrollCourse(courseId, paymentIntentId)
AppSync->>Lambda: Invoke resolver
Lambda->>Stripe: Verify payment status
Stripe->>Lambda: Confirmed
Lambda->>Aurora: INSERT INTO enrollments
Lambda->>Aurora: INSERT INTO payments
Aurora->>Lambda: Success
Lambda->>AppSync: Return enrollment
AppSync->>Frontend: Enrollment confirmed
Frontend->>User: Show success message
end
rect rgb(255, 250, 240)
Note over User,SES: Subscription Flow (Future)
User->>Frontend: Click "Subscribe Monthly"
Frontend->>Stripe: Create Checkout Session
Stripe->>Frontend: Return checkout URL
Frontend->>User: Redirect to Stripe Checkout
User->>Stripe: Complete subscription signup
Stripe->>Webhook: subscription.created webhook
Webhook->>Lambda: Process webhook
Lambda->>Lambda: Verify webhook signature
Lambda->>Aurora: UPDATE users SET role='PREMIUM'
Lambda->>Aurora: INSERT INTO enrollments (all courses)
Aurora->>Lambda: Success
Lambda->>SNS: Publish subscription.created event
SNS->>SES: Send welcome email
SES->>User: Subscription confirmation email
end
rect rgb(255, 240, 245)
Note over User,SES: Payment Failure Handling
Stripe->>Webhook: payment_intent.payment_failed
Webhook->>Lambda: Process failure webhook
Lambda->>Lambda: Verify signature
Lambda->>Aurora: UPDATE payments SET status='failed'
Lambda->>SNS: Publish payment.failed event
SNS->>SES: Send payment failure email
SES->>User: Payment failed notification
end
rect rgb(240, 255, 240)
Note over User,SES: Refund Flow
User->>Frontend: Request refund
Frontend->>AppSync: requestRefund(enrollmentId)
AppSync->>Lambda: Process refund
Lambda->>Aurora: SELECT payment_id FROM enrollments
Aurora->>Lambda: Return stripe_payment_id
Lambda->>Stripe: Create refund
Stripe->>Lambda: Refund created
Lambda->>Aurora: UPDATE enrollments SET status='CANCELLED'
Lambda->>Aurora: UPDATE payments SET status='refunded'
Aurora->>Lambda: Success
Lambda->>AppSync: Refund confirmed
AppSync->>Frontend: Show confirmation
Stripe->>Webhook: charge.refunded webhook
Webhook->>Lambda: Process webhook
Lambda->>SNS: Publish refund.completed
SNS->>SES: Send refund confirmation
SES->>User: Refund processed email
end
Reference: CLAUDE.md - Payment Processing
8. Real-time Subscriptions
Purpose: Shows how AppSync GraphQL subscriptions enable real-time updates in the frontend when data changes occur.
Subscription Flows:
- WebSocket Connection Establishment:
- Frontend establishes WebSocket connection
- JWT token validated
- User subscribes to specific data updates
- Mutation Triggers Subscription:
- User performs action (e.g., complete lesson)
- Mutation executed via AppSync
- AppSync matches mutation to active subscriptions
- Update pushed to all subscribed clients via WebSocket
- UI automatically updates in real-time
- Course Update Subscription:
- Users subscribe to course changes
- Admin updates course
- All subscribed users receive instant update
- Frontend auto-refreshes without page reload
- Subscription Lifecycle Management:
- Graceful unsubscribe when navigating away
- Auto-disconnect after idle timeout
- Automatic reconnection with exponential backoff
- Error Handling:
- Mutation errors returned via GraphQL
- Subscription remains active
- Frontend implements retry logic
File: docs/diagrams/08-realtime-subscriptions.mmd
sequenceDiagram
participant User1 as User Device 1
participant User2 as User Device 2 (Dashboard)
participant Frontend as Next.js Frontend
participant AppSync as AWS AppSync
participant Lambda as Lambda Resolver
participant Aurora as Aurora PostgreSQL
participant Cache as AppSync Cache
rect rgb(230, 240, 255)
Note over User1,Cache: WebSocket Connection Establishment
Frontend->>AppSync: Connect WebSocket (wss://)
AppSync->>AppSync: Validate JWT token
AppSync->>Frontend: Connection established
Frontend->>AppSync: Subscribe to onProgressUpdate(userId)
AppSync->>AppSync: Register subscription
AppSync->>Frontend: Subscription confirmed
end
rect rgb(255, 240, 230)
Note over User1,Cache: Mutation Triggers Subscription
User1->>Frontend: Mark lesson complete
Frontend->>AppSync: markLessonComplete(lessonId) mutation
AppSync->>Lambda: Invoke resolver
Lambda->>Aurora: UPDATE progress SET completed=true
Lambda->>Aurora: SELECT * FROM progress WHERE id=...
Aurora->>Lambda: Return updated progress
Lambda->>Cache: Update cache entry
Lambda->>AppSync: Return progress data
Note over AppSync: AppSync matches mutation to subscriptions
AppSync->>AppSync: Find subscribers to onProgressUpdate
AppSync-->>Frontend: Push update via WebSocket (User1)
AppSync-->>User2: Push update via WebSocket (Dashboard)
Frontend->>User1: Update UI with completion
User2->>User2: Update progress chart in real-time
end
rect rgb(240, 255, 240)
Note over User1,Cache: Course Update Subscription
User2->>Frontend: Subscribe to onCourseUpdate(courseId)
AppSync->>AppSync: Register subscription for course
Note over User1: Admin updates course
User1->>Frontend: Update course title (Admin)
Frontend->>AppSync: updateCourse(id, input) mutation
AppSync->>Lambda: Invoke resolver (admin check)
Lambda->>Aurora: UPDATE courses SET title=...
Aurora->>Lambda: Return updated course
Lambda->>Cache: Invalidate course cache
Lambda->>AppSync: Return course data
AppSync-->>User1: Push update (Admin view)
AppSync-->>User2: Push update (Student view)
AppSync-->>Frontend: Push to all subscribed clients
Frontend->>User2: Auto-refresh course details
end
rect rgb(255, 245, 230)
Note over User1,Cache: Subscription Lifecycle Management
User2->>Frontend: Navigate away / close tab
Frontend->>AppSync: Unsubscribe from onCourseUpdate
AppSync->>AppSync: Remove subscription registration
AppSync->>Frontend: Unsubscribe confirmed
Note over Frontend: Cleanup after timeout
Frontend->>Frontend: No activity for 2 hours
AppSync->>AppSync: Auto-disconnect idle WebSocket
AppSync->>Frontend: Connection closed
Frontend->>Frontend: Attempt reconnection with backoff
end
rect rgb(255, 230, 230)
Note over User1,Cache: Error Handling
User1->>Frontend: Mark lesson complete
Frontend->>AppSync: markLessonComplete mutation
AppSync->>Lambda: Invoke resolver
Lambda->>Aurora: UPDATE progress...
Aurora-->>Lambda: Database error
Lambda-->>AppSync: Return error
AppSync-->>Frontend: GraphQL error response
Frontend->>User1: Show error message
Note over Frontend: Subscription remains active
Frontend->>Frontend: Retry mutation with exponential backoff
end
Reference: CLAUDE.md - GraphQL Schema Overview - Subscriptions
How to Use These Diagrams
Viewing Diagrams
- GitHub/GitLab: Diagrams render automatically in markdown files
- VS Code: Install the “Markdown Preview Mermaid Support” extension
- Online: Use Mermaid Live Editor to paste and edit diagrams
- Documentation Sites: Most static site generators support Mermaid natively
Editing Diagrams
- Open the
.mmdfile in thedocs/diagrams/directory - Edit the Mermaid syntax
- Preview using one of the methods above
- Save and commit changes
Diagram Syntax Reference
- Flowcharts:
graph TB(top to bottom),graph LR(left to right) - Sequence Diagrams:
sequenceDiagram - Entity Relationship:
erDiagram - Styling: Use
stylecommand or inline CSS classes
Full documentation: Mermaid Documentation
Architecture Decision Records
For detailed rationale behind architectural decisions, see:
Last Updated: 2025-11-28 Diagram Count: 8 Format: Mermaid 9.x+ Status: Complete