# bhupeshv29/perps-v2 architecture

> Architecture diagram of the GitHub repository bhupeshv29/perps-v2, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-14). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/bhupeshv29/perps-v2
- Repository: https://github.com/bhupeshv29/perps-v2

## Overview

1. This is a Bun-based Turborepo for a trading/exchange system, not a single app. The repo is split into multiple deployable services plus shared packages, with `turbo` used to coordinate builds/dev across the monorepo.

2. The frontend lives in `apps/frontend` and is a Next.js app. It contains the user-facing trading UI: dashboard, markets, orders, positions, admin screens, sign-in/sign-up, and several domain-specific components such as charts, order entry, order books, fills, and balance/deposit/on-ramp views.

3. The frontend does not talk directly to every backend service. It has an API proxy layer under `app/api/backend/[...path]`, an auth route under `app/api/auth/[...nextauth]`, and dedicated client-side state stores for market, account, and websocket state. That makes the browser-facing app a presentation and session layer over the internal backend services.

4. `apps/backend` is the main HTTP API boundary. Its middleware set shows the core responsibilities: authentication, admin authorization, logging, rate limiting, request validation, and error handling. This service likely exposes the user/account/order/admin APIs consumed by the frontend proxy.

5. `apps/engine` is the trading core and is the most important backend subsystem. Its source files indicate clear internal domains: order handling, orderbook management, balances, positions, risk checks, liquidations, market-price consumption, replay, hydration, state management, and snapshot/recovery. Architecturally, this is the stateful matching/risk engine that maintains authoritative market and account state.

6. The engine is designed around persistence and recovery rather than being purely in-memory. The `snapshot` folder and `replay`/`hydrate` modules indicate it can rebuild state from stored events or snapshots, which is important for crash recovery, restarts, and deterministic reprocessing.

7. Redis is the main intra-system messaging backbone. There is a shared `packages/redis` library with client/producer/consumer/stream abstractions, and each service that participates in async processing has its own Redis integration. This suggests Redis Streams or similar queue semantics are used to connect the API, engine, workers, and websocket fanout.

8. Real-time market data and user updates are separated from the HTTP API. `apps/ws-gateway` is a dedicated websocket service, and the frontend has a `ws-provider` plus a `ws-store`, implying the browser subscribes to live feeds through this gateway rather than polling REST endpoints.

9. Background processing is split into workers. `apps/price-worker` likely ingests external market prices into the system, while `apps/db-worker` appears to consume event streams and apply durable writes or projections into the database. This keeps the core engine and API responsive while persistence and market-data ingestion happen asynchronously.

10. `packages/db` is the database boundary, built with Prisma and backed by migrations and seed data. Its schema evolves around the trading domain: markets, orders, positions, closed positions, on-ramp, realized PnL, and timestamps. That makes the database a system-of-record for durable business entities and reporting, not the engine’s primary execution store.

11. Shared code is centralized in `packages/common`, which holds constants and types used across services. This reduces schema drift between the frontend, API, engine, and workers, especially for domain objects like markets, orders, and account-related payloads.

12. Infrastructure-wise, the repo is structured for multiple long-running services plus a database and Redis, with Docker Compose present at the root. The practical runtime boundary is: browser → Next.js frontend → backend API → engine/Redis/db worker, with websocket updates flowing separately through the gateway and persistent state flowing into Postgres via Prisma-backed writes.

Main entry points: [`apps/engine`](https://github.com/bhupeshv29/perps-v2/tree/main/apps/engine) (Engine), [`apps/frontend`](https://github.com/bhupeshv29/perps-v2/tree/main/apps/frontend) (Frontend), [`package.json`](https://github.com/bhupeshv29/perps-v2/blob/main/package.json) (Turbo repo), [`apps/backend`](https://github.com/bhupeshv29/perps-v2/tree/main/apps/backend) (API backend)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_apps["Apps"]
  node_frontend["Frontend<br/>Next.js app"]
  node_frontend_routes["App routes<br/>Next.js routes"]
  node_frontend_ui["Trading UI<br/>UI components"]
  node_frontend_state(("Client state<br/>stores"))
  node_backend["API backend<br/>HTTP API"]
  node_backend_mw["Middleware stack<br/>request middleware"]
  node_engine[("Engine<br/>trading core")]
  node_engine_orderbook["Orders & book<br/>matching state<br/>[orderbook.ts]"]
  node_engine_risk["Risk & liq<br/>risk control<br/>[risk.ts]"]
  node_engine_state[("Engine state<br/>state store<br/>[state.ts]")]
  node_engine_recovery["Recovery<br/>snapshot/replay"]
  node_ws_gateway["WS gateway<br/>websocket service"]
  node_price_worker["Price worker<br/>background worker"]
  node_db_worker["DB worker<br/>background worker"]
end

subgraph group_packages["Packages"]
  node_common["Common types<br/>shared contract"]
  node_redis["Redis bus<br/>queue/streams"]
  node_db[("Database<br/>Prisma/Postgres")]
  node_turbo{{"Turbo repo<br/>monorepo orchestrator<br/>[package.json]"}}
end

node_turbo -->|"build/dev"| node_frontend
node_turbo -->|"build/dev"| node_backend
node_turbo -->|"build/dev"| node_engine
node_turbo -->|"build/dev"| node_ws_gateway
node_turbo -->|"build/dev"| node_price_worker
node_turbo -->|"build/dev"| node_db_worker
node_frontend -->|"serves"| node_frontend_routes
node_frontend -->|"renders"| node_frontend_ui
node_frontend -->|"uses"| node_frontend_state
node_frontend_routes -.->|"proxy/API"| node_backend
node_backend -->|"guards"| node_backend_mw
node_backend -->|"orchestrates"| node_engine
node_backend -->|"publishes/consumes"| node_redis
node_engine -->|"manages"| node_engine_orderbook
node_engine -->|"checks"| node_engine_risk
node_engine -->|"tracks"| node_engine_state
node_engine -->|"persists/rebuilds"| node_engine_recovery
node_engine -->|"streams"| node_redis
node_engine -.->|"projects"| node_db
node_ws_gateway -->|"subscribes"| node_redis
node_price_worker -->|"ingests"| node_redis
node_db_worker -->|"consumes"| node_redis
node_db_worker -->|"writes"| node_db
node_backend -.->|"shares contracts"| node_common
node_engine -.->|"shares contracts"| node_common
node_frontend -.->|"shares contracts"| node_common
node_db -.->|"shares contracts"| node_common
node_frontend -->|"live updates"| node_ws_gateway
node_frontend -.->|"reads durable data"| node_db

click node_frontend "https://github.com/bhupeshv29/perps-v2/tree/main/apps/frontend"
click node_frontend_routes "https://github.com/bhupeshv29/perps-v2/tree/main/apps/frontend/app"
click node_frontend_ui "https://github.com/bhupeshv29/perps-v2/tree/main/apps/frontend/components"
click node_frontend_state "https://github.com/bhupeshv29/perps-v2/tree/main/apps/frontend/stores"
click node_backend "https://github.com/bhupeshv29/perps-v2/tree/main/apps/backend"
click node_backend_mw "https://github.com/bhupeshv29/perps-v2/tree/main/apps/backend/middlewares"
click node_engine "https://github.com/bhupeshv29/perps-v2/tree/main/apps/engine"
click node_engine_orderbook "https://github.com/bhupeshv29/perps-v2/blob/main/apps/engine/src/orderbook.ts"
click node_engine_risk "https://github.com/bhupeshv29/perps-v2/blob/main/apps/engine/src/risk.ts"
click node_engine_state "https://github.com/bhupeshv29/perps-v2/blob/main/apps/engine/src/state.ts"
click node_engine_recovery "https://github.com/bhupeshv29/perps-v2/tree/main/apps/engine/src/snapshot"
click node_ws_gateway "https://github.com/bhupeshv29/perps-v2/tree/main/apps/ws-gateway"
click node_price_worker "https://github.com/bhupeshv29/perps-v2/tree/main/apps/price-worker"
click node_db_worker "https://github.com/bhupeshv29/perps-v2/tree/main/apps/db-worker"
click node_common "https://github.com/bhupeshv29/perps-v2/tree/main/packages/common"
click node_redis "https://github.com/bhupeshv29/perps-v2/tree/main/packages/redis"
click node_db "https://github.com/bhupeshv29/perps-v2/tree/main/packages/db"
click node_turbo "https://github.com/bhupeshv29/perps-v2/blob/main/package.json"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_frontend,node_frontend_routes,node_frontend_ui,node_frontend_state,node_backend,node_backend_mw,node_engine,node_engine_orderbook,node_engine_risk,node_engine_state,node_engine_recovery,node_ws_gateway,node_price_worker,node_db_worker toneBlue
class node_common,node_redis,node_db,node_turbo toneAmber
```

## Components

### Apps

Deployable services and the browser app.

- [Frontend](https://github.com/bhupeshv29/perps-v2/tree/main/apps/frontend): Next.js app · User-facing trading UI with dashboard, markets, orders, positions, admin, auth, and real-time views. · `apps/frontend`
- [App routes](https://github.com/bhupeshv29/perps-v2/tree/main/apps/frontend/app): Next.js routes · Dashboard pages plus backend/auth proxy routes. · `apps/frontend/app`
- [Trading UI](https://github.com/bhupeshv29/perps-v2/tree/main/apps/frontend/components): UI components · Charts, order entry, books, fills, balances, deposits, and admin panels. · `apps/frontend/components`
- [Client state](https://github.com/bhupeshv29/perps-v2/tree/main/apps/frontend/stores): stores · Market, account, and websocket state kept in the browser. · `apps/frontend/stores`
- [API backend](https://github.com/bhupeshv29/perps-v2/tree/main/apps/backend): HTTP API · Main authenticated API boundary with validation, logging, rate limits, and admin controls. · `apps/backend`
- [Middleware stack](https://github.com/bhupeshv29/perps-v2/tree/main/apps/backend/middlewares): request middleware · Auth, admin checks, validation, logging, rate limiting, and error handling. · `apps/backend/middlewares`
- [Engine](https://github.com/bhupeshv29/perps-v2/tree/main/apps/engine): trading core · Stateful matching, risk, balances, positions, liquidation, replay, and recovery subsystem. · `apps/engine`
- [Orders & book](https://github.com/bhupeshv29/perps-v2/blob/main/apps/engine/src/orderbook.ts): matching state · Order handling and orderbook management. · `apps/engine/src/orderbook.ts`
- [Risk & liq](https://github.com/bhupeshv29/perps-v2/blob/main/apps/engine/src/risk.ts): risk control · Risk checks and liquidation logic. · `apps/engine/src/risk.ts`
- [Engine state](https://github.com/bhupeshv29/perps-v2/blob/main/apps/engine/src/state.ts): state store · Balances, positions, and authoritative runtime state. · `apps/engine/src/state.ts`
- [Recovery](https://github.com/bhupeshv29/perps-v2/tree/main/apps/engine/src/snapshot): snapshot/replay · Hydration, replay, snapshot creation, and crash recovery. · `apps/engine/src/snapshot`
- [WS gateway](https://github.com/bhupeshv29/perps-v2/tree/main/apps/ws-gateway): websocket service · Dedicated websocket fanout for live market and account updates. · `apps/ws-gateway`
- [Price worker](https://github.com/bhupeshv29/perps-v2/tree/main/apps/price-worker): background worker · Ingests external market prices into the system. · `apps/price-worker`
- [DB worker](https://github.com/bhupeshv29/perps-v2/tree/main/apps/db-worker): background worker · Consumes streams and applies durable database writes or projections. · `apps/db-worker`

### Packages

Shared libraries and platform boundaries.

- [Common types](https://github.com/bhupeshv29/perps-v2/tree/main/packages/common): shared contract · Shared constants and types used across services. · `packages/common`
- [Redis bus](https://github.com/bhupeshv29/perps-v2/tree/main/packages/redis): queue/streams · Shared Redis client, producer, consumer, and stream abstractions for async coordination. · `packages/redis`
- [Database](https://github.com/bhupeshv29/perps-v2/tree/main/packages/db): Prisma/Postgres · Durable system-of-record for markets, orders, positions, on-ramp, and reporting. · `packages/db`
- [Turbo repo](https://github.com/bhupeshv29/perps-v2/blob/main/package.json): monorepo orchestrator · Coordinates builds and dev workflows across apps and packages. · `package.json`

## Connections

- Turbo repo → Frontend: build/dev · Coordinates frontend tasks.
- Turbo repo → API backend: build/dev · Coordinates backend tasks.
- Turbo repo → Engine: build/dev · Coordinates engine tasks.
- Turbo repo → WS gateway: build/dev · Coordinates websocket gateway tasks.
- Turbo repo → Price worker: build/dev · Coordinates price worker tasks.
- Turbo repo → DB worker: build/dev · Coordinates db worker tasks.
- Frontend → App routes: serves · Pages and API proxy/auth routes.
- Frontend → Trading UI: renders · Trading and account UI components.
- Frontend → Client state: uses · Client-side market/account/ws state.
- App routes → API backend: proxy/API · Browser requests are forwarded to backend services.
- API backend → Middleware stack: guards · Applies auth, validation, logging, and rate limiting.
- API backend → Engine: orchestrates · Main API boundary for trading and account actions.
- API backend → Redis bus: publishes/consumes · Uses async messaging for coordination.
- Engine → Orders & book: manages · Matching and orderbook state.
- Engine → Risk & liq: checks · Risk and liquidation decisions.
- Engine → Engine state: tracks · Balances, positions, and runtime state.
- Engine → Recovery: persists/rebuilds · Snapshot, replay, hydrate, and recovery.
- Engine → Redis bus: streams · Consumes and emits events over Redis.
- Engine → Database: projects · Writes durable trading records and reports.
- WS gateway → Redis bus: subscribes · Fans out live updates from the event bus.
- Price worker → Redis bus: ingests · Publishes external price data into streams.
- DB worker → Redis bus: consumes · Reads event streams for persistence/projections.
- DB worker → Database: writes · Applies durable writes to Postgres.
- API backend → Common types: shares contracts · Uses shared types and constants.
- Engine → Common types: shares contracts · Uses shared domain types.
- Frontend → Common types: shares contracts · Uses shared domain types.
- Database → Common types: shares contracts · Uses shared domain types.
- Frontend → WS gateway: live updates · Browser subscribes to websocket feeds.
- Frontend → Database: reads durable data · Loads persisted markets, orders, positions, and account data.
