Build a Scalable Portfolio Optimizer with Point-in-Time Data
System DesignModel answerLast updated
Design a system that runs 30,000 portfolio optimizations in 90 minutes with strict as-of-date correctness, deterministic replay, and full audit trails.
Problem
Design a portfolio optimization engine that rebalances thousands of investment accounts every evening. The system must handle both live daily runs (applying tax-loss harvesting, asset location across account types, and alpha tilts) and large-scale historical simulations used to test new strategies across many parameter sets.
Each optimization solves a constrained mathematical program balancing expected return, risk, transaction costs, and tax consequences. Solver routines are CPU-intensive numerical algorithms (quadratic or mixed-integer programming) that respect constraints like wash-sale rules, tracking error limits, and cash availability.
Requirements
Functional:
- Execute single-date production runs and multi-period backtests spanning dozens of rebalance dates
- Guarantee point-in-time correctness: every input (security prices, dividend events, tax lot cost basis, risk factor loadings) reflects only what was known at the simulation timestamp, preventing look-ahead bias
- Provide deterministic reproducibility: identical inputs produce identical outputs, enabling exact replay for audit and debugging
- Validate results before committing: detect infeasible solutions, constraint violations, and anomalous portfolio turnover
Scale:
- Process roughly 30,000 accounts during the evening batch window of 90 minutes
- Each optimization consumes 1–2 CPU cores and completes in 3–15 seconds depending on portfolio complexity
- The system must tolerate individual worker failures without restarting the entire batch
Data characteristics:
- Tax lot data: ~15 million lot records across all accounts at any snapshot
- Risk models: factor-based representation with ~5,000 securities and ~80 factors
- Historical simulations reuse the same snapshot data across thousands of strategy variants
What to Design
- Overall architecture: how orchestration, data retrieval, compute workers, and storage layers interact
- Point-in-time data management: storing and serving bitemporal financial data efficiently to thousands of concurrent tasks
- Worker orchestration: scheduling, horizontal scaling, shared-data caching, and handling slow or failed tasks
- Lineage and audit: capturing complete provenance for compliance and deterministic replay
- Key trade-offs: exact solvers vs. heuristics, pre-materialization vs. on-demand queries, and strategies to finish within the batch window
Hints
Hint 1
Calculate the total CPU-hours required and work backward to determine how many concurrent workers you need—it's far fewer than 30,000
Hint 2
Materialize point-in-time snapshots once per batch and share them across all workers to avoid overwhelming the database
Hint 3
Use content-addressable storage for snapshots and pin solver versions to guarantee deterministic replay
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Clarify and Size the Problem
Start by translating the requirements into concrete resource needs.
Compute capacity:
- Average case: 30,000 runs × 9 seconds × 1.5 cores ≈ 405,000 core-seconds (~112 core-hours)
- Worst case: 30,000 runs × 15 seconds × 2 cores ≈ 900,000 core-seconds (~250 core-hours)
- Target completion time: 60 minutes of compute, leaving 30 minutes for validation and order routing
- At 70% utilization: 900,000 ÷ (3,600 × 0.7) ≈ 360 cores required
- This translates to roughly 12 machines with 32 cores each, running 200–250 concurrent optimization tasks
Critical insight: We need a few hundred worker slots, not 30,000. This fundamentally changes how we approach data serving—hundreds of database connections are manageable, tens of thousands are not.
Data volumes:
- Risk model in factor form: ~3 MB for loadings, small covariance matrix for factors
- Tax lots: ~15 million rows per snapshot date
- Backtests multiply snapshot count by simulation dates, but shared data (prices, risk models) remains constant per date
Clarifying questions:
- Are multiple accounts per household optimized jointly?
- What is the market-close-to-order-submission deadline?
- Does determinism require identical hardware, or just pinned solver versions?
2. High-Level Architecture
Components:
-
Orchestrator (Temporal, Airflow, or Prefect): manages the batch DAG
- Snapshot materialization → task fan-out → optimize → validate → persist → route orders
-
Bitemporal data store (PostgreSQL with temporal extensions, or Iceberg tables): stores prices, corporate actions, risk models, and tax lots with both valid-time and transaction-time dimensions
-
Snapshot materializer: executes expensive point-in-time queries once per batch, writes immutable Parquet/Arrow files to object storage (S3, GCS)
-
Worker pool (Kubernetes pods or Ray cluster): stateless containers executing:
optimize(snapshot_refs, account_data, config) → (trades, weights, diagnostics)Workers have no database access and maintain no state between runs.
-
Task queue and state tracker (Redis, DynamoDB): manages work distribution, leases, retry attempts, keyed by deterministic
task_id -
Validator service: independently verifies constraint satisfaction and flags anomalies before persistence
-
Artifact store (S3 with object lock): WORM storage for lineage manifests, input snapshots, and output trades
3. Point-in-Time Data Management
Bitemporal model:
Every fact has two time dimensions:
- Valid time: when the fact was true in the real world (e.g., a stock price on 2024-03-15)
- Transaction time: when the system learned about it (e.g., recorded on 2024-03-16 at 09:00)
A point-in-time query for simulation date t with knowledge cutoff k retrieves:
WHERE valid_from <= t < valid_to
AND transaction_from <= k < transaction_to
Setting k = t ensures backtests see only information available at that moment, preventing look-ahead bias. Corrections are handled by inserting new rows that close out previous versions—never updating in place.
Efficient serving strategy:
Never allow 30,000 tasks to query the database directly. Instead:
-
Snapshot materialization phase (runs once per batch):
- Execute bitemporal queries in bulk for each simulation date
- Write two types of snapshots:
- Shared snapshots: universe prices, risk factor loadings, corporate actions (~10–50 MB per date), stored as content-addressed Arrow files
- Account-partitioned snapshots: tax lots and holdings bucketed by household, with columnar compression
-
Storage layout:
- Partition tax lots by
(as_of_date, household_bucket) - Precompute derived fields: holding period (short-term vs. long-term), cost basis adjustments, wash-sale windows
- Use Parquet with dictionary encoding for security symbols
- Partition tax lots by
-
Backtests:
- Materialize snapshots for all rebalance dates once
- Thousands of strategy variants reuse the same snapshots, deduplicating the expensive point-in-time work
Content addressing: Snapshot IDs are content hashes: snapshot_id = SHA256(data). This makes caching trivial and guarantees immutability.
4. Worker Orchestration and Scaling
Shared-data caching:
- Each compute node downloads shared snapshots (risk models, prices) once into local NVMe or
/dev/shm - All worker processes on that node memory-map the Arrow files read-only, achieving zero-copy sharing
- Content hashes make cache invalidation deterministic: new hash = new file
Task scheduling:
- Longest-job-first heuristic: predict runtime from historical solve times, lot counts, and constraint complexity. Schedule long tasks first to minimize tail latency.
- Work-stealing queue with leases: tasks carry expiring leases with heartbeats. If a worker crashes, the lease expires and the task returns to the queue.
- Idempotent results: keyed by
task_id = hash(snapshot_ids, account_id, config, image_digest, seed). Duplicate completions are safe—last write wins with identical content.
Straggler mitigation:
- Set per-task solver timeouts at 3× predicted runtime
- Speculative re-execution: if a task exceeds its p95 runtime prediction, launch a duplicate. Determinism guarantees both produce identical results; first to finish wins.
Determinism guarantees:
- Pin container image digest and solver library version
- Configure solver in deterministic mode with fixed thread count and random seed
- Sort all inputs canonically (e.g., securities by symbol)
- Set reproducible math library flags (e.g.,
MKL_CBWR=COMPATIBLE) - Define "bit-for-bit" as "same image on same CPU architecture family" (exact microarchitecture reproducibility across vendors is impractical)
Autoscaling:
- Pre-warm the worker pool 30 minutes before market close
- Scale based on:
(queue_depth × avg_predicted_runtime) / time_remaining
5. Lineage and Reproducibility
Every run produces an immutable RunManifest containing:
- Git SHA and container image digest
- Solver name, version, configuration, and random seed
- All input
snapshot_idhashes and configuration hash - Output content hashes (trades, final weights)
- Diagnostics: solver status (optimal, feasible, infeasible), objective value, MIP gap, runtime
- Validator results
Replay: Given a run_id, fetch its manifest, retrieve the pinned snapshots, re-execute with identical parameters, and assert output hash equality. Run sampled replay checks nightly to detect non-determinism drift.
Storage: Manifests and artifacts go to object storage with WORM (write-once-read-many) enforcement for regulatory compliance. A metadata catalog indexes runs by account, batch, and snapshot for audit queries.
6. Validation and Monitoring
The validator runs independently of the solver and checks:
- Constraint violations: cash non-negativity, no short positions (if restricted), tracking error within bounds, wash-sale compliance
- Solver health: solution status, KKT residuals, dual feasibility
- Anomaly detection: turnover z-score relative to historical distribution, concentration risk
Runs failing validation are quarantined and routed to a manual review queue. Only validated runs proceed to order routing.
Monitoring dashboard:
- Real-time batch progress: completed / in-progress / failed tasks
- p50, p95, p99 solve times
- Straggler count and speculative-execution hit rate
- Validator rejection rate by failure type
7. Key Trade-offs
Exact MIP vs. heuristics for tax optimization:
- Mixed-integer programming gives provably optimal tax-loss harvesting but can take 10–30 seconds for complex portfolios
- Greedy heuristics run in <1 second but may leave tax alpha on the table
- Recommendation: Use exact MIP for production with time limits; fall back to heuristics if timeout is hit. Backtests can afford longer solve times.
Pre-materialization vs. on-demand queries:
- On-demand: simpler architecture, but 30,000 concurrent database queries create a bottleneck
- Pre-materialization: adds a preprocessing step but decouples compute workers from the database entirely
- Recommendation: Always pre-materialize. The upfront cost is small relative to solver time, and it enables horizontal scaling without database pressure.
Distributed vs. local execution:
- Cloud workers (Kubernetes, Ray) provide elasticity and fault tolerance
- Local HPC clusters may offer lower latency and cost for predictable workloads
- Recommendation: Use cloud for elasticity during batch windows; consider hybrid for large backtests that run overnight.
8. Complexity and Bottlenecks
- Compute: O(n) tasks, each O(m²) to O(m³) in portfolio size depending on solver (QP vs. MIP)
- Data retrieval: O(1) bitemporal queries per batch with pre-materialization, O(n) without
- Storage: O(n × d) for backtests over d dates; deduplication via content addressing keeps this manageable
Common mistakes:
- Querying the database from every worker (creates connection pool exhaustion)
- Forgetting transaction-time in the bitemporal model (allows restatement leakage)
- Not pinning solver versions (breaks determinism)
- Ignoring stragglers (the last 1% of tasks determine batch completion time)
This design balances strict correctness guarantees with the horizontal scalability needed to meet production SLAs.