mayursurani.medium.com 93 min read Original Source

The Lead Data Engineer Interview: 100 Questions, Answered

A complete, field-tested preparation guide for senior data engineering roles — from advanced SQL and Spark tuning to AWS architecture, data modelling, infrastructure-as-code, and the leadership questions most candidates underestimate.

I have sat on both sides of the interview table for senior data engineering roles, and I have learned that the difference between a good candidate and a hired candidate is rarely raw technical ability. It is preparation with intent — knowing what a Lead-level role actually tests, and being able to justify every architectural and tuning decision you make, not just name the tools you have used.

This guide is the result of that observation. It is a curated set of 100 interview questions and answers, built around a real Lead Data Engineer job description at a data-focused consulting practice — one that hires on advanced SQL, Python, PySpark, Hive, a defined AWS stack, Terraform, CI/CD, shell scripting, and, crucially, leadership and client-facing delivery.

Every question here is mapped to something an interviewer actually asks. Every answer is written the way I would give it in a live round: structured, opinionated, measured, and tied back to a business outcome.

If you are preparing for a senior or lead data engineering role — especially at a consulting firm where you will be both the person designing the architecture and the person who owns the client relationship — this is the breadth you need to cover. Keep it open as a reference, or read it end to end as a study plan.

A note on how this was built._ The original material was assembled around one specific job description and an anonymized candidate profile. All company names, employer names and personal identifiers have been removed; the technical content is generic and applies to any senior data engineering interview. Treat process specifics as indicative guidance rather than an official description, and use this to be thoroughly prepared and honest — not to memorise a script. The strongest answer is always the one backed by something you have genuinely built._

How to use this guide

  • If you have a week: work through one major section per day — SQL, Python, Spark, Big Data/Hive, AWS, modelling, infrastructure and delivery, shell, then leadership. Finish with the 60-minute cheat sheet.
  • If you have a day: read the “Shape of the Role” and “Mapping Your Experience” sections first, then skim every question’s headline answer. Depth wins on the questions you are asked; breadth keeps you safe on the ones you are not.
  • If you have an hour: go straight to the 60-Minute Cheat Sheet at the end, then come back to the sections that expose gaps.

Each question follows the same structure: a short framing of what is really being tested, a detailed answer, and — where it matters — a one-line “interview tip” that captures the sentence I would want to land.

Part I — The Shape of the Role

Before a single technical question is asked, understand what a Lead Data Engineer is actually hired to do. The job description usually reads as a pie chart, and reading it that way tells you where to weight your preparation.

┌──────────────────────────────────────────────────────────────────────┐
│              LEAD DATA ENGINEER — WHAT YOU ACTUALLY DO               │
├──────────────────────────────────────────────────────────────────────┤
│                                                                      │
│   30%  HANDS-ON DATA PIPELINE ENGINEERING                            │
│         "Design and create fault-tolerant data pipelines             │
│          running on cluster" — PySpark, Spark SQL, Python, Hive      │
│                                                                      │
│   25%  SOLUTION ARCHITECTURE & DATA MODELLING                        │
│         "Design data engineering solutions end to end...             │
│          scalable and modular solutions"                             │
│                                                                      │
│   20%  STAKEHOLDER & REQUIREMENTS MANAGEMENT                         │
│         "Communicate with users, technical teams and senior          │
│          management... convert to user stories"                      │
│                                                                      │
│   15%  PERFORMANCE OPTIMIZATION & TUNING                             │
│         "Debugging, tuning and optimizing PySpark pipelines...       │
│          Spark UI, DAG, config parameters"                           │
│                                                                      │
│   10%  PRACTICE ALIGNMENT, QUALITY, SECURITY & COMPLIANCE            │
│         "Adherence with best practices... with the Enterprise        │
│          Data & Analytics Architect"                                 │
│                                                                      │
└──────────────────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────────────────┐
│              LEAD DATA ENGINEER — WHAT YOU ACTUALLY DO               │
├──────────────────────────────────────────────────────────────────────┤
│                                                                      │
│   30%  HANDS-ON DATA PIPELINE ENGINEERING                            │
│         "Design and create fault-tolerant data pipelines             │
│          running on cluster" — PySpark, Spark SQL, Python, Hive      │
│                                                                      │
│   25%  SOLUTION ARCHITECTURE & DATA MODELLING                        │
│         "Design data engineering solutions end to end...             │
│          scalable and modular solutions"                             │
│                                                                      │
│   20%  STAKEHOLDER & REQUIREMENTS MANAGEMENT                         │
│         "Communicate with users, technical teams and senior          │
│          management... convert to user stories"                      │
│                                                                      │
│   15%  PERFORMANCE OPTIMIZATION & TUNING                             │
│         "Debugging, tuning and optimizing PySpark pipelines...       │
│          Spark UI, DAG, config parameters"                           │
│                                                                      │
│   10%  PRACTICE ALIGNMENT, QUALITY, SECURITY & COMPLIANCE            │
│         "Adherence with best practices... with the Enterprise        │
│          Data & Analytics Architect"                                 │
│                                                                      │
└──────────────────────────────────────────────────────────────────────┘

The five pillars of the job description, decoded

The consulting twist: governance and “governed data products”

Because a role like this usually sits inside a consulting practice built on cloud-native lakehouses and governed data products, you will constantly face:

  • Client-owned data with real compliance constraints — you must speak PII, masking, IAM/Lake Formation, encryption and auditability fluently.
  • Mixed batch and streaming estates — some clients are still on Hive/Sqoop batch; others want near-real-time Kafka/Kinesis. You must be credible in both.
  • Cost as a first-class concern — engagements are priced, so cost-per-record is a design constraint, not an afterthought.
  • Multi-tenant delivery — you will likely work across several client accounts, so modularity and reuse of frameworks matter enormously.

Your unfair advantage, whichever side of the table you are on: a metadata-driven ingestion framework (configuration over code), a Medallion lakehouse with data-quality gating, streaming with schema governance, cost-tuned Spark, and a leadership record. Frame yourself as the person who can drop into a client environment on day one and start designing.

Part II — The Interview Loop, and How to Prepare for It

A data-consulting interview process is typically multi-stage and fast-moving. The structure below is indicative and drawn from common patterns — treat it as a map, not a promise.

Critical implications:

  1. You may get to choose Python or SQL for the first technical round — but do not skip the other. Lead candidates are expected to be fluent in both. This guide covers both to full depth.
  2. The stack is not a wish list — the firm delivers on real AWS services, so expect specific, practical questions, not textbook definitions.
  3. Big Data and SQL heritage means traditional data-warehouse concepts (Hive, partitioning, dimensional modelling, warehouse distribution keys) are fair game. Prepare them as seriously as Spark.
  4. The Lead dimension is real. They will probe how you decompose work, review code, gather requirements and influence stakeholders — not just whether you can write a window function.
  5. Breadth beats a single deep niche. Given a fast, multi-round process, prepare wide across SQL → Python → PySpark → Hive/Hadoop → AWS → modelling → IaC → leadership.

Part III — Mapping Your Experience to the Job Description

The requirements you must be able to speak to

Before the interview, identify the requirements that map directly to what you have done, and rehearse a proof point for each. In a lead role the interviewer is not checking boxes — they are listening for evidence.

The gap-closing playbook (the honest gaps)

Do not bluff — good interviewers test the stack practically. For each gap, use Acknowledge → Map → Commit.

Gap 1 — Scheduling tools you have not used (e.g. Autosys, CA Workload Automation)

You orchestrate with Airflow, Step Functions and workflow tools, not legacy schedulers.

❌ BAD:  "Yes, I've used Autosys heavily."
✅ GOOD: "My orchestration is Airflow, AWS Step Functions and managed workflows.
          The scheduling concepts — job dependencies, calendars, conditional
          triggers, retries, alerting, critical-path SLAs — map one-to-one onto
          Autosys or CA Workload Automation. Autosys is a JIL-defined schedule;
          Airflow is a Python DAG. It's a matter of days to be productive,
          not months, and I've migrated logic between orchestrators before."
❌ BAD:  "Yes, I've used Autosys heavily."
✅ GOOD: "My orchestration is Airflow, AWS Step Functions and managed workflows.
          The scheduling concepts — job dependencies, calendars, conditional
          triggers, retries, alerting, critical-path SLAs — map one-to-one onto
          Autosys or CA Workload Automation. Autosys is a JIL-defined schedule;
          Airflow is a Python DAG. It's a matter of days to be productive,
          not months, and I've migrated logic between orchestrators before."

Gap 2 — On-prem Hadoop depth (if your Hadoop exposure is primarily Hive/Spark on cloud)

✅ GOOD: "My hands-on Hadoop is Hive/Spark on managed clusters — Hive metastore,
          partitioning, ORC/Parquet, HDFS-style layout on object storage, and
          YARN-based resource sharing. I understand NameNode/DataNode/block-
          replication theory and MapReduce mechanics well enough to reason about
          and migrate on-prem workloads, but my production depth is on managed
          cloud clusters. For a lead role, I'd pair that with someone deep on
          on-prem operations and own the architecture and migration design."
✅ GOOD: "My hands-on Hadoop is Hive/Spark on managed clusters — Hive metastore,
          partitioning, ORC/Parquet, HDFS-style layout on object storage, and
          YARN-based resource sharing. I understand NameNode/DataNode/block-
          replication theory and MapReduce mechanics well enough to reason about
          and migrate on-prem workloads, but my production depth is on managed
          cloud clusters. For a lead role, I'd pair that with someone deep on
          on-prem operations and own the architecture and migration design."

Gap 3 — Aligning with an enterprise architecture function (a behavioural gap)

Some job descriptions say you work closely with an Enterprise Data & Analytics Architect and engineering practice leads. Show you have done cross-team standard-setting:

“On my last platform I owned ingestion and lakehouse architecture and had to align with platform, security and analytics leads on naming standards, DQ contracts and access patterns. I treat an enterprise architect as a partner — I bring implementation reality to their standards, and I adopt their guardrails even when they slow a sprint, because consistency across client accounts is the whole point of a central architecture function.”

A risk register — the questions that could expose you

Part IV — The Stack at a Glance

Memorise this map. Every keyword in a data-engineering JD should trigger a one-line “what I’d say” reflex.

Part V — Introductions & “Tell Me About Yourself”

The one-liner (recruiter screen)

“I’m a Lead Data Engineer with 8+ years building cloud data platforms — PySpark, Spark SQL, managed Spark, warehousing, and Kafka streaming — processing tens of millions of records a day, and I lead a team of engineers.”

The 60-second version (recommended for round 1)

“I’m a Lead Data Engineer with 8+ years across data engineering and analytics on AWS.

Three things define my profile. First, I build at scale: I architected an enterprise lakehouse using a Medallion architecture that processes tens of millions of records a day at very high accuracy — PySpark on managed Spark, a serverless ETL tier, a warehouse, and Kafka streaming with a Schema Registry for zero data loss.

Second, I optimize hard: I tuned Spark jobs with AQE, broadcast joins and partition pruning to cut compute cost by a quarter and storage by a fifth, and I build fault-tolerant, DQ-gated pipelines that reduced failures by roughly a third.

Third, I lead and face stakeholders: I run a team, design end-to-end solutions, and work directly with business owners to turn requirements into technical specs — including a natural-language layer that lets business users query hundreds of source systems directly.

That mix — hands-on PySpark, cloud architecture, and client-facing leadership — is exactly what a Lead Data Engineer role describes.”

The 90-second version (full narrative — use for later rounds)

“I lead data engineering and I’ve spent 8+ years in three acts.

Act one was at a large retail bank, where I built ETL/ELT on managed Spark, serverless ETL and Lambda for retail assets, payments and risk; designed warehouse data marts that cut reporting turnaround by 40%; and put machine-learning models into production for segmentation, risk scoring and customer lifetime value — driving significant measurable business impact.

Act two is a global financial-services consultancy, where I built the platform layer. I architected an enterprise data lakehouse on AWS — Medallion architecture, Bronze to Gold — processing tens of millions of records per day at very high accuracy. I built a metadata-driven ingestion framework with configurable wrappers that cut onboarding time by 40%, implemented Kafka streaming with a Schema Registry for zero data loss, added multi-layer data-quality checks that reduced pipeline failures by a third, and applied fine-grained governance. I tuned serverless PySpark with AQE, broadcast joins and partition pruning to cut compute cost by a quarter, and I lead a team of engineers.

Act three is where I am now: applied AI on top of the platform — a retrieval-augmented system over hundreds of source systems letting business users query data in natural language, plus an agentic data-engineering platform with cost routing and SQL safety guardrails.

Why this role? The practice is built on exactly this — cloud-native lakehouses, real-time streaming and governed data products on AWS. I bring the PySpark depth, the cloud architecture, the cost-optimization discipline and the client-facing leadership to design and deliver those platforms end to end.”

The elevator pitch (staircase variant — great for panels)

“Lead Data Engineer. 8+ years. Tens of millions of records a day at high accuracy. PySpark on managed Spark and serverless ETL. Warehousing and Athena. Kafka streaming. A quarter lower compute cost. A team of six. That’s what I’d bring.”

Part VI — The 100 Questions

Fourteen sections and one hundred questions, mapped to every skill a Lead Data Engineer role tests. Read them in order, or jump straight to the area you need most.

1. Advanced SQL

Why this section exists:_ Advanced SQL is usually the first skill listed in the job description, and the first technical round often lets you choose SQL or Python. Either way, a Lead Data Engineer is expected to be fluent and fast. Answer these with confidence — and where possible, sketch the query._

Q1: What is the logical order in which SQL clauses are executed, and why does it matter?

Description: Interviewers use this to separate people who memorised SQL syntax from people who understand it. The practical value: it explains why you can’t use a SELECT alias in a WHERE clause, and why window functions are evaluated so late.

Detailed Answer:

The logical processing order (not the written order) is:

FROM / JOIN  →  WHERE  →  GROUP BY  →  HAVING  →  SELECT  →  DISTINCT
             →  ORDER BY  →  LIMIT / OFFSET   (+ window functions run after HAVING, with SELECT)
FROM / JOIN  →  WHERE  →  GROUP BY  →  HAVING  →  SELECT  →  DISTINCT
             →  ORDER BY  →  LIMIT / OFFSET   (+ window functions run after HAVING, with SELECT)

Why it matters in practice: WHERE alias = ... fails because the alias doesn’t exist yet at step 2, while ORDER BY alias works because it runs at step 7. HAVING SUM(x) > 100 is legal; WHERE SUM(x) > 100 is not. Understanding this lets you predict plan behaviour and debug “invalid identifier” errors instantly.

Interview tip: “The takeaway for optimization is that WHERE runs before GROUP BY — so pushing filters as early as possible reduces the volume that aggregation and shuffles chew on. That’s the same instinct behind partition pruning in Spark.”

Q2: Explain the types of JOINs. How does each behave on duplicate keys and unmatched rows?

Description: Foundational, but a Lead is expected to add the data-quality dimension — a join that silently multiplies rows is one of the most common production bugs.

Detailed Answer:

he duplicate-key discipline (say this): Before joining a large fact to a dimension, I verify the dimension’s join key is unique — SELECT key, COUNT(*) FROM dim GROUP BY key HAVING COUNT(*) > 1. If it isn’t, either I de-duplicate first (window ROW_NUMBER), or I intend the fan-out and account for it with SUM/COUNT(DISTINCT).

Semi/anti joins: In Spark, LEFT SEMI JOIN keeps only left columns where a match exists (“customers who ordered”); LEFT ANTI gives the opposite (“customers who never ordered”). Both avoid the fan-out and extra shuffle columns of a full join.

Q3: What are window functions, and when would you use them over GROUP BY?

Description: The single most tested advanced-SQL topic in data-engineering interviews. Be ready to write one from memory.

Detailed Answer:

A window function computes across a set of rows related to the current row without collapsing them — unlike GROUP BY, which returns one row per group.

-- Running total of revenue per customer, ordered by day
SELECT
    customer_id,
    order_date,
    revenue,
    SUM(revenue) OVER (
        PARTITION BY customer_id
        ORDER BY order_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_revenue,
    AVG(revenue) OVER (PARTITION BY customer_id) AS avg_revenue
FROM orders;
-- Running total of revenue per customer, ordered by day
SELECT
    customer_id,
    order_date,
    revenue,
    SUM(revenue) OVER (
        PARTITION BY customer_id
        ORDER BY order_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_revenue,
    AVG(revenue) OVER (PARTITION BY customer_id) AS avg_revenue
FROM orders;

Anatomy of the OVER clause:

  • PARTITION BY — the “group” (like GROUP BY, but rows survive)
  • ORDER BY — ordering within the partition (required for cumulative/ranking functions)
  • Frame — ROWS / RANGE between bounds (e.g. ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING for a 3-row moving average)

When to prefer window over GROUP BY:

Performance note (Lead-level): Window functions require a sort/shuffle by the partition key — often the most expensive operator in a query. Minimise window columns, filter before the window where possible, and choose a well-distributed PARTITION BY key to avoid skew.

Q4: Difference between ROW_NUMBER(), RANK() and DENSE_RANK()? Show the de-duplication pattern.

Description: A classic with a practical follow-up: they want the de-duplication use case, because it appears in almost every real pipeline.

Detailed Answer:

For values 10, 20, 20, 30:

  • ROW_NUMBER() — unique, sequential, never ties (breaks ties arbitrarily via the ORDER BY).
  • RANK() — ties share a rank, then skips (gaps).
  • DENSE_RANK() — ties share a rank, no gaps.

De-duplication pattern (keep the latest record per key):

WITH ranked AS (
    SELECT *,
           ROW_NUMBER() OVER (
               PARTITION BY customer_id
               ORDER BY updated_at DESC
           ) AS rn
    FROM raw.customers
)
SELECT * FROM ranked WHERE rn = 1;
WITH ranked AS (
    SELECT *,
           ROW_NUMBER() OVER (
               PARTITION BY customer_id
               ORDER BY updated_at DESC
           ) AS rn
    FROM raw.customers
)
SELECT * FROM ranked WHERE rn = 1;

ROW_NUMBER() is the correct choice here because you want exactly one survivor per key — RANK()/DENSE_RANK() leave duplicates when ties exist on updated_at. Add a secondary sort column (e.g. ingest id) to make the tie-break deterministic.

Q5: How would you find and remove duplicates from a very large table?

Description: Tests both SQL and engineering judgment — on billions of rows you cannot just DELETE naively.

Detailed Answer:

Step 1 — Detect the scale of the problem (cheap aggregation):

1
ORDER BY c DESC LIMIT 100;” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

SELECT customer_id, COUNT(*) AS c
FROM fact_orders
GROUP BY customer_id, order_date, amount
HAVING COUNT(*) > 1
ORDER BY c DESC LIMIT 100;
SELECT customer_id, COUNT(*) AS c
FROM fact_orders
GROUP BY customer_id, order_date, amount
HAVING COUNT(*) > 1
ORDER BY c DESC LIMIT 100;

Step 2 — Profile root cause before deleting: duplicates usually come from a non-idempotent re-run (a job that appends instead of upserts), a fan-out join, or late-arriving corrections. Fixing the cause matters more than cleaning the symptom — I state that explicitly in an interview.

Step 3 — Remove safely with a window function, writing to a new table (never destructive in place on a huge table):

CREATE TABLE fact_orders_dedup AS
SELECT * EXCLUDE (rn) FROM (
    SELECT *, ROW_NUMBER() OVER (
        PARTITION BY order_id
        ORDER BY load_ts DESC, ingest_id DESC
    ) AS rn
    FROM fact_orders
) WHERE rn = 1;
CREATE TABLE fact_orders_dedup AS
SELECT * EXCLUDE (rn) FROM (
    SELECT *, ROW_NUMBER() OVER (
        PARTITION BY order_id
        ORDER BY load_ts DESC, ingest_id DESC
    ) AS rn
    FROM fact_orders
) WHERE rn = 1;

Step 4 — Prove it and promote:

SELECT COUNT(*) - COUNT(DISTINCT order_id) AS remaining_dupes FROM fact_orders_dedup;
-- then atomic swap / partition overwrite
SELECT COUNT(*) - COUNT(DISTINCT order_id) AS remaining_dupes FROM fact_orders_dedup;
-- then atomic swap / partition overwrite

Scale tactics to mention:

  • Operate partition by partition (e.g. per order_date) to bound the shuffle and allow re-runnable chunks.
  • On a warehouse, use DELETE ... USING or a CTAS + swap; run VACUUM/ANALYZE after.
  • On Spark, partition-overwrite the target (spark.sql.sources.partitionOverwriteMode=dynamic) so the rewrite is atomic per partition.
  • Prevent recurrence: make the load idempotent (MERGE/upsert by business key, or partition-overwrite) — see Q82.

Q6: CTE vs subquery vs temp table vs view — what are the differences and performance implications?

Description: Tests whether you understand that these are not interchangeable, and whether you think about the optimizer.

Detailed Answer:

Performance nuances to raise at Lead level:

  • A CTE referenced twice may be re-executed twice in engines that inline it — if it’s expensive, a temp table (or a MATERIALIZED CTE hint where supported) pays for itself.
  • CTEs are excellent for readability and reviewability — in a consulting practice with shared code, that’s real engineering value.
  • Some engines treat CTEs as optimization fences that block predicate pushdown; if a query gets slower when wrapped in a CTE, that’s the cause — check the plan.
  • A view is not a performance tool; it’s a contract/abstraction tool. Use materialised views for performance.

Interview tip: “I default to CTEs for clarity and review, then promote a hot intermediate to a temp/materialised table when the plan shows it being recomputed.”

Q7: Write a query for the Nth-highest salary. And top-N per group.

Description: The most-asked classic; they then escalate to “per group”, which many candidates fumble.

Detailed Answer:

Nth highest salary — modern answer (window function):

SELECT DISTINCT salary
FROM (
    SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
    FROM employees
) t
WHERE rnk = 3;   -- 3rd highest
SELECT DISTINCT salary
FROM (
    SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
    FROM employees
) t
WHERE rnk = 3;   -- 3rd highest

Use DENSE_RANK() so ties don’t artificially “consume” a rank; use ROW_NUMBER() if you want a strict positional Nth.

Classic alternatives to mention briefly:

= e1.salary);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

-- Offsets (fragile with ties)
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 2;

-- Correlated count (portable, less efficient)
SELECT MAX(salary) FROM employees e1
WHERE 3 = (SELECT COUNT(DISTINCT salary) FROM employees e2 WHERE e2.salary >= e1.salary);
-- Offsets (fragile with ties)
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 2;

-- Correlated count (portable, less efficient)
SELECT MAX(salary) FROM employees e1
WHERE 3 = (SELECT COUNT(DISTINCT salary) FROM employees e2 WHERE e2.salary >= e1.salary);

Top-N per group (the real interview target):

<button data-code="SELECT * FROM (
SELECT
department_id,
employee_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS rn
FROM employees
) t
WHERE rn

SELECT * FROM (
    SELECT
        department_id,
        employee_id,
        salary,
        ROW_NUMBER() OVER (
            PARTITION BY department_id
            ORDER BY salary DESC
        ) AS rn
    FROM employees
) t
WHERE rn <= 3;   -- top 3 earners per department
SELECT * FROM (
    SELECT
        department_id,
        employee_id,
        salary,
        ROW_NUMBER() OVER (
            PARTITION BY department_id
            ORDER BY salary DESC
        ) AS rn
    FROM employees
) t
WHERE rn <= 3;   -- top 3 earners per department

The same SQL works in Spark SQL; in the DataFrame API use a Window.partitionBy("department_id").orderBy(desc("salary")) — see Q45.

Q8: Explain SCD Types 1, 2 and 3. How would you implement SCD Type 2 in SQL?

Description: Data-modelling is an explicit JD requirement, and SCD2 is the canonical test. Be ready to write the MERGE.

Detailed Answer:

SCD Type 2 implementation pattern:

<button data-code="– dimension has: sk (surrogate), nk (business key), attrs,
— valid_from, valid_to, is_current

— 1) Expire changed current rows
UPDATE dim_customer d
SET valid_to = CURRENT_DATE – 1,
is_current = FALSE
FROM staging_customer s
WHERE d.nk = s.nk
AND d.is_current = TRUE
AND (d.plan s.plan OR d.address s.address);
— 2) Insert the new version for changed-or-new keys
INSERT INTO dim_customer (nk, plan, address, valid_from, valid_to, is_current)
SELECT s.nk, s.plan, s.address, CURRENT_DATE, '9999-12-31', TRUE
FROM staging_customer s
LEFT JOIN dim_customer d
ON d.nk = s.nk AND d.is_current = TRUE
WHERE d.nk IS NULL — brand-new key
OR (d.plan s.plan OR d.address s.address); — changed key” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

-- dimension has: sk (surrogate), nk (business key), attrs,
--                valid_from, valid_to, is_current

-- 1) Expire changed current rows
UPDATE dim_customer d
SET valid_to = CURRENT_DATE - 1,
    is_current = FALSE
FROM staging_customer s
WHERE d.nk = s.nk
  AND d.is_current = TRUE
  AND (d.plan <> s.plan OR d.address <> s.address);
-- 2) Insert the new version for changed-or-new keys
INSERT INTO dim_customer (nk, plan, address, valid_from, valid_to, is_current)
SELECT s.nk, s.plan, s.address, CURRENT_DATE, '9999-12-31', TRUE
FROM staging_customer s
LEFT JOIN dim_customer d
  ON d.nk = s.nk AND d.is_current = TRUE
WHERE d.nk IS NULL                              -- brand-new key
   OR (d.plan <> s.plan OR d.address <> s.address);   -- changed key
-- dimension has: sk (surrogate), nk (business key), attrs,
--                valid_from, valid_to, is_current

-- 1) Expire changed current rows
UPDATE dim_customer d
SET valid_to = CURRENT_DATE - 1,
    is_current = FALSE
FROM staging_customer s
WHERE d.nk = s.nk
  AND d.is_current = TRUE
  AND (d.plan <> s.plan OR d.address <> s.address);
-- 2) Insert the new version for changed-or-new keys
INSERT INTO dim_customer (nk, plan, address, valid_from, valid_to, is_current)
SELECT s.nk, s.plan, s.address, CURRENT_DATE, '9999-12-31', TRUE
FROM staging_customer s
LEFT JOIN dim_customer d
  ON d.nk = s.nk AND d.is_current = TRUE
WHERE d.nk IS NULL                              -- brand-new key
   OR (d.plan <> s.plan OR d.address <> s.address);   -- changed key

n Spark it’s cleaner as a single MERGE (Delta/Iceberg) or a two-pass DataFrame job. Key design points to volunteer: use a surrogate key for the dimension, open-ended valid_to = '9999-12-31' for the current row, a boolean is_current for fast filtering, and handle late-arriving dimension rows (see Q81).

Q9: How do you solve a “gaps and islands” or sessionization problem in SQL?

Description: A favourite for separating strong SQL users. It tests window functions combined with clever grouping.

Detailed Answer:

Problem: given web events, group them into sessions where a new session starts if the gap from the previous event exceeds 30 minutes.

INTERVAL '30 minutes'
THEN 1 ELSE 0 END AS is_new_session
FROM ordered
),
sessionised AS (
SELECT *,
SUM(is_new_session) OVER (
PARTITION BY user_id ORDER BY event_ts
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS session_id
FROM flagged
)
SELECT user_id, session_id,
MIN(event_ts) AS session_start,
MAX(event_ts) AS session_end,
COUNT(*) AS n_events
FROM sessionised
GROUP BY user_id, session_id;” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

WITH ordered AS (
    SELECT user_id, event_ts,
           LAG(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts) AS prev_ts
    FROM events
),
flagged AS (
    SELECT *,
           CASE WHEN prev_ts IS NULL
                  OR event_ts - prev_ts > INTERVAL '30 minutes'
                THEN 1 ELSE 0 END AS is_new_session
    FROM ordered
),
sessionised AS (
    SELECT *,
           SUM(is_new_session) OVER (
               PARTITION BY user_id ORDER BY event_ts
               ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
           ) AS session_id
    FROM flagged
)
SELECT user_id, session_id,
       MIN(event_ts) AS session_start,
       MAX(event_ts) AS session_end,
       COUNT(*)      AS n_events
FROM sessionised
GROUP BY user_id, session_id;
WITH ordered AS (
    SELECT user_id, event_ts,
           LAG(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts) AS prev_ts
    FROM events
),
flagged AS (
    SELECT *,
           CASE WHEN prev_ts IS NULL
                  OR event_ts - prev_ts > INTERVAL '30 minutes'
                THEN 1 ELSE 0 END AS is_new_session
    FROM ordered
),
sessionised AS (
    SELECT *,
           SUM(is_new_session) OVER (
               PARTITION BY user_id ORDER BY event_ts
               ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
           ) AS session_id
    FROM flagged
)
SELECT user_id, session_id,
       MIN(event_ts) AS session_start,
       MAX(event_ts) AS session_end,
       COUNT(*)      AS n_events
FROM sessionised
GROUP BY user_id, session_id;

The core trick: LAG flags boundaries (1/0), then a cumulative SUM of the flag creates a monotonic group id — the “island” label. Everything else is a normal GROUP BY.

Related “gaps” variant — consecutive dates:

SELECT MIN(d) AS range_start, MAX(d) AS range_end
FROM (
  SELECT d, d - INTERVAL '1 day' * ROW_NUMBER() OVER (ORDER BY d) AS grp
  FROM (SELECT DISTINCT login_date AS d FROM logins) x
) y
GROUP BY grp;
SELECT MIN(d) AS range_start, MAX(d) AS range_end
FROM (
  SELECT d, d - INTERVAL '1 day' * ROW_NUMBER() OVER (ORDER BY d) AS grp
  FROM (SELECT DISTINCT login_date AS d FROM logins) x
) y
GROUP BY grp;

Spark note: the same pattern works in Spark SQL; in the DataFrame API use lag() and a Window.rowsBetween(Window.unboundedPreceding, Window.currentRow) for the cumulative sum.

Q10: Explain GROUPING SETS, CUBE and ROLLUP.

Description: Tests breadth of aggregation knowledge — used constantly for multi-level reports.

Detailed Answer:

These produce multiple grouping levels in one pass instead of unioning several GROUP BY queries.

SELECT region, product, SUM(sales)
FROM fact_sales
GROUP BY CUBE(region, product);      -- (region,product), (region), (product), ()
-- ROLLUP(region, product)             → (region,product), (region), ()
-- GROUPING SETS((region),(product),()) → exactly those three
SELECT region, product, SUM(sales)
FROM fact_sales
GROUP BY CUBE(region, product);      -- (region,product), (region), (product), ()
-- ROLLUP(region, product)             → (region,product), (region), ()
-- GROUPING SETS((region),(product),()) → exactly those three

Practical points:

  • Far faster and cheaper than UNION ALL of multiple aggregations — one shuffle instead of many.
  • GROUPING(col) returns 1 when the column is NULL because of the rollup (not because of real data) — invaluable for labelling subtotal rows correctly.
  • In a warehouse, GROUPING SETS is my default; CUBE only when I genuinely need every combination (it explodes as 2ⁿ).

Q11: How do you pivot and unpivot data in SQL?

Description: Very common in reporting extensions and when reshaping survey/metric data.

Detailed Answer:

PIVOT (long → wide):

-- Redshift / modern warehouse syntax
SELECT * FROM (
    SELECT region, quarter, sales FROM fact_sales
)
PIVOT (SUM(sales) FOR quarter IN ('Q1','Q2','Q3','Q4'));
-- Redshift / modern warehouse syntax
SELECT * FROM (
    SELECT region, quarter, sales FROM fact_sales
)
PIVOT (SUM(sales) FOR quarter IN ('Q1','Q2','Q3','Q4'));

Portable CASE-based pivot (works anywhere):

SELECT region,
       SUM(CASE WHEN quarter='Q1' THEN sales ELSE 0 END) AS q1,
       SUM(CASE WHEN quarter='Q2' THEN sales ELSE 0 END) AS q2,
       SUM(CASE WHEN quarter='Q3' THEN sales ELSE 0 END) AS q3,
       SUM(CASE WHEN quarter='Q4' THEN sales ELSE 0 END) AS q4
FROM fact_sales
GROUP BY region;
SELECT region,
       SUM(CASE WHEN quarter='Q1' THEN sales ELSE 0 END) AS q1,
       SUM(CASE WHEN quarter='Q2' THEN sales ELSE 0 END) AS q2,
       SUM(CASE WHEN quarter='Q3' THEN sales ELSE 0 END) AS q3,
       SUM(CASE WHEN quarter='Q4' THEN sales ELSE 0 END) AS q4
FROM fact_sales
GROUP BY region;

UNPIVOT (wide → long):

SELECT region, metric, value
FROM pivoted
UNPIVOT (value FOR metric IN (q1, q2, q3, q4));
SELECT region, metric, value
FROM pivoted
UNPIVOT (value FOR metric IN (q1, q2, q3, q4));

Portable equivalent: SELECT region, 'q1' AS metric, q1 AS value FROM pivoted UNION ALL ....

Spark note: groupBy.pivot("quarter") needs to know the distinct values (otherwise it triggers an extra pass to discover them) and can produce very wide, sparse frames. For dynamic schemas I prefer to pivot downstream in the BI layer or handle it explicitly.

Lead-level caveat: pivoting in the warehouse couples the schema to a fixed value set (e.g. quarters). Prefer keeping data long/tidy and pivoting late — it’s more flexible and cheaper to change.

Q12: How do you optimize a slow SQL query that scans billions of rows?

Description: Directly tied to the JD’s “optimizing efficient SQL queries… handling large data sets”. They want a method, not a list of buzzwords.

Detailed Answer:

My method (say it in this order):

  1. Measure first — read the query plan (EXPLAIN / EXPLAIN ANALYZE, or the warehouse/Athena plan view). Find the actual expensive operator: a full scan, a huge shuffle/exchange, or a nested loop. Never tune blind.
  2. Reduce data scanned — almost always the biggest win:
  • Partition pruning — filter on the partition column so whole partitions are skipped.
  • Predicate pushdown — push filters to the storage/scan layer so less data moves.
  • Column pruning — never SELECT *; read only needed columns (huge with columnar formats).
  • Columnar + compression — ORC/Parquet with Snappy/Zstd.
  1. Fix joins — ensure join keys are well-distributed; look for fan-out; put the small table on the build side; broadcast small dimensions.
  2. Aggregate early — pre-aggregate before joins where possible.
  3. Watch for skew — one key with 40% of rows will hog a reducer. Detect via per-key counts; mitigate by salting or two-phase aggregation.
  4. Statistics & maintenance — stale stats cause bad plans; ANALYZE/VACUUM on the warehouse; refresh manifests/partitions for the query engine.
  5. Rewrite — replace correlated subqueries with joins; replace NOT IN with NOT EXISTS (NULL-safe and often faster); avoid functions on filter columns (e.g. WHERE DATE(ts)='2026-01-01' prevents pruning — use a range instead).

Signature examples to have ready:

  • WHERE YEAR(order_date)=2026 blocks partition pruning → rewrite as WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01'.
  • Move a filter into the CTE / subquery to shrink the shuffle.

Q13: In a warehouse like Redshift, how do distribution styles and sort keys affect performance?

Description: Firms with warehouse heritage care deeply about this, and Redshift is commonly in the JD. This is a high-signal question.

Detailed Answer:

A warehouse like Redshift is a columnar, MPP warehouse: a leader node compiles the plan; compute nodes hold slices that process in parallel. Two physical design decisions dominate performance.

Distribution style — how rows are spread across slices:

The rule I state: distribute the large fact on its most-used join key; distribute small dimensions as ALL; that turns a costly redistribution into a local collocated join.

Sort keys — physical ordering on disk:

Benefits: zone maps skip blocks whose min/max don’t match the filter, and merge joins become possible on sorted data.

Other levers: VACUUM (reclaim space, re-sort), ANALYZE (fresh stats), Result Caching, Concurrency Scaling for burst read load, RA3 for managed storage + independent compute scaling, Spectrum to query object storage without loading, and WLM for query queues.

Interview tip: “I model for the query pattern: fact distributed on the dominant join key, small dims set to ALL, sort key matching the most common filter prefix — then let AUTO handle the rest, and VACUUM/ANALYZE on a schedule.”

Q14: How do you handle semi-structured data and NULLs in SQL?

Description: Two pragmatic topics bundled — JSON/semi-structured handling (very relevant to modern lakehouses) and NULL semantics (a classic trip-up).

Detailed Answer:

Semi-structured data:

  • Redshift: SUPER type with PartiQL (SELECT data.attr, data.items[0].sku FROM t) — no need to shred JSON at load.
  • Athena/Spark: query JSON/Parquet/ORC directly, then shred nested structures into columns at the Silver layer so downstream consumers get flat, fast tables. My default: land raw JSON in Bronze, flatten in Silver.
  • Spark: from_json, schema_of_json, explode/explode_outer for arrays, get_json_object for quick extraction.

NULL handling — the semantics that bite people:

Interview tip: “NULLs are where data-quality bugs hide. My rule: define the null-policy per column in the contract — is NULL allowed, should it default, or should it fail the DQ check — and enforce it at the Silver layer so Gold consumers never have to guess.”

2. Python, Pandas & NumPy

Why this section exists:_ The job description lists “Python and associated libraries like Pandas, NumPy” plus shell scripting. The first technical round may hand you a choice between Python and SQL. Python answers should show_ idiomatic, memory-aware, production code — not notebook one-liners.

Q15: Walk me through Python’s core data structures. When do you use a list vs dict vs set vs tuple?

Description: A warm-up, but they watch for whether you pick structures by access pattern (which is what makes data code fast).

Detailed Answer:

The performance instinct to state: “The single most common Python performance mistake in data code is membership testing in a list — if x in my_list is O(n), while if x in my_set is O(1). On a million-row loop, converting the lookup structure to a set or dict is often the difference between seconds and minutes.”

Related: collections.defaultdict, Counter, and namedtuple/dataclass come up a lot in ETL code — mention them. Counter for frequency, defaultdict(list) for grouping without key-existence checks.

Q16: List comprehension vs generator expression — and why does it matter at data scale?

Description: Tests memory-awareness — the crux of handling large datasets in Python.

Detailed Answer:

squares_list = [n*n for n in range(10_000_000)]   # builds the WHOLE list in memory
squares_gen  = (n*n for n in range(10_000_000))   # lazy — yields one at a time
squares_list = [n*n for n in range(10_000_000)]   # builds the WHOLE list in memory
squares_gen  = (n*n for n in range(10_000_000))   # lazy — yields one at a time
  • A list comprehension evaluates eagerly and stores every element — O(n) memory.
  • A generator expression is lazy and stores only the current item — O(1) memory. It can be consumed once.

Why it matters at scale: for a 50 GB file or a stream, a generator pipeline lets you process it in constant memory:

def read_batches(path, size=100_000):
    with open(path) as f:
        batch = []
        for line in f:
            batch.append(line)
            if len(batch) == size:
                yield batch
                batch = []
        if batch:
            yield batch

for batch in read_batches("huge.csv"):   # constant memory
    process(batch)
def read_batches(path, size=100_000):
    with open(path) as f:
        batch = []
        for line in f:
            batch.append(line)
            if len(batch) == size:
                yield batch
                batch = []
        if batch:
            yield batch

for batch in read_batches("huge.csv"):   # constant memory
    process(batch)

Rule I use: comprehensions for small, consumed-once-or-stored collections; generators (or chunked reads) for anything that could be large. In PySpark/Pandas-heavy work this matters less because the framework handles distribution, but the instinct is what they’re testing.

Q17: How would you read a 20 GB CSV in Pandas when it doesn’t fit in memory?

Description: A very common, very practical question for the Pandas requirement.

Detailed Answer:

Pandas loads eagerly by default, so a 20 GB CSV will OOM a typical machine. Strategies, in the order I’d try them:

  1. Use a faster/leaner engine and Parquet: pd.read_csv(..., engine="pyarrow") and, long-term, convert to Parquet — it’s columnar, compressed and far smaller to read.
  2. Chunked reading:

for chunk in pd.read_csv("big.csv", chunksize=500_000, dtype=dt):
process(chunk)
for chunk in pd.read_csv("big.csv", chunksize=500_000, dtype=dt):
process(chunk)

3. Load only what you need: usecols=[...] (column pruning) — a first-class lever.

4. Downcast dtypes: int64 → int32, float64 → float32, and category for low-cardinality string columns — this often cuts memory 60–80%.

dt = {"region": "category", "amount": "float32", "customer_id": "int64"}
dt = {"region": "category", "amount": "float32", "customer_id": "int64"}

5. Stream with a generator of chunks rather than accumulating one frame.

6. Outgrow Pandas gracefully: for genuinely huge data use Polars (fast, lower memory), Dask, or — since the role is Spark-centric — PySpark, which is the correct tool at that scale anyway.

Interview tip: “My answer is: for 20 GB, Pandas chunking works but you’re solving the wrong problem — I’d land it as Parquet and process with PySpark. I’d use the Pandas path only for a quick exploratory slice.”

Q18: In Pandas, explain merge vs join vs concat. What goes wrong with duplicate keys?

Description: Tests whether you understand that Pandas merges fan out exactly like SQL joins.

Detailed Answer:

Duplicate keys cause fan-out — a left row matching k right rows produces k rows, exactly like SQL. Detect it by checking the right frame’s key uniqueness (df.duplicated(subset=['key']).any()) or by comparing lengths after the merge.

validate= is the underrated feature: Pandas can enforce join cardinality and fail loudly instead of silently fanning out:

df.merge(dim, on="customer_id", how="left", validate="many_to_one")
df.merge(dim, on="customer_id", how="left", validate="many_to_one")

validate accepts "one_to_one", "one_to_many", "many_to_one", "many_to_many". Using it in production ETL code is a strong signal you’ve been burned by a silent fan-out before.

Also mention: indicator=True to debug which rows matched, and drop_duplicates() / groupby to pre-de-duplicate the right side.

Q19: Explain groupby + agg, and the difference between apply, map and transform.

Description: Core Pandas fluency, and the vectorization theme is the real point.

Detailed Answer:

Aggregation:

df.groupby("region").agg(
    total_sales=("sales", "sum"),
    avg_price=("price", "mean"),
    n_orders=("order_id", "count"),
    first_date=("order_date", "min"),
).reset_index()
df.groupby("region").agg(
    total_sales=("sales", "sum"),
    avg_price=("price", "mean"),
    n_orders=("order_id", "count"),
    first_date=("order_date", "min"),
).reset_index()

Named aggregation keeps the output self-documenting — important for maintainable ETL.

apply vs map vs transform:

The key distinction: groupby.agg reduces each group to one row; groupby.transform broadcasts the result back to every original row — ideal for feature engineering like “this row’s value minus its group mean”.

Performance warning: apply (especially row-wise with axis=1) is effectively a Python loop and is a common cause of slow pipelines. Prefer map, merge, or vectorised operations.

Q20: Why is iterrows() slow, and what do you use instead?

Description: A direct “do you write fast Pandas?” probe.

Detailed Answer:

iterrows() creates a new Series object for every row — that per-row object construction is the killer. On a million rows it turns milliseconds of vectorised work into minutes.

What to use instead, in order of preference:

  1. Vectorised operations — arithmetic, string ops via .str, conditions via np.where/np.select.
  2. map / replace for lookups.
  3. groupby + transform for per-group values.
  4. itertuples() if you truly must iterate — returns lightweight tuples (10–100× faster than iterrows).
  5. apply only when vectorization isn’t possible, and never with axis=1 on large frames if it can be avoided.

Example — vectorize instead of loop:

# ❌ slow
for i, row in df.iterrows():
    df.at[i, "total"] = row["price"] * row["qty"]

# ✅ vectorised, ~100x faster
df["total"] = df["price"] * df["qty"]
# ❌ slow
for i, row in df.iterrows():
    df.at[i, "total"] = row["price"] * row["qty"]

# ✅ vectorised, ~100x faster
df["total"] = df["price"] * df["qty"]

Interview tip: “My rule is simple: if I’m writing a for loop over a DataFrame, I stop and ask whether it can be expressed as a vectorised operation, a merge, or a groupby. Ninety percent of the time it can.”

Q21: How do you handle missing data in Pandas?

Description: Practical and heavily tested, because missing data causes silent analytical errors.

Detailed Answer:

Detect first:

df.isna().sum()                 # count per column
df.isna().mean()                # fraction — decide policy by severity
df.isna().sum()                 # count per column
df.isna().mean()                # fraction — decide policy by severity

Strategies:

Lead-level framing: “Filling is a business decision, not a technical one. Blindingly filling nulls with 0 in a financial field is a data-quality incident waiting to happen. My habit is to log the fill statistics, keep a missing-indicator column where it matters, and make the null policy explicit in the Silver-layer contract.”

Q22: What is NumPy broadcasting, and why is it faster than Python lists?

Description: NumPy is named explicitly; they want to know you understand vectorization, not just that you can import it.

Detailed Answer:

Why NumPy is fast:

  • ndarray stores homogeneous data in contiguous memory (a C array), with the element type fixed at creation.
  • Operations execute in compiled C loops without Python interpreter overhead or per-element object boxing.
  • A Python list holds pointers to arbitrary PyObjects, so element-wise arithmetic re-enters the interpreter for every element.

Broadcasting is the rule set that lets NumPy do arithmetic between arrays of different shapes without copying data:

a = np.array([[1, 2, 3],
              [4, 5, 6]])          # shape (2, 3)
b = np.array([10, 20, 30])         # shape (3,)
a + b                              # b is "stretched" across rows → shape (2, 3)
a = np.array([[1, 2, 3],
              [4, 5, 6]])          # shape (2, 3)
b = np.array([10, 20, 30])         # shape (3,)
a + b                              # b is "stretched" across rows → shape (2, 3)

Broadcasting aligns shapes from the trailing dimension; a dimension of size 1 (or missing) is stretched to match. It enables e.g. (matrix - column_mean) / column_std for standardization with no explicit loop and no data duplication.

Data-engineering relevance: this is exactly how vectorized pandas operations and PySpark’s Arrow-backed pandas UDFs get their speed — the same single-instruction-multiple-data idea. Mentioning that link signals you understand the why, not just the API.

Q23: How do you write a reusable, production-grade ETL function in Python?

Description: Tests engineering maturity — idempotency, error handling, logging, configurability.

Detailed Answer:

A production function should be idempotent, observable, configurable and fail-loud.

int:
"""Idempotent ingest for a single partition date. Returns rows written."""
log.info("ingest.start source=%s target=%s date=%s",
cfg.source, cfg.target, cfg.run_date)
try:
rows = extract(cfg.source, cfg.run_date)
validate(rows) # DQ gate: fail fast
n = load(cfg.target, cfg.run_date, rows) # partition-overwrite = idempotent
log.info("ingest.done rows=%d", n)
return n
except TransientError:
log.warning("ingest.retryable_failure")
raise # let the orchestrator's retry policy handle it
except Exception:
log.exception("ingest.failed")
raise # never swallow – alerting relies on it” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

import logging
from dataclasses import dataclass

log = logging.getLogger(__name__)
@dataclass
class IngestConfig:
    source: str
    target: str
    run_date: str
def ingest(cfg: IngestConfig) -> int:
    """Idempotent ingest for a single partition date. Returns rows written."""
    log.info("ingest.start source=%s target=%s date=%s",
             cfg.source, cfg.target, cfg.run_date)
    try:
        rows = extract(cfg.source, cfg.run_date)
        validate(rows)                       # DQ gate: fail fast
        n = load(cfg.target, cfg.run_date, rows)   # partition-overwrite = idempotent
        log.info("ingest.done rows=%d", n)
        return n
    except TransientError:
        log.warning("ingest.retryable_failure")
        raise                                # let the orchestrator's retry policy handle it
    except Exception:
        log.exception("ingest.failed")
        raise                                # never swallow - alerting relies on it
import logging
from dataclasses import dataclass

log = logging.getLogger(__name__)
@dataclass
class IngestConfig:
    source: str
    target: str
    run_date: str
def ingest(cfg: IngestConfig) -> int:
    """Idempotent ingest for a single partition date. Returns rows written."""
    log.info("ingest.start source=%s target=%s date=%s",
             cfg.source, cfg.target, cfg.run_date)
    try:
        rows = extract(cfg.source, cfg.run_date)
        validate(rows)                       # DQ gate: fail fast
        n = load(cfg.target, cfg.run_date, rows)   # partition-overwrite = idempotent
        log.info("ingest.done rows=%d", n)
        return n
    except TransientError:
        log.warning("ingest.retryable_failure")
        raise                                # let the orchestrator's retry policy handle it
    except Exception:
        log.exception("ingest.failed")
        raise                                # never swallow - alerting relies on it

Principles to state:

  • Idempotent: re-running for the same run_date yields the same result (partition overwrite or MERGE/upsert by key) — the job description asks for fault-tolerant pipelines, and idempotency is half of that.
  • Fail-loud, don’t swallow: only catch what you can handle; let retryable errors propagate for the orchestrator.
  • Config-driven: no hard-coded paths/dates; parameters or a config file.
  • Structured logging: correlation id / run id on every line.
  • Schema validation at the boundary: validate input schema and business rules.
  • Testable: pure functions, dependency injection, covered with pytest.

Q24: How do you structure a Python data project for maintainability?

Description: A Lead-level question — they want to know you design code others can own.

Detailed Answer:

A clean layout (works for local scripts, serverless ETL jobs and Spark app code):

project/
├── src/
│   ├── config/          # settings, env loading (pydantic-settings)
│   ├── extract/         # readers: api, db, s3
│   ├── transform/       # pure transformation functions
│   ├── load/            # writers
│   ├── quality/         # DQ checks
│   └── utils/           # logging, retry, io helpers
├── jobs/                # thin entrypoints (glue_job.py, emr_job.py)
├── tests/               # pytest: unit + contract tests
├── conf/                # yaml configs per pipeline
├── requirements.txt / pyproject.toml
└── Dockerfile
project/
├── src/
│   ├── config/          # settings, env loading (pydantic-settings)
│   ├── extract/         # readers: api, db, s3
│   ├── transform/       # pure transformation functions
│   ├── load/            # writers
│   ├── quality/         # DQ checks
│   └── utils/           # logging, retry, io helpers
├── jobs/                # thin entrypoints (glue_job.py, emr_job.py)
├── tests/               # pytest: unit + contract tests
├── conf/                # yaml configs per pipeline
├── requirements.txt / pyproject.toml
└── Dockerfile

Principles:

  • Thin entrypoints, fat libraries — a serverless/cluster entrypoint should just parse args and call an importable function. That makes the logic unit-testable without a cluster.
  • Pure transforms — take a DataFrame, return a DataFrame; no side effects; easy to test.
  • Config over code — a new source should be a config change, not new code (exactly the metadata-driven philosophy that scales in a consulting practice).
  • Dependency pinning — reproducibility.
  • Central logging + error handling utilities rather than ad-hoc prints.

Q25: Parquet vs CSV vs Avro vs ORC — how do you choose, and how do you use them in Python?

Description: Extremely common in data-engineering interviews; ties directly to performance and cost.

Detailed Answer:

Choosing:

  • Analytical reads → Parquet (Spark/Athena/warehouse). My default.
  • Hive-native, ORC-tuned estate → ORC.
  • Kafka/streaming and schema-evolving records → Avro (with Schema Registry).
  • Semi-structured API payloads → land JSON, then convert to Parquet.

In Python:

df.to_parquet("s3://bucket/gold/txn/", partition_cols=["dt"], compression="snappy")
pd.read_parquet("s3://bucket/gold/txn/", columns=["id","amount"])   # column pruning
df.to_avro("out.avro", schema)  # via fastavro
df.to_parquet("s3://bucket/gold/txn/", partition_cols=["dt"], compression="snappy")
pd.read_parquet("s3://bucket/gold/txn/", columns=["id","amount"])   # column pruning
df.to_avro("out.avro", schema)  # via fastavro

Cost link (Lead-level): format choice directly hits the cloud bill — columnar + compression means fewer bytes scanned, which on Athena is literally the pricing model (per TB scanned). Mention that.

Q26: How do you test a data pipeline in Python?

Description: Tests engineering discipline and ties to the “assures quality” responsibility.

Detailed Answer:

Testing a data pipeline spans four layers:

Practical pytest example:

= 0).all()” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

import pandas as pd
from src.transform.clean import drop_negative_amounts

def test_drop_negative_amounts():
    df = pd.DataFrame({"amount": [10, -5, 20]})
    out = drop_negative_amounts(df)
    assert out["amount"].tolist() == [10, 20]
    assert (out["amount"] >= 0).all()
import pandas as pd
from src.transform.clean import drop_negative_amounts

def test_drop_negative_amounts():
    df = pd.DataFrame({"amount": [10, -5, 20]})
    out = drop_negative_amounts(df)
    assert out["amount"].tolist() == [10, 20]
    assert (out["amount"] >= 0).all()

The tests I’d insist on for every pipeline (say these):

  1. Idempotency test — run twice, assert identical output (the #1 fault-tolerance guarantee).
  2. Schema test — output schema matches the contract.
  3. Reconciliation test — row counts / sums match the source within tolerance.
  4. Null/threshold test — critical columns aren’t suddenly all-null.

CI integration: run unit + contract tests on every PR (see Q88), so a broken transform fails before it reaches a cluster.

Q27: Multithreading vs multiprocessing vs async in Python — which for data tasks?

Description: Tests whether you understand the GIL and pick the right concurrency model.

Detailed Answer:

The deciding factor is I/O-bound vs CPU-bound and the GIL (Global Interpreter Lock).

The rule I state: “Threads or async for I/O concurrency — pulling many API pages or object-store objects in parallel; processes for CPU-bound Python. But my real answer for large data is neither: at scale I push the work to PySpark, which parallelises across executors, and reserve Python concurrency for orchestration and I/O fan-out.”

Concrete examples to give:

  • Parallel API extraction with ThreadPoolExecutor (or asyncio) → collapses wall-clock time.
  • ProcessPoolExecutor to run per-file heavy Pandas transforms across cores.
  • Never do distributed data processing by spawning threads — that’s what Spark is for. A lead who proposes threads for a billion-row job signals inexperience.

3. PySpark & Spark Internals / Tuning

Why this section exists:_ This is the heart of the role. A typical JD devotes five separate bullets to it: PySpark dataframes, joins, caching, memory management, partitioning, parallelism, Spark UI, Event Timelines, DAG, Spark config parameters, and tuning long-running pipelines. Expect depth here — and expect to be asked to_ choose between options and justify it.

Q28: Walk me through Spark’s architecture. What happens when you submit a job?

Description: The fundamental question. Every later tuning answer builds on it, so get it crisp.

Detailed Answer:

┌──────────────────────────┐
   spark-submit ───►│  DRIVER                  │
                    │  - SparkContext/Session  │
                    │  - DAG Scheduler         │
                    │  - Task Scheduler        │
                    │  - builds logical plan   │
                    └──────────┬───────────────┘
                               │  requests resources
                    ┌──────────▼───────────────┐
                    │  CLUSTER MANAGER         │
                    │  (YARN / K8s / EMR)      │
                    └──────────┬───────────────┘
                               │  launches
        ┌──────────────────────┼──────────────────────┐
   ┌────▼─────┐          ┌─────▼────┐          ┌──────▼───┐
   │ EXECUTOR │          │ EXECUTOR │          │ EXECUTOR │
   │  slots → │          │  slots → │          │  slots → │
   │  tasks   │          │  tasks   │          │  tasks   │
   └──────────┘          └──────────┘          └──────────┘
┌──────────────────────────┐
   spark-submit ───►│  DRIVER                  │
                    │  - SparkContext/Session  │
                    │  - DAG Scheduler         │
                    │  - Task Scheduler        │
                    │  - builds logical plan   │
                    └──────────┬───────────────┘
                               │  requests resources
                    ┌──────────▼───────────────┐
                    │  CLUSTER MANAGER         │
                    │  (YARN / K8s / EMR)      │
                    └──────────┬───────────────┘
                               │  launches
        ┌──────────────────────┼──────────────────────┐
   ┌────▼─────┐          ┌─────▼────┐          ┌──────▼───┐
   │ EXECUTOR │          │ EXECUTOR │          │ EXECUTOR │
   │  slots → │          │  slots → │          │  slots → │
   │  tasks   │          │  tasks   │          │  tasks   │
   └──────────┘          └──────────┘          └──────────┘

The lifecycle of a job:

  1. spark-submit starts the driver, which creates a SparkSession/SparkContext.
  2. The driver parses your code into a logical plan; on the first action, it triggers optimization (Catalyst) into a physical plan.
  3. The DAG Scheduler splits the plan into stages at shuffle boundaries.
  4. The Task Scheduler requests resources from the cluster manager and launches one task per partition per stage on executor cores.
  5. Executors run tasks, cache/shuffle data, and return results (or write to storage) back to the driver.

Vocabulary to keep straight:

  • Job = triggered by one action (count, write, collect).
  • Stage = a set of tasks with no shuffle between them; stage boundaries are shuffles.
  • Task = one unit of work on one partition (one core).
  • Partition = a chunk of the dataset.

Interview tip: “The mental model that matters for tuning: partitions drive task count, shuffles create stage boundaries, and the number of concurrent tasks is bounded by total executor cores. Almost every performance problem is one of those three numbers being wrong.”

Q29: What are narrow vs wide transformations, and why do they matter so much?

Description: The concept that explains most Spark performance. If you nail one answer in this section, make it this one.

Detailed Answer:

Why it matters: a shuffle writes data to disk and reads it back across the network — it is the single most expensive operation in Spark. Wide transformations:

  • Serialize and write shuffle files,
  • Move data across the network,
  • Increase latency and can cause OOM/skew/disk spill.

Tuning implication (say this):

  • Minimise the number of shuffles and the columns/rows per shuffle — filter and select before a wide op.
  • Choose the right shuffle partition count (spark.sql.shuffle.partitions, tuned by AQE).
  • For a small join side, avoid the shuffle entirely with a broadcast join (Q34).
  • Watch the Spark UI shuffle read/write bytes — the biggest signal for “this job is shuffle-bound”.

Q30: RDD vs DataFrame vs Dataset — and what are Catalyst and Tungsten?

Description: Tests whether you understand the abstraction layers and why DataFrames are fast.

Detailed Answer:

Catalyst is Spark’s query optimizer: it takes your logical plan → applies rule-based optimizations (predicate pushdown, constant folding, column pruning, join reordering) → produces and costs physical plans → picks the cheapest.

Tungsten is the execution engine: whole-stage code generation (fuses operators into a single compiled function), off-heap memory management, and cache-aware computation.

Practical stance: “I default to DataFrames/Spark SQL because Catalyst and Tungsten optimise them for free. I drop to RDDs only for something the declarative API genuinely can’t express — custom partitioners, raw byte manipulation — and I accept that I’ve then given up those optimizations.”

Q31: Explain lazy evaluation and how Spark builds the DAG.

Description: Explains why Spark is efficient and why your print/timing can mislead you.

Detailed Answer:

Spark builds a lineage graph of transformations (the DAG) but executes nothing until an action is called. Transformations are lazy; actions are eager.

0").select("id","amount").groupBy("id").sum() # nothing runs
df2.count() # ← an ACTION: now the whole DAG executes” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

df2 = df.filter("amount > 0").select("id","amount").groupBy("id").sum()  # nothing runs
df2.count()   # ← an ACTION: now the whole DAG executes
df2 = df.filter("amount > 0").select("id","amount").groupBy("id").sum()  # nothing runs
df2.count()   # ← an ACTION: now the whole DAG executes

Why lazy evaluation?

  1. Whole-plan optimization — Spark sees the entire pipeline before executing, so Catalyst can push filters down, prune columns, reorder joins and combine operations you never asked it to combine.
  2. Pipelining — narrow transformations fuse into a single stage (no intermediate materialisation) via Tungsten whole-stage codegen.
  3. Avoids needless work — if you never call an action, nothing is computed.

The DAG in practice: wide transformations cut the DAG into stages. Spark schedules stages respecting dependencies (a “shuffle map” stage feeds a “result” stage). Lineage is also the fault-tolerance mechanism — if a partition is lost, Spark recomputes it from lineage (or from a cache/persisted point, avoiding recomputation of ancestors).

Common gotcha to mention: double-execution. If you reuse a DataFrame without cache(), each action re-runs the full upstream DAG — a classic accidental 2× cost.

Q32: What’s the difference between a transformation and an action? How does lineage give fault tolerance?

Description: Complements Q31 — tests the RDD/DAG model and resilience.

Detailed Answer:

Transformations (lazy, build the plan): map, filter, select, join, groupBy, withColumn, repartition. Actions (eager, trigger execution): count, collect, show, take, write, foreach, reduce.

Lineage & fault tolerance:

  • Each RDD/DataFrame remembers how it was derived from its parent (the lineage graph).
  • If an executor dies and its partitions are lost, Spark doesn’t panic — it recomputes the lost partitions from the lineage using surviving data.
  • This is why Spark is called fault-tolerant without mandatory replication: the recipe is enough to rebuild the result.
  • Cost implication: recomputation can be expensive for long lineages, which is why cache()/persist()/checkpointing exist — they break the lineage at a point so recovery resumes from there instead of the beginning.
  • checkpoint() (especially in Structured Streaming) truncates lineage by writing to reliable storage — essential for very long-running stream jobs.

Interview tip: “This is exactly what ‘fault-tolerance’ in a data-engineering JD means — the pipeline can lose a node mid-run and still produce the correct result. Lineage gives that for free; caching and idempotent sinks let me keep it cheap and safe.”

Q33: How do Spark joins work under the hood? How do you choose the strategy?

Description: Joins are where most production Spark jobs get slow. Expect a deep follow-up.

Detailed Answer:

Spark has several physical join strategies; the optimizer picks based on size and hints:

My decision path:

  1. Is one side small (a few hundred MB or less)? → broadcast it (and set the threshold or use a hint).
  2. Both large, keys well-distributed? → sort-merge (the default) with tuned shuffle partitions.
  3. Skewed key? → enable AQE skew join, or salt the hot keys.
  4. Non-equi condition? → consider a range join approach or broadcast nested loop only on tiny inputs.

Rules I state: always filter and select before the join (shrink the shuffle), join on a well-distributed key, and watch shuffle read/write in the UI to confirm the strategy chosen.

Q34: Explain broadcast joins. When do they fail?

Description: A concrete, high-frequency optimisation. Interviewers love the failure modes.

Detailed Answer:

A broadcast join sends the small table to every executor, which lets each executor join locally against its partitions of the big table — no shuffle of the big side, often a 5–10× speedup.

from pyspark.sql.functions import broadcast
big.join(broadcast(small_dim), "customer_id")

# or tune the threshold (bytes); 0 disables auto-broadcast
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", 50 * 1024 * 1024)
from pyspark.sql.functions import broadcast
big.join(broadcast(small_dim), "customer_id")

# or tune the threshold (bytes); 0 disables auto-broadcast
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", 50 * 1024 * 1024)

When broadcast fails / is the wrong choice:

  1. The “small” side isn’t small — estimated > threshold (or > spark.sql.broadcastTimeout, default 300 s). The driver may time out collecting it.
  2. Driver memory blow-up — the driver collects the small side to broadcast it; a too-large side OOMs the driver.
  3. Executor memory pressure — every executor holds a copy in memory, and many concurrent broadcasts across a big job multiply the footprint.
  4. Highly skewed big side — broadcast doesn’t fix skew among the big-side partitions.
  5. It’s already a large-large join — forcing a broadcast there is worse than sort-merge.

How to diagnose: check the Spark UI SQL plan for BroadcastHashJoin vs SortMergeJoin; watch for Collect/broadcast timeouts and driver OOM in logs.

Interview tip: “Broadcast is my first move for dimension joins — but only after I’ve confirmed the dimension is genuinely small. A 500 MB dimension broadcast across 200 executors is an OOM, not an optimization.”

Q35: cache() vs persist() — and when does caching hurt?

Description: Tests whether you cache with intent rather than reflexively.

Detailed Answer:

  • cache() = persist(MEMORY_AND_DISK) (in PySpark the default storage level) — a DataFrame reused many times is materialised so the upstream DAG isn’t recomputed.
  • persist(level) lets you choose a storage level:

When caching HELPS: a DataFrame (or expensive intermediate) is used by ≥2 actions, or feeds multiple downstream branches — it avoids recomputing lineage.

When caching HURTS (say this — it’s the signal of experience):

  • Used only once — you pay memory + serialization cost for nothing.
  • Memory is tight — a cached frame can evict other cached data and cause spilling, slowing everything down.
  • Cached too early/late in the lineage — caching a huge raw frame is wasteful; cache the optimised intermediate.
  • Left un-unpersisted — a long-lived job accumulates cached frames. Always unpersist() when done.

Interview tip: “I cache deliberately: only an intermediate that’s read more than once, at the smallest useful point in the lineage, and I unpersist when finished. Reflexive cache() is how a job quietly starts spilling to disk.”

Q36: Explain Spark memory management. How do you debug an out-of-memory error?

Description: Directly from the JD (“memory management”). Give the model, then a method.

Detailed Answer:

Per executor, the memory model (unified memory manager since Spark 1.6):

┌─────────────────────────────────────────────┐
│  Reserved memory (300 MB)                    │
├─────────────────────────────────────────────┤
│  User memory                                 │  ← your data structures, UDF overhead
│  (1 - spark.memory.fraction) of heap         │
├─────────────────────────────────────────────┤
│  Unified memory = spark.memory.fraction      │
│    ├── Execution memory  (shuffles, joins,   │
│    │                      sorts, aggregation)│
│    └── Storage memory    (cache/persist)     │
│  (execution can evict storage and vice versa)│
├─────────────────────────────────────────────┤
│  Overhead (spark.executor.memoryOverhead)    │  ← off-heap: Python, JVM internals
└─────────────────────────────────────────────┘
┌─────────────────────────────────────────────┐
│  Reserved memory (300 MB)                    │
├─────────────────────────────────────────────┤
│  User memory                                 │  ← your data structures, UDF overhead
│  (1 - spark.memory.fraction) of heap         │
├─────────────────────────────────────────────┤
│  Unified memory = spark.memory.fraction      │
│    ├── Execution memory  (shuffles, joins,   │
│    │                      sorts, aggregation)│
│    └── Storage memory    (cache/persist)     │
│  (execution can evict storage and vice versa)│
├─────────────────────────────────────────────┤
│  Overhead (spark.executor.memoryOverhead)    │  ← off-heap: Python, JVM internals
└─────────────────────────────────────────────┘

Key configs: spark.memory.fraction (default 0.6), spark.memory.storageFraction (0.5), spark.executor.memory, spark.executor.memoryOverhead, spark.executor.cores.

Common OOM types and fixes:

My debugging method: open the Spark UI → Stages, look at task duration skew (one task 10× the median = skew), shuffle spill (memory) / (disk), and GC time. Those three tell you whether it’s skew, memory pressure, or partition sizing — and each has a different fix.

Q37: repartition() vs coalesce() — and how do you handle the small-files problem?

Description: Partitioning is called out in most JDs, and small files are a universal lakehouse pain.

Detailed Answer:

Rule of thumb: repartition when you need balance or key-colocation; coalesce when you just want fewer output files and cost matters.

The small-files problem: writing a job with 2000 tiny files destroys read performance (per-file overhead, metadata cost, poor scan efficiency) — on object storage, in the query engine, and in Spark alike.

Fixes I use:

  1. Reduce output partitions before writing: df.coalesce(partitions_based_on_size) or AQE’s coalesce partitions (auto).
  2. Target ~128 MB per file — coalesce(target_size_MB * 1024 / avg_partition_MB) — a common, defensible heuristic.
  3. AQE coalescePartitions on by default in Spark 3.x shrinks post-shuffle partitions automatically.
  4. Compaction job — for streaming/late-arriving files, run periodic compaction (rewrite small files into larger ones). This is the same “compaction” pattern as Delta/Iceberg OPTIMIZE.
  5. Partition pruning on read — ensure the write is partitioned so readers skip data.

Interview tip: “I decide partition count by target file size, not habit. Roughly 128 MB per file, then let AQE coalesce. For streaming, I add a scheduled compaction step — small files are a debt you pay down on a timer.”

Q38: How do you tune parallelism? Explain spark.default.parallelism vs spark.sql.shuffle.partitions.

Description: Directly named in most JDs (“parallelism”). A precise answer here lands well.

Detailed Answer:

Two different knobs control two different things:

Other knobs: spark.executor.cores, spark.executor.instances, spark.sql.adaptive.enabled.

My method:

  1. Compute total cores = executors × cores/executor. That sets the max concurrent tasks.
  2. Ensure partitions ≫ cores (a few multiples) so work is balanced and stragglers don’t idle the cluster.
  3. Set spark.sql.shuffle.partitions so each shuffle partition is around 100–200 MB — shuffle_partitions ≈ shuffle_data_MB / 128.
  4. Let AQE coalesce the partitions after the shuffle (spark.sql.adaptive.coalescePartitions.enabled=true) rather than guessing a single global number — this is the modern default.

Symptom → fix map:

  • Too many partitions → tiny tasks, scheduler overhead, and small output files → coalesce / lower shuffle partitions.
  • Too few partitions → long tasks, OOM, and idle cores → raise shuffle partitions / repartition.
  • Stragglers (task-skew) → skew, not parallelism → Q39.

Q39: What is data skew and how do you fix it?

Description: The most common cause of a Spark job “running overnight”. Expect scenario-based follow-ups.

Detailed Answer:

Skew = some partitions have far more rows than others, so a few tasks take far longer while the rest finish and sit idle. The job’s runtime is set by the slowest task.

How I detect it:

  • Spark UI → Stages → task duration distribution: if max/median ≫ 3, it’s skewed.
  • Spark UI → Shuffle Read Size per task: one task reading GBs while others read MBs.
  • Profile the key: df.groupBy("join_key").count().orderBy(desc("count")).show() — a hot key like NULL, 0, or Unknown is the usual culprit.

Fixes (in order):

Salting example:

# big side: add salt 0..N
big = big.withColumn("salt", (rand() * 10).cast("int"))
# small side: explode into N salts
small = small.withColumn("salt", explode(array(*[lit(i) for i in range(10)])))
joined = big.join(small, ["key", "salt"])
# big side: add salt 0..N
big = big.withColumn("salt", (rand() * 10).cast("int"))
# small side: explode into N salts
small = small.withColumn("salt", explode(array(*[lit(i) for i in range(10)])))
joined = big.join(small, ["key", "salt"])

Interview tip: “My first move is always AQE — it fixes most real skew for free. Salting is the hammer for the cases where a single key genuinely dominates, and I only reach for it after I’ve proven the skew with the task-duration histogram.”

Q40: What is Adaptive Query Execution (AQE), and what does it do?

Description: The modern Spark optimisation that a Lead must know cold. Don’t answer Spark 2.x tuning only.

Detailed Answer:

AQE re-optimizes the query at runtime, using actual shuffle statistics instead of the optimizer’s pre-run estimates. Enabled by spark.sql.adaptive.enabled=true (default on in Spark 3.2+).

Three headline features:

Supporting improvement: AQE can also eliminate the second shuffle for joins when it converts to broadcast.

Why it matters: pre-AQE, you guessed spark.sql.shuffle.partitions globally and hoped. With AQE, you set a sensible upper bound and let Spark right-size partitions using measured bytes.

Interview tip: “AQE is my default first lever. I enable it, set advisoryPartitionSizeInBytes around 128 MB and a reasonable shuffle.partitions ceiling, and let it coalesce, switch joins and handle skew. I only go manual — salting, explicit repartition — for what AQE can’t fix.”

Q41: Walk me through reading the Spark UI to diagnose a slow job.

Description: Most JDs explicitly name Spark UI, Event Timelines, DAG and config parameters. This is a must-answer-perfectly question.

Detailed Answer:

My diagnostic walkthrough (say it as a sequence, not a list):

  1. Jobs tab — identify the slowest job/action first. That’s where the wall-clock time is.
  2. Stages tab — for the slow stage, look at:
  • Duration distribution across tasks → a long tail = skew / stragglers.
  • Shuffle Read/Write Size → big numbers = shuffle-bound, so reduce shuffle (broadcast, filter early).
  • Shuffle Spill (memory) / (disk) → spilling means partitions exceed memory → more/smaller partitions or more memory.
  • GC Time → high GC = too much memory pressure or caching.
  • Input Size / Records → confirm pruning is working (not scanning everything).
  1. SQL tab — inspect the physical plan: which join strategy was chosen (BroadcastHashJoin vs SortMergeJoin), where the exchanges (shuffles) are, whether filters were pushed down. Use this to spot a wrong join choice or a missing predicate pushdown.
  2. DAG Visualization — see stages and the shuffle boundaries between them; count how many shuffles the job does.
  3. Event Timeline — visualize the executor/task timeline to see concurrent vs serial execution, gaps where the cluster is idle (too few tasks / a driver bottleneck), and when executors joined/left.
  4. Environment tab — confirm the actual configs applied (shuffle.partitions, AQE, memory) — a mis-set config is a common root cause.

The three-second triage I teach: “Look at the slowest stage. If one task is much longer than the median → skew. If shuffle read/write dominates → shuffle-bound, fix the join/filters. If spill or GC is high → memory/partition sizing. Everything else is a consequence of one of those three.”

Q42: A PySpark job that used to run in 20 minutes now takes 4 hours. How do you fix it?

Description: A scenario question that ties together the whole section. They want a method, not a lucky guess.

Detailed Answer:

What changed? Where’s the time going? Diagnosis first, tuning second.

Step 1 — Find where the time is (Spark UI): Which stage is slow? Skew (task histogram), shuffle volume, spill, GC, or input size. Compare to a known-good run if you have one.

Step 2 — Check the data, not just the code. Most regressions are data-driven:

  • Did the input grow? Volume up = more partitions needed.
  • Did a key become skewed? A new hot customer/tenant/NULL bucket. (Very common after a merge or a new client.)
  • Did partition pruning break? A new full-table scan or a lost filter.
  • Did schema drift appear? A new column changing size/shape.

Step 3 — Apply the right fix for the diagnosis:

Step 4 — Validate with measurement: re-time the job, and confirm shuffle bytes / spill / task skew actually improved. A tuning change without a before/after number is a guess.

Step 5 — Prevent recurrence: add a monitoring alert on job duration, shuffle bytes and skew ratio; add a stop-the-line DQ check on new hot keys; document the fix.

Interview tip: “I open the UI before I open the code. Nine times out of ten a job that got 10× slower didn’t change code — the data changed. I find the skewed key or the lost pruning first, then decide whether the fix is config, code, or a data-layout change.”

Q43: UDFs vs built-in functions — and what are Pandas UDFs?

Description: A classic optimisation question; the “why avoid UDFs” answer is what they’re hunting for.

Detailed Answer:

The core problem: a plain Python UDF is an opaque black box to Catalyst, so Spark:

  • Cannot optimize it (no pushdown, no codegen),
  • Serializes/deserializes every row between the JVM and the Python worker (massive overhead).

Rule: always prefer built-in functions (pyspark.sql.functions), which run in optimized JVM code and benefit from Tungsten codegen. E.g. use when/otherwise, regexp_replace, date_trunc, size, explode instead of custom Python.

# ❌ slow: per-row Python serialization
from pyspark.sql.functions import udf
@udf("string")
def cat(a, b):
  return f"{a}-{b}"

# ✅ fast: built-in
from pyspark.sql.functions import concat_ws
df.withColumn("c", concat_ws("-", "a", "b"))
# ❌ slow: per-row Python serialization
from pyspark.sql.functions import udf
@udf("string")
def cat(a, b):
  return f"{a}-{b}"

# ✅ fast: built-in
from pyspark.sql.functions import concat_ws
df.withColumn("c", concat_ws("-", "a", "b"))

When you genuinely need custom logic → Pandas UDF (vectorized UDF):

pd.Series: # operates on batches via Apache Arrow
return (s – s.mean()) / s.std()” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

from pyspark.sql.functions import pandas_udf
import pandas as pd

@pandas_udf("double")
def zscore(s: pd.Series) -> pd.Series:      # operates on batches via Apache Arrow
    return (s - s.mean()) / s.std()
from pyspark.sql.functions import pandas_udf
import pandas as pd

@pandas_udf("double")
def zscore(s: pd.Series) -> pd.Series:      # operates on batches via Apache Arrow
    return (s - s.mean()) / s.std()

Pandas UDFs process data in Arrow-backed batches rather than row-by-row — 10–100× faster than a plain UDF. There are also Scalar, Grouped Map (per-group pandas transforms — great for per-entity time-series features) and Map Iterator forms.

Even better for a full transform: applyInPandas / mapInPandas for grouped operations, or move the logic to SQL.

Interview tip: “My order is: built-in function → Spark SQL expression → Pandas UDF → plain UDF as the last resort. A plain UDF in a hot loop is the fastest way to turn a 20-minute job into 4 hours.”

Q44: How do you handle nested JSON and schema evolution in Spark?

Description: Real-world ingestion question — directly relevant to landing multi-format source data.

Detailed Answer:

Parsing nested JSON:

from pyspark.sql.functions import from_json, col, explode
from pyspark.sql.types import StructType, StructField, StringType, ArrayType

schema = StructType([
    StructField("id", StringType()),
    StructField("items", ArrayType(StructType([
        StructField("sku", StringType()),
        StructField("qty",  StringType()),
    ]))),
])
parsed = (raw
    .withColumn("d", from_json(col("value"), schema))
    .select("d.id", "d.items")            # struct access with dot notation
)
flat = parsed.select("id", explode("items").alias("item")) 
             .select("id", "item.sku", "item.qty")
from pyspark.sql.functions import from_json, col, explode
from pyspark.sql.types import StructType, StructField, StringType, ArrayType

schema = StructType([
    StructField("id", StringType()),
    StructField("items", ArrayType(StructType([
        StructField("sku", StringType()),
        StructField("qty",  StringType()),
    ]))),
])
parsed = (raw
    .withColumn("d", from_json(col("value"), schema))
    .select("d.id", "d.items")            # struct access with dot notation
)
flat = parsed.select("id", explode("items").alias("item")) 
             .select("id", "item.sku", "item.qty")

Key techniques: from_json / schema_of_json, dot-notation for structs, explode/explode_outer for arrays, get_json_object for quick extraction, to_json back out.

Schema evolution strategies:

Discipline I state: “I never let a source’s schema surprise a production table. Bronze keeps the raw payload; Silver applies an explicit contract and routes unparseable records to a dead-letter location with an alert. Schema evolution is a governed change, not an accident.”

Q45: How do window functions work in PySpark, and what are the performance caveats?

Description: Connects the SQL window answer (Q3) to Spark and to performance.

Detailed Answer:

from pyspark.sql import Window
from pyspark.sql.functions import row_number, col, sum as _sum, desc

w = Window.partitionBy("customer_id").orderBy(desc("order_date"))
df.withColumn("rn", row_number().over(w)) 
  .filter(col("rn") == 1)          # latest order per customer
# cumulative sum with an explicit frame
wf = (Window.partitionBy("customer_id")
            .orderBy("order_date")
            .rowsBetween(Window.unboundedPreceding, Window.currentRow))
df.withColumn("running_total", _sum("amount").over(wf))
from pyspark.sql import Window
from pyspark.sql.functions import row_number, col, sum as _sum, desc

w = Window.partitionBy("customer_id").orderBy(desc("order_date"))
df.withColumn("rn", row_number().over(w)) 
  .filter(col("rn") == 1)          # latest order per customer
# cumulative sum with an explicit frame
wf = (Window.partitionBy("customer_id")
            .orderBy("order_date")
            .rowsBetween(Window.unboundedPreceding, Window.currentRow))
df.withColumn("running_total", _sum("amount").over(wf))

Performance caveats (Lead-level):

  • A window function forces partitioning and sorting by the window key — a shuffle + sort, often the most expensive operator.
  • All rows of a partition must be co-located on one task → a large partitionBy key (e.g. a high-volume customer) causes skew.
  • Without an explicit orderBy, some functions can’t be computed; and rowsBetween vs rangeBetween changes cost and results.
  • Reusing the same window definition lets Spark share the sort — but different window definitions trigger separate shuffles/sorts. Consolidate windows where possible.
  • For “latest record per key” at scale, an alternative is a groupBy + max join or a Delta MERGE, which can be cheaper than a global window sort.

Interview tip: “I treat a window function like a shuffle — I ask ‘can I avoid it?’. Often a groupBy + join or a deduplicated dimension gets the same result without a global sort, especially on a skewed key.”

Q46: Explain Spark Structured Streaming — micro-batch, watermarking, checkpoints and exactly-once.

Description: Most JDs require streaming and batch pipelines, so this is core, not optional.

Detailed Answer:

The model: Structured Streaming treats a stream as an unbounded table you query with the same DataFrame API. It runs in micro-batches (default trigger) or continuous/AvailableNow modes.

query = (spark.readStream
    .format("kafka").option("kafka.bootstrap.servers", brokers)
    .option("subscribe", "orders").load()
    .selectExpr("CAST(value AS STRING) AS json")
    .select(from_json("json", schema).alias("d")).select("d.*")
    .withWatermark("event_time", "10 minutes")            # lateness bound
    .groupBy(window("event_time", "5 minutes"), "region")
    .agg(count("*").alias("orders"))
    .writeStream
    .outputMode("update")
    .option("checkpointLocation", "s3://.../checkpoints/orders")
    .format("delta")                                       # idempotent sink
    .start())
query = (spark.readStream
    .format("kafka").option("kafka.bootstrap.servers", brokers)
    .option("subscribe", "orders").load()
    .selectExpr("CAST(value AS STRING) AS json")
    .select(from_json("json", schema).alias("d")).select("d.*")
    .withWatermark("event_time", "10 minutes")            # lateness bound
    .groupBy(window("event_time", "5 minutes"), "region")
    .agg(count("*").alias("orders"))
    .writeStream
    .outputMode("update")
    .option("checkpointLocation", "s3://.../checkpoints/orders")
    .format("delta")                                       # idempotent sink
    .start())

Key concepts:

Exactly-once semantics — the important nuance:

  • Spark replays from the last checkpoint on failure, which is at-least-once at the source.
  • True exactly-once end-to-end requires an idempotent sink (or transactional): Delta/Iceberg upsert by key, or Kafka idempotent producer + transactions.
  • Combined with checkpointLocation + replayable source (Kafka offsets) + idempotent sink → effectively exactly-once.

Exactly-once checklist I state: replayable source (Kafka/Kinesis with committed offsets) + durable checkpoint + idempotent/deduplicating sink + a dedup key/dropDuplicates on event id.

4. Big Data: Hadoop, Hive & Partitioning

Why this section exists:_ Most JDs list Big Data and Hadoop / Hive as first-class skills, and consulting firms with a BI heritage often grew out of a Big Data practice — so this heritage matters more than at a pure cloud-native shop. The JD also specifically asks for “designing Hive tables with partitioning for performance“._

Q47: Give an overview of the Hadoop ecosystem. What does each component do?

Description: Tests breadth — you should be able to place every tool on the map without hesitation.

Detailed Answer:

Hadoop was the original open-source big-data stack; its components still name the concepts Spark and cloud data lakes are built on.

┌────────────────────────────────────────────────────────────┐
│  COORDINATION / WORKFLOW   Zookeeper · Oozie / Airflow      │
├────────────────────────────────────────────────────────────┤
│  QUERY & SQL               Hive · Pig · Spark SQL · Impala │
├────────────────────────────────────────────────────────────┤
│  PROCESSING                MapReduce · Spark · Tez          │
├────────────────────────────────────────────────────────────┤
│  NoSQL / COLUMNAR          HBase · Cassandra                │
├────────────────────────────────────────────────────────────┤
│  INGESTION                 Sqoop · Flume · Kafka            │
├────────────────────────────────────────────────────────────┤
│  RESOURCE MANAGEMENT       YARN                             │
├────────────────────────────────────────────────────────────┤
│  STORAGE                   HDFS                             │
└────────────────────────────────────────────────────────────┘
┌────────────────────────────────────────────────────────────┐
│  COORDINATION / WORKFLOW   Zookeeper · Oozie / Airflow      │
├────────────────────────────────────────────────────────────┤
│  QUERY & SQL               Hive · Pig · Spark SQL · Impala │
├────────────────────────────────────────────────────────────┤
│  PROCESSING                MapReduce · Spark · Tez          │
├────────────────────────────────────────────────────────────┤
│  NoSQL / COLUMNAR          HBase · Cassandra                │
├────────────────────────────────────────────────────────────┤
│  INGESTION                 Sqoop · Flume · Kafka            │
├────────────────────────────────────────────────────────────┤
│  RESOURCE MANAGEMENT       YARN                             │
├────────────────────────────────────────────────────────────┤
│  STORAGE                   HDFS                             │
└────────────────────────────────────────────────────────────┘

Cloud mapping (say this to connect it to their stack): HDFS ↔ object storage, YARN ↔ managed cluster/K8s, MapReduce/Tez ↔ Spark on managed clusters, Hive Metastore ↔ a managed Data Catalog, Sqoop ↔ managed ingestion/DMS, Oozie ↔ workflow services. “Knowing the lineage means an on-prem client can be migrated to the cloud with a one-to-one conceptual mapping.”

Q48: Explain HDFS architecture.

Description: Foundational storage question — do not fumble the split between metadata and data.

Detailed Answer:

Why it matters:

  • Block size ≠ partition size. A block is the storage unit; a Spark/Hive partition is a logical data-organisation unit (e.g. dt=2026-10-15) that maps to a directory of files.
  • Replication gives durability (3 copies by default); modern lakehouse stacks instead rely on object storage’s own eleven-nines durability.
  • Small files hurt the NameNode (metadata pressure) exactly as they hurt Spark (per-file overhead) — the fix (compaction) is the same.

Q49: How does MapReduce work, and why is Spark faster?

Description: Tests whether you understand the shuffle heritage behind Spark’s shuffle.

Detailed Answer:

MapReduce phases:

Written as map() + reduce() + a driver to submit.

Why Spark is faster (the standard answer, made precise):

  1. In-memory computation — Spark keeps intermediate data in memory (as RDD partitions) and can cache across actions; MapReduce writes every stage’s output to HDFS.
  2. DAG execution & pipelining — Spark builds one DAG for a whole computation and fuses narrow transformations, avoiding the fixed Map→Reduce→Map→Reduce materialisation of chained MR jobs.
  3. Operator fusion via Tungsten — whole-stage code generation compiles a stage into a single function.
  4. Less disk I/O — MR materialises between every job; Spark spills to disk only when needed.
  5. Rich API + Catalyst optimizer — declarative DataFrames get rule-based + cost-based optimization for free.

Interview tip: “The shuffle is common to both — and that’s the point. MapReduce taught us that the shuffle is the cost. Spark didn’t remove the shuffle; it removed the round-trips to disk around it.”

Q50: What is YARN and how do resources get allocated?

Description: Needed to explain cluster behaviour and answer “why is my job waiting in a queue”.

Detailed Answer:

YARN (Yet Another Resource Negotiator) decouples resource management from processing.

How a Spark-on-YARN job gets resources:

  1. Client submits the app to the RM.
  2. The RM launches an ApplicationMaster (in cluster mode, the Spark driver runs inside it).
  3. The AM requests executor containers from the RM based on your --executor-memory/--num-executors/cores.
  4. NMs launch executors; the driver schedules tasks onto them.
  5. When the app finishes, containers are released.

Queues & capacity: YARN queues (e.g. default, ETL, ad-hoc) give capacity/fair-share between teams. A job “stuck” is usually queued for resources, not failing — check the RM UI for available memory vs requested. Memory requests are executor memory + overhead, so overhead requests are a frequent cause of “not enough resources” on a cluster with free-looking memory.

Q51: Hive — architecture and the difference between managed and external tables?

Description: Hive is explicitly in most JDs. This question is expected verbatim.

Detailed Answer:

Hive architecture:

  • Hive Metastore — stores table schemas, column types, partitions, and the storage location of each table. This is the catalogue the whole Hadoop ecosystem reads.
  • HiveQL / driver — parses the query, compiles a plan, and (historically) submits MapReduce (now often Tez or Spark).
  • Execution engine — Tez/Spark; storage — HDFS/object storage in ORC/Parquet.
  • On cloud, the metastore role is played by a managed Data Catalog, so the query engine, the managed cluster and the warehouse spectrum all share one catalogue.

Managed vs External tables:

CREATE EXTERNAL TABLE raw_orders (...)
PARTITIONED BY (dt STRING)
STORED AS PARQUET
LOCATION 's3://bucket/raw/orders/';   -- DROP leaves the data intact
CREATE EXTERNAL TABLE raw_orders (...)
PARTITIONED BY (dt STRING)
STORED AS PARQUET
LOCATION 's3://bucket/raw/orders/';   -- DROP leaves the data intact

Interview tip: “In a shared client lakehouse I default to external tables — the platform shouldn’t own data that other teams and tools depend on, and a dropped catalogue entry must never delete a client’s data. Managed tables are for tables the pipeline genuinely owns end-to-end.”

Q52: Hive partitioning vs bucketing — when do you use each?

Description: The JD specifically calls out “designing Hive tables with partitioning for performance”. This is the question they mean.

Detailed Answer:

Design rules I state:

  • Partition by the most common filter column — almost always a date (dt), sometimes region. This gives the biggest win because most queries filter by time.
  • Bucket by the high-cardinality join key when you do repeated large joins on it — equal bucket counts on both sides enable an efficient sort-merge-bucket join with no shuffle.
  • Target file sizes of 100–256 MB within a partition.
  • Avoid over-partitioning — don’t partition by something with millions of values (e.g. user_id).
  • Use MSCK REPAIR TABLE (or ALTER TABLE ADD PARTITION) to sync the metastore after new partitions land; on cloud, partition projection avoids this entirely for time-series data.

Example:

CREATE TABLE fact_orders (
    order_id  STRING,
    customer_id STRING,
    amount    DECIMAL(12,2)
)
PARTITIONED BY (dt STRING)               -- pruned by date filters
CLUSTERED BY (customer_id) INTO 64 BUCKETS   -- join key
STORED AS ORC;
CREATE TABLE fact_orders (
    order_id  STRING,
    customer_id STRING,
    amount    DECIMAL(12,2)
)
PARTITIONED BY (dt STRING)               -- pruned by date filters
CLUSTERED BY (customer_id) INTO 64 BUCKETS   -- join key
STORED AS ORC;

Q53: How do you design Hive tables for performance?

Description: Combines file format, partitioning and compression — a design question a Lead must answer crisply.

Detailed Answer:

My Hive table design checklist:

  1. File format: ORC (Hive-native, excellent predicate pushdown + compression) or Parquet (better cross-engine, row-group statistics). Pick one and be consistent. Avoid text/CSV at scale.
  2. Compression: Snappy (fast, splittable, the workhorse) or Zstd (better ratio, slightly more CPU). Avoid gzip at scale — not splittable.
  3. Partitioning: by the top filter column (usually dt), sized to ~100–256 MB files, avoiding over-partitioning.
  4. Bucketing: on high-cardinality join keys for repeated joins.
  5. Statistics: ANALYZE TABLE ... COMPUTE STATISTICS so the optimizer can cost plans.
  6. Predicate pushdown / column pruning: only works if you write columnar AND avoid SELECT *.
  7. Small-file control: compaction, ALTER TABLE ... CONCATENATE (ORC), or an AQE/coalesce write.
  8. Storage layout: for object-store-backed “Hive” tables, keep partitions as prefixes and consider partition projection.
  9. Table type: external for shared/raw data.

Interview tip: “The order of impact is: partition by date → use ORC/Parquet with Snappy → bucket only if you repeatedly join on a high-cardinality key → keep files ~128 MB. Partitioning and columnar format give you most of the win; bucketing is the specialised lever.”

Q54: How does Hive fit with Spark and a shared Data Catalog?

Description: Tests whether you understand a shared metastore — central to any lakehouse.

Detailed Answer:

  • Hive Metastore (HMS) is the schema catalogue: it stores database/table definitions, columns, partition locations and formats. It does not store data.
  • Spark on a managed cluster can use the Hive metastore so spark.sql("SELECT * FROM db.table") resolves tables registered in Hive — the same tables Hive, Tez and Presto/Athena read.
  • On cloud, a managed Data Catalog is the equivalent: the query engine, the managed Spark service, the warehouse spectrum and ETL all share it. Spark uses a catalogue-backed metastore via the catalog integration.

Producers (Spark/ETL)  ──►  Managed Data Catalog  ──►  Consumers (Athena, Redshift Spectrum, EMR, BI)
        │                          ▲
        └────── Object storage ────┘  (catalogue points to storage locations)
Producers (Spark/ETL)  ──►  Managed Data Catalog  ──►  Consumers (Athena, Redshift Spectrum, EMR, BI)
        │                          ▲
        └────── Object storage ────┘  (catalogue points to storage locations)

Why it matters (say this): “A shared catalogue is what turns separate tools into one lakehouse. One table definition, one source of truth for schema and location, and every engine sees the same data. That’s the architecture a modern consulting practice sells, and it’s how I’d unify a client’s Hive, Spark and Athena consumers.”

Q55: How do you deal with the small-files problem in Hive/HDFS?

Description: A real operational pain, and it connects Hive to the Spark/cloud answers.

Detailed Answer:

Why small files are bad:

  • NameNode/metastore pressure — every file and partition consumes master memory. Millions of tiny files can take down the NameNode.
  • Slow scans — per-file open/seek overhead dominates; every Spark task pays the cost.
  • Wasted parallelism — thousands of tiny tasks with high scheduling overhead.

How they get created: streaming micro-batches writing every few seconds, over-partitioned tables, jobs writing with too many output partitions, frequent small appends.

Fixes:

Interview tip: “I treat small files as technical debt with a payment schedule — a compaction job runs on a timer, and I set a target file size in the write path. It’s the same pattern as Delta OPTIMIZE; only the tool changes.”

Q56: Hive vs Spark SQL — when would you use which?

Description: Tests pragmatic tool selection rather than tribal loyalty.

Detailed Answer:

My position: “For new pipelines I default to Spark SQL — same SQL surface, but with Catalyst, AQE and in-memory speed. I keep Hive where it’s already proven (huge, disk-tolerant batch jobs, legacy dependencies) and I never rewrite a working Hive job without a measured reason. On cloud that’s a managed Spark engine or Athena for ad-hoc, with a shared catalog so both see the same tables.”

This “don’t rewrite what works, but standardise new builds” answer signals judgment, not fashion-chasing.

Q57: Batch vs streaming architecture — Lambda vs Kappa?

Description: Most JDs require both batch and streaming, so a Lead must know when to choose each.

Detailed Answer:

How I decide (say this):

  • Latency requirement drives it. If the business can live with hourly/daily, batch — cheapest, simplest, most accurate. Don’t stream for streaming’s sake.
  • Replayability drives Kappa feasibility. If the source events are retained in Kafka/Kinesis and I can replay, Kappa works.
  • Complexity drives Lambda’s cost. Two codebases mean two test suites, two failure modes, and inevitable drift.
  • My default in practice: a unified lakehouse — land raw (batch or stream) into Bronze, process with one engine (Spark/Structured Streaming) into Silver/Gold, with idempotent, replayable writes. That collapses most Lambda complexity into one path.

Interview tip: “I ask the business what decision the data changes and how fast it must change. Nine times out of ten the answer is hourly, not sub-second — and the honest engineering answer is a batch pipeline with a unified lakehouse, not a Kafka cluster nobody needed.”

5. AWS Data Engineering Services

Why this section exists:_ Most JDs name a specific set of AWS services — typically EMR, Kinesis, Kafka, Lambda, Glue, Athena, Redshift, Step Functions. Consulting firms_ deliver on these, so expect practical, “how would you design / how would you fix / when would you use which” questions rather than definitions.

Q58: Design an end-to-end data pipeline on AWS. Walk me through it.

Description: The signature architecture question. Draw the boxes and justify each choice. This answer should be reusable for any “design a pipeline” follow-up.

Detailed Answer:

A reference architecture (adapt the middle to the client’s reality):

SOURCES              INGEST                 STORE              PROCESS                  SERVE
┌─────────┐   ┌──────────────────┐   ┌──────────────┐   ┌──────────────────┐   ┌───────────────┐
│ Databases│─► │ Glue / DMS (batch)│─► │ S3 Bronze    │─► │ Glue / EMR       │─► │ Redshift (DW) │
│ APIs     │   │ Lambda (event)    │   │ (raw, JSON/  │   │ (PySpark, Spark  │   │ Athena (ad-hoc)│
│ Events   │   │ Kinesis / MSK     │   │  Avro, immut.)│   │  SQL) → Silver   │   │ QuickSight/BI │
│ Files    │   │ (streaming)       │   │              │   │   → Gold          │   │ ML feature    │
└─────────┘   └──────────────────┘   └──────────────┘   └──────────────────┘   └───────────────┘
        orchestration: Step Functions / MWAA (Airflow)   governance: Glue Catalog + Lake Formation + KMS/IAM
        observability: CloudWatch metrics/alarms + lineage
SOURCES              INGEST                 STORE              PROCESS                  SERVE
┌─────────┐   ┌──────────────────┐   ┌──────────────┐   ┌──────────────────┐   ┌───────────────┐
│ Databases│─► │ Glue / DMS (batch)│─► │ S3 Bronze    │─► │ Glue / EMR       │─► │ Redshift (DW) │
│ APIs     │   │ Lambda (event)    │   │ (raw, JSON/  │   │ (PySpark, Spark  │   │ Athena (ad-hoc)│
│ Events   │   │ Kinesis / MSK     │   │  Avro, immut.)│   │  SQL) → Silver   │   │ QuickSight/BI │
│ Files    │   │ (streaming)       │   │              │   │   → Gold          │   │ ML feature    │
└─────────┘   └──────────────────┘   └──────────────┘   └──────────────────┘   └───────────────┘
        orchestration: Step Functions / MWAA (Airflow)   governance: Glue Catalog + Lake Formation + KMS/IAM
        observability: CloudWatch metrics/alarms + lineage

The walkthrough I’d give, layer by layer:

  1. Ingest — batch from databases via Glue or DMS; file drops via Lambda/S3 events; streaming via Kinesis Data Streams (or MSK/Kafka if the client already runs Kafka). Land raw and immutable.
  2. Store (Bronze) — S3 landing zone, partitioned (dt=YYYY-MM-DD), format = source-native (JSON/Avro) or Parquet if already clean. Object Lock/versioning where audit is required.
  3. Process (Silver/Gold) — Glue for serverless Spark and EMR/EMR Serverless for heavier or long-running Spark. Cleanse, conform, de-duplicate and DQ-gate into Silver; build business-level Gold aggregates/dimensions.
  4. Serve — Redshift for BI/high-concurrency SQL; Athena for ad-hoc SQL on S3; QuickSight/BI on top; Gold tables as ML features.
  5. Orchestrate — Step Functions for AWS-native event-driven flows, MWAA (Airflow) for complex DAGs with SLAs; Glue Workflows for simple chains.
  6. Govern — Glue Data Catalog for schema/lineage, Lake Formation for fine-grained access, IAM + KMS for security, CloudWatch for alarms.

Design principles I’d state:

  • Idempotent, re-runnable every step.
  • Decoupled layers (Bronze/Silver/Gold) so a source change doesn’t ripple to consumers.
  • Config-driven ingestion so a new source is a config, not a new job.
  • Cost-aware: serverless for spiky, provisioned for steady; Spot on EMR; lifecycle policies on S3.
  • Governed by default: catalogue + access control from day one.

Interview tip: “I always ask the client two questions before drawing: what decision does this data change, and how fresh must it be? Those two answers pick the whole architecture — batch vs streaming, Redshift vs Athena, Glue vs EMR.”

Q59: How do you design S3 for a data lake?

Description: S3 is the foundation of every AWS lakehouse. Layout mistakes are expensive to fix.

Detailed Answer:

Layout:

s3://client-data-lake/
├── bronze/  source=orders/  dt=2026-10-15/  part-*.parquet     # raw, immutable, partitioned by dt
├── silver/  orders/         dt=2026-10-15/  ...
├── gold/    dim_customer/   ...                                 # curated/business-ready
└── sandbox/                                                     # ad-hoc/experimentation
s3://client-data-lake/
├── bronze/  source=orders/  dt=2026-10-15/  part-*.parquet     # raw, immutable, partitioned by dt
├── silver/  orders/         dt=2026-10-15/  ...
├── gold/    dim_customer/   ...                                 # curated/business-ready
└── sandbox/                                                     # ad-hoc/experimentation

Key design decisions:

Anti-patterns to name: partitioning by high-cardinality ids (millions of prefixes), un-compressed/un-columnar at scale, no lifecycle policy, and public/shared buckets with over-broad IAM.

Interview tip: “In a lakehouse, S3 is the storage layer and everything else is compute. So I design S3 layout once, carefully — partition scheme, format, and lifecycle — because changing it later means rewriting everything on top.”

Q60: AWS Glue — crawlers, catalog, jobs, and when to choose Glue over EMR?

Description: Glue is explicitly in most JDs, and Glue-vs-EMR is a favourite comparison.

Detailed Answer:

Glue components:

Pricing model: DPU-hours — you pay for provisioned/consumed Data Processing Units (1 DPU = 4 vCPU + 16 GB). This is the crux of the Glue-vs-EMR decision.

Glue vs EMR decision matrix:

My rule of thumb: “Glue for spiky, moderate ETL and anything that needs crawlers/catalog; EMR (often Serverless) for heavy, sustained, tuned Spark where cost per CPU-hour matters. Both share the Glue Catalog, so I can move a job between them with minimal change.”

Q61: EMR — architecture, EMR Serverless, Spot instances, and tuning?

Description: EMR is usually the first AWS service in the JD’s list. Expect practical depth.

Detailed Answer:

EMR architecture: a managed Hadoop/Spark cluster = a master node (drivers, NameNode/ResourceManager) + core nodes (HDFS data + compute) + task nodes (compute only, no HDFS — ideal for Spot). EMR manages provisioning, bootstrap actions, and integrates with Glue Catalog, S3, and Lake Formation.

Cluster types / deployment:

  • Transient clusters — spin up per job, terminate when done (cost-efficient for batch).
  • Long-running clusters — persistent for ad-hoc/BI workloads.
  • EMR Serverless — no cluster to manage; submit a job with configurable workers; pay per vCPU/memory-second. Great for variable workloads.
  • EMR on EKS — Spark on Kubernetes for teams standardised on K8s.

Spot instances: up to ~90% cheaper; used on task nodes (stateless) so an interruption just re-runs tasks. Combine with on-demand core nodes for safety. Managed Scaling + instance fleets handle capacity automatically.

Tuning levers (connect to Q42):

  • Right-size executors: cores/executor (keep ≤ 5), memory, memoryOverhead.
  • Enable AQE; tune shuffle.partitions.
  • Use Spot for task nodes; Graviton instances for price-performance.
  • Enable S3 as the storage layer (EMRFS) and avoid HDFS for lakehouse data.
  • Set maximizeResourceAllocation or configure manually for known jobs.
  • Watch CloudWatch/Spark UI for skew and spill.

Interview tip: “For batch lakehouse work I default to EMR Serverless — no cluster lifecycle to babysit, and it scales with the job. For heavy sustained loads I use a cluster with on-demand core nodes and Spot task nodes, because that’s where the cost per CPU-hour wins.”

Q62: How do you use Lambda in a data pipeline? What are its limits?

Description: Lambda is in most AWS JDs; interviewers want to see you use it correctly (small, event-driven) and not as a batch engine.

Detailed Answer:

Where Lambda fits in data engineering:

  • Event-driven ingestion — S3 ObjectCreated → Lambda → validate/copy/trigger a downstream job.
  • Light transforms — small files, one-off cleanups, metadata extraction.
  • API extraction / pagination — pull a paginated API and drop JSON to S3 (Lambda handles the loop, not the heavy transform).
  • Orchestration — Lambda as a task in a workflow, or to start a job run.
  • Alerting / notifications — react to CloudWatch alarms, EventBridge events, SNS.

Limits to know:

Anti-patterns to name: doing the actual heavy transformation in Lambda, using it as a scheduler for long jobs (Step Functions is the scheduler), unbounded recursive S3 triggers, and storing data in /tmp.

Interview tip: “Lambda is glue, not an engine. It triggers work, does small stateless transforms, and orchestrates — but the moment I need more than 15 minutes or real throughput, the answer is Glue or EMR, with Lambda just kicking it off.”

Q63: Step Functions — when do you use it, and how does it compare to Airflow?

Description: Step Functions is in most JDs; the Airflow comparison is a common follow-up.

Detailed Answer:

Step Functions is a serverless state machine: you define states (Task, Choice, Parallel, Map, Wait, Retry, Catch) as JSON (Amazon States Language) and it orchestrates AWS services (Glue, EMR, Lambda, ECS, Athena, SNS).

Why use it:

  • Serverless, no infrastructure — no cluster/scheduler to run.
  • Built-in retries, error catching, and backoff per state.
  • Visual execution history — every state transition is recorded; powerful for debugging a failed pipeline.
  • Native AWS integration — first-class calls to Glue/EMR/Lambda with .sync waiting patterns.
  • Map state — fan out over a list (e.g. process N files in parallel).

Step Functions vs Airflow (MWAA):

My rule: “Step Functions for event-driven, AWS-native orchestration and short workflows — it’s serverless and the execution history is unbeatable for debugging. Airflow/MWAA for complex DAGs with lots of Python logic, dynamic task generation, or cross-cloud/cross-tool dependencies.”

Q64: Compare Kinesis Data Streams, Kinesis Data Firehose, and Managed Flink.

Description: Kinesis is in most JDs. The three-way distinction is a standard screening question.

Detailed Answer:

Decision path: need custom/multiple consumers or replay → KDS. Just want data in S3/warehouse with no code → Firehose (and convert to Parquet in-flight). Need windows, joins, sessionization → Flink. Or bring Kafka (MSK) if the client already speaks Kafka.

Interview tip: “Firehose is the ‘set and forget’ path to a lake; KDS is the stream you build consumers on; Flink is when you need real stream processing. Most clients need Firehose and think they need Flink — I right-size it.”

Q65: Explain Kafka on AWS (MSK) — topics, partitions, consumer groups, offsets, exactly-once.

Description: Kafka is in most JDs. Expect a rigorous answer.

Detailed Answer:

Core model:

  • Topic — a named, append-only log.
  • Partition — the unit of parallelism; a topic is split into partitions; ordering is guaranteed only within a partition, not across the topic.
  • Producer — writes to a topic; the partition key determines the target partition (same key → same partition → ordered).
  • Consumer Group — a set of consumers that share the partitions of a topic: each partition is consumed by exactly one consumer in the group. Partitions per topic = max parallelism per consumer group.
  • Offset — the position of a consumer in a partition; committed offsets are how consumers track progress and resume after restart.

Delivery semantics:

On AWS (MSK): managed Kafka clusters (MSK Serverless or provisioned). Typical pairing: Kafka → Spark Structured Streaming or Flink → S3 (Delta/Iceberg) → Athena/Redshift. Use the Glue Schema Registry for schema governance.

Exactly-once in practice (the honest answer): “Kafka-side exactly-once is transactional idempotent produce+consume. End-to-end, I combine committed offsets + a durable checkpoint + an idempotent sink — an upsert/merge by business key — so a replay after failure converges to the same result instead of duplicating rows. That’s how I actually get exactly-once semantics in production.”

Operational points: monitor consumer lag (the #1 Kafka health metric), rebalance storms, partition count tuning, replication factor (≥3), retention, and hotspot partitions from skewed keys.

Q66: Kinesis vs Kafka — how do you choose?

Description: Tests architectural judgment between the managed and the self-managed stream.

Detailed Answer:

My decision rule: “If the stack is AWS-native and the team wants zero Kafka ops, Kinesis. If the client already runs Kafka, needs the Connect/Streams ecosystem, wants multi-cloud portability, or has heavy multi-consumer fan-out and long retention, MSK/Kafka. I match the client’s existing operating model rather than my preference — reskilling a Kafka team onto Kinesis is a cost with no upside.”

Interview tip (connects to the streaming-lakehouse pitch): “Either way the destination is the same — Structured Streaming into an idempotent lakehouse sink — so the choice is an operational one, not an architectural dead-end.”

Q67: Explain Redshift’s architecture and when you’d use it over Athena.

Description: Both are in most JDs. The comparison question is almost guaranteed.

Detailed Answer:

Redshift architecture:

  • MPP, columnar warehouse — a leader node compiles queries and coordinates; compute nodes hold slices that process partitions in parallel.
  • Columnar storage + compression — reads only needed columns, heavily compressed.
  • Distribution & sort keys drive performance (Q13).
  • RA3 nodes — separate compute and managed storage (scale each independently).
  • Redshift Spectrum — query S3 directly from Redshift using the Glue Catalog.
  • Concurrency Scaling — automatically adds transient clusters for burst read load.
  • AQUA / materialized views / result caching for acceleration.

Redshift vs Athena:

My decision path: “High-concurrency BI with repeated complex queries → Redshift (its caching, materialized views and distribution keys pay off). Ad-hoc/exploratory or intermittent workloads on the lake → Athena (pay-per-scan, no cluster). And they’re not mutually exclusive: I use Athena on Bronze/Silver for exploration and Redshift on Gold for the BI layer.”

Q68: How do you optimize Athena queries and control cost?

Description: Athena’s cost model is data-scanned, so optimization is cost control. Interviewers love this.

Detailed Answer:

Athena charges per TB of data scanned, so every optimization is a cost optimization.

Optimization levers, highest impact first:

  1. Partition your data — Athena skips whole partitions (prefixes on S3) it doesn’t need. This is the single biggest lever.
  2. Use columnar format (Parquet/ORC) — reads only referenced columns, hugely compressed. CSV→Parquet is often a 10× scan reduction.
  3. Compress — Snappy/Zstd reduce bytes scanned.
  4. Avoid SELECT * — scan only needed columns (columnar formats make this real).
  5. Partition projection — for time-series data, configure projection so new partitions are found without MSCK REPAIR and without listing millions of objects.
  6. Bucket on high-cardinality filter/join columns for finer pruning.
  7. Compact small files — fewer, larger objects mean less per-object overhead and fewer reads.
  8. LIMIT where appropriate and push filters early.
  9. Workgroups + limits — per-team query limits, and CloudWatch metrics on scanned bytes.
  10. CTAS / materialized views for expensive repeated queries.

Signature example: “A query scanning 5 TB of raw CSV becomes a query scanning 150 GB of partitioned, Snappy Parquet — roughly a 30× cost reduction on the same question. Partitioning + columnar + compression is the whole game.”

Interview tip: “Athena is where a careless SELECT * has a price tag. I treat scanned-bytes per query as a monitored metric, same as latency.”

Q69: Glue vs EMR vs Lambda — give me a decision matrix for ETL.

Description: The practical “which service” question that follows any cloud architecture discussion.

Detailed Answer:

My default ladder:

  1. Event-triggered or tiny transform → Lambda.
  2. Standard, moderate ETL, spiky, catalogue needed → Glue.
  3. Heavy, tuned, sustained Spark or a big join → EMR (Serverless).
  4. Orchestration across them → Step Functions / MWAA.

Interview tip: “Because all three share the Glue Catalog and read/write the same S3 lakehouse, moving a job between them is a config change, not a rewrite. So I pick the cheapest and simplest that meets the requirement, and I don’t over-engineer.”

Q70: Data lake vs data warehouse vs lakehouse — and how do you choose on AWS?

Description: Conceptual architecture question — directly relevant to a “cloud-native lakehouse” pitch.

Detailed Answer:

How to choose on AWS: In 2026 the pragmatic default is a lakehouse: land everything in S3, add a table format for ACID/upserts/time-travel, catalogue with Glue, and serve both BI (Redshift) and ad-hoc/ML (Athena/Spark) from the same foundation. This is precisely the “modern data platform — cloud-native lakehouse” that most consulting practices describe.

Interview tip: “I don’t dogmatically choose lake or warehouse — I build the lakehouse: S3 as the single storage layer for cost and flexibility, an open table format for reliability, and the right compute per consumer. That also avoids vendor lock-in, which clients care about.”

Q71: How do you orchestrate data pipelines on AWS? And with Autosys/CA Workload?

Description: Covers the “scheduling tool like Autosys, CA Workload Automation” mention that appears in some JDs. Answer the AWS tools and translate to Autosys.

Detailed Answer:

AWS orchestration options:

Cross-tool pattern: EventBridge (schedule/event) → Step Functions or Airflow → Glue/EMR/Lambda tasks, with CloudWatch alarms on SLA breaches.

Translating to Autosys / CA Workload Automation (the JD’s tools):

“I orchestrate with Airflow/MWAA and Step Functions. The scheduling concepts are identical to Autosys or CA Workload Automation — job dependencies, calendars and run windows, conditional triggers, retries with backoff, critical-path SLAs and alerting. An Autosys JIL is a declarative job definition; an Airflow DAG is a Python one. The harder skills — designing dependency graphs, avoiding fan-in bottlenecks, setting SLAs, handling late-arriving data — are 100% transferable. I’d be productive in Autosys in days.”

Interview tip: “I care about the dependency graph and the SLAs, not the logo. Whether it’s Autosys, Airflow or Step Functions, the same three questions decide the design: what depends on what, what’s the deadline, and what happens when it fails?”

Q72: How do you secure and govern data on AWS?

Description: Most JDs explicitly name “quality, security and compliance requirements”. A Lead must answer this well.

Detailed Answer:

Security layers:

Governance:

Interview tip: “Security and compliance aren’t a phase at the end — they’re a design constraint from the first table. My rule is least-privilege access via Lake Formation, encrypt with customer-managed KMS keys, mask PII at the Silver layer so raw sensitive data never reaches Gold, and log every access with CloudTrail. That’s what I’d hold a client’s platforms to.”

Q73: How do you monitor and operate AWS data pipelines?

Description: Tests the “assures quality and compliance” and “fault-tolerance” responsibilities.

Detailed Answer:

Monitoring across the stack:

What I actually alert on (the signals that matter):

  1. Job failure — pipeline didn’t complete.
  2. SLA miss — job completed but late.
  3. Data-quality breach — volume drop/spike, null rate spike, referential failure.
  4. Consumer lag (Kinesis/Kafka) — falling behind.
  5. Cost anomaly — a job that suddenly scans or provisions far more.
  6. Skew/slow-job regression — duration up vs the trailing baseline.

Operational practices:

  • Idempotent jobs so a retry is always safe.
  • Automatic retries with backoff for transient failures (Step Functions Retry, Airflow retries).
  • Dead-letter queues/paths for unprocessable records — quarantine, don’t crash.
  • Runbooks + on-call for recurring failure modes.
  • Reconciliation at layer boundaries (source count = landed count = transformed count).

Interview tip: “A pipeline isn’t done when it runs — it’s done when it’s observable. I instrument four things: did it run, did it finish on time, is the data right, and did it cost what I expected. Those four alerts catch almost every production incident before a business user does.”

Q74: How do you optimize cost across an AWS data platform?

Description: Directly relevant to a consulting practice where cost-per-record is part of the value proposition.

Detailed Answer:

By service:

Engineering levers:

  • Right-size compute based on measured utilisation, not guesses.
  • Partition & format for minimal bytes scanned.
  • Schedule heavy jobs in off-peak windows where batch pricing applies.
  • Tag everything so cost is attributable per pipeline/team.
  • Set budgets and anomaly alerts so cost regressions surface as incidents.
  • Fix skew and shuffles — inefficient Spark burns money as well as time.

Interview tip: “I treat cost like latency — a first-class SLO with instrumentation and alerts. On a client engagement, cost-per-record is part of the deliverable, so a 25% compute reduction is a business outcome, not an infrastructure footnote.”

Q75: How do you build a fault-tolerant pipeline that works in both batch and streaming?

Description: Ties together “fault-tolerance”, “streaming and batch mode”, and idempotency themes — a great closing design question.

Detailed Answer:

The unifying principle: one processing contract, two ingestion modes — both idempotent.

STREAMING:  Kinesis/Kafka ──► Structured Streaming ──┐
                                                       ├──► SAME transforms ──► idempotent sink (Bronze/Silver)
BATCH:      S3/Glue/DMS ─────► Spark batch ──────────┘
STREAMING:  Kinesis/Kafka ──► Structured Streaming ──┐
                                                       ├──► SAME transforms ──► idempotent sink (Bronze/Silver)
BATCH:      S3/Glue/DMS ─────► Spark batch ──────────┘

Design rules I’d state:

  1. Same transformation logic for both — factor transforms into shared functions/SQL so batch and stream don’t drift. Only the read/write wrappers differ. This is how you avoid Lambda-architecture duplication.
  2. Idempotent writes — partition-overwrite (by dt) in batch, and MERGE/upsert or dedup-by-key in streaming. Re-running a batch or replaying a stream converges to the same table.
  3. Checkpointing (streaming) — durable checkpointLocation so a restart resumes from the last committed offset, not the beginning.
  4. Replayable source — Kafka/Kinesis retention means you can reprocess; batch sources land immutably in Bronze.
  5. Exactly-once via idempotency — committed offsets + checkpoint + idempotent sink (Q46, Q65).
  6. Dead-letter / quarantine path — bad records are set aside with an alert, never silently dropped or allowed to kill the job.
  7. Watermarking (streaming) — bound lateness and state growth.
  8. Retries with backoff + DLQ (both) — handle transient failures (throttling, network) gracefully.
  9. DQ gates at layer boundaries — Bronze→Silver, Silver→Gold.
  10. Reconciliation — counts/sums match across layers and modes.

Lead-level framing: “Fault-tolerance isn’t a feature you add — it’s a property you design in. Replayable source + checkpoint + idempotent sink + DQ gate + dead-letter path = a pipeline you can safely re-run at 2 a.m. without a human double-checking the row counts.”

6. Data Modelling, ETL & ELT

Why this section exists:_ Most JDs list Data Modelling as a core skill and call out “strong understanding of concepts of ETL, ELT and data modeling”. Firms with a BI/warehouse heritage care about_ modelling_, not just plumbing._

Q76: Explain dimensional modelling — star vs snowflake, facts vs dimensions, and grain.

Description: The foundational modelling question. The word grain should appear in your answer early — it signals real modelling experience.

Detailed Answer:

Facts vs dimensions:

  • Fact tables — the measurements (transactions, events, snapshots). They hold foreign keys to dimensions + numeric measures + degenerate keys. They are long and narrow and grow fast.
  • Dimension tables — the context (customer, product, date, store). They are wide with descriptive attributes, are usually shorter, and are what you slice and filter by.
  • Grain — the level of detail of one fact row (e.g. “one row per order line”). Declare the grain first; every modelling decision follows from it. Mixing grains in one table is the most common modelling error.

Star vs snowflake:

Other schema types: Galaxy (multiple fact tables sharing conformed dimensions — the enterprise norm), Data Vault (Q80), Wide/OBT (one big table — fast but costly to maintain).

My design process (say this):

  1. Pick the business process (sales, shipments, clicks).
  2. Declare the grain — the most atomic level the business needs.
  3. Identify the dimensions that apply.
  4. Identify the facts/measures and their additivity (additive, semi-additive, non-additive).
  5. Conform the dimensions across facts so they can be joined consistently.

Interview tip: “I always start from the grain, because grain is the one decision you cannot quietly fix later. Get the grain right and the model stays consistent; get it wrong and every downstream number is subtly wrong.”

Q77: Normalization vs denormalization — where do you apply each?

Description: Tests whether you understand the OLTP-vs-analytics divide rather than memorising normal forms.

Detailed Answer:

Normal forms (short version):

  • 1NF — atomic values, no repeating groups.
  • 2NF — 1NF + no partial dependency on part of a composite key.
  • 3NF — 2NF + no transitive dependency (non-key attribute depending on another non-key attribute).

My rule: “Normalize at the source and in the integration/staging layer to protect integrity; denormalize in the consumption (Gold/mart) layer to protect query performance. Different layers have different jobs — so the answer isn’t ‘normalize’ or ‘denormalize’, it’s ‘at which layer’.”

Trade-off to name honestly: denormalization duplicates data, which means keeping duplicated attributes consistent is your new problem — solved by engineered (automated, idempotent) loads rather than manual updates.

Q78: ETL vs ELT — when do you choose each?

Description: Explicit in most JDs. The modern answer leans ELT, but a Lead must justify it.

Detailed Answer:

Why ELT wins on cloud: S3 storage is cheap and elastic compute is powerful, so landing raw and transforming in-place is simpler, more flexible, and lets you re-derive when business logic changes — you never lose the source of truth. This is the medallion pattern (Q79) in practice.

My position: “On a cloud lakehouse I default to ELT: land raw in Bronze, transform through Silver and Gold with Spark/SQL. The exception is compliance — if a source contains PII I’m not allowed to persist raw, I apply a masking step at ingestion, which is effectively a hybrid. The decision is driven by cost, flexibility and compliance, not fashion.”

Interview tip: “Most of my ‘ETL’ is really ELT with strong contracts: Bronze is raw, Silver is typed and quality-gated, Gold is business-ready. That gives me the flexibility of ELT and the correctness of a governed ETL.”

Q79: What is the Medallion architecture, and how does it map to a lakehouse?

Description: The dominant modern lakehouse pattern and directly aligned with a “cloud-native lakehouse” positioning.

Detailed Answer:

Medallion = layered data refinement on the lake:

Sources → Bronze (raw) → Silver (clean/conformed/DQ) → Gold (business-ready)
          immutable        typed, de-duplicated           aggregates/dims/features
          replayable       quality contracts              fast for BI/ML
Sources → Bronze (raw) → Silver (clean/conformed/DQ) → Gold (business-ready)
          immutable        typed, de-duplicated           aggregates/dims/features
          replayable       quality contracts              fast for BI/ML

Why it works (say this):

  • Reprocessing — because Bronze preserves the raw source, you can rebuild Silver/Gold when logic changes, without re-extracting from the source.
  • Separation of concerns — ingestion problems live in Bronze, data-quality/conformance in Silver, business logic in Gold. A change in business logic never touches ingestion.
  • Multiple consumers — BI reads Gold, data scientists read Silver + Gold, auditors read Bronze.
  • Governance — lineage flows layer to layer; PII is masked at Silver so Gold is safe to expose broadly.

Governed data products: each Gold table has an owner, a documented contract, a freshness SLA and access controls — it’s a product, not just a table.

Interview tip: “Medallion isn’t about having three folders — it’s about having three contracts. Each layer promises something specific to the layer above, and that’s what makes the platform maintainable and auditable.”

Q80: What is Data Vault modelling and when would you use it?

Description: A senior/lead-level differentiator; shows breadth beyond star schemas.

Detailed Answer:

Data Vault 2.0 models the enterprise integration layer as three component types:

Why it exists: it’s designed for auditability, agile loading, and parallel source integration. Because hubs hold business keys and satellites are append-only with load dates, the model is highly resilient to source changes and supports full history by construction (a “raw vault” is historically accurate).

Strengths:

  • Auditable — every record carries load date/source; nothing overwrites.
  • Flexible — add a source or a satellite without reworking the model.
  • Parallel-load-friendly — hubs/satellites load independently.
  • Handles multi-source integration where the same entity arrives from several systems.

Weaknesses:

  • Complex and join-heavy — not for direct BI; you build star-schema marts on top for consumption.
  • Overkill for small/single-source cases — the ceremony isn’t free.

My position: “Data Vault is the right integration layer when many source systems must converge into one auditable enterprise model — I’d choose it for a large multi-source integration. For most marts I use star schemas on top of a vault, or a Medallion layering if the estate is simpler. I match the modelling paradigm to the integration complexity, not to a preference.”

Q81: How do you handle slowly changing dimensions and late-arriving data?

Description: Extends SCD (Q8) into the operational realities of pipes that arrive out of order and late.

Detailed Answer:

SCD recap: Type 1 (overwrite), Type 2 (new row + validity dates + current flag — full history), Type 3 (previous-value column). Type 2 is the analytics default when “as-of” history matters.

Late-arriving dimensions: a fact arrives referencing a dimension key that hasn’t landed yet.

  • Option A — inferred/placeholder member: insert a “late-arriving”/”unknown” dimension row (e.g. nk = 'UNKNOWN'), then back-fill when the real dimension arrives.
  • Option B — reprocess: hold the fact or reprocess the affected window once the dimension lands (only feasible if the fact is replayable — another argument for Medallion + idempotency).
  • Option C — surrogate key at fact-load: assign the current dimension version and accept eventual reconciliation in the dimension.

Late-arriving facts (out-of-order events): an event with an older event_time arrives after you’ve already processed later data — common in streaming.

  • Use watermarking (streaming) to accept events within a lateness bound.
  • For batch, reprocess the partition the event belongs to (partition-overwrite by dt), which is idempotent — this is why event-time partitioning matters.
  • Keep a reconciliation step so the correction is visible, not silent.

Lead-level framing: “Late-arriving data is where idempotency earns its keep. Because my loads are partition-overwrite and time-partitioned by event time, a corrected record just means re-running one partition — cheap, safe, and reproducible. In streaming I bound lateness with a watermark and rely on the upsert sink for the rest.”

Q82: How do you make a pipeline idempotent and support backfills?

Description: Idempotency is the linchpin of the “fault-tolerance” requirement. This is a high-value Lead question.

Detailed Answer:

Idempotency = running the same job twice for the same input yields the same result (no duplicates, no drift). Without it, every retry corrupts the table.

Techniques:

Backfills — reprocessing history safely:

  1. Parameterise by run window — every job takes a run_date/window, not “yesterday”.
  2. Re-runnable in isolation — a backfill for 2026–09–01 must not disturb other dates → partition-overwrite makes this true.
  3. Control concurrency — limit parallel backfill jobs so they don’t starve production SLAs or blow the budget.
  4. Recompute downstream — a backfill must cascade: if Silver changes, Gold partitions that depend on them must be rebuilt. An orchestration tool with dependency-aware backfill (Airflow --clear/catchup, or a Step Function map) handles this.
  5. Reconcile and validate — after a backfill, re-run DQ checks and reconciliation for the affected range.
  6. Audit — log what was backfilled, why, and the row deltas.

Interview tip: “Every pipeline I ship is parameterised by its run window and writes idempotently — partition-overwrite in batch, MERGE in streaming. That single discipline turns ‘the job failed, fix it and hope’ into ‘re-run it’, which is what fault-tolerance actually looks like in operations.”

Q83: How do you build a data quality framework?

Description: Directly addresses the “quality… requirements are met” responsibility.

Detailed Answer:

Quality dimensions I check:

Where to enforce: at layer boundaries — on landing (Bronze), on conformance (Silver), and on business rules (Gold). Enforce at the layer where the defect occurs, not at the consumer.

What a check does on failure:

  • Fail fast for critical checks (stop the pipeline, alert) — e.g. a null spike in a financial column.
  • Quarantine for record-level issues — route bad rows to a dead-letter path with an alert, keep processing the good ones.
  • Warn for soft checks — log and monitor.

Implementation on AWS: DQ rules as code (in the transform job, or Glue Data Quality / Great Expectations / pandera), results to CloudWatch with alarms, a DQ scorecard per table, and lineage so a consumer can see the table’s quality history.

Lead-level framing: “Data quality is a contract, not a report. Every table has an owner, declared thresholds, and an automated check that runs with the pipeline. When a check fails, the pipeline either stops or quarantines — it never silently publishes bad data. And I always investigate the cause upstream rather than papering over it downstream.”

Q84: How do you create metadata-driven pipelines and manage lineage?

Description: A strong differentiator for a consulting role — the metadata-driven framework is exactly what a practice needs for repeatable delivery.

Detailed Answer:

Metadata-driven (configuration-over-code): instead of writing bespoke code per source, describe each source declaratively and let a generic engine execute it.

= 0" }” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# one config file per source
source: crm_orders
type: api            # api | jdbc | file | stream
endpoint: https://crm/orders
auth: sm://crm/token
pagination: { style: cursor, size: 500 }
target: s3://lake/bronze/crm_orders/
partition: ingest_dt
retry: { max: 5, backoff: exponential }
dq:
  - not_null: [order_id, customer_id]
  - unique: [order_id]
  - range: { amount: ">= 0" }
# one config file per source
source: crm_orders
type: api            # api | jdbc | file | stream
endpoint: https://crm/orders
auth: sm://crm/token
pagination: { style: cursor, size: 500 }
target: s3://lake/bronze/crm_orders/
partition: ingest_dt
retry: { max: 5, backoff: exponential }
dq:
  - not_null: [order_id, customer_id]
  - unique: [order_id]
  - range: { amount: ">= 0" }

Why it wins: a new dataset is a config change, not a development task — this cuts onboarding time dramatically (40% in my experience) and makes quality/retry behaviour consistent across every source instead of re-implemented per pipeline.

Lineage & metadata:

  • Technical lineage — which source table fed which transform produced which target table/column. Captured from the Glue Catalog, Spark plans, or a lineage tool (DataZone, OpenLineage, dbt).
  • Business lineage — the mapping from a business metric (“GMV”) down to the columns and sources.
  • Operational metadata — run times, row counts, DQ results, freshness, cost.

Why it matters: “Lineage is what lets you answer ‘where did this number come from?’ and ‘what breaks if I drop this column?’ in minutes instead of days. In a client engagement, that’s the difference between a platform people trust and one they route around.”

Governed data products: catalogue every Gold table with an owner, description, freshness SLA, quality score and access policy — so consumers can self-serve safely.

7. Terraform, IaC, CI/CD & Git

Why this section exists:_ Most JDs list IaC tools like Terraform, plus Git and CI/CD pipelines to deploy cloud applications. For a Lead, infrastructure and delivery discipline are as important as any single Spark trick._

Q85: Explain Terraform basics — providers, resources, state, and remote state.

Description: The core IaC question. If you claim Terraform, you must explain state confidently.

Detailed Answer:

Core concepts:

State — the critical part:

  • Terraform compares desired config to state to decide what to create/change/destroy.
  • Never commit local state to Git — it contains secrets and causes conflicts.
  • Use a remote backend with locking:

terraform {
  backend "s3" {
    bucket         = "client-tf-state"
    key            = "data-platform/terraform.tfstate"
    region         = "ap-south-1"
    dynamodb_table = "tf-lock"      # state locking
    encrypt        = true
  }
}
terraform {
  backend "s3" {
    bucket         = "client-tf-state"
    key            = "data-platform/terraform.tfstate"
    region         = "ap-south-1"
    dynamodb_table = "tf-lock"      # state locking
    encrypt        = true
  }
}

The S3 backend provides durable, versioned state; the DynamoDB table provides locking so two engineers can’t apply simultaneously and corrupt state.

Other essentials: terraform state list / mv / import for reconciliation, terraform fmt/validate in CI, and plan on every PR so infra changes get reviewed like code.

Interview tip: “State is the thing people get wrong. My non-negotiables: remote S3 backend, DynamoDB locking, state never in Git, and a reviewed terraform plan on every PR.”

Q86: How do you structure Terraform for multiple environments and reuse?

Description: Tests real infrastructure-management experience, not just syntax.

Detailed Answer:

Structure I use (environment-per-directory with shared modules):

infra/
├── modules/
│   ├── data-lake/          # S3 buckets, lifecycle, policies
│   ├── glue/               # jobs, crawlers, catalog
│   ├── emr/                # EMR Serverless apps, IAM
│   ├── redshift/           # cluster/serverless, WLM
│   └── networking/         # VPC endpoints, subnets
├── environments/
│   ├── dev/     main.tf  terraform.tfvars
│   ├── test/    main.tf  terraform.tfvars
│   └── prod/    main.tf  terraform.tfvars
└── global/      # IAM, state bucket, shared services
infra/
├── modules/
│   ├── data-lake/          # S3 buckets, lifecycle, policies
│   ├── glue/               # jobs, crawlers, catalog
│   ├── emr/                # EMR Serverless apps, IAM
│   ├── redshift/           # cluster/serverless, WLM
│   └── networking/         # VPC endpoints, subnets
├── environments/
│   ├── dev/     main.tf  terraform.tfvars
│   ├── test/    main.tf  terraform.tfvars
│   └── prod/    main.tf  terraform.tfvars
└── global/      # IAM, state bucket, shared services

Patterns:

  • Modules for reuse — write the resource once, instantiate per environment with different variables.
  • tfvars per environment — dev uses smaller instances, no multi-AZ, shorter retention; prod uses HA, longer retention, stricter IAM.
  • Separate state per environment — a dev apply can never touch prod state.
  • Workspaces — an alternative to directory-per-env; good for identical environments, but risky when envs differ structurally (I prefer directories for any real divergence).
  • Versioned modules — pin module versions so an upstream change doesn’t silently alter prod.

Remote environments / CI: Terraform runs in CI with a role-based backend, plan on PR, manual approval before apply to prod.

Interview tip: “Modules for reuse, directories for environments, separate state per environment. Workspaces are fine when environments are identical — but real dev/test/prod drift, so I keep them physically separate so a dev change can’t ever reach prod.”

Q87: Terraform vs CloudFormation vs CDK — how do you choose?

Description: Tests breadth and engineering judgment.

Detailed Answer:

My position: “Terraform for multi-cloud or when the client already uses it — it’s the de facto industry standard and its module ecosystem is unmatched. CloudFormation when the stack is AWS-only and the team wants zero state management. CDK when engineers want real code with types, loops and abstractions. For a data platform that spans AWS plus, say, Snowflake or Databricks, Terraform is the pragmatic default because one tool manages everything.”

Interview tip: “The tool matters less than the discipline: version control, remote state, reviewed plans, and environment isolation. I can be productive in any of the three.”

Q88: How do you set up CI/CD for data pipelines?

Description: Many JDs require “Git and CI/CD pipelines to deploy cloud applications”. This is a design question, so give a pipeline.

Detailed Answer:

CI (on every PR):

  1. Lint & format — black/ruff/flake8 for Python, terraform fmt/sqlfluff for SQL/Terraform.
  2. Unit tests — pytest on transform functions and DQ rules.
  3. Contract/schema tests — output schema matches the expected contract.
  4. SAST / quality gate — SonarQube or equivalent; fail the build on critical issues.
  5. terraform plan — show the infra diff for review; comment it on the PR.
  6. Artifact build — package the Spark job (zip/wheel/container) and bump a version.

CD (on merge to main): 7. Deploy to dev/test — upload the artifact to S3 (or push the container), update the Terraform-defined job definition, trigger a smoke-test run on a sample partition. 8. Validate with tests — run integration tests against a sandbox. 9. Manual approval → prod — promote the same immutable artifact (never rebuild for prod). 10. Deploy & verify — apply the infra change, run the pipeline, verify outputs and reconciliation, enable alerts.

PR ──► lint · unit tests · terraform plan · build artifact ──► REVIEW ──► MERGE
                                                                          │
                     deploy to test ──► smoke test ──► APPROVE ──► deploy to prod ──► verify
PR ──► lint · unit tests · terraform plan · build artifact ──► REVIEW ──► MERGE
                                                                          │
                     deploy to test ──► smoke test ──► APPROVE ──► deploy to prod ──► verify

Principles I state:

  • Same artifact to every environment — no “it worked in dev” rebuilds.
  • Infrastructure as code, config as code — a pipeline deploy is a Terraform apply, not a console click.
  • Automated tests gate the merge — a broken transform never reaches a cluster.
  • Rollback plan — versioned artifacts + versioned table snapshots (Delta/Iceberg time travel) so a bad deploy is reversible.

Tools: GitHub Actions / Jenkins / GitLab CI for orchestration; Terraform for infra; SonarQube for gates.

Q89: Explain your Git workflow for a data team.

Description: Tests day-to-day collaboration discipline — a Lead sets these norms.

Detailed Answer:

Branching: trunk-based / feature branches off main:

main ───●───●───────────●──────────► (always deployable)
                      /
feature/X ●───●───●───●            (short-lived, PR-reviewed)
main ───●───●───────────●──────────► (always deployable)
                      /
feature/X ●───●───●───●            (short-lived, PR-reviewed)
  • main is always deployable; features merge via short-lived branches through PRs.
  • PR review required — at least one peer; two for anything touching prod data models.
  • Protected main — no direct pushes, required checks (CI, tests, coverage).
  • Small, focused PRs — easier review, faster feedback, fewer conflicts.
  • Merge vs rebase — I prefer squash merges to keep main history linear and readable; rebase for keeping a feature branch current with main.

What a good PR contains: a clear description, the “why”, test evidence, a data-impact note (which tables/consumers change), and a rollback/backfill plan for schema or logic changes.

Release branches / tags: tag releases for traceability, so a production artifact maps to a commit.

Repo strategy for pipelines:

  • Monorepo — all pipelines + shared libraries in one repo with path-based CI. Easier shared standards and dependencies; needs disciplined CI scoping.
  • Polyrepo — one repo per pipeline; looser coupling but duplicated standards and harder cross-repo changes.
  • I lean monorepo for a platform team so the shared ingestion framework and DQ library are versioned together with the jobs that use them.

Interview tip: “The rule I enforce is that data code is code: reviewed, tested, versioned. No console edits to production jobs — if it isn’t in Git, it doesn’t exist.”

Q90: How do you manage secrets and promote across environments in CI/CD?

Description: Security + delivery discipline — commonly probed at Lead level.

Detailed Answer:

Secrets — never in code, never in Git:

  • AWS Secrets Manager / SSM Parameter Store — fetch at runtime via the execution role.
  • IAM roles with OIDC for CI (GitHub Actions → assume a role) — no long-lived access keys stored in CI.
  • KMS for encryption; rotate credentials on a schedule.
  • .gitignore + secret scanning (GitHub secret scanning, gitleaks) in CI to catch accidental commits.
  • Local dev uses a .env that is git-ignored, with values that aren’t production.

Promotion across environments:

  • One immutable artifact built once, promoted dev → test → prod (never rebuild).
  • Configuration differs, code doesn’t — environment-specific values come from tfvars / parameter store, not from branching code.
  • Separate accounts (recommended) or at least separate VPCs/IAM boundaries per environment — blast radius containment.
  • Approval gates before prod, with an auditable trail (who approved, what changed).
  • Database/infra migrations versioned and applied in order (e.g. numbered SQL/liquibase, or Terraform applies).
  • Rollback — versioned artifacts, versioned infra (Git), and time-travel on Delta/Iceberg tables.

Interview tip: “The two principles: secrets are fetched, never stored, and the artifact is built once and promoted. Anything else — rebuilding in prod, copying credentials into CI — is how you get a security incident or an ‘it worked in dev’ outage.”

Q91: How do you package and deploy a Spark job with its dependencies?

Description: A practical delivery question. A Lead must own the mechanics, not just the logic.

Detailed Answer:

Options:

What I recommend for production: a versioned wheel for the logic and a container image when reproducibility is critical (or the dependency set is heavy/sensitive). The image approach guarantees dev, test and prod run identical byte-for-byte environments — eliminating the classic “works on my cluster” failure.

Best practices:

  • Pin dependency versions (requirements.txt / poetry.lock) — reproducibility.
  • Build the artifact in CI, publish to S3/ECR with a version, and reference that version in the job definition (Terraform).
  • Keep entrypoints thin — main.py parses args and calls a library function.
  • Log the artifact version at job start for traceability.
  • Parameterise — pass run_date, input/output paths, config key as arguments, never hard-code.

Interview tip: “I want the exact same artifact running in every environment, referenced by version. That’s how a pipeline gets reproducible, and reproducibility is what makes a backfill trustworthy.”

8. Shell Scripting & Linux

Why this section exists:_ Most JDs list Shell scripting directly, and it appears in every real data-engineering job: bootstrap scripts, job wrappers, file orchestration, log parsing and troubleshooting._

Q92: What are your common shell-scripting patterns in data pipelines?

Description: Practical and expected — they want to see safe, production-grade scripts, not toys.

Detailed Answer:

The safety header I use in every script:

&2' ERR” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

#!/usr/bin/env bash
set -euo pipefail          # exit on error, unset var, and pipe failure
IFS=$'nt'                # safer word-splitting
trap 'echo "FAILED at line $LINENO" >&2' ERR
#!/usr/bin/env bash
set -euo pipefail          # exit on error, unset var, and pipe failure
IFS=$'nt'                # safer word-splitting
trap 'echo "FAILED at line $LINENO" >&2' ERR
  • set -e — exit on any command failure (don’t continue past an error).
  • set -u — error on undefined variables (catches typos).
  • set -o pipefail — a failure mid-pipe fails the whole pipeline (otherwise only the last command’s status counts).
  • trap — cleanup / logging on exit or error.

Common data-pipeline patterns:

/dev/null || { echo "aws CLI missing" >&2; exit 1; }
# Guarded destructive op
[ -n "$TARGET" ] || { echo "TARGET empty"; exit 1; }
rm -rf — "$TARGET"/*” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# Argument/date handling with a default
RUN_DATE="${1:-$(date -d 'yesterday' +%F)}"

# Ensure a temp dir is cleaned up on exit
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
# Retry a flaky command
retry() { local n=0; until "$@"; do
  ((n++)); [ $n -ge 5 ] && return 1; sleep $((2**n)); done; }
# Log with timestamps
log() { printf '%s %sn' "$(date -u +%FT%TZ)" "$*"; }
# Check a prerequisite before doing work
command -v aws >/dev/null || { echo "aws CLI missing" >&2; exit 1; }
# Guarded destructive op
[ -n "$TARGET" ] || { echo "TARGET empty"; exit 1; }
rm -rf -- "$TARGET"/*
# Argument/date handling with a default
RUN_DATE="${1:-$(date -d 'yesterday' +%F)}"

# Ensure a temp dir is cleaned up on exit
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
# Retry a flaky command
retry() { local n=0; until "$@"; do
  ((n++)); [ $n -ge 5 ] && return 1; sleep $((2**n)); done; }
# Log with timestamps
log() { printf '%s %sn' "$(date -u +%FT%TZ)" "$*"; }
# Check a prerequisite before doing work
command -v aws >/dev/null || { echo "aws CLI missing" >&2; exit 1; }
# Guarded destructive op
[ -n "$TARGET" ] || { echo "TARGET empty"; exit 1; }
rm -rf -- "$TARGET"/*

Where shell fits vs Python: shell for orchestration, file movement, environment setup, bootstrap actions and cron wrappers; Python (or PySpark) for the actual data logic. I use shell as the thin glue and keep the analysis in Python.

Interview tip: “The single most important line in any pipeline script is set -euo pipefail. Without it, a failing step sails through and you discover the problem downstream — in the data.”

Q93: How do you process large files with awk/sed/grep/sort? When does shell beat Python?

Description: Tests practical Linux fluency, which matters for on-prem/Hadoop estates with flat files.

Detailed Answer:

When shell (coreutils) wins:

  • Huge, line-oriented text where you only need filtering, counting or a column extract — awk/grep stream in constant memory and are often faster to write and run than Python.
  • Pre-processing before ingestion — splitting, concatenating, compressing, moving.
  • Quick operational tasks — counting records, header checks, finding malformed lines.

Examples:

1{c[$3]++} END{for (k in c) print c[k], k}' big.csv | sort -rn | head

# Extract specific columns, skip the header
awk -F',' 'NR>1{print $1","$5}' big.csv > subset.csv
# Find and count malformed rows (wrong field count)
awk -F',' 'NF!=12{print NR}' big.csv | wc -l
# Sort a huge file using disk (external sort), then dedupe
sort -T /tmp -S 2G -k1,1 big.csv | uniq > sorted_unique.csv
# Grep a pattern across compressed logs without decompressing to disk
zgrep -c "ERROR" logs/*.gz” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# Count rows in a big CSV by a column, top 10 (streams, constant memory)
awk -F',' 'NR>1{c[$3]++} END{for (k in c) print c[k], k}' big.csv | sort -rn | head

# Extract specific columns, skip the header
awk -F',' 'NR>1{print $1","$5}' big.csv > subset.csv
# Find and count malformed rows (wrong field count)
awk -F',' 'NF!=12{print NR}' big.csv | wc -l
# Sort a huge file using disk (external sort), then dedupe
sort -T /tmp -S 2G -k1,1 big.csv | uniq > sorted_unique.csv
# Grep a pattern across compressed logs without decompressing to disk
zgrep -c "ERROR" logs/*.gz
# Count rows in a big CSV by a column, top 10 (streams, constant memory)
awk -F',' 'NR>1{c[$3]++} END{for (k in c) print c[k], k}' big.csv | sort -rn | head

# Extract specific columns, skip the header
awk -F',' 'NR>1{print $1","$5}' big.csv > subset.csv
# Find and count malformed rows (wrong field count)
awk -F',' 'NF!=12{print NR}' big.csv | wc -l
# Sort a huge file using disk (external sort), then dedupe
sort -T /tmp -S 2G -k1,1 big.csv | uniq > sorted_unique.csv
# Grep a pattern across compressed logs without decompressing to disk
zgrep -c "ERROR" logs/*.gz

Key tools: awk (field processing + aggregation), sed (stream edits), grep/zgrep/rg (search), sort (external sort with -S memory / -T temp), uniq (dedupe on sorted input), cut/paste/join, split (chunk big files), xargs -P (parallelism).

When Python beats shell: anything with real logic — nested structures, JSON, joins across files, error handling, type awareness, or reuse across a team. “I use awk for a one-liner over a 100 GB file and Python when the logic needs to survive review and live in Git.”

Q94: A data job is failing on a Linux box. How do you troubleshoot?

Description: Practical ops question — separates people who’ve carried a pager from those who haven’t.

Detailed Answer:

My troubleshooting sequence:

  1. Read the actual error first — logs (journalctl, CloudWatch, the job’s log file), not a guess. tail -n 100 the log; grep -i error.
  2. Processes & load — is the job even running?

<button data-code="ps -ef | grep
top / htop # CPU/mem live
uptime # load average” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

ps -ef | grep <job>
top / htop # CPU/mem live
uptime # load average
ps -ef | grep <job>
top / htop # CPU/mem live
uptime # load average

3. Memory — OOM is the #1 cause:

free -h # memory pressure
dmesg | grep -i "killed process" # OOM-killer evidence
free -h # memory pressure
dmesg | grep -i "killed process" # OOM-killer evidence

4. Disk — full disk fails writes silently and confusingly:

df -h # is the mount full?
du -sh /tmp/* # what's eating space
df -h # is the mount full?
du -sh /tmp/* # what's eating space

5. I/O & files — are the input files present and complete? Permissions? A partial file looks like a data bug and is actually an I/O bug.

<button data-code="ls -l /path/in
lsof -p # what's the process holding ope” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

ls -l /path/in
lsof -p <pid> # what's the process holding ope
ls -l /path/in
lsof -p <pid> # what's the process holding ope

6. Network / dependencies — can it reach the DB/object store/endpoint? curl -v, DNS, firewall, timeouts.

7. Scheduling — is cron even firing?

crontab -l
grep CRON /var/log/syslog
crontab -l
grep CRON /var/log/syslog

8. Reproduce with the same inputs/params — the fastest path to root cause.

Then: fix the cause, not the symptom. If it’s OOM, the answer is usually partition sizing or skew (Q36), not “add RAM”. If it’s disk, the answer is cleanup + quotas/compaction, not a manual delete on the node.

Interview tip: “My first three commands are tail the log, free -h, and df -h. Memory, disk and the actual error message explain the large majority of ‘the job died’ incidents.”

9. Leadership, Agile & Behavioral

Why this section exists:_ Read the responsibilities of a Lead JD again — collecting requirements from users and senior management, converting business needs to user stories, communicating results, aligning with the Enterprise Data Architect, and assuring quality/security/compliance. Roughly half the role is communication and leadership. These answers must be as rehearsed as any Spark answer._

Q95: How do you lead a data engineering team and ensure quality, security and compliance?

Description: The core leadership question, combining people, quality and governance.

Detailed Answer:

How I lead (the model I actually use):

  • Set standards, then trust with review. Shared conventions (naming, layering, DQ contracts, PR checklist) mean quality is baked in, not requested. Code reviews are the enforcement point.
  • Make the standards cheap to follow — a reusable framework (like a metadata-driven ingestion framework) means the easy path is the right path.
  • Own the platform, not just the tickets — I keep a roadmap of technical debt and proactively pay it down (small-file compaction, cost tuning, refactoring duplications).
  • Coach, don’t just correct — in reviews I explain why, so the standard propagates.
  • Shield the team and surface reality — I manage stakeholder expectations so the team isn’t doing surprise fire drills.

Ensuring quality:

  • Automated tests + DQ gates in every pipeline (unit, contract, reconciliation) — quality is a gate, not a hope.
  • Definition of Done includes: tested, documented, instrumented with alerts, cost-reviewed, and handed over.
  • Reconciliation at layer boundaries and a DQ scorecard per table.

Security & compliance:

  • Least-privilege by default — IAM roles, Lake Formation, no shared credentials.
  • Encrypt at rest and in transit with customer-managed KMS keys.
  • PII classified and masked at Silver so sensitive data never reaches broadly-accessible Gold.
  • Audit via CloudTrail and lineage via the catalogue; retention policies per regulation.
  • Fail-closed — a pipeline that can’t verify compliance stops rather than publishes.

Interview tip: “My leadership thesis: make the correct thing the easy thing. If governance is a form people fill out, it gets skipped; if it’s a framework that ingests safely by default, it just happens.”

Q96: How do you run Agile delivery for data engineering work?

Description: Many JDs require “experience working in Agile implementations”. Tests whether you adapt Agile to data realities.

Detailed Answer:

How I run it:

How data work differs from app work (say this — it shows nuance):

  • Estimation is uncertain — data is messy; I estimate spikes and discovery explicitly, and revise after profiling the source rather than pretending to know up front.
  • “Done” needs a data definition — a pipeline is done when data is verified, reconciled, documented and alerting.
  • Dependencies are external — source teams, access approvals, upstream schema changes. I track these as risks, not surprises.
  • Backfills and incidents cost sprint capacity — I reserve a fraction of capacity for operational work so one incident doesn’t derail the sprint.

Story format: “As a [business owner], I want [the metric/report/data product] so that [decision it improves]”, with acceptance criteria that include data freshness, completeness thresholds and reconciliation to source.

Interview tip: “I keep the Agile spirit — short feedback loops and demonstrable value — but I don’t pretend a data pipeline is a software feature. I add explicit discovery, a data-quality definition of done, and protected capacity for the operational reality.”

Q97: How do you collect requirements from business owners and turn them into user stories and technical specs?

Description: This is verbatim in many JDs. Get this one right — it’s a core responsibility of the role.

Detailed Answer:

My 5-step requirements process:

  1. Understand the decision, not just the data request. “What decision will this change, and what would you do differently if you had it?” This reframes “I need a report” into a measurable outcome and often reveals a simpler solution.
  2. Define the metric precisely. Agree on the definition, grain, filters, time window and edge cases. (Two teams reporting different “revenue” is almost always an undefined metric, not a data bug.)
  3. Locate and profile the source. Find the systems and columns; check quality, volume and freshness before promising a date. Assumptions here cause missed deadlines.
  4. Write the user story with acceptance criteria. Include functional requirements (what the data must show) and non-functional ones (freshness SLA, completeness threshold, access restrictions, retention).
  5. Agree the technical spec and get sign-off. Source → Bronze → Silver → Gold mapping, transformations, DQ rules, orchestration, and consumers. Confirm in writing; this is the contract.

Template I use:

<button data-code="Story: As a I want
so that .
Acceptance criteria:
– Reflects data up to 23:59 the previous day; delivered by 08:00 (SLA)
– Churn probability >= 0.7; list joins to campaign system via merchant_id
– Completeness: >= 99% of active merchants scored; DQ alert if not
– Access: restricted to Risk + Retention teams; PII masked
Spec: source (POS + CRM) → Bronze (raw) → Silver (features) → Gold (scored list)
DQ: null/id checks, volume anomaly, referential integrity to dim_merchant” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

Story:  As a <risk analyst> I want <daily at-risk merchant list by 8am>
        so that <I can run targeted retention campaigns>.
Acceptance criteria:
  - Reflects data up to 23:59 the previous day; delivered by 08:00 (SLA)
  - Churn probability >= 0.7; list joins to campaign system via merchant_id
  - Completeness: >= 99% of active merchants scored; DQ alert if not
  - Access: restricted to Risk + Retention teams; PII masked
Spec:   source (POS + CRM) → Bronze (raw) → Silver (features) → Gold (scored list)
        DQ: null/id checks, volume anomaly, referential integrity to dim_merchant
Story:  As a <risk analyst> I want <daily at-risk merchant list by 8am>
        so that <I can run targeted retention campaigns>.
Acceptance criteria:
  - Reflects data up to 23:59 the previous day; delivered by 08:00 (SLA)
  - Churn probability >= 0.7; list joins to campaign system via merchant_id
  - Completeness: >= 99% of active merchants scored; DQ alert if not
  - Access: restricted to Risk + Retention teams; PII masked
Spec:   source (POS + CRM) → Bronze (raw) → Silver (features) → Gold (scored list)
        DQ: null/id checks, volume anomaly, referential integrity to dim_merchant

Communication habits:

  • Translate both ways — business language for stakeholders, technical detail for engineers.
  • Manage expectations with evidence — when a date slips, I show why (data quality, an unknown source) rather than apologising vaguely.
  • Document decisions — a written spec prevents the classic “that’s not what I asked for” at UAT.

Interview tip: “I spend the first half of any requirements conversation on the decision, not the dataset. ‘I need a customer report’ and ‘I need to know who to call tomorrow’ are different requirements with different solutions — and only one of them might need a pipeline at all.”

Q98: A production pipeline fails and a business SLA is at risk. Walk me through your response.

Description: An incident-response question. They want calm, method, and communication.

Detailed Answer:

A phased response:

1. Stabilise and communicate (first).

  • Acknowledge the incident; tell stakeholders early with an ETA estimate — silence erodes trust faster than the outage.
  • Assess blast radius: which tables/dashboards/consumers are affected, and is data silently wrong or just late?

2. Diagnose (method, not panic).

  • Find the failing step in the orchestration (Step Functions history / Airflow logs / Spark UI).
  • Read the error, check the last successful run, and compare — what changed? (data volume, a schema change from an upstream source, a config release, a throttling event).
  • Classify: code bug, data problem, infrastructure (capacity/OOM), or dependency (upstream/source failure).

3. Mitigate.

  • If it’s a transient failure (throttling/network), retry — safe because the pipeline is idempotent.
  • If a source delivered bad/partial data, pause and quarantine rather than publishing wrong numbers.
  • If it’s a code/config bug, roll back to the last good version (versioned artifacts make this quick).
  • Restore the SLA — reprocess the affected window once the cause is fixed (backfill is a single partition-overwrite because of event-time partitioning).

4. Verify.

  • Re-run DQ checks and reconcile counts/sums against the source; confirm the downstream dashboard is correct; notify stakeholders that the SLA is restored.

5. Prevent.

  • Write a blameless post-mortem: timeline, root cause, impact, and action items with owners — an alert that would have caught it earlier, a DQ check, a retry policy, a source contract.
  • Feed the lesson back into the framework so every pipeline benefits, not just this one.

Interview tip: “My priorities in order: communicate, protect the data’s correctness, restore the SLA, then prevent recurrence. I would rather delay a report than publish a wrong number — a late number damages trust for a day; a wrong number damages it for months.”

Q99: How do you mentor engineers and work with the Enterprise Data Architect?

Description: Two JD threads: leading/mentoring, and aligning with the Enterprise Data & Analytics Architect.

Detailed Answer:

Mentoring and growing engineers:

  • Pair on real problems — the fastest learning is debugging a skewed job together, not a slide deck.
  • Progressive ownership — start someone on a well-templated pipeline, then a new source, then a design.
  • Code reviews as teaching — explain the why behind a suggestion and link the standard (why broadcast vs sort-merge here).
  • A shared standards library so learning is codified, not tribal.
  • A skills map — identify gaps (e.g. Spark tuning, Terraform) and target them with stretch work.

Working with the Enterprise Data & Analytics Architect (a common JD requirement):

  • Adopt their guardrails — naming standards, layering, security and access patterns are non-negotiable, even when they slow a sprint. Consistency across client accounts is the point.
  • Bring implementation reality back — the architect designs for the enterprise; I tell them where the standard is impractical and propose a principled exception.
  • Reuse enterprise patterns — build on the sanctioned ingestion framework, DQ library and catalogue rather than reinvent.
  • Escalate with data — when a standard creates a production risk, I bring evidence (a failed job, a cost figure), not an opinion.
  • Feed learnings upward — a pattern proven in my pipelines becomes an enterprise standard.

Interview tip: “I treat the enterprise architect as a partner, not an obstacle. I implement to their standards by default and bring them measured evidence when a standard needs to bend — because a fragmented set of one-off pipelines is exactly what the architecture function exists to prevent.”

Q100: Why this role, and how would you design a scalable, modular solution end to end?

Description: The closing question — often combines motivation with a mini design exercise.

Detailed Answer:

Why this role (tailor honestly to the firm):

  • The practice matches my specialism. Cloud-native lakehouses, real-time streaming pipelines and governed data products on AWS — which is what I’ve been building: managed Spark, serverless ETL, warehousing, Athena and streaming, a Medallion lakehouse, metadata-driven ingestion.
  • The JD reads like my last few years — PySpark at scale, Spark tuning, Hive partitioning, Terraform, streaming + batch. It’s a role where I can contribute on day one, not ramp for months.
  • Consulting delivery fits how I work — I like being close to business owners, turning requirements into specs, and being measured on outcomes. My experience includes client-facing work and leading a team.
  • Leadership + hands-on is the mix I want — I still write production PySpark and I also design, mentor and face stakeholders. That’s this role exactly.

The end-to-end design (give structure, then depth):

  1. Ingest — batch (Glue/DMS), events (Lambda/S3), streaming (Kinesis/Kafka with Schema Registry), all config-driven so a new source is a config change.
  2. Store — S3 lakehouse, Medallion (Bronze/Silver/Gold), partitioned by event date, columnar (Parquet), with lifecycle policies.
  3. Process — PySpark on EMR Serverless / Glue, shared transformation library, DQ gates at each boundary, AQE-tuned jobs, target ~128 MB partitions.
  4. Model — dimensional Gold marts (facts/dimensions, SCD2) and governed data products with owners and SLAs.
  5. Serve — Redshift for high-concurrency BI, Athena for ad-hoc, Gold tables as ML features.
  6. Orchestrate — Step Functions for event-driven flows, MWAA for complex DAGs.
  7. Govern & secure — Glue Catalog + Lake Formation, IAM least privilege, KMS, PII masked at Silver, CloudTrail audit.
  8. Observability & cost — CloudWatch alarms on failure/SLA/DQ volume, latency and cost SLOs, budgets and anomaly alerts.
  9. Deliver — Terraform for all infra, CI/CD with tests and reviewed plans, idempotent, re-runnable, backfillable pipelines.

Modularity & scalability principles I’d state: decoupled layers (Bronze/Silver/Gold), config-driven ingestion, shared reusable libraries, idempotent/cost-aware jobs, and governance built in from day one — so the platform scales in data volume, in sources, and in consumers without re-architecture.

Interview tip: “I’d design it so the tenth data source is as easy as the first and the hundredth is still cheap — that’s what config-driven, layered, governed pipelines give you, and it’s why I build them that way.”

10. Questions to Ask the Interviewer

Asking sharp questions signals seniority. Pick 4–6 and adapt to who you’re speaking with.

About the practice & the role

  1. What does the data practice look like today — is the balance more on new lakehouse builds, migrations from on-prem Hadoop/Hive, or optimisation of existing platforms?
  2. Which client accounts or industries would I typically be deployed to, and do Lead Data Engineers work across multiple accounts or embedded in one?
  3. What does success look like for a Lead Data Engineer in the first 6 and 12 months?
  4. Are the Lead roles more architecture/design-weighted, or hands-on coding-weighted? (Signal: I’m comfortable with both — this shows I’m not avoiding one.)

About tech & delivery 5. What’s the standard cloud data stack across engagements — managed Spark vs serverless ETL for Spark, warehouse vs query-engine for serving, managed streaming vs Kafka? 6. How central is Terraform/IaC and CI/CD in delivery here — is infrastructure provisioned as code by the data team or a platform team? 7. Is there a shared internal framework for ingestion/DQ, or does each project build its own? 8. How do you handle scheduling across clients — Airflow/MWAA, Step Functions, or legacy tools like Autosys on the client side?

About growth & team 9. How is the data engineering team structured — pod-based, practice-based, and how large? 10. How does the Enterprise Data & Analytics Architect role interact with the delivery leads day to day? 11. What does the career path look like from Lead Data Engineer — towards architect, delivery manager, or practice leadership? 12. What are the biggest technical challenges the practice is trying to solve in the next year?

About logistics & process 13. How does hybrid work operate in practice for this role, and what does a typical week look like? 14. What are the next steps in the process and the expected timeline?

Questions to avoid — anything answerable by a two-second web search, questions about salary in a technical round (save for HR), and anything that sounds like you’re interviewing them rather than exploring a partnership.

11. The 60-Minute Pre-Interview Cheat Sheet

Last 60 minutes. Scan this once, out loud where you can.

The 30-second positioning (template — fill in your own)

“Lead Data Engineer, 8+ years on cloud. PySpark on managed Spark and serverless ETL at tens of millions of records/day, high accuracy. Warehousing, a query engine, Kafka streaming. Tuned Spark to cut compute by a quarter. Lead a team. I design pipelines end to end and face business owners directly.”

Numbers to have ready (prepare your own)

The one-line answers to the JD’s keywords

  • Spark UI → slowest stage → task skew? shuffle-bound? spill/GC? Triage those three first.
  • Partitions → target ~128 MB; AQE coalesces; repartition (shuffle) vs coalesce (no shuffle).
  • Skew → AQE skew join first; salt hot keys as the hammer.
  • Joins → broadcast small side; sort-merge large-large; filter before joining.
  • Cache → only reused intermediates; unpersist after; never reflexively.
  • Hive table → partition by date, ORC/Parquet + Snappy, bucket by join key, ~128 MB files.
  • Warehouse → dist key on the join column, ALL for small dims, sort key on the filter prefix, VACUUM/ANALYZE.
  • Athena → partitioning + Parquet + compression + no SELECT * = the whole cost story.
  • Glue vs EMR → spiky/moderate/catalog = Glue; heavy/tuned/sustained = EMR (often Serverless).
  • Streaming → replayable source + checkpoint + idempotent sink = exactly-once in practice.
  • ETL vs ELT → ELT on the lakehouse (Bronze raw → Silver clean → Gold business), masked at ingestion for PII.
  • Data quality → completeness, validity, uniqueness, referential, volume — enforced at layer boundaries.
  • Idempotency → partition-overwrite (batch) / MERGE (streaming) → safe retries and clean backfills.
  • Terraform → remote S3 state + DynamoDB lock, modules per environment, plan on every PR.
  • CI/CD → lint, unit + contract tests, terraform plan, build once, promote the same artifact, approve before prod.
  • Shell → set -euo pipefail + trap — the safety header on every script.
  • Autosys/CA → same concepts as Airflow/Step Functions (dependencies, calendars, SLAs) — days to ramp.
  • Agile → vertical slices, definition of done includes DQ + alerts, protected capacity for incidents.

The tuning method (say it exactly this way)

“Open the UI first: find the slowest stage. One long task → skew. Big shuffle read/write → reduce shuffle (broadcast, filter early). Spill or GC → partition sizing or memory. Then fix the cause, re-time it, and add an alert so it doesn’t regress.”

The design method (for any “design a pipeline” question)

“Ingest (config-driven) → Bronze (raw, immutable) → Silver (typed, DQ-gated) → Gold (business-ready, governed). Orchestrate with Step Functions/Airflow, catalogue with Glue, secure with IAM + Lake Formation + KMS, observe with CloudWatch, ship with Terraform + CI/CD. Always ask what decision the data changes and how fresh it must be.”

Three stories to have loaded (S/T/A/R)

  1. A compute-cost reduction — profiled Spark jobs, enabled AQE, broadcast joins, partition pruning, fixed skew → lower compute and storage cost, no throughput loss.
  2. Zero-data-loss streaming — Kafka + Schema Registry + schema evolution + DQ, so upstream schema changes never broke downstream tables.
  3. Faster onboarding / fewer failures — a metadata-driven ingestion framework + multi-layer DQ checks; config over code.

Mindset reminders

  • Measure before you tune. A performance claim without a before/after number is a guess.
  • Fix the cause, not the symptom. Three times out of four a “model/data bug” is an upstream data change.
  • Admit gaps honestly with Acknowledge → Map → Commit. Bluffing is caught in two questions.
  • Tie everything to a business outcome. Consulting firms sell outcomes; engineering for its own sake loses the room.
  • Breadth wins a fast multi-round process. You don’t know which round probes which skill — stay solid everywhere.

First three things to say if you freeze

  1. The 30-second positioning.
  2. “Let me think about the design from the data’s perspective — what decision it changes and how fresh it must be.”
  3. “I’d measure first: open the Spark UI / query plan and find where the time actually goes.”

Closing thoughts

A Lead Data Engineer interview is not a trivia test. It is an attempt to find out whether you can design something that survives contact with real data, real clients and real deadlines — and whether you can explain why you chose one path over another.

The candidates who get hired are rarely the ones who memorised the most answers. They are the ones who understood the shape of the role, prepared breadth across the whole stack, and could back every claim with something they had genuinely built.

Use this guide to get thorough and stay honest. The strongest answer is always the one you can defend from experience — and when you don’t have the experience yet, the second strongest is an honest “here’s how I’d approach it, and here’s how quickly I’d close the gap.”

Good luck. Go get the offer.

If this was useful, the sections map cleanly onto a week of study: one a day, then the cheat sheet on the morning of the interview.