# Foxhunt HFT Trading System - Production Deployment Guide **Version**: 2.0 **Last Updated**: 2025-10-03 **Wave**: 71 - Complete Production Stack **Status**: Production Ready with Full Security Stack --- ## Table of Contents 1. [Executive Summary](#executive-summary) 2. [System Architecture Overview](#system-architecture-overview) 3. [Prerequisites](#prerequisites) 4. [Pre-Deployment Checklist](#pre-deployment-checklist) 5. [Infrastructure Setup](#infrastructure-setup) 6. [Database Migration](#database-migration) 7. [TLS Certificate Configuration](#tls-certificate-configuration) 8. [Environment Configuration](#environment-configuration) 9. [Service Deployment](#service-deployment) 10. [Post-Deployment Verification](#post-deployment-verification) 11. [Performance Tuning](#performance-tuning) 12. [Disaster Recovery](#disaster-recovery) 13. [Rollback Procedures](#rollback-procedures) 14. [Production Deployment Pitfalls](#production-deployment-pitfalls) --- ## Executive Summary This guide provides a complete, step-by-step procedure for deploying the Foxhunt HFT Trading System to production. The system consists of 4 main services with comprehensive security features designed for SOX/MiFID II compliance. ### Production Readiness Status **✅ Production Ready Components**: - API Gateway (6-layer authentication, rate limiting, audit logging) - Trading Service (order execution, portfolio management, kill switch) - Backtesting Service (strategy validation) - ML Training Service (model lifecycle management) - TLI (terminal client interface) **✅ Security Features**: - JWT authentication with revocation (Redis-backed) - MFA/TOTP implementation (RFC 6238) - RBAC with granular permissions - Mutual TLS between services - SQL injection protection (parameterized queries) - Comprehensive audit trails (SOX/MiFID II) **✅ Infrastructure**: - PostgreSQL 16+ with NOTIFY/LISTEN for hot-reload - Redis 7+ for JWT revocation and rate limiting - S3 integration for ML model storage - Docker deployment configurations ### Deployment Timeline **Total Deployment Time**: 4-6 hours (first deployment) | Phase | Duration | Status Gate | |-------|----------|-------------| | Infrastructure Setup | 60 min | PostgreSQL + Redis operational | | Database Migration | 30 min | All migrations applied | | Certificate Generation | 45 min | CA + service certs ready | | Service Deployment | 90 min | All health checks passing | | Verification | 60 min | Smoke tests complete | | Performance Tuning | 60 min | Latency baselines measured | --- ## System Architecture Overview ### Service Topology ``` ┌─────────────────────────────────────────────────────────────────────────┐ │ FOXHUNT HFT SYSTEM │ │ Production Architecture │ └─────────────────────────────────────────────────────────────────────────┘ ┌──────────────────────────────────────────────────────────────────────────┐ │ CLIENT LAYER │ ├──────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────────────────────────────────────────────────────────┐ │ │ │ TLI (Terminal Client) │ │ │ │ - Ratatui terminal UI │ │ │ │ - gRPC client to 3 services │ │ │ │ - JWT authentication │ │ │ └─────────────────────┬────────────────────────────────────────────┘ │ │ │ │ └────────────────────────┼────────────────────────────────────────────────┘ │ ┌────────────────────────┼────────────────────────────────────────────────┐ │ │ API GATEWAY LAYER │ ├────────────────────────┼────────────────────────────────────────────────┤ │ │ │ │ ┌─────────────────────▼──────────────────────────────────────────┐ │ │ │ API Gateway (0.0.0.0:50051) │ │ │ │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │ │ │ │ 6-Layer Security Stack: │ │ │ │ 1. JWT Validation (HS512, cached decoding key) │ │ │ │ 2. JWT Revocation Check (Redis, <100μs) │ │ │ │ 3. MFA/TOTP Validation (RFC 6238) │ │ │ │ 4. RBAC Authorization (cached permissions) │ │ │ │ 5. Rate Limiting (100 req/s per user) │ │ │ │ 6. Audit Logging (SOX/MiFID II compliance) │ │ │ │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │ │ │ │ Performance: <10μs authentication overhead │ │ │ └──────────┬──────────────┬──────────────┬────────────────────────┘ │ │ │ │ │ │ └─────────────┼──────────────┼──────────────┼────────────────────────────┘ │ │ │ ┌─────────────┼──────────────┼──────────────┼────────────────────────────┐ │ │ │ │ BACKEND SERVICES │ ├─────────────┼──────────────┼──────────────┼────────────────────────────┤ │ │ │ │ │ │ ┌──────────▼─────────┐ ┌─▼────────────┐ ┌▼──────────────────────┐ │ │ │ Trading Service │ │ Backtesting │ │ ML Training Service │ │ │ │ (50052) │ │ Service │ │ (50054) │ │ │ │ │ │ (50053) │ │ │ │ │ │ • Order execution │ │ │ │ • Model training │ │ │ │ • Portfolio mgmt │ │ • Strategy │ │ • S3 model storage │ │ │ │ • Risk checks │ │ validation │ │ • Version management │ │ │ │ • Kill switch │ │ • Historical │ │ • Metrics collection │ │ │ │ • Compliance │ │ replay │ │ │ │ │ └──────────┬─────────┘ └─┬────────────┘ └┬──────────────────────┘ │ │ │ │ │ │ │ └──────────────┴──────────────┘ │ │ │ │ └────────────────────────────┼───────────────────────────────────────────┘ │ ┌────────────────────────────┼───────────────────────────────────────────┐ │ │ INFRASTRUCTURE LAYER │ ├────────────────────────────┼───────────────────────────────────────────┤ │ │ │ │ ┌─────────────────────────▼────────────────────────────────────┐ │ │ │ PostgreSQL 16+ Cluster (Primary + Replica) │ │ │ │ • Streaming replication (async) │ │ │ │ • NOTIFY/LISTEN for config hot-reload │ │ │ │ • Connection pooling (20 max per service) │ │ │ │ • Schema: users, roles, permissions, mfa_config, audit │ │ │ └──────────────────────────────────────────────────────────────┘ │ │ │ │ ┌──────────────────────────────────────────────────────────────┐ │ │ │ Redis 7+ Cluster (Sentinel/Cluster Mode) │ │ │ │ • JWT revocation blacklist │ │ │ │ • Rate limiting (token bucket) │ │ │ │ • AOF persistence │ │ │ └──────────────────────────────────────────────────────────────┘ │ │ │ │ ┌──────────────────────────────────────────────────────────────┐ │ │ │ S3 (ML Model Storage) │ │ │ │ • Server-side encryption (SSE-S3) │ │ │ │ • Model versioning │ │ │ │ • Local cache (/cache/models/) │ │ │ └──────────────────────────────────────────────────────────────┘ │ │ │ └────────────────────────────────────────────────────────────────────────┘ ┌────────────────────────────────────────────────────────────────────────┐ │ MONITORING & OBSERVABILITY │ ├────────────────────────────────────────────────────────────────────────┤ │ │ │ Prometheus → Grafana → PagerDuty/Slack │ │ • Service metrics (latency, throughput, errors) │ │ • Infrastructure metrics (CPU, memory, disk, network) │ │ • Business metrics (orders/sec, fill rate, P&L) │ │ │ │ ELK Stack / Loki (Centralized Logging) │ │ • All service logs aggregated │ │ • Audit trail immutability │ │ • Security event monitoring │ │ │ └────────────────────────────────────────────────────────────────────────┘ ``` ### Network Topology ``` ┌─────────────────────────────────────────────────────────────────────┐ │ NETWORK SEGMENTATION │ └─────────────────────────────────────────────────────────────────────┘ Internet/Exchanges │ │ TLS 1.3 ▼ ┌──────────────────┐ │ Firewall/WAF │ └────────┬─────────┘ │ ▼ ┌─────────────────────────────────────────────┐ │ DMZ (Public Zone) │ │ ┌──────────────────┐ │ │ │ API Gateway │ 0.0.0.0:50051 (gRPC) │ │ │ Health: 8080 │ (HTTP health check) │ │ └────────┬─────────┘ │ └───────────┼──────────────────────────────────┘ │ mTLS ▼ ┌─────────────────────────────────────────────┐ │ Application Zone (Private) │ │ ┌──────────────┐ ┌──────────────┐ │ │ │ Trading Svc │ │ Backtesting │ │ │ │ :50052 │ │ Svc :50053 │ │ │ └──────┬───────┘ └──────┬───────┘ │ │ │ │ │ │ ┌──────▼─────────────────▼───────┐ │ │ │ ML Training Service │ │ │ │ :50054 │ │ │ └──────┬──────────────────────────┘ │ └─────────┼──────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────┐ │ Data Zone (Restricted) │ │ ┌───────────────┐ ┌──────────────┐ │ │ │ PostgreSQL │ │ Redis │ │ │ │ :5432 │ │ :6379 │ │ │ └───────────────┘ └──────────────┘ │ │ │ │ ┌──────────────────────────────────┐ │ │ │ S3 (via VPC Endpoint) │ │ │ │ s3://foxhunt-models/ │ │ │ └──────────────────────────────────┘ │ └─────────────────────────────────────────────┘ ``` --- ## Prerequisites ### Hardware Requirements #### API Gateway + Backend Services (Single Host Deployment) **Minimum**: ```yaml CPU: Intel Xeon Gold 6248R (24 cores @ 3.0GHz) OR AMD EPYC 7543 (32 cores @ 2.8GHz) RAM: 128GB DDR4-3200 ECC Storage: 2TB NVMe SSD (Samsung 980 PRO, WD Black SN850) - Write latency: <100μs (99.9th percentile) - Sequential read: >6000 MB/s Network: 25Gbps NIC (Mellanox ConnectX-6, Intel E810) - Sub-1ms latency to exchange colocations - PTP/NTP for time synchronization (±100μs accuracy) ``` **Recommended (Distributed Deployment)**: ```yaml API Gateway Host: CPU: 16 cores @ 3.5GHz+ RAM: 64GB Network: 10Gbps dedicated Trading Service Host: CPU: 32 cores @ 3.5GHz+ (CPU affinity for critical threads) RAM: 128GB Network: 25Gbps, kernel bypass (DPDK) ML Training Service Host: GPU: 2x NVIDIA A100 80GB OR 1x H100 80GB CPU: 32 cores RAM: 256GB Storage: 4TB NVMe (model storage cache) Database/Redis Host: CPU: 24 cores RAM: 256GB (large PostgreSQL shared_buffers) Storage: 4TB NVMe in RAID 10 ``` ### Operating System **Recommended**: Ubuntu 22.04 LTS (Kernel 6.2+) **OS-Level Hardening** (Critical for HFT): ```bash # Real-time kernel for low latency sudo apt install linux-image-lowlatency # Network tuning sudo sysctl -w net.core.rmem_max=134217728 sudo sysctl -w net.core.wmem_max=134217728 sudo sysctl -w net.ipv4.tcp_rmem="4096 87380 134217728" sudo sysctl -w net.ipv4.tcp_wmem="4096 65536 134217728" sudo sysctl -w net.ipv4.tcp_congestion_control=bbr # File descriptor limits echo "* soft nofile 1048576" | sudo tee -a /etc/security/limits.conf echo "* hard nofile 1048576" | sudo tee -a /etc/security/limits.conf # CPU isolation (replace 0-7 with CPU cores to isolate) # Edit /etc/default/grub: # GRUB_CMDLINE_LINUX="isolcpus=0-7 nohz_full=0-7 rcu_nocbs=0-7" sudo update-grub ``` ### Software Dependencies ```bash # Update system sudo apt update && sudo apt upgrade -y # Essential build tools sudo apt install -y \ build-essential \ cmake \ pkg-config \ libssl-dev \ libpq-dev \ protobuf-compiler \ git \ curl \ wget # PostgreSQL 16 sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list' wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - sudo apt update sudo apt install -y postgresql-16 postgresql-client-16 # Redis 7 sudo apt install -y redis-server # Docker (optional, for containerized deployment) sudo apt install -y docker.io docker-compose sudo systemctl enable --now docker sudo usermod -aG docker $USER # Rust toolchain (1.75+) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y source ~/.cargo/env rustup default stable # Verify versions cargo --version # Should be 1.75.0+ psql --version # Should be 16.x redis-server --version # Should be 7.x ``` ### Time Synchronization (CRITICAL for HFT) **⚠️ WARNING**: Skewed clocks can cause incorrect trades, regulatory violations (MiFID II), and audit failures. ```bash # Install chrony (more accurate than ntpd) sudo apt install -y chrony # Configure chrony for financial market time sync sudo tee /etc/chrony/chrony.conf < /secrets/jwt_secret.key chmod 600 /secrets/jwt_secret.key ``` - [ ] **Database Credentials** stored in secrets manager - [ ] **Redis Password** generated and stored - [ ] **S3 Access Keys** created with minimal IAM permissions - [ ] **TLS CA Certificate** ready (or use Let's Encrypt) - [ ] **Firewall Rules** defined (see Network Topology) ### Infrastructure Validation - [ ] **PostgreSQL 16+** installed and accessible - [ ] **Redis 7+** installed and accessible - [ ] **S3 Bucket** created with versioning enabled - [ ] **DNS Records** configured (if using domain names) - [ ] **NTP/PTP** synchronized (time offset < 100μs) - [ ] **Network Connectivity** tested (ping exchanges, databases) - [ ] **Disk Space** available (minimum 500GB free) ### Compliance Documentation - [ ] **SOX Compliance** checklist reviewed - [ ] **MiFID II** timestamping requirements understood - [ ] **Audit Trail** retention policy defined (7 years recommended) - [ ] **Disaster Recovery** plan documented - [ ] **Incident Response** plan reviewed --- ## Infrastructure Setup ### PostgreSQL Cluster Setup #### 1. Primary Database Configuration ```bash # Create production database and user sudo -u postgres psql < Result<()> { // ... } ``` Rebuild and redeploy services after tuning. ### TCP Kernel Tuning (Already applied in Prerequisites) Verify tuning is active: ```bash sysctl net.ipv4.tcp_congestion_control # Should be 'bbr' sysctl net.core.rmem_max # Should be 134217728 ``` --- ## Disaster Recovery ### Backup Strategy **PostgreSQL Backups**: ```bash # Daily full backup sudo -u postgres pg_dump foxhunt_production > /backups/foxhunt_$(date +%Y%m%d).sql # Compress and upload to S3 gzip /backups/foxhunt_$(date +%Y%m%d).sql aws s3 cp /backups/foxhunt_$(date +%Y%m%d).sql.gz s3://foxhunt-backups/postgres/ # Retention: Keep last 30 days locally, 7 years in S3 ``` **Redis Backups**: ```bash # Trigger RDB snapshot redis-cli -a $REDIS_PASSWORD BGSAVE # Copy RDB file to backup location sudo cp /var/lib/redis/dump.rdb /backups/redis_$(date +%Y%m%d).rdb ``` **Configuration Backups**: ```bash # Backup all .env files and certificates tar -czf /backups/config_$(date +%Y%m%d).tar.gz /etc/foxhunt/ ``` ### Restore Procedures **Restore PostgreSQL**: ```bash # Stop services sudo systemctl stop api_gateway trading_service backtesting_service ml_training_service # Drop and recreate database sudo -u postgres psql < 100μs) - Verify time sync before every trading session #### 4. Network Latency & Jitter **Pitfall**: Overlooking network topology, physical proximity to exchanges, internal network hops. **Impact**: Increased order latency, missed trading opportunities, competitive disadvantage. **Mitigation**: - Collocate infrastructure near exchanges - Use dedicated network infrastructure (no shared VLANs) - Implement kernel bypass (DPDK) for ultra-low latency - Measure and monitor network jitter continuously #### 5. Insufficient Resource Allocation **Pitfall**: Under-provisioning CPU, memory, network bandwidth, or improper OS/kernel tuning. **Impact**: High latency, service crashes, data loss. **Mitigation**: - Follow hardware requirements strictly (32+ cores, 128GB+ RAM) - Apply OS-level tuning (see Prerequisites section) - Reserve CPU cores for critical trading threads (CPU affinity) - Monitor resource usage and scale proactively #### 6. Observability Gaps **Pitfall**: Deploying without comprehensive logging, metrics, distributed tracing. **Impact**: Inability to diagnose production issues, extended downtime. **Mitigation**: - Deploy Prometheus + Grafana for metrics - Deploy ELK stack or Loki for centralized logging - Implement distributed tracing (OpenTelemetry) - Create dashboards for critical KPIs (latency, throughput, error rate) #### 7. Certificate Management Overheads **Pitfall**: Expired mTLS certificates, difficult rotation, lack of automation. **Impact**: Service outages, broken inter-service communication. **Mitigation**: - Implement automated certificate renewal (cert-manager, Let's Encrypt) - Set up alerts for expiring certificates (30 days before expiry) - Test certificate rotation in staging regularly - Document manual renewal procedures for emergencies #### 8. Database/Redis Misconfiguration **Pitfall**: Lack of HA, improper caching strategies, insufficient connection pooling. **Impact**: Service bottlenecks, data loss, downtime. **Mitigation**: - Deploy PostgreSQL streaming replication (async or sync) - Deploy Redis Sentinel or Cluster for HA - Use PgBouncer for connection pooling - Tune PostgreSQL `shared_buffers`, `work_mem` based on workload #### 9. Compliance Blind Spots **Pitfall**: Not fully addressing SOX/MiFID II requirements for audit trails, data retention, access control. **Impact**: Regulatory fines, legal liability, loss of trading license. **Mitigation**: - Enable comprehensive audit logging (all trades, logins, config changes) - Implement immutable audit trails (PostgreSQL with no DELETE) - Define data retention policies (7 years for audit trails) - Conduct regular compliance audits #### 10. Poor Rollback Strategy **Pitfall**: Inability to quickly and safely revert to a previous stable state. **Impact**: Extended downtime during deployment failures. **Mitigation**: - Keep previous binary versions (`api_gateway.bak`) - Backup database before migrations (`pg_dump`) - Test rollback procedures in staging monthly - Document rollback steps in runbook #### 11. Rust-Specific Pitfalls **Pitfall**: Not building with `--release`, missing LTO, unreviewed `unsafe` blocks. **Impact**: Slower performance, larger binaries, memory safety issues. **Mitigation**: - Always build with `cargo build --release` for production - Enable LTO in `Cargo.toml`: `lto = "fat"` - Strictly review any `unsafe` blocks (should be rare) - Run `cargo clippy` and `cargo audit` in CI/CD #### 12. JWT Secret Entropy **Pitfall**: Using weak JWT secrets (< 32 bytes) or predictable values. **Impact**: JWT forgery, unauthorized access. **Mitigation**: - Generate JWT secrets with `openssl rand -base64 64` - Rotate JWT secrets every 90 days - Never share JWT secrets across environments --- ## Appendix: Quick Reference ### Service Ports | Service | gRPC Port | Health Port | |---------|-----------|-------------| | API Gateway | 50051 | 8080 | | Trading Service | 50052 | 8081 | | Backtesting Service | 50053 | 8082 | | ML Training Service | 50054 | 8083 | ### Important File Locations | Component | Path | |-----------|------| | Binaries | `/usr/local/bin/` | | Config | `/etc/foxhunt/{service}/.env` | | Certificates | `/etc/foxhunt/certs/` | | Logs | `/var/log/foxhunt/` | | Backups | `/backups/` | | Model Cache | `/cache/models/` | ### Emergency Contacts - **Trading Operations Lead**: [PagerDuty rotation] - **Database Administrator**: [PagerDuty rotation] - **Security Team**: security@foxhunt.local - **On-Call Engineer**: [PagerDuty rotation] --- **End of Production Deployment Guide** *This document should be reviewed quarterly and updated after every major deployment.*