Databases & State Management
Relevant source files
The following files were used as context for generating this wiki page:
OpenAlgo utilizes a multi-database architecture designed to provide isolation between live trading, sandbox testing, logging, and historical market data. The system primarily relies on SQLite for operational data and DuckDB for high-performance historical data storage. State management is handled through a combination of SQLAlchemy ORM for relational data and ZeroMQ for real-time state change propagation across processes.
The architecture emphasizes "FD (File Descriptor) hygiene" to prevent resource leaks in its single-worker production environment. This is achieved through standardized engine creation patterns that enforce specific pooling behaviors depending on the database type and environment.
Sources: CLAUDE.md:144-147, audit/FD_LEAK_AUDIT.md:16-24
Multi-Database Architecture
OpenAlgo segregates data into six distinct databases to ensure that logging or analytics activities do not interfere with live trading performance or sandbox integrity.
| Database Name | File Path | Primary Purpose |
|---|---|---|
| Main DB | openalgo.db | User authentication, API keys, and master contract data (SymToken). |
| Sandbox DB | sandbox.db | Fully isolated from live trading; stores sandbox orders, trades, and funds. |
| Logs DB | logs.db | Traffic logs, 404 tracking, and invalid API key attempts. |
| Latency DB | latency.db | Execution timing and round-trip performance metrics. |
| Health DB | health.db | System health probes and diagnostic results. |
| Historify | historify.duckdb | High-performance storage for historical market data using DuckDB. |
Sources: CLAUDE.md:144-147, upgrade/migrate_indexes.py:166-177, database/db_init_helper.py:12-25
Database Connectivity Flow
The following diagram illustrates how the application initializes and connects to these various data stores.
The application initializes engines via a centralized factory to ensure consistent configuration across the codebase.
Sources: database/engine_factory.py:10-45, database/db_init_helper.py:12-25
Engine Factory & Connection Pooling
A critical invariant in the OpenAlgo architecture is the use of NullPool for all SQLite databases. This ensures that every operation receives a fresh connection which is closed immediately upon completion, preventing cursor corruption and "Database is locked" errors in concurrent environments.
SQLite Configuration
For SQLite, the factory enforces the following settings:
- Pool Class:
NullPool(no persistent connections). - Concurrency:
check_same_thread=Falseto allow cross-thread access within the Flask/Eventlet environment. - Journal Mode: Configured via pragmas to ensure reliability.
PostgreSQL Support
While SQLite is the default, the create_db_engine function detects PostgreSQL URLs and switches to QueuePool with specific sizing for better performance in networked database environments.
| Option | Value (PostgreSQL) | Value (SQLite) |
|---|---|---|
pool_size | 10 | N/A |
max_overflow | 20 | N/A |
pool_recycle | 3600s | N/A |
poolclass | QueuePool | NullPool |
Sources: database/engine_factory.py:10-45, CLAUDE.md:131-137, audit/FD_LEAK_AUDIT.md:82-95
State Management & Invalidation
OpenAlgo handles real-time state changes and cache consistency through a "fan-in" ZeroMQ architecture. This decoupled pipeline ensures that the core application worker remains responsive while streaming ticks or handling configuration changes.
ZeroMQ Invalidation Bus
When sensitive state changes occur (such as updating broker authentication tokens), a CACHE_INVALIDATE_ALL signal is published over ZeroMQ (port 5555). The out-of-process WebSocket proxy receives this signal to disconnect stale adapter pools.
Sources: CLAUDE.md:92-105, CLAUDE.md:112-129
Historical Data Management (Historify)
The Historify module manages large-scale market data using DuckDB, chosen for its efficiency in handling analytical queries over time-series data. The system maintains a shared engine instance to manage file access safely.
Historify Initialization
The database initialization process creates a separate directory for DuckDB files and configures the engine with specific pathing logic to handle relative or absolute paths from the .env configuration.
# database/historify_db.py:27-40
def init_historify_db():
"""Initialize Historify DuckDB database."""
try:
db_path = get_historify_db_path()
db_dir = os.path.dirname(db_path)
if db_dir and not os.path.exists(db_dir):
os.makedirs(db_dir, exist_ok=True)
engine = get_historify_engine()
# Initialization logic...
Sources: database/historify_db.py:27-45, database/engine_factory.py:72-85
Performance Indexing
To support fast lookup of symbols (over 180,000 in some environments) and rapid retrieval of audit logs, the system maintains a suite of performance indexes across all databases.
Key Index Structure
| Table | Index Name | Columns | Benefit |
|---|---|---|---|
symtoken | idx_symtoken_name | name | Speeds up FNO underlying lookups. |
symtoken | idx_symtoken_exchange_name_expiry | exchange, name, expiry | Composite index for option chain queries. |
traffic_logs | idx_traffic_ip_timestamp | client_ip, timestamp | Faster security auditing for suspicious IPs. |
auth | idx_auth_user_id | user_id | Quick session resumption. |
Sources: upgrade/migrate_indexes.py:91-118, upgrade/migrate_indexes.py:186-200
Conclusion
Databases in OpenAlgo are designed for resilience and strict isolation. By enforcing NullPool for SQLite and separating operational data from high-volume historical data in DuckDB, the system maintains high performance under the constraints of a single-worker algorithmic trading engine. State synchronization across the various architectural layers is reliably managed via ZeroMQ signals and a robust SQLAlchemy-based session cleanup cycle.