InertialEvent System Architecture¶
Cross-Platform Prediction Market Trading System¶
Status: Accepted Date: 2026-01-20 Last Updated: 2026-01-21
Overview¶
This document provides a high-level overview of the InertialEvent system architecture. Detailed architectural decisions are documented in standalone ADRs:
| ADR | Title | Summary |
|---|---|---|
| ADR-004 | Core Engine in Rust | Performance-critical trading core in Rust |
| ADR-005 | Actor Model | Concurrent execution with message passing |
| ADR-006 | Lock-Free Orderbook | Sub-microsecond read latency for market data |
| ADR-007 | Saga Pattern | Distributed transaction handling for cross-platform execution |
| ADR-008 | Control Interface | Telegram + REST/gRPC for user interaction |
| ADR-009 | Credential Management | AES-256-GCM encryption with HSM option |
| ADR-010 | Deployment | AWS us-east-1 for optimal latency |
| ADR-011 | Multi-Tenancy | Hybrid isolation with pod-based enterprise tier |
Context¶
We need to build a high-performance trading system that enables: 1. Cross-platform arbitrage between Polymarket and Kalshi 2. Copy trading across both platforms 3. Remote control via Telegram with optional API access 4. Scalable monetization through multi-tenancy
The system must match or exceed the capabilities of: - Polycule: Telegram-based Polymarket trading bot with copy trading - Polymarket-Kalshi-Arbitrage Bot: Rust-based arbitrage system
Key constraints: - Latency sensitivity: arbitrage opportunities exist for milliseconds to seconds - Regulatory: Kalshi is CFTC-regulated, Polymarket operates on Polygon blockchain - Reliability: Real money at stake, requires robust error handling
Architecture Overview¶
┌─────────────────────────────────────────────────────────────────────────────┐
│ CONTROL LAYER │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Telegram Bot │ │ REST API │ │ Web Dashboard│ │
│ │ (Python) │ │ (Axum) │ │ (React) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ └─────────────────┼─────────────────┘ │
│ │ gRPC/nats │
├───────────────────────────┼─────────────────────────────────────────────────┤
│ CORE ENGINE (Rust) │
│ ┌────────────────────────┼────────────────────────┐ │
│ │ Message Bus │ │
│ └────────────────────────┼────────────────────────┘ │
│ ┌─────────────────┼─────────────────┐ │
│ │ │ │ │
│ ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐ │
│ │ Market │ │ Strategy │ │ Order │ │
│ │ Monitor │ │ Engine │ │ Executor │ │
│ │ │ │ ┌───────┐ │ │ │ │
│ │ • WebSocket │ │ │ Arb │ │ │ • Poly CLOB │ │
│ │ • Orderbook │ │ │Engine │ │ │ • Kalshi │ │
│ │ • Matching │ │ ├───────┤ │ │ • Chain Tx │ │
│ └──────┬──────┘ │ │ Copy │ │ └──────┬──────┘ │
│ │ │ │Engine │ │ │ │
│ │ │ └───────┘ │ │ │
│ │ └──────┬──────┘ │ │
│ │ │ │ │
│ ┌──────▼─────────────────▼─────────────────▼──────┐ │
│ │ Risk Manager │ │
│ │ • Circuit Breaker • Position Limits │ │
│ │ • P&L Tracking • Exposure Management │ │
│ └──────────────────────┬──────────────────────────┘ │
│ │ │
│ ┌──────────────────────▼──────────────────────────┐ │
│ │ Wallet Layer │ │
│ │ • Polygon Signer • Kalshi Auth │ │
│ │ • CTF Operations • Multi-Account │ │
│ └──────────────────────┬──────────────────────────┘ │
├─────────────────────────┼───────────────────────────────────────────────────┤
│ DATA LAYER │
│ ┌──────────────────────▼──────────────────────────┐ │
│ │ PostgreSQL │ Redis │ │
│ │ • Users/Accounts │ • Orderbook Cache │ │
│ │ • Trade History │ • Session State │ │
│ │ • Strategy Config │ • Pub/Sub Events │ │
│ └─────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
Key Architectural Decisions¶
The following decisions form the foundation of the InertialEvent architecture. Each is documented in a standalone ADR with full context, alternatives considered, and consequences.
Core Technology (ADR-004)¶
Decision: Implement the trading core in Rust for sub-millisecond latency without GC pauses.
Concurrency Model (ADR-005)¶
Decision: Use actor-based concurrency with message passing via tokio channels. Each component (Market Monitor, Strategy Engine, Order Executor) runs as an isolated actor.
Orderbook Cache (ADR-006)¶
Decision: Lock-free atomic orderbook storage using arc_swap::ArcSwap for sub-microsecond reads.
Lock-Free vs Execution Atomicity
"Lock-free" refers to memory access safety, NOT cross-market execution atomicity. See ADR-007 for execution guarantees.
Execution Safety (ADR-007)¶
Decision: Saga pattern state machine for distributed transactions to handle "legging risk" when executing across Polymarket and Kalshi.
enum ArbState {
Pending,
Leg1Initiated(OrderId),
Leg1Filled(FillDetails),
Leg2Initiated(OrderId, FillDetails),
Completed,
Failed(Reason),
Compensating(HedgeStrategy),
Compensated,
}
Control Interface (ADR-008)¶
Decision: Telegram as primary mobile interface with REST/gRPC API for programmatic access.
Credential Security (ADR-009)¶
Decision: AES-256-GCM encryption with per-user key derivation and optional HSM for production.
Deployment (ADR-010)¶
Decision: AWS us-east-1 for optimal latency to both Kalshi (NYC) and Polygon RPC nodes.
Multi-Tenancy (ADR-011)¶
Decision: Hybrid model with shared infrastructure for basic users (rate-limited) and isolated pods for enterprise users.
System Components¶
Component: Market Monitor¶
Responsibility: Real-time market data aggregation
| Source | Protocol | Reconnect Strategy |
|---|---|---|
| Polymarket CLOB | WebSocket | Exponential backoff, max 30s |
| Polymarket RTDS | WebSocket | Immediate reconnect |
| Kalshi | WebSocket | Exponential backoff |
| Polygon RPC | HTTP/WS | Failover to backup RPC |
Key Features: - Maintain synchronized orderbook state - Cross-platform market matching - Publish orderbook updates to strategy engines
Component: Arbitrage Engine¶
Responsibility: Detect and execute arbitrage opportunities
Detection Loop:
loop {
// Batch process all matched markets
let opportunities = detector.scan_all_markets(&orderbook_cache);
for opp in opportunities.filter(|o| o.profit > min_threshold) {
// Validate still valid
if opp.is_stale() { continue; }
// Check risk limits
if !risk_manager.can_trade(&opp) { continue; }
// Execute concurrently on both platforms
executor.execute_arb(opp).await;
}
// Yield to allow orderbook updates
tokio::task::yield_now().await;
}
Component: Copy Engine¶
Responsibility: Monitor target wallets and replicate trades
Event Sources: - Polymarket: Polygon blockchain events + CLOB API - Kalshi: Trade feed (where available)
Processing Pipeline:
Component: Execution Engine¶
Responsibility: Submit and manage orders across platforms
Polymarket Execution:
pub async fn execute_polymarket(&self, order: &Order) -> Result<OrderId> {
// 1. Prepare order with CLOB client
let signed_order = self.clob_client.create_order(
order.token_id,
order.price,
order.size,
order.side,
).await?;
// 2. Submit via CLOB API (gasless via relayer)
let order_id = self.clob_client.post_order(signed_order).await?;
Ok(order_id)
}
Kalshi Execution:
pub async fn execute_kalshi(&self, order: &Order) -> Result<OrderId> {
// 1. Sign request with RSA-PSS
let request = self.kalshi_client.create_order_request(
order.market_ticker,
order.side,
order.yes_price, // cents
order.count,
)?;
// 2. Submit via REST API
let response = self.kalshi_client.create_order(request).await?;
Ok(response.order.order_id)
}
Technology Stack¶
| Layer | Technology | Rationale |
|---|---|---|
| Core Engine | Rust 1.75+ | Performance, safety |
| Async Runtime | Tokio | Industry standard |
| WebSocket | tokio-tungstenite | Low overhead |
| HTTP Client | reqwest | Ergonomic, async |
| Ethereum | ethers-rs | Mature, maintained |
| gRPC | tonic | Protocol buffers |
| Database | PostgreSQL | ACID, JSON support |
| Cache | Redis | Fast pub/sub |
| Telegram | python-telegram-bot | Feature complete |
| API | Axum | Fast, ergonomic |
| Monitoring | Prometheus + Grafana | Industry standard |
| Tracing | OpenTelemetry | Distributed tracing |
Risk Assessment¶
| Risk | Probability | Impact | Mitigation |
|---|---|---|---|
| API rate limiting | High | Medium | Implement backoff, request batching |
| WebSocket disconnection | Medium | High | Auto-reconnect, state recovery |
| Partial fill exposure | Medium | High | Automatic rebalancing, circuit breaker |
| Platform API changes | Medium | Medium | Version monitoring, feature flags |
| Legging Risk | High | Critical | ADR-001.4 Saga Pattern / Compensating logic |
| Regulatory changes | Low | High | Modular platform support |
Verification Plan¶
Automated Testing¶
| Test Type | Scope | Command |
|---|---|---|
| Unit Tests | Core logic | cargo test |
| Integration | Platform clients | cargo test --features integration |
| Load Tests | Performance | cargo bench |
| Recovery Tests | Saga Logic | cargo test --features chaos_monkey |
Manual Verification¶
- Paper Trading
- Configure
DRY_RUN=1 - Monitor detected opportunities
-
Verify no real orders submitted
-
Demo Environment
- Use Kalshi demo environment
- Use Polygon testnet for Polymarket
-
Execute end-to-end flows
-
Production Canary
- Small position limits
- Single market pair
- 24-hour monitoring
Consequences¶
Positive¶
- Sub-millisecond arbitrage detection
- Scalable multi-tenant architecture
- Mobile-first control via Telegram
- Platform for monetization
- Robustness against partial execution failures (Saga)
Negative¶
- Rust learning curve for team
- Dual-platform maintenance burden
- Credential security complexity
- Execution logic more complex due to state machine
Neutral¶
- Need to maintain market mapping database
- Ongoing monitoring of platform API changes