# prajwalgraj/cex-rust architecture

> Architecture diagram of the GitHub repository prajwalgraj/cex-rust, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-02). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/prajwalgraj/cex-rust
- Repository: https://github.com/prajwalgraj/cex-rust

## Overview

1. **Overall shape**
   - This is a Rust workspace for a centralized exchange simulator.
   - The architecture is split into small crates with clear boundaries: HTTP/API, orchestration, matching, balance handling, shared domain types, persistence, and benchmarking.

2. **External entrypoints**
   - The main runtime path is the **API service** in `crates/api`, which exposes REST endpoints.
   - There is also a separate **benchmark runner** in `crates/benchmark` that exercises the API end-to-end.
   - The repository includes a root `src/main.rs` and a separate `crates/app` binary, which likely serve as launchers/wrappers around the exchange runtime.

3. **API boundary**
   - `crates/api` is the transport layer.
   - It owns HTTP routes such as deposit, order placement, order cancellation, balance lookup, and book retrieval.
   - Its job is to translate HTTP requests into domain actions and return serialized responses; it should not contain matching or persistence rules itself.

4. **Exchange orchestration layer**
   - `crates/exchange` is the coordination layer that sits between the API and the core subsystems.
   - It contains actor-like components such as `market_actor.rs` and `balance_actor.rs`, which suggests asynchronous message-driven coordination.
   - This is the main boundary where request handling becomes exchange workflow: validate, reserve funds, match orders, settle fills, and persist state.

5. **Matching engine**
   - `crates/engine` implements order-book behavior and matching logic.
   - The README says it uses **price-time priority**, with a `BTreeMap` for price levels and `VecDeque` for FIFO execution within each price level.
   - This crate is the core trading algorithm boundary: it knows how orders are matched, partially filled, fully filled, and canceled.

6. **Balance management**
   - `crates/balance` handles reservation and release of funds.
   - This is a separate subsystem from matching so that funds are controlled independently from order-book logic.
   - In the architecture diagram, this is the pre-trade/post-trade money control path: reserve on order entry, release on cancel or remaining unfilled amounts, and update after settlement.

7. **Domain model layer**
   - `crates/domain` contains shared types and business entities used across the system.
   - It includes market and settlement models, so the API, exchange, engine, and storage can all speak the same language.
   - This crate is the canonical definition of exchange concepts and reduces coupling between subsystems.

8. **Persistence layer**
   - `crates/storage` is the PostgreSQL persistence boundary.
   - It is organized into repositories for balances, orders, trades, and settlements.
   - The README emphasizes atomic settlement, so the persistence layer is not just storage; it is part of consistency control, likely using SQLx transactions.

9. **Database and schema**
   - PostgreSQL is the system of record.
   - SQL migrations in `migrations/` define the core tables for balances, orders, and trades.
   - Recovery on restart implies the service can rebuild exchange state from these persisted records rather than keeping all state only in memory.

10. **Request/data flow for order placement**
   - A client calls `POST /orders`.
   - The API hands the request to exchange orchestration.
   - The balance subsystem reserves funds, the engine attempts matching, and the storage layer records the resulting order/trade/settlement state.
   - This is the main end-to-end path to show in a diagram.

11. **Request/data flow for cancellation**
   - Cancellation begins at `POST /orders/{order_id}/cancel`.
   - The exchange layer coordinates the cancel with the engine and then releases or adjusts reserved balance.
   - The repositories persist the cancellation and any resulting balance changes.

12. **Read paths**
   - `GET /balances/{user_id}` reads from the balance storage path.
   - `GET /book/{market}` exposes the current order book, which is likely backed by the engine or an exchange-owned in-memory view.
   - These are read-oriented boundaries and are distinct from the transactional order flow.

13. **Benchmarking and observability of behavior**
   - `crates/benchmark` is an external load/testing client, not part of the exchange runtime.
   - It includes separate scenarios for place, match, and cancel latency measurements.
   - This indicates the project cares about request latency across the full stack, from API through orchestration to persistence.

14. **Deployment/runtime concerns**
   - The project is async Rust using **Tokio**.
   - **Axum** provides the HTTP layer, **SQLx** handles PostgreSQL access, and **Serde** handles serialization.
   - `docker-compose.yml`, `.env.example`, and SQL migrations show that local deployment depends on a PostgreSQL service and environment-based configuration.

15. **Best way to draw the architecture**
   - Draw the system as four layers: HTTP/API, exchange orchestration, domain/core services, and PostgreSQL storage.
   - Put the matching engine and balance manager as sibling core services coordinated by the exchange layer.
   - Show the benchmark client as an external consumer hitting the API, and show PostgreSQL as the durable source of truth used for settlement and recovery.

Main entry points: [`crates/exchange/src/market_actor.rs`](https://github.com/prajwalgraj/cex-rust/blob/main/crates/exchange/src/market_actor.rs) (Market Actor), [`crates/storage/src/lib.rs`](https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/lib.rs) (Storage), [`crates/api/src/main.rs`](https://github.com/prajwalgraj/cex-rust/blob/main/crates/api/src/main.rs) (API Service), [`crates/exchange/src/lib.rs`](https://github.com/prajwalgraj/cex-rust/blob/main/crates/exchange/src/lib.rs) (Exchange)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_external["External clients"]
  node_benchmark_runner["Benchmark<br/>load client<br/>[main.rs]"]
end

subgraph group_runtime["Runtime entrypoints"]
  node_root_launcher["Root Main<br/>launcher<br/>[main.rs]"]
  node_app_launcher["App Main<br/>launcher<br/>[main.rs]"]
end

subgraph group_api["API layer"]
  node_api_service["API Service<br/>http server<br/>[main.rs]"]
  node_api_models["API Models<br/>transport models<br/>[models.rs]"]
end

subgraph group_exchange["Orchestration"]
  node_exchange_coord{{"Exchange<br/>orchestrator<br/>[lib.rs]"}}
  node_market_actor(("Market Actor<br/>async actor<br/>[market_actor.rs]"))
  node_balance_actor(("Balance Actor<br/>async actor<br/>[balance_actor.rs]"))
end

subgraph group_core["Core services"]
  node_engine_core{{"Matching Engine<br/>price-time matcher<br/>[lib.rs]"}}
  node_balance_core{{"Balance Service<br/>funds control<br/>[lib.rs]"}}
  node_domain_market["Market Types<br/>domain model<br/>[market.rs]"]
  node_domain_settlement["Settlement Types<br/>domain model<br/>[settlement.rs]"]
end

subgraph group_persistence["Persistence"]
  node_storage_facade[("Storage<br/>repository layer<br/>[lib.rs]")]
  node_balance_repo["Balance Repo<br/>postgres repo"]
  node_order_repo["Order Repo<br/>postgres repo"]
  node_trade_repo["Trade Repo<br/>postgres repo"]
  node_settlement_repo["Settlement Repo<br/>postgres repo"]
  node_postgres[("PostgreSQL<br/>database")]
end

node_benchmark_runner -->|"HTTP load"| node_api_service
node_root_launcher -->|"starts"| node_api_service
node_app_launcher -->|"starts"| node_api_service
node_api_service -->|"serializes"| node_api_models
node_api_service -->|"dispatches"| node_exchange_coord
node_exchange_coord -->|"routes orders"| node_market_actor
node_exchange_coord -->|"routes funds"| node_balance_actor
node_market_actor -->|"matches"| node_engine_core
node_market_actor -->|"persists orders"| node_order_repo
node_market_actor -->|"persists trades"| node_trade_repo
node_market_actor -->|"uses types"| node_domain_market
node_balance_actor -->|"controls funds"| node_balance_core
node_balance_actor -->|"persists balances"| node_balance_repo
node_balance_actor -->|"uses types"| node_domain_settlement
node_exchange_coord -->|"persists state"| node_storage_facade
node_storage_facade -->|"contains"| node_balance_repo
node_storage_facade -->|"contains"| node_order_repo
node_storage_facade -->|"contains"| node_trade_repo
node_storage_facade -->|"contains"| node_settlement_repo
node_balance_repo -->|"reads/writes"| node_postgres
node_order_repo -->|"reads/writes"| node_postgres
node_trade_repo -->|"reads/writes"| node_postgres
node_settlement_repo -->|"reads/writes"| node_postgres
node_engine_core -->|"interprets"| node_domain_market
node_balance_core -->|"interprets"| node_domain_settlement

click node_benchmark_runner "https://github.com/prajwalgraj/cex-rust/blob/main/crates/benchmark/src/main.rs"
click node_api_service "https://github.com/prajwalgraj/cex-rust/blob/main/crates/api/src/main.rs"
click node_root_launcher "https://github.com/prajwalgraj/cex-rust/blob/main/src/main.rs"
click node_app_launcher "https://github.com/prajwalgraj/cex-rust/blob/main/crates/app/src/main.rs"
click node_api_models "https://github.com/prajwalgraj/cex-rust/blob/main/crates/api/src/models.rs"
click node_exchange_coord "https://github.com/prajwalgraj/cex-rust/blob/main/crates/exchange/src/lib.rs"
click node_market_actor "https://github.com/prajwalgraj/cex-rust/blob/main/crates/exchange/src/market_actor.rs"
click node_balance_actor "https://github.com/prajwalgraj/cex-rust/blob/main/crates/exchange/src/balance_actor.rs"
click node_engine_core "https://github.com/prajwalgraj/cex-rust/blob/main/crates/engine/src/lib.rs"
click node_balance_core "https://github.com/prajwalgraj/cex-rust/blob/main/crates/balance/src/lib.rs"
click node_domain_market "https://github.com/prajwalgraj/cex-rust/blob/main/crates/domain/src/market.rs"
click node_domain_settlement "https://github.com/prajwalgraj/cex-rust/blob/main/crates/domain/src/settlement.rs"
click node_storage_facade "https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/lib.rs"
click node_balance_repo "https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/balance_repository.rs"
click node_order_repo "https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/order_repository.rs"
click node_trade_repo "https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/trade_repository.rs"
click node_settlement_repo "https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/settlement_repository.rs"

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_benchmark_runner toneBlue
class node_root_launcher,node_app_launcher toneAmber
class node_api_service,node_api_models toneMint
class node_exchange_coord,node_market_actor,node_balance_actor toneRose
class node_engine_core,node_balance_core,node_domain_market,node_domain_settlement toneIndigo
class node_storage_facade,node_balance_repo,node_order_repo,node_trade_repo,node_settlement_repo,node_postgres toneTeal
```

## Components

### External clients

Clients and runners that exercise the exchange over HTTP.

- [Benchmark](https://github.com/prajwalgraj/cex-rust/blob/main/crates/benchmark/src/main.rs): load client · End-to-end benchmark runner for place, match, and cancel flows. · `crates/benchmark/src/main.rs`

### Runtime entrypoints

Binary entrypoints that launch the exchange service.

- [Root Main](https://github.com/prajwalgraj/cex-rust/blob/main/src/main.rs): launcher · Workspace-level binary entrypoint. · `src/main.rs`
- [App Main](https://github.com/prajwalgraj/cex-rust/blob/main/crates/app/src/main.rs): launcher · Alternate binary entrypoint for running the exchange application. · `crates/app/src/main.rs`

### API layer

HTTP transport and request/response boundary.

- [API Service](https://github.com/prajwalgraj/cex-rust/blob/main/crates/api/src/main.rs): http server · Axum-based REST entrypoint for exchange operations. · `crates/api/src/main.rs`
- [API Models](https://github.com/prajwalgraj/cex-rust/blob/main/crates/api/src/models.rs): transport models · Request and response shapes used by the HTTP layer. · `crates/api/src/models.rs`

### Orchestration

Coordination layer that turns requests into exchange workflows.

- [Exchange](https://github.com/prajwalgraj/cex-rust/blob/main/crates/exchange/src/lib.rs): orchestrator · Coordinates validation, reservation, matching, settlement, and persistence. · `crates/exchange/src/lib.rs`
- [Market Actor](https://github.com/prajwalgraj/cex-rust/blob/main/crates/exchange/src/market_actor.rs): async actor · Market workflow coordinator for order entry, matching, and cancellation. · `crates/exchange/src/market_actor.rs`
- [Balance Actor](https://github.com/prajwalgraj/cex-rust/blob/main/crates/exchange/src/balance_actor.rs): async actor · Balance workflow coordinator for reserve, release, and settlement updates. · `crates/exchange/src/balance_actor.rs`

### Core services

Matching, balance control, and shared domain types.

- [Matching Engine](https://github.com/prajwalgraj/cex-rust/blob/main/crates/engine/src/lib.rs): price-time matcher · Order-book engine using price-time priority for fills and cancels. · `crates/engine/src/lib.rs`
- [Balance Service](https://github.com/prajwalgraj/cex-rust/blob/main/crates/balance/src/lib.rs): funds control · Reserves, releases, and applies balance changes around trading. · `crates/balance/src/lib.rs`
- [Market Types](https://github.com/prajwalgraj/cex-rust/blob/main/crates/domain/src/market.rs): domain model · Shared market and order-book concepts used across the system. · `crates/domain/src/market.rs`
- [Settlement Types](https://github.com/prajwalgraj/cex-rust/blob/main/crates/domain/src/settlement.rs): domain model · Shared settlement and trade result concepts. · `crates/domain/src/settlement.rs`

### Persistence

Repositories and database-backed state.

- [Storage](https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/lib.rs): repository layer · Persistence boundary that groups order, trade, balance, and settlement storage. · `crates/storage/src/lib.rs`
- [Balance Repo](https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/balance_repository.rs): postgres repo · Balance persistence and lookup. · `crates/storage/src/balance_repository.rs`
- [Order Repo](https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/order_repository.rs): postgres repo · Order persistence and cancellation state. · `crates/storage/src/order_repository.rs`
- [Trade Repo](https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/trade_repository.rs): postgres repo · Executed trade persistence. · `crates/storage/src/trade_repository.rs`
- [Settlement Repo](https://github.com/prajwalgraj/cex-rust/blob/main/crates/storage/src/settlement_repository.rs): postgres repo · Atomic settlement persistence. · `crates/storage/src/settlement_repository.rs`
- **PostgreSQL**: database · System of record for balances, orders, trades, and settlements.

## Connections

- Benchmark → API Service: HTTP load · Exercises place, match, and cancel flows end to end.
- Root Main → API Service: starts · Bootstraps the service runtime.
- App Main → API Service: starts · Alternate application entrypoint.
- API Service → API Models: serializes · Maps HTTP payloads to typed requests and responses.
- API Service → Exchange: dispatches · Hands validated requests into exchange workflows.
- Exchange → Market Actor: routes orders · Delegates market operations to the market coordinator.
- Exchange → Balance Actor: routes funds · Delegates reserve, release, and settlement handling.
- Market Actor → Matching Engine: matches · Uses the matching engine for order-book execution.
- Market Actor → Order Repo: persists orders · Records order lifecycle changes.
- Market Actor → Trade Repo: persists trades · Stores executed fills and trade records.
- Market Actor → Market Types: uses types · Shares market and order-book domain concepts.
- Balance Actor → Balance Service: controls funds · Coordinates reservation and release logic.
- Balance Actor → Balance Repo: persists balances · Stores balance changes and lookups.
- Balance Actor → Settlement Types: uses types · Shares settlement and post-trade domain concepts.
- Exchange → Storage: persists state · Coordinates durable writes across repositories.
- Storage → Balance Repo: contains · Balance persistence boundary.
- Storage → Order Repo: contains · Order persistence boundary.
- Storage → Trade Repo: contains · Trade persistence boundary.
- Storage → Settlement Repo: contains · Settlement persistence boundary.
- Balance Repo → PostgreSQL: reads/writes · Stores balances in PostgreSQL.
- Order Repo → PostgreSQL: reads/writes · Stores orders in PostgreSQL.
- Trade Repo → PostgreSQL: reads/writes · Stores trades in PostgreSQL.
- Settlement Repo → PostgreSQL: reads/writes · Stores settlements in PostgreSQL.
- Matching Engine → Market Types: interprets · Uses shared market types for matching behavior.
- Balance Service → Settlement Types: interprets · Uses settlement concepts for post-trade updates.
