A high-performance centralized trading exchange built in Rust.
This exchange system consists of four main services that communicate via Redis:
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ API │ │ ENGINE │ │ WEBSOCKET │ │ DATABASE │
│ Service │ │ Service │ │ Service │ │ Service │
│ │ │ │ │ │ │ │
│ - REST API │ │ - Order │ │ - Real-time │ │ - Trade │
│ - User │ │ Matching │ │ Updates │ │ Storage │
│ Requests │ │ - Balance │ │ - Market │ │ - Order │
│ - Market │ │ Management│ │ Data │ │ History │
│ Data │ │ │ │ │ │ - Analytics │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
│ │
└───────────────────┼───────────────────┼───────────────────┘
│ │
┌─────────────┐ ┌─────────────┐
│ REDIS │ │ POSTGRESQL │
│ │ │ │
│ - Message │ │ -TimescaleDB│
│ Queue │ │ -Trade Data │
│ - PubSub │ │ -Historical │
│ │ │ Records │
└─────────────┘ └─────────────┘
- Technology: Actix Web (Rust)
- Purpose: Handles HTTP REST API requests
- Features:
- Order placement and cancellation
- Market depth queries
- Open orders retrieval
- Recent Trade retrieval
Endpoints:
POST /api/v1/order/- Place orderDELETE /api/v1/order/- Cancel orderGET /api/v1/order/open- Get open ordersGET /api/v1/depth/- Get market depthGET /api/v1/klines/- Get candlestick dataGET /api/v1/trades/- Get recent tradesGET /api/v1/tickers/- Get ticker data
- Technology: Tokio (Rust)
- Purpose: Core trading engine and order matching
- Features:
- Order book management
- Order matching algorithm
- Balance validation and locking
- Trade execution
- Market data generation
Key Components:
- Orderbook: BTreeMap-based order matching.
- Balance Manager: Handles user fund locking/unlocking
- Trade Engine: Executes matched orders and updates balances
- Technology: Tokio WebSockets (Rust)
- Purpose: Real-time market data streaming
- Features:
- Live order book updates
- Trade stream
- Ticker updates
- Technology: PostgreSQL with TimescaleDB (Rust + sqlx)
- Purpose: Persistent storage and historical data management
- Features:
- Trade data persistence
- Order history tracking
- Time-series data optimization
- OHLCV candlestick generation
Database Schema:
- Trades Table: Stores all executed trades with precise decimal values
- Orders Table: Tracks order states and execution history
- TimescaleDB Hypertables: Optimized for time-series queries
- Indexes: Efficient querying by market, timestamp, and order ID
- API receives order request via HTTP
- API validates request and sends to Redis queue
- Engine processes order from queue
- Engine validates balance and locks funds
- Engine matches order against orderbook
- Engine executes trades and updates balances
- Engine sends trade/order data to Database via Redis queue
- Database persists trade and order updates to PostgreSQL
- Engine sends response back to API via Redis pubsub
- Engine publishes market updates to WebSocket service
- API returns response to client
- WebSocket broadcasts updates to connected clients
- Engine creates trade records after order matching
- Engine sends trade data to Redis
db_processorqueue - Database service consumes messages from queue
- Database stores trades with DECIMAL precision in TimescaleDB
- Database updates order execution status with UPSERT logic
- API queries database for historical data (trades, klines)
- TimescaleDB provides optimized time-series aggregations
- Engine generates market data (trades, depth changes)
- Engine publishes to Redis channels
- WebSocket service subscribes to channels
- WebSocket broadcasts to connected clients
- Language: Rust
- Web Framework: Actix Web
- Async Runtime: Tokio
- Message Broker: Redis
- Database: PostgreSQL with TimescaleDB extension
- Database Driver: sqlx with async support
- Data Structures: BTreeMap for orderbooks
- Precision: rust_decimal for financial calculations
- Serialization: Serde JSON
- Rust 1.70+
- Redis Server
- PostgreSQL with TimescaleDB extension
- Environment variables:
REDIS_URL=redis://localhost:6379DATABASE_URL=postgresql://username:password@localhost:5432/exchange_db
-
Start Redis:
redis-server
-
Start PostgreSQL with TimescaleDB:
# Install TimescaleDB extension sudo apt install timescaledb-postgresql-14 # Or using Docker docker run -d --name timescaledb -p 5432:5432 -e POSTGRES_PASSWORD=password timescale/timescaledb:latest-pg14
-
Setup Database:
cd db # Run migration to create tables sqlx migrate run
-
Start Database Service:
cd db cargo run --release -
Start Engine Service:
cd engine cargo run --release -
Start API Service:
cd api cargo run --release -
Start WebSocket Service:
cd ws cargo run --release
Place an order:
# Place an order
curl -X POST http://localhost:8000/api/v1/order/ \
-H "Content-Type: application/json" \
-d '{
"market": "TATA_INR",
"price": "100",
"quantity": "10",
"side": "buy",
"user_id": "1"
}'
# Get recent trades
curl "http://localhost:8000/api/v1/trades?symbol=TATA_INR&limit=10"
# Get candlestick data
curl "http://localhost:8000/api/v1/klines?market=TATA_INR&interval=1h&start_time=2024-01-01T00:00:00Z"- Independent Scaling: Services can be scaled independently
- Fault Tolerance: Service failures don't cascade
- Technology Flexibility: Each service can use optimal technology
- Order Matching: Sub-millisecond latency
- API Response: < 10ms typical
- WebSocket Updates: Real-time (< 1ms)
- Hypertables: Automatic partitioning by time for trades and orders
- Time-bucket aggregations: Efficient OHLCV candlestick generation
- Authentication and authorization
- Rate limiting
- Market making algorithms
- Advanced order types (stop-loss, etc.)
- Multi-asset support
- Compliance and reporting features
- Database read replicas for analytics
- Data archival and backup strategies