Valuefy's Speed Layer: How We Achieved Sub-Second Portfolio Dashboards

Wealth managers won't wait 30 seconds for a dashboard. Here's how we built a CQRS speed layer with ClickHouse to deliver sub-second portfolio analytics.

Siddhartha Lahiri · · 5 min read

The Problem

Our platform was built on a modern stack—Node.js with Loopback ORM—which served us well initially. But as we scaled to more customers and larger portfolios, performance degraded significantly.

The root cause: portfolio calculations are inherently complex. They depend on date ranges, currency choices, and instrument selections. When we were single-tenant, the answer was straightforward—more compute, better indexes, query optimization. But we never achieved sub-second response times for our dashboards, even with these improvements.

The Caching Detour

Our first instinct was Redis caching with cache warming. It failed for two reasons:

Article content

Generated by Google Gemini

Cold start latency. Wealth management isn't high-volume retail. Each client's data is unique, and they rarely hit the same queries twice in quick succession. The Pareto principle that makes caching effective in e-commerce (80% of traffic hits 20% of data) simply doesn't apply here. Everyone experiences the first hit—and the first hit was slow.

Memory economics. Cache warming at scale became prohibitively expensive. We were on Redis Open Source, so Redis Flash wasn't available to tier less-frequently-accessed data to disk. Worse, portfolio data changes overnight—prices update, transactions settle—so the entire cache needed rebuilding daily.

Approaches We Considered (and Rejected)

Post-caching failure, we explored two directions:

  1. Rewrite to Python/NumPy. Move computation-heavy algorithms out of Node.js, leverage NumPy for in-memory calculations, and use existing Python implementations for XIRR, TWR, and MWR.
  2. Migrate to TimescaleDB. Move portfolio data to a time-series database and rebuild the retrieval logic from scratch.

Both required enormous investment—regression testing across known and unknown scenarios, large-scale data migrations for existing customers—while we were already mid-stream on engineering modernization. We couldn't afford a big-bang rewrite. A Python microservice just for calculations would have added operational complexity without solving the core problem.

The Speed Layer: CQRS-Inspired, Pragmatically Executed

Article content

Generated by Google Gemini

We landed on a read-optimized architecture inspired by CQRS, though not a purist implementation. Think of it as a "Strangler Fig" approach—wrapping new capability around the existing system rather than replacing it wholesale.

The core idea: Introduce ClickHouse as a read-only replica for portfolio data (transactions, holdings, prices). Use RabbitMQ for event-driven synchronization. Pre-compute aggregations—including complex metrics like XIRR, TWR, and MWR—on transaction events and overnight batch runs. Store these computed values in ClickHouse so dashboards fetch results, not raw data for calculation. Modify APIs to consume ClickHouse data, with a feature flag to fall back to the original source during transition.

Why ClickHouse?

  • Time-series nature. Transactions are append-heavy, rarely updated, queried by date ranges. ClickHouse is purpose-built for this pattern.
  • Aggregation performance. Portfolio valuations, NAV calculations, performance metrics, AUM rollups—all involve scanning millions of rows and aggregating. Columnar storage means the engine skips irrelevant columns entirely, resulting in orders-of-magnitude faster scans.
  • High-cardinality filtering. Filtering by client, account, security, and date combinations across billions of rows remains performant with proper partitioning.

Why RabbitMQ over Kafka?

We chose RabbitMQ for simpler operations at our scale. The trade-off is clear: Kafka's log retention would let us rebuild ClickHouse state by replaying events. But our source of truth remains MySQL—we can rebuild ClickHouse from there if needed. Kafka's operational overhead wasn't justified for our recovery model.

Phased rollout:

  1. Build for specific currencies first (limited blast radius)
  2. Extend to full multi-currency support

Handling Consistency

CQRS introduces eventual consistency—there's a lag between a write to MySQL and its reflection in ClickHouse. In wealth management, a user updating a transaction and immediately checking their dashboard could see stale data. Our approach:

  • Optimistic UI updates. The interface reflects the user's action immediately while sync happens in the background.
  • Sub-second sync for most events. RabbitMQ consumers process events fast enough that lag is rarely perceptible.
  • Transactional outbox pattern. We write the transaction and an outbox record in the same database transaction. A separate process publishes to RabbitMQ—guaranteeing no lost events even if RabbitMQ has a network blip.
  • Idempotent ingestion. RabbitMQ provides at-least-once delivery, so duplicate events are inevitable. Our consumers check before insert, and the pre-compute logic is idempotent—recalculating a portfolio replaces the previous result rather than accumulating.
  • Single source of calculation logic. The same financial algorithms power both the pre-compute batch and any fallback calculations—no parallel implementations that could drift.
  • Nightly reconciliation. Automated reconciliation between MySQL and ClickHouse catches any drift—belt and suspenders on top of the outbox pattern.
  • Graceful fallback. If RabbitMQ fails, dashboards fall back to the original MySQL path via feature flags—slower, but never stale.

Handling Corrections

Financial data changes. A transaction posted yesterday might need correction today—wrong price, wrong quantity, misclassified instrument. ClickHouse mutations (UPDATE/DELETE) are async and expensive at scale, so we avoid them entirely.

When a transaction is corrected in MySQL, corrections trigger a full recompute of affected portfolios in the overnight batch. The corrected data flows through the same pre-computation pipeline as new data, and ClickHouse receives clean, computed results. Users see updated numbers the next morning—acceptable for back-office workflows, and we avoid the operational nightmare of managing mutations at scale.

Trade-offs We Accept

This isn't a purist architecture. We consciously accept:

  • Eventual consistency. Sub-second lag in most cases, with fallback mechanisms if sync fails.
  • Overnight correction latency. Corrections reflect next morning, not instantly. Acceptable for back-office workflows.
  • Hybrid batch/event model. Some aggregations compute on events, others overnight. This creates two logic paths, but keeps the system tractable.
  • ClickHouse operational overhead. Merge trees, partitioning, and specialized expertise are now part of our stack. We mitigate this with a dedicated platform team and thorough documentation.

These are conscious choices. The alternative was months more development and a riskier migration. For our scale and use case, the trade-offs are worth it.

What's Next: Open Engineering Initiatives

The Speed Layer solved our immediate performance problem, but we're not done. The platform engineering team is actively working on:

  • Change Data Capture (CDC) pipeline. Our current "rebuild from MySQL" recovery strategy works today, but bulk-extracting millions of rows from a production OLTP database won't scale. We're evaluating Debezium to decouple ClickHouse rehydration from MySQL load.
  • Real-time sync observability. Better monitoring of RabbitMQ consumer lag and ClickHouse sync latency, with automated alerts when eventual consistency stretches beyond acceptable thresholds.
  • Expanded pre-computation coverage. Identifying additional calculation-heavy operations that can move from on-read to pre-compute, further reducing the surface area where the fallback path gets exercised.

Results

We achieved sub-second response times on large portfolio dashboards. Customers migrating to the new platform experience the difference immediately.
Article content

Generated by Google Gemini

Dedicated platform engineering. We carved out a team focused solely on core architecture, separate from feature delivery pods. This prevented the classic trap where refactoring tickets die in the feature backlog—and ensures we're building ClickHouse expertise in-house rather than creating a knowledge silo.

Conversation before code. Roughly 50:50 split between discussion and implementation. Unless the team genuinely owns the why and how, you don't get the quality and commitment needed for foundational changes.

Good enough over perfect. We chose a pragmatic approach over the theoretically optimal one. No big-bang migration, no months of invisible work before results. Ideation to production in two months.

Engineering-led ownership. Developers led this initiative with minimal oversight. When engineers own the problem end-to-end, outcomes improve dramatically.

First published on LinkedIn. Join the discussion there →