Loading publication...
AccessibleEPUB Pro (ZenPub) — SaaS System Design 1. Current State Analysis What You Have ┌─────────────────────────────────────────────────────┐ │ CURRENT ARCHITECTURE │ │ │ │ ┌──────────┐ ┌──────────────┐ ┌───────────┐ │ │ │ React │───▶│ FastAPI │───▶│ PostgreSQL│ │ │ │ SPA │ │ (monolith) │ │ (SQLite │ │ │ │ :5173 │ │ :8000 │ │ in dev) │ │ │ └──────────┘ └──────┬───────┘ └───────────┘ │ │ │ │ │ ┌────┴────┐ │ │ │ Local │ │ │ │ Disk │ │ │ │ Storage │ │ │ └─────────┘ │ │ │ │ Auth: JWT (HS256) + bcrypt │ │ Jobs: threading.Event in-process │ │ Email: None │ │ Billing: None │ │ Analytics: None │ │ CDN: None │ └─────────────────────────────────────────────────────┘ Strengths to preserve: ● Solid domain logic (conversion pipeline, EPUB generation, accessibility checks) ● Working JWT auth with refresh tokens, token blocklist, rate limiting ● Tenant/TenantUser models already scaffolded ● Clean REST API design with proper status codes ● HTML sanitization, security headers, input validation already in place
Gaps for SaaS: Area Current Needed Auth Email/password only OAuth2, SSO, MFA Billing None Stripe subscriptions + usage metering Feature gating None Tier-based access control Storage Local disk S3-compatible object storage Jobs In-process threads Distributed task queue Email None Transactional + marketing Analytics Console logs Product analytics + business metrics Deployment Docker Compose Container orchestration Multi-tenancy Models exist, not enforced Row-level isolation 2. Target Architecture ┌─────────────────┐ │ CloudFlare │ │ CDN / WAF │ └────────┬────────┘ │ ┌────────────────┼────────────────┐ │ │ │ ┌─────▼─────┐ ┌──────▼──────┐ ┌──────▼──────┐ │ Next.js │ │ React │ │ API │ │ Marketing │ │ App (SPA) │ │ Docs │ │ + Landing │ │ app.* │ │ docs.* │ └────────────┘ └──────┬──────┘ └─────────────┘ │ ┌──────▼──────┐ │ API │ │ Gateway │
│ (Kong/ │ │ Traefik) │ └──────┬──────┘ │ ┌────────────────────────┼────────────────────────┐ │ │ │ ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐ │ Auth │ │ Core API │ │ Billing │ │ Service │ │ Service │ │ Service │ │ (FastAPI) │ │ (FastAPI) │ │ (FastAPI) │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ │ │ ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐ │ Redis │ │ PostgreSQL │ │ Stripe │ │ (sessions, │ │ (primary) │ │ (payments) │ │ cache, │ └──────┬──────┘ └─────────────┘ │ rate limit)│ │ └─────────────┘ ┌──────▼──────┐ │ Celery / │ │ ARQ Workers │──────┐ └─────────────┘ │ │ ┌────────────────────────────────┼──────┐ │ │ │ ┌──────▼──────┐ ┌─────▼────┐ │ │ S3 / │ │ Claude / │ │ │ MinIO │ │ OpenAI │ │
│ (files) │ │ APIs │ │ └─────────────┘ └──────────┘ │ │ ┌────────────▼─┐ │ Email Service│ │ (SES/Resend) │ └──────────────┘ Phased Rollout Strategy Phase Timeline Scope Phase 1 — Auth + Billing foundation Weeks 1-4 OAuth, Stripe, feature flags, Redis Phase 2 — Infrastructure Weeks 5-8 S3 storage, Celery workers, email Phase 3 — SaaS features Weeks 9-12 Admin dashboard, analytics, usage metering Phase 4 — Scale Weeks 13-16 CDN, API gateway, horizontal scaling 3. Authentication & Authorization Layer 3.1 Auth Architecture ┌──────────────────────────────────────────────────────────── ───┐ │ AUTHENTICATION FLOW │ │ │ │ ┌──────────┐ ┌───────────┐ ┌──────────────────────┐ │
│ │ Client │────▶│ /auth/* │────▶│ Auth Service │ │ │ │ (React) │◀────│ routes │◀────│ │ │ │ └──────────┘ └───────────┘ │ ┌─────────────────┐ │ │ │ │ │ Local Provider │ │ │ │ Stores: │ │ (email/password) │ │ │ │ - access_token (memory) │ └─────────────────┘ │ │ │ - refresh_token (httpOnly cookie) │ ┌─────────────────┐ │ │ │ │ │ Google OAuth2 │ │ │ │ On 401: │ └─────────────────┘ │ │ │ - Try silent refresh │ ┌─────────────────┐ │ │ │ - If fails → login page │ │ Microsoft OIDC │ │ │ │ │ └─────────────────┘ │ │ │ │ ┌─────────────────┐ │ │ │ │ │ SAML/SSO │ │ │ │ │ │ (Enterprise) │ │ │ │ │ └─────────────────┘ │ │ │ └──────────────────────┘ │ └──────────────────────────────────────────────────────────── ───┘ 3.2 What Changes From Current
SQL Current security.py keeps its JWT signing, bcrypt hashing, and token blocklist. Add on top: NEW ENDPOINTS: POST /api/v1/auth/register — existing (add email verification) POST /api/v1/auth/login — existing (add MFA check) POST /api/v1/auth/refresh — existing (move refresh to httpOnly cookie) POST /api/v1/auth/logout — existing (keep blocklist) GET /api/v1/auth/oauth/google — NEW: initiate Google OAuth GET /api/v1/auth/oauth/google/cb — NEW: Google callback GET /api/v1/auth/oauth/microsoft — NEW: Microsoft OIDC GET /api/v1/auth/oauth/microsoft/cb POST /api/v1/auth/mfa/setup — NEW: TOTP setup (QR code) POST /api/v1/auth/mfa/verify — NEW: verify TOTP code POST /api/v1/auth/password/forgot — NEW: send reset email POST /api/v1/auth/password/reset — NEW: reset with token POST /api/v1/auth/email/verify — NEW: verify email token POST /api/v1/auth/invite/accept — NEW: accept team invite 3.3 New Database Models -- Extend existing User model ALTER TABLE users ADD COLUMN email VARCHAR(255) UNIQUE NOT NULL; ALTER TABLE users ADD COLUMN email_verified BOOLEAN DEFAULT FALSE; ALTER TABLE users ADD COLUMN avatar_url VARCHAR(500); ALTER TABLE users ADD COLUMN mfa_secret VARCHAR(64);
ALTER TABLE users ADD COLUMN mfa_enabled BOOLEAN DEFAULT FALSE; ALTER TABLE users ADD COLUMN auth_provider VARCHAR(20) DEFAULT 'local'; -- 'local', 'google', 'microsoft' ALTER TABLE users ADD COLUMN provider_id VARCHAR(255); ALTER TABLE users ADD COLUMN last_login_at TIMESTAMP; ALTER TABLE users ADD COLUMN password_changed_at TIMESTAMP; -- API Keys (for programmatic access) CREATE TABLE api_keys ( id UUID PRIMARY KEY, user_id UUID REFERENCES users(id) ON DELETE CASCADE, tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE, name VARCHAR(100) NOT NULL, key_hash VARCHAR(255) NOT NULL, -- bcrypt hash of key key_prefix VARCHAR(8) NOT NULL, -- first 8 chars for identification scopes JSONB DEFAULT '[]', -- ['projects:read', 'export:write'] last_used_at TIMESTAMP, expires_at TIMESTAMP, created_at TIMESTAMP DEFAULT NOW() ); -- Sessions (replace in-memory blocklist) CREATE TABLE sessions ( id UUID PRIMARY KEY, user_id UUID REFERENCES users(id) ON DELETE CASCADE, refresh_hash VARCHAR(255) NOT NULL, user_agent VARCHAR(500), ip_address INET, expires_at TIMESTAMP NOT NULL, revoked_at TIMESTAMP, created_at TIMESTAMP DEFAULT NOW() );
None -- Invitations CREATE TABLE invitations ( id UUID PRIMARY KEY, tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE, email VARCHAR(255) NOT NULL, role VARCHAR(20) DEFAULT 'user', invited_by UUID REFERENCES users(id), token_hash VARCHAR(255) NOT NULL, accepted_at TIMESTAMP, expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); 3.4 Token Strategy (Upgrade from Current) CURRENT: TARGET: ───────── ─────── access_token in localStorage → access_token in memory (JS variable) no refresh cookie → refresh_token in httpOnly/Secure/SameSite cookie HS256 signing → RS256 signing (asymmetric, enables key rotation) in-memory blocklist → Redis blocklist + sessions table 8-hour access tokens → 15-minute access + 7-day refresh Why RS256: Allows key rotation without invalidating all tokens. Public key can be shared with microservices for local verification without calling auth service. 3.5 Role-Based Access Control (RBAC) PERMISSION HIERARCHY:
Python None super_admin (your team) └── Can: manage all tenants, impersonate users, view analytics tenant_admin (customer org admin) └── Can: manage team, billing, all projects in org editor (paid team member) └── Can: create/edit/export projects, use AI features viewer (free or limited) └── Can: view projects, limited exports api_consumer (programmatic access) └── Can: scoped by API key permissions Extend existing TenantUser model: class TenantUser(Base): __tablename__ = "tenant_users" id = Column(UUID, primary_key=True) tenant_id = Column(UUID, ForeignKey("tenants.id")) user_id = Column(UUID, ForeignKey("users.id")) role = Column(Enum("super_admin", "tenant_admin", "editor", "viewer")) permissions = Column(JSONB, default=[]) # override-level granular permissions invited_at = Column(DateTime) joined_at = Column(DateTime) 3.6 Middleware Chain Request Flow:
Request │ ▼ ┌──────────────────┐ │ Rate Limiter │ ← Redis sliding window (by tier) │ (per IP + user) │ └────────┬─────────┘ ▼ ┌──────────────────┐ │ Auth Middleware │ ← Validates JWT or API key │ (extract user) │ └────────┬─────────┘ ▼ ┌──────────────────┐ │ Tenant Resolver │ ← Sets tenant context from user └────────┬─────────┘ ▼ ┌──────────────────┐ │ Subscription │ ← Checks plan limits, feature flags │ Gate │ └────────┬─────────┘ ▼ ┌──────────────────┐ │ RBAC Check │ ← Verifies role has permission └────────┬─────────┘ ▼ Route Handler 4. Subscription & Billing (Stripe) 4.1 Tier Design ┌──────────────────────────────────────────────────────────── ──────────┐
│ PRICING TIERS │ ├───────────────┬──────────────┬──────────────┬────────────── ──────────┤ │ │ FREE │ PRO │ ENTERPRISE │ │ │ $0/mo │ $29/mo │ Custom │ ├───────────────┼──────────────┼──────────────┼────────────── ──────────┤ │ Projects │ 3 active │ Unlimited │ Unlimited │ │ Conversions │ 5/month │ 100/month │ Unlimited │ │ File Size │ 10 MB │ 100 MB │ 500 MB │ │ Pages/PDF │ 50 pages │ 500 pages │ Unlimited │ │ AI Pipeline │ ✗ │ ✓ │ ✓ │ │ Alt Text Gen │ 5/month │ 200/month │ Unlimited │ │ EPUB Export │ Reflowable │ Both layouts │ Both + custom │ │ HTML Export │ ✗ │ ✓ │ ✓ │ │ EPUBCheck │ ✗ │ ✓ │ ✓ │ │ ACE (DAISY) │ ✗ │ ✓ │ ✓ │ │ Team Members │ 1 │ 5 │ Unlimited │ │ API Access │ ✗ │ ✓ (rate ltd) │ ✓ (high rate) │ │ SSO/SAML │ ✗ │ ✗ │ ✓ │ │ Storage │ 500 MB │ 10 GB │ 100 GB │
│ Support │ Community │ Email │ Dedicated + SLA │ │ Retention │ 30 days │ 1 year │ Custom │ └───────────────┴──────────────┴──────────────┴────────────── ──────────┘ 4.2 Stripe Integration Architecture ┌───────────────────────────────────────────────────────────┐ │ BILLING DATA FLOW │ │ │ │ User clicks Stripe Checkout │ │ "Upgrade" ──────────────▶ (hosted page) │ │ │ │ │ │ payment succeeds │ │ ▼ │ │ Stripe Webhook ──────────┐ │ │ POST /webhooks/stripe │ │ │ ▼ │ │ ┌─────────────┐│ │ Mapping: │ Update DB ││ │ Stripe Customer ←→ Tenant │ - plan tier ││ │ Stripe Sub ←→ Subscription │ - limits ││ │ Stripe Product ←→ Plan/Tier │ - status ││ │ Stripe Price ←→ Monthly/Annual │ ││ │ Stripe PayMethod ←→ (managed by Stripe) └─────────────┘│
SQL │ │ └───────────────────────────────────────────────────────────┘ 4.3 Billing Database Models CREATE TABLE plans ( id VARCHAR(50) PRIMARY KEY, -- 'free', 'pro', 'enterprise' name VARCHAR(100) NOT NULL, stripe_product_id VARCHAR(100), limits JSONB NOT NULL, -- Example limits JSONB: -- { -- "max_projects": 3, -- "conversions_per_month": 5, -- "max_file_size_mb": 10, -- "max_pages_per_pdf": 50, -- "ai_pipeline": false, -- "alt_text_per_month": 5, -- "export_formats": ["reflowable"], -- "validation_tools": [], -- "max_team_members": 1, -- "api_access": false, -- "sso": false, -- "storage_mb": 500, -- "retention_days": 30, -- "rate_limit_per_minute": 30 -- } is_active BOOLEAN DEFAULT TRUE, created_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE subscriptions ( id UUID PRIMARY KEY, tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
plan_id VARCHAR(50) REFERENCES plans(id), stripe_customer_id VARCHAR(100) NOT NULL, stripe_sub_id VARCHAR(100) UNIQUE, status VARCHAR(20) NOT NULL, -- 'trialing', 'active', 'past_due', 'canceled', 'unpaid' current_period_start TIMESTAMP, current_period_end TIMESTAMP, cancel_at_period_end BOOLEAN DEFAULT FALSE, trial_end TIMESTAMP, created_at TIMESTAMP DEFAULT NOW(), updated_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE usage_records ( id UUID PRIMARY KEY, tenant_id UUID REFERENCES tenants(id), user_id UUID REFERENCES users(id), metric VARCHAR(50) NOT NULL, -- 'conversion', 'alt_text_generation', 'export', 'api_call', -- 'storage_bytes' quantity INTEGER DEFAULT 1, period_start DATE NOT NULL, -- first of month metadata JSONB, -- { "project_id": "...", "file_type": "pdf" } created_at TIMESTAMP DEFAULT NOW() ); -- Aggregated for fast limit checks CREATE TABLE usage_summaries ( tenant_id UUID REFERENCES tenants(id), metric VARCHAR(50) NOT NULL, period_start DATE NOT NULL, total INTEGER DEFAULT 0, updated_at TIMESTAMP DEFAULT NOW(), PRIMARY KEY (tenant_id, metric, period_start) );
CREATE TABLE invoices ( id UUID PRIMARY KEY, tenant_id UUID REFERENCES tenants(id), stripe_invoice_id VARCHAR(100) UNIQUE, amount_cents INTEGER NOT NULL, currency VARCHAR(3) DEFAULT 'usd', status VARCHAR(20), -- 'draft','open','paid','void','uncollectible' pdf_url VARCHAR(500), period_start TIMESTAMP, period_end TIMESTAMP, created_at TIMESTAMP DEFAULT NOW() ); 4.4 Billing API Endpoints POST /api/v1/billing/checkout — Create Stripe Checkout session POST /api/v1/billing/portal — Create Stripe Customer Portal session GET /api/v1/billing/subscription — Get current subscription state GET /api/v1/billing/usage — Get usage for current period GET /api/v1/billing/invoices — List invoices POST /api/v1/billing/cancel — Cancel at period end POST /webhooks/stripe — Stripe webhook receiver (verify sig) CRITICAL WEBHOOK EVENTS TO HANDLE: checkout.session.completed → activate subscription invoice.paid → renew period, update usage counters invoice.payment_failed → mark past_due, send warning email
Python customer.subscription.updated → plan change (up/downgrade) customer.subscription.deleted → revoke to free tier customer.subscription.trial_will_end → send trial ending email 4.5 Feature Gating Implementation # middleware/subscription_gate.py from functools import wraps # In-memory plan cache (refresh from DB every 5 min via Redis) _plan_cache: dict[str, dict] = {} class FeatureGate: """Checks tenant subscription against plan limits.""" def __init__(self, redis_client, db_session): self.redis = redis_client self.db = db_session async def check_limit(self, tenant_id: str, metric: str) -> tuple[bool, dict]: """Returns (allowed, details) — details include remaining, limit, etc.""" plan = await self._get_plan(tenant_id) limits = plan["limits"] # Boolean features (ai_pipeline, api_access, sso) if metric in limits and isinstance(limits[metric], bool): return limits[metric], {"feature": metric, "plan": plan["id"]} # Counted features (conversions, alt_text, etc.) current = await self._get_usage(tenant_id, metric)
limit = limits.get(f"{metric}_per_month", float("inf")) return current < limit, { "used": current, "limit": limit, "remaining": max(0, limit - current), "resets_at": self._period_end(tenant_id) } async def check_storage(self, tenant_id: str) -> tuple[bool, dict]: """Check aggregate storage usage.""" plan = await self._get_plan(tenant_id) max_bytes = plan["limits"]["storage_mb"] * 1024 * 1024 used = await self._get_storage_usage(tenant_id) return used < max_bytes, {"used": used, "limit": max_bytes} # Decorator for route handlers def require_feature(feature: str): def decorator(func): @wraps(func) async def wrapper(*args, tenant=None, gate=None, **kwargs): allowed, details = await gate.check_limit(tenant.id, feature) if not allowed: raise HTTPException( status_code=403, detail={ "error": "plan_limit_exceeded", "feature": feature, **details, "upgrade_url": "/billing/upgrade" } )
return await func(*args, tenant=tenant, gate=gate, **kwargs) return wrapper return decorator # Usage in routes: @app.post("/api/v1/projects/{id}/export/epub") @require_feature("export") async def export_epub(id: str, tenant=Depends(get_tenant), gate=Depends(get_gate)): ... 5. Data Architecture 5.1 Complete Entity Relationship Diagram ┌──────────────────────────────────────────────────────────── ──────┐ │ COMPLETE DATA MODEL │ │ │ │ ┌─────────┐ 1 * ┌──────────────┐ * 1 ┌─────────┐ │ │ │ TENANT │───────▶│ TENANT_USER │◀───────│ USER │ │ │ │ │ │ (role, perms)│ │ │ │ │ └────┬─────┘ └──────────────┘ └────┬─────┘ │ │ │ │ │ │ │ 1 │ 1 │
│ │ ┌───────────────┐ │ │ │ ├───▶│ SUBSCRIPTION │ ├─── sessions │ │ │ │ (stripe, plan)│ ├─── api_keys │ │ │ └───────────────┘ └─── audit_log │ │ │ │ │ │ 1 * ┌───────────┐ 1 * ┌──────────┐ │ │ ├───────▶│ PROJECT │───────▶│ SECTION │ │ │ │ │ │ │ │ │ │ │ └─────┬──────┘ └────┬─────┘ │ │ │ │ │ │ │ │ │ 1 * │ 1 * │ │ │ ├───────▶ ARTIFACT ├───────▶ IMAGE_ASSET │ │ │ ├───────▶ COVER_IMAGE │ │ │ │ └───────▶ TOC_ENTRY │ │ │ │ │ │ │ 1 * ┌───────────────┐ │ │ ├───────▶│ USAGE_RECORD │ │ │ │ └───────────────┘ │ │ │ 1 * ┌───────────────┐ │
Python │ └───────▶│ USAGE_SUMMARY │ │ │ └───────────────┘ │ │ │ │ ┌──────────┐ ┌──────────────┐ ┌────────────┐ │ │ │ PLAN │◀───│ SUBSCRIPTION │ │ INVITATION │ │ │ │ (limits) │ └──────────────┘ │ (pending) │ │ │ └──────────┘ └────────────┘ │ │ │ │ ┌──────────────┐ ┌──────────────┐ │ │ │ AUDIT_LOG │ │ WEBHOOK_EVENT│ │ │ │ (who,what, │ │ (stripe evt │ │ │ │ when,where) │ │ idempotency)│ │ │ └──────────────┘ └──────────────┘ │ └──────────────────────────────────────────────────────────── ──────┘ 5.2 Multi-Tenancy Enforcement Your current code doesn't enforce tenant isolation on queries. Every DB query touching user data must be scoped: # db.py — add tenant-scoped session class TenantSession:
SQL None """Wraps SQLAlchemy session with automatic tenant filtering.""" def __init__(self, session: Session, tenant_id: str): self.session = session self.tenant_id = tenant_id def query(self, model): q = self.session.query(model) if hasattr(model, 'tenant_id'): q = q.filter(model.tenant_id == self.tenant_id) if hasattr(model, 'owner_id'): # Projects are owned by tenant, not user q = q.join(User).filter(User.tenant_id == self.tenant_id) return q Alternatively, use PostgreSQL Row-Level Security (RLS) for defense-in-depth: -- RLS policies (belt + suspenders with app-level filtering) ALTER TABLE projects ENABLE ROW LEVEL SECURITY; CREATE POLICY tenant_isolation ON projects USING (owner_id IN ( SELECT user_id FROM tenant_users WHERE tenant_id = current_setting('app.current_tenant')::uuid )); 5.3 Caching Strategy CACHE LAYERS: ┌──────────────────────────────────────────────────────┐ │ REDIS CACHE │
│ │ │ Layer 1: Session / Auth (TTL: 15 min) │ │ ├── user:{id}:profile → user + tenant + plan │ │ ├── token:blocklist:{jti} → revoked tokens │ │ └── rate:{key} → sliding window counters │ │ │ │ Layer 2: Plan / Limits (TTL: 5 min) │ │ ├── plan:{plan_id} → plan limits JSON │ │ ├── tenant:{id}:plan → current subscription │ │ └── tenant:{id}:usage:{m} → usage counters │ │ │ │ Layer 3: Hot Data (TTL: 60 sec) │ │ ├── project:{id}:sections → section list │ │ └── project:{id}:metadata → project metadata │ │ │ │ Layer 4: Job Queue │ │ └── (Celery/ARQ broker) │ └──────────────────────────────────────────────────────┘ INVALIDATION: - Auth: invalidate on login/logout/role change - Plans: invalidate on webhook (subscription changed) - Usage: increment atomically (INCRBY), flush to DB every 5 min - Projects: invalidate on write operations 6. Background Job Processing 6.1 Migration from In-Process Threads Current: _run_conversion_background() runs in a threading.Event — dies if the API process restarts, can't distribute across workers. Target: Celery (or ARQ for async-native) with Redis broker.
┌──────────────────────────────────────────────────────────── ┐ │ JOB ARCHITECTURE │ │ │ │ API Server Worker Pool │ │ ┌──────────┐ ┌───────┐ ┌──────────────────────────┐ │ │ │ POST │───▶│ Redis │───▶│ conversion_worker │ │ │ │ /projects │ │ Queue │ │ ├── pdf_ai_pipeline │ │ │ └──────────┘ │ │ │ ├── pdf_legacy_pipeline │ │ │ │ │ │ ├── docx_pipeline │ │ │ ┌──────────┐ │ │ │ └── idml_pipeline │ │ │ │ POST │───▶│ │───▶│ │ │ │ │ /export │ │ │ │ export_worker │ │ │ └──────────┘ │ │ │ ├── epub_generation │ │ │ │ │ │ ├── html_zip │ │ │ │ │ │ └── validation │ │ │ ┌──────────┐ │ │ │ │ │ │ │ POST │───▶│ │───▶│ ai_worker │ │ │ │ /alt/gen │ │ │ │ ├── alt_text_generation │ │ │ └──────────┘ │ │ │ └── ocr_extraction │ │
│ │ │ │ │ │ │ │ │───▶│ email_worker │ │ │ │ │ │ ├── welcome │ │ │ │ │ │ ├── password_reset │ │ │ │ │ │ └── billing_alerts │ │ │ └───────┘ └──────────────────────────┘ │ │ │ │ QUEUE PRIORITIES: │ │ critical (P0): auth emails, billing webhooks │ │ high (P1): conversions (paid users) │ │ default (P2): conversions (free users), exports │ │ low (P3): analytics, cleanup, alt text batch │ │ │ │ CONCURRENCY: │ │ conversion_worker: 4 concurrent (CPU-bound PDF rendering)│ │ ai_worker: 8 concurrent (I/O-bound API calls) │ │ email_worker: 2 concurrent │ │ export_worker: 4 concurrent │ └──────────────────────────────────────────────────────────── ┘
Python None 6.2 Job State Management # Replace threading.Event progress tracking class JobProgress: """Redis-backed progress tracking for background jobs.""" KEY_PREFIX = "job:progress:" def __init__(self, redis, job_id: str): self.redis = redis self.key = f"{self.KEY_PREFIX}{job_id}" async def update(self, pct: int, message: str, **extra): await self.redis.hset(self.key, mapping={ "pct": pct, "message": message, "updated_at": datetime.utcnow().isoformat(), **{k: json.dumps(v) for k, v in extra.items()} }) await self.redis.expire(self.key, 86400) # 24h TTL async def get(self) -> dict: return await self.redis.hgetall(self.key) # Progress polling endpoint stays the same — just reads from Redis now # GET /api/v1/projects/{id}/progress # → reads job:progress:{project_id} from Redis # → returns same schema as today 7. Cloud Storage Migration 7.1 Storage Architecture CURRENT: TARGET: ───────── ───────
Python ./storage/ S3-compatible (AWS S3 / MinIO) ├── {project_id}/ ├── uploads/ │ ├── original.pdf │ └── {tenant}/{project}/original.* │ ├── images/ ├── images/ │ │ └── *.png │ └── {tenant}/{project}/{section}/*.png │ └── artifacts/ ├── artifacts/ │ └── *.epub │ └── {tenant}/{project}/*.epub └── covers/ ├── covers/ └── {project_id}.* │ └── {tenant}/{project}/cover.* └── exports/ (temporary, 24h TTL) └── {tenant}/{project}/*.epub 7.2 Abstraction Layer # storage/base.py from abc import ABC, abstractmethod class StorageBackend(ABC): @abstractmethod async def put(self, key: str, data: bytes | BinaryIO, content_type: str = None) -> str: ... @abstractmethod async def get(self, key: str) -> bytes: ... @abstractmethod async def get_presigned_url(self, key: str, expires: int = 3600) -> str: ...
@abstractmethod async def delete(self, key: str) -> None: ... @abstractmethod async def list_keys(self, prefix: str) -> list[str]: ... class S3Storage(StorageBackend): """Production: AWS S3 or S3-compatible (MinIO, R2, etc.)""" ... class LocalStorage(StorageBackend): """Development: local filesystem (current behavior)""" ... # Factory def get_storage() -> StorageBackend: if settings.STORAGE_BACKEND == "s3": return S3Storage(bucket=settings.S3_BUCKET, ...) return LocalStorage(base_dir=settings.STORAGE_DIR) Key change: File serving endpoints (GET /api/v1/assets/{id}) return presigned URLs (302 redirect) instead of streaming bytes through the API server. This offloads bandwidth to S3/CDN. 8. Email System 8.1 Email Architecture ┌──────────────────────────────────────────────────┐ │ EMAIL SYSTEM │ │ │ │ Templates (MJML → HTML) Delivery │ │ ┌──────────────────────┐ ┌───────────────┐ │ │ │ welcome.mjml │ │ Amazon SES │ │ │ │ email_verification │ │ (or Resend, │ │
SQL │ │ password_reset │────▶│ Postmark) │ │ │ │ trial_ending │ │ │ │ │ │ payment_failed │ │ Throughput: │ │ │ │ subscription_changed │ │ ~50/sec │ │ │ │ export_ready │ └───────────────┘ │ │ │ team_invitation │ │ │ │ weekly_digest │ │ │ └──────────────────────┘ │ │ │ │ Trigger Points: │ │ ├── Auth events → welcome, verify, reset │ │ ├── Stripe webhooks → payment, subscription │ │ ├── Job completion → export_ready │ │ └── Cron (weekly) → usage digest │ └──────────────────────────────────────────────────┘ 8.2 Email Database CREATE TABLE email_log ( id UUID PRIMARY KEY, tenant_id UUID REFERENCES tenants(id), user_id UUID REFERENCES users(id), template VARCHAR(50) NOT NULL, to_email VARCHAR(255) NOT NULL, subject VARCHAR(255), status VARCHAR(20), -- 'queued','sent','delivered','bounced','complained' provider_id VARCHAR(100), -- SES message ID metadata JSONB, sent_at TIMESTAMP, created_at TIMESTAMP DEFAULT NOW() ); 9. API Rate Limiting by Tier 9.1 Rate Limit Design
Python ┌──────────────────────────────────────────────────────────┐ │ RATE LIMITING TIERS │ ├─────────────────┬────────┬──────────┬────────────────────┤ │ Endpoint Group │ FREE │ PRO │ ENTERPRISE │ ├─────────────────┼────────┼──────────┼────────────────────┤ │ General API │ 30/min │ 120/min │ 600/min │ │ Upload │ 2/min │ 10/min │ 30/min │ │ Conversion │ 1/min │ 5/min │ 20/min │ │ AI (alt text) │ 3/min │ 20/min │ 60/min │ │ Export │ 2/min │ 10/min │ 30/min │ │ Auth │ 10/5min│ 10/5min │ 10/5min (same) │ ├─────────────────┴────────┴──────────┴────────────────────┤ │ Algorithm: Redis sliding window (ZRANGEBYSCORE) │ │ Key pattern: rate:{tenant_id}:{endpoint_group} │ │ Headers returned: X-RateLimit-Limit, -Remaining, -Reset │ └──────────────────────────────────────────────────────────┘ 9.2 Implementation # middleware/rate_limit.py import time from fastapi import Request, HTTPException class TieredRateLimiter: """Redis sliding window rate limiter with per-plan limits.""" def __init__(self, redis): self.redis = redis async def check(self, request: Request, tenant_id: str, plan_id: str, endpoint_group: str) -> dict: limits = RATE_LIMITS[plan_id][endpoint_group] key = f"rate:{tenant_id}:{endpoint_group}" now = time.time()
window = limits["window_seconds"] max_requests = limits["max_requests"] pipe = self.redis.pipeline() pipe.zremrangebyscore(key, 0, now - window) # remove expired pipe.zadd(key, {f"{now}:{uuid4()}": now}) # add current pipe.zcard(key) # count pipe.expire(key, window) _, _, count, _ = await pipe.execute() remaining = max(0, max_requests - count) if count > max_requests: raise HTTPException( status_code=429, detail={ "error": "rate_limit_exceeded", "retry_after": window, "limit": max_requests, "window": window, "upgrade_url": "/billing/upgrade" }, headers={ "Retry-After": str(window), "X-RateLimit-Limit": str(max_requests), "X-RateLimit-Remaining": str(remaining), "X-RateLimit-Reset": str(int(now + window)) } ) return { "X-RateLimit-Limit": str(max_requests), "X-RateLimit-Remaining": str(remaining), "X-RateLimit-Reset": str(int(now + window)) }
10. Admin Dashboard 10.1 Admin API Endpoints PREFIX: /api/v1/admin/* (requires super_admin role) TENANTS: GET /tenants — list all tenants (paginated, filterable) GET /tenants/{id} — tenant detail + subscription + usage PATCH /tenants/{id} — update status, plan override POST /tenants/{id}/impersonate — get token as tenant_admin (audit logged) USERS: GET /users — list all users GET /users/{id} — user detail + activity POST /users/{id}/disable — disable account POST /users/{id}/reset-password — force password reset ANALYTICS: GET /analytics/overview — MRR, signups, churn, conversions GET /analytics/usage — aggregate usage metrics GET /analytics/cohorts — retention cohorts GET /analytics/revenue — revenue by plan, MRR trend OPERATIONS: GET /jobs — list background jobs (status, retries) POST /jobs/{id}/retry — retry failed job GET /health/detailed — service health (DB, Redis, S3, Stripe) GET /feature-flags — list flags PATCH /feature-flags/{key} — toggle flag 10.2 Audit Log
SQL None CREATE TABLE audit_log ( id UUID PRIMARY KEY, tenant_id UUID, user_id UUID, action VARCHAR(100) NOT NULL, -- 'user.login', 'project.create', 'export.epub', -- 'billing.upgrade', 'admin.impersonate' resource VARCHAR(50), -- 'project', 'user', 'subscription' resource_id VARCHAR(100), details JSONB, -- action-specific metadata ip_address INET, user_agent VARCHAR(500), created_at TIMESTAMP DEFAULT NOW() ); -- Partitioned by month for query performance CREATE INDEX idx_audit_tenant_time ON audit_log (tenant_id, created_at DESC); CREATE INDEX idx_audit_action ON audit_log (action, created_at DESC); 11. Analytics & Monitoring 11.1 Product Analytics ┌──────────────────────────────────────────────────────┐ │ ANALYTICS STACK │ │ │ │ Client-Side Server-Side │ │ ┌───────────────┐ ┌────────────────────────┐ │ │ │ PostHog / Mix │ │ Custom event emitter: │ │ │ │ panel (free │ │ │ │ │ │ tier okay) │ │ conversion.started │ │ │ │ │ │ conversion.completed │ │
│ │ Tracks: │ │ conversion.failed │ │ │ │ - page views │ │ export.epub │ │ │ │ - feature use │ │ export.html │ │ │ │ - funnel │ │ ai.alt_text_generated │ │ │ │ - retention │ │ billing.upgraded │ │ │ └───────────────┘ │ billing.downgraded │ │ │ │ billing.churned │ │ │ │ user.registered │ │ │ │ user.invited │ │ │ └────────────────────────┘ │ │ │ │ │ ┌──────▼──────┐ │ │ │ Events DB │ │ │ │ (TimescaleDB│ │ │ │ or append │ │ │ │ table) │ │ │ └─────────────┘ │ └──────────────────────────────────────────────────────┘ KEY BUSINESS METRICS (Admin Dashboard): MRR (Monthly Recurring Revenue) Signup → Paid conversion rate Trial → Paid conversion rate Churn rate (monthly) ARPU (Average Revenue Per User) Feature adoption (% using AI pipeline, alt text, etc.) Conversion success rate (by file type) Active users (DAU/WAU/MAU) 11.2 Infrastructure Monitoring ┌───────────────────────────────────────────────────┐ │ MONITORING & ALERTING │ │ │ │ Metrics: Prometheus + Grafana │ │ ├── API latency (p50, p95, p99) │ │ ├── Error rates (5xx, 4xx) │
│ ├── Queue depth + job processing time │ │ ├── Redis memory + hit rate │ │ ├── DB connections + query time │ │ ├── S3 operations + bandwidth │ │ └── Conversion pipeline duration │ │ │ │ Logging: Structured JSON → Loki / CloudWatch │ │ ├── request_id on every log line │ │ ├── tenant_id for filtering │ │ └── correlation across API → worker → storage │ │ │ │ Alerting: PagerDuty / Opsgenie │ │ ├── P0: API down, DB unreachable, Stripe wh fail │ │ ├── P1: Error rate > 5%, queue backlog > 100 │ │ ├── P2: High latency, storage > 80% │ │ └── P3: Usage anomalies, churn spike │ │ │ │ Uptime: External ping (UptimeRobot / Checkly) │ │ └── /health endpoint every 30s │ └───────────────────────────────────────────────────┘ 12. Infrastructure & Deployment 12.1 Production Architecture ┌──────────────────────────────────────────────────────────── ─────┐ │ PRODUCTION DEPLOYMENT │ │ │ │ DNS: CloudFlare │ │ ├── zenpub.com → CDN → Next.js (Vercel) │
│ ├── app.zenpub.com → CDN → React SPA (S3 + CloudFront) │ │ ├── api.zenpub.com → ALB → ECS/Fargate (API) │ │ └── docs.zenpub.com → CDN → Static docs │ │ │ │ ┌──────────────────────────────────────────────────────────── ─┐│ │ │ AWS (or equivalent) ││ │ │ ││ │ │ ┌──────────┐ ┌───────────────────────────────────┐ ││ │ │ │ ALB │ │ ECS Fargate Cluster │ ││ │ │ │ (TLS term)│──│ ┌─────┐ ┌─────┐ ┌─────┐ │ ││ │ │ └──────────┘ │ │ API │ │ API │ │ API │ (2-8) │ ││ │ │ │ │ #1 │ │ #2 │ │ #3 │ │ ││ │ │ │ └─────┘ └─────┘ └─────┘ │ ││ │ │ │ ┌──────┐ ┌──────┐ ┌──────┐ │ ││ │ │ │ │Worker│ │Worker│ │Worker│ (2-6) │ ││ │ │ │ │ #1 │ │ #2 │ │ #3 │ │ ││ │ │ │ └──────┘ └──────┘ └──────┘ │ ││ │ │ └───────────────────────────────────┘ ││ │ │ ││
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ││ │ │ │ RDS Postgres │ │ ElastiCache │ │ S3 │ ││ │ │ │ (primary + │ │ Redis │ │ (files, │ ││ │ │ │ read replica)│ │ (cluster │ │ artifacts, │ ││ │ │ │ │ │ mode) │ │ static) │ ││ │ │ └──────────────┘ └──────────────┘ └──────────────┘ ││ │ │ ││ │ │ ┌──────────────┐ ┌──────────────┐ ││ │ │ │ SES (email) │ │ CloudWatch │ ││ │ │ └──────────────┘ │ (logs/alerts)│ ││ │ │ └──────────────┘ ││ │ └──────────────────────────────────────────────────────────── ─┘│ └──────────────────────────────────────────────────────────── ─────┘ 12.2 Scaling Strategy STAGE 1 (0-500 users): API: 1 instance (2 vCPU, 4 GB) Workers: 1 instance (2 vCPU, 4 GB) DB: RDS db.t3.medium (2 vCPU, 4 GB) Redis: ElastiCache cache.t3.micro S3: Standard tier Cost: ~$150-200/month
STAGE 2 (500-5,000 users): API: 2-4 instances (auto-scaling) Workers: 2-4 instances (queue-depth scaling) DB: RDS db.r6g.large + read replica Redis: ElastiCache cache.r6g.large S3: Standard + CloudFront CDN Cost: ~$500-800/month STAGE 3 (5,000-50,000 users): API: 4-8 instances Workers: 4-8 instances (split by queue type) DB: RDS db.r6g.xlarge + 2 read replicas Redis: Redis cluster (3 nodes) S3: Intelligent-Tiering + lifecycle rules Cost: ~$2,000-5,000/month 12.3 CI/CD Pipeline ┌────────────────────────────────────────────┐ │ CI/CD PIPELINE │ │ │ │ Push to main │ │ │ │ │ ▼ │ │ ┌───────────────────────┐ │ │ │ GitHub Actions │ │ │ │ ├── lint (ruff+eslint)│ │ │ │ ├── type-check (mypy) │ │ │ │ ├── unit tests │ ← parallel │ │ │ ├── integration tests │ │ │ │ └── security scan │ │ │ └──────────┬────────────┘ │ │ │ all pass │ │ ▼ │ │ ┌───────────────────────┐ │ │ │ Build & Push │ │
│ │ ├── Docker build │ │ │ │ ├── Push to ECR │ │ │ │ └── Vite build → S3 │ │ │ └──────────┬────────────┘ │ │ │ │ │ ▼ │ │ ┌───────────────────────┐ │ │ │ Deploy to Staging │ │ │ │ └── smoke tests │ │ │ └──────────┬────────────┘ │ │ │ approved │ │ ▼ │ │ ┌───────────────────────┐ │ │ │ Deploy to Production │ │ │ │ ├── rolling update │ │ │ │ ├── health checks │ │ │ │ └── auto-rollback │ │ │ └───────────────────────┘ │ └────────────────────────────────────────────┘ 13. Security Hardening for Production 13.1 What to Change From Current Current State Production Target JWT_SECRET=dev_secret_cha nge_me AWS Secrets Manager, rotated quarterly HS256 algorithm RS256 with key rotation Real API key in .env Secrets Manager, scoped IAM roles SQLite in dev PostgreSQL with encrypted connections (SSL) localStorage for tokens Memory + httpOnly refresh cookie In-memory token blocklist Redis-backed blocklist No CSP header Strict Content-Security-Policy
No audit logging Full audit trail on sensitive actions CORS: all from env Strict origin allowlist 13.2 Additional Security Measures PRODUCTION SECURITY CHECKLIST: Authentication: ☐ RS256 JWT with key rotation ☐ httpOnly/Secure/SameSite cookies for refresh tokens ☐ MFA (TOTP) support for all paid tiers ☐ Account lockout after 10 failed attempts ☐ Password policy (min 12 chars, breach database check via HaveIBeenPwned API) ☐ Session management (view/revoke active sessions) Data Protection: ☐ Encryption at rest (RDS, S3 SSE-S3) ☐ Encryption in transit (TLS 1.3 everywhere) ☐ PII encryption at application level (email, name) — for GDPR ☐ File scanning (ClamAV) on upload before processing ☐ Tenant data isolation verified by integration tests Infrastructure: ☐ VPC with private subnets for DB/Redis ☐ No public DB access ☐ WAF rules (CloudFlare or AWS WAF) ☐ DDoS protection ☐ Container scanning (Trivy) in CI ☐ Dependency scanning (Snyk/Dependabot) Compliance: ☐ GDPR data export/deletion endpoints ☐ SOC 2 Type II readiness (if enterprise) ☐ Data processing agreement (DPA) template ☐ Privacy policy + Terms of Service ☐ Cookie consent (marketing site)
14. Complete API Versioning & Structure 14.1 Final API Surface /api/v1/ ├── auth/ │ ├── POST register │ ├── POST login │ ├── POST refresh │ ├── POST logout │ ├── GET oauth/{provider} │ ├── GET oauth/{provider}/callback │ ├── POST mfa/setup │ ├── POST mfa/verify │ ├── POST password/forgot │ ├── POST password/reset │ ├── POST email/verify │ └── POST invite/accept │ ├── users/ │ ├── GET me │ ├── PATCH me │ ├── GET me/sessions │ ├── DELETE me/sessions/{id} │ ├── GET me/api-keys │ ├── POST me/api-keys │ └── DELETE me/api-keys/{id} │ ├── teams/ ← NEW (tenant management) │ ├── GET current │ ├── PATCH current │ ├── GET members │ ├── POST members/invite │ ├── PATCH members/{id}/role │ └── DELETE members/{id} │ ├── projects/ ← EXISTING (add tenant scoping) │ ├── POST (upload)
│ ├── GET (list) │ ├── GET {id} │ ├── DELETE {id} │ ├── GET {id}/sections │ ├── GET {id}/toc │ ├── POST {id}/toc/confirm │ ├── GET {id}/metadata │ ├── PATCH {id}/metadata │ ├── POST {id}/cover │ ├── GET {id}/cover │ ├── POST {id}/export/epub ← gated by plan │ ├── POST {id}/export/html ← gated by plan │ ├── POST {id}/accessibility ← gated by plan │ └── GET {id}/progress │ ├── sections/ ← EXISTING │ ├── GET {id} │ ├── PATCH {id} │ └── GET {id}/images │ ├── billing/ ← NEW │ ├── POST checkout │ ├── POST portal │ ├── GET subscription │ ├── GET usage │ ├── GET invoices │ └── POST cancel │ ├── validate/ ← EXISTING (gated) │ ├── POST epub │ └── POST ace │ ├── admin/ ← NEW (super_admin only) │ ├── GET tenants │ ├── GET tenants/{id} │ ├── GET users │ ├── GET analytics/overview │ ├── GET jobs │ └── PATCH feature-flags/{key}
│ └── webhooks/ ← NEW (no auth, signature verified) └── POST stripe 15. Trade-off Analysis Decision Choice Alternative Why Auth tokens RS256 JWT + httpOnly cookie Session-based auth JWTs scale horizontally without shared session store; RS256 allows key rotation Background jobs Celery + Redis ARQ (async-native) Celery is battle-tested, richer ecosystem; ARQ is simpler but fewer monitoring tools Object storage S3 with presigned URLs Serve through API Offloads bandwidth; CDN-cacheable; scales independently Billing Stripe Checkout + Customer Portal Custom payment forms 80% less PCI compliance burden; Stripe handles all payment UI Rate limiting Redis sliding window Fixed window / token bucket Sliding window prevents burst-at-boundary attacks; Redis is already in stack Multi-tenanc y Shared DB with row-level filtering DB-per-tenant Simpler ops at scale; RLS for defense-in-depth; DB-per-tenant only justified at enterprise scale Frontend state Keep local React state (for now) Migrate to Zustand global store Current flat architecture works; migrate only when deep prop drilling becomes painful Email Amazon SES Resend / Postmark Cheapest at scale ($0.10/1000); Resend has better DX but higher cost Monitoring Prometheus + Grafana Datadog Self-hosted is cheaper; Datadog is better but $15/host/month adds up
Hosting AWS ECS Fargate Kubernetes (EKS) Fargate is simpler to operate for small team; K8s is overkill until 10+ services 16. Cost Estimation MONTHLY INFRASTRUCTURE COST (Stage 1: 0-500 users) Compute (Fargate): 2 API tasks × 0.5 vCPU × 1 GB ~$30 2 Worker tasks × 1 vCPU × 2 GB ~$60 Database (RDS PostgreSQL): db.t3.medium (2 vCPU, 4 GB) ~$50 Cache (ElastiCache Redis): cache.t3.micro ~$15 Storage (S3): 100 GB stored + 50 GB transfer ~$5 CDN (CloudFront): 50 GB transfer ~$5 Email (SES): 10,000 emails/month ~$1 Secrets Manager: 5 secrets ~$3 Logging (CloudWatch): 10 GB ingested ~$5 Domain + SSL: Route53 + ACM ~$1 ────── TOTAL: ~$175/month
External services: Stripe: 2.9% + $0.30 per transaction Anthropic API: usage-based (passed through to user's tier) PostHog (analytics): free tier up to 1M events BREAK-EVEN: At $29/mo PRO plan → need ~7 paying customers to cover infra At 5% free→paid conversion → need ~140 signups 17. Implementation Priority — What to Build First WEEK 1-2: Foundation ├── Add Redis to docker-compose.yml ├── Migrate token blocklist from in-memory → Redis ├── Move refresh token to httpOnly cookie ├── Add plans table + seed free/pro/enterprise ├── Add subscriptions table └── Add usage_records + usage_summaries tables WEEK 3-4: Billing Core ├── Stripe integration (checkout, portal, webhooks) ├── Feature gate middleware ├── Usage tracking on conversion/export/alt-text endpoints └── Upgrade prompts in frontend (403 → "upgrade" modal) WEEK 5-6: Auth Upgrade ├── Google OAuth2 flow ├── Email verification ├── Password reset flow ├── Team invitations └── API key management WEEK 7-8: Infrastructure ├── S3 storage backend + migration script ├── Celery workers (extract conversion from main.py)
├── Email service (SES + templates) └── Structured logging WEEK 9-10: Admin + Analytics ├── Admin dashboard API ├── Admin frontend (separate route or React admin) ├── PostHog/Mixpanel integration ├── Audit logging └── Usage dashboard for tenants WEEK 11-12: Production Readiness ├── CI/CD pipeline (GitHub Actions → ECS) ├── Terraform/Pulumi for infrastructure ├── Security audit (headers, CSP, scanning) ├── Load testing └── Monitoring + alerting setup WEEK 13+: Scale & Iterate ├── CDN for static assets ├── Read replicas ├── MFA (TOTP) ├── Microsoft SSO ├── GDPR data export/deletion └── Public API documentation What to Revisit as You Grow 1. At 1,000+ concurrent conversions: Split conversion workers into dedicated services by file type (PDF worker, DOCX worker) with separate scaling policies. 2. At 10,000+ tenants: Consider read replicas for analytics queries, separate analytics DB (TimescaleDB), and caching project listings aggressively. 3. At enterprise deals: DB-per-tenant for largest customers (data isolation compliance), dedicated worker pools, custom SLAs. 4. At international expansion: Multi-region deployment, data residency (EU storage for EU customers), latency-based routing.
5. At public API adoption: API gateway (Kong), OpenAPI spec, SDK generation, webhook system for async notifications. This design transforms your current monolith into a production SaaS incrementally — each phase delivers value independently, and you never need to "stop and rewrite." The existing domain logic (conversion pipeline, EPUB generation, accessibility checks) remains untouched; you're wrapping it with the billing, auth, and infrastructure layers that every SaaS product needs.