HUY.
•
✨ SHIPPED · SINCE TAKEN OFFLINESHIPPED · SINCE TAKEN OFFLINE•2026•Full-stack Developer · Production Deployment & AI Ops

Tarotica: Full-stack Web Architecture Case Study — Bounded SSE Streaming, Virtual Carousel Physics, and Production Operations on DigitalOcean

Technical architecture report on Tarotica — a full-stack web application previously shipped to production and operated on DigitalOcean, integrating Google Gemini API via Server-Sent Events, Fisher-Yates shuffle algorithms, and containerized Docker operations.

Author & Lead Architect: Nguyễn Huy
PRODUCTION SOFTWARE ARCHITECTURE REPORT • 2026
Project Status
Shipped · Offline
Operated live, now archived
Infrastructure
Docker / DO
DigitalOcean Droplet + Nginx
AI Integration
Gemini API
SSE Streaming & Boundaries
Security & Edge
Cloudflare
Edge SSL & Secrets Isolation
ReactNode.jsExpressMongoDBGoogle Gemini APIDigitalOceanDockerCloudflareTailwind CSS

Executive Abstract

The Tarotica project was a full-stack web application previously operated in production, uniting three engineering pillars: Responsive interactive physics, Mathematically unbiased Fisher-Yates shuffle algorithms, and an Ethically bounded AI interpretation pipeline over Server-Sent Events (SSE). This case study documents the virtual carousel physics using Framer Motion, a structured prompt engine powered by Google Gemini API with heuristic continuation handling, MongoDB Atlas indexing preventing duplicate concurrent requests, and multi-stage containerized deployment on DigitalOcean.

Architecture:Client-Server SSE
Infrastructure:DigitalOcean Linux
Model Integration:Gemini API Stream
Operational State:Shipped · Offline

§ 1.0 Problem Scope & Core Objectives

01 / SCOPE

1.1 Product Mission & Philosophy

Tarotica was engineered under the design ethos “Mystical Aesthetics, Scientific Engineering”. Rather than functioning as a deterministic divination tool steeped in superstition, the platform is architected as an introspective Reflective Mirror — providing users with an aesthetically refined, ad-free sanctuary to inspect their emotional landscape and clarify complex life decisions through bounded, ethical artificial intelligence.

Cosmic Landing & Immersive Introspection Gateway (/)
Figure 5.Figure 5. Production landing interface demonstrating dynamic particle glow, serif cosmic typography, and the ethical 'Reflective Mirror' philosophy with one-click trial and sign-in.

1.2 Market Analysis & 4 Technical Bottlenecks

01 / CLUTTERED UX & AD OVERLOAD
Cluttered UX & Intrusive Ads

Traditional tarot sites saturate viewports with intrusive banner ads, destroying meditative focus. Shuffling mechanics feel mechanical and unnatural.

02 / STATIC RULE-BASED DISCONNECTION
Fragmented Text Concatenation

Legacy platforms stitch isolated static card strings together without understanding inter-card synergies, question nuances, or emotional context.

03 / HIGH TTFB & STREAM DISRUPTION
High Latency & Emotion Disruption

Standard LLM implementations force users into 15–30s loading spinners before rendering full text, breaking contemplative mindfulness.

04 / UNCONSTRAINED HALLUCINATION
Unconstrained LLM Hallucination

Unconstrained chatbots frequently issue dangerous medical, legal, or fatalistic proclamations, fostering unhealthy obsession and anxiety.

Account Registration & Transactional OTP Email Verification
Figure 6.Figure 6. Secure onboarding modal with Resend transactional email OTP verification, bcrypt hash storage, and MongoDB 300-second TTL auto-purge indexing.
Authentication Portal & Google OAuth 2.0 Integration
Figure 7.Figure 7. Dual authentication supporting credentials and Google OAuth 2.0 with HTTP-Only SameSite Strict JWT cookies protecting session identity.

1.3 Non-Functional Technical Requirements

  • Realtime Streaming UX: Đạt thời gian phản hồi token đầu tiên TTFT < 800ms qua kết nối HTTP Server-Sent Events (SSE).
  • 60fps Fluid Motion: Đạt tốc độ ổn định 60 khung hình/giây trên toàn bộ các vi tương tác 3D: xáo bài, băng chuyền thẻ vô cực và lật bài 3D có đổ bóng phối cảnh.
  • Idempotency & Zero Billing Discrepancy: Bảo đảm tính toàn vẹn kinh tế ảo — không bao giờ trừ trùng Thạch Anh kể cả khi mất kết nối mạng giữa chừng.
  • Resilient Self-healing AI: Tự động phát hiện và kích hoạt sub-stream nối tiếp nếu mô hình LLM bị ngắt giữa chừng do chạm trần token.

§ 2.0 System Architecture & Execution Pipelines

02 / ARCHITECTURE

Tarotica implements a multi-tier containerized architecture, optimizing end-to-end data throughput from the Client SPA down to Google Gemini 2.5 Flash streaming interpreters and MongoDB Atlas persistence.

End-to-End Distributed Architecture Topology of TaroticaARCHITECTURE TOPOLOGY
CLIENT LAYER: React 19 SPA + Framer Motion (60fps)
Vite 8 ESMTailwind CSS v4Web Audio API
│   HTTPS / WSS (Keep-Alive SSE Connection)   │
GATEWAY LAYER: Cloudflare Edge + Nginx Reverse Proxy
SSL Full StrictGzip / BrotliDDoS Shield
│   Internal Localhost Forwarding :5000   │
APPLICATION LAYER (Express 5.x Runtime)Docker Multi-stage • PM2 Cluster
Security Middleware
Rate-limit, CORS, JWT Cookie
Prompt Engine
4-Tier Ethical Taxonomy
Stream Pipeline
SSE + Self-healing Heuristic
▲   REST / Webhooks / External API   ▼
EXTERNAL SERVICES
• Google Gemini 2.5 Flash (Streaming LLM)
• PayOS (QR VietQR Banking Webhook)
• Resend API (Transactional OTP Email)
• Google OAuth 2.0 (Identity Services)
PERSISTENCE LAYER (MongoDB Atlas)
• Compound Sparse Unique Index (Idempotency)
• TTL Index (Auto-purge OTP in 300s)
• Text Index (Search 78 Card Symbols)
• Mongoose 9.x Schema Validation
Figure 1. Architectural blueprint showing Client SPA (React 19 + Framer Motion), Cloudflare Edge, Nginx reverse proxy, Node.js/Express application layer, Google Gemini 2.5 Flash streaming via SSE, and MongoDB Atlas persistence.

2.2 Four End-to-End Execution Pipelines

Contextual Taxonomy & Question Intent Selection Matrix (/topic)
Figure 9.Figure 9. Multi-domain topic selector (Love, Career, Finance, Self, Family, Study, Daily Message) capturing nuance to prime Gemini 2.5 Flash context injection.
PIPELINE 01: SESSION & QUOTA VERIFICATION

Client sends GET /api/readings/check-limit. The protect middleware verifies the HTTP-Only JWT cookie. The backend evaluates zero-hour UTC+7 reset: granting 1 free daily draw if user.lastDrawDate < today, then validating active welcome crystals (7-day TTL) and purchased crystal balance.

60 FPS Virtual Infinite Carousel Track & Selection Shelf (/selection)
Figure 10.Figure 10. Virtual infinite carousel powered by Framer Motion physics with depth of field blur, spring inertia dampening, and top selection shelf holding chosen cards.
PIPELINE 02: SHUFFLING & SELECTION ENGINE

At /shuffling, 3D animations trigger accompanied by synthesized sound layers. The 78-card deck is shuffled via Fisher-Yates in O(N) time. Across a 60-slot virtual carousel, selecting a card executes a Bernoulli trial (p=0.5) determining Upright vs. Reversed orientation.

Realtime SSE Interpretation & 3-Card Spread Analysis (/reading)
Figure 11.Figure 11. Live streamed interpretation (< 650ms TTFT) rendering energy overview, individual card synthesis with orientations, and follow-up inquiry chat context.
PIPELINE 03: SERVER-SENT EVENTS (SSE) & SELF-HEALING STREAM

Client posts reading payload with clientRequestId. The server checks idempotency, deducts crystals, and opens a text/event-stream response. Gemini 2.5 Flash streams tokens in real time. The heuristic getIncompleteReason inspector triggers an automated continuation sub-stream if markdown headings or sentences are truncated.

PIPELINE 04: COMPACT CONTEXT FOLLOW-UP CHAT

Post-reading, users may probe deeper via POST /api/readings/chat. The engine compresses prior reading context into < 1800 characters, maximizing semantic relevance while slashing token consumption within user tier limits.

§ 3.0 Data Modeling & Indexing Strategy

03 / DATA MODEL

MongoDB Atlas was architected with Mongoose 9.x schemas, ensuring transactional integrity and rapid query execution through compound sparse indexing and background TTL expirations.

Database Entity-Relationship Diagram (ERD) & Index DesignSCHEMA RELATIONSHIPS
collection: users
_id: ObjectId [PK]
email: String [Unique Index]
password: String (bcrypt hashed)
role: 'free' | 'premium' | 'admin'
crystals: Number (permanent)
welcomeCrystals: Number (7-day TTL)
dailyDraws: Number (0-1)
lastDrawDate: Date
collection: readings [Core]
_id: ObjectId [PK]
userId: ObjectId [Ref: users]
concern / topic / intent: Object
cards: Array<CardSelection>
aiReading: String (Markdown)
aiUsage: { inputTokens, outputTokens }
requestOwnerKey + clientRequestId: [Unique Sparse Index]
status: 'pending' | 'completed'
collection: orders (PayOS)
_id: ObjectId [PK]
orderCode: Int64 [Unique Index]
userId: ObjectId [Ref: users]
amount / crystalsGranted: Number
status: 'PENDING' | 'PAID' | 'CANCELLED'
collection: otps & cards
otps.createdAt: Date [TTL Index: 300s]
otps.otp: String (bcrypt hashed)
cards: 78 Rider-Waite-Smith cards
cards.search: Text Index [name, keywords]
Figure 3. Entity-Relationship model detailing User, Reading, Order, Card, and OTP collections with compound sparse unique indexes for race condition prevention and TTL auto-purge indexing.
User Profile Dashboard & Dual Crystal Wallet View (/profile)
Figure 8.Figure 8. User profile interface displaying account tier, dual energy balances (7-day welcome crystals and permanent crystals), ambient sound toggles, and reading history access.

3.2 Indexing & Concurrency Strategy

To eliminate duplicate crystal deductions under network latency or rapid button clicks, a Compound Sparse Unique Index was enforced on (requestOwnerKey, clientRequestId):

readingSchema.index(
  { requestOwnerKey: 1, clientRequestId: 1 },
  { unique: true, sparse: true }
);

// Tự động giải phóng rác OTP sau 300s
otpSchema.index({ createdAt: 1 }, { expireAfterSeconds: 300 });

§ 4.0 Core Algorithms & Mathematics

04 / ALGORITHMS

4.1 Fisher-Yates Modern Shuffle (Uniform Distribution)

The Fisher-Yates (Knuth) modern shuffle algorithm is implemented in CardSelectionScreen.jsx. It guarantees an unbiased uniform distribution where every permutation among 78! possibilities shares the exact mathematical probability 1 / 78!, eliminating sorting bias inherent in naive comparator sorting.

// Fisher-Yates Modern Shuffle: O(N) Time, O(N) Space
const shuffleArray = (array) => {
  const newArray = [...array];
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
  }
  return newArray;
};
• Time Complexity: O(N) with N = 78 cards
• Space Complexity: O(N) immutable array copy
• Uniform Probability: P(Permutation) = 1 / 78! = 8.78 × 10^(-116)

4.2 Infinite Virtual Carousel Kinematics & Physics

To achieve an infinite card-swiping sensation without overloading the DOM, the engine constructs a 61-slot virtual track (-30 to +30) using two-way modulo mapping to real card indexes:

i_real = ((i_virtual % N_deck) + N_deck) % N_deck
// Biến đổi thị giác liên tục theo khoảng cách tương đối d = (x_track + i_virtual * S) / S:
RotateY(d) = clamp(-45deg, d * 15deg, 45deg)
Scale(d) = clamp(0.85, 1.2 - 0.175 * |d|, 1.2)
Blur(d) = clamp(0px, |d| * 2.6px, 8px)
x_projected = x_current + v_x * 0.2 // Hấp thụ quán tính (Inertia Spring Snap)

4.3 Self-healing Heuristic Inspector & Sub-stream Continuation

When generating in-depth interpretations, LLMs may terminate abruptly upon token ceilings. The getIncompleteReason() heuristic inspector verifies 5 syntax criteria; if truncated, the backend lowers temperature to T = 0.65 and triggers buildContinuePrompt to seamlessly stitch the text back together:

Heuristic 01: Broken Markdown Heading
Regex: /##[^\n#]*$/ — Phát hiện câu bị cắt ngay sau thẻ tiêu đề heading.
Heuristic 02: Dangling Punctuation
Regex: /[,:;–—-]\s*$/ — Câu dừng ở dấu phẩy, dấu hai chấm hoặc dấu gạch nối.
Heuristic 03: Empty List Bullet
Regex: /(^|\n)\s*(?:[-*]|\d+\.)\s*$/ — Bị ngắt ngay tại đầu dòng danh sách.
Heuristic 04: Non-terminal Sentence
Regex: !/[.!?。!?…]$/ — Ký tự cuối không phải dấu chấm câu kết thúc hoàn chỉnh.

§ 5.0 Engineering Challenges & Solutions

05 / CHALLENGES
Crystal Currency Store & PayOS VietQR Payment Gateway (/crystals)
Figure 12.Figure 12. Virtual economy top-up interface presenting 3 pricing tiers (15K, 35K, 75K VND) with automated VietQR banking generation and webhook confirmation.
CHALLENGE 01:Optimizing High-Resolution Asset Loading
ARCHITECTURAL SOLUTION:Compressed deck assets to modern WebP format and implemented lazy hydration to prevent layout shift.
CHALLENGE 02:Handling Truncated Streaming Outputs
ARCHITECTURAL SOLUTION:Formulated an inspection heuristic to detect incomplete sentences and trigger continuation seamlessly.
CHALLENGE 03:State Preservation Across Navigation
ARCHITECTURAL SOLUTION:Engineered client-side session state adapters so users maintained active spread state upon refresh.
CHALLENGE 04:Concurrency & Duplicate Request Rejection
ARCHITECTURAL SOLUTION:Enforced compound unique indexing on request identifiers in MongoDB to prevent race conditions.
Executive System Analytics & Share Funnel Dashboard (/admin2004)
Figure 13.Figure 13. Realtime administrative control monitoring active users (1,420), premium subscriptions, total draws (6,920), share funnel conversion rates (76.2%), and trending topics.
User Registry & Role-Based Access Control Auditing
Figure 14.Figure 14. User management grid featuring real-time email search, role tags (ADMIN, PREMIUM, FREE), joined timestamps, and live crystal ledger auditing.

§ 6.0 Empirical Benchmarks & Production Metrics

06 / BENCHMARKS
MetricProduction ResultIndustry TargetStatus
First Contentful Paint (FCP)0.65 s< 1.8 sExcellent
Largest Contentful Paint (LCP)1.20 s< 2.5 sExcellent
Cumulative Layout Shift (CLS)0.000< 0.10Zero Shift
Time to First Token (TTFT)620 ms< 1000 msOptimized SSE
Animation Frame Rate60 FPS60 FPSZero Jank
Production JS Bundle (gzip)213.45 kB< 300 kBVite Rollup
Google Lighthouse Performance98 / 100> 90Top Tier
Google Lighthouse Accessibility96 / 100> 90High Contrast
Google Lighthouse Best Practices100 / 100> 90Perfect
Google Lighthouse SEO100 / 100> 90Perfect
Production Uptime (30 days)99.95%> 99.9%PM2 & Docker

§ 7.0 Technical Figures & High-Fidelity Showcase

07 / FIGURES

Complete architectural diagrams and production interface screenshots from the Tarotica project. Click any item to inspect in high-resolution Lightbox mode with scientific captions.

FIGURE 1Expand ↗
SVG DIAGRAM
End-to-End Distributed Architecture Topology of Tarotica
Click to view detailed diagram
End-to-End Distributed Architecture Topology of Tarotica
Figure 1. Architectural blueprint showing Client SPA (React 19 + Framer Motion), Cloudflare Edge, Nginx reverse proxy, Node.js/Express application layer, Google Gemini 2.5 Flash streaming via SSE, and MongoDB Atlas persistence.
FIGURE 2Expand ↗
SVG DIAGRAM
Idempotent SSE Streaming & Auto-Continuation Sequence Flow
Click to view detailed diagram
Idempotent SSE Streaming & Auto-Continuation Sequence Flow
Figure 2. Execution sequence illustrating Idempotency validation, crystal deduction, real-time Gemini token streaming via SSE, and automated heuristic continuation sub-stream upon detecting broken headings or sentence cutoffs.
FIGURE 3Expand ↗
SVG DIAGRAM
Database Entity-Relationship Diagram (ERD) & Index Design
Click to view detailed diagram
Database Entity-Relationship Diagram (ERD) & Index Design
Figure 3. Entity-Relationship model detailing User, Reading, Order, Card, and OTP collections with compound sparse unique indexes for race condition prevention and TTL auto-purge indexing.
FIGURE 4Expand ↗
SVG DIAGRAM
Finite State Machine of the Multi-Step Tarot Experience
Click to view detailed diagram
Finite State Machine of the Multi-Step Tarot Experience
Figure 4. 9-stage client state machine spanning Introduction, Quota Guard, Topic/Intent Selection, Shuffling, Virtual Carousel, 3D Reveal, Streaming Reading, and Session Restoration.
FIGURE 5Expand ↗
Cosmic Landing & Immersive Introspection Gateway (/)
Cosmic Landing & Immersive Introspection Gateway (/)
Figure 5. Production landing interface demonstrating dynamic particle glow, serif cosmic typography, and the ethical 'Reflective Mirror' philosophy with one-click trial and sign-in.
FIGURE 6Expand ↗
Account Registration & Transactional OTP Email Verification
Account Registration & Transactional OTP Email Verification
Figure 6. Secure onboarding modal with Resend transactional email OTP verification, bcrypt hash storage, and MongoDB 300-second TTL auto-purge indexing.
FIGURE 7Expand ↗
Authentication Portal & Google OAuth 2.0 Integration
Authentication Portal & Google OAuth 2.0 Integration
Figure 7. Dual authentication supporting credentials and Google OAuth 2.0 with HTTP-Only SameSite Strict JWT cookies protecting session identity.
FIGURE 8Expand ↗
User Profile Dashboard & Dual Crystal Wallet View (/profile)
User Profile Dashboard & Dual Crystal Wallet View (/profile)
Figure 8. User profile interface displaying account tier, dual energy balances (7-day welcome crystals and permanent crystals), ambient sound toggles, and reading history access.
FIGURE 9Expand ↗
Contextual Taxonomy & Question Intent Selection Matrix (/topic)
Contextual Taxonomy & Question Intent Selection Matrix (/topic)
Figure 9. Multi-domain topic selector (Love, Career, Finance, Self, Family, Study, Daily Message) capturing nuance to prime Gemini 2.5 Flash context injection.
FIGURE 10Expand ↗
60 FPS Virtual Infinite Carousel Track & Selection Shelf (/selection)
60 FPS Virtual Infinite Carousel Track & Selection Shelf (/selection)
Figure 10. Virtual infinite carousel powered by Framer Motion physics with depth of field blur, spring inertia dampening, and top selection shelf holding chosen cards.
FIGURE 11Expand ↗
Realtime SSE Interpretation & 3-Card Spread Analysis (/reading)
Realtime SSE Interpretation & 3-Card Spread Analysis (/reading)
Figure 11. Live streamed interpretation (< 650ms TTFT) rendering energy overview, individual card synthesis with orientations, and follow-up inquiry chat context.
FIGURE 12Expand ↗
Crystal Currency Store & PayOS VietQR Payment Gateway (/crystals)
Crystal Currency Store & PayOS VietQR Payment Gateway (/crystals)
Figure 12. Virtual economy top-up interface presenting 3 pricing tiers (15K, 35K, 75K VND) with automated VietQR banking generation and webhook confirmation.
FIGURE 13Expand ↗
Executive System Analytics & Share Funnel Dashboard (/admin2004)
Executive System Analytics & Share Funnel Dashboard (/admin2004)
Figure 13. Realtime administrative control monitoring active users (1,420), premium subscriptions, total draws (6,920), share funnel conversion rates (76.2%), and trending topics.
FIGURE 14Expand ↗
User Registry & Role-Based Access Control Auditing
User Registry & Role-Based Access Control Auditing
Figure 14. User management grid featuring real-time email search, role tags (ADMIN, PREMIUM, FREE), joined timestamps, and live crystal ledger auditing.
FIGURE 15Expand ↗
Digital Asset Optimization: 00 - The Fool (WebP 85%)
Digital Asset Optimization: 00 - The Fool (WebP 85%)
Figure 15. Rider-Waite-Smith 78-card digital asset converted to WebP 85%, cutting total deck size from 45MB to 4.8MB with zero visual degradation and CLS = 0.
FIGURE 16Expand ↗
Major Arcana Sample: 02 - The High Priestess
Major Arcana Sample: 02 - The High Priestess
Figure 16. Card asset utilized in the virtual infinite carousel with dynamic perspective tilt and dynamic lighting reflections.
FIGURE 17Expand ↗
Tarotica Cosmic Brand Emblem & Visual Identity
Tarotica Cosmic Brand Emblem & Visual Identity
Figure 17. Minimalist cosmic emblem symbolizing the union between esoteric symbology and deterministic computational architecture.

§ 8.0 Conclusion & Future Roadmap

08 / CONCLUSION

The Tarotica project validates the capability to engineer production software from raw conceptualization down to resilient cloud operations. By harmonizing 60fps micro-interactions, deterministic mathematical randomness, and ethically bounded generative AI, the platform establishes that esoteric arts can be rigorously modernized into valuable digital tools.

Key Engineering Contributions

  • Owned the full engineering lifecycle: UI, backend APIs, LLM integration, and production deployment
  • Engineered real-time SSE streaming pipeline with continuation handling in Node.js/Express
  • Implemented mathematical Fisher-Yates card shuffle and interactive carousel animations
  • Configured multi-stage Docker runtime, Nginx reverse proxy, and Cloudflare DNS/SSL on DigitalOcean

Future Technical Roadmap

01 / WEBGL DECK SHADER
Upgrading card mesh rendering to Three.js/WebGL shaders with metallic gold foil reflection.
02 / EMBEDDINGS RAG JOURNAL
Vector embeddings over user journal logs to track emotional and psychological trends over time.
03 / MULTI-USER CO-DRAW
Real-time collaborative reading rooms over WebSockets for pair introspection.