Design a Governed Market Data Catalog and Point-in-Time Access Layer
Medium · Software Engineering Fundamentals · Data Engineer · Technical Screen
Prompt
An investment research firm ingests hundreds of daily market, fundamental, and reference feeds covering thousands of traded securities from multiple external data providers. Quantitative researchers consume historical series from Python, while portfolio managers pull current and historical metrics through SQL queries and spreadsheet formulas.
Design a unified self-service catalog, governance, and data-serving middleware layer that satisfies four core capabilities:
- Self-Service Search & Cataloging: Internal consumers can look up security symbols, financial fields, and upstream provider feeds from one central catalog.
- Provenance & Backtest Reproducibility: Every stored value traces back to its originating provider, arrival timestamp, and transformation jobs so historical simulations remain reproducible over time.
- Contractual Entitlements: Provider agreements restrict who may read specific feeds and how those feeds may be used; the platform must enforce role- and license-based access controls across every client interface.
- Feed Health & Outlier Alerting: Operators and subscribers receive automated notifications whenever an expected feed is late, incomplete, or diverges sharply from its rolling historical moving average.
Scope & Expectations
- Propose a metadata catalog schema covering datasets, field definitions, identifier mappings, license policies, and pipeline run lineage.
- Sketch the high-level service and storage architecture alongside the end-to-end flow from upstream provider ingestion to Python, SQL, and spreadsheet clients.
- Detail how bitemporal / point-in-time storage prevents look-ahead bias during historical backtests without overwriting vendor revisions.
- Explain how entitlements and calendar-aware freshness, completeness, and moving-average outlier checks operate across hundreds of daily feeds.
Step-by-step walkthrough
Clarify users, requirements, and data scale
Three internal personas shape every design choice in a market data platform:
- Quantitative researchers (Python): run historical backtests (simulations of how a trading strategy would have performed in the past) and need reproducible, point-in-time history with zero future data leakage.
- Portfolio managers (Excel and SQL): pull current metrics and recent history into spreadsheets and dashboards, needing clear freshness indicators so they never act on stale feeds.
- Data engineers: onboard feeds from external providers such as S&P, LSEG, and Morningstar, enforce vendor contracts, and answer "where did this number come from?" in minutes.
Priority order for non-functional requirements: 1) point-in-time correctness and reproducibility, 2) strict license compliance with an audit log, and 3) interactive query latency (sub-second to a few seconds). Because the feeds are daily (plus periodic vendor restatements), this is a batch-ingestion and analytical-serving layer, not an ultra-low-latency tick-streaming engine.
Back-of-the-envelope storage sizing under generous upper-bound assumptions:
300 daily feeds * 5,000 symbols * 20 metrics = 30,000,000 (3 * 10^7) values / trading day * 250 trading days / year = 7.5 * 10^9 values / year * 16 to 32 bytes per row (keys + timestamps) = 120 to 240 GB / year raw (~40 GB compressed) Metadata catalog: 300 datasets * ~50 fields = ~15,000 field definitions (< 50 MB)Roughly
40–240 GB/yearfits comfortably in a single columnar data warehouse or Parquet/Iceberg lakehouse, and the metadata catalog fits in memory inside PostgreSQL. Raw data volume is not the bottleneck—time travel, entitlements, and automated quality governance are.Design the metadata catalog schema
A metadata catalog is a central database storing structured descriptions of every dataset, field, license, identifier mapping, and pipeline run. Store the authoritative tables in PostgreSQL and sync text fields to a search index (Postgres full-text search or OpenSearch) for instant keyword lookup across tickers, metrics, and vendors:
vendor (vendor_id, name, contract_ref) license (license_id, vendor_id, usage_modes: display | non_display | redistribution, allowed_groups, allowed_service_accounts, region, expires_on) dataset (dataset_id, vendor_id, license_id, name, description, owner_team, schedule_cron, exchange_calendar, grace_minutes, schema_version) field (dataset_id, field_name, vendor_field_code, unit, currency, data_type, valid_min, valid_max, is_point_in_time_safe: bool) instrument (instrument_id, asset_class, listed_date, delisted_date) symbology (instrument_id, id_type: ticker | ISIN | FIGI | vendor_id, symbol, valid_from, valid_to) ingestion_run (run_id, dataset_id, business_date, raw_uri, sha256, row_count, ingested_at, status, connector_git_sha) transform_run (run_id, job_name, code_git_sha, input_run_ids, finished_at, status) quality_result (run_id, check_name, severity: BLOCK | WARN, observed_val, threshold, passed)Two modeling rules prevent classic financial-data bugs: - Never key data by ticker—use a permanent internal
instrument_id: Tickers change and get reused (for example, Meta Platforms changed its ticker fromFBtoMETAin June 2022, and delisted tickers are later reassigned to new companies). The datedsymbologytable resolves"FB on 2021-05-10"and"META on 2023-05-10"to the exact sameinstrument_id. - Make lineage machine-written data, not wiki pages: Pipelines writeingestion_runandtransform_runautomatically, and every stored data row carriesrun_id, tracing straight back to the exact vendor file checksum and parser commit SHA.High-level architecture: one gateway in front of storage
Vendor APIs / SFTP (S&P, LSEG, Morningstar) | [Scheduled Connectors] | Immutable Raw Zone (S3 / GCS: raw bytes + SHA-256) | [Normalizer + Staging Quality Gate] ---------> [Alerting & Ops Notifications] (Write -> Audit -> Publish only if valid) | | v Curated Bitemporal Store (Columnar Warehouse) [Catalog Service] | (Postgres + Search) v ^ ^ [Data Access Service] <------------------------+ | | | \------> [Entitlement Service + Audit] | v v v | Python SDK SQL Proxy Excel Add-in (REST) -------------------+The single most important architectural boundary is that Python, SQL, and Excel all route through the Data Access Service (users hold zero direct credentials to S3 or warehouse tables). That guarantees entitlements, symbology mapping, point-in-time filtering, and audit logging behave identically regardless of tool.
End-to-end data flow from vendor API to analyst
Data moves through a six-step Write-Audit-Publish (WAP) pipeline:
- Ingest raw bytes: On the dataset's exchange schedule, the connector downloads the vendor feed, saves the untouched file to immutable object storage (
s3://market-raw/<vendor>/<dataset>/<date>/<run_id>), and writes aningestion_runrow. Keeping raw files lets engineers replay parser bug fixes years later. - Stage & normalize: The normalizer maps vendor field codes to canonical
field_names, resolves vendor symbols toinstrument_ids usingsymbologyvalid on that date, standardizes units/currencies, and writes rows into an unexposed staging partition. - Audit (Quality Gate): Automated schema, completeness, range, and outlier checks run against staging and log
quality_resultrows. - Publish or quarantine: If all
BLOCK-severity checks pass, the partition is atomically appended to the curated bitemporal store and catalog status updates toFRESH. If a blocking check fails, staging is quarantined, yesterday's clean data remains live with statusSTALE, and owners are paged. - Discover: An analyst searches
"LSEG EPS"in Python or the web catalog; the Catalog Service returns field definitions, freshness, quality history, and license status. - Query with governance: A
get()call, SQL query, or Excel formula hits the Data Access Service, which verifies SSO identity and license rights, executes the point-in-time query, logs an audit record, and returns values alongsiderun_idlineage and quality flags.
- Ingest raw bytes: On the dataset's exchange schedule, the connector downloads the vendor feed, saves the untouched file to immutable object storage (
Eliminate look-ahead bias with bitemporal versioning
Look-ahead bias occurs when a historical simulation accidentally uses data before it was actually available in the real world—for instance, trading on Q2 earnings on June 30 even though Q2 earnings were not announced until August 1, or using a September accounting restatement during an August trade.
Prevent look-ahead bias with a bitemporal data model that records two distinct timestamps on every row in an append-only version table: -
value_date(valid time): the economic period or market date the metric describes (e.g., fiscal Q2 ending2024-06-30). -known_from(knowledge time): the exact UTC timestamp our platform first knew this value (max(vendor_published_at, our_ingested_at)).A vendor correction never overwrites an existing row; it appends a new row with a newer
known_from. An SCD Type 2 (Slowly Changing Dimension) view or materialized projection exposesknown_to(theknown_fromof the next version, orNULLif still current) for fast interval filtering:instrument_id field value_date value known_from known_to note --------------------------------------------------------------------------------------------------- 1042 (AAPL) eps 2024-06-30 1.20 2024-08-01 18:42Z 2024-09-15 07:00Z initial release 1042 (AAPL) eps 2024-06-30 1.12 2024-09-15 07:00Z NULL vendor revision Backtest decision at 2024-07-15 16:00Z -> None (Q2 EPS not announced yet!) Backtest decision at 2024-08-20 16:00Z -> 1.20 (initial release was known; revision was not) Backtest decision at 2024-10-01 16:00Z -> 1.12 (revision is now in effect)def value_as_known_at(versions: list, decision_time: str): """Return the latest version with known_from <= decision_time, or None if unreleased.""" latest_pair = None for known_from, value in versions: if known_from <= decision_time: if latest_pair is None or known_from > latest_pair[0]: latest_pair = (known_from, value) return None if latest_pair is None else latest_pair[1] eps_versions = [ ("2024-08-01T18:42:00Z", 1.20), ("2024-09-15T07:00:00Z", 1.12), ] assert value_as_known_at(eps_versions, "2024-07-15T16:00:00Z") is None assert value_as_known_at(eps_versions, "2024-08-20T16:00:00Z") == 1.20 assert value_as_known_at(eps_versions, "2024-10-01T16:00:00Z") == 1.12In SQL, the interval projection filters cleanly without window functions at query time:
SELECT instrument_id, value FROM curated_fundamentals WHERE field_name = 'eps' AND value_date = DATE '2024-06-30' AND known_from <= TIMESTAMP '2024-08-20 16:00:00' AND (known_to IS NULL OR TIMESTAMP '2024-08-20 16:00:00' < known_to);Apply the same point-in-time discipline to index constituents and delisted stocks (
listed_date/delisted_date): building a backtest universe from today's S&P 500 silently drops companies that went bankrupt, creating survivorship bias.Enforce entitlements and vendor licensing
Market data contracts restrict both who and how data is consumed: -
display: human viewing in Excel or a dashboard. -non_display: automated consumption by backtests, signals, or ML models (often priced separately by institutional market-data providers). -redistribution: copying vendor values into shared downstream tables or external reports.Every request follows a default-deny check inside the Entitlement Service: 1. Caller authenticates via corporate Single Sign-On (SSO) token (for humans in Excel/Jupyter) or dedicated service identity (for scheduled jobs—never shared passwords). 2. Data Access Service calls
check_access(principal, usage_mode, dataset_id, fields). 3. Disallowed columns are stripped or rejected with an actionable error naming the license ID and dataset owner, and an immutable audit log entry(timestamp, principal, usage_mode, dataset_id, fields, row_count)is written for vendor compliance audits. 4. Through catalog lineage, any derived dataset automatically inherits the most restrictive license of its upstream inputs unless Legal explicitly marks it exempted derived data.Monitor freshness, completeness, and moving-average outliers
Reliability rules live as metadata on each
datasetandfieldso onboarding a feed automatically enables monitoring:- Staleness (calendar-aware): Evaluate
schedule_cron + grace_minutesagainst the feed'sexchange_calendar. If US equities close data is due at18:30 ETwith30 mingrace and no validingestion_runexists by19:00 ETon a NYSE trading day, flip status toSTALEand alert subscribers (without false alarms on market holidays). - Missing data: Compare today's
row_countagainst the 20-day trailing median (e.g.,4,210symbols vs.5,000median =84.2% < 95%threshold) and diff against the active universe to list exact missinginstrument_ids. - Outlier detection against a historical moving average (plus robust MAD): Always test split-adjusted daily returns (
(P_t - P_{t-1}) / P_{t-1}) rather than raw price levels (raw prices drift over time, and a 2-for-1 stock split looks like a-50%crash unless corporate actions are applied first!).- Baseline moving-average z-score: If the 60-day rolling mean return is
0.05%with rolling standard deviation1.20%, a-9.00%print givesz = (-9.00 - 0.05) / 1.20 = -7.54, triggering an outlier alert (|z| > 5). - Why pair with a robust MAD check: A single earlier bad spike in the window inflates the rolling standard deviation and blinds ordinary z-scores! Suppose 10 historical returns (%) are
[0.4, -0.3, 0.1, 0.0, 0.2, -0.1, 0.3, -0.2, 0.1, 25.0]: the mean is2.55%and sample std is7.89%, so a fresh-8.0%bad print scores a harmless-lookingz = -1.34. Using the median (0.1%) and MAD (Median Absolute Deviation) (median(|x - 0.1|) = 0.2%, scaled by1.4826to match normal std) scores(-8.0 - 0.1) / (1.4826 * 0.2) = -27.32, catching the anomaly immediately:
- Baseline moving-average z-score: If the 60-day rolling mean return is
import statistics def standard_z(history: list, today: float) -> float: """Z-score relative to historical moving average and sample standard deviation.""" mean = statistics.mean(history) stdev = statistics.stdev(history) return 0.0 if stdev == 0 else (today - mean) / stdev def robust_mad_z(history: list, today: float) -> float: """Outlier score using median and Median Absolute Deviation (immune to prior spikes).""" med = statistics.median(history) mad = statistics.median([abs(x - med) for x in history]) if mad == 0: return 0.0 if today == med else float("inf") return (today - med) / (1.4826 * mad) polluted_window = [0.4, -0.3, 0.1, 0.0, 0.2, -0.1, 0.3, -0.2, 0.1, 25.0] assert abs(standard_z(polluted_window, -8.0)) < 2.0 # -1.34: masked by the old +25% spike! assert abs(robust_mad_z(polluted_window, -8.0)) > 25.0 # -27.32: clearly flagged!Crucially, statistical outliers warn and tag (
SUSPECT) rather than silently deleting rows, because a-9%move on an earnings miss can be genuine market action—cross-checking a second vendor breaks ties automatically.- Staleness (calendar-aware): Evaluate
Python, SQL, and Excel interfaces and key trade-offs
- Python SDK for quants (
usage_mode="non_display"): Exposes two complementary time controls so backtests are both bias-free and bit-for-bit reproducible:
# Conceptual SDK call: # df = md.get( # symbols=["AAPL"], # fields=["eps"], # start="2024-01-01", # end="2024-12-31", # point_in_time=True, # date t sees only versions with known_from <= t # as_of="2025-01-02T00:00:00Z", # caps visibility at min(t, as_of) for exact reruns # )Why both parameters matter: `point_in_time=True` prevents look-ahead bias across dates (`2024-08-20` gets `1.20`; `2024-10-01` gets `1.12`), while `as_of` freezes the knowledge cutoff (`known_from <= min(t, as_of)`) so rerunning a 2025 backtest in 2026 ignores any vendor backfills ingested after `2025-01-02`.- Excel add-in & SQL gateway for PMs (
usage_mode="display"): Worksheet formulas like=MD("AAPL", "eps", "2024-08-20")batch-call the same REST gateway using the PM's SSO token, caching within the session and rendering explicit[STALE]or[SUSPECT]indicators beside cell values.
Core design trade-offs: - Append-only bitemporal rows vs. in-place updates: uses slightly more storage and adds interval filters, in exchange for zero look-ahead bias and 100% reproducible backtests. - Central Data Access Service vs. direct warehouse access: introduces one network hop that must be highly available, in exchange for unified licensing, symbology, and audit compliance across Python, SQL, and Excel. - Strict schema blocks vs. statistical flags: blocks structurally broken feeds from corrupting storage while letting genuine high-volatility market moves flow through with
SUSPECTmetadata.- Python SDK for quants (
Intuition & how it works
Think of a market data platform like a research library with a strict card catalog, reading-room passes, and time-stamped editions. Instead of letting researchers wander into the loading dock to grab raw boxes from external providers like S&P, LSEG, or Morningstar, every delivery is logged upon arrival, shelved as a dated edition without throwing away earlier printings, and checked out through a single front desk that verifies the reader's pass and records every loan.
The naive approach—dumping daily vendor CSVs into shared SQL tables keyed by ticker symbol and overwriting rows whenever a vendor sends a correction—breaks down in three ways. First, overwriting past rows causes look-ahead bias (feeding a historical simulation numbers that were not actually announced or revised until weeks later) and destroys reproducibility. Second, keying by ticker corrupts history whenever companies rename or reuse symbols (like FB becoming META). Third, letting Python scripts and Excel spreadsheets query raw tables directly makes vendor license restrictions and audit trails impossible to enforce.
Trace one concrete data point from ingestion to query:
1. Ingest & lineage: On 2024-08-01 18:42Z, LSEG delivers Apple's (instrument_id = 1042) Q2 eps = 1.20 for period value_date = 2024-06-30. We archive the raw file checksum under run_id = R101 and append (1042, "eps", 2024-06-30, 1.20, known_from=2024-08-01 18:42Z, run_id=R101).
2. Vendor correction: On 2024-09-15 07:00Z, LSEG revises Q2 eps to 1.12 (run_id = R145). Instead of overwriting 1.20, we append a second version with known_from = 2024-09-15 07:00Z (closing the first version's known_to interval at 2024-09-15 07:00Z).
3. Governed point-in-time query: When a quant backtest asks for AAPL EPS across 2024 through the central Data Access Service, the service checks the quant's non_display license, maps "AAPL" -> 1042, logs the audit record, and returns None on 2024-07-15 (unreleased), 1.20 on 2024-08-20, and 1.12 on 2024-10-01.
Key points
- Automated metadata catalog as the single source of truth: store datasets, fields, vendor licenses, permanent
instrument_ids with time-ranged symbology (the mapping between tickers/ISINs/FIGIs and internal instrument IDs over validity dates), and machine-writteningestion_run/transform_runlineage (the chain of raw files and code versions that produced each value). - Append-only bitemporal storage eliminates look-ahead bias: a bitemporal table tracks both
value_date(what period a number describes) andknown_from/known_to(when our system knew that version), while keeping delisted instruments avoids survivorship bias (testing only on companies that survived to the present). - One central Data Access Service for Python, SQL, and Excel: centralizing every query behind one gateway guarantees identical point-in-time logic, symbol resolution, freshness badges, and license enforcement without handing raw warehouse credentials to end users.
- Usage-aware entitlements and audit logging: entitlements (access rules tied to vendor contracts) check principal identity, dataset/field, and usage mode (
displayfor Excel humans vs.non_displayfor automated quant models vs.redistribution), defaulting to deny and propagating restrictions to derived datasets via lineage. - Calendar-aware freshness and robust return-based outlier checks: evaluate staleness on exchange holiday calendars, test completeness against trailing row counts, and run outlier checks on split-adjusted daily returns using both rolling moving-average z-scores and MAD (Median Absolute Deviation)—a outlier-resistant spread measure defined as
median(|x - median(x)|)—flagging anomalies asSUSPECTrather than silently deleting real market crashes. - Right-sized batch architecture: ~30 million daily values (
~120–240 GB/yearuncompressed,~40 GB/yearin columnar Parquet) fits cleanly in a standard columnar warehouse + PostgreSQL catalog without unnecessary streaming complexity.
Common mistakes
- Overwriting historical rows on vendor restatements: mutating values in place silently alters old backtests and leaks future revisions into earlier trading dates.
- Joining fundamentals on
value_date(quarter-end) instead ofknown_from(announcement timestamp): Q2 ends June 30, but earnings are announced weeks later in July/August. - Using ticker strings as primary keys: tickers change (
FB->META) and bankrupt tickers get reassigned to completely different companies years later. - Enforcing vendor entitlements only in the web UI or Excel plugin: if analysts can still query the underlying Snowflake/Parquet tables directly via a shared service account, non-display licensing is bypassed.
- Running outlier detection on unadjusted price levels or purely with sample mean/std: a 2-for-1 stock split looks like a
-50%crash on raw prices, and a single historical bad spike inflates rolling standard deviation enough to mask subsequent bad ticks (z = -1.34vs. robust MAD score-27.32). - Alerting on wall-clock timers without exchange calendars: paging on-call engineers every Good Friday or Thanksgiving erodes alert trust.
Follow-up questions
- When an upstream provider restates past figures weeks or months later, how should your storage model record the revision without breaking prior backtests? Never overwrite the original row: append the corrected value as a new version with
known_fromset to the receipt timestamp of the correction (and close the prior version'sknown_toat that same timestamp in the SCD Type 2 view), linked to the correction'srun_id. Existing backtests that pinned anas_ofcutoff earlier than the correction continue to reproduce the exact same numbers bit-for-bit, whereas unpinned "latest" queries see the updated history. Using catalog lineage, automatically query which registered backtests or production models read the affected(instrument_id, field, value_date)range and send their owners an impact diff (e.g.,AAPL 2024-06-30 EPS: 1.20 -> 1.12 as of 2024-09-15) so researchers can decide whether to evaluate realistic trading decisions (as-first-known) or economic truth (restated). - Suppose a researcher notices today's rerun of a strategy produces different numbers than last week's run—which audit logs and diagnostics isolate a code change from a data revision? First inspect the run's provenance manifest—every backtest run should log
(strategy_git_sha, package_lock_hash, random_seed, query_as_of_timestamp, input_run_ids)—and diff the two manifests. Isolate the root cause systematically with a 2 x 2 matrix of reruns:(old code, old as_of),(new code, old as_of), and(old code, new as_of)against(new code, new as_of). If(old code, old as_of)matches the original result while(old code, new as_of)diverges, a data update caused the shift—querycurated_*andsymbologyfor rows withknown_frombetween the two timestamps, checking new restatements, corporate-action split factors, and universe changes. If(new code, old as_of)already diverges, a code or environment change caused it; and if even(old code, old as_of)fails to reproduce, the pipeline has unpinned non-determinism (unseeded randomness, floating-point parallel reduction order, or an unversioned table) that must be fixed immediately. - How would you place an automated validation gate in the ingestion pipeline so malformed schemas or out-of-range values never reach production models? Use the Write-Audit-Publish (WAP) pattern: connectors and normalizers write incoming batches into an isolated staging partition invisible to users, then execute catalog-driven validation rules split into
BLOCKchecks (schema mismatch, unexpectedNULLs, duplicate(instrument_id, field, value_date)keys, impossible physical ranges likeclose_price <= 0orvolume < 0, row count drop> 10%) andWARNchecks (statistical return outliers). AnyBLOCKfailure aborts publication, quarantines the staging partition for inspection, leaves the previous clean partition serving with dataset status markedSTALE, and pages the feed owner. Downstream automated models call the SDK withquality_policy="strict"so runs either halt safely when a required feed isSTALEor exclude rows flaggedSUSPECT, with any human override requiring an audited approval record.
Follow-up questions
- When an upstream provider restates past figures weeks or months later, how should your storage model record the revision without breaking prior backtests?
- Suppose a researcher notices today's rerun of a strategy produces different numbers than last week's run—which audit logs and diagnostics isolate a code change from a data revision?
- How would you place an automated validation gate in the ingestion pipeline so malformed schemas or out-of-range values never reach production models?
Similar questions
- p-Value Interpretation and Cointegration Testing for Price Series
- Incremental Pipeline for Rolling Market Metrics
- Point-in-Time Market Data Pipeline for Backtesting
- Data Model for Time-Versioned Trading Restrictions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target