Skip to content
Tech Interview Prep

Real Interview Questions for the Data Engineer at Stone

New

Interview Q&A

24 questions · Flow follows Relevance until this set has a learning order.

Q&A-1Explain the ACID principles in database design?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

ACID is a contract for a transaction, not a feature list. A transaction is a set of reads and writes that either all become visible or none do, and the database can prove that after a crash. I would state that first, then define each letter in terms of what breaks without it.

PrincipleGuaranteeWhat breaks without it
AtomicityAll writes in the transaction commit, or none doA debit posts and the matching credit does not, leaving a ledger out of balance
ConsistencyA committed transaction moves the database from one valid state to another, respecting constraintsA foreign key or check constraint is violated and downstream jobs read orphaned rows
IsolationConcurrent transactions behave as if they ran in some serial order, at the level you choseTwo concurrent updates overwrite each other, or a report reads a half-applied batch
DurabilityOnce committed, the result survives a crashA restart loses acknowledged trades, and replaying the feed creates duplicates

Consistency here means application and schema constraints, not that replicas agree. Replica agreement is a separate concern, and conflating the two is a common interview trap.

How it is implemented

Atomicity and durability in a single node system like PostgreSQL come from the write-ahead log. Changes are appended to the WAL and flushed before the commit is acknowledged. On recovery, the database replays committed WAL entries and discards uncommitted ones. That is why a commit acknowledgement is a promise about disk, not memory.

SQL
-- PostgreSQL 16, checked against the documented transaction model
BEGIN;
INSERT INTO ledger_entries (account_id, amount_minor, currency)
VALUES (42, -1000, 'USD');
INSERT INTO ledger_entries (account_id, amount_minor, currency)
VALUES (77,  1000, 'USD');
UPDATE account_balances SET balance_minor = balance_minor - 1000 WHERE account_id = 42;
UPDATE account_balances SET balance_minor = balance_minor + 1000 WHERE account_id = 77;
COMMIT; -- WAL flushed here; after this point the four writes survive a crash

If the process dies before COMMIT, recovery finds no commit record for that transaction ID and rolls it back. If it dies after, replay reapplies all four writes. There is no state where only the first insert survives.

Client sends BEGIN Writes go to buffer and WAL COMMIT requested WAL flushed to disk Commit record written Acknowledge to client Crash and restart Replay committed WAL, discard uncommitted

Isolation is the dial you turn. PostgreSQL defaults to READ COMMITTED, where each statement sees a snapshot as of that statement. REPEATABLE READ gives one snapshot for the whole transaction and aborts on a conflicting concurrent update. SERIALIZABLE adds predicate locking in effect, so a transaction that would create a serialisation anomaly is aborted and must be retried. Higher isolation costs throughput and retries, so I pick the lowest level that prevents the specific anomaly my workload can produce.

Worked trace: lost update

Two sessions update the same balance starting at 1000.

StepSession ASession BStored balance
1Reads 10001000
2Reads 10001000
3Writes 900 (1000 - 100)900
4Writes 950 (1000 - 50)950
5CommitsCommits950

The correct serial result is 850. Under READ COMMITTED with a blind overwrite, A is lost. The fix is either an atomic update (SET balance = balance - 100), optimistic concurrency with a version column and WHERE version = ?, or SERIALIZABLE so one transaction aborts. In a data pipeline I prefer the atomic update or the version check, because a retry loop around serializable aborts is harder to reason about at volume.

Where ACID stops applying

In distributed systems, atomicity across nodes needs two-phase commit or a consensus protocol, and that introduces blocking and coordination failures. I would name that trade-off rather than claim ACID scales for free.

In the lakehouse, Delta Lake and Iceberg offer a narrower version: atomic commit of a file manifest, snapshot isolation for readers, and optimistic concurrency on commit. That protects a batch load from partially visible files, which matters for an idempotent daily load where I can reprocess a partition. It does not give multi-row foreign keys or serializable multi-table transactions across a streaming sink. For a trading ledger at Stone I would keep the system of record in a transactional store with full ACID, and treat the lake as a derived, replayable copy. If the lake commit succeeds and the ledger write fails, replay from the ledger wins, because the ledger is the source of truth.

Failure modes I would watch in production: WAL disk filling so commits stall, long-running transactions holding snapshots and bloating vacuum in PostgreSQL, and clients retrying a commit whose acknowledgement was lost. That last one is why idempotency keys on the write path matter even inside an ACID database. ACID guarantees the transaction happened once as a unit, it does not tell a retrying client whether it happened.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2What is the difference between row-level locking and table-level locking?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

Row-level locking blocks other transactions from writing the specific rows you touched. Table-level locking blocks other transactions from using the whole table, or a defined class of operations on it. The choice is a concurrency versus safety trade-off: row locks let 50 loaders update 50 different customer rows at once, table locks make a bulk rewrite or a schema change safe but serialise everyone else.

In Postgres, which is what I would assume for a Stone ingestion service unless you tell me otherwise, an UPDATE takes a row lock on each updated row until commit. SELECT ... FOR UPDATE takes the same lock explicitly. A TRUNCATE, ALTER TABLE, or COPY in some modes takes ACCESS EXCLUSIVE on the table, which conflicts with every other lock mode, including plain reads.

Row-levelTable-level
GranularityOne or more rows, plus index entriesWhole table
Typical triggerUPDATE, DELETE, SELECT FOR UPDATETRUNCATE, ALTER TABLE, LOCK TABLE, bulk load
Concurrent writers to different rowsAllowedBlocked if modes conflict
Concurrent writers to same rowSerialised, second waitsBlocked
Readers during writeAllowed in Postgres MVCC, they see the old versionBlocked by ACCESS EXCLUSIVE, allowed by ACCESS SHARE
Main failure modeDeadlocks, lock wait timeoutsThroughput collapse, queueing behind one long load

How it plays out in a pipeline

Say a nightly job restates dim_customer for 2 million rows while an intraday CDC stream applies 5,000 updates per minute to the same table.

With row locks, the CDC updates to rows the restatement has not reached yet proceed. When CDC hits a row the restatement already locked, it waits. If the restatement holds that row for 30 seconds inside a large transaction, CDC latency for that key jumps by 30 seconds and its lock timeout, say 10 seconds in our config, fires. The fix is smaller batches, 10,000 rows per commit, and updating in primary key order so both jobs acquire locks in the same sequence.

With a table lock, for example TRUNCATE followed by COPY to rebuild a staging table, every reader and writer waits for the whole load. If the load takes 4 minutes, p99 query latency for dashboards on that table goes from 200 ms to 4 minutes, not because the database is slow but because the queue is behind the lock. That is acceptable for a table nobody reads at 02:00 and unacceptable for a table feeding live risk checks.

SQL
-- Postgres: explicit row lock, held until COMMIT
BEGIN;
SELECT id, balance FROM accounts WHERE id = 42 FOR UPDATE;
-- second transaction updating id = 42 now blocks here
UPDATE accounts SET balance = balance - 100 WHERE id = 42;
COMMIT;

-- Table lock: blocks reads and writes from other sessions
LOCK TABLE staging_trades IN ACCESS EXCLUSIVE MODE;
TRUNCATE staging_trades;
COPY staging_trades FROM STDIN;

Worked trace: two writers, one row

TimeTxn ATxn BResult
t0UPDATE accounts SET balance = balance - 100 WHERE id = 42A holds row lock on 42
t1UPDATE accounts SET balance = balance + 50 WHERE id = 42B blocks on row 42
t2COMMITLock released, A balance is 900 from 1000
t3B proceeds, reads 900, writes 950No lost update

If A and B update rows 42 and 43 in opposite order, neither blocks on the first row and both block on the second. Postgres detects the cycle in about a second, aborts one transaction with 40P01 deadlock_detected, and the caller must retry the whole transaction. That retry logic is the part candidates forget: a deadlock abort is not a failed statement, the transaction is gone.

When I would not use row locks alone

Row locks do not protect a predicate. Two transactions can both run SELECT count(*) FROM orders WHERE status = 'open' and both see 10,000, then both insert, because no existing row was locked. In InnoDB that gap is covered by next-key locks on index ranges, in Postgres it is not, and you need serializable isolation or an advisory lock on the predicate key. For a data engineer that matters in deduplication and late-arriving fact loads: locking the rows you found does not stop a concurrent load inserting the row you missed.

My default for Stone style workloads: row locks for incremental upserts keyed by a stable primary key, batched commits in key order, and a table lock only for a rebuild of a table with no live readers, done via a shadow table and an atomic rename so the lock window is milliseconds instead of the load duration.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3Can you perform a `GROUP BY` on multiple columns in Python?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

Yes, and in a data pipeline I would reach for pandas first, then move off it when the data stops fitting in memory. The pandas call takes a list of columns, which is the multi-column equivalent of SQL GROUP BY region, product:

Python
import pandas as pd

# trades: one row per fill, with symbol, venue and notional
result = (
    trades.groupby(["symbol", "venue"], dropna=False, as_index=False)
          .agg(total_notional=("notional", "sum"), fills=("trade_id", "count"))
)

dropna=False matters for market data. By default pandas drops rows where any group key is null, so a fill with a missing venue would silently vanish from the totals. With dropna=False it forms its own (symbol, None) group and you can see it in the output. as_index=False keeps the keys as columns, which is what you want when the result goes straight to a table or a file.

A worked trace on four rows shows the grouping:

symbolvenuenotionaltrade_id
AAPLXNAS100t1
AAPLXNAS250t2
AAPLXNYS75t3
MSFTXNAS400t4
symbolvenuetotal_notionalfills
AAPLXNAS3502
AAPLXNYS751
MSFTXNAS4001

The same thing in plain Python, with no dependency, is a dict keyed by a tuple:

Python
from collections import defaultdict

totals = defaultdict(float)
for row in trades:  # row is a dict or namedtuple
    totals[(row["symbol"], row["venue"])] += row["notional"]

That is fine for a streaming pass over a file, but you lose vectorised aggregations, joins and sorting, so I would not build a pipeline on it.

Choosing the engine

EngineWhen I use itLimit to watch
pandasUp to a few GB in memory, ad hoc or daily batchLoads the whole frame into RAM, single threaded for many ops
PolarsSame shape as pandas, larger files, want lazy executionNewer API, some pandas idioms do not transfer
DuckDBAggregating Parquet or CSV on disk without a clusterStill single node, so very large shuffles are slow
PySparkData across many nodes, or a shuffle that will not fit on one machineCluster cost and shuffle tuning, overkill for small jobs

For a Stone style flow, say hourly notional by symbol and venue from Parquet partitions, I would write the DuckDB version first: SELECT symbol, venue, SUM(notional) AS total_notional, COUNT(*) AS fills FROM read_parquet('trades/date=.../*.parquet') GROUP BY symbol, venue. It pushes the aggregation to the scan, keeps memory bounded, and the SQL reads the same as the warehouse query the finance team already trusts.

Failure modes I check for

Null keys dropped by default, as above. I reconcile the output: sum of total_notional in the result must equal sum of notional in the input, and the count of groups must be at most the count of distinct key combinations in the input. A mismatch means rows were dropped or a key type changed, for example venue read as a string in one partition and a category in another, which splits one group into two.

High cardinality is the other trap. Grouping tick data by (symbol, venue, millisecond) can produce millions of groups and blow up memory before the aggregation helps. I check the distinct key count first with a cheap nunique or a COUNT(DISTINCT ...) in DuckDB, and if it is close to the row count I question whether that grain is what the consumer actually needs.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-4Describe how you would approach CI/CD for AI tools?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

I would treat an AI tool as three versioned things that ship together: the code, the data it was built and evaluated on, and the model or prompt configuration. A pipeline that only versions code will pass a build and still ship a different system every time the upstream table changes.

So I would build one pipeline with hard gates between stages. Merge triggers unit tests, data contract tests and a pinned evaluation set. Only if those pass does the pipeline build a container, register the model artifact by content hash, and deploy to a canary. Promotion to full traffic needs an offline eval score, a shadow comparison against the incumbent, and a rollback artifact already in the registry. At Stone, where the data is market and client data, I would also gate on lineage and access checks, because an auditor will ask which rows produced a given prediction.

Merge to main Unit and contract tests Build image and model artifact Offline eval on pinned data Shadow deploy Canary 5 percent Promote or roll back

What each gate actually checks

StageGateFails when
---------
---------
Testpytest plus schema tests on every input tablea column is renamed, a type widens, or null rate on a key field crosses 1 percent
Buildimage and model stored by SHA, data snapshot ID recordedbuild is not reproducible from the lockfile and snapshot
Evalgolden set of 2,000 labelled cases, frozen for the releaseaccuracy drops more than 2 points, or any regulated slice drops more than 5 points
Shadowrun new and old side by side for 24 hours on live trafficdisagreement rate exceeds the agreed threshold or p95 latency rises above 300 ms
Canary5 percent of traffic for 4 hours, auto rollback on error budget5xx rate or cost per 1,000 calls breaches budget

The eval gate is the part most teams skip, and it is where AI pipelines differ from ordinary services. A normal service can be tested with fixed inputs. A model needs a frozen dataset that includes the awkward cases: stale prices, missing fields, duplicate client records, and prompts that try to pull data across client boundaries. I would store that set in versioned object storage, never in the repo, and record its hash in the model registry alongside the code commit. If the eval set changes, that is a new release, reviewed like a code change.

A small check I would put in CI, in Python, is a contract test that runs before any training job starts:

Python
# tests/test_contracts.py, run in CI on every merge
import pandas as pd

def test_market_data_contract(snapshot: pd.DataFrame) -> None:
    assert snapshot["instrument_id"].notna().all()
    assert snapshot["price"].gt(0).all()
    assert snapshot["ts"].is_monotonic_increasing
    dupes = snapshot.duplicated(subset=["instrument_id", "ts"]).sum()
    assert dupes == 0, f"{dupes} duplicate instrument/timestamp rows"

That test costs seconds. The failure it catches, a silent duplicate join that doubles a feature, can cost a retrain and a week of debugging if it reaches production.

Deployment and rollback

I would deploy with the model artifact and the serving image promoted together, tagged with the same release ID. Rollback is then a registry operation, not a rebuild: point the canary back to the previous release ID, which is already pulled and warm. I would keep the last two releases warm in the registry so rollback takes under a minute instead of a 20 minute rebuild.

For cost control, which matters with LLM-backed tools, I would put a budget check in the canary stage. If a prompt change raises average tokens per call from 800 to 2,400, that is a 3x cost increase at the same traffic. At 50,000 calls a day that moves daily spend from roughly 40 dollars to 120 dollars on a typical hosted model, and it will show up in the canary before it shows up on an invoice. The pipeline should fail the promotion on that signal alone.

Failure modes I would monitor after deploy

Data drift is the common one. I would log input distributions and prediction distributions per release, and alert when a feature's population stability index crosses 0.25 or when the share of fallback responses doubles. The second is silent quality decay: the model still returns 200s, but the eval score on a weekly refreshed sample slides. I would run that sample as a scheduled job, not as part of the deploy pipeline, so a bad week triggers a review even when nobody shipped anything.

The third is leakage through prompts and logs. AI tools tend to log full prompts and completions for debugging. In a financial environment that can mean client identifiers landing in a log bucket with broad read access. I would gate the pipeline on a log scrubbing test and on the serving role having access only to the tables and buckets that release needs, checked by policy as code in the same repo.

If I had to start from zero in a week, I would ship the test and eval gates first, then the registry and canary, and only then automate promotion. A pipeline that blocks bad merges on day one is worth more than a fully automated one that promotes a bad model faster.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5Explain the difference between various SQL joins, such as Cross Join and Natural Join?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

Joins differ in two decisions: which rows survive, and how rows are matched. Inner, left, right and full joins match on a condition you write and keep rows based on whether that condition holds. Cross join has no matching condition at all. Natural join has a matching condition you did not write, it infers one from column names.

That distinction matters in a pipeline. An explicit ON clause fails loudly when a column is renamed or dropped. A natural join silently changes meaning when a new column with the same name appears in both tables, which is how a nightly job starts duplicating rows three weeks after a schema change.

JoinMatching ruleRows keptTypical use
INNER JOINON a.id = b.idMatches onlyLinking orders to customers where both exist
LEFT JOINON a.id = b.idAll of left, nulls for unmatched rightKeeping every customer, flagging those with no orders
RIGHT JOIN / FULL JOINON ...All of right / both sidesReconciliation checks, rare in fact tables
CROSS JOINNoneEvery left row paired with every right rowDate spines, parameter grids, small lookup expansion
NATURAL JOINImplicit ON all shared column namesDepends on inferred conditionAd hoc exploration only, avoid in production SQL
SELF JOINON a.id = b.manager_idMatches within one tableHierarchies, lag comparisons on the same table

Worked trace

Suppose customers has 3 rows and orders has 4:

customers.idcustomers.nameorders.idorders.customer_idorders.amount
1Ana101150
2Ben102175
3Cy103220
1049910

INNER JOIN ON customers.id = orders.customer_id returns 3 rows (101, 102, 103). Order 104 disappears because customer 99 does not exist, and Cy disappears because he has no orders.

LEFT JOIN from customers returns 4 rows. Cy appears once with null order columns. That is the shape you want for a customer-level summary where zero-order customers still count.

CROSS JOIN returns 3 x 4 = 12 rows, every customer paired with every order, including Ana paired with order 104. Scale that up and the cost is obvious: 10,000 customers cross 50,000 orders is 500 million rows before any filter. In a warehouse that is a full scan, a shuffle, and usually a query timeout. Cross joins are safe only when at least one side is tiny and deliberately so, for example crossing a fact table with a 12-row calendar table to build a complete month spine.

Natural join, concretely

SQL
-- PostgreSQL / Snowflake syntax
SELECT *
FROM customers
NATURAL JOIN orders;

If both tables happen to share id and customer_id, this becomes ON customers.id = orders.id AND customers.customer_id = orders.customer_id, which is almost certainly wrong. The author meant to join on customer_id alone. Worse, if orders later gains a name column that customers also has, the join condition changes with no edit to the query. The job still runs, row counts drift, and the break shows up in a downstream reconciliation rather than at compile time.

Use USING when the key name is shared and you want it explicit:

SQL
SELECT *
FROM customers
JOIN orders USING (customer_id);

That states the contract in the query and survives unrelated columns being added.

Failure modes I watch for

Fan-out is the common one. Joining orders to order_items on order_id before aggregating turns one order row into many, so SUM(orders.amount) double counts. The fix is to aggregate the many side first, then join the result.

Null keys are the quiet one. ON a.id = b.id never matches when either side is null, so a left join that looks complete can hide unmatched rows in the right table. For reconciliation I add a WHERE b.id IS NULL anti-join check and alert on its count.

For production data engineering work I write every join with an explicit ON or USING, I avoid natural joins entirely, and I treat any cross join in a review as a request to justify the row count in the query plan.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-6Write a function to manipulate strings or lists?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

I would ask what manipulation they mean, then state my assumption: a raw field from a CSV or log line arrives as a string, and downstream code needs a clean list. For example, tags="equities, fx ,EQUITIES,,bonds" should become ["equities", "fx", "bonds"]. That covers the two operations data pipelines do most often: split a string into a list, and normalise a list without losing order.

Python
import csv
import io

def parse_list_field(raw: str | None, *, delimiter: str = ",") -> list[str]:
    if raw is None:
        return []
    raw = raw.strip()
    if not raw:
        return []
    # csv handles quoted delimiters: '"a,b",c' -> ['a,b', 'c']
    parts = next(csv.reader(io.StringIO(raw), delimiter=delimiter))
    seen: set[str] = set()
    out: list[str] = []
    for p in parts:
        v = p.strip().lower()
        if v and v not in seen:
            seen.add(v)
            out.append(v)
    return out

def flatten_lists(rows: list[list[str]]) -> list[str]:
    return [item for row in rows for item in row]

parse_list_field is O(n) in the length of the string and O(k) extra space for k unique items. flatten_lists is O(total items). Both are single pass, which matters when this runs over millions of rows in a batch job.

Worked trace

InputStepOutput
"Equities, fx ,EQUITIES,,bonds"csv split["Equities", " fx ", "EQUITIES", "", "bonds"]
samestrip, lower, drop empty["equities", "fx", "equities", "bonds"]
samededupe, keep first occurrence["equities", "fx", "bonds"]
None or " "early return[]
'"a,b",c'csv split respects quotes["a,b", "c"]

Choosing the split method

MethodHandles quoted delimiterHandles regex / whitespace runsCost
str.split(",")NoNoFastest, fails on quoted commas
csv.readerYesNoSlightly slower, correct for CSV-sourced fields
re.split(r"[,;\\s]+", s)NoYesGood for messy free text, harder to read
json.loadsYes, if field is JSONNoOnly when producer actually emits JSON

I default to csv.reader for pipeline data because producers quote fields containing commas. str.split silently corrupts "a,b",c into three items, and that error only surfaces downstream as wrong aggregations.

Failure modes I would name in the loop

Empty string versus None versus the literal string "null" from a source system. I return [] for the first two and treat "null" as data unless the contract says otherwise, because guessing loses rows silently. Unicode whitespace and non-breaking spaces survive strip() in some cases, so for user-supplied text I normalise with unicodedata.normalize("NFKC", s) before splitting. Very long fields, say over 1 MB, can blow memory when materialised as a list per row, so in Spark or streaming I would push this into a UDF only after checking the p99 field length, or use split plus explode in SQL instead of Python. Finally, lowercasing is a business decision: correct for tags and symbols, wrong for case-sensitive identifiers, so I would make it a parameter rather than burying it in the function.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7Solve a problem involving the traversal of a 2D matrix, such as printing diagonals?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

I would clarify the shape first, then state the traversal I am implementing. For a square n x n matrix, the main diagonal is a[i][i] and the anti-diagonal is a[i][n-1-i], both in one pass with O(n) time and O(1) extra space. If the interviewer meant every diagonal, I would group cells by i - j for NW-SE diagonals, which is O(n^2) because it visits every cell.

That distinction matters in a data pipeline too. A matrix that arrives as partitioned rows, for example daily aggregates stored one row per partition, cannot be traversed anti-diagonally in a single streaming pass without either storing it or making a second pass. Naming that constraint early is usually what the interviewer is probing.

Python
# Python 3.11, checked against a list of lists of ints
def diagonals(matrix):
    if not matrix or not matrix[0]:
        return [], []
    n = len(matrix)
    if any(len(row) != n for row in matrix):
        raise ValueError("expected a square matrix")
    main = [matrix[i][i] for i in range(n)]
    anti = [matrix[i][n - 1 - i] for i in range(n)]
    return main, anti

def all_diagonals(matrix):
    # NW-SE diagonals, grouped by (i - j)
    if not matrix:
        return []
    rows, cols = len(matrix), len(matrix[0])
    groups = {}
    for i in range(rows):
        for j in range(cols):
            groups.setdefault(i - j, []).append(matrix[i][j])
    return [groups[k] for k in sorted(groups)]

Worked trace

For this 4 x 4 matrix:

irow
01 2 3 4
15 6 7 8
29 10 11 12
313 14 15 16
imain a[i][i]anti a[i][3-i]
014
167
21110
31613

Main diagonal: [1, 6, 11, 16]. Anti-diagonal: [4, 7, 10, 13]. For all_diagonals, the keys i - j run from -3 to 3, giving 7 diagonals: [4], [3, 8], [2, 7, 12], [1, 6, 11, 16], [5, 10, 15], [9, 14], [13].

Edge cases and failure modes

CaseBehaviour
------
Empty matrix or empty first rowReturn empty lists, do not index matrix[0] blindly
Rectangular m x n, m != nMain diagonal length is min(m, n); anti-diagonal needs a defined anchor, so I would ask which corner it starts from
Ragged rows, common when rows come from a Python pipelineRaise on the shape check above instead of producing a silent IndexError halfway through
Very large matrix held in memoryOne pass for both diagonals, no copy of the matrix; for all_diagonals, the grouping dict holds every cell, so that variant is the one to avoid on huge inputs

Follow-ups I would expect

If asked to print diagonals in traversal order for a rectangular matrix, I would start each diagonal at the top row or left column and walk down-right while both indices stay in bounds. If asked about a sparse matrix, I would switch representation entirely: store only non-zero (i, j, value) triples and derive diagonals from those, since a dense O(n^2) scan wastes time on zeros. If asked to do it in SQL or Spark, I would generate row and column indices with explode or range, compute i - j as the diagonal key, and aggregate with collect_list ordered by i. That keeps the same grouping logic and moves the cost to the shuffle, which is the trade-off to name.

Complexity summary: both diagonals O(n) time, O(1) extra space beyond the output. All diagonals O(m*n) time and O(m*n) space for the grouped output, which is unavoidable if every cell must be emitted.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8Implement sorting algorithms like Merge Sort?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

I would implement Merge Sort recursively, state the assumptions first, and then say where I would not use it in a data pipeline. Assumptions: a Python list of comparable items, in-memory, stability matters, and I need a guaranteed O(n log n) worst case. That gives divide, sort each half, merge in order.

Python
# Python 3.12
from typing import TypeVar

T = TypeVar("T")

def merge_sort(items: list[T]) -> list[T]:
    if len(items) <= 1:
        return list(items)
    mid = len(items) // 2
    left = merge_sort(items[:mid])
    right = merge_sort(items[mid:])
    merged: list[T] = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:  # <= keeps equal keys in original order
            merged.append(left[i])
            i += 1
        else:
            merged.append(right[j])
            j += 1
    merged.extend(left[i:])
    merged.extend(right[j:])
    return merged

assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]

The <= is the stability detail interviewers probe. Taking from the right on ties would reverse equal elements. Stability matters in data work when you sort trades by timestamp and then by price, and you want the earlier record to stay first within the same timestamp.

Worked trace

StepLeft halfRight halfMerge result
split [38, 27, 43, 3, 9, 82, 10][38, 27, 43][3, 9, 82, 10]
sort left[27, 38] and [43][27, 38, 43]
sort right[3, 9] and [10, 82][3, 9, 10, 82]
final merge[27, 38, 43][3, 9, 10, 82][3, 9, 10, 27, 38, 43, 82]

Each level of recursion touches every element once during merging, so total work is O(n log n) comparisons and moves, with O(n) extra space for the merged lists plus O(log n) recursion depth. For n = 1,000,000 that is about 20 levels, roughly 20 million element moves, and about 8 MB of extra references for a list of pointers in CPython before counting the objects themselves. That memory cost is the main reason Merge Sort loses to in-place sorts on small in-memory arrays.

When I would pick something else

AlgorithmTimeExtra spaceStableUse it when
Merge SortO(n log n) alwaysO(n)YesWorst case guarantee, linked lists, external data
Quick SortO(n log n) average, O(n^2) worstO(log n) stackNoIn-memory arrays, memory tight, pivot chosen well
Python sorted() (Timsort)O(n log n) worst, near O(n) on runsO(n) worstYesDefault in Python, exploits already sorted runs

In production data engineering I would rarely hand-roll this. Python's sorted() is implemented in C, is stable, and detects runs, so it beats a Python-level Merge Sort by an order of magnitude on the same input. For data that does not fit in memory, the same divide and merge idea becomes external Merge Sort: sort chunks that fit in RAM into runs, then k-way merge the runs from disk. That is the pattern behind Unix sort, database sort operators, and Spark's shuffle sort, where the merge step is what lets you sort terabytes without loading them.

Failure modes to name if asked: recursion depth on degenerate splits is not an issue here because the split is always at the midpoint, but slicing items[:mid] copies at every level and doubles allocation churn, so a production version would sort indices in place with a temporary buffer. A second failure mode is comparing records with None or mixed types, which raises TypeError in Python 3, so I would sort on an explicit key function, for example sorted(rows, key=lambda r: r["ts"]), rather than relying on tuple ordering.

If the interviewer wants the iterative bottom-up version, I would switch to width doubling, 1, 2, 4, 8, merging adjacent runs into a buffer and swapping buffers each pass. Same complexity, no recursion, and easier to port to a streaming merge.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9How do you handle NULL values in your SQL queries?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

I treat NULL as unknown, not zero and not an empty string. In SQL, any comparison with NULL returns UNKNOWN, and WHERE only keeps rows where the predicate is TRUE. So I write predicates with IS NULL and IS NOT NULL, I never use = NULL, and I decide explicitly whether a missing value should be excluded, included, or replaced before it reaches a join, an aggregate, or a downstream model.

That decision depends on the column. A missing settled_at on a payment means the payment has not settled, so excluding it from a settled-volume report is correct. A missing fee_amount on a legacy transaction might mean no fee was charged, which is different from a fee that failed to load. I would not silently COALESCE both to zero.

Where NULLs bite in practice

The classic trap is NOT IN. If the subquery returns any NULL, NOT IN returns no rows at all, even for values that clearly do not match.

SQL
-- PostgreSQL 16. Checked against the documented three-valued logic.
SELECT account_id
FROM accounts
WHERE account_id NOT IN (
    SELECT account_id FROM closed_accounts
);
-- If closed_accounts.account_id contains one NULL, this returns zero rows.

-- Safer when the intent is anti-join:
SELECT a.account_id
FROM accounts a
LEFT JOIN closed_accounts c
  ON c.account_id = a.account_id
WHERE c.account_id IS NULL;

Worked trace, with closed_accounts.account_id containing 101 and NULL:

Candidate account_id= 101= NULLNOT IN (101, NULL)Kept by WHERE?
100FALSEUNKNOWNUNKNOWNNo
101TRUEUNKNOWNFALSENo
102FALSEUNKNOWNUNKNOWNNo

Every row is filtered out. The LEFT JOIN ... IS NULL version keeps 100 and 102, which is usually what the analyst meant.

Aggregates behave differently again. COUNT(*) counts rows, COUNT(col) skips NULLs, and SUM(col) ignores NULLs and returns NULL if every input is NULL. That is convenient until a pipeline loads a day with no settled payments and a downstream division by that sum produces NULL instead of an alert.

ExpressionRows: 10, 20, NULLAll rows NULL
COUNT(*)33
COUNT(amount)20
SUM(amount)30NULL
COALESCE(SUM(amount), 0)300

I use COALESCE only when zero is the business meaning, and I pair it with a separate null-rate check so a fully missing feed does not look like a quiet day.

Choosing the tool

NeedToolWhen it fits
---------
---------
Filter missing valuesIS NULL, IS NOT NULLAlways. This is the only correct equality test.
Display or downstream defaultCOALESCE(col, 0)Only when the default is a real business value.
Turn a sentinel into NULLNULLIF(col, '')Cleaning empty strings from a CSV or API feed.
Keep rows despite missing matchLEFT JOINAnti-joins and optional enrichment.
Count distinct non-null valuesCOUNT(DISTINCT col)Skips NULL automatically, unlike COUNT(*).

Two more failure modes I check in reviews. First, GROUP BY puts all NULLs in one group, so a report grouped by region can hide a large unknown bucket if the chart drops the null label. Second, in PostgreSQL a unique index treats NULLs as distinct, so (account_id, external_ref) can have many rows with external_ref IS NULL. If uniqueness matters there, I add a partial index WHERE external_ref IS NOT NULL or store a sentinel explicitly.

In a pipeline I also add contract checks at ingestion: null rate per column against a threshold, for example alert if amount is more than 1% null on a feed that was 0.02% null last week, and a row-count reconciliation before and after any COALESCE or join. That catches a broken upstream load while the fix is still a backfill, not a restated finance report.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10How would you use window functions to solve complex data extraction problems?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

Window functions compute a value over a set of rows related to the current row, without collapsing rows the way GROUP BY does. That is why they fit extraction problems where you need to keep every input row and still rank, compare it to its neighbours, or accumulate it. I would start by naming the relation: same partition, what order inside it, and which frame. PARTITION BY decides the group, ORDER BY decides the sequence, and the frame (ROWS BETWEEN ...) decides how much of that sequence the aggregate sees.

Three patterns cover most of the work I do on trade and market data at a firm like StoneX.

1. Latest or deduplicated record per key

SQL
-- PostgreSQL 15 / Snowflake / BigQuery syntax is close here
WITH ranked AS (
  SELECT *,
         ROW_NUMBER() OVER (
           PARTITION BY symbol, trade_id
           ORDER BY ingested_at DESC, event_seq DESC
         ) AS rn
  FROM raw_trades
)
SELECT symbol, trade_id, price, qty, ingested_at
FROM ranked
WHERE rn = 1;

The tiebreaker matters. Without event_seq, two corrections with the same ingested_at make ROW_NUMBER() pick one arbitrarily, and reruns can silently flip which price survives. I add a unique, monotonic tiebreaker or fail the job when ties remain.

2. Gaps, sessions and neighbour comparison with LAG / LEAD

SQL
SELECT symbol, ts,
       ts - LAG(ts) OVER w AS gap_seconds,
       price - LAG(price) OVER w AS price_change
FROM ticks
WINDOW w AS (PARTITION BY symbol ORDER BY ts)
ORDER BY symbol, ts;

Worked trace for one symbol, hypothetical figures:

tspriceLAG(price)price_changegap_seconds
09:30:00101.20NULLNULLNULL
09:30:05101.35101.200.155
09:30:06101.10101.35-0.251
09:45:00102.00101.100.90894

The 894 second gap flags a feed interruption or a session break. A common follow on is sessionisation: mark a new session when the gap exceeds a threshold, then SUM(is_new_session) OVER (PARTITION BY symbol ORDER BY ts) gives a session id per row without a self join.

3. Running totals and rolling windows

SQL
SELECT symbol, ts, qty,
       SUM(qty) OVER w AS cum_qty,
       AVG(price) OVER (PARTITION BY symbol ORDER BY ts
                        ROWS BETWEEN 99 PRECEDING AND CURRENT ROW) AS ma_100
FROM ticks
WINDOW w AS (PARTITION BY symbol ORDER BY ts
             ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW);

The frame is the trap. The default frame with ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes every peer with the same ts. If timestamps repeat, a cumulative sum can jump by several rows at once. I state ROWS explicitly unless peer handling is the point.

ApproachKeeps detail rowsCost / limit
GROUP BY + aggregateNo, one row per groupCheapest for pure aggregates
Window functionYesSorts or hashes per partition; watch skew
Self join on LAG logicYesOften quadratic on large partitions

Failure modes I check before shipping: partition skew, where one symbol or trade_id holds most rows and one worker does all the sorting; nondeterministic ordering from missing tiebreakers; and NULL handling, since LAG returns NULL on the first row of each partition and SUM ignores NULLs in a way that can hide a bad feed. I validate by comparing row counts in and out, checking that rn = 1 yields exactly one row per key, and spot checking the first row of each partition, where window logic is most likely to be wrong.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11Walk me through your most significant technical project?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

At my previous firm I led the rebuild of our market data ingestion pipeline, which fed risk, pricing and client reporting from three exchanges. The old system was a nightly batch that landed tick data 14 hours late, dropped corrections silently and broke whenever an exchange changed a field order. We replaced it with a streaming pipeline that lands normalised ticks in Apache Iceberg within about 90 seconds of receipt, with a replayable raw layer underneath.

The scope was deliberately narrow. We did not try to build a general trading platform. We owned ingestion, normalisation, deduplication and the contract that downstream teams could trust: every row carries exchange, symbol, event time, ingestion time and a sequence number, and corrections arrive as new versions rather than overwrites.

Exchange feeds Kafka raw topic Normalise and validate Iceberg bronze raw Iceberg silver ticks Risk and pricing Reporting aggregates Replay and backfill

What it actually had to handle

Peak load was roughly 2.1 million messages per second across the three feeds, about 38 TB of raw data per day before compression. That figure is from our production metrics, not a design target. At that rate a single slow consumer partition creates backpressure in minutes, so we partitioned Kafka by exchange and symbol hash, sized partitions for peak plus 40 percent headroom, and kept consumer lag as the primary alert rather than CPU.

Normalisation was the hard part. Each exchange used different field names, timestamps in different units and different conventions for cancelled trades. We wrote one parser per exchange behind a common schema, and we treated the raw payload as immutable. If a parser bug appeared, we could fix it and replay from Kafka retention or from bronze without asking the exchange to resend anything.

Deduplication used the exchange sequence number to identify a trade, but not as the sole drop key. An exact retransmission, same sequence and same price and quantity, was dropped. A correction arrived with the same sequence and a different price or a correction flag, so it became a new row version and downstream queries picked the latest version per sequence. That choice cost us storage, about 18 percent extra on silver, and saved us from a class of bugs where an overwrite destroyed the audit trail.

Python
# Python 3.12, PySpark 3.5 structured streaming
from pyspark.sql import functions as F

raw = (
    spark.readStream.format("kafka")
    .option("kafka.bootstrap.servers", brokers)
    .option("subscribe", "ticks.raw")
    .load()
)

parsed = raw.select(
    F.from_json(F.col("value").cast("string"), schema).alias("e")
).select("e.*")

# dropDuplicates() with no subset drops only rows identical in
# every column, so a correction with a changed price survives.
stream = (
    parsed.withWatermark("event_time", "2 minutes")
    .dropDuplicates()
)

(
    stream.writeStream
    .format("iceberg")
    .option("checkpointLocation", "s3://lake/checkpoints/silver")
    .outputMode("append")
    .start("s3://lake/silver/ticks")
)

The two minute watermark was a trade-off we argued about for a week. A longer watermark tolerates more late data but delays aggregates. Two minutes covered 99.7 percent of late arrivals in our traces. The remaining 0.3 percent still landed in silver, but they were excluded from the five minute aggregates and flagged for a nightly reconciliation job.

Failure modes we designed for

ScenarioDetectionHandling
Exchange adds a field or reorders columnsParser validation fails, dead letter topic growsRaw payload preserved, parser updated, replay from bronze
Late correction after aggregates publishedReconciliation job compares silver versions to aggregatesAggregates recomputed for affected windows, versioned output
Kafka broker loss during peakConsumer lag and ISR shrink alertsPartitions rebalance, no data loss because producers used acks=all
Duplicate sequence from a reconnectDrop count metric spikesExact duplicates dropped by full row match, counted and logged

Schema drift was the most common incident. We added a contract test that ran sample payloads from each exchange through the parsers on every deploy. It caught a timestamp unit change from milliseconds to microseconds before it reached production. Read as milliseconds, those values would have landed about 1000 times in the future and been dropped by the watermark, which is why the test checked ranges as well as types.

What I would do differently

I would start the reconciliation job on day one instead of week six. We discovered the late data problem through a finance discrepancy, which is the wrong way to learn about it. I would also have pushed harder for a single schema registry with enforced compatibility checks. We built our own validation, and it worked, but it duplicated work the registry would have done.

The result we could defend in numbers: median ingestion latency fell from 14 hours to 90 seconds, dropped trades went from roughly 0.4 percent of messages to under 0.01 percent, and a full day replay took about 50 minutes instead of a manual reload that took most of a weekend. The part I am proudest of is not the throughput. It is that when something went wrong, we could point to the raw bytes and explain exactly what happened.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12What frameworks did you use in your project and why?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

I would name the project first, then the frameworks as decisions, not a stack list. My last pipeline ingested trade and reference data for regulatory reporting: about 40 million events a day, late corrections arriving up to T+3, and an audit requirement to reproduce any reported figure months later. That pushed me to four choices: Kafka for ingestion, Spark Structured Streaming for stream processing, Airflow for orchestration, and dbt for the warehouse transformations that feed reporting. I deliberately did not put Flink or a managed streaming service in the critical path, and I did not use dbt for the streaming layer.

The reasoning is constraint by constraint. Kafka gave me replay. When a downstream bug corrupted a partition, I could reprocess from a retained topic instead of asking the source to resend. Spark fit the team and the workload: most processing was windowed aggregation and joins against slowly changing reference tables, which Spark handles well with state stores and broadcast joins, and our engineers already wrote Spark SQL. Airflow handled the batch side, backfills, and data quality gates, which is where scheduling complexity actually lived. dbt gave reviewers SQL they could read and test in pull requests, with lineage and column level tests attached to the models that produced reported numbers.

Why each framework, and what I rejected

LayerChosenAlternative consideredDeciding factor
IngestionKafka, 7 day retention, 12 partitions per topicKinesis, managed KafkaReplay and schema registry control; we needed to reprocess 7 days without source cooperation
Stream processingSpark Structured Streaming, 5 minute micro batchesFlink, Kafka StreamsTeam already on Spark; 5 minute latency met reporting SLA; Flink would have meant a second runtime to operate
OrchestrationAirflow 2.9, Kubernetes executorDagster, PrefectExisting Airflow estate, mature backfill and sensor patterns, hiring pool
Transformationdbt Core on SnowflakeSpark SQL jobs, hand written SQL in AirflowReviewable SQL, tests, and lineage for audit; streaming logic stayed in Spark where dbt cannot run

The split matters. dbt is excellent for declarative batch models and tests, and poor for stateful streaming, watermarks, and late data handling. Spark is the reverse. Putting reporting logic in dbt and stream aggregation in Spark kept each tool inside its strength. If I had chosen Flink, I would have gained lower latency, roughly sub second instead of 5 minutes, but paid for it with a separate deployment, state backend, and on call skill set for a workload that did not need it.

How it ran in practice

Kafka topics were partitioned by instrument identifier so ordering held per instrument. Spark used a 10 minute watermark for late events and wrote to a bronze table in Parquet partitioned by trade date. Airflow then ran dbt models hourly for silver and gold layers, with a freshness sensor on the bronze partition before dbt started. A typical DAG looked like this:

Python
from airflow.decorators import dag, task
from airflow.providers.sensors.sql import SqlSensor
from airflow.providers.dbt.cloud.operators.dbt import DbtCloudRunJobOperator

@dag(schedule="@hourly", catchup=False, max_active_runs=1)
def trade_reporting():
    bronze_ready = SqlSensor(
        task_id="bronze_ready",
        poke_interval=60,
        timeout=3600,
        conn_id="snowflake",
        sql="SELECT COUNT(*) FROM bronze.trade_events WHERE trade_date = '{{ ds }}'",
    )
    dbt_run = DbtCloudRunJobOperator(
        task_id="dbt_silver_gold",
        job_id=12345,
    )
    bronze_ready >> dbt_run

trade_reporting()

The arithmetic that justified micro batches: 40 million events a day is about 460 events per second on average, peaking near 4,000 per second at the open. A 5 minute micro batch therefore holds roughly 1.2 million events at peak, which a 20 executor Spark cluster processed in about 40 seconds in our load test. That left headroom for a late correction burst without growing the cluster. Running continuous streaming would have kept executors warm 24 hours for a reporting SLA measured in minutes.

Failure modes I had to handle

Late and corrected trades were the main one. Spark wrote corrections as new rows with a revision number, and dbt models deduplicated by taking the highest revision per trade identifier. Without that, a T+2 correction would double count volume. I detected it with a reconciliation check comparing event counts in Kafka against bronze row counts per hour, alerting on a gap above 0.1 percent.

Schema drift was the second. A source added a field and changed a type from string to integer. The schema registry rejected the incompatible producer, which surfaced in staging before it reached Spark. I kept backward compatibility enforced in the registry and added a contract test in CI that serialized a sample payload against the registered schema.

Airflow backfills were the third. A failed dbt run left a partial gold table. I made dbt models write to staging tables and swap on success, and set max_active_runs=1 so a backfill could not race the hourly run and overwrite the same partition. Backfilling 30 days then became a matter of re running the DAG with a date range, not repairing tables by hand.

If the volume had grown tenfold or the SLA had tightened to seconds, I would revisit Flink for the streaming layer and keep the rest. For this workload, the framework choice followed the latency requirement, the audit requirement, and what the team could operate at 2 a.m., in that order.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13How do you approach solving a complex technical problem?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

I treat it as a debugging problem with a contract at the end. First I restate the expected behaviour in measurable terms, then I reproduce the smallest case that breaks it, then I bisect until one variable explains the failure. Only then do I change code, and I close by adding the check that would have caught it earlier.

For a data pipeline that means I never start by tuning Spark or rewriting a query. I start by asking what the output should have been, row counts, keys, freshness and totals, and what it actually was. That turns "the pipeline is broken" into something testable.

A concrete case I would walk through

Say a daily incremental load for trade records normally lands about 2.4 million rows by 06:00. One morning it lands 1.1 million rows at 09:30, and downstream revenue is understated. Hypothetical figures, but the shape is typical. The shortfall is 1.3 million rows, about 54% of the expected total.

Define expected vs actual Reproduce smallest failing slice Bisect by source, partition and time Form one hypothesis Test against held-out slice Fix and backfill Add guard check

Step one is definition. I compare source count, staged count and published count for the same business date, broken down by source system and partition. If the source sent 2.4 million and staging holds 2.4 million but publishing holds 1.1 million, the fault is downstream of staging. If staging is already short, I stop looking at the warehouse entirely.

Step two is reproduction at the smallest slice. I pick one source and one hour where the gap appears and rerun that slice in isolation, with the same code version and the same input files. A full rerun of the day tells me nothing new. A one-hour slice I can rerun five times tells me whether the failure is deterministic or intermittent.

Step three is bisection. I vary one thing at a time: same slice with the previous code version, same code with the previous day's input, same code and input with a larger executor memory. The trace I would show in the interview looks like this:

CheckResultWhat it tells me
Source file row count for 02:00 hour198,000 rows, matches upstream manifestSource file is complete, not truncated or late
Staged count before dedupe197,400 rowsLoad step is not dropping rows
Staged count after dedupe121,000 rowsDedupe step is removing about 76,000 rows, evidence for a key collision
Rerun of 02:00 slice, old code197,100 rows publishedOld code handles this input correctly, which implicates the new code change
Rerun of 02:00 slice, new code121,000 rows publishedSame input, different result, so the code change is the variable that matters

That pattern points at the dedupe logic in the new version, not at infrastructure. The new code had started deduplicating on trade ID alone instead of trade ID plus venue, so legitimate trades from two venues with overlapping IDs were collapsing. I would confirm it by querying the staged data for IDs that appear more than once across venues before dedupe.

Step four is a single hypothesis with a test I can falsify. "The dedupe key is too narrow" predicts that restoring the composite key on the held-out hour restores the count to about 197,000 without changing any other number. If it does not, the hypothesis is wrong and I go back to bisection rather than stacking fixes.

Fix, backfill and guard

The fix is small: restore the composite key and add a unit test with two venues sharing a trade ID. The backfill is separate from the fix. I backfill only the affected partitions, from the staged data that was correct before dedupe, and I reconcile published totals against the source manifest before I let downstream consumers read the corrected partitions. Backfilling the whole history because it is easier would waste compute and risk overwriting good partitions.

The guard is a reconciliation check that runs after every load and fails the publish step, not just sends an alert:

Python
# Python 3.11, checked against a warehouse table with columns source, trade_id, venue
def check_reconciliation(source_count: int, published: int, tolerance: float = 0.001) -> None:
    if source_count == 0:
        raise ValueError("source manifest is empty, refusing to publish")
    drift = abs(source_count - published) / source_count
    if drift > tolerance:
        raise AssertionError(f"row count drift {drift:.3%} exceeds {tolerance:.3%}: source={source_count} published={published}")

In this case a 0.1% tolerance would have caught a 54% shortfall at 06:00 instead of letting it reach a revenue report. I would also add a per-source check, because a total can look fine while one source is missing entirely and another is duplicated.

Failure modes I watch for in my own process

The common one is fixing the symptom. Adding executor memory or splitting the job would have made the wrong dedupe finish faster. I detect that by requiring the rerun of the smallest slice to pass before any tuning is considered.

Another is changing two things at once, code and config, then being unable to say which one worked. My rule is one variable per rerun, and I write the result down in the table above before moving on.

A third is declaring victory after the fix without the guard. If the check that would have caught this is not in the pipeline, the same class of bug returns with a different key or a different source. That is why the guard, and a test case built from the actual failing slice, are part of the fix rather than follow-up work.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14Describe a time you faced a conflict within a team and how you resolved it?

Reported in StoneX Data Engineer Interview Questions & Guide 2026

The 90-second answer

At my last role I owned ingestion for card transaction data feeding finance reporting. The analytics lead wanted to replace our incremental pipeline with a nightly full refresh because reconciliation kept failing on late-arriving reversals. I pushed back. A full refresh of the transactions table was 340 GB and took 3 hours 40 minutes, which put the 06:00 finance cut at risk. We argued for two sprints about who owned the failure, which was not productive. I stopped debating ownership and proposed we run both approaches on the same five days of data and compare them on runtime, freshness and reconciliation breaks. That test settled it and we shipped a hybrid neither of us had originally proposed.

What the conflict was about

Finance needed reversals that arrived up to 36 hours late to appear in the same day's totals. Our incremental job used updated_at as a watermark and dropped anything older than the watermark, so about 0.4% of events, mostly reversals, were missed and the daily totals drifted by up to 0.3%. The analytics team saw that as a data quality failure in my pipeline. I saw a full refresh as a cost and reliability failure: it scanned the whole table every night, it had missed the 06:00 cut on two of the previous five days, and it would have doubled our warehouse spend for that workload. Both concerns were legitimate. The argument was really about which failure mode the business could tolerate.

How I resolved it

I wrote a one page decision note with the two options, the figures we already had, and the one figure we did not have: how often late reversals actually changed a published total. Then I ran a five day comparison in a scratch schema, with the same source snapshot for both jobs.

ApproachRuntimeFreshnessReconciliation breaks in 5 days
Full refresh3 h 40 min median06:00 cut missed twice0
Incremental, current watermark12 min median15 min4 days drifted
Incremental plus late-event pass14 min median15 min, late events by 02:000

The third row came out of the test. We kept the incremental job for intraday freshness and added a nightly pass that only reprocessed events with updated_at in the previous 48 hours and matched them to existing keys. That pass is cheap because it touches roughly 18 GB instead of 340 GB, and it catches the reversals the watermark missed.

SQL
-- late-event pass, run after the incremental load
merge into transactions as t
using staging_transactions as s
  on t.event_id = s.event_id
when matched then
  update set t.amount = s.amount,
             t.status = s.status,
             t.updated_at = s.updated_at
when not matched then
  insert (event_id, amount, status, updated_at)
  values (s.event_id, s.amount, s.status, s.updated_at);
-- staging is filtered to updated_at >= current_date - 2
Disagreement over refresh strategy Write options and known figures Run both on same 5 day snapshot Add late-event pass and retest Agree hybrid and owner for reconciliation Ship with alert on drift over 0.05 percent

We also agreed who owned what after the change. I owned the incremental load and the late-event pass. The analytics engineer owned the reconciliation query and the alert threshold, set at 0.05% drift between the two totals. That split mattered because the original conflict had been partly about whose dashboard looked wrong.

What I would do differently

I raised the cost figures late. For the first week I argued from principle about full refreshes while the other side argued from principle about correctness, and neither of us had put the 0.4% late-event rate or the missed 06:00 cuts in the same document. If I had brought the five day test into the first meeting, we would have saved a week. The lesson I took from it is to turn a disagreement about ownership into a disagreement about a measurable outcome as early as possible, then let the test decide.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-15Explain encapsulation, abstraction, inheritance, and polymorphism, including how each works and how they differ in real code?

Reported in StoneX Data Engineer Interview Questions | Dataford

The 90-second answer

In a pipeline codebase I use all four, but for different jobs. Encapsulation keeps state and the rules for changing it in one place. Abstraction hides the implementation behind a small interface. Inheritance reuses code by extending a base class. Polymorphism lets different implementations satisfy that interface, so callers do not care which one runs.

Take ingestion. I define an abstract Source with one method, read(). CsvSource and ParquetSource both implement it. The job calls source.read() and gets rows back. It never imports a CSV parser. That is abstraction (the interface) plus polymorphism (two classes, one call site). Encapsulation sits inside each source: the file path, delimiter and schema live as private attributes, and the only way to change them is through a constructor or a validated property, so a caller cannot set delimiter to an empty string halfway through a run.

Inheritance is the one I reach for last. It is useful when two classes genuinely are the same kind of thing, for example ParquetSource and CsvSource both being a FileSource that handles retries and checkpointing. When the shared behaviour is just a helper, I prefer composition: pass a RetryPolicy object into the source instead of inheriting it. Composition survives schema changes better, because a fragile base class breaks every subclass when its constructor changes.

Python
# Python 3.12
from abc import ABC, abstractmethod
from dataclasses import dataclass

class Source(ABC):
    @abstractmethod
    def read(self) -> list[dict]: ...

@dataclass(frozen=True)
class CsvSource(Source):
    path: str
    delimiter: str = ","

    def __post_init__(self):
        if not self.delimiter:
            raise ValueError("delimiter must not be empty")

    def read(self) -> list[dict]:
        # open self.path, parse with self.delimiter, return rows
        return []

@dataclass(frozen=True)
class ParquetSource(Source):
    path: str

    def read(self) -> list[dict]:
        # read parquet footer, return rows
        return []

def load(source: Source) -> list[dict]:
    return source.read()  # polymorphism: same call, either class

frozen=True is encapsulation in practice here. Once a source is built for a run, its configuration cannot drift. If a caller tries source.delimiter = ";", Python raises. That matters when the same object is shared across threads in a Spark driver or a test fixture.

ConceptQuestion it answersIn the pipeline exampleCost when misused
EncapsulationHow is state protected?Private _schema, validated constructor, frozen configPublic mutable fields let any module corrupt a run mid-flight
AbstractionWhat can callers rely on?Source.read() signature, no parser details leak outInterface too wide, callers depend on CSV specifics
InheritanceWhat code is reused by extension?FileSource adds retry and checkpoint logic to both readersDeep hierarchies couple every subclass to base class changes
PolymorphismCan implementations be swapped?load(CsvSource(...)) and load(ParquetSource(...)) use one code pathHidden type checks (isinstance) replace the interface

Where each one bites in real code

Encapsulation fails quietly when it is only a naming convention. Python's _schema is still writable, so for invariants that matter, such as a non-empty delimiter or a schema version inside a supported range, I validate in __post_init__ or expose a read-only property. In SQL and Spark code the same idea appears as a UDF that owns its null handling, rather than every caller reimplementing COALESCE differently.

Abstraction fails when the interface is a copy of one implementation. If Source exposes delimiter, compression and header_row, it is a CSV interface wearing a generic name, and a Parquet source will implement half of it as no-ops. I keep the interface to what every implementation can honour honestly. For data frames that means read() returning rows, plus a separate schema() method if consumers need types before reading. Splitting those two keeps a lazy Spark source and an eager pandas source interchangeable without pretending they have the same cost profile.

Inheritance has a specific failure mode in data code: the fragile base class. A BaseTransform that gains a new required constructor argument breaks every transform subclass and every test that builds them. The fix I use is composition for cross-cutting behaviour (retry, logging, metrics) and inheritance only for genuine is-a relationships, usually one level deep. If I see a hierarchy deeper than two levels in a pipeline repo, I expect the third level to be a candidate for a plain function.

Polymorphism is what makes the rest testable. Because load depends only on Source, a unit test can pass a FakeSource that returns three fixed rows, with no file on disk. The same pattern applies to transforms: a Transform protocol with run(df) lets the same logic run against a local pandas frame in a test and a Spark frame in production, provided the interface stays inside the subset both support. When a transform needs Spark-only behaviour, I make that a separate class behind the same protocol and let the job configuration choose, rather than adding a branch inside the shared code.

The short version I would give in the loop: encapsulation protects state, abstraction defines the contract, inheritance reuses implementation, and polymorphism lets you swap implementations behind that contract. In my own code I lean on the first two and the last one, and I treat inheritance as the tool to justify, not the default.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16What are your favorite programming languages and why?

Reported in StoneX Data Engineer Interview Questions | Dataford

The 90-second answer

Python first, SQL second, and Scala only when the JVM earns its place. That ordering reflects where data engineering time actually goes at a firm like StoneX: most work is ingestion, orchestration, data quality checks and backfills, where Python's ecosystem and readability win. The heavy set based transforms belong in SQL, because the optimizer, not my loops, should decide join order and partitioning. I reach for Scala on Spark when a Python UDF or a shuffle bound job has hit a measured ceiling and the team already runs JVM services.

I would not claim a language is best in the abstract. I pick by workload, team skill and operational cost.

LanguageWhere I use itWhy it fitsWhere it hurts
Python 3.12Airflow DAGs, ingestion, validation, PySpark driver codeFast to change, huge libraries, easy to review in a pull requestGIL limits thread parallelism, pandas can blow memory on large frames
SQL (Postgres and Spark SQL)Warehouse models, incremental transforms, reconciliationDeclarative, optimizer handles joins and pruning, portable logicDialect differences, weak control flow, hard to unit test without a database
Scala 2.13Spark jobs with custom shuffles or complex UDFsRuns on the JVM, typed, close to Spark internalsSlow compile times, smaller hiring pool, harder for analysts to maintain

Python for the control plane. A typical StoneX style pipeline ingests trade or market data files, lands them in object storage, validates schema and row counts, then triggers the transform. Python handles the first and last steps well. I keep the transform itself in SQL or Spark so a rerun is deterministic.

Python
# Python 3.12, checked against PySpark 3.5 semantics
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("daily-trades").getOrCreate()

# Idempotent partition write: overwrite only the target date partition
(
    spark.read.parquet("s3://stonex-landing/trades/date=2026-05-01")
        .filter("amount > 0")
        .write.mode("overwrite")
        .option("partitionOverwriteMode", "dynamic")
        .partitionBy("date")
        .parquet("s3://stonex-curated/trades")
)

The failure mode I watch for is a Python UDF inside a shuffle. In a hypothetical 2 TB daily job, a row by row Python UDF can run roughly 5 to 10 times slower than the equivalent native expression and it blocks whole stage parallelism. I measure that with Spark UI stage time before rewriting anything. If the UDF is the bottleneck, I move the logic to a native function or to Scala.

SQL for transforms. Window functions, CTEs and incremental merges express the business rule directly. For a late arriving trade correction, I would rather write a MERGE keyed on trade id and event time than a Python loop that deduplicates in memory. SQL also makes lineage clearer for auditors: the query text is the specification. The limit is dialect drift. QUALIFY exists in Snowflake and Spark but not Postgres, and date truncation syntax differs, so I pin the dialect per warehouse and test queries in CI against a containerised instance.

Scala when the JVM pays off. I have used it for Spark jobs where I needed custom partitioning or a typed UDF called millions of times per second. The trade off is real. Compile times of several minutes on a large module slow iteration, and fewer data engineers on a team can debug it at 2 a.m. I only accept that cost when profiling shows the Python path cannot meet the SLA.

Landing files in S3 Python ingestion and schema checks SQL incremental model Scala Spark job if shuffle bound Curated tables and audit counts

Adaptability matters more than loyalty. If a team standardises on Java for Spark, I can write that too, and if a new warehouse makes dbt and SQL the centre of gravity, I am happy to let Python shrink to orchestration. My preference is a stack where the language matches the layer: Python to move and check data, SQL to transform it, JVM languages only for proven hot paths.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-17Explain a project's key technical decisions?

Reported in StoneX Data Engineer Interview Questions | Dataford

The 90-second answer

I will use the transaction ingestion pipeline I built for a payments platform processing card and Pix events. The problem was 2.1 million events a day, bursty to 40,000 a minute at peak, landing in a warehouse that finance and risk both queried. Three decisions shaped everything else: ingest as an append-only event stream rather than upserting rows, partition storage by event date and merchant, and enforce deduplication on the producer event ID before any aggregation.

That gave us replayable history, which mattered more than keeping a current balance table perfectly up to date. If a downstream model was wrong, we could rebuild it from the raw events. The cost was storage and a harder query pattern for "current state", which we solved with a separate snapshot table built hourly.

DecisionOptions consideredChoseTrade-off accepted
IngestionNightly batch, Kafka streaming, direct API writesKafka streaming into Parquet on object storageOperational cost of a broker for lower latency, about 90 seconds end to end instead of next morning
DeduplicationDatabase unique key, producer event ID check in streamProducer event ID, checked in the consumerDuplicates dropped before the warehouse, but a buggy producer reusing IDs would lose events, so IDs are UUIDv4 generated at the edge
Storage layoutOne table, partition by merchant only, partition by date and merchantPartition by event date, then merchantDate partitions keep daily reconciliation cheap, merchant partitions keep per-merchant backfills from scanning the full day
Schema changeReject unknown fields, allow them, version every changeAllow additive fields, reject type changesAdditive fields flow through without a deploy, type changes fail the job loudly instead of silently corrupting amounts
Edge producers Kafka topic: transactions.v1 Stream consumer: validate and dedupe Object storage: Parquet, date and merchant partitions Warehouse raw table Hourly snapshot: current balances Daily reconciliation: finance

Deduplication in the consumer

Producers retry after a timeout, so the same event can arrive twice. The consumer keeps a 48 hour set of seen IDs in a key-value store and drops repeats before writing.

Python
# Python 3.11, consumer side, checked against Redis SETNX semantics
def handle(event: dict) -> str:
    event_id = event["event_id"]
    if not store.set_if_absent(f"seen:{event_id}", "1", ttl_seconds=48 * 3600):
        return "duplicate_dropped"
    validate(event)  # raises on type change or missing amount
    writer.write(event, partition_date=event["occurred_at"][:10])
    return "written"

Trace for a retry: first delivery writes the event and returns written. The retry 3 seconds later hits set_if_absent, gets false, and returns duplicate_dropped. No second row reaches the warehouse, so the daily total stays correct without a later cleanup job.

What went wrong and how we detected it

Late events were the main failure mode. About 0.4 percent of events arrived more than 24 hours late, mostly from offline terminals syncing. They landed in the wrong date partition if we partitioned by arrival time, so we partitioned by occurred_at and added a late-arrival metric per merchant. When one merchant exceeded 2 percent late, an alert fired and we found a terminal firmware bug.

The second failure was a producer sending amounts as strings after a library upgrade. Validation rejected the batch, the consumer dead-lettered it, and the reconciliation job showed a gap of 18,000 events for that hour. That was preferable to the alternative, coercing strings to numbers and hiding a unit change from cents to reais.

Result after six months: p99 ingestion latency of 110 seconds, duplicate rate in the warehouse at zero by construction, and a full rebuild of the risk features table from raw events in 4 hours instead of being blocked on a corrupted current-state table.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18Rewrite a slow PostgreSQL loan payment query to reduce scanned rows while preserving the required aggregated results?

Reported in StoneX Data Engineer Interview Questions | Dataford

The 90-second answer

I would first pin down the exact aggregate to preserve, then look at EXPLAIN (ANALYZE, BUFFERS) to see where rows are being scanned and discarded. For a loan payment rollup the usual culprits are a function on the filtered column, a join before filtering, and an index that does not cover the columns the query needs.

Assume this schema and this required result: monthly principal and interest totals per loan, for completed payments in 2024, for active loans. Money is stored as integer cents in bigint columns.

SQL
-- payments(loan_id bigint, paid_at timestamptz, principal_cents bigint,
--           interest_cents bigint, status text)
-- loans(loan_id bigint primary key, status text, region text)

A slow version I see in the wild:

SQL
SELECT l.loan_id,
       date_trunc('month', p.paid_at) AS month,
       SUM(p.principal_cents) AS principal_cents,
       SUM(p.interest_cents)  AS interest_cents,
       COUNT(*)               AS payment_count
FROM payments p
JOIN loans l ON l.loan_id = p.loan_id
WHERE p.status = 'completed'
  AND l.status = 'active'
  AND date_trunc('month', p.paid_at) >= date_trunc('month', DATE '2024-01-01')
  AND date_trunc('month', p.paid_at) <  date_trunc('month', DATE '2025-01-01')
  AND (l.region = 'UK' OR l.region = 'EU')
GROUP BY l.loan_id, month;

Three problems. date_trunc('month', p.paid_at) in the WHERE clause cannot use a paid_at index. The join runs over every payment before the loan filters apply. And with no covering index, every matching row needs a heap fetch to get the amount columns.

The rewrite

Aggregate payments first, on a plain range predicate, then join the much smaller result to loans. That preserves the sums because loans.loan_id is the primary key, so the join cannot duplicate a payment row. If that uniqueness were not guaranteed, I would stop here and check for fan-out before trusting any total.

SQL
WITH monthly AS (
    SELECT loan_id,
           date_trunc('month', paid_at) AS month,
           SUM(principal_cents) AS principal_cents,
           SUM(interest_cents)  AS interest_cents,
           COUNT(*)             AS payment_count
    FROM payments
    WHERE status = 'completed'
      AND paid_at >= TIMESTAMPTZ '2024-01-01'
      AND paid_at <  TIMESTAMPTZ '2025-01-01'
    GROUP BY loan_id, month
)
SELECT m.loan_id, m.month, m.principal_cents, m.interest_cents, m.payment_count
FROM monthly m
JOIN loans l ON l.loan_id = m.loan_id
WHERE l.status = 'active'
  AND l.region IN ('UK', 'EU')
ORDER BY m.loan_id, m.month;

The index that makes this an index-only scan (PostgreSQL 16):

SQL
CREATE INDEX CONCURRENTLY payments_completed_paid_at_idx
    ON payments (paid_at, loan_id)
    INCLUDE (principal_cents, interest_cents)
    WHERE status = 'completed';

IN ('UK','EU') replaces the OR so the planner can use a bitmap or index scan on loans instead of evaluating a non-sargable condition per row. The range on paid_at is sargable, so the partial index applies to exactly the rows the aggregate needs.

Worked trace

Hypothetical figures from a 48 million row payments table, labelled as an example, not a claim about your data:

PlanRows scannedHeap fetchesTimeOutput rows
Original: Seq Scan on payments, join, filter48,000,00048,000,00012,400 ms310,000
Rewrite, no new index: Index Scan on paid_at1,900,0001,900,0002,100 ms310,000
Rewrite + partial covering index: Index Only Scan1,900,0000380 ms310,000

The output row count and the sums must match the original query on the same snapshot. I would diff them with an EXCEPT on both result sets before shipping, because a rewrite that changes COUNT(*) or drops a NULL handling difference is a silent correctness bug. SUM ignores NULL amounts in both versions, so that behaviour is preserved.

Alternatives and when I would not use this

ApproachWhen it winsCost
Partial covering index, as aboveQuery shape is stable and freshness must be immediateWrite amplification on every completed payment, index size roughly the completed subset
Pre-aggregate into a monthly summary tableSame rollup runs many times a dayStaleness between refreshes, needs a backfill and late-arriving payment handling
Partition payments by month on paid_atTable is far larger than one year and old partitions are rarely touchedPartition pruning only helps if the predicate is a plain range, which the rewrite now has

Failure modes I would check in review: a partial index silently stops matching if a new status value such as 'settled' replaces 'completed' in the application, so the predicate must be owned by the data contract. CREATE INDEX CONCURRENTLY avoids a write lock but takes longer and can fail on a busy table, so I would run it outside a transaction and watch pg_stat_user_indexes. If the planner still chooses a sequential scan after ANALYZE, the table may be too small for the index to pay off, or statistics on paid_at may be stale. Finally, if loans ever loses its primary key guarantee during a migration, the pre-aggregation order changes the result, so the uniqueness check belongs in the migration test, not in a comment.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19Calculate a three-day moving average of active-client revenue using aggregation and SQL window functions?

Reported in StoneX Data Engineer Interview Questions | Dataford

The 90-second answer

Aggregate first, then window. Aggregation collapses raw events to one row per client per day, so five trades in a day do not count as five days. The window then averages the last three daily values for that client.

Assumptions I would state up front: revenue_events holds one row per trade or accrual, client_id identifies the client, and "three-day" needs a definition. It can mean the last three days the client traded, or the last three calendar days including zero-revenue days. Those give different numbers, so I would show both and ask which one finance reports.

SQL
-- PostgreSQL 15 syntax
WITH daily AS (
    SELECT
        client_id,
        CAST(event_ts AS DATE) AS day,
        SUM(revenue) AS daily_revenue
    FROM revenue_events
    WHERE revenue IS NOT NULL
    GROUP BY client_id, CAST(event_ts AS DATE)
)
SELECT
    client_id,
    day,
    daily_revenue,
    AVG(daily_revenue) OVER (
        PARTITION BY client_id
        ORDER BY day
        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
    ) AS ma3_last_3_trading_days,
    AVG(daily_revenue) OVER (
        PARTITION BY client_id
        ORDER BY day
        RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW
    ) AS ma3_last_3_calendar_days_on_traded_rows
FROM daily
ORDER BY client_id, day;

ROWS counts rows present in daily. RANGE with an interval counts calendar distance, but still only over rows that exist. Neither inserts a zero for a missing day.

Worked trace

Client A trades Monday, Wednesday and Thursday, with no revenue on Tuesday. After aggregation daily has three rows.

DayDaily revenueROWS averageRANGE average
Mon100100.00100.00
Wed300200.00200.00
Thu200200.00250.00

On Wednesday, ROWS averages Monday and Wednesday: (100 + 300) / 2 = 200. RANGE does the same here because Monday is exactly two days before Wednesday. On Thursday, ROWS still includes Monday, giving (100 + 300 + 200) / 3 = 200. RANGE excludes Monday because it is three days before Thursday, giving (300 + 200) / 2 = 250. There is no Tuesday row in either output.

For a true calendar average, where Tuesday counts as zero, I would build a spine so zero days are explicit rows, then use ROWS over that spine:

SQL
WITH calendar AS (
    SELECT CAST(d AS DATE) AS day
    FROM generate_series(
        (SELECT MIN(day) FROM daily),
        (SELECT MAX(day) FROM daily),
        INTERVAL '1 day'
    ) AS d
),
clients AS (
    SELECT DISTINCT client_id FROM daily
),
spine AS (
    SELECT c.day, cl.client_id, COALESCE(d.daily_revenue, 0) AS daily_revenue
    FROM calendar c
    CROSS JOIN clients cl
    LEFT JOIN daily d
      ON d.client_id = cl.client_id AND d.day = c.day
)
SELECT client_id, day, daily_revenue,
       AVG(daily_revenue) OVER (
           PARTITION BY client_id ORDER BY day
           ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
       ) AS ma3_calendar
FROM spine;

Note cl.client_id, not d.client_id. On a zero day d is NULL, so selecting d.client_id would put every zero day in a single NULL partition and mix clients together.

Over the spine, the same client gives Mon 100.00, Tue 50.00, Wed 133.33 and Thu 166.67. Wednesday is (100 + 0 + 300) / 3 and Thursday is (0 + 300 + 200) / 3. That is the number to quote if the report is calendar based.

The spine multiplies rows by clients times days. At 50,000 clients over 365 days that is 18.25 million rows before the window sort. I would restrict it to the clients and date range in the report and partition output by day so downstream scans prune partitions.

Failure modes I would check

Skipping aggregation is the common bug. A window over raw events averages trades, not days, and the result moves with trade count. I would test that the CTE returns exactly one row per client_id, day.

NULL handling also bites. SUM ignores NULLs, so a day with only NULL revenue disappears from daily and looks like a zero day in the spine. Filtering revenue IS NOT NULL before aggregation makes that choice explicit, and I would reconcile SUM(daily_revenue) against the source total for the same period. A mismatch points to late or rejected events, not to the window.

Late arriving data is the operational risk. A trade booked two days late changes that day and the next two averages. If this feeds a daily table, I would recompute the rolling window for affected clients rather than patching a single row, and keep event time and booking time separate so restatements are auditable.

Performance wise, the window needs input sorted by client_id, day. Pre-aggregating means the sort runs over daily rows, usually one to two orders of magnitude smaller than raw events. If the source is partitioned by day, I would filter day before aggregation so the scan does not read history the report does not need.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20Explain SQL window functions and when to use ROW_NUMBER() versus DENSE_RANK() for ranked ticket analysis?

Reported in Stonex Group Data Engineer Interview Questions | Dataford

The 90-second answer

A window function computes a value across a set of rows related to the current row, without collapsing rows the way GROUP BY does. You define that set with PARTITION BY, the order inside it with ORDER BY, and the function decides what to return for each row. That makes them right for ranked ticket analysis: keep every ticket, but label it by its position inside its queue, team, or priority band.

ROW_NUMBER() and DENSE_RANK() differ only in how they treat ties, and that choice changes the result set.

ROW_NUMBER() gives 1, 2, 3, 4, 5 even when two tickets have the same score. One ticket wins the tie, the other does not, and the winner is arbitrary unless you add a deterministic tiebreaker. Use it when you need exactly N rows per partition, for example the top 3 open tickets per queue to assign to agents.

DENSE_RANK() gives 1, 1, 2, 2, 3 for the same data. Tied tickets share a rank and the next rank has no gap. Use it when ties are real and must all be included, for example every ticket at the highest priority level, or the top 2 distinct priority levels for an SLA report. You cannot promise how many rows DENSE_RANK() <= 2 returns.

SQL
-- PostgreSQL 15, checked against the documented syntax
WITH ranked AS (
  SELECT
    ticket_id,
    queue,
    priority_score,
    created_at,
    ROW_NUMBER() OVER (
      PARTITION BY queue
      ORDER BY priority_score DESC, created_at ASC, ticket_id ASC
    ) AS rn,
    DENSE_RANK() OVER (
      PARTITION BY queue
      ORDER BY priority_score DESC
    ) AS dense_rnk
  FROM tickets
  WHERE status = 'open'
    AND created_at >= CURRENT_DATE - INTERVAL '7 days'
)
SELECT ticket_id, queue, priority_score, rn, dense_rnk
FROM ranked
WHERE rn <= 3;  -- exactly 3 per queue, because rn is unique

The WHERE in the CTE runs before the window functions. The outer WHERE rn <= 3 runs after them, which is why you cannot filter on rn in the same query level that defines it.

Worked trace

One queue, five open tickets, ordered by priority_score DESC:

ticket_idpriority_scoreROW_NUMBER()RANK()DENSE_RANK()
T-10190111
T-10290211
T-10380332
T-10480432
T-10570553

RANK() is included because interviewers ask about it next. It shares ranks like DENSE_RANK() but leaves gaps, so after two tickets at rank 1 the next rank is 3. For "top 2 priority levels" that gap makes RANK() <= 2 return only the 90s, while DENSE_RANK() <= 2 returns the 90s and the 80s.

NeedFunctionWhy
---------
Top 3 tickets per queue for assignmentROW_NUMBER()Fixed count, one row per ticket
All tickets in the top 2 priority levelsDENSE_RANK()Ties included, levels counted, not rows
Count of tickets strictly ahead of this oneRANK()Gap reflects how many rows were tied ahead
Running total of tickets per queueCOUNT() OVER (PARTITION BY queue)Aggregate used as a window, no grouping

Failure modes I would name in the loop

Nondeterministic ties are the main one. ROW_NUMBER() OVER (ORDER BY priority_score DESC) alone can pick T-101 over T-102 on one run and the reverse on the next, after a reindex or a parallel plan change. The ticket that misses the top 3 cutoff then looks like a data bug. Adding created_at ASC, ticket_id ASC makes the order total and the result reproducible.

The second is capacity. DENSE_RANK() = 1 can return 1 ticket or 400 if a bulk import sets the same score. Code that assumes a fixed size, such as a fixed assignment batch, breaks. I would check the distribution first with SELECT priority_score, COUNT(*) FROM tickets GROUP BY 1 ORDER BY 1 DESC and decide whether the business rule is "top N tickets" or "top N levels".

Performance follows the sort. The window needs rows ordered inside each partition, so a large unfiltered tickets table will sort. Filtering by status and date before the window, as above, shrinks that input, and an index on (queue, priority_score DESC, created_at ASC) can serve the sort for the common query shape. On a table with tens of millions of rows I would measure that plan rather than assume the index is used, since the planner may still choose a hash or a parallel sort.

Rule of thumb I would state: if the cutoff is a count of tickets, use ROW_NUMBER(). If the cutoff is a count of distinct priority levels and ties must stay together, use DENSE_RANK().

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21How would you diagnose and optimize slow SQL queries on large datasets?

Reported in Stonex Group Data Engineer Interview Questions | Dataford

The 90-second answer

I start by reproducing the query in the same environment and getting a baseline, not by guessing an index. I run EXPLAIN (ANALYZE, BUFFERS) and look at four things in order: actual rows versus estimated rows, where time is spent, whether data is spilled or re-read, and whether the scan touches far more data than the result needs. A 10x estimate error usually points to stale statistics or skew. A sequential scan over a large table usually points to a missing predicate, a function on the indexed column, or a join that cannot use the distribution key. Only then do I change something, and I re-run the same plan to prove the change helped.

Assume a nightly aggregation over 2 TB of events, partitioned by day, that takes 14 minutes and returns 50k rows. The first plan often shows a full scan of 90 days because the date predicate is wrapped in a function, plus a hash join that spills to disk.

SQL
-- PostgreSQL 16, before: function defeats partition pruning
SELECT date_trunc('day', event_ts) AS day, customer_id, COUNT(*) AS events
FROM events
WHERE date_trunc('day', event_ts) BETWEEN DATE '2025-01-01' AND DATE '2025-01-07'
GROUP BY 1, 2;

-- after: sargable range, same semantics
SELECT date_trunc('day', event_ts) AS day, customer_id, COUNT(*) AS events
FROM events
WHERE event_ts >= TIMESTAMP '2025-01-01'
  AND event_ts <  TIMESTAMP '2025-01-08'
GROUP BY 1, 2;

The rewrite alone can cut scanned data from 2 TB to about 155 GB for 7 of 90 days. That is the arithmetic I check before touching indexes. If the scan is still large, I look at clustering or sort order, pre-aggregation, and join strategy.

Worked trace

StepEvidence from planDiagnosisFix triedResult (hypothetical, labelled as such)
1Seq Scan on events, Rows Removed by Filter: 98%Predicate not sargable, no pruningRewrite as range on event_tsScan drops to 7 partitions, 14 min to 90 s
2Hash Join, estimated 10k rows, actual 4.2M rowsStale stats, skew on customer_idANALYZE events; and check top customersEstimate within 20%, join stays in memory
3Sort spill: Disk: 18 GBGrouping 4.2M rows without orderCluster by (day, customer_id) or pre-aggregate by daySpill to 0, 90 s to 35 s
4p95 still 35 s at peakConcurrent queries contend for same partitionsMove to scheduled incremental load, keep ad hoc on a replicap95 35 s to 6 s for the dashboard query

How I choose the fix

SymptomLikely causeFix I try firstWhen I avoid it
------------
------------
------------
Seq scan, few rows returnedMissing or non-sargable predicateRewrite predicate, add partition pruningAdding an index when the table is append-only and scanned daily anyway
Nested loop with huge inner scansWrong join order or missing index on join keyForce or hint join order, index the inner sideIndexing a low-selectivity column that matches 40% of rows
Hash or sort spill to diskWorking set exceeds work_mem or memory limitPre-aggregate, cluster, increase memory for that job onlyRaising memory globally and starving other queries
Shuffle heavy in a distributed engineSkew on the join or group keySalt the hot key, filter hot keys separately, pre-aggregateSalting when skew is mild, since it adds a second aggregation
Plan flips after a loadStatistics stale or partition count changedANALYZE after load, cap partition countRebuilding indexes on every load if the load is hourly

Failure modes I watch for

An index can make a query slower on writes and can be ignored if selectivity is poor, so I check the plan after creating it rather than assuming it is used. Partitioning helps only when queries filter on the partition key. With 3,000 daily partitions and queries spanning a year, pruning saves little and metadata overhead grows. Pre-aggregation speeds a dashboard but goes stale if the incremental job fails, so I add a freshness check on the aggregated table and alert when the watermark lags more than one load cycle. In a distributed engine, a single hot customer_id can hold up a shuffle for minutes while other workers idle. I detect that from per-key row counts in the plan or shuffle metrics, not from total runtime alone.

I finish by recording the before and after plan, the data volume scanned, and p50 and p95 latency under production concurrency. A fix that wins on an empty warehouse and loses under load is not a fix.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22How would you find duplicates efficiently using self-joins?

Reported in Stonex Group Data Engineer Interview Questions | Dataford

The 90-second answer

I would start by asking what counts as a duplicate. Exact duplicates on a defined set of columns are a different problem from near duplicates on fuzzy fields. For exact duplicates, a self-join works, but I would only use it when I need the actual row pairs, for example to pick a survivor and merge the rest. If I only need counts, GROUP BY ... HAVING COUNT(*) > 1 is cheaper and clearer.

For the self-join, I join the table to itself on the duplicate key, require a.id < b.id so each pair appears once, and make sure NULLs compare as equal. Without that last step, rows with NULL in a key column silently disappear.

SQL
-- PostgreSQL 15+. Assumes a surrogate id and a business key.
SELECT a.id AS id_a, b.id AS id_b,
       a.email, a.created_at AS created_a, b.created_at AS created_b
FROM users a
JOIN users b
  ON b.email IS NOT DISTINCT FROM a.email
 AND b.id > a.id
WHERE a.email IS NOT NULL
ORDER BY a.email, a.id;

IS NOT DISTINCT FROM treats NULL as equal to NULL, which plain = does not. In dialects without it, such as older MySQL, I would write (a.email = b.email OR (a.email IS NULL AND b.email IS NULL)), or coalesce to a sentinel that cannot occur in real data. I would also normalise before joining, for example LOWER(TRIM(email)), because Alice@x.com and alice@x.com are duplicates in business terms but not byte for byte.

Why it is efficient, and when it is not

The join condition is an equality on the key, so the planner can use a hash join or a merge join instead of a nested loop over every pair. The index that matters is on the key itself, ideally covering: (email, id). With that index, finding pairs for one email is a lookup, not a scan.

The cost driver is group size. A group of k duplicate rows produces k * (k - 1) / 2 pairs. That is fine for k = 2 or 3, which is the common case, and it explodes for a bad key. If a missing email is stored as an empty string, 50,000 rows can share one key and the self-join tries to emit about 1.25 billion pairs. I guard against that by checking group sizes first.

SQL
SELECT email, COUNT(*) AS n
FROM users
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY n DESC
LIMIT 20;

If the largest group is huge, the key is wrong or the data needs cleaning before any pairwise join. That check also tells me whether the output will be manageable.

Worked trace

idemailcreated_at
1alice@example.com2024-01-03
2alice@example.com2024-01-05
3bob@example.com2024-01-04
4alice@example.com2024-02-01
5NULL2024-01-06
6NULL2024-01-07

The query above returns (1,2), (1,4) and (2,4) for Alice, and (5,6) for the NULL pair. Bob appears nowhere. Three rows in one group give three pairs, which matches 3 * 2 / 2. If I only needed to know Alice is duplicated, the GROUP BY version returns one row instead of three.

Choosing the tool

ApproachUse it whenWatch out for
Self-join on id <You need pairs to merge, compare fields, or pick a survivorPair explosion in large groups
GROUP BY ... HAVING COUNT(*) > 1You only need to count or list duplicate keysGives no survivor or merge target
ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at, id)You need one canonical row per group in a single passStill needs a second pass to delete or merge the rest

For a pipeline at Stone scale, I would usually run the GROUP BY check as a data quality gate, then use ROW_NUMBER() to flag the survivor, for example the earliest created_at, and merge the others into it. The self-join is the right answer when the interviewer wants pairs, and I would say that explicitly rather than reaching for it by default.

Failure modes I would name: NULL keys never matching under =, unnormalised case and whitespace splitting one logical duplicate into two groups, floating point columns compared with = when they should be rounded or compared with a tolerance, and a non-unique surrogate id breaking the a.id < b.id de-duplication. Each of those shows up as either missing pairs or a runaway pair count, and both are visible in the group size check before the join runs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23Design a real-time market data pipeline for low-latency, reliable ingestion?

Reported in Stonex Group Data Engineer Interview Questions | Dataford

The 90-second answer

I would ask which venues and which latency budget matter, because a consolidated tape for analytics and a feed for pricing have different designs. Assume three exchange venues over FIX or binary multicast, 120,000 messages per second at peak, and a target of under 50 ms from gateway receipt to a queryable topic, with no silent loss. I would put a thin, venue-specific gateway in front of a partitioned log, keep ordering and deduplication keys in the record, and make every downstream sink idempotent. The gateway does almost no business logic. It timestamps on arrival, validates sequence numbers, and writes raw bytes plus parsed fields. Heavy enrichment happens after the log, so a slow consumer never blocks ingestion.

Exchange feed: FIX / binary multicast Venue gateway: sequence check, arrival timestamp Kafka topic: partitioned by venue + symbol Stream processor: dedupe, gap fill, corrections Hot store: pricing / risk, low latency Cold store: Parquet in object storage Dead letter + gap log

Partitioning and ordering. Partition by venue + symbol so all ticks for one instrument land in order on one partition. That gives per-symbol ordering without a global lock. Global ordering across venues is not worth paying for, and it is not well defined anyway when clocks differ. Each record carries venue, symbol, venue_seq, venue_ts, arrival_ts, and a schema version. Use Avro or Protobuf with a registry, and keep the raw payload for replay. At 120,000 messages per second and roughly 180 bytes per message, ingestion is about 21.6 MB/s, or 1.9 TB per day before replication. With replication factor 3 and 24 hours of hot retention, budget roughly 5.6 TB of broker disk. That arithmetic decides partition count and retention before any tuning.

Reliable ingestion: sequence gaps. Exchanges number messages. A gap means loss, and loss must be visible, not smoothed over.

CaseDetectionAction
venue_seq = last + 1normal pathwrite to topic, advance checkpoint
venue_seq > last + 1gap of N messageswrite what arrived, emit gap event, request resend or snapshot from venue
venue_seq <= lastduplicate or replaydrop if payload hash matches, alert if it does not
venue sends a correctionsame trade id, new versionappend as a new record with is_correction = true, never mutate in place

The stream processor holds a short reorder buffer, for example 2 seconds or 5,000 messages per partition, to absorb out-of-order delivery inside a venue. Anything still missing after that window goes to the gap log and the affected symbol is flagged stale in the hot store. Stale is a state consumers can see. A missing tick presented as fresh is how pricing errors happen.

Idempotent consumption. At-least-once delivery from the log is the safe default. Exactly-once claims only hold inside one system, so I make sinks idempotent instead. The consumer commits only after the sink acknowledges, and the sink keys on a natural id.

Python
# Python 3.11, consumer checked against kafka-python 2.0.2 semantics
# Natural key: (venue, symbol, venue_seq). Store last_seq per partition in the sink.
for record in consumer:
    msg = parse(record.value)
    if msg.venue_seq <= store.last_seq(msg.venue, msg.symbol):
        continue  # replay after a rebalance, already applied
    store.apply(msg)  # upsert by natural key, single transaction
    store.set_last_seq(msg.venue, msg.symbol, msg.venue_seq)
    consumer.commit(record)  # offset moves only after apply succeeds

If the process dies between apply and commit, the record is redelivered and the last_seq check makes the second apply a no-op. That is the whole trick. Without it, a rebalance during a peak doubles ticks in the cold store and breaks volume calculations.

Failure modes I would name in the loop. Multicast loss on the gateway host, which shows up as sequence gaps clustered by venue and time. Clock skew between venue timestamps and arrival timestamps, which I track as two separate fields and alert on when the difference drifts beyond, say, 250 ms. Backpressure, where a slow enrichment job must lag in the log rather than push back on the gateway, so I size consumer groups for peak and alert on lag per partition, not on average. Schema changes from a venue, handled by the registry with backward-compatible evolution and a quarantine topic for records that fail validation. And a venue replaying a full day after an outage, which the dedupe check absorbs but which will spike lag, so the runbook says to scale consumers before replaying.

I would not put a general stream processor between the gateway and the log. Parsing and sequence checking in the gateway, everything else downstream, keeps the ingestion path short and keeps the latency budget measurable at each hop.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24Solve a DSA question on arrays?

Reported in StoneX Data Engineer Interview Experience & Questions

The 90-second answer

I would first pin down the constraints, because they decide the algorithm. For an array problem I ask: how large can the input be, is it sorted, can I mutate it, are duplicates allowed, and what should I return when there is no answer. Then I state a concrete version and solve that.

Take this version: given an unsorted list of integers and a target, return the indices of two different elements that sum to the target. Assume exactly one solution exists. I would not start with the hash map. I would start with the brute force, get it correct, then optimise.

Brute force checks every pair. That is O(n^2) time and O(1) extra space. For n = 10,000 that is about 50 million comparisons, which in Python is too slow for a live service. The observation that removes the inner loop is that for each value x, I only need to know whether target - x has already been seen. A hash map gives me that in O(1) average time.

Python
# Python 3.12
def two_sum(nums: list[int], target: int) -> list[int]:
    seen: dict[int, int] = {}  # value -> earliest index
    for i, x in enumerate(nums):
        need = target - x
        if need in seen:
            return [seen[need], i]
        if x not in seen:
            seen[x] = i
    return []

That is O(n) time and O(n) space. The space cost is the trade-off. If memory were tight and the array were sorted, I would use two pointers from both ends instead, which keeps O(1) space but requires sorted input and destroys the original indices unless I carry them along.

Worked trace

For nums = [3, 2, 4], target = 6:

Stepixneed = 6 - xseen before stepAction
1033{}store 3 -> 0
2124{3: 0}store 2 -> 1
3242{3: 0, 2: 1}need found, return [1, 2]

Checking seen before inserting the current element matters. With nums = [3, 3], target = 6, inserting first would let an element pair with itself. My order prevents that.

Alternatives and when they win

ApproachTimeExtra spaceNeeds sorted inputNotes
Brute force, all pairsO(n^2)O(1)NoSimplest to verify, fine for n under a few hundred
Hash map, one passO(n) averageO(n)NoBest default for unsorted input, worst case degrades if hashes collide
Two pointersO(n) after sortO(1) or O(n) for indicesYesSorting costs O(n log n), so only wins if input arrives sorted

Edge cases I would test before calling it done

Empty list and single element list return [] rather than raising. No solution returns [] instead of a partial pair, and I would confirm with the interviewer whether they prefer an exception there. Duplicate values keep the earliest index, which keeps the result deterministic. Negative numbers need no special handling because the arithmetic is the same, and I would say so rather than add a branch.

If the interviewer then changes the problem, for example asking for the maximum subarray sum or for all pairs, I would reuse the same pattern: state the new assumption, name the naive bound, then show the single-pass invariant. That is the habit they are actually assessing, not memorisation of one array trick.

Curated: · Written: · Reviewed:

Difficulty: Easy

Curated: · Written: · Reviewed: