Dropstake
Technical Documentation

System Architecture

Complete technical blueprint for the live commerce platform — covering infrastructure, data flow, scaling strategy, and security architecture.

Contents

01

High-Level Architecture

Dropstake follows a distributed, event-driven architecture optimized for spiky traffic patterns. The system separates concerns across five layers: client, API, real-time, media, and data.

System Overview
graph TB subgraph Clients ["Clients"] direction LR WEB["Web App
(Cloudflare Pages)"] IOS["iOS App
(Capacitor)"] AND["Android App
(Capacitor)"] end subgraph API ["API Layer — GCP Cloud Run"] direction LR GW["API Gateway
& Auth Middleware"] US["User
Service"] PS["Product
Service"] DS["Drop
Service"] CS["Campaign
Service"] OS["Order
Service"] end subgraph RT ["Real-Time Layer"] FS["Firebase
Firestore"] FCM["Push
Notifications"] end subgraph Media ["Media Layer — Bunny.net"] BS["Bunny
Stream"] BC["Bunny
CDN"] BO["Bunny
Optimizer"] end subgraph Data ["Data Layer — GCP"] PG["PostgreSQL
(Cloud SQL)"] RD["Redis
(Memorystore)"] PB["Pub-Sub
(Queue)"] end PAY["Stripe
Connect"] Clients --> GW GW --> US GW --> PS GW --> DS GW --> CS GW --> OS DS --> FS DS --> BS OS --> PB PB --> OS OS --> PAY US --> PG PS --> PG CS --> PG DS --> RD OS --> RD PS --> BC PS --> BO DS --> FCM
Key Design Principle: Every component is independently scalable and replaceable. The API layer auto-scales via Cloud Run, media delivery is entirely offloaded to Bunny.net, real-time sync is managed by Firebase, and the order processing pipeline uses Pub/Sub queues to absorb purchase surges without overwhelming the database.

02

Technology Stack

Each technology was selected for Dropstake's specific requirements: spiky traffic, live streaming, real-time interactivity, and financial transactions.

⚛️
Next.js / React.js
Cloudflare Pages
Mobile-first web application with SSR for SEO and initial load performance. Deployed to Cloudflare's 300+ edge locations with unlimited bandwidth and built-in DDoS protection.
📱
Capacitor
iOS & Android
Native wrapper for iOS and Android distribution. Shares the web codebase while providing native device APIs for push notifications, camera access, and haptic feedback during drops.
🚀
Node.js / TypeScript
GCP Cloud Run
Backend API services with full TypeScript end-to-end for shared types and validation. Cloud Run provides scale-to-zero (€0 when idle) and rapid scale-up during drop surges.
🗄️
PostgreSQL
GCP Cloud SQL
Primary relational database for users, products, orders, campaigns, and financial records. ACID transactions for payment integrity. Read replicas for surge traffic during drops.
Redis
GCP Memorystore
In-memory cache and real-time state store. Handles session data, product caching, rate limiting, and atomic inventory counters (DECR operations prevent overselling).
🔥
Firebase / Firestore
GCP Native
Real-time client synchronization for live chat, viewer presence, inventory updates, and notification delivery. Clients subscribe to documents and receive push updates automatically.
📺
Bunny Stream
Bunny.net
Live streaming (RTMP ingest → HLS delivery), automatic VOD archiving, and product video hosting. Handles transcoding to multiple quality levels for adaptive playback.
💳
Stripe Connect
Stripe
Payment processing, marketplace splits, escrow for crowdfunding campaigns, and automated payout distribution to the platform, influencers, and investors.

03

Frontend Architecture

A single codebase serves web, iOS, and Android. The frontend communicates with the backend via REST APIs and subscribes to real-time updates through Firebase.

Frontend Component Architecture
graph LR subgraph App ["Next.js Application"] direction TB PAGES["Pages and Routes"] COMP["Shared Components"] STATE["State Management
(React Context + Hooks)"] API_CLIENT["API Client Layer
(fetch + auth tokens)"] RT_CLIENT["Real-Time Client
(Firestore SDK)"] STREAM["Stream Player
(HLS.js + Bunny)"] end subgraph Deploy ["Deployment"] CF["Cloudflare Pages
(Web)"] CAP["Capacitor
(iOS / Android)"] end App --> CF App --> CAP API_CLIENT -->|"REST / JSON"| BACKEND["Cloud Run APIs"] RT_CLIENT -->|"WebSocket"| FIRE["Firestore"] STREAM -->|"HLS"| BUNNY["Bunny Stream CDN"]
LayerTechnologyPurpose
FrameworkNext.js 14+SSR, routing, API routes for edge middleware
StylingTailwind CSSUtility-first CSS with custom design tokens
StateReact Context + HooksGlobal state for auth, cart, and real-time data
Data FetchingTanStack QueryServer state, caching, optimistic updates
Real-TimeFirebase SDKFirestore listeners for chat, inventory, presence
VideoHLS.jsAdaptive bitrate streaming from Bunny Stream
NativeCapacitorPush notifications, camera, haptics, app shell

04

Backend Services

The backend is split into domain-specific services, all running on Cloud Run with auto-scaling. Each service owns its domain logic and communicates through well-defined APIs.

Service Architecture
graph TB GW["API Gateway
Auth + Rate Limiting + Routing"] subgraph Services ["Cloud Run Services"] US["User Service
Profiles, roles, follows"] PS["Product Service
Listings, media, search"] DS["Drop Service
Scheduling, streaming, events"] CS["Campaign Service
Crowdfunding, milestones"] OS["Order Service
Cart, checkout, inventory"] NS["Notification Service
Push, email, in-app"] AS["Analytics Service
Events, dashboards, reports"] end GW --> US GW --> PS GW --> DS GW --> CS GW --> OS GW --> NS GW --> AS US --> PG["PostgreSQL"] PS --> PG PS --> BUNNY["Bunny CDN"] DS --> PG DS --> REDIS["Redis"] DS --> FIRE["Firestore"] DS --> STREAM["Bunny Stream"] CS --> PG CS --> STRIPE["Stripe"] OS --> REDIS OS --> PUBSUB["Pub-Sub"] OS --> STRIPE NS --> FIRE NS --> FCM["FCM"] AS --> PG
ServiceResponsibilitiesDependencies
User ServiceRegistration, profiles, role management (creator/investor/customer), follow relationships, preferencesPostgreSQL, Better Auth
Product ServiceProduct CRUD, media uploads, search indexing, category management, video/image processing triggersPostgreSQL, Bunny CDN, Bunny Optimizer
Drop ServiceSchedule drops, manage stream lifecycle, trigger drop events, sync with Firestore, coordinate with Bunny StreamPostgreSQL, Redis, Firestore, Bunny Stream
Campaign ServiceCrowdfunding campaigns, investment tiers, milestone tracking, escrow management, payout triggersPostgreSQL, Stripe Connect
Order ServiceOrder queue processing, inventory management (atomic Redis ops), payment execution, order historyRedis, Pub/Sub, Stripe, PostgreSQL
Notification ServicePush notifications (FCM), email (transactional), in-app notifications, drop reminders, investment alertsFirestore, FCM, Email provider
Analytics ServiceEvent tracking, creator dashboards, investor portfolio analytics, platform-wide reportingPostgreSQL (read replicas)

05

Database Schema

PostgreSQL serves as the source of truth for all relational data. The schema is normalized for integrity while using strategic denormalization for read-heavy queries.

Core Entity Relationships
erDiagram USERS ||--o{ PRODUCTS : creates USERS ||--o{ INVESTMENTS : makes USERS ||--o{ ORDERS : places USERS ||--o{ FOLLOWS : follows PRODUCTS ||--o{ DROPS : "launched via" PRODUCTS ||--|| CAMPAIGNS : "funded by" CAMPAIGNS ||--o{ INVESTMENTS : receives DROPS ||--o{ ORDERS : generates DROPS ||--o{ CHAT_MESSAGES : contains ORDERS ||--o{ ORDER_ITEMS : contains PRODUCTS ||--o{ MEDIA : has USERS { uuid id PK string email string role string display_name string avatar_url jsonb profile_data timestamp created_at } PRODUCTS { uuid id PK uuid creator_id FK string title text description decimal price decimal cogs integer total_units string status } CAMPAIGNS { uuid id PK uuid product_id FK decimal goal_amount decimal raised_amount integer backer_count timestamp deadline string status } DROPS { uuid id PK uuid product_id FK uuid creator_id FK string stream_id timestamp scheduled_at timestamp started_at string status integer peak_viewers } ORDERS { uuid id PK uuid user_id FK uuid drop_id FK decimal total string stripe_payment_id string status timestamp created_at } INVESTMENTS { uuid id PK uuid user_id FK uuid campaign_id FK decimal amount string status decimal return_amount }
Three-Database Strategy: PostgreSQL holds the source of truth (users, products, orders, financials). Redis holds ephemeral real-time state (inventory counters, sessions, cache). Firestore holds client-facing real-time data (chat, presence, live inventory projections). Data flows one direction: PostgreSQL → Redis/Firestore. If real-time stores fail, they rebuild from PostgreSQL.

06

Live Drop Flow

The drop is the atomic unit of Dropstake. This sequence covers the full lifecycle from scheduling to post-drop settlement.

Drop Lifecycle Sequence
sequenceDiagram participant C as Creator participant API as Cloud Run API participant R as Redis participant PS as Pub-Sub participant PG as PostgreSQL participant FS as Firestore participant BS as Bunny Stream participant V as Viewers participant S as Stripe Note over C,S: Phase 1 - Pre-Drop C->>API: Schedule drop API->>PG: Store drop record API->>FS: Create drop document FS-->>V: Push countdown Note over C,S: Phase 2 - Go Live C->>BS: Start RTMP stream BS-->>V: HLS video delivery API->>R: Load inventory into cache API->>FS: Update status to LIVE FS-->>V: Stream is live event Note over C,S: Phase 3 - Product Drop C->>API: Trigger drop API->>FS: Update drop document FS-->>V: Push BUY NOW overlay Note over C,S: Phase 4 - Purchase Rush V->>API: Place order API->>R: DECR inventory (atomic) R-->>API: Remaining count API->>PS: Enqueue order PS->>API: Worker picks up order API->>S: Process payment S-->>API: Payment confirmed API->>PG: Write order record API->>FS: Update inventory count FS-->>V: Push new inventory Note over C,S: Phase 5 - Post-Drop BS->>BS: Archive stream as VOD API->>PG: Generate financial report API->>S: Trigger profit distribution
1

Pre-Warm Infrastructure

Before a scheduled drop, Cloud Run pre-scales instances, Redis caches product data and initializes inventory counters, and Bunny Stream prepares the RTMP ingest endpoint.

2

Stream Goes Live

Creator begins broadcasting via the app. Bunny ingests the RTMP feed, transcodes to multiple quality levels, and delivers via HLS to all viewers. Firebase opens real-time listeners for chat and presence.

3

Drop Trigger

The creator triggers the product drop. Cloud Run updates a Firestore document, which pushes the BUY NOW event to all connected viewers within milliseconds.

4

Queue-Based Ordering

Purchase requests hit Cloud Run, which uses Redis DECR to atomically check and reserve inventory, then enqueues orders to Pub/Sub. Workers process orders sequentially — no overselling, no race conditions.

5

Settlement & Archive

After the drop ends, Bunny Stream archives the live stream as VOD. The Order Service generates financial reports and triggers profit distribution via Stripe Connect to the platform, influencer, and investors.


07

Real-Time Architecture

Firebase Firestore serves as the real-time sync layer. Clients subscribe to documents and receive instant updates. The backend writes to Firestore as a projection of PostgreSQL state.

Real-Time Data Flow
graph LR subgraph Backend ["Backend (Cloud Run)"] OS["Order Service"] DS["Drop Service"] end subgraph Firestore ["Firestore Collections"] DC["drops/{id}
status, inventory, viewers"] CC["drops/{id}/chat
messages"] PC["drops/{id}/presence
viewer list"] NC["users/{id}/notifications"] end subgraph Clients ["Connected Clients"] V1["Viewer 1"] V2["Viewer 2"] VN["Viewer N"] end OS -->|"inventory update"| DC DS -->|"drop status"| DC DS -->|"chat message"| CC DC -->|"onSnapshot"| V1 DC -->|"onSnapshot"| V2 DC -->|"onSnapshot"| VN CC -->|"onSnapshot"| V1 CC -->|"onSnapshot"| V2 CC -->|"onSnapshot"| VN
Firestore CollectionDocumentsPurposeUpdate Frequency
drops/{id}Drop stateStatus, inventory count, viewer count, active productHigh (during drop)
drops/{id}/chatChat messagesLive chat messages from viewers during streamHigh
drops/{id}/presenceViewer presenceWho is watching, viewer count, join/leave eventsMedium
users/{id}/notificationsUser notificationsDrop reminders, purchase confirmations, investment updatesLow
campaigns/{id}Campaign stateFunding progress, backer count (real-time projection)Low

08

Payment & Revenue Flow

Stripe Connect manages the entire financial flow — from customer payment through escrow to automated profit distribution among the platform, influencer, and investors.

Revenue Distribution Flow
graph TB CUST["Customer Pays 100"] STRIPE["Stripe Processes Payment"] FEE["Platform Fee 10%"] STRIPE_FEE["Stripe Fee 3.2%"] NET_FEE["Net Platform Fee 6.80"] REMAIN["Remaining 90"] COGS_D["COGS Deducted 40"] PROFIT["Distributable Profit 50"] PLAT["Platform 25% = 12.50"] INF_S["Influencer 25% = 12.50"] INV_S["Investors 50% = 25.00"] CUST --> STRIPE STRIPE --> FEE STRIPE --> REMAIN FEE --> STRIPE_FEE FEE --> NET_FEE REMAIN --> COGS_D COGS_D --> PROFIT PROFIT --> PLAT PROFIT --> INF_S PROFIT --> INV_S classDef blueFill fill:#285EF7,color:#fff,stroke:none classDef pinkFill fill:#EC4899,color:#fff,stroke:none classDef greenFill fill:#22C55E,color:#fff,stroke:none class FEE,PLAT blueFill class INF_S pinkFill class INV_S greenFill
Crowdfunding Escrow Flow
graph LR INV_F["Investor Commits Funds"] --> ESC["Stripe Escrow"] ESC -->|"Goal Met"| REL["Funds Released"] ESC -->|"Goal Not Met"| REF["Funds Refunded"] REL --> PROD["Product Manufactured"] PROD --> DROP_E["Drop Event"] DROP_E --> DIST["Profit Distribution"] DIST --> P1["Platform 25%"] DIST --> P2["Influencer 25%"] DIST --> P3["Investors 50%"]

09

Media Pipeline

All media — live streams, VOD replays, product videos, and product images — flows through Bunny.net's infrastructure for processing and global delivery.

Media Processing Pipeline
graph TB subgraph Input ["Content Input"] LIVE["Live Stream
(RTMP from App)"] VID["Product Video
(Upload)"] IMG["Product Images
(Upload)"] end subgraph Processing ["Bunny.net Processing"] BS_INGEST["Bunny Stream
RTMP Ingest"] BS_TRANS["Transcoding
1080p / 720p / 480p"] BS_VOD["VOD Archive"] BO["Bunny Optimizer
Resize + WebP/AVIF"] BSTORE["Bunny Storage
Origin Store"] end subgraph Delivery ["Global Delivery"] CDN["Bunny CDN
119+ Edge Locations"] end subgraph Clients ["Clients"] HLS["HLS Player
(Adaptive Bitrate)"] IMGC["Image Tags
(Responsive)"] end LIVE --> BS_INGEST --> BS_TRANS --> CDN --> HLS BS_TRANS --> BS_VOD --> CDN VID --> BS_TRANS IMG --> BSTORE --> BO --> CDN --> IMGC
Media TypeProcessingStorageDelivery
Live StreamsRTMP ingest → HLS transcoding (1080/720/480p)Auto-archive to Bunny StreamBunny CDN (HLS adaptive)
VOD ReplaysSame as live (already transcoded)Bunny Stream storageBunny CDN (HLS adaptive)
Product VideosUpload → Bunny Stream transcodingBunny Stream storageBunny CDN (HLS adaptive)
Product ImagesUpload → Bunny Optimizer (resize, crop, WebP/AVIF)Bunny StorageBunny CDN + Optimizer (on-the-fly)
User AvatarsUpload → Bunny OptimizerBunny StorageBunny CDN

10

Authentication & Authorization

Better Auth provides self-hosted authentication with full control over the user data model. Role-based access control governs what each user type can do across the platform.

Auth Flow
graph LR USER["User"] -->|"Email / Social Login"| BA["Better Auth
(Self-Hosted)"] BA -->|"Verify + Issue Token"| JWT["JWT Session
Token"] JWT -->|"Attached to Requests"| GW["API Gateway"] GW -->|"Validate + Extract Role"| RBAC["RBAC Middleware"] RBAC -->|"creator"| CREATOR_API["Creator Endpoints
Drops, Products, Analytics"] RBAC -->|"investor"| INVESTOR_API["Investor Endpoints
Campaigns, Portfolio"] RBAC -->|"customer"| CUSTOMER_API["Customer Endpoints
Shop, Orders, Wishlist"] BA -->|"Store Sessions"| PG["PostgreSQL"]
RolePermissionsRestricted From
CreatorCreate products, schedule drops, go live, view analytics, manage storefrontInvesting in own products
InvestorBrowse campaigns, invest, track portfolio, view returns, withdrawCreating products, going live
CustomerBrowse, watch streams, purchase products, follow creators, wishlistCreating products, investing (unless upgraded)
AdminAll operations, user management, platform analytics, content moderationNothing

11

Scaling Strategy

Dropstake's traffic is highly spiky — long idle periods punctuated by extreme surges during drops. The architecture is designed to handle 50,000+ concurrent viewers scaling from near-zero in seconds.

Scaling Layers
graph TB subgraph Auto ["Auto-Scaling (No Manual Intervention)"] CR["Cloud Run
0 → 1000 instances
in seconds"] CF["Cloudflare CDN
300+ edges
unlimited bandwidth"] BC["Bunny CDN
119+ edges
auto-scale delivery"] end subgraph Managed ["Managed Scaling"] PG_R["PostgreSQL
Read Replicas
(add during growth)"] REDIS["Redis
Scale memory
(vertical)"] end subgraph Absorb ["Surge Absorption"] QUEUE["Pub-Sub Queue
Absorbs 10K+ orders/sec
Workers process sequentially"] CACHE["Redis Cache
Product data pre-warmed
Reduces DB reads 95%"] FS_RT["Firestore
Handles 1M+ connections
Push updates, not polling"] end
1

Pre-Drop Warming

Before a scheduled drop, Cloud Run minimum instances are set to 10-20 (configurable per expected audience size). Redis caches all product data. Bunny Stream confirms RTMP endpoint readiness.

2

During Drop — Read Path

Product pages served from Redis cache (no DB hits). Stream delivered by Bunny CDN globally. Real-time updates pushed by Firestore (no polling). Frontend assets served by Cloudflare edge. Result: the read path is entirely cache/CDN-served.

3

During Drop — Write Path

Purchase requests enqueued to Pub/Sub (absorbs any burst instantly). Workers process orders sequentially using Redis DECR for inventory. Only confirmed orders write to PostgreSQL. Result: the database never sees more than a steady stream of writes regardless of request volume.

4

Post-Drop Cooldown

Cloud Run scales back to minimum (or zero). Queue drains remaining orders. Infrastructure costs return to baseline within minutes.


12

Security & Compliance

Security is designed into every layer — from network edge to database, with special attention to financial data handling and bot protection during high-value drops.

🛡️
Edge Protection
Cloudflare
Enterprise DDoS mitigation, WAF rules, bot detection, and rate limiting at the CDN edge. Drop traffic spikes don't incur overage charges on Cloudflare.
🔐
API Security
Cloud Run
JWT token validation on every request. Role-based middleware enforces permissions. Rate limiting per user and per IP. Request signing for sensitive operations.
🤖
Bot Protection
Custom + Cloudflare
During drops, additional verification prevents automated purchasing bots from sniping limited inventory. Captcha challenges, device fingerprinting, and purchase velocity checks.
💰
Financial Security
Stripe PCI DSS
All payment processing handled by Stripe (PCI DSS Level 1 compliant). No card data touches Dropstake servers. Escrow protects investor funds until milestones are met.
🗄️
Data Encryption
GCP
All data encrypted at rest (AES-256) and in transit (TLS 1.3). Database connections via private VPC networking. No public database endpoints. Automated daily backups with point-in-time recovery.
📋
Compliance
GDPR + KYC
GDPR-compliant data handling with user consent management and right-to-deletion. KYC verification for investors above threshold amounts. Transparent data processing policies.

Dropstake

Dropstake System Architecture · Confidential