How prajwalgraj/cex-rust works
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: market_actor.rs Market Actor · src/lib.rs Storage · main.rs API Service · src/lib.rs Exchange
Components 18
External clients
Clients and runners that exercise the exchange over HTTP.
- Benchmark · 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.
API layer
HTTP transport and request/response boundary.
- API Service · Axum-based REST entrypoint for exchange operations.
crates/api/src/main.rs - API 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 · Coordinates validation, reservation, matching, settlement, and persistence.
crates/exchange/src/lib.rs - Market Actor · Market workflow coordinator for order entry, matching, and cancellation.
crates/exchange/src/market_actor.rs - Balance 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 · Order-book engine using price-time priority for fills and cancels.
crates/engine/src/lib.rs - Balance Service · Reserves, releases, and applies balance changes around trading.
crates/balance/src/lib.rs - Market Types · Shared market and order-book concepts used across the system.
crates/domain/src/market.rs - Settlement Types · Shared settlement and trade result concepts.
crates/domain/src/settlement.rs
Persistence
Repositories and database-backed state.
- Storage · Persistence boundary that groups order, trade, balance, and settlement storage.
crates/storage/src/lib.rs - Balance Repo · Balance persistence and lookup.
crates/storage/src/balance_repository.rs - Order Repo · Order persistence and cancellation state.
crates/storage/src/order_repository.rs - Trade Repo · Executed trade persistence.
crates/storage/src/trade_repository.rs - Settlement Repo · Atomic settlement persistence.
crates/storage/src/settlement_repository.rs - PostgreSQL · System of record for balances, orders, trades, and settlements.
Connections 25
- 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.