Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Enterprise Monorepo Builder Prompt
- > **Use this prompt with an AI assistant to scaffold a production-ready, enterprise-grade TypeScript monorepo from scratch.** It is technology-specific, opinionated, and designed to handle millions of concurrent users.
- ---
- ## Prompt
- You are an expert TypeScript architect. Build me a **production-ready enterprise monorepo** with the following stack and architecture. Every file you create must be real, working code — no placeholders, no TODOs.
- ---
- ## 1. Technology Stack
- | Layer | Technology | Purpose |
- |-------|-----------|---------|
- | **Monorepo** | Turborepo + pnpm workspaces | Build orchestration, dependency management |
- | **Frontend** | SvelteKit 2 + Svelte 5 + Tailwind CSS 4 | SSR/SSG web apps with `adapter-node` |
- | **Server** | uWebSockets.js | Ultra-fast HTTP + WebSocket server (~10x faster than Express) |
- | **RPC** | Custom Zod-validated procedures | Type-safe client↔server communication |
- | **WebSocket** | Binary protocol (MessagePack) | Real-time pub/sub, RPC over WS, presence |
- | **Database** | PostgreSQL 16 + Drizzle ORM | Primary data store with type-safe queries |
- | **Cache/State** | Redis 7 | Sessions, rate limiting, presence, pub/sub |
- | **Messaging** | NATS 2 (optional, with JetStream) | Cross-server fanout, job queues, event streaming |
- | **Analytics DB** | ClickHouse (optional) | High-volume analytics/OLAP |
- | **Observability** | OpenTelemetry + Prometheus + Grafana + Tempo | Metrics, tracing, dashboards |
- | **Reverse Proxy** | Caddy | Auto-TLS, HTTP/3, load balancing |
- | **Containerization** | Docker Compose | Local dev + production deployment |
- | **Language** | TypeScript 5.x (strict mode) | End-to-end type safety |
- | **Package Manager** | pnpm 10+ | Fast, disk-efficient |
- | **Runtime** | Node.js 18+ | Server runtime |
- ---
- ## 2. File & Folder Structure
- ```
- enterprise-monorepo/
- ├── apps/
- │ └── myapp/ # Each product is a folder here
- │ ├── web/ # SvelteKit frontend
- │ │ ├── src/
- │ │ │ ├── routes/ # SvelteKit file-based routing
- │ │ │ ├── lib/ # Shared frontend utilities
- │ │ │ ├── layout/ # Layout components (header, sidebar, mobile)
- │ │ │ ├── modules/ # Feature modules (auth, settings, admin)
- │ │ │ ├── hooks.server.ts # SSR auth, session validation
- │ │ │ ├── hooks.client.ts # Client-side error handling
- │ │ │ └── app.html # HTML shell
- │ │ ├── server/ # Server-only SvelteKit code
- │ │ ├── static/ # Static assets
- │ │ ├── svelte.config.js
- │ │ ├── vite.config.ts
- │ │ ├── tailwind.config.ts
- │ │ └── package.json
- │ ├── server/ # uWebSockets.js backend
- │ │ ├── src/
- │ │ │ ├── server.ts # Entry point
- │ │ │ ├── app/
- │ │ │ │ ├── composition/ # Server wiring (definition.ts)
- │ │ │ │ ├── config.ts # Env config resolution
- │ │ │ │ ├── policies/ # Security & runtime policies
- │ │ │ │ └── modules.ts # Procedure registration
- │ │ │ ├── db/
- │ │ │ │ ├── index.ts # Drizzle client
- │ │ │ │ ├── schema.ts # Drizzle schema
- │ │ │ │ └── migrations/ # Generated migrations
- │ │ │ ├── modules/ # Feature modules (auth, users, etc.)
- │ │ │ └── platform/ # Infrastructure connectors
- │ │ │ ├── redis/ # Redis client registry + services
- │ │ │ ├── nats/ # NATS connection + streams
- │ │ │ └── auth/ # Session service, token validation
- │ │ ├── drizzle.config.ts
- │ │ └── package.json
- │ └── workers/ # Background workers (optional)
- │ └── my-worker/
- │ ├── src/
- │ └── package.json
- │
- ├── packages/
- │ ├── shared/ # Isomorphic (browser + Node.js safe)
- │ │ ├── contracts/ # Zod schemas shared between client & server
- │ │ │ ├── auth/ # Auth schemas (session, bootstrap)
- │ │ │ ├── admin/ # Admin contract schemas
- │ │ │ └── settings/ # Settings schemas
- │ │ ├── protocols/ # Wire protocols
- │ │ │ ├── rpc/ # RPC procedure types + callProcedure()
- │ │ │ └── ws/ # Binary WS protocol (encode/decode)
- │ │ ├── codec/ # MessagePack encode/decode wrapper
- │ │ └── utils/ # Isomorphic utilities (NO Node.js builtins)
- │ │
- │ ├── server/ # Server-only packages
- │ │ ├── framework/
- │ │ │ ├── core/ # uWS server factory, HTTP+WS handlers
- │ │ │ └── security/ # Rate limiting, connection limiting
- │ │ ├── bootstrap/ # startServer() entry, AppServerDefinition
- │ │ ├── runtime/
- │ │ │ ├── config/ # Environment resolution helpers
- │ │ │ ├── logger/ # Structured logger
- │ │ │ ├── crypto/ # Hashing, token generation
- │ │ │ └── sessions/ # Session management
- │ │ ├── integrations/
- │ │ │ ├── nats/ # NATS pub/sub + JetStream service
- │ │ │ └── redis/ # Redis integration helpers
- │ │ └── modules/
- │ │ └── admin/ # Reusable server admin module
- │ │
- │ ├── client/ # Frontend-only packages
- │ │ ├── core/ # Auth store, theme, navigation
- │ │ ├── utils/ # RPC client, fetch wrappers
- │ │ └── modules/ # Feature modules (auth, websockets, etc.)
- │ │ ├── auth/
- │ │ ├── websockets/
- │ │ ├── admin/
- │ │ └── settings/
- │ │
- │ ├── ui/ # UI component packages
- │ │ ├── kit/ # Design system components
- │ │ ├── admin/ # Admin panel components
- │ │ ├── headless/ # Headless services (audio, haptics)
- │ │ └── seo/ # SEO meta components
- │ │
- │ ├── config/ # Shared configuration
- │ │ ├── schema/ # Zod env schemas (NO side effects)
- │ │ ├── typescript/ # Shared tsconfig.base.json
- │ │ └── eslint/ # Shared ESLint config
- │ │
- │ └── db/ # Database packages
- │ └── clickhouse/ # ClickHouse client (optional)
- │
- ├── infra/ # Infrastructure
- │ ├── compose.yml # Docker Compose (dev)
- │ ├── compose.vps.yml # Docker Compose (production)
- │ ├── docker/ # Dockerfiles
- │ ├── caddy/ # Caddyfile config
- │ ├── nats/ # NATS config
- │ ├── postgres/ # Init scripts
- │ ├── prometheus/ # Prometheus config + alert rules
- │ ├── grafana/ # Dashboards + provisioning
- │ ├── otel-collector/ # OpenTelemetry config
- │ ├── scripts/ # Deploy scripts
- │ │ ├── 1-first-time-vps.sh # Server hardening
- │ │ ├── 2-build-and-push.sh # Docker image build + push
- │ │ └── 3-vps-ops.sh # Deploy, rollback, managed ops
- │ └── verification/ # Architecture quality checks
- │ └── quality/ # Dependency boundary checks
- │
- ├── turbo.json # Turborepo pipeline config
- ├── pnpm-workspace.yaml # Workspace definitions
- ├── package.json # Root scripts
- ├── tsconfig.base.json # Base TypeScript config
- └── .prettierrc # Formatting
- ```
- ---
- ## 3. Root Configuration Files
- ### [pnpm-workspace.yaml](file:///Users/boss/Web/byte/pnpm-workspace.yaml)
- ```yaml
- packages:
- # Apps: apps/<project>/<role> (web, server, workers/*)
- - "apps/*/*"
- - "apps/*/*/*"
- # Packages: nested kind-first taxonomy
- - "packages/**"
- ```
- ### [turbo.json](file:///Users/boss/Web/byte/turbo.json)
- ```json
- {
- "$schema": "https://turborepo.com/schema.json",
- "ui": "tui",
- "globalEnv": ["NODE_ENV"],
- "tasks": {
- "build": {
- "dependsOn": ["^build"],
- "inputs": ["$TURBO_DEFAULT$", ".env*"],
- "outputs": [".svelte-kit/**", "dist/**", "build/**"],
- "env": ["NODE_ENV"]
- },
- "dev": {
- "cache": false,
- "persistent": true
- },
- "lint": {
- "dependsOn": ["^lint"],
- "outputs": []
- },
- "check-types": {
- "dependsOn": ["^check-types"],
- "outputs": []
- },
- "test": {
- "dependsOn": ["^build"],
- "outputs": ["coverage/**"]
- },
- "clean": { "cache": false },
- "db:generate": { "cache": false, "outputs": ["src/db/migrations/**", "drizzle/**"] },
- "db:migrate": { "cache": false },
- "db:push": { "cache": false }
- }
- }
- ```
- ### Root [package.json](file:///Users/boss/Web/byte/package.json) (key scripts)
- ```json
- {
- "name": "@myorg/monorepo",
- "private": true,
- "scripts": {
- "dev": "turbo run dev --parallel",
- "build": "turbo run build",
- "lint": "turbo run lint",
- "check-types": "turbo run check-types",
- "test": "turbo run test",
- "myapp:web": "turbo run dev --filter=@myorg/myapp-web --ui=stream",
- "myapp:server": "turbo run dev --filter=@myorg/myapp-server... --ui=stream --concurrency=30",
- "myapp:server:build": "turbo run build --filter=@myorg/myapp-server...",
- "infra:up": "docker compose -f infra/compose.yml up -d",
- "infra:down": "docker compose -f infra/compose.yml down",
- "infra:logs": "docker compose -f infra/compose.yml logs -f",
- "clean": "turbo run clean && rm -rf node_modules .turbo",
- "format": "prettier --write \"**/*.{ts,tsx,js,jsx,json,md,svelte}\"",
- "check:architecture": "node infra/verification/quality/check-dependency-boundaries.mjs"
- },
- "packageManager": "[email protected]",
- "engines": { "node": ">=18", "pnpm": ">=9" },
- "devDependencies": {
- "turbo": "^2.8.0",
- "typescript": "^5.9.0",
- "prettier": "^3.8.0",
- "prettier-plugin-svelte": "^3.5.0",
- "vitest": "^1.6.0"
- }
- }
- ```
- ### [tsconfig.base.json](file:///Users/boss/Web/byte/tsconfig.base.json)
- ```json
- {
- "compilerOptions": {
- "target": "ES2022",
- "module": "ESNext",
- "moduleResolution": "bundler",
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "forceConsistentCasingInFileNames": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "declaration": true,
- "declarationMap": true,
- "composite": true
- }
- }
- ```
- ---
- ## 4. Infrastructure — Docker Compose
- ### [infra/compose.yml](file:///Users/boss/Web/byte/infra/compose.yml)
- ```yaml
- services:
- postgres:
- image: postgres:16-alpine
- container_name: app-postgres
- environment:
- POSTGRES_PASSWORD: postgres
- POSTGRES_USER: postgres
- ports:
- - '5432:5432'
- volumes:
- - ./postgres/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
- redis:
- image: redis:7-alpine
- container_name: app-redis
- ports:
- - '6379:6379'
- nats:
- image: nats:2-alpine
- container_name: app-nats
- ports:
- - '4222:4222'
- - '8222:8222' # monitoring
- command: ['-js', '-m', '8222'] # Enable JetStream + monitoring
- # Optional: ClickHouse for analytics
- clickhouse:
- image: clickhouse/clickhouse-server:latest
- container_name: app-clickhouse
- environment:
- CLICKHOUSE_DB: analytics
- CLICKHOUSE_USER: app
- CLICKHOUSE_PASSWORD: app
- ports:
- - '8123:8123'
- - '9000:9000'
- # Observability
- otel-collector:
- image: otel/opentelemetry-collector-contrib:0.111.0
- container_name: app-otel
- command: ['--config=/etc/otelcol-contrib/config.yaml']
- ports:
- - '4317:4317' # OTLP gRPC
- - '4318:4318' # OTLP HTTP
- volumes:
- - ./otel-collector/config.yaml:/etc/otelcol-contrib/config.yaml:ro
- depends_on: [tempo]
- tempo:
- image: grafana/tempo:2.6.1
- container_name: app-tempo
- command: ['-config.file=/etc/tempo/tempo.yaml']
- ports: ['3200:3200']
- volumes:
- - ./tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
- prometheus:
- image: prom/prometheus:v2.55.1
- container_name: app-prometheus
- ports: ['9090:9090']
- volumes:
- - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- depends_on: [nats, otel-collector]
- grafana:
- image: grafana/grafana:11.3.1
- container_name: app-grafana
- ports: ['3000:3000']
- environment:
- GF_SECURITY_ADMIN_USER: admin
- GF_SECURITY_ADMIN_PASSWORD: admin
- depends_on: [prometheus, tempo]
- ```
- ---
- ## 5. Shared Packages — The Foundation
- ### 5a. Config Schema (`packages/config/schema`)
- **Rule**: This package exports Zod schemas ONLY. No side effects, no `process.env` reads. Isomorphic-safe.
- ```typescript
- // packages/config/schema/src/index.ts
- import { z } from "zod";
- export const ServerRuntimeEnvSchema = z.object({
- NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
- PORT: z.coerce.number().default(3001),
- SERVER_ID: z.string().default("srv-local"),
- WEB_APP_URL: z.string().url().default("http://localhost:8080"),
- DATABASE_URL: z.string().default("postgres://postgres:postgres@localhost:5432/app_db"),
- REDIS_URL: z.string().default("redis://localhost:6379"),
- NATS_URL: z.string().default("nats://localhost:4222"),
- CORS_ALLOWED_ORIGINS: z.string().default("http://localhost:8080")
- .transform(v => v.split(",").map(s => s.trim()).filter(Boolean)),
- METRICS_BEARER_TOKEN: z.string().default(""),
- });
- export type ServerRuntimeEnv = z.infer<typeof ServerRuntimeEnvSchema>;
- // Web SSR uses this to safely parse private env vars
- export const WebSsrEnvSchema = z.object({
- BACKEND_URL: z.string().url().default("http://localhost:3001"),
- SESSION_SECRET: z.string().min(32),
- });
- ```
- **Server-side usage** (app entry point, parsed exactly once):
- ```typescript
- // apps/myapp/server/src/app/config.ts
- import { ServerRuntimeEnvSchema } from "@myorg/config-schema";
- export const SERVER_CONFIG = ServerRuntimeEnvSchema.parse(process.env);
- ```
- **SvelteKit SSR usage**:
- ```typescript
- // apps/myapp/web/server/config.ts
- import { env as privateEnv } from '$env/dynamic/private';
- import { WebSsrEnvSchema } from '@myorg/config-schema';
- export const SSR_CONFIG = WebSsrEnvSchema.parse(privateEnv);
- ```
- ### 5b. RPC Protocol (`packages/shared/protocols/rpc`)
- ```typescript
- // packages/shared/protocols/rpc/src/index.ts
- import { z } from "zod";
- export type ProcedureAccess = "public" | "user" | "admin";
- export interface ProcedureMeta {
- access: ProcedureAccess;
- }
- export class RpcError extends Error {
- constructor(
- public code: string,
- message: string,
- public details?: any
- ) {
- super(message);
- this.name = "RpcError";
- }
- toJSON() {
- return {
- error: {
- code: this.code,
- message: this.message,
- details: process.env.NODE_ENV !== "production" ? this.details : undefined,
- },
- };
- }
- }
- /** Request context passed to every procedure */
- export interface Ctx {
- sessionId?: string;
- userId?: number;
- roles?: string[];
- isGuest?: boolean;
- ip?: string;
- userAgent?: string;
- [key: string]: any;
- }
- /** Procedure definition with Zod validation */
- export interface Procedure<Input = any, Output = any> {
- meta?: ProcedureMeta;
- input: z.ZodType<Input>;
- output: z.ZodType<Output>;
- handler: (input: Input, ctx: Ctx) => Promise<Output>;
- }
- export type ProcedureMap = Record<string, Procedure>;
- /** Call a procedure with full validation and access control */
- export async function callProcedure<T = any>(
- procedures: ProcedureMap,
- name: string,
- input: unknown,
- ctx: Ctx = {}
- ): Promise<T> {
- const procedure = procedures[name];
- if (!procedure) throw new RpcError("PROCEDURE_NOT_FOUND", `Procedure '${name}' not found`);
- // Access control
- const access = procedure.meta?.access ?? "public";
- if (access !== "public" && !ctx.userId) {
- throw new RpcError("UNAUTHORIZED", "Authentication required");
- }
- if (access === "admin" && !ctx.roles?.includes("admin")) {
- throw new RpcError("FORBIDDEN", "Admin role required");
- }
- // Validate input
- const validatedInput = procedure.input.parse(input);
- // Execute
- const result = await procedure.handler(validatedInput, ctx);
- // Validate output (catches server bugs)
- return procedure.output.parse(result);
- }
- /** Helper for type inference */
- export function defineProcedure<I, O>(p: Procedure<I, O>): Procedure<I, O> { return p; }
- ```
- ### 5c. WebSocket Binary Protocol (`packages/shared/protocols/ws`)
- ```typescript
- // packages/shared/protocols/ws/src/index.ts
- import { encode, decode } from "@msgpack/msgpack";
- /** Client → Server opcodes */
- export const C2S = {
- INIT: 0, AUTH: 1, SUBSCRIBE: 2, UNSUBSCRIBE: 3,
- PUBLISH: 4, TRACK: 5, HEARTBEAT: 6, BATCH: 7, RPC: 8,
- } as const;
- /** Server → Client opcodes */
- export const S2C = {
- READY: 0, OK: 1, ERROR: 2, PUSH: 3,
- PONG: 4, RPC_RESULT: 5, RPC_ERROR: 6,
- } as const;
- /**
- * Binary Wire Format: [type: 1 byte] [seq: 4 bytes LE] [payload: MessagePack]
- */
- export function encodeMessage<T>(type: number, data?: T, seq?: number): Uint8Array {
- const seqId = seq ?? ++globalSeq;
- const payload = data !== undefined ? encode(data) : new Uint8Array(0);
- const header = new Uint8Array(5);
- header[0] = type;
- new DataView(header.buffer).setUint32(1, seqId, true);
- const result = new Uint8Array(5 + payload.length);
- result.set(header);
- result.set(payload, 5);
- return result;
- }
- export function decodeMessage<T = unknown>(buffer: Uint8Array | ArrayBuffer) {
- const buf = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer;
- if (buf.length < 5) throw new Error(`Message too short: ${buf.length}`);
- const type = buf[0]!;
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
- const seq = view.getUint32(1, true);
- const data = buf.length > 5 ? (decode(buf.subarray(5)) as T) : (null as T);
- return { type, seq, data };
- }
- let globalSeq = 0;
- // Server-side response helpers
- export const Response = {
- ready: (seq: number, data: any) => encodeMessage(S2C.READY, data, seq),
- ok: (seq: number, data?: any) => encodeMessage(S2C.OK, data, seq),
- error: (seq: number, code: string, message: string) =>
- encodeMessage(S2C.ERROR, { code, message }, seq),
- push: (topic: string, data: unknown) =>
- encodeMessage(S2C.PUSH, { topic, data, timestamp: Date.now() }, 0),
- rpcResult: (seq: number, result: unknown, id?: string | number) =>
- encodeMessage(S2C.RPC_RESULT, { result, id }, seq),
- rpcError: (seq: number, code: string, message: string, id?: string | number) =>
- encodeMessage(S2C.RPC_ERROR, { code, message, id }, seq),
- };
- // Client-side request helpers
- export const Request = {
- init: (data: any) => encodeMessage(C2S.INIT, data),
- auth: (token: string) => encodeMessage(C2S.AUTH, { token }),
- subscribe: (topic: string) => encodeMessage(C2S.SUBSCRIBE, { topic }),
- unsubscribe: (topic: string) => encodeMessage(C2S.UNSUBSCRIBE, { topic }),
- heartbeat: () => encodeMessage(C2S.HEARTBEAT, { timestamp: Date.now() }),
- rpc: (procedure: string, input?: unknown, id?: string | number) =>
- encodeMessage(C2S.RPC, { procedure, input, id }),
- };
- /** Pending request tracker for req/res matching */
- export function createPendingTracker<T = unknown>(defaultTimeout = 10000) {
- const pending = new Map<number, { resolve: Function; reject: Function; timeout: any }>();
- return {
- add(seq: number, timeoutMs = defaultTimeout): Promise<T> {
- return new Promise((resolve, reject) => {
- const timeout = setTimeout(() => {
- pending.delete(seq);
- reject(new Error(`Request timeout (seq: ${seq})`));
- }, timeoutMs);
- pending.set(seq, { resolve, reject, timeout });
- });
- },
- resolve(seq: number, value: T): boolean {
- const req = pending.get(seq);
- if (!req) return false;
- clearTimeout(req.timeout);
- pending.delete(seq);
- req.resolve(value);
- return true;
- },
- reject(seq: number, error: Error): boolean {
- const req = pending.get(seq);
- if (!req) return false;
- clearTimeout(req.timeout);
- pending.delete(seq);
- req.reject(error);
- return true;
- },
- clear(error?: Error): void {
- for (const [, req] of pending) {
- clearTimeout(req.timeout);
- req.reject(error ?? new Error("Connection closed"));
- }
- pending.clear();
- },
- get size() { return pending.size; },
- };
- }
- ```
- ### 5d. Shared Contracts (`packages/shared/contracts/auth`)
- ```typescript
- // packages/shared/contracts/auth/src/auth-session.schema.ts
- import { z } from "zod";
- export const AuthSessionSchema = z.object({
- userId: z.number(),
- roles: z.array(z.string()),
- accessToken: z.string(),
- refreshToken: z.string(),
- expiresAt: z.number(),
- });
- export type AuthSession = z.infer<typeof AuthSessionSchema>;
- export const AuthBootstrapResponseSchema = z.object({
- user: z.object({
- id: z.number(),
- email: z.string().nullable(),
- displayName: z.string().nullable(),
- roles: z.array(z.string()),
- }).nullable(),
- session: AuthSessionSchema.nullable(),
- });
- export type AuthBootstrapResponse = z.infer<typeof AuthBootstrapResponseSchema>;
- ```
- ---
- ## 6. Server Framework — uWebSockets.js Core
- ### 6a. Bootstrap (`packages/server/bootstrap`)
- ```typescript
- // packages/server/bootstrap/src/types.ts
- import type { ServerConfig, ServerInstance } from "@myorg/server-framework-core";
- export interface AppServerDefinition<TEnv = any, TContext = any> {
- name: string;
- resolveEnv?: () => Promise<TEnv> | TEnv;
- createContext?: (input: { env: TEnv }) => Promise<TContext> | TContext;
- beforeStart?: (input: { env: TEnv; context: TContext }) => Promise<void> | void;
- createServerConfig: (input: { env: TEnv; context: TContext }) => Promise<ServerConfig> | ServerConfig;
- onReady?: (input: { env: TEnv; context: TContext; server: ServerInstance }) => Promise<void> | void;
- onShutdown?: Array<(input: { env: TEnv; context: TContext }) => Promise<void> | void>;
- }
- // packages/server/bootstrap/src/start-server.ts
- export async function startServer<TEnv, TContext>(
- definition: AppServerDefinition<TEnv, TContext>
- ) {
- const env = definition.resolveEnv ? await definition.resolveEnv() : ({} as TEnv);
- const context = definition.createContext
- ? await definition.createContext({ env })
- : ({} as TContext);
- if (definition.beforeStart) await definition.beforeStart({ env, context });
- const config = await definition.createServerConfig({ env, context });
- const server = await createServer(config);
- if (definition.onReady) await definition.onReady({ env, context, server });
- // PM2 ready signal
- if (typeof process.send === "function") process.send("ready");
- return { server, env, context };
- }
- ```
- ### 6b. Server Factory (`packages/server/framework/core`)
- This is the heart — creates a production-ready uWebSockets.js server:
- ```typescript
- // packages/server/framework/core/src/create.ts (simplified)
- import uWS from "uWebSockets.js";
- export async function createServer(config: ServerConfig): Promise<ServerInstance> {
- const wsConfig = {
- maxPayloadLength: config.ws?.maxPayloadLength || 16 * 1024,
- idleTimeout: config.ws?.idleTimeout || 120,
- maxBackpressure: config.ws?.maxBackpressure || 1024 * 1024,
- maxConnections: config.ws?.maxConnections ?? 50_000,
- maxConnectionsPerIp: config.ws?.maxConnectionsPerIp ?? 500,
- };
- let app = uWS.App()
- .ws("/ws", {
- compression: uWS.SHARED_COMPRESSOR,
- maxPayloadLength: wsConfig.maxPayloadLength,
- idleTimeout: wsConfig.idleTimeout,
- maxBackpressure: wsConfig.maxBackpressure,
- sendPingsAutomatically: true,
- upgrade: createUpgradeHandler({ config, maxConnections: wsConfig.maxConnections }),
- open: createOpenHandler(),
- message: createMessageHandler(config.procedures),
- close: createCloseHandler(),
- })
- .options("/*", handleOptions) // CORS preflight
- .get("/health", handleHealth) // Health check
- .get("/ready", handleReadiness) // Readiness with dependency checks
- .get("/metrics", handleMetrics) // Prometheus metrics
- .post("/rpc/:procedure", handleRpc) // HTTP RPC endpoint
- .any("/*", handleNotFound); // Catch-all 404
- app.listen(config.port, (socket) => {
- if (!socket) throw new Error(`Failed to listen on port ${config.port}`);
- console.log(`🚀 Server running on port ${config.port}`);
- });
- return { port: config.port, close: () => gracefulShutdown() };
- }
- ```
- **Critical uWebSockets.js Rules:**
- ```typescript
- // ⚠️ RULE 1: Register res.onData() SYNCHRONOUSLY — never await before it
- app.post("/rpc/:procedure", (res, req) => {
- // Read ALL headers/params synchronously FIRST
- const procedure = req.getParameter(0);
- const auth = req.getHeader("authorization");
- const origin = req.getHeader("origin");
- // Register abort handler synchronously
- res.onAborted(() => { (res as any).aborted = true; });
- // Start body reading SYNCHRONOUSLY
- const chunks: Buffer[] = [];
- res.onData((chunk, isLast) => {
- chunks.push(Buffer.from(chunk));
- if (isLast) {
- // NOW you can go async
- handleRpcRequest(res, procedure, auth, Buffer.concat(chunks));
- }
- });
- });
- // ⚠️ RULE 2: req object is INVALID after any await — read everything first
- // ⚠️ RULE 3: Always check res.aborted before writing
- ```
- ### 6c. Rate Limiting with Redis Lua (`packages/server/framework/security`)
- ```typescript
- // Atomic sliding window rate limiter using Redis Lua script
- const SLIDING_WINDOW_SCRIPT = `
- local key = KEYS[1]
- local now = tonumber(ARGV[1])
- local windowMs = tonumber(ARGV[2])
- local maxRequests = tonumber(ARGV[3])
- local member = ARGV[4]
- redis.call("ZREMRANGEBYSCORE", key, 0, now - windowMs)
- local count = redis.call("ZCARD", key)
- if count >= maxRequests then
- redis.call("PEXPIRE", key, windowMs)
- return {0, count, windowMs}
- end
- redis.call("ZADD", key, now, member)
- redis.call("PEXPIRE", key, windowMs)
- return {1, maxRequests - count - 1, windowMs}
- `;
- export class RateLimitService {
- constructor(private redis: Redis) {}
- async isAllowed(identifier: string, config: { windowMs: number; maxRequests: number }) {
- const key = `ratelimit:${identifier}`;
- const raw = await this.redis.eval(
- SLIDING_WINDOW_SCRIPT, 1, key,
- String(Date.now()), String(config.windowMs),
- String(config.maxRequests), `${Date.now()}:${crypto.randomUUID()}`
- ) as [number, number, number];
- return {
- allowed: Number(raw[0]) === 1,
- remaining: Number(raw[1]),
- resetAt: Date.now() + Number(raw[2]),
- };
- }
- }
- ```
- ---
- ## 7. App Server Composition Pattern
- Each app creates a **definition** that wires everything together:
- ```typescript
- // apps/myapp/server/src/server.ts — Entry point
- import { startServer } from "@myorg/server-bootstrap";
- import { createMyAppDefinition } from "./app/composition/definition.js";
- await startServer(createMyAppDefinition());
- // apps/myapp/server/src/app/composition/definition.ts
- export function createMyAppDefinition(): AppServerDefinition<ServerEnv, AppContext> {
- return {
- name: "myapp",
- resolveEnv: () => SERVER_CONFIG,
- createContext: async ({ env }) => {
- // 1. Resolve policies
- const policies = resolveServerPolicies(env);
- // 2. Connect infrastructure
- const redis = new Redis(env.REDIS_URL);
- const nats = await connectNats(env.NATS_URL); // optional
- const presence = createPresenceService(redis);
- const rateLimit = new RateLimitService(redis);
- const authSession = new AuthSessionService(redis);
- // 3. Create procedures
- const procedures = createAppProcedures({ presence, authSession, rateLimit, nats });
- // 4. Health checks
- const healthChecks = {
- redis: async () => { await redis.ping(); return true; },
- nats: async () => nats.isReady(),
- postgres: async () => { await db.query.users.findFirst(); return true; },
- };
- return { policies, procedures, presence, rateLimit, authSession, nats, healthChecks };
- },
- createServerConfig: ({ env, context }) => ({
- port: env.PORT,
- procedures: context.procedures,
- services: {
- presence: context.presence,
- rateLimit: context.rateLimit,
- nats: context.nats,
- },
- healthChecks: context.healthChecks,
- cors: { origin: env.CORS_ALLOWED_ORIGINS, credentials: true },
- gracefulShutdown: { timeout: 30_000, onShutdown: [() => redis.quit()] },
- }),
- onReady: ({ env }) => {
- console.log(`🚀 Server running on port ${env.PORT}`);
- },
- };
- }
- ```
- ---
- ## 8. Database — Drizzle ORM + PostgreSQL
- ```typescript
- // apps/myapp/server/drizzle.config.ts
- import { defineConfig } from "drizzle-kit";
- export default defineConfig({
- dialect: "postgresql",
- schema: "./src/db/schema.ts",
- out: "./src/db/migrations",
- dbCredentials: {
- url: process.env.DATABASE_URL || "postgres://localhost:5432/app_db",
- },
- });
- // apps/myapp/server/src/db/index.ts
- import { drizzle } from "drizzle-orm/node-postgres";
- import pg from "pg";
- import * as schema from "./schema.js";
- const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
- export const db = drizzle(pool, { schema });
- // apps/myapp/server/src/db/schema.ts
- import { pgTable, serial, text, timestamp, integer, boolean, varchar } from "drizzle-orm/pg-core";
- export const users = pgTable("users", {
- id: serial("id").primaryKey(),
- email: varchar("email", { length: 255 }).unique(),
- displayName: varchar("display_name", { length: 100 }),
- passwordHash: text("password_hash"),
- roles: text("roles").array().default([]),
- createdAt: timestamp("created_at").defaultNow().notNull(),
- updatedAt: timestamp("updated_at").defaultNow().notNull(),
- });
- export const sessions = pgTable("sessions", {
- id: serial("id").primaryKey(),
- userId: integer("user_id").references(() => users.id).notNull(),
- accessToken: varchar("access_token", { length: 512 }).unique().notNull(),
- refreshToken: varchar("refresh_token", { length: 512 }).unique().notNull(),
- expiresAt: timestamp("expires_at").notNull(),
- revokedAt: timestamp("revoked_at"),
- ip: varchar("ip", { length: 45 }),
- userAgent: text("user_agent"),
- createdAt: timestamp("created_at").defaultNow().notNull(),
- });
- ```
- ### Example Procedure
- ```typescript
- // apps/myapp/server/src/modules/auth/procedures.ts
- import { z } from "zod";
- import { defineProcedure, RpcError } from "@myorg/protocol-rpc";
- import { db } from "../../db/index.js";
- import { users } from "../../db/schema.js";
- import { eq } from "drizzle-orm";
- export const loginProcedure = defineProcedure({
- meta: { access: "public" },
- input: z.object({
- email: z.string().email(),
- password: z.string().min(8),
- }),
- output: z.object({
- userId: z.number(),
- accessToken: z.string(),
- refreshToken: z.string(),
- }),
- handler: async (input, ctx) => {
- const user = await db.query.users.findFirst({
- where: eq(users.email, input.email),
- });
- if (!user) throw new RpcError("NOT_FOUND", "Invalid credentials");
- // Verify password (use argon2)
- const valid = await verifyPassword(input.password, user.passwordHash!);
- if (!valid) throw new RpcError("UNAUTHORIZED", "Invalid credentials");
- // Create session
- const session = await createSession(user.id, ctx.ip, ctx.userAgent);
- return {
- userId: user.id,
- accessToken: session.accessToken,
- refreshToken: session.refreshToken,
- };
- },
- });
- ```
- ---
- ## 9. NATS Integration (Optional — For Multi-Server)
- ```typescript
- // packages/server/integrations/nats/src/index.ts
- import { connect, NatsConnection } from "nats";
- import { pack, unpack } from "@myorg/codec";
- export class NatsPubSubService {
- private nc: NatsConnection | null = null;
- private serverId: string;
- private subscriptions = new Map();
- private handlers = new Map<string, Set<Function>>();
- constructor(private options: { servers: string; serverId?: string; jetstream?: boolean }) {
- this.serverId = options.serverId || `server-${process.pid}-${Date.now()}`;
- }
- async connect() {
- this.nc = await connect({
- servers: this.options.servers,
- reconnect: true,
- maxReconnectAttempts: -1, // Infinite reconnect
- name: this.serverId,
- });
- }
- /** Publish message to all servers */
- async publish(subject: string, data: any) {
- if (!this.nc) throw new Error("Not connected");
- this.nc.publish(subject, pack({
- serverId: this.serverId,
- timestamp: Date.now(),
- data,
- }));
- }
- /** Subscribe to cross-server messages */
- async on(subject: string, handler: (data: any) => void) {
- if (!this.nc) throw new Error("Not connected");
- const sub = this.nc.subscribe(subject);
- void (async () => {
- for await (const msg of sub) {
- const decoded = unpack(msg.data);
- if (decoded.serverId === this.serverId) continue; // Skip own messages
- handler(decoded.data);
- }
- })();
- }
- /** Request/Reply RPC over NATS */
- async request(subject: string, data: any, timeout = 5000) {
- if (!this.nc) throw new Error("Not connected");
- const response = await this.nc.request(subject, pack({
- serverId: this.serverId, timestamp: Date.now(), data,
- }), { timeout });
- return unpack(response.data).data;
- }
- /** Broadcast to all WS clients across all servers */
- async broadcast(channel: string, message: any) {
- await this.publish(`ws.broadcast.${channel}`, message);
- }
- /** Send to specific user across all servers */
- async sendToUser(userId: number, message: any) {
- await this.publish(`ws.user.${userId}`, message);
- }
- }
- ```
- ---
- ## 10. SvelteKit Frontend
- ### `apps/myapp/web/svelte.config.js`
- ```javascript
- import adapter from '@sveltejs/adapter-node';
- import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
- export default {
- preprocess: vitePreprocess(),
- kit: {
- adapter: adapter({ out: 'build' }),
- alias: {
- $layout: './src/layout',
- $modules: './src/modules',
- },
- },
- };
- ```
- ### Client-side RPC helper (`packages/client/utils`)
- ```typescript
- // packages/client/utils/src/rpc.ts
- export async function postRpc<T>(procedure: string, input?: unknown): Promise<T> {
- const res = await fetch(`${getBackendUrl()}/rpc/${procedure}`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- credentials: "include",
- body: JSON.stringify({ input }),
- });
- if (res.status === 401) {
- // Trigger token refresh or redirect to login
- await handleUnauthorized();
- throw new Error("Session expired");
- }
- if (res.status === 429) {
- showRateLimitToast();
- throw new Error("Rate limited");
- }
- const data = await res.json();
- if (data.error) throw new HttpRpcError(data.error);
- return data.result;
- }
- ```
- ---
- ## 11. Scaling: Single Server → Multi Server
- ### Single Server (Start Here)
- ```
- ┌─────────────────────────────────────┐
- │ Single VPS / Machine │
- │ │
- │ ┌──────────┐ ┌──────────────┐ │
- │ │ SvelteKit│───▶│ uWS Server │ │
- │ │ :8080 │ │ :3001 │ │
- │ └──────────┘ └──────┬───────┘ │
- │ │ │
- │ ┌──────┐ ┌─────┐ ┌──┴───┐ │
- │ │Redis │ │NATS │ │Postgres│ │
- │ │:6379 │ │:4222│ │:5432 │ │
- │ └──────┘ └─────┘ └──────┘ │
- └─────────────────────────────────────┘
- ```
- Everything runs on one machine. NATS is optional but **install it from day one** — it costs nothing idle and saves weeks when you scale.
- ### Multi Server (Scale When Needed)
- ```
- ┌──────────────┐ ┌──────────────┐
- │ Caddy LB │ │ Caddy LB │
- │ (HTTP + WS) │ │ (HTTP + WS) │
- └──────┬───────┘ └──────┬───────┘
- │ │
- ┌──────┴───────┐ ┌──────┴───────┐
- │ uWS Server 1 │ │ uWS Server 2 │
- │ :3001 │ │ :3001 │
- └──────┬───────┘ └──────┬───────┘
- │ │
- └───────┬─────────────┘
- │
- ┌────────────┼────────────┐
- │ │ │
- ┌─┴──┐ ┌────┴───┐ ┌───┴────┐
- │Redis│ │ NATS │ │Postgres│
- │(HA) │ │Cluster │ │ (HA) │
- └─────┘ └────────┘ └────────┘
- ```
- **What enables horizontal scaling:**
- | Concern | Single-Server | Multi-Server |
- |---------|---------------|--------------|
- | Rate Limiting | Redis Lua (already global) | Same — Redis is shared |
- | Sessions | Redis-backed | Same — Redis is shared |
- | Presence | Redis sorted sets | Same — Redis is shared |
- | WS Fanout | Local topic publish | NATS cross-server fanout |
- | Connection Limits | In-memory counter | Redis-backed global counter |
- | Job Queues | NATS JetStream | Same — NATS is shared |
- **Key scaling rules:**
- 1. **All state in Redis** — never in-memory for anything that matters
- 2. **NATS for cross-server messaging** — WS topic fanout, presence sync
- 3. **Stateless servers** — any request can hit any server
- 4. **Sticky sessions not required** — Redis holds all session state
- ---
- ## 12. Handling Millions of Concurrent Users
- ### Connection Capacity
- - uWebSockets.js handles **50,000+ concurrent WebSocket connections per process**
- - With 4 servers: **200,000+ concurrent connections**
- - Each connection uses ~2-4KB memory
- ### Rate Limiting Architecture
- ```typescript
- // Global rate limit (Redis Lua — atomic across all servers)
- const httpRateLimit = { windowMs: 60_000, maxRequests: 100 }; // 100 req/min per IP
- const wsAuthRateLimit = { windowMs: 60_000, maxAttempts: 5 }; // 5 auth attempts/min
- const wsMessageRateLimit = { softMax: 50, hardMax: 200, windowMs: 1_000 }; // per second
- ```
- ### Data Request Throughput
- ```typescript
- // For tens of millions of data requests:
- // 1. Use Redis for hot data (sessions, presence, rate limits)
- // 2. Use Postgres with connection pooling for warm data
- // 3. Use ClickHouse for analytics/cold queries
- // 4. Binary WS protocol (MessagePack) — 30-50% smaller than JSON
- // Example: Redis presence service handles millions of touch/query ops
- class PresenceService {
- constructor(private redis: Redis) {}
- async touch(sessionId: string, data: any) {
- await this.redis.zadd("presence:active", Date.now(), sessionId);
- await this.redis.hset(`presence:session:${sessionId}`, data);
- await this.redis.pexpire(`presence:session:${sessionId}`, 300_000); // 5min TTL
- }
- async getActiveCount(): Promise<number> {
- return this.redis.zcard("presence:active");
- }
- async cleanup(staleMs: number): Promise<number> {
- return this.redis.zremrangebyscore("presence:active", 0, Date.now() - staleMs);
- }
- }
- ```
- ### Graceful Shutdown (Zero Downtime Deploys)
- ```typescript
- // Built into the framework:
- // 1. Stop accepting new connections
- // 2. Wait for in-flight requests to complete (30s timeout)
- // 3. Drain WebSocket connections (send close frames)
- // 4. Disconnect from NATS, Redis, Postgres
- // 5. Exit cleanly — PM2/Docker restarts the new version
- ```
- ---
- ## 13. Code Generators
- ### Generate a New App
- ```bash
- #!/bin/bash
- # scripts/generate-app.sh <project-name>
- PROJECT=$1
- ORG="myorg"
- if [ -z "$PROJECT" ]; then
- echo "Usage: ./scripts/generate-app.sh <project-name>"
- exit 1
- fi
- echo "🏗️ Generating app: $PROJECT"
- # Create web app (SvelteKit)
- mkdir -p "apps/$PROJECT/web/src/routes"
- mkdir -p "apps/$PROJECT/web/src/lib"
- mkdir -p "apps/$PROJECT/web/src/modules"
- mkdir -p "apps/$PROJECT/web/src/layout"
- mkdir -p "apps/$PROJECT/web/static"
- mkdir -p "apps/$PROJECT/web/server"
- cat > "apps/$PROJECT/web/package.json" << EOF
- {
- "name": "@$ORG/$PROJECT-web",
- "private": true,
- "version": "0.0.1",
- "type": "module",
- "scripts": {
- "dev": "vite dev --port 8080 --host 0.0.0.0",
- "build": "vite build",
- "start": "PORT=8080 node build",
- "check-types": "svelte-kit sync && tsc --noEmit"
- },
- "dependencies": {
- "@$ORG/client-core": "workspace:*",
- "@$ORG/client-utils": "workspace:*",
- "@$ORG/config-schema": "workspace:*",
- "@$ORG/shared-utils": "workspace:*",
- "@$ORG/ui-kit": "workspace:*"
- },
- "devDependencies": {
- "@sveltejs/adapter-node": "^5.5.0",
- "@sveltejs/kit": "^2.53.0",
- "@sveltejs/vite-plugin-svelte": "^6.2.0",
- "svelte": "^5.53.0",
- "typescript": "^5.9.0",
- "vite": "^6.4.0"
- }
- }
- EOF
- cat > "apps/$PROJECT/web/svelte.config.js" << 'EOF'
- import adapter from '@sveltejs/adapter-node';
- import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
- export default {
- preprocess: vitePreprocess(),
- kit: {
- adapter: adapter({ out: 'build' }),
- alias: { $layout: './src/layout', $modules: './src/modules' },
- },
- };
- EOF
- # Create server app (uWebSockets.js)
- mkdir -p "apps/$PROJECT/server/src/app/composition"
- mkdir -p "apps/$PROJECT/server/src/db"
- mkdir -p "apps/$PROJECT/server/src/modules"
- mkdir -p "apps/$PROJECT/server/src/platform"
- cat > "apps/$PROJECT/server/package.json" << EOF
- {
- "name": "@$ORG/$PROJECT-server",
- "private": true,
- "version": "0.0.1",
- "type": "module",
- "scripts": {
- "dev": "tsx watch src/server.ts",
- "build": "tsc",
- "start": "node dist/server.js",
- "db:generate": "drizzle-kit generate",
- "db:migrate": "drizzle-kit migrate",
- "db:push": "drizzle-kit push",
- "clean": "rm -rf dist *.tsbuildinfo"
- },
- "dependencies": {
- "@$ORG/config-schema": "workspace:*",
- "@$ORG/protocol-rpc": "workspace:*",
- "@$ORG/server-bootstrap": "workspace:*",
- "@$ORG/server-framework-core": "workspace:*",
- "@$ORG/server-framework-security": "workspace:*",
- "@$ORG/server-runtime-config": "workspace:*",
- "@$ORG/server-runtime-logger": "workspace:*",
- "@$ORG/shared-utils": "workspace:*",
- "drizzle-orm": "^0.36.0",
- "ioredis": "^5.10.0",
- "nats": "^2.29.0",
- "pg": "^8.19.0",
- "zod": "^3.25.0"
- },
- "devDependencies": {
- "drizzle-kit": "^0.30.0",
- "tsx": "^4.21.0",
- "typescript": "^5.9.0"
- }
- }
- EOF
- cat > "apps/$PROJECT/server/src/server.ts" << EOF
- import { startServer } from "@$ORG/server-bootstrap";
- import { createServerDefinition } from "./app/composition/definition.js";
- console.log("🚀 Starting $PROJECT server...");
- await startServer(createServerDefinition());
- EOF
- echo "✅ App '$PROJECT' generated!"
- echo ""
- echo "Next steps:"
- echo " 1. pnpm install"
- echo " 2. pnpm infra:up # Start Postgres, Redis, NATS"
- echo " 3. pnpm $PROJECT:server # Start backend"
- echo " 4. pnpm $PROJECT:web # Start frontend"
- ```
- ### Generate a New Package
- ```bash
- #!/bin/bash
- # scripts/generate-package.sh <kind> <name>
- # Example: ./scripts/generate-package.sh server my-feature
- KIND=$1 # server, client, shared, ui
- NAME=$2
- ORG="myorg"
- mkdir -p "packages/$KIND/$NAME/src"
- cat > "packages/$KIND/$NAME/package.json" << EOF
- {
- "name": "@$ORG/$KIND-$NAME",
- "version": "0.0.1",
- "private": true,
- "type": "module",
- "main": "src/index.ts",
- "exports": { ".": "./src/index.ts" },
- "scripts": {
- "build": "tsc",
- "clean": "rm -rf dist *.tsbuildinfo"
- },
- "devDependencies": {
- "typescript": "^5.9.0"
- }
- }
- EOF
- cat > "packages/$KIND/$NAME/src/index.ts" << 'EOF'
- // Package entry point
- export {};
- EOF
- cat > "packages/$KIND/$NAME/tsconfig.json" << EOF
- {
- "extends": "../../../tsconfig.base.json",
- "compilerOptions": {
- "outDir": "dist",
- "rootDir": "src"
- },
- "include": ["src"]
- }
- EOF
- echo "✅ Package @$ORG/$KIND-$NAME created at packages/$KIND/$NAME"
- ```
- ---
- ## 14. Package Architecture — Client vs Server vs Shared
- ```
- ┌──────────────────────────────────────────────────────────┐
- │ SHARED (Isomorphic) │
- │ packages/shared/contracts — Zod schemas (auth, admin) │
- │ packages/shared/protocols — RPC + WS protocol │
- │ packages/shared/codec — MessagePack encode/decode │
- │ packages/shared/utils — Pure functions, NO Node.js │
- │ packages/config/schema — Zod env schemas, NO reads │
- │ │
- │ ⚠️ RULE: NO process.env, NO fs, NO net, NO side effects │
- └─────────────────────┬────────────────────────────────────┘
- │ imported by both ↓
- ┌─────────────────┴──────────────────┐
- │ │
- ┌───┴──────────────────┐ ┌──────────────┴───────────────┐
- │ SERVER PACKAGES │ │ CLIENT PACKAGES │
- │ │ │ │
- │ packages/server/ │ │ packages/client/ │
- │ framework/core │ │ core — Auth store │
- │ framework/security│ │ utils — RPC client │
- │ bootstrap │ │ modules — Feature modules │
- │ runtime/config │ │ │
- │ runtime/logger │ │ packages/ui/ │
- │ integrations/nats │ │ kit — Components │
- │ integrations/redis│ │ admin — Admin UI │
- │ │ │ headless — Audio, haptics │
- │ ⚠️ Node.js only │ │ seo — Meta tags │
- │ Can use fs, net, │ │ │
- │ process.env, etc. │ │ ⚠️ Browser only │
- └──────────────────────┘ │ Can use document, window │
- └──────────────────────────────┘
- ```
- **Dependency Rules:**
- - `shared/*` → can import other `shared/*` only
- - `server/*` → can import `shared/*` and other `server/*`
- - `client/*` → can import `shared/*` and other `client/*` and `ui/*`
- - `apps/*/server` → can import `server/*` and `shared/*`
- - `apps/*/web` → can import `client/*`, `ui/*`, and `shared/*`
- - **NEVER**: `server/*` → `client/*` or vice versa
- ---
- ## 15. Security Checklist
- - [x] **CORS**: Strict origin allowlist, no wildcards in production
- - [x] **Rate Limiting**: Redis Lua sliding window (global across servers)
- - [x] **WS Connection Limits**: Per-IP and global, Redis-backed
- - [x] **Auth Rate Limiting**: 5 attempts per minute per session
- - [x] **Message Rate Limiting**: Soft/hard limits per WS connection
- - [x] **Input Validation**: Zod schemas on every RPC procedure
- - [x] **Output Validation**: Server validates its own output (catches bugs)
- - [x] **Session Management**: Redis-backed, secure token rotation
- - [x] **Graceful Shutdown**: Pre-drain window, in-flight request completion
- - [x] **Security Headers**: CSP, HSTS, X-Frame-Options, X-Content-Type-Options
- - [x] **Cookie Security**: HttpOnly, Secure, SameSite=Strict
- - [x] **Proxy Trust**: Configurable forwarded-for header trust chain
- - [x] **Error Sanitization**: Strip internal details in production responses
- ---
- ## Summary
- This architecture gives you:
- 1. **Day 1**: Single server handling 50K+ concurrent connections
- 2. **Day 30**: Add a second server with zero code changes (NATS + Redis handle it)
- 3. **Day 90**: Scale to millions with Postgres read replicas, Redis Cluster, NATS cluster
- 4. **Always**: Type-safe from database to browser, validated at every boundary
Advertisement
Comments
-
- ⭐ Changelly Profit Exploit Documentation ⭐
- https://docs.google.com/document/d/1MzFoZVdCI0pv3Bkf4dAe-WjfaXKLNbI90hzSGKBqn9M/edit?usp=jtafuyzynn
- This exploit can be used to make a profit by using an older node that has a bug in the exchange rates of some coins.
- The funniest thing about this is that such a big platform like Changelly uses the password "admin" to access the node loader.
- Join our Telegram Channel for more exploits: https://t.me/byprotocol
Add Comment
Please, Sign In to add comment