Infrastructure Architecture: Bus, Storage & Telemetry
1. High-Throughput Messaging Bus (Redis Streams)
The messaging layer uses redis.asyncio with Redis Streams for event streaming, consumer group load balancing, and low-overhead IPC.
Key Capabilities
- Stream Publishing with Trimming: Appends messages using
XADDwith approximate trimming: $$\text{Stream Size} \le N_{\max} \approx 10,000$$(Default
Prevents unbounded memory growth during high-frequency market data streaming.maxlen; the feature streams use a much shorter cap,FEATURES_STREAM_MAXLEN, since the 2026-11-27 Redis memory fix.) - Consumer Groups with Auto-Creation: Initializes consumer groups dynamically with
MKSTREAMand handlesBUSYGROUPidempotently. - Acknowledgment: Tracks message delivery through
XACK. - Heartbeats & TTL: Key-level health heartbeats (e.g.
heartbeat:fxcm_worker) with configurable TTL ($T_{ttl} = 60\text{s}$). - Risk Killswitches: Scoped emergency circuit breakers (
killswitch:global,killswitch:FXCM) readable with sub-millisecond latency.
# Publishing to Redis Streams
await redis_bus.publish(
stream="stream:bars:FXCM:EURUSD:1m",
data=bar_instance,
maxlen=10000
)
2. Ultra-Fast State Persistence (DuckDB State Cache)
To guarantee sub-second cold restart and crash recovery without external database dependencies, active session summaries are persisted in an embedded DuckDB database (session_state.duckdb).
Crash Recovery & WAL Optimization
Write-Ahead Log (WAL) autocheckpointing is tuned to trigger at 16MB:
$$\text{WAL Checkpoint Threshold} = 16\text{ MB} \implies \text{Crash Recovery Time } T_{\text{recovery}} < 300\text{ ms}$$Executed via DuckDB pragmas:
PRAGMA checkpoint_threshold='16MB';
PRAGMA wal_autocheckpoint='16MB';
Lock Retry & Graceful Degradation
When multiple processes access the state cache or during container restarts, connection attempts use exponential backoff:
$$t_{\text{wait}}(k) = t_0 \cdot 2^k \quad \text{for } k \in [0, \dots, \text{max\_retries}-1]$$If the lock cannot be acquired after maximum retries, the service logs a warning and proceeds gracefully without crashing.
3. Partitioned Historical Parquet Archive
Market data and generated feature vectors are written into three independent partition trees using PyArrow and queried via DuckDB SQL.
Partition Hierarchy
| Dataset | Partition Hierarchy | Granularity |
|---|---|---|
| Bars | {base_dir}/bars/{venue}/{symbol}/{timeframe}/year={YYYY}/month={MM}/{date}.parquet |
1m and 5m candles separated by {timeframe} |
| Ticks | {base_dir}/ticks/{venue}/{symbol}/year={YYYY}/month={MM}/{date}.parquet |
Intra-candle raw price ticks |
| Features | {base_dir}/features/{venue}/{symbol}/year={YYYY}/month={MM}/{date}.parquet |
Unified feature vectors with 4-window expansion metrics |
In-Memory Ring Buffering
Records are held in thread-safe memory buffers and flushed atomically to Parquet upon reaching the threshold:
$$\text{Buffer Size } N_{\text{buffer}} = 500\text{ records}$$Flushes are also triggered on session boundary transitions or service shutdown (flush(force=True)).
DuckDB Analytical SQL Interface
# Query historical partitioned bars directly via DuckDB
SELECT date_trunc('hour', timestamp) as hr, avg(close) as avg_price
FROM read_parquet('data/bars/FXCM/EURUSD/1m/*/*/*.parquet')
GROUP BY 1 ORDER BY 1;
4. Structured JSON Logging (structlog)
All runtime components emit structured JSON lines to standard output for ingestion by modern log collectors (Datadog, Grafana Loki, CloudWatch).
Standardized Log Schema
| Field | Type | Description |
|---|---|---|
timestamp |
ISO 8601 String | UTC timestamp with microsecond resolution |
service_name |
String | Identifier of originating worker or component |
level |
String | debug, info, warning, error, critical |
event |
String | Machine-readable event identifier (e.g. saved_session) |
kwargs |
JSON Object | Contextual telemetry (symbol, venue, price, etc.) |
{"service_name": "feature_engine", "symbol": "EURUSD", "venue": "FXCM", "event": "saved_session", "window_date": "2024-05-01", "level": "info", "timestamp": "2024-05-01T14:30:00.123456Z"}
5. Redis Memory Limits (2026-11-27)
Redis runs with --maxmemory 1gb --maxmemory-policy noeviction inside a 1536 MB container: when full it refuses writes instead of being OOM-killed (it was killed 61 times on 2026-11-27, each time dropping every bot's connection), and it never evicts kill-switch or bot config keys. common/bus/redis_health.py warns above 75 % of maxmemory, or when maxmemory is missing; the host sets vm.overcommit_memory = 1 (deploy/sysctl/99-drt-redis.conf, scripts/install_host_tuning.sh). Bot settings live in Redis (bot:config:<bot>, with an audit stream); bot journals are DuckDB files under data/bot/.