Overview
The Database Storage (DBStorage) service is responsible for persisting trading data and managing user records in PostgreSQL. It consumes messages from Redis Streams, stores closed orders in the database, handles user creation/updates, and serves queries for historical order data. Location:apps/DBstorage/src/index.ts:1
Database: PostgreSQL with Prisma ORM
Message Source: Redis Streams (dbStorageStream)
Key Features
- Closed Order Persistence: Stores completed trades with P/L calculations
- User Management: Creates and updates user records from Engine
- Historical Queries: Retrieves closed order history for users
- Data Integrity: Ensures orders match Prisma schema constraints
- Idempotent Operations: Handles duplicate messages gracefully
- Async Processing: Consumes Redis Streams continuously
Architecture
Service Initialization
The DBStorage service uses a single consumer that processes messages sequentially to maintain data consistency and avoid race conditions in the database.
Core Functions
Database Storage Function
Main message router that handles different operation types:Create Close Order
Stores a closed trading position with profit/loss data:Get Close Orders
Retrieves historical closed orders for a user:Create User
Handles user creation and updates with conflict resolution:Database Schema
Orders Table
Users Table
Data Flow
Configuration
Environment Variables
Redis connection URL for streams
PostgreSQL connection string for Prisma
Redis Streams
Stream for incoming storage requests
Stream for outgoing query responses
Deployment
DBStorage must wait for database migrations to complete before starting to ensure the schema is up to date.
Error Handling
Validation Errors
Database Errors
Performance Considerations
Indexing Strategy
Query Optimization
Monitoring
Performance Metrics
Related Services
- Trading Engine - Sends closed order data
- Backend API - Queries historical orders
- Batch Upload - Stores raw trade data