Design a Portfolio Aggregation Service
System DesignModel answerLast updated
Build a system that combines investment data from multiple third-party sources into a unified view with clear freshness indicators and consistent calculations.
You need to architect a service that aggregates investment portfolio information from various third-party data providers. The system should display cash balances, equity positions, digital asset holdings, and calculated summary metrics to end users.
Each connected provider exposes data through its own API with distinct data structures, refresh intervals, and rate-limiting policies. Provider APIs may experience downtime, return stale information, send duplicate records, or issue retroactive corrections. Your users should clearly understand when their displayed information was last updated and should never see silently misleading aggregate numbers.
What You Should Consider
- Users typically link multiple provider accounts to get a complete financial picture
- External APIs exhibit varied reliability: some lag by minutes, others may be hours behind, and outages occur unpredictably
- Calculated metrics like total portfolio value depend on current market prices and currency conversions, which themselves change continuously
- Most traffic will be users viewing their dashboard; account connections and data syncs happen far less frequently
- You must be able to explain how any displayed number was calculated, including reproducing historical views
Questions You Should Explore
- Which displayed values need second-by-second accuracy versus eventual consistency?
- Does the system ingest individual transactions or only periodic snapshots of balances and holdings?
- What staleness threshold is acceptable for pricing data before the UI should warn users?
- What compliance requirements govern data retention, user privacy, and geographic storage?
Hints
Hint 1
Think about how to make repeated API fetches from the same provider safe even if the network duplicates requests or the provider sends the same event twice
Hint 2
Consider how you'll compute a portfolio total when some provider data is fresh but other pieces are hours old—what should the user see?
Hint 3
Design your data model to capture not just what the values are, but when they were observed and from which source
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architecture Overview
A strong design separates concerns into distinct layers: ingestion adapters that speak each provider's protocol, a normalization layer that maps heterogeneous schemas into a unified internal model, a calculation engine that produces derived metrics from consistent snapshots, and a serving layer that delivers dashboard views with explicit freshness metadata.
Core Components
Provider Adapters
Each third-party integration needs its own adapter that handles authentication, pagination, rate limits, and API-specific quirks. Adapters should emit raw events stamped with the provider's identifier, the observation timestamp, and a monotonic cursor or version token for that provider. This cursor enables idempotent processing: if the same event arrives twice, the system recognizes it and avoids double-counting.
Store raw provider responses before transformation. This audit trail allows you to reprocess historical data if you discover a normalization bug or if a provider issues a correction.
Normalization and Canonical Schema
Transform provider-specific records into a unified model with standard entities: accounts, instruments (stocks, bonds, cryptocurrencies), positions (quantity held in each instrument per account), prices, and transactions if you ingest them. Each normalized record carries its source provider, the observation time reported by the provider, and the ingestion timestamp in your system.
Use durable identifiers for instruments (ISIN, ticker + exchange, or blockchain contract addresses) so that the same asset from different providers maps to one canonical instrument.
Synchronization and Consistency
Run periodic sync jobs per provider account. Use the stored cursor to fetch only new data. If a provider doesn't support cursors, use timestamp-based pagination and tolerate overlapping windows by deduplicating on a composite key (provider + account + instrument + observation time).
Handle corrections by treating them as new records that supersede older ones. Store both the original and corrected values with version metadata. This preserves the history needed to explain what users saw at any point in time.
Snapshot and Valuation Model
To compute portfolio totals, you need a coherent point-in-time view. Create snapshots at regular intervals (every 15 minutes, hourly, or daily depending on requirements). A snapshot bundles all positions, balances, and the market prices that were current at that moment. Derived metrics—total value, asset allocation percentages, currency-converted sums—are calculated from this frozen snapshot.
When rendering the dashboard, pick the most recent complete snapshot. Display its timestamp prominently. If some providers failed to sync recently, flag affected accounts and exclude them from aggregated totals, or mark the total as "partial." Never silently aggregate fresh and hours-old data without telling the user.
Freshness and Partial Data Indicators
Expose per-account and per-metric freshness:
- Account-level freshness: "Checking account last updated 5 minutes ago."
- Aggregate-level freshness: "Portfolio total calculated at 10:15 AM using data from 3 of 4 connected accounts. Crypto account data is unavailable."
If a provider is down, show a warning icon and continue displaying the last known good values with a clear staleness label. For critical metrics, set thresholds: if data is older than 1 hour, switch to a "stale" badge; older than 4 hours, hide the metric or show it grayed out.
Rate Limits and Backoff
Track rate-limit quotas per provider. Use exponential backoff for retries. Queue sync jobs per account and per provider with prioritization: user-initiated refreshes go to the front, scheduled background syncs can wait.
If a provider repeatedly fails, move to a slower polling cadence and notify the user. Provide a manual "refresh" button that attempts an immediate sync but respects rate limits.
Security and Isolation
Store provider credentials (OAuth tokens, API keys) encrypted at rest. Use separate storage per user with strict access control. Rotate tokens proactively where provider APIs support it.
Isolate user data with tenant-scoped queries and row-level security policies. Never allow one user's query to leak data from another.
Historical Reproducibility
Keep versioned snapshots so that if a user asks "Why did my portfolio value show $X last Tuesday?" you can replay the exact calculation: which provider data was available, what prices were used, and which accounts were included. Store snapshots in a time-series database or append-only log.
For regulatory or audit purposes, retain raw provider responses and calculation logs according to compliance requirements.
Observability and Reconciliation
Instrument every adapter with metrics: sync success rate, latency, error types, records ingested. Set up alerts for prolonged provider outages or sudden drops in data volume.
Build reconciliation dashboards for internal operators: compare expected sync frequencies against actuals, detect drift between provider-reported balances and your stored values, and flag anomalies like negative positions or impossible price movements.
Example Data Flow
- Scheduled job triggers sync for User A's brokerage account.
- Adapter fetches new position data, stamped with provider's timestamp and a cursor.
- Raw JSON is stored in an audit table.
- Normalizer maps brokerage-specific fields to canonical Position records and writes them to the main database.
- Snapshot builder runs every 15 minutes, fetches latest prices, and computes portfolio total across all accounts.
- User requests dashboard. Serving layer returns the most recent snapshot, marks one account as "last updated 2 hours ago," and displays a partial-data notice because one provider is down.
Trade-offs
- Snapshot frequency vs. cost: More frequent snapshots give users fresher totals but increase compute and storage costs. Balance this with user expectations; for most retail dashboards, 15-minute snapshots suffice.
- Real-time vs. eventual consistency: Pushing every provider update immediately to the dashboard is expensive and often unnecessary. Batch updates and rely on periodic snapshots unless the product explicitly promises sub-second latency.
- Correction handling: Surfacing every retroactive correction to users can be confusing. Decide whether to rewrite history transparently or show a "corrected" label.
Common Mistakes
- Silently mixing stale and fresh data in a single aggregate number. Always annotate totals with the oldest data timestamp involved.
- Not deduplicating provider events, leading to double-counted balances after network retries or provider API bugs.
- Ignoring provider-specific quirks like delayed batch updates, missing instruments, or inconsistent schemas, which cause normalization failures.
- Overfetching by polling too aggressively, hitting rate limits and getting throttled or banned.
- Skipping audit logs, making it impossible to debug discrepancies or comply with regulations.
This design provides a robust foundation for aggregating unreliable external data into a trustworthy, transparent user experience.