Feature Store Reliability, Observability, and Historical Backfills

Medium · ML System Design · Machine Learning Engineer · Onsite

Prompt

Architect the data reliability, governance, and observability layer for a machine-learning platform centered on a dual-storage feature store. Upstream relational warehouse tables and real-time event streams feed transformation pipelines that materialize features into two targets:

  • an offline store queried by batch training jobs to assemble historical datasets, and
  • an online store queried at millisecond latency by live prediction services.

This is a structured architecture discussion spanning three areas:

  1. Reliability dimensions: Define, measure, and enforce eight distinct quality pillars without conflating them—operational readiness (availability, freshness), data integrity (completeness, validity, consistency, distribution), and governance (lineage, compliance).
  2. Feature-store observability: Monitor serving infrastructure, batch and streaming materialization pipelines, live served feature values, and divergence between offline training data and online inference lookups.
  3. Historical backfills: Recompute feature history across past date windows (for updated logic, newly onboarded features, or corrupted upstream intervals) safely and accurately.

Scale assumptions—such as entity cardinality, feature and model counts, latency/freshness targets, storage engines, and applicable privacy statutes—are intentionally left open; state concrete assumptions up front.

Scope & Expectations

  • Non-overlapping quality checks and ownership: Give each of the eight dimensions a distinct quantitative metric, pipeline execution point, failure severity (blocking publication versus alerting), and clear team ownership so signals roll up into an actionable view for feature and model owners.
  • End-to-end store and skew monitoring: Cover serving-path health, pipeline health, served default/null rates, statistical drift, training-versus-serving skew detection, and metadata-driven alert routing that avoids alert storms.
  • Leak-free, isolated backfills: Ensure historical recomputation respects point-in-time visibility with zero future data leakage, supports idempotent chunked retries and reversible cut-overs, isolates live traffic and fresher online keys, and identifies downstream training sets and models requiring updates.

Step-by-step walkthrough

  1. Clarify requirements, core concepts, and assumptions

    This design focuses on the data infrastructure behind machine learning models, centered on a feature store—a shared data system that computes, stores, and serves features (measurable input signals for a model, such as a retailer's order count over the past 30 days). A typical feature store maintains two copies of every feature:

    • An offline store (large historical tables in cloud storage) read by batch training jobs to build datasets.
    • An online store (a fast low-latency key-value database) read by live services during real-time prediction.

    Because thresholds, storage choices, and blocking rules depend heavily on traffic and business context, we start by stating clear assumptions for an online wholesale marketplace connecting brands and retailers.

    Functional requirements

    • Define and continuously measure eight non-overlapping quality pillars grouped across operational readiness (availability, freshness), content integrity (completeness, validity, consistency, distribution), and governance (lineage, compliance).
    • Block corrupt batch data before consumers read it, and isolate bad streaming records without needlessly freezing healthy features.
    • Monitor the feature store end to end: live serving health, pipeline job health, served feature values, and training-serving skew (disagreement between values seen during training and values served live).
    • Run historical backfills (recomputing feature values over past dates) that avoid leaking future information, safely survive retries, stay isolated from live traffic, support fast rollback, and identify affected downstream models.

    Assumptions from the clarifying questions

    Question Assumption used in this design
    Primary consumers Both offline training and online serving (search ranking, recommendations, fraud/risk). Online serving is most latency- and outage-sensitive; offline training requires point-in-time joins (joining each historical event with feature values as they existed at that exact past moment).
    Feature computation Both scheduled batch jobs (hourly/daily Apache Spark jobs on warehouse tables) and real-time streaming jobs (Apache Flink jobs reading Apache Kafka event streams).
    Freshness targets Streaming features: ≤ 10 minutes old online. Daily batch features: ≤ 26 hours old (24-hour cycle plus a 2-hour compute buffer).
    Regulated / personal data User and retailer contact details, addresses, and behavioral identifiers count as PII (personally identifiable information). Deletion requests must complete within statutory windows (such as 30 days under GDPR).
    Ownership Every group of features (feature view) declares an owning team and on-call rotation in a central registry; every upstream source table declares an owner in the data catalog.
    Blocking vs. alerting Batch: failing a critical correctness check blocks publishing the new partition. Streaming: individual events cannot wait for batch audits, so invalid events route to a quarantine topic (a separate holding stream for bad records) and a circuit breaker (an automatic safety switch) halts online writes if error rates spike.

    Assumed marketplace scale: 2,000 total features organized into 150 feature views feeding 40 production models across 10M products, 1M retailers, and 100K brands. Online ranking handles 2,000 requests/s, each scoring 100 candidate products for 1 browsing retailer. Roughly 550 features live on those three large entity types (products, retailers, brands) and dominate storage and I/O; the remaining 1,450 sit on tiny entities (categories, countries, seasons) with negligible volume.

  2. Back-of-the-envelope numbers

    Let's size storage, read throughput, monitoring overhead, and backfill compute so we know where real bottlenecks live.

    1. Online store memory (latest value per entity)
       Products:   10,000,000 x 150 features = 1.50B scalar values
       Retailers:   1,000,000 x 300 features = 0.30B scalar values
       Brands:        100,000 x 100 features = 0.01B scalar values
       Total:      1.81B values x ~10 bytes  = ~18.1 GB of raw values
                   With entity keys, metadata, and hash-table overhead: ~60-100 GB in Redis or DynamoDB
    
    2. Online serving reads
       2,000 ranking requests/s x (1 retailer + 100 candidate products)
       = ~202,000 entity feature-vector lookups/s
    
    3. Offline store growth (daily historical snapshots)
       1.81B values/day x 8 bytes = ~14.5 GB/day uncompressed (~5.3 TB/year raw)
       With columnar Parquet + Zstd compression (~3x): ~5 GB/day (~1.8 TB/year)
    
    4. Quality profiling volume
       One single-scan profile per partition computes count, nulls, min, max,
       approximate distinct count, and quantile sketches for every column at once:
       - Batch:     2,000 feature profiles/day
       - Streaming: 300 streaming features x 24 hourly windows = 7,200 profiles/day
       Total metadata rows written: < 10,000/day (tiny compared to data scans)
    
    5. Skew logging (sampling served features in live traffic)
       At 100% logging: 2,000 req/s x 100 candidates x ~1 KB/row = 200 MB/s = ~17.3 TB/day (too costly!)
       At 0.1% sample:  2 req/s x 100 candidates = 200 rows/s = ~17.3M rows/day
                        17.3M x ~1 KB = ~17.3 GB/day -> 30-day retention = ~520 GB
    
    6. Backfill compute (1 product view x 12 months)
       365 daily partitions x 10M product rows = 3.65B rows recomputed
       At ~10 minutes of Spark compute per daily chunk:
       - Serial execution:       3,650 min = ~61 hours
       - 10 chunks in parallel:  ~6.1 hours on an isolated worker pool
    

    Four design decisions follow directly from this math:

    • Profile every column in a single pass. Running a separate SELECT query per rule across 2,000 features would trigger thousands of table scans per day; computing all summary statistics in one scan adds under 5–10% to job runtime.
    • Sample online feature logs. Logging 100% of served vectors would write ~17.3 TB/day; a 0.1% uniform request sample (~17.3 GB/day) gives millions of rows per day for skew checks at 1/1,000th the cost.
    • Treat backfills as multi-hour distributed jobs. Recomputing a year takes ~61 serial hours, so chunked checkpointing and isolated compute pools are mandatory.
    • Protect humans from alert storms. With 2,000 features × 8 dimensions, naive alerting could fire hundreds of pages when one upstream table breaks. Alerts must group by upstream root cause.
  3. Declarative feature specs and the quality API

    Monitoring rules only work when ownership, freshness targets, and value expectations are defined alongside the feature code itself. Every feature view (a logical group of features computed together from the same upstream sources and keyed by the same entity, such as shop_id) is declared in a YAML specification stored in Git and checked during CI (continuous integration, automated validation run on every pull request):

    feature_view: shop_order_stats
    version: 4
    entity: shop_id
    owner: team-buyer-ml                 # maps to PagerDuty escalation and Slack channel
    tier: critical                       # critical | standard (controls fail-closed blocking)
    sources:
      - table: warehouse.orders
        event_time: created_at           # when the business event actually happened
        available_time: ingested_at      # when the row first landed in the warehouse
    transform: sql/shop_order_stats.sql
    schedule:
      batch: "daily 02:00 UTC"
      online: streaming
    freshness_sla:
      offline: 26h
      online: 10m
    pii: false
    retention_days: 730
    features:
      - name: orders_28d
        type: int64
        expect: {min: 0, max_null_rate: 0.0, default_value: 0}
        drift: {reference: same_weekday_last_4_weeks, psi_warn: 0.10, psi_alert: 0.25}
      - name: gmv_90d_usd
        type: float64
        expect: {min: 0.0, max_null_rate: 0.01, default_value: 0.0}
    

    CI rejects any pull request that omits owner, omits event_time or available_time on a source, or marks pii: false while reading an upstream column tagged as personal data in the data catalog.

    Quality and Lineage API (used by pipeline runners, serving health checks, dashboards, and the alert router):

    POST /v1/checks/results
         body: {target, dimension, metric, observed, threshold, status, severity, run_id}
    GET  /v1/views/{view}/versions/{v}/partitions/{date}/status
         -> {overall_status: "PASS" | "WARN" | "BLOCKED", failing_checks: [...]}
    GET  /v1/models/{model}/scorecard
         -> worst status across the exact (view, version, feature) list the model consumes
    GET  /v1/lineage/{node_id}?direction=upstream|downstream&depth=4
         -> connected source columns, tables, feature partitions, training snapshots, models
    
  4. Data model: versioned stores, registry, check results, and lineage

    We separate feature storage from metadata, quality results, and backfill state so each store matches its query pattern.

    1. Offline store — Apache Iceberg or Delta Lake tables (columnar files with atomic table commits)
       Table: shop_order_stats_v4
       Columns: (shop_id, feature_ts, orders_28d, gmv_90d_usd, computed_at, run_id)
       Partitioned by: date(feature_ts)
    
    2. Online store — Redis Cluster or DynamoDB (low-latency key-value lookup)
       Key:   "shop_order_stats:v4:{shop_id}"
       Value: {orders_28d: 9, gmv_90d_usd: 2410.75, feature_ts: 1762741800, written_at: 1762741805}
    
    3. Feature registry — PostgreSQL
       feature_views  (view_name, version, owner_team, tier, spec_commit, status)
       features       (view_name, version, feature_name, dtype, expectations_json, pii_class)
       model_features (model_name, model_version, view_name, view_version, feature_name)
    
    4. Quality ledger — Append-only partitioned table + time-series metrics
       check_results  (check_id, target_node, dimension, metric_name, observed_value,
                       threshold_spec, status, severity, run_id, checked_at)
    
    5. Lineage graph — PostgreSQL / Graph store (written atomically at job publish time)
       lineage_nodes  (node_id, node_type, uri, metadata_json)
                      -- types: column | table_snapshot | feature_partition | training_set | model_version
       lineage_edges  (src_node_id, dst_node_id, run_id, git_commit, created_at)
    
    6. Backfill ledger — PostgreSQL
       backfill_chunks (backfill_id, view_version, chunk_date, status, input_snapshot_ids,
                        row_count, checksum, attempt, updated_at)
    

    Three modeling choices prevent subtle bugs later:

    • Breaking logic changes create a new version (_v4), never a silent overwrite. Live models pin _v3 until they are retrained on _v4, so changing how orders_28d handles cancelled orders never corrupts an already-deployed model.
    • Every offline row stores two timestamps: feature_ts and computed_at. feature_ts records when that value became valid for predictions (used by point-in-time training joins); computed_at records wall-clock execution time (letting engineers distinguish a live run from a backfill run).
    • Lineage edges are written inside the publish step, not scraped afterward from SQL query logs. That makes missing lineage an immediate, blockable check failure rather than a silent blind spot.
  5. High-level architecture

    Data passes through three quality checkpoints: (1) source contracts before feature jobs read inputs, (2) write-audit-publish on an isolated staging partition before consumers see batch outputs, and (3) post-publish serving and skew monitors on live traffic.

      OLTP DBs --CDC--> Kafka Streams <---- App & Search Click Events
          |                  |
          v                  v
     Warehouse Tables   Streaming Jobs (Flink) ---> Quarantine Topic (invalid records)
          |                  |            \
     [1. Source Checks]      |             +------> Online Store (Redis / DynamoDB) <---+
     (schema, volume,        |                                     |                    |
      freshness)             +--> Stream Archive                   |                    |
          |                                                        v                    |
          v                                                 Feature Server              |
     Batch Jobs (Spark)                                     (reads + probes)            |
          |                                                        |                    |
          v                                                        v                    |
     Staging Partition                                      Live Model Serving          |
          |                                                        |                    |
     [2. Staging Audit] ---> Quality Service                       | 0.1% sampled       |
     (completeness,          (profiles, rules,                     | served features    |
      validity, drift)        reconciliations)                     v                    |
          | pass!                   |                       [3. Skew Joiner]            |
          v                         v                       (compares served            |
     Atomic Publish -------> check_results Table             vs. offline as-of)         |
     (+ Lineage Commit)             |                              |                    |
          |                         v                              |                    |
          v                  Alert Router <------------------------+                    |
     Offline Store           (groups by upstream lineage,                               |
     (Iceberg / Delta)        pages root-cause owner)                                   |
          |                                                                             |
          +---> Point-in-Time Join ---> Training Snapshots ---> Trained Models          |
          +---> Batch Push (with feature_ts guard) -------------------------------------+
    

    How one batch update flows safely (Write-Audit-Publish): At 02:00 UTC, Spark verifies upstream warehouse.orders passed its source checks, writes shop_order_stats_v4 for today into a hidden staging branch, and runs a single-pass audit. Only if all blocking checks pass does Iceberg atomically commit the staging snapshot into the main table, write the lineage_edges record, and push updated keys to the online store. If a blocking check fails, the staging data stays quarantined, the main offline table is untouched, and the online store continues serving yesterday's clean values.

  6. Deep dive 1: Non-overlapping metrics across all eight dimensions

    A classic failure mode is blurring dimensions together—for instance, using "did today's partition arrive?" for availability, freshness, and completeness. To keep each metric orthogonal, test how three different outages get classified:

    Outage A: Redis cluster times out on 2% of live lookups    -> AVAILABILITY failure (data exists, can't read it)
    Outage B: Daily Spark job is stuck in queue for 6 hours    -> FRESHNESS failure    (reads work, data is old)
    Outage C: Spark job finishes on time, drops 40% of rows    -> COMPLETENESS failure (fresh & readable, missing rows)
    

    Here is the exact metric, failure rule, execution stage, and response for all eight dimensions—with zero overlap:

    Dimension Plain-English question Exact metric computed Failure threshold (starting baseline) Where it runs Action & owner
    Availability Can consumers read the store within their latency budget right now? Online: successful read % and p99 latency (99th-percentile response time). Offline: synthetic query success rate. Success < 99.9% over 5 min, or online p99 > 20 ms Feature server telemetry + 1-min synthetic probes Page platform on-call (cannot block publish; serving issue)
    Freshness How old is the newest event reflected in the store? now - watermark (where watermark is the newest event timestamp fully processed); online: now - written_at across recently active entities. Age exceeds SLA (> 10 min streaming; > 26 h daily batch) Job commit metadata, Kafka lag, sampled active keys Alert feature owner; serving keeps last known good values
    Completeness Are all expected entities and non-null values present? rows_written / expected_entity_count and per-feature null_count / rows_written; online key coverage for active entities. Row ratio outside [0.98, 1.02] or null rate > spec's max_null_rate Staging audit (batch); hourly coverage check (online) Block publish for critical tier; page feature owner
    Validity Does every present value obey its type, domain, and key rules? Fraction of rows violating data type, [min, max] bounds, allowed enum set, regex format, or entity-key uniqueness. > 0% on hard invariants (negative order count, duplicate PK); > 0.1% soft rules Staging audit (batch); per-event filter (streaming) Block publish (batch) or quarantine record (stream); owner
    Consistency Do two representations or derivations of the same fact agree? (a) Aggregate reconciliation vs. upstream (SUM(orders_28d) vs. raw orders table); (b) online vs. offline value mismatch rate at identical as_of times. Source reconciliation diff > 0.1%; online/offline logic mismatch > 0.5% Staging audit (reconciliation); hourly skew job (online/offline) Block publish (reconciliation); alert owner (skew)
    Distribution Does the statistical shape of values resemble historical norms? PSI (Population Stability Index, a symmetric score measuring how much histogram bucket shares shifted) or KS (Kolmogorov-Smirnov max cumulative gap) vs. same weekday over past 4 weeks; default-value share. PSI in [0.10, 0.25] -> warn; PSI > 0.25 or default share 2× baseline -> alert Staging audit (batch); hourly window (streaming) Alert owner by default (world changes!); opt-in block only
    Compliance Are privacy, retention, and access-control policies satisfied? % of upstream columns classified; PII-scanner hits on pii: false views; open deletion requests nearing legal SLA; partitions older than retention_days; unauthorized reads. Any untagged PII in pii: false view; deletion age > 25 days (for 30d SLA); expired partition retained Git CI check, daily catalog/PII scan, audit logs Block PR in CI / page data-governance team
    Lineage Can we trace every value backward to inputs/code and forward to models? Fraction of published partitions and training snapshots carrying complete lineage_edges (upstream snapshot IDs, Git SHA, run_id). < 100% (any published artifact missing lineage metadata) Atomic publish transaction Block publish; platform infrastructure team

    Rolling checks up into an actionable picture: Every check writes a standardized row to check_results. A feature's status is the worst status across its 8 dimensions; a feature view's status is the worst across its features; and a model scorecard joins model_features to show each model owner only the features their model actually consumes (for example, "38/40 features healthy; gmv_90d_usd freshness WARN (28h old)").

  7. Deep dive 2: Monitoring the feature store and catching training-serving skew

    Observability spans three operational layers plus explicit parity checks between the offline and online stores:

    1. Serving-path health: Request rate, error rate, and p50/p99 latency per view at the feature server; Redis/DynamoDB memory pressure, cache evictions, and hot-key skew; plus a 1-minute synthetic probe reading known canary keys.
    2. Materialization job health: Batch run duration compared against the job's trailing 14-day median (a Spark job finishing in 1 minute instead of 20 minutes often read an empty upstream partition!), row counts written, Flink consumer lag, checkpoint failures, and quarantine topic rate.
    3. Served feature-value health: Measured directly from the 0.1% live prediction sample, because offline checks cannot see online failures! Specifically, we track the served default-fill rate (when a missing Redis key silently falls back to default_value: 0, the model sees a valid integer 0 and never throws an error, even though predictions degrade), age at serve time (request_ts - served_feature_ts), and live feature PSI against the model's training baseline.

    Why offline and online copies drift apart—and how to classify mismatches

    Because batch Spark SQL writes the offline store while Flink streaming or batch-push jobs write the online store, the two stores can disagree for four distinct reasons:

    • Missing online keys: A key expired via TTL or failed to push, so live serving substituted default_value.
    • Expected timing lag: Streaming updated the online key 2 minutes ago, whereas the offline table only has midnight snapshots (or vice versa).
    • Window/logic bugs (true skew): Flink used UTC midnight while Spark used local time, or Flink counted cancelled orders that Spark filtered out.

    Our hourly skew joiner joins each 0.1%-sampled live request against the offline store and classifies every row in strict priority order:

    Sampled live log row: (shop_id="s_84", req_ts=15:10, served_val=0, served_feat_ts=None, is_default=True)
    Offline lookup as_of=15:10 -> (offline_val=9, offline_feat_ts=02:30)
    
    Step-by-step classification order (order is critical!):
      1. |served_val - offline_val| <= 1e-6                  -> MATCH
      2. is_default and offline_val is not None              -> MISSING_ONLINE_KEY  (alert if > 0.5%)
      3. served_feat_ts != offline_feat_ts                   -> TIMING_DIFFERENCE   (expected; track gap)
      4. Same feature_ts, different value!                   -> LOGIC_MISMATCH      (page owner if > 0.5%!)
    

    Notice why Step 2 must run before Step 3: a missing online key has served_feat_ts = None, which never equals offline_feat_ts = 02:30. Testing timestamps first would misclassify every missing Redis key as a harmless "timing difference"! And for streaming features whose served_feat_ts (15:08) sits between daily offline partitions, the skew job runs the batch transformation SQL on the tiny sampled entity set at as_of = 15:08 so true logic bugs cannot hide behind daily timestamp gaps.

    Lineage-driven alert routing: When upstream warehouse.orders fails its source freshness check at 01:45 UTC, 25 downstream feature views and 12 models are affected. Instead of firing 37 separate pages, the alert router walks lineage_edges upstream, sends one page to the warehouse.orders owner, suppresses downstream pages caused by that node, and posts a single informational Slack summary to the 25 feature owners and 12 model owners.

  8. Deep dive 3: Safe, point-in-time-correct data backfills

    Suppose we evolve shop_order_stats into v4 and need to recompute 12 months of history for training. What exact value should v4 produce for shop s_84 on historical date August 14? It must equal what the live pipeline would have published on August 14 using only facts known at that moment.

    Look at how a late-arriving refund creates data leakage (accidentally letting future facts sneak into historical training features) if we filter only on event_time:

    Timeline for Shop s_84:
      Aug 13, 23:45 UTC  Order #412 placed ($640)
                         event_time = Aug 13 23:45, available_time = Aug 13 23:46
      Aug 14, 00:00 UTC  Logical window cutoff (cutoff_ts) for the Aug 14 daily batch
      Aug 14, 02:00 UTC  Live daily Spark job starts scanning warehouse (scan_ts)
      Aug 14, 02:30 UTC  Live job finishes & publishes to stores (feature_ts = 02:30!)
      Aug 16, 11:20 UTC  Order #412 is refunded, back-dated to event_time = Aug 13 23:50,
                         but lands in warehouse at available_time = Aug 16 11:20!
    
    Naive backfill (filters ONLY event_time <= Aug 14 00:00):
      Sees the Aug 16 refund! Writes $0 GMV for Aug 14 -> LEAKS FUTURE REFUND into training!
    
    Correct two-timestamp backfill for Aug 14:
      Reads rows WHERE event_time     <= Aug 14 00:00 UTC   (cutoff_ts)
                   AND available_time <= Aug 14 02:00 UTC   (scan_ts = cutoff_ts + 2h schedule offset)
      Stamps output row with feature_ts = Aug 14 02:30 UTC  (scan_ts + 30m normal publish duration)
    

    Three rules make historical recomputation faithful:

    1. Bound both event_time and available_time: event_time <= cutoff_ts stops future orders; available_time <= scan_ts hides late-arriving events (like the August 16 refund) that live production could not see at 02:00 UTC.
    2. Stamp feature_ts at publish_ts (02:30 UTC), never cutoff_ts (00:00 UTC): A live buyer browsing at 01:15 UTC on August 14 still saw August 13's feature value because the August 14 job had not finished yet. Stamping feature_ts = 02:30 UTC ensures point-in-time training joins hand 01:15 UTC training examples August 13's value, matching live serving.
    3. Never read mutable tables in place, and reuse the exact production transform: If orders.status is overwritten in place without history, reading it today leaks today's status into last year. Backfills must read append-only CDC (change data capture, an immutable log of every row change) or historical table snapshots—and execute the exact same SQL/code as production parameterized by (cutoff_ts, scan_ts). (If an upstream table lacks history, the registry flags the backfill approximate_history = true so modelers validate carefully.)

    Idempotent, resumable execution and atomic cut-over

    An idempotent write produces the exact same stored result whether a chunk runs once or retries three times after a worker crash:

    from typing import List
    
    
    def run_backfill(
        backfill_id: str,
        view_version: str,
        days: List[str],
    ) -> None:
        """Recompute daily partitions safely with pinned snapshots and staging audits."""
        staging = f"{view_version}__staging_{backfill_id}"
    
        for day in days:
            # 1. Check ledger so a restarted backfill skips already-validated days
            chunk = ledger_get(backfill_id, day)
            if chunk is not None and chunk.status == "VALIDATED":
                continue
    
            # 2. Pin upstream Iceberg snapshot IDs BEFORE computing so retries read identical inputs
            if chunk is None:
                snapshots = pin_upstream_snapshots(view_version, day)
                ledger_put(backfill_id, day, status="RUNNING", input_snapshot_ids=snapshots)
            else:
                snapshots = chunk.input_snapshot_ids
    
            # 3. Run the production transform parameterized by historical cutoff & scan times
            rows = compute_production_transform(view_version, as_of_day=day, snapshots=snapshots)
    
            # 4. OVERWRITE (never append!) the day's staging partition so retries never duplicate rows
            overwrite_partition(table=staging, partition_day=day, rows=rows)
    
            # 5. Run the exact same completeness, validity, and reconciliation audit as live batch
            audit = run_staging_audit(table=staging, partition_day=day)
            if not audit.passed:
                ledger_put(backfill_id, day, status="FAILED", input_snapshot_ids=snapshots)
                raise RuntimeError(f"Backfill audit failed on {day}: {audit.failures}")
    
            ledger_put(
                backfill_id,
                day,
                status="VALIDATED",
                input_snapshot_ids=snapshots,
                row_count=len(rows),
                checksum=compute_checksum(rows),
            )
    
        # 6. All days passed audit -> atomically commit staging partitions into the offline table
        atomic_publish_partitions(staging_table=staging, target_table=view_version, days=days)
    

    Cut-over, isolation, and downstream discovery:

    • Safe cut-over: For a new definition (_v4), we run _v4 live alongside _v3 for 7 days and verify that backfilled partitions match live _v4 outputs before training new models on _v4; _v3 stays untouched for deployed models. For repairing corrupt historical days on _v3, atomic_publish_partitions swaps all repaired partitions in one Iceberg metadata commit, keeping the prior table snapshot for instant time-travel rollback.
    • Workload and online isolation: Backfills run on a separate preemptible Spark pool with strict concurrency quotas, reading warehouse snapshots (never live OLTP databases). Backfills skip the online store unless repairing current values—in which case Redis/DynamoDB writes enforce a conditional version guard (incoming.feature_ts >= stored.feature_ts, rate-limited) so a backfill repair replaces a corrupt same-timestamp value (==) without ever clobbering a newer streaming update (<).
    • Downstream impact: Querying GET /v1/lineage/shop_order_stats_v3?direction=downstream lists every training dataset snapshot whose date range overlaps the repaired partitions and every model version trained on them.
  9. Treating quality checks as an ML detection system

    Static rules work well for hard invariants (orders_28d >= 0), but distribution and volume checks act like binary classifiers predicting "real data incident vs. normal business variation". Framing them as an ML detection problem keeps false alarms low:

    • Labels: Every fired alert requires a one-click triage tag on resolution (pipeline_bug, real_world_shift, or false_alarm), and postmortems log missed_incident windows. Six months of triaged alerts and incidents form our labeled evaluation dataset.
    • Detector features: Raw metric value (e.g., today's PSI or row-count delta), seasonal baseline (same weekday over the past 4 weeks and same week last year), marketplace calendar indicators (major wholesale trade-show weeks, Black Friday, holidays), and correlated movement across sibling features sharing the same source.
    • Model progression: Start with interpretable declarative bounds in the YAML spec (psi_alert: 0.25). For seasonal features with noisy fixed bounds, graduate to adaptive historical quantiles (alert when residuals after weekday/holiday adjustment exceed the 99.5th percentile of the past 90 days).
    • Offline evaluation: Replay candidate threshold rules across 6 months of stored check_results time series, measuring alert precision (fraction of alerts that were real bugs), incident recall (fraction of true incidents caught), and detection lead time. Promote threshold changes only when offline replay improves precision without dropping recall.
    • Serving, monitoring, and A/B testing: Single-pass audits must stay under 10% of batch job runtime. We monitor weekly alerts per on-call engineer and muted-check counts (a muted check is tech debt). Finally, when a backfill repairs or upgrades a feature, any retrained model is evaluated offline on a fixed holdout and rolled out via an online A/B test (randomly splitting live traffic between incumbent and retrained models) on business metrics like search conversion before full cut-over.
  10. Scaling, bottlenecks, failure handling, and trade-off summary

    Scaling to 10× features and traffic

    • Mergeable statistical sketches: Computing exact medians or exact COUNT(DISTINCT) across billions of rows requires expensive sorting or shuffling. Instead, the single-pass profiler stores compact mergeable sketches per daily partition—HyperLogLog (a fixed-kilobyte probabilistic counter that estimates distinct values within ~1% error) and KLL / t-digest sketches (compact summaries that estimate percentiles like p50/p99 and can be combined across 28 days in milliseconds without rescanning raw rows).
    • Adaptive skew sampling: Critical tier-1 models sample 0.5–1.0% of requests for faster skew detection while long-tail models sample 0.05%, batching offline point-in-time lookups by (view, date) partition.
    • Organizational scaling: Infrastructure scales linearly with columns, whereas human attention does not—so mandatory spec ownership, lineage root-cause grouping, and seasonal baselines remain the primary defense against alert fatigue.

    Failure handling (including failures inside the quality platform)

    Failure scenario System behavior Why this trade-off wins
    Critical check fails on staging partition Block publish; online store keeps serving last good values; freshness metric turns WARN; page owner with explicit override command if verified benign Serving 1-day-stale order counts hurts ranking far less than serving all-zeros or corrupt negatives
    Quality service / audit runner crashes critical tier fails closed (blocks publish, pages platform); standard tier publishes with audited=false flag Prevents a checker bug from freezing all 2,000 features while still protecting tier-1 revenue models
    Spike of malformed streaming events Invalid events go to quarantine topic; if > 5% invalid over 5 min, circuit breaker pauses online writes for that view Stops poison events from corrupting millions of Redis keys while preserving healthy views
    Corrupt batch partition discovered after publish Roll Iceberg table pointer back to previous snapshot; re-push prior snapshot to online store with rollback override while pausing live stream writes; flag tainted training sets in lineage Requires keeping table snapshots for 14–30 days, buying fast 1-step recovery
    Lineage database temporarily unreachable Spark/Flink still embeds upstream snapshot IDs and Git SHA inside Iceberg commit properties; graph ingester catches up asynchronously Keeps publishing decoupled from graph DB uptime without ever losing lineage truth

    Summary of core trade-offs

    • Block vs. alert: Block on deterministic corruption (completeness, validity, source reconciliation, compliance, missing lineage) where bad data beats stale data; alert on freshness, availability, and distribution drift where blocking is either impossible or triggered by real-world business shifts.
    • Immutable versions (_v4) vs. in-place edits: Temporarily duplicates storage during model migration, in exchange for zero silent breakage of deployed models and instant pointer rollback.
    • Two-timestamp point-in-time backfills vs. naive date filters: Tracking available_time alongside event_time and keeping CDC/snapshots costs extra storage, but eliminates future data leakage in historical training sets.

Intuition & how it works

Think of an ML feature store (a shared platform that computes and serves model input signals, called features) like a central prep kitchen supplying two dining rooms at once: a recipe test kitchen (offline store, large historical tables used to train models) and a fast-paced dinner line (online store, a low-latency key-value database read in milliseconds during live predictions). Keeping dishes consistent and safe requires four habits: inspecting raw ingredients at the loading dock (source contracts), tasting every batch on a staging counter before putting it on the serving line (write-audit-publish), verifying that the dinner line serves the exact same portion sizes the test kitchen practiced with (training-serving skew monitoring), and—whenever a recipe changes—rebuilding past test batches using only the ingredients that were actually sitting in the cooler on each past date (point-in-time backfills).

A naive setup—checking only "did the daily Spark job exit with code 0?" and running a quick backfill query over today's live tables—fails silently in production. A job can succeed while an upstream bug turns a feature 90% null, expired Redis keys can quietly feed default zeros to live models while offline tables look spotless, and reading today's updated orders table during a backfill leaks future refunds into last year's training rows. Conversely, blocking every pipeline whenever a feature's average changes turns every holiday sale into a self-inflicted outage.

Concrete 4-step walkthrough (orders_28d for shop s_84)

  1. Daily batch staging audit (02:00 UTC): Spark computes orders_28d into a hidden staging partition and profiles every column in one scan. Row count is 99.8% of expected (completeness pass), minimum is 0 (validity pass), and total orders match raw warehouse.orders within 0.01% (consistency pass), so the job atomically commits the partition to Apache Iceberg (a table format supporting all-or-nothing snapshot commits), records lineage (which upstream snapshots and Git commit produced it), and pushes s_84 -> 9 to Redis.
  2. Online skew detection (15:10 UTC): Suppose a Redis eviction wipes s_84's key, so live serving falls back to default_value = 0. A 0.1% sampled request log joins (s_84, 15:10, served=0, is_default=True) against the offline store (offline=9) and flags MISSING_ONLINE_KEY before model accuracy visibly drops.
  3. Root-cause alert routing: Next day, upstream warehouse.orders stalls. Instead of paging 25 feature owners and 12 model owners separately, the alert router traces the lineage graph upstream, pages only the warehouse.orders owner, and posts one grouped status notice downstream while online serving safely keeps yesterday's values.
  4. Leak-free backfill (recomputing August 14): Months later, the team creates v4. For August 14 (cutoff = 00:00 UTC, live job scan = 02:00 UTC, live publish = 02:30 UTC), the backfill reads historical snapshots where event_time <= Aug 14 00:00 and available_time <= Aug 14 02:00 (ignoring a refund that arrived on August 16), and stamps feature_ts = Aug 14 02:30 UTC so training rows before 02:30 never see a value live serving did not have yet.

Key trade-offs

  • Blocking publish vs. alerting only: Blocking guarantees bad batch partitions never reach consumers, but every false alarm makes online features go stale. Block where corrupt values are strictly worse than day-old values and rules are deterministic (completeness, validity, upstream reconciliation, compliance, missing lineage); alert where blocking makes no sense (availability, freshness) or where real-world events shift numbers legitimately (distribution drift, measured via PSI, or Population Stability Index, a histogram-divergence score).
  • Fail-closed vs. fail-open when the quality service itself crashes: Failing closed (refusing to publish unaudited data) protects critical revenue models, whereas failing open everywhere lets corrupt data slip through and failing closed everywhere turns a checker bug into a platform-wide freeze. Splitting views into critical (fail-closed) and standard (publish with audited=false flag) bounds the blast radius.
  • Exact scans vs. mergeable statistical sketches: Exact COUNT(DISTINCT) and exact medians across billions of rows require costly distributed shuffles. Mergeable sketches—such as HyperLogLog (compact approximate distinct counters) and KLL / t-digest (compact percentile summaries that combine across days without rescanning raw rows)—cut profiling overhead to one cheap pass, reserving exact checks for hard invariants like primary-key uniqueness on new partitions.
  • Row-level skew joins vs. distribution-only drift checks: Sampling 0.1% of live feature vectors and running point-in-time joins (looking up offline values as of the exact request timestamp) requires a logging stream and hourly join job, but pinpoints exact logic mismatches and missing Redis keys that aggregate histogram checks miss (such as two swapped columns with similar ranges).
  • New immutable version (_v4) vs. in-place backfill overwrite: Creating _v4 temporarily doubles storage until deployed models migrate off _v3, but prevents silent prediction shifts in live models expecting _v3 semantics and makes rollback an instant pointer flip. In-place atomic partition replacement is reserved strictly for repairing corrupt data under an unchanged definition.
  • Two-timestamp CDC history vs. reading current tables: Retaining CDC (change data capture, an append-only log of historical row mutations) and available_time metadata costs storage, but without them backfills over mutable tables inevitably leak future updates into training sets and inflate offline metrics.

Common mistakes

  • Reusing the same check across multiple reliability dimensions: Measuring availability, freshness, and completeness all as "did today's partition land?" makes it impossible to distinguish a down Redis cluster, a delayed Spark job, and a job that dropped half its rows.
  • Computing metrics with no owner, threshold, or pipeline stage: Numbers on a passive dashboard that neither gate staging partitions nor route to a named team's on-call rotation decay into ignored noise.
  • Blocking batch publishes on distribution drift by default: Holiday shopping spikes, wholesale trade shows, and promotions legitimately shift feature distributions; auto-blocking on PSI freezes features exactly during peak business traffic.
  • Monitoring only the offline warehouse: Online-only failures—TTL key evictions turning features into silent default zeros, Flink consumer lag, or partial Redis pushes—never appear in offline Iceberg tables.
  • Testing timestamp inequality before default-fill flags in skew checks: Because a missing online key lacks a real feature_ts, checking served_feature_ts != offline_feature_ts first mislabels broken cache misses as harmless timing lag.
  • Filtering backfills only by event_time or stamping feature_ts at midnight cutoff: Ignoring available_time leaks late-arriving refunds/chargebacks into the past, and stamping feature_ts = 00:00 instead of actual publish time (02:30) feeds 01:00 training examples a value live serving had not computed yet.
  • Writing a separate Python/SQL script for backfills or appending on retry: Separate backfill logic inevitably drifts from production code, and INSERT appends instead of partition OVERWRITEs create duplicate rows whenever a worker retries a failed day.
  • Pushing backfilled rows to the online store without a timestamp guard: Without requiring incoming.feature_ts >= stored.feature_ts, a slow backfill job overwrites fresher minute-old streaming values in Redis.

Follow-up questions

  • When an account holder submits a statutory right-to-erasure request, how do you locate and purge their records across raw warehouse tables, offline feature partitions, cached online keys, and saved training datasets? Classification tags in the catalog and the lineage graph trace every column containing PII (personally identifiable information) forward to affected feature views, offline Iceberg partitions, online keys, and training snapshots. A durable deletion_log records the user ID and drives an automated erasure workflow: (1) execute row-level deletes in raw warehouse and offline feature tables, followed by file compaction and snapshot expiration so Iceberg time travel (querying historical snapshots) no longer retains deleted bytes; (2) immediately DEL the entity's keys across all versions in the online store; (3) purge rows from retained training snapshots (or enforce snapshot retention shorter than the 30-day statutory deadline, while ensuring short-lived logs like Kafka and the 30-day skew sample auto-expire within window); and (4) verify erasure with an audit scan logged as a compliance metric. Every future backfill joins against deletion_log to filter erased IDs so historical recomputation never resurrects deleted users, or uses crypto-shredding (encrypting each user's payload with a per-user key and destroying the key).
  • Suppose a key feature's value histogram shifts dramatically between yesterday and today. How do you distinguish genuine marketplace behavior from an upstream data bug, and should drift checks halt publication automatically? Check for pipeline fingerprints first: did null or default-fill rates jump, did row counts drop, did the shift start abruptly at a Git deploy or upstream schema change recorded in lineage, is it isolated to one shard/platform, or did sibling features reading the same upstream table stay flat? Next, cross-check real-world signals: marketplace promotions or seasonal trade events on the calendar and matching movement in independent executive order dashboards. By default, pure distribution checks (PSI > 0.25) should alert rather than block, because real-world demand shifts happen often and freezing features hurts live ranking—whereas bug-specific invariants (null spikes, negative counts, out-of-range values) belong under completeness and validity, which do block publishing. Owners of high-stakes models may opt specific features into extreme-drift blocking paired with a one-command audited override.
  • If an upstream engineering team renames a source column without warning, which safeguard trips first and how does the platform handle dependent features and alerts? The source contract check, which validates the upstream table's schema against all columns declared in active feature specs before any feature job starts, catches the missing column first and pages the upstream table owner directly. Downstream feature jobs found via lineage pause automatically before running, the online store continues serving their last known good values, and downstream freshness warnings roll up under that single root-cause alert instead of paging 20 feature teams. (Without a source contract check, either Spark crashes with a missing-column error or—far worse on schema-on-read Parquet files wrapped in COALESCE(col, 0)—reads all nulls and silently emits zeros until staging completeness/default-rate audits block it.) Because only the column name changed and not the business meaning, engineers map the new column name under the same feature view version, verify identical output on a test day, and rerun the held partitions so offline history stays gap-free.
  • After recomputing six months of history for a modified feature, how do you prioritize which downstream models need retraining, and how do you verify parity between backfilled outputs and live production runs? Walk the lineage graph downstream from the rewritten (view, version, date_range) to find every overlapping training snapshot and deployed model version, then prioritize retraining models where both the feature changed substantially (measured by % of modified rows and PSI between old and backfilled training columns) and the model relies heavily on that feature (measured by permutation or SHAP feature importance, which quantifies each input's contribution to predictions), validating candidates offline and via an online A/B test. To prove production parity before cut-over, take a recent 7-day overlap window where both the live pipeline and the backfill produced values, join on (entity_id, feature_ts), and require 100% exact match on integers and ≥ 99.9% match within tight relative tolerance (1e-5) on floats. Any unexplained discrepancy indicates a bug in time filtering or mutable-source handling and blocks switching over.

Follow-up questions

Similar questions

More Faire interview questions

All 10 Faire questions →