Real Interview Questions for the Data Engineer at Stone
NewInterview Q&A
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.
| Principle | Guarantee | What breaks without it |
|---|---|---|
| Atomicity | All writes in the transaction commit, or none do | A debit posts and the matching credit does not, leaving a ledger out of balance |
| Consistency | A committed transaction moves the database from one valid state to another, respecting constraints | A foreign key or check constraint is violated and downstream jobs read orphaned rows |
| Isolation | Concurrent transactions behave as if they ran in some serial order, at the level you chose | Two concurrent updates overwrite each other, or a report reads a half-applied batch |
| Durability | Once committed, the result survives a crash | A 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.
-- 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 crashIf 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.
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.
| Step | Session A | Session B | Stored balance |
|---|---|---|---|
| 1 | Reads 1000 | 1000 | |
| 2 | Reads 1000 | 1000 | |
| 3 | Writes 900 (1000 - 100) | 900 | |
| 4 | Writes 950 (1000 - 50) | 950 | |
| 5 | Commits | Commits | 950 |
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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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-level | Table-level | |
|---|---|---|
| Granularity | One or more rows, plus index entries | Whole table |
| Typical trigger | UPDATE, DELETE, SELECT FOR UPDATE | TRUNCATE, ALTER TABLE, LOCK TABLE, bulk load |
| Concurrent writers to different rows | Allowed | Blocked if modes conflict |
| Concurrent writers to same row | Serialised, second waits | Blocked |
| Readers during write | Allowed in Postgres MVCC, they see the old version | Blocked by ACCESS EXCLUSIVE, allowed by ACCESS SHARE |
| Main failure mode | Deadlocks, lock wait timeouts | Throughput 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.
-- 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
| Time | Txn A | Txn B | Result |
|---|---|---|---|
| t0 | UPDATE accounts SET balance = balance - 100 WHERE id = 42 | A holds row lock on 42 | |
| t1 | UPDATE accounts SET balance = balance + 50 WHERE id = 42 | B blocks on row 42 | |
| t2 | COMMIT | Lock released, A balance is 900 from 1000 | |
| t3 | B proceeds, reads 900, writes 950 | No 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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:
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:
| symbol | venue | notional | trade_id |
|---|---|---|---|
| AAPL | XNAS | 100 | t1 |
| AAPL | XNAS | 250 | t2 |
| AAPL | XNYS | 75 | t3 |
| MSFT | XNAS | 400 | t4 |
| symbol | venue | total_notional | fills |
|---|---|---|---|
| AAPL | XNAS | 350 | 2 |
| AAPL | XNYS | 75 | 1 |
| MSFT | XNAS | 400 | 1 |
The same thing in plain Python, with no dependency, is a dict keyed by a tuple:
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
| Engine | When I use it | Limit to watch |
|---|---|---|
| pandas | Up to a few GB in memory, ad hoc or daily batch | Loads the whole frame into RAM, single threaded for many ops |
| Polars | Same shape as pandas, larger files, want lazy execution | Newer API, some pandas idioms do not transfer |
| DuckDB | Aggregating Parquet or CSV on disk without a cluster | Still single node, so very large shuffles are slow |
| PySpark | Data across many nodes, or a shuffle that will not fit on one machine | Cluster 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
What each gate actually checks
| Stage | Gate | Fails when |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| Test | pytest plus schema tests on every input table | a column is renamed, a type widens, or null rate on a key field crosses 1 percent |
| Build | image and model stored by SHA, data snapshot ID recorded | build is not reproducible from the lockfile and snapshot |
| Eval | golden set of 2,000 labelled cases, frozen for the release | accuracy drops more than 2 points, or any regulated slice drops more than 5 points |
| Shadow | run new and old side by side for 24 hours on live traffic | disagreement rate exceeds the agreed threshold or p95 latency rises above 300 ms |
| Canary | 5 percent of traffic for 4 hours, auto rollback on error budget | 5xx 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:
# 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
| Join | Matching rule | Rows kept | Typical use |
|---|---|---|---|
INNER JOIN | ON a.id = b.id | Matches only | Linking orders to customers where both exist |
LEFT JOIN | ON a.id = b.id | All of left, nulls for unmatched right | Keeping every customer, flagging those with no orders |
RIGHT JOIN / FULL JOIN | ON ... | All of right / both sides | Reconciliation checks, rare in fact tables |
CROSS JOIN | None | Every left row paired with every right row | Date spines, parameter grids, small lookup expansion |
NATURAL JOIN | Implicit ON all shared column names | Depends on inferred condition | Ad hoc exploration only, avoid in production SQL |
SELF JOIN | ON a.id = b.manager_id | Matches within one table | Hierarchies, lag comparisons on the same table |
Worked trace
Suppose customers has 3 rows and orders has 4:
| customers.id | customers.name | orders.id | orders.customer_id | orders.amount |
|---|---|---|---|---|
| 1 | Ana | 101 | 1 | 50 |
| 2 | Ben | 102 | 1 | 75 |
| 3 | Cy | 103 | 2 | 20 |
| 104 | 99 | 10 |
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
-- 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:
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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
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
| Input | Step | Output |
|---|---|---|
"Equities, fx ,EQUITIES,,bonds" | csv split | ["Equities", " fx ", "EQUITIES", "", "bonds"] |
| same | strip, lower, drop empty | ["equities", "fx", "equities", "bonds"] |
| same | dedupe, keep first occurrence | ["equities", "fx", "bonds"] |
None or " " | early return | [] |
'"a,b",c' | csv split respects quotes | ["a,b", "c"] |
Choosing the split method
| Method | Handles quoted delimiter | Handles regex / whitespace runs | Cost |
|---|---|---|---|
str.split(",") | No | No | Fastest, fails on quoted commas |
csv.reader | Yes | No | Slightly slower, correct for CSV-sourced fields |
re.split(r"[,;\\s]+", s) | No | Yes | Good for messy free text, harder to read |
json.loads | Yes, if field is JSON | No | Only 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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 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:
| i | row |
|---|---|
| 0 | 1 2 3 4 |
| 1 | 5 6 7 8 |
| 2 | 9 10 11 12 |
| 3 | 13 14 15 16 |
| i | main a[i][i] | anti a[i][3-i] |
|---|---|---|
| 0 | 1 | 4 |
| 1 | 6 | 7 |
| 2 | 11 | 10 |
| 3 | 16 | 13 |
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
| Case | Behaviour |
|---|---|
| --- | --- |
| Empty matrix or empty first row | Return empty lists, do not index matrix[0] blindly |
Rectangular m x n, m != n | Main 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 pipeline | Raise on the shape check above instead of producing a silent IndexError halfway through |
| Very large matrix held in memory | One 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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 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
| Step | Left half | Right half | Merge 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
| Algorithm | Time | Extra space | Stable | Use it when |
|---|---|---|---|---|
| Merge Sort | O(n log n) always | O(n) | Yes | Worst case guarantee, linked lists, external data |
| Quick Sort | O(n log n) average, O(n^2) worst | O(log n) stack | No | In-memory arrays, memory tight, pivot chosen well |
Python sorted() (Timsort) | O(n log n) worst, near O(n) on runs | O(n) worst | Yes | Default 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
-- 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 | = NULL | NOT IN (101, NULL) | Kept by WHERE? |
|---|---|---|---|---|
| 100 | FALSE | UNKNOWN | UNKNOWN | No |
| 101 | TRUE | UNKNOWN | FALSE | No |
| 102 | FALSE | UNKNOWN | UNKNOWN | No |
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.
| Expression | Rows: 10, 20, NULL | All rows NULL |
|---|---|---|
COUNT(*) | 3 | 3 |
COUNT(amount) | 2 | 0 |
SUM(amount) | 30 | NULL |
COALESCE(SUM(amount), 0) | 30 | 0 |
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
| Need | Tool | When it fits |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| Filter missing values | IS NULL, IS NOT NULL | Always. This is the only correct equality test. |
| Display or downstream default | COALESCE(col, 0) | Only when the default is a real business value. |
| Turn a sentinel into NULL | NULLIF(col, '') | Cleaning empty strings from a CSV or API feed. |
| Keep rows despite missing match | LEFT JOIN | Anti-joins and optional enrichment. |
| Count distinct non-null values | COUNT(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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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
-- 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
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:
| ts | price | LAG(price) | price_change | gap_seconds |
|---|---|---|---|---|
| 09:30:00 | 101.20 | NULL | NULL | NULL |
| 09:30:05 | 101.35 | 101.20 | 0.15 | 5 |
| 09:30:06 | 101.10 | 101.35 | -0.25 | 1 |
| 09:45:00 | 102.00 | 101.10 | 0.90 | 894 |
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
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.
| Approach | Keeps detail rows | Cost / limit |
|---|---|---|
GROUP BY + aggregate | No, one row per group | Cheapest for pure aggregates |
| Window function | Yes | Sorts or hashes per partition; watch skew |
Self join on LAG logic | Yes | Often 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
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 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
| Scenario | Detection | Handling |
|---|---|---|
| Exchange adds a field or reorders columns | Parser validation fails, dead letter topic grows | Raw payload preserved, parser updated, replay from bronze |
| Late correction after aggregates published | Reconciliation job compares silver versions to aggregates | Aggregates recomputed for affected windows, versioned output |
| Kafka broker loss during peak | Consumer lag and ISR shrink alerts | Partitions rebalance, no data loss because producers used acks=all |
| Duplicate sequence from a reconnect | Drop count metric spikes | Exact 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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
| Layer | Chosen | Alternative considered | Deciding factor |
|---|---|---|---|
| Ingestion | Kafka, 7 day retention, 12 partitions per topic | Kinesis, managed Kafka | Replay and schema registry control; we needed to reprocess 7 days without source cooperation |
| Stream processing | Spark Structured Streaming, 5 minute micro batches | Flink, Kafka Streams | Team already on Spark; 5 minute latency met reporting SLA; Flink would have meant a second runtime to operate |
| Orchestration | Airflow 2.9, Kubernetes executor | Dagster, Prefect | Existing Airflow estate, mature backfill and sensor patterns, hiring pool |
| Transformation | dbt Core on Snowflake | Spark SQL jobs, hand written SQL in Airflow | Reviewable 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:
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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
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:
| Check | Result | What it tells me |
|---|---|---|
| Source file row count for 02:00 hour | 198,000 rows, matches upstream manifest | Source file is complete, not truncated or late |
| Staged count before dedupe | 197,400 rows | Load step is not dropping rows |
| Staged count after dedupe | 121,000 rows | Dedupe step is removing about 76,000 rows, evidence for a key collision |
| Rerun of 02:00 slice, old code | 197,100 rows published | Old code handles this input correctly, which implicates the new code change |
| Rerun of 02:00 slice, new code | 121,000 rows published | Same 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 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
| Approach | Runtime | Freshness | Reconciliation breaks in 5 days |
|---|---|---|---|
| Full refresh | 3 h 40 min median | 06:00 cut missed twice | 0 |
| Incremental, current watermark | 12 min median | 15 min | 4 days drifted |
| Incremental plus late-event pass | 14 min median | 15 min, late events by 02:00 | 0 |
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.
-- 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 - 2We 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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 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 classfrozen=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.
| Concept | Question it answers | In the pipeline example | Cost when misused |
|---|---|---|---|
| Encapsulation | How is state protected? | Private _schema, validated constructor, frozen config | Public mutable fields let any module corrupt a run mid-flight |
| Abstraction | What can callers rely on? | Source.read() signature, no parser details leak out | Interface too wide, callers depend on CSV specifics |
| Inheritance | What code is reused by extension? | FileSource adds retry and checkpoint logic to both readers | Deep hierarchies couple every subclass to base class changes |
| Polymorphism | Can implementations be swapped? | load(CsvSource(...)) and load(ParquetSource(...)) use one code path | Hidden 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
| Language | Where I use it | Why it fits | Where it hurts |
|---|---|---|---|
| Python 3.12 | Airflow DAGs, ingestion, validation, PySpark driver code | Fast to change, huge libraries, easy to review in a pull request | GIL limits thread parallelism, pandas can blow memory on large frames |
| SQL (Postgres and Spark SQL) | Warehouse models, incremental transforms, reconciliation | Declarative, optimizer handles joins and pruning, portable logic | Dialect differences, weak control flow, hard to unit test without a database |
| Scala 2.13 | Spark jobs with custom shuffles or complex UDFs | Runs on the JVM, typed, close to Spark internals | Slow 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 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.
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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
| Decision | Options considered | Chose | Trade-off accepted |
|---|---|---|---|
| Ingestion | Nightly batch, Kafka streaming, direct API writes | Kafka streaming into Parquet on object storage | Operational cost of a broker for lower latency, about 90 seconds end to end instead of next morning |
| Deduplication | Database unique key, producer event ID check in stream | Producer event ID, checked in the consumer | Duplicates dropped before the warehouse, but a buggy producer reusing IDs would lose events, so IDs are UUIDv4 generated at the edge |
| Storage layout | One table, partition by merchant only, partition by date and merchant | Partition by event date, then merchant | Date partitions keep daily reconciliation cheap, merchant partitions keep per-merchant backfills from scanning the full day |
| Schema change | Reject unknown fields, allow them, version every change | Allow additive fields, reject type changes | Additive fields flow through without a deploy, type changes fail the job loudly instead of silently corrupting amounts |
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 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
-- 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:
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.
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):
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:
| Plan | Rows scanned | Heap fetches | Time | Output rows |
|---|---|---|---|---|
| Original: Seq Scan on payments, join, filter | 48,000,000 | 48,000,000 | 12,400 ms | 310,000 |
| Rewrite, no new index: Index Scan on paid_at | 1,900,000 | 1,900,000 | 2,100 ms | 310,000 |
| Rewrite + partial covering index: Index Only Scan | 1,900,000 | 0 | 380 ms | 310,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
| Approach | When it wins | Cost |
|---|---|---|
| Partial covering index, as above | Query shape is stable and freshness must be immediate | Write amplification on every completed payment, index size roughly the completed subset |
| Pre-aggregate into a monthly summary table | Same rollup runs many times a day | Staleness between refreshes, needs a backfill and late-arriving payment handling |
Partition payments by month on paid_at | Table is far larger than one year and old partitions are rarely touched | Partition 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
-- 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.
| Day | Daily revenue | ROWS average | RANGE average |
|---|---|---|---|
| Mon | 100 | 100.00 | 100.00 |
| Wed | 300 | 200.00 | 200.00 |
| Thu | 200 | 200.00 | 250.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:
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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
-- 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 uniqueThe 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_id | priority_score | ROW_NUMBER() | RANK() | DENSE_RANK() |
|---|---|---|---|---|
| T-101 | 90 | 1 | 1 | 1 |
| T-102 | 90 | 2 | 1 | 1 |
| T-103 | 80 | 3 | 3 | 2 |
| T-104 | 80 | 4 | 3 | 2 |
| T-105 | 70 | 5 | 5 | 3 |
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.
| Need | Function | Why |
|---|---|---|
| --- | --- | --- |
| Top 3 tickets per queue for assignment | ROW_NUMBER() | Fixed count, one row per ticket |
| All tickets in the top 2 priority levels | DENSE_RANK() | Ties included, levels counted, not rows |
| Count of tickets strictly ahead of this one | RANK() | Gap reflects how many rows were tied ahead |
| Running total of tickets per queue | COUNT() 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
-- 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
| Step | Evidence from plan | Diagnosis | Fix tried | Result (hypothetical, labelled as such) |
|---|---|---|---|---|
| 1 | Seq Scan on events, Rows Removed by Filter: 98% | Predicate not sargable, no pruning | Rewrite as range on event_ts | Scan drops to 7 partitions, 14 min to 90 s |
| 2 | Hash Join, estimated 10k rows, actual 4.2M rows | Stale stats, skew on customer_id | ANALYZE events; and check top customers | Estimate within 20%, join stays in memory |
| 3 | Sort spill: Disk: 18 GB | Grouping 4.2M rows without order | Cluster by (day, customer_id) or pre-aggregate by day | Spill to 0, 90 s to 35 s |
| 4 | p95 still 35 s at peak | Concurrent queries contend for same partitions | Move to scheduled incremental load, keep ad hoc on a replica | p95 35 s to 6 s for the dashboard query |
How I choose the fix
| Symptom | Likely cause | Fix I try first | When I avoid it |
|---|---|---|---|
| --- | --- | --- | --- |
| --- | --- | --- | --- |
| --- | --- | --- | --- |
| Seq scan, few rows returned | Missing or non-sargable predicate | Rewrite predicate, add partition pruning | Adding an index when the table is append-only and scanned daily anyway |
| Nested loop with huge inner scans | Wrong join order or missing index on join key | Force or hint join order, index the inner side | Indexing a low-selectivity column that matches 40% of rows |
| Hash or sort spill to disk | Working set exceeds work_mem or memory limit | Pre-aggregate, cluster, increase memory for that job only | Raising memory globally and starving other queries |
| Shuffle heavy in a distributed engine | Skew on the join or group key | Salt the hot key, filter hot keys separately, pre-aggregate | Salting when skew is mild, since it adds a second aggregation |
| Plan flips after a load | Statistics stale or partition count changed | ANALYZE after load, cap partition count | Rebuilding 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
-- 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.
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
| id | created_at | |
|---|---|---|
| 1 | alice@example.com | 2024-01-03 |
| 2 | alice@example.com | 2024-01-05 |
| 3 | bob@example.com | 2024-01-04 |
| 4 | alice@example.com | 2024-02-01 |
| 5 | NULL | 2024-01-06 |
| 6 | NULL | 2024-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
| Approach | Use it when | Watch out for |
|---|---|---|
Self-join on id < | You need pairs to merge, compare fields, or pick a survivor | Pair explosion in large groups |
GROUP BY ... HAVING COUNT(*) > 1 | You only need to count or list duplicate keys | Gives 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 pass | Still 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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.
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.
| Case | Detection | Action |
|---|---|---|
venue_seq = last + 1 | normal path | write to topic, advance checkpoint |
venue_seq > last + 1 | gap of N messages | write what arrived, emit gap event, request resend or snapshot from venue |
venue_seq <= last | duplicate or replay | drop if payload hash matches, alert if it does not |
| venue sends a correction | same trade id, new version | append 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 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 succeedsIf 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
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 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:
| Step | i | x | need = 6 - x | seen before step | Action |
|---|---|---|---|---|---|
| 1 | 0 | 3 | 3 | {} | store 3 -> 0 |
| 2 | 1 | 2 | 4 | {3: 0} | store 2 -> 1 |
| 3 | 2 | 4 | 2 | {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
| Approach | Time | Extra space | Needs sorted input | Notes |
|---|---|---|---|---|
| Brute force, all pairs | O(n^2) | O(1) | No | Simplest to verify, fine for n under a few hundred |
| Hash map, one pass | O(n) average | O(n) | No | Best default for unsorted input, worst case degrades if hashes collide |
| Two pointers | O(n) after sort | O(1) or O(n) for indices | Yes | Sorting 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:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: