IIT Madras Zanzibar · Teaching

← Course Overview

Question Bank

Organised by lab and difficulty. Use this bank to prepare for Quiz 1, the course project, and the end-semester examination. Questions test both conceptual understanding and practical implementation knowledge.

Reference Sheet: Pair these problems with the compiled 2-page PDF formula summary before inspecting solutions.Big Data & Lakehouse Cheat Sheet (PDF)
Lab 1

Big Data Landscape & Setup


Q1EasyQuiz

Define the three Vs of Big Data (Volume, Velocity, Variety). Give a concrete example of a dataset that scores high on all three.

Reveal Worked Solution
Volume (scale of stored data), Velocity (arrival speed), and Variety (heterogeneous structured/JSON/image formats): for example, real-time global mobile payment telemetry paired with merchant receipts.
Q2EasyAssignment

What is the difference between a data lake, a data warehouse, and a lakehouse? In what scenario would you choose each?

Reveal Worked Solution
A data warehouse stores curated relational schemas for BI; a data lake holds raw low-cost files without ACID; a lakehouse adds ACID transactions, schema enforcement, and indexing directly over open Parquet object storage.
Q3EasyQuiz

What does the Spark UI show you? Name three pieces of information you can extract from a Spark job's DAG visualisation.

Reveal Worked Solution
The Spark UI shows job DAG stages, narrow vs. wide shuffle boundaries, task duration skew/GC time, and shuffle read/write byte volumes.
Q1IntermediateQuiz

Explain the difference between Spark's driver and executor roles. What happens when an executor fails? How does Spark's fault tolerance model handle this?

Reveal Worked Solution
The driver coordinates planning and task scheduling, whereas executors run tasks and cache partitions. If an executor fails, Spark recomputes lost partitions from upstream RDD lineage on healthy executors.
Q2IntermediateAssignment

Write a PySpark job that reads a CSV file, filters rows where sales > 1000, groups by region, computes the total and average sales per region, and writes the result to a Delta Lake table.

Reveal Worked Solution
df = spark.read.csv('sales.csv', header=True, inferSchema=True)
agg = df.filter(df.sales > 1000).groupBy('region').agg(F.sum('sales'), F.avg('sales'))
agg.write.format('delta').mode('overwrite').save('/lake/gold/region_sales')
Q1AdvancedExam

Compare the Hadoop MapReduce and Apache Spark execution models. Why is Spark typically 10–100× faster for iterative workloads? Under what conditions does MapReduce outperform Spark?

Reveal Worked Solution
Hadoop MapReduce writes intermediate outputs to HDFS disk after every map and reduce stage, whereas Spark pipelines narrow transforms in memory across a multi-stage DAG. MapReduce only wins when memory-starved clusters process single-pass batch jobs exceeding RAM with heavy spill.
Lab 2

Lakehouse & Delta Lake


Q1EasyQuiz

What ACID properties does Delta Lake provide on top of a plain Parquet data lake? How does it achieve atomicity for multi-file writes?

Reveal Worked Solution
Delta Lake adds Atomicity, Consistency, Isolation, and Durability via an append-only transaction log (_delta_log); multi-file writes become visible atomically only when the single JSON commit entry lands.
Q2EasyAssignment

What is Delta Lake's time travel feature? Write a PySpark snippet to read a Delta table as it existed 3 versions ago.

Reveal Worked Solution
Time travel queries prior table snapshots stored in the Delta log: spark.read.format('delta').option('versionAsOf', v - 3).load(path).
Q1IntermediateQuiz

Explain the Delta Lake MERGE (UPSERT) operation. Write a PySpark MERGE statement that inserts new customer records and updates the email address for existing customers based on customer_id.

Reveal Worked Solution
DeltaTable.forPath(spark, path).alias('t').merge(src.alias('s'), 't.customer_id = s.customer_id').whenMatchedUpdate(set={'email': 's.email'}).whenNotMatchedInsertAll().execute()
Q2IntermediateAssignment

What is Delta Lake's transaction log (_delta_log)? How does it differ from a traditional write-ahead log? What information does each JSON file in the log contain?

Reveal Worked Solution
_delta_log stores ordered JSON commit actions (add, remove, metaData, protocol) plus periodic Parquet checkpoints rather than raw row byte images, giving snapshot isolation via optimistic concurrency.
Q1AdvancedExam

A Delta Lake table receives 10,000 small file writes per hour. Explain the "small files problem" and its performance impact. What Delta Lake operations (OPTIMIZE, Z-ORDER, VACUUM) would you schedule and at what frequency to maintain query performance?

Reveal Worked Solution
Small files inflate metadata listing and per-file open overhead. Schedule hourly/daily OPTIMIZE table ZORDER BY (key) to compact into 128–512 MB Parquet files and weekly VACUUM table RETAIN 168 HOURS to prune obsolete unreferenced files.
Lab 3

Apache Iceberg & Data Governance


Q1EasyQuiz

What is Apache Iceberg? Name two features that distinguish it from a plain Parquet-based data lake.

Reveal Worked Solution
Apache Iceberg is an open table format supporting snapshot-based ACID commits and hidden partitioning, distinguishing it from unversioned Parquet folders that require full directory listing.
Q2EasyAssignment

What is partition evolution in Iceberg? Why is it important for long-lived production tables?

Reveal Worked Solution
Partition evolution changes table partitioning (for example, monthly to daily) in metadata without rewriting historical Parquet files, preventing downtime on multi-terabyte production tables.
Q1IntermediateQuiz

Explain schema evolution in Iceberg. What operations (add column, rename column, drop column) are supported without rewriting data? What is the role of field IDs in making this safe?

Reveal Worked Solution
Adding, renaming, reordering, and dropping columns occur purely in Iceberg metadata because every column is tracked by an immutable integer field_id rather than positional name.
Q2IntermediateExam

Compare Delta Lake and Apache Iceberg across: ACID support, schema evolution, partition evolution, engine support, and catalog integration. For a multi-engine lakehouse (Spark + Flink + Trino), which would you choose and why?

Reveal Worked Solution
Both offer ACID and schema evolution; Iceberg natively supports hidden partition evolution, immutable field IDs, and broad multi-engine read/write compatibility across Spark, Flink, and Trino.
Q1AdvancedProject

Design a data governance framework for a lakehouse serving both a regulatory reporting team (needs lineage, audit, immutability) and a data science team (needs fast iteration, schema flexibility). How do you balance these competing needs using Iceberg, Nessie Catalog, and OpenLineage?

Reveal Worked Solution
Store immutable snapshots in Iceberg, isolate experimental data-science branches in Project Nessie (dev vs. main), merge validated changes via CI quality gates, and emit OpenLineage events on every Spark/Trino job for regulatory provenance.
Lab 4

Spark Foundations & DataFrame API


Q1EasyQuiz

What is the difference between a Spark transformation and an action? Give two examples of each. Why does Spark use lazy evaluation?

Reveal Worked Solution
Transformations (filter, select) build a lazy logical DAG; actions (count, write) trigger execution. Lazy evaluation lets Catalyst combine filters, push predicates to Parquet, and prune unused columns.
Q2EasyAssignment

What is a Spark partition? How does the number of partitions affect parallelism and performance? What is the recommended partition size in MB?

Reveal Worked Solution
A partition is the unit of data parallelism (one task per partition per stage); too few underutilize cores, whereas millions inflate scheduler overhead. Target roughly 128 MB per partition.
Q3EasyQuiz

Explain the difference between cache() and persist() in Spark. When should you cache a DataFrame?

Reveal Worked Solution
cache() is shorthand for persist(MEMORY_AND_DISK); persist() lets you pick explicit storage levels (such as DISK_ONLY or serialized). Cache only DataFrames reused repeatedly across multiple actions.
Q1IntermediateAssignment

Write PySpark code to: read a JSON dataset of e-commerce orders, explode a nested items array, compute total revenue per product category, and write the output as a partitioned Parquet file partitioned by category.

Reveal Worked Solution
df.withColumn('item', F.explode('items')).groupBy('item.category').agg(F.sum(F.col('item.qty') * F.col('item.price')).alias('rev')).write.partitionBy('category').parquet('/out/rev')
Q2IntermediateQuiz

What is the difference between map() on an RDD and select() on a DataFrame? When would you prefer the RDD API over the DataFrame API?

Reveal Worked Solution
map() runs opaque Python lambdas row-by-row with serialization overhead across the JVM boundary, whereas DataFrame select() compiles into Catalyst Tungsten vectorized bytecode. Use RDDs only for unstructured binary data lacking tabular schema.
Q1AdvancedExam

A Spark job reads a 500 GB Parquet file and runs a groupBy aggregation. The job has 200 tasks in stage 1 and 200 tasks in stage 2, but stage 2 takes 10× longer with a few tasks running much longer than others. Diagnose this problem and propose three specific remedies.

Reveal Worked Solution
Straggler tasks in stage 2 indicate hot-key data skew after shuffle. Remedies: (1) enable Spark 3 AQE skew join optimization; (2) apply two-stage key salting on skewed group keys; (3) filter NULL or sentinel placeholder keys before aggregation.
Lab 5

Spark SQL, Joins & Window Functions


Q1EasyQuiz

What are the two physical join strategies Spark uses? When does Spark automatically choose a broadcast join?

Reveal Worked Solution
Broadcast Hash Join and Sort-Merge Join (plus shuffled hash join). Spark auto-broadcasts when a table's estimated size falls under spark.sql.autoBroadcastJoinThreshold (default 10 MB).
Q2EasyAssignment

Write a Spark SQL window function query to compute each employee's salary rank within their department, using RANK(). How does RANK() differ from DENSE_RANK()?

Reveal Worked Solution
SELECT *, RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk FROM emp. On ties, RANK() skips subsequent numbers (1, 1, 3), whereas DENSE_RANK() stays contiguous (1, 1, 2).
Q1IntermediateQuiz

Explain what a shuffle join is in Spark. Why is it expensive? How does a sort-merge join differ from a hash join, and when does Spark prefer each?

Reveal Worked Solution
A shuffle join partitions both tables by join key over the network (expensive disk + network I/O). Sort-merge join sorts partitions and merges them with bounded memory, whereas shuffled hash join builds an in-memory hash table on the smaller partition without sorting.
Q2IntermediateAssignment

Using a transactions table with columns (txn_id, user_id, amount, txn_date), write Spark SQL to compute: (a) 7-day rolling average amount per user, (b) cumulative total amount per user ordered by date, (c) each transaction's percentage contribution to the user's monthly total.

Reveal Worked Solution
Use window frames over partitioned user_id: (a) 7-day range/row rolling average, (b) SUM(amount) OVER (PARTITION BY user_id ORDER BY txn_date), and (c) amount / SUM(amount) OVER (PARTITION BY user_id, date_trunc('month', txn_date)).
Q1AdvancedExam

You are joining a 500 GB fact table with a 200 MB dimension table. Explain two strategies: (a) broadcast join, (b) bucketed join. For each, describe how to implement it in PySpark, its memory requirements, and when it is preferable. What happens if you try to broadcast a 5 GB table?

Reveal Worked Solution
Broadcast join copies the 200 MB dimension table to every executor (raise threshold cautiously if driver/executor RAM allows); bucketed join pre-partitions and sorts both tables into matching bucket counts on join key to skip shuffles. Broadcasting a 5 GB table risks driver/executor OOM crashes.
Labs 5–6 Topic

Spark Performance Tuning & AQE


Q1EasyQuiz

What is data skew in Spark? How can you detect it in the Spark UI? Name two techniques to fix it.

Reveal Worked Solution
Data skew occurs when a small subset of keys dominates partition size, visible in Spark UI task duration max >> median. Fix with AQE skew splitting or salted keys.
Q2EasyQuiz

What is Adaptive Query Execution (AQE) in Spark 3? Name three optimisations it can apply at runtime that the static query planner cannot.

Reveal Worked Solution
AQE re-optimizes plans using live shuffle statistics: (1) coalescing tiny post-shuffle partitions, (2) switching sort-merge to broadcast join at runtime, and (3) splitting skewed shuffle partitions.
Q1IntermediateAssignment

A Spark job joining two large tables runs for 4 hours. You observe in the Spark UI that 5 of 200 tasks take 90% of the time, and the join key is country_code with 70% of rows having country_code = 'TZ'. Propose and implement a salting strategy to fix this skew.

Reveal Worked Solution
Salt skewed keys (country_code = 'TZ') with random suffix 0..9 on the large table and explode matching small-table rows across buckets 0..9 so 10 tasks process the hot partition in parallel.
Q2IntermediateQuiz

Explain the impact of the following Spark configuration parameters: spark.executor.memory, spark.executor.cores, spark.sql.shuffle.partitions. What values would you start with for a cluster with 10 nodes, 16 cores each, and 64 GB RAM per node?

Reveal Worked Solution
For 10 nodes x 16 cores x 64 GB: allocate 3 executors/node with 5 cores and ~19 GB RAM each (leaving OS + overhead headroom), and set initial spark.sql.shuffle.partitions around 2-3x total cores (roughly 300–450, letting AQE coalesce).
Q1AdvancedExam

Profile a Spark job end-to-end: describe the metrics you would examine in the Spark UI (stages, tasks, GC time, shuffle read/write, spill) to identify whether the bottleneck is CPU-bound, memory-bound, I/O-bound, or network-bound. For each bottleneck type, prescribe specific configuration changes and code changes.

Reveal Worked Solution
High GC time + spill indicates memory pressure (increase executor memory/partitions or drop excessive caching); long serialization/Python UDF time indicates CPU-bound overhead (switch to native Spark SQL); high shuffle read/write wait indicates network I/O (broadcast small tables, filter early, enable compression).
Lab 6

Data Orchestration with Airflow


Q1EasyQuiz

What is an Airflow DAG? What do nodes and edges represent? What happens if an Airflow DAG has a cycle?

Reveal Worked Solution
An Airflow DAG is a Directed Acyclic Graph where nodes are operators/tasks and directed edges express execution dependencies. Airflow rejects DAGs containing cycles at parse time.
Q2EasyAssignment

What is the difference between Airflow and Dagster in terms of their data model? How does Dagster's asset-based approach differ from Airflow's task-based approach?

Reveal Worked Solution
Airflow models imperative task execution order (task_a >> task_b), whereas Dagster models declarative software-defined assets that track upstream data lineage and freshness directly.
Q1IntermediateAssignment

Write an Airflow DAG (in Python) that: (1) extracts data from an API daily at 06:00 UTC, (2) runs a Spark job to transform it, (3) loads the result to a Delta Lake table, (4) sends a Slack alert if any task fails. Include retry logic and timeouts.

Reveal Worked Solution
Define a @dag(schedule='0 6 * * *', default_args={'retries': 2, 'retry_delay': timedelta(minutes=5), 'on_failure_callback': slack_alert}) chaining extract >> spark_transform >> load_delta with task-level execution_timeout.
Q2IntermediateExam

Explain Airflow's XCom mechanism. What are its limitations for large data? What alternative patterns exist for passing data between tasks in a production pipeline?

Reveal Worked Solution
XCom serializes small task outputs in Airflow's metadata DB, causing bloat or crashes on large payloads. Pass object-store URIs or Delta table versions between tasks instead of raw DataFrames.
Q1AdvancedProject

Design a production data pipeline orchestration strategy for a financial reporting system that must: process 50 GB of daily transaction data, complete within a 4-hour SLA, handle partial failures gracefully with idempotent reruns, and maintain a full audit log. Compare Airflow vs Dagster for this use case.

Reveal Worked Solution
Use date-partitioned idempotent MERGE writes keyed by logical ds, task-level SLAs with alerting, retry backoff, and Dagster/OpenLineage asset tracking for end-to-end auditability.
Lab 7

Kafka & Real-Time Streaming


Q1EasyQuiz

Define: Kafka topic, partition, offset, producer, consumer group. Explain how consumer groups enable both load balancing and message broadcasting.

Reveal Worked Solution
Topic: named stream; Partition: ordered append-only log shard; Offset: sequential message ID inside a partition; Producer: writer; Consumer group: set of workers sharing partition ownership for parallel scale-out, whereas distinct groups independently broadcast the full stream.
Q2EasyAssignment

What guarantees does Kafka provide regarding message ordering? Are messages ordered globally across all partitions or only within a partition?

Reveal Worked Solution
Kafka guarantees strict message ordering solely within each individual partition, not globally across all partitions of a multi-partition topic.
Q3EasyQuiz

What is Redpanda? How does it differ from Apache Kafka architecturally (no ZooKeeper/KRaft dependency)?

Reveal Worked Solution
Redpanda is a Kafka-protocol-compatible C++ streaming engine built on Raft consensus with thread-per-core execution, removing JVM garbage collection and ZooKeeper/KRaft coordination overhead.
Q1IntermediateAssignment

Write a Python Kafka producer that publishes JSON sensor readings (temperature, humidity, device_id, timestamp) to a topic at 100 messages/second. Write a consumer that reads from the topic and writes batches of 1000 messages to a Delta Lake table.

Reveal Worked Solution
Use confluent_kafka.Producer or kafka-python keyed by device_id, and consume batches with manual offset commits only after the Delta Lake batch write succeeds.
Q2IntermediateExam

Explain the three delivery semantics in Kafka: at-most-once, at-least-once, and exactly-once. What producer and consumer configuration settings control each? What is the trade-off between exactly-once and throughput?

Reveal Worked Solution
At-most-once commits offsets before processing; at-least-once commits after sink write (requires idempotent sink); exactly-once pairs idempotent producers (enable.idempotence=true), transactions, and read_committed consumers at slight latency/throughput cost.
Q1AdvancedProject

Design a Kafka-based architecture for a real-time fraud detection system that processes 500,000 payment events per second. Specify: number of partitions and why, replication factor, retention policy, consumer group topology, and how you would handle a downstream consumer that is 10 minutes behind.

Reveal Worked Solution
Provision 64–128 partitions keyed by account_id, replication factor 3 with acks=all and min.insync.replicas=2, 7-day retention + compacted state topics, and separate consumer groups for real-time scoring vs. lagging analytics backfill.
Lab 8

Spark Structured Streaming


Q1EasyQuiz

What is a watermark in Spark Structured Streaming? Why is it needed for window aggregations on event-time data?

Reveal Worked Solution
A watermark tracks max(event_time) - delay_threshold, telling Spark when older event-time windows can finalize and drop per-window state safely.
Q2EasyAssignment

What are the three output modes in Spark Structured Streaming (Complete, Append, Update)? Which modes are compatible with aggregations and which with watermarks?

Reveal Worked Solution
Complete emits the full aggregate table each trigger; Append emits finalized rows once past the watermark; Update emits only modified aggregate rows per micro-batch.
Q1IntermediateAssignment

Write a Spark Structured Streaming job that reads from a Kafka topic of clickstream events (user_id, page_id, event_time), applies a 5-minute tumbling window with a 2-minute watermark, counts clicks per page per window, and writes results to a Delta Lake table.

Reveal Worked Solution
stream.withWatermark('event_time', '2 minutes').groupBy(F.window('event_time', '5 minutes'), 'page_id').count().writeStream.format('delta').outputMode('append').option('checkpointLocation', '/chk/clicks').start('/lake/clicks')
Q2IntermediateExam

Explain exactly-once semantics in Spark Structured Streaming. What role do checkpoints play? What happens to the stream state if the checkpoint directory is deleted?

Reveal Worked Solution
Structured Streaming persists Kafka offsets and incremental state in an atomic write-ahead checkpoint directory paired with an idempotent sink. Deleting checkpoints erases offset tracking and active window state, causing full reprocessing from earliest/latest offset.
Q1AdvancedProject

Design a stateful streaming pipeline that detects user sessions from a clickstream (a session ends after 30 minutes of inactivity). Discuss how to implement this using Spark's flatMapGroupsWithState or mapGroupsWithState. What are the memory implications of storing state for 10 million concurrent sessions?

Reveal Worked Solution
Maintain per-user session state (last event timestamp, count) in RocksDB state store via flatMapGroupsWithState with event-time timeout 30 minutes, bounding memory by always configuring watermarks and state TTL eviction.
Lab 9

Big Data Visualization


Q1EasyAssignment

What is the difference between Grafana and Superset? Which is better suited for infrastructure/metrics monitoring and which for business intelligence dashboards?

Reveal Worked Solution
Grafana excels at real-time time-series infrastructure/Prometheus telemetry, whereas Apache Superset targets interactive SQL BI exploration over data warehouses and lakehouses.
Q2EasyAssignment

What is Streamlit? How does it differ from a traditional web framework like Flask? When is it appropriate for a data engineer to use Streamlit?

Reveal Worked Solution
Streamlit turns pure Python scripts into reactive data apps without HTML/JS boilerplate, unlike Flask which requires manual routing and templates, making Streamlit great for internal ML prototypes.
Q1IntermediateExam

Design a Grafana dashboard for monitoring a Spark Structured Streaming job. List five metrics you would display (include latency, throughput, lag, state size) and explain what alert thresholds you would set for each.

Reveal Worked Solution
Track input rows/sec, micro-batch duration ms, Kafka consumer offset lag, state store memory MB, and watermark delay, alerting when batch duration exceeds trigger interval or consumer lag grows monotonically.
Q1AdvancedProject

Build a real-time executive dashboard specification for a ride-hailing company. The dashboard must update every 30 seconds and show: active rides, revenue per hour, driver availability by region, and surge pricing zones. Specify the data flow from Kafka through Spark Streaming to the visualisation layer, including where to cache hot data.

Reveal Worked Solution
Stream ride events from Kafka through Spark Structured Streaming into Redis (for 30-second hot region counts) and Delta Gold tables (for hourly revenue), powering Grafana/Superset panels with sub-second Redis reads.
Lab 10

Distributed ML with Spark MLlib & Ray


Q1EasyAssignment

What is the MLlib Pipeline API? What are Transformers and Estimators? Give one example of each.

Reveal Worked Solution
A Transformer maps a DataFrame to a DataFrame (VectorAssembler); an Estimator calls fit() on training data to produce a Transformer (RandomForestClassifier). Pipelines chain both cleanly without fold leakage.
Q2EasyQuiz

What is Ray? How does it differ from Spark for distributed computing? What is Ray Tune used for?

Reveal Worked Solution
Ray executes general stateful actor/task graphs across Python clusters with low task latency, complementing Spark's SQL ETL engine; Ray Tune runs distributed hyperparameter search.
Q1IntermediateAssignment

Write a Spark MLlib pipeline to train a classification model on a 10 GB customer churn dataset: include StringIndexer, VectorAssembler, and a RandomForestClassifier. Evaluate with cross-validation. How would you scale this to 1 TB?

Reveal Worked Solution
Chain StringIndexer -> OneHotEncoder -> VectorAssembler -> RandomForestClassifier inside CrossValidator; to scale to 1 TB, sample stratified tuning subsets, repartition cleanly, or move gradient boosting to Ray XGBoost.
Q2IntermediateExam

Explain distributed hyperparameter tuning with Ray Tune. What is the ASHA (Asynchronous Successive Halving Algorithm) scheduler? How does it reduce compute cost compared to grid search?

Reveal Worked Solution
ASHA promotes only top-performing trials at exponential rung budgets while terminating weak trials asynchronously, cutting compute waste vs. exhaustive grid search.
Q1AdvancedProject

You need to train a gradient boosting model on 500 GB of tabular data. Compare three approaches: (a) Spark MLlib GBT, (b) XGBoost on Ray, (c) LightGBM on a single large machine. Discuss training time, memory requirements, prediction latency, and operational complexity for each.

Reveal Worked Solution
Spark MLlib GBT integrates natively inside Spark ETL; XGBoost on Ray achieves faster distributed histogram tree training; single-node LightGBM minimizes cluster ops if 500 GB compresses/samples into high-RAM hardware.
Lab 11

MLOps with MLflow


Q1EasyAssignment

What are the four main components of MLflow (Tracking, Projects, Models, Registry)? Briefly describe what each does.

Reveal Worked Solution
Tracking (params/metrics/artifacts), Projects (reproducible packaging), Models (standardized inference flavor), and Model Registry (versioned stage governance).
Q2EasyQuiz

What is a model registry? What lifecycle stages does MLflow's Model Registry support (Staging, Production, Archived)? Who should approve a model promotion to Production?

Reveal Worked Solution
A centralized catalog mapping registered model names to numbered versions and stages (None, Staging, Production, Archived); CI quality gates plus ML lead sign-off approve Production promotions.
Q1IntermediateAssignment

Write Python code using the MLflow API to: log a training run (parameters, metrics, artifacts), register the resulting model, compare two model versions using logged metrics, and programmatically promote the better model to Production.

Reveal Worked Solution
Wrap training in with mlflow.start_run(): mlflow.log_params(...); mlflow.log_metric('f1', ...); mlflow.sklearn.log_model(..., registered_model_name='churn'), query MlflowClient().search_runs(), and call transition_model_version_stage(..., stage='Production').
Q2IntermediateExam

Explain model versioning in an MLOps workflow. What metadata should be recorded with every model version to ensure reproducibility? How do you roll back to a previous model version if the new one degrades in production?

Reveal Worked Solution
Record Git commit SHA, Delta table version hash, conda/Docker environment lockfile, hyperparameters, and validation metrics; roll back immediately by reassigning the Production alias/stage to the prior archived version.
Q1AdvancedProject

Design a complete MLOps pipeline for a credit scoring model. Cover: data versioning with Delta Lake, experiment tracking with MLflow, CI/CD model validation gates, A/B deployment with canary rollout, and real-time performance monitoring with automatic rollback triggers. What metrics would you monitor post-deployment?

Reveal Worked Solution
Pin training sets to Delta table versions, track candidates in MLflow, gate CI promotion on precision/latency/fairness tests, roll out via 5% canary traffic, monitor PSI feature drift and default calibration, and trigger auto-rollback if p99 latency or error rates breach thresholds.
Labs 12–13

Model Deployment, Monitoring & Governance


Q1EasyAssignment

What is BentoML? What does "packaging a model" mean in the context of BentoML? What is a Bento?

Reveal Worked Solution
BentoML packages trained models, preprocessing logic, and dependency definitions into a standardized deployable archive called a Bento for REST/gRPC serving.
Q2EasyQuiz

What is OpenLineage? What is data lineage and why is it important for regulated industries (healthcare, finance)?

Reveal Worked Solution
OpenLineage is an open specification capturing dataset-to-job execution provenance across Spark, Airflow, and dbt, providing auditable traceability required in finance and healthcare.
Q3EasyAssignment

What is a Prometheus metric? Describe the four metric types (Counter, Gauge, Histogram, Summary) and give a Big Data example for each.

Reveal Worked Solution
Counter (monotonic total: requests_total), Gauge (current level: kafka_lag), Histogram (bucketed latencies for quantiles: inference_duration_ms), Summary (client-side streaming quantiles).
Q1IntermediateAssignment

Package an MLflow model as a BentoML REST API service: write the service definition, define input/output schemas, add Prometheus metrics instrumentation, and write a Dockerfile to containerise it. What endpoints does BentoML expose by default?

Reveal Worked Solution
Load the MLflow model inside a @bentoml.service class exposing a typed @bentoml.api predict method, export Prometheus counters/histograms on /metrics, and containerize via bentoml containerize (exposing /readyz and /livez).
Q2IntermediateExam

Explain model drift vs. data drift. How would you detect each in production? Describe a monitoring pipeline using Prometheus and Grafana to alert when prediction distribution shifts by more than 10%.

Reveal Worked Solution
Data drift shifts input feature distributions (detected via PSI or KS tests), whereas concept/model drift shifts the relationship between features and target (detected via delayed-label accuracy drop). Scrape feature histograms into Prometheus and alert on Grafana when shift exceeds 10%.
Q1AdvancedProject

A production ML system serves 10,000 requests per second. Design a scalable serving architecture using BentoML with auto-scaling on Kubernetes. Include: load balancing, request batching for GPU efficiency, circuit breakers, canary deployment for new model versions, and an alerting strategy for latency SLA violations (p99 < 50 ms).

Reveal Worked Solution
Deploy stateless BentoML workers behind Kubernetes HorizontalPodAutoscaler with adaptive micro-batching enabled for GPU/CPU throughput, circuit breakers on downstream feature stores, canary traffic splitting, and Prometheus alerts whenever p99 latency exceeds 50 ms.