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.
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.
§ 1.0 Problem Scope & Core Objectives
01 / SCOPE1.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.

1.2 Market Analysis & 4 Technical Bottlenecks
Traditional tarot sites saturate viewports with intrusive banner ads, destroying meditative focus. Shuffling mechanics feel mechanical and unnatural.
Legacy platforms stitch isolated static card strings together without understanding inter-card synergies, question nuances, or emotional context.
Standard LLM implementations force users into 15–30s loading spinners before rendering full text, breaking contemplative mindfulness.
Unconstrained chatbots frequently issue dangerous medical, legal, or fatalistic proclamations, fostering unhealthy obsession and anxiety.


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 / ARCHITECTURETarotica 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.
2.2 Four End-to-End Execution Pipelines

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.

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.

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.
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 MODELMongoDB Atlas was architected with Mongoose 9.x schemas, ensuring transactional integrity and rapid query execution through compound sparse indexing and background TTL expirations.

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 / ALGORITHMS4.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;
};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:
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:
§ 5.0 Engineering Challenges & Solutions
05 / CHALLENGES


§ 6.0 Empirical Benchmarks & Production Metrics
06 / BENCHMARKS| Metric | Production Result | Industry Target | Status |
|---|---|---|---|
| First Contentful Paint (FCP) | 0.65 s | < 1.8 s | Excellent |
| Largest Contentful Paint (LCP) | 1.20 s | < 2.5 s | Excellent |
| Cumulative Layout Shift (CLS) | 0.000 | < 0.10 | Zero Shift |
| Time to First Token (TTFT) | 620 ms | < 1000 ms | Optimized SSE |
| Animation Frame Rate | 60 FPS | 60 FPS | Zero Jank |
| Production JS Bundle (gzip) | 213.45 kB | < 300 kB | Vite Rollup |
| Google Lighthouse Performance | 98 / 100 | > 90 | Top Tier |
| Google Lighthouse Accessibility | 96 / 100 | > 90 | High Contrast |
| Google Lighthouse Best Practices | 100 / 100 | > 90 | Perfect |
| Google Lighthouse SEO | 100 / 100 | > 90 | Perfect |
| Production Uptime (30 days) | 99.95% | > 99.9% | PM2 & Docker |
§ 7.0 Technical Figures & High-Fidelity Showcase
07 / FIGURESComplete architectural diagrams and production interface screenshots from the Tarotica project. Click any item to inspect in high-resolution Lightbox mode with scientific captions.













§ 8.0 Conclusion & Future Roadmap
08 / CONCLUSIONThe 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