Real Interview Questions for the Data Engineer at Walmart Global Tech
NewInterview Q&A
Q&A-1Write a query to find employees with salaries greater than the average salary in their respective departments.
Reported in Walmart Global Tech Data Engineer Interview Questions ...
The 60-second answer
I'd compute each department's average in the same pass as the rows, using a window function, then filter. Window functions can't appear in WHERE, so the average goes in a CTE and the filter sits in the outer query. I'd exclude rows with a NULL department_id first, because PARTITION BY groups NULLs together and would produce a meaningless average.
WITH dept_pay AS (
SELECT employee_id,
department_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS dept_avg_salary
FROM employees
WHERE department_id IS NOT NULL
)
SELECT employee_id, department_id, salary, dept_avg_salary
FROM dept_pay
WHERE salary > dept_avg_salary;Why it works. AVG ignores NULL salaries. A NULL salary makes salary > dept_avg_salary unknown, so that row drops out without an explicit check. The window has no ORDER BY, so the frame is the whole partition and every row in a department sees the same average.
Trace (hypothetical data).
| employee_id | department_id | salary | dept avg | kept? |
|---|---|---|---|---|
| 1 | 10 | 50 | 70 | no |
| 2 | 10 | 70 | 70 | no (not strictly greater) |
| 3 | 10 | 90 | 70 | yes |
| 4 | 20 | 60 | 60 | no |
| 5 | 20 | 60 | 60 | no |
| 6 | 20 | NULL | 60 | no (unknown) |
Row 2 is the boundary case the interviewer may probe: equal to the average is not greater than it.
Alternative: aggregate and join.
SELECT e.employee_id, e.department_id, e.salary, d.avg_salary
FROM employees e
JOIN (SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id) d
ON d.department_id = e.department_id
WHERE e.salary > d.avg_salary;The join version is equally correct and runs on engines without window functions. The correlated subquery WHERE salary > (SELECT AVG(salary) FROM employees x WHERE x.department_id = e.department_id) also works, but most optimizers handle it as a per-row lookup unless they decorrelate it, so I'd avoid it at scale.
What changes at Walmart scale. The window version scans the table once and shuffles by department_id. The cost to watch is skew: a few very large departments make a few reducers or executors do most of the work. I'd check the partition size distribution first, and if one department dominates, pre-aggregate averages into a small table and join to it. For a daily batch, I'd also confirm the salary column's type (a decimal, not a float) so the average does not drift under rounding, and that the department key is the same one the rest of the pipeline uses.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Walk me through how you would split a string column in a SQL table and generate one output row per character.
Reported in Walmart Global Tech Data Engineer Interview Questions ...
The 90-second answer
I'd use a set-based expansion, not a loop or a UDF. Each input row produces length(val) output rows, and each output row carries a 1-based position so the order is explicit. I'd state three assumptions first. The column is a text type with ordinary collation. NULL and empty strings produce zero rows, not a row holding a NULL character. "Character" means a Unicode code point, which is what length() counts in Postgres and Spark. Grapheme clusters such as emoji with skin-tone modifiers will split into several rows, and I'd flag that to the product owner rather than silently fixing it.
The portable form is a recursive CTE. This is the Postgres version, checked against Postgres 16:
WITH RECURSIVE walk (id, val, pos) AS (
SELECT id, val, 1
FROM src
WHERE val IS NOT NULL AND val <> ''
UNION ALL
SELECT id, val, pos + 1
FROM walk
WHERE pos < length(val)
)
SELECT id, pos, substr(val, pos, 1) AS ch
FROM walk
ORDER BY id, pos;Trace on src = {(7, 'abc'), (8, ''), (9, NULL)}:
| anchor row | pos | recursion | output |
|---|---|---|---|
| (7,'abc') | 1 | 1 < 3, emit pos 2 | (7,1,'a') |
| (7,'abc') | 2 | 2 < 3, emit pos 3 | (7,2,'b') |
| (7,'abc') | 3 | 3 < 3 false, stop | (7,3,'c') |
| (8,'') | filtered | none | nothing |
| (9,NULL) | filtered | none | nothing |
The filter sits in the anchor on purpose. If it were only in the recursive term, an empty string would still emit a row at pos 1 with an empty character.
SQL Server needs LEN for length, SUBSTRING for substr, and OPTION (MAXRECURSION 0) if a value can exceed 100 characters, because its recursion limit defaults to 100. Postgres does not impose a comparable default cap on recursive CTEs, so a long value is a performance question there, not a hard failure.
Spark SQL is shorter because it has a set-returning generator. This version uses explode, not posexplode, and the position is the value from sequence, so it is already 1-based:
SELECT s.id, p.pos, substring(s.val, p.pos, 1) AS ch
FROM src s
LATERAL VIEW explode(sequence(1, length(s.val))) p AS pos
WHERE length(s.val) > 0;The WHERE is required. sequence(1, 0) returns a descending array, so an empty string would otherwise emit positions 1 and 0. A NULL input gives a NULL array, which explode drops, so the guard is only needed for the empty case. I'd avoid split(val, '') as the mechanism, because relying on an empty-pattern split is fragile and harder for the next reader to trust.
Cost. Output size is the sum of lengths. A 1 million row table with 12-character average values emits 12 million rows, and a 500-character free-text column emits 500 rows per source row. Check the total with SELECT sum(length(val)) FROM src before running it, and write to a table partitioned by source id rather than one unpartitioned insert. One long value can skew a single executor or worker, so check the maximum length(val) as well as the mean.
Failure modes to name:
- Consumers that rely on physical row order. Neither engine guarantees it without an explicit
ORDER BY, soposmust travel with the row. - Byte-based functions.
substringover bytes, orLENGTHB, splits multi-byte UTF-8 characters into invalid fragments. Use character functions only. - Silent NULL output from a missing guard. Spot it with a row count that disagrees with
sum(length(val)).
I'd end by asking whether consumers need characters or code points, because that decides whether the grapheme caveat is a bug or a documented limitation.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Write a function to group an array of strings into anagrams.
Reported in Walmart Global Tech Data Engineer Interview Questions ...
The 90-second answer
I'd clarify three things first: is the comparison case-sensitive, is whitespace significant, and can the input contain non-ASCII text. I'll assume case-sensitive, no trimming, and arbitrary Unicode, which means the key has to be built from characters rather than from a fixed 26-letter alphabet. Two strings are anagrams exactly when their sorted characters match, so that sorted form is the grouping key. A dictionary from key to list does the rest in one pass.
# Python 3.12
from collections import defaultdict
def group_anagrams(words: list[str]) -> list[list[str]]:
groups: defaultdict[tuple[str, ...], list[str]] = defaultdict(list)
for w in words:
groups[tuple(sorted(w))].append(w)
return list(groups.values())I use a tuple rather than a joined string so that no separator can collide with a character in the input. Dict insertion order (guaranteed since Python 3.7) means groups come back in order of first appearance, which makes the output deterministic and easy to assert in a test.
Trace. Input ["eat", "tea", "tan", "ate", "nat", "bat"]:
| word | sorted key | groups after insert |
|---|---|---|
| eat | a,e,t | {aet: [eat]} |
| tea | a,e,t | {aet: [eat, tea]} |
| tan | a,n,t | {aet: [eat, tea], ant: [tan]} |
| ate | a,e,t | {aet: [eat, tea, ate], ant: [tan]} |
| nat | a,n,t | {aet: [eat, tea, ate], ant: [tan, nat]} |
| bat | a,b,t | adds abt: [bat] |
Result: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]].
Complexity. With n strings of average length k, sorting each key costs O(k log k), so the total is O(n · k log k) time and O(n · k) space for the keys and output. If the input is known to be lowercase a–z and long strings dominate, a count-vector key (a 26-tuple of letter counts) brings each key to O(k) and the total to O(n · k). For short words, the sort is fast in practice and clearer, so I'd only switch after profiling.
Failure modes I'd check for:
- Mutation: the function never edits the input list, so the caller's data is safe.
- Unicode:
éwritten as one code point and aseplus a combining accent sorts differently. Normalise withunicodedata.normalize("NFC", w)before keying if the source mixes forms. Noneor non-string entries raise aTypeErrorinsidesorted. I'd filter or reject them at the boundary, not inside the grouping loop.- Empty strings form their own group
(), which is correct, since""is only an anagram of"".
At Walmart scale. If the array is really a column of billions of rows, the same idea becomes a group-by on a canonical key. In Spark I'd compute the key with array_sort(split(lower(word), '')) and concat_ws, then groupBy that key and collect_list the words. The shuffle is hash-partitioned on the key, so the work parallelises cleanly, but a skewed key (one very common letter multiset) can overload a single partition, so I'd check key frequency before running it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4What are the steps of creating the database, physical, conceptual, logical schema, partitioning/indexing?
Reported in Database Creation Steps
The 90-second answer
I'd work top-down in four passes and keep them separate, so the business vocabulary is agreed before anyone picks engine types. Assumptions first: a retail sales workload of about 2 billion transaction lines a year, queries mostly filtered by store, item and day, and daily batch loads.
-
Conceptual model. Entities and relationships only, in business terms: Store, Item, Customer, Transaction, Transaction line, Return. No types, no keys. The output is shared vocabulary and a stated grain: one row per transaction line.
-
Logical model. Add attributes, primary keys, foreign keys and business rules, still engine-neutral. Normalise the transactional side to 3NF so each fact is stored once. For the analytic side, pick a star schema:
fact_sales_linewith conformed dimensionsdim_store,dim_item,dim_date. Decide slowly changing dimension handling here: Type 2 for store format changes, Type 1 for corrected typos. -
Physical model. Bind to the engine. Choose types (
DECIMAL(12,2)for money, never FLOAT), file format, compression, clustering keys and the partition column. Volume check: 2e9 rows × about 120 bytes per row is roughly 240 GB raw per year before compression, so partition layout matters from day one. -
Partitioning and indexing. Partition on a column that appears in most filters and has bounded cardinality. Date is the usual answer and the right one here:
CREATE TABLE fact_sales_line (
txn_date DATE,
store_id INT,
item_id BIGINT,
qty INT,
amount DECIMAL(12,2)
)
PARTITIONED BY (txn_date);Daily partitions give 365 × 5 = 1,825 partitions over five years, which most engines handle comfortably. Partitioning by store_id gives about 5,000 partitions with uneven sizes, and any query across all stores scans every one. Avoid high-cardinality columns such as customer_id: thousands of tiny files per partition is the small-files failure.
Indexing differs by engine. In a columnar warehouse I rely on partition pruning, file-level min/max statistics and clustering on (store_id, item_id) rather than B-tree indexes. In an OLTP source feeding the pipeline I index the foreign keys and the change-tracking column, knowing every index adds write cost on each insert.
Failure modes and how I'd detect them
- Skew: one store holds 40% of rows, so one task runs about 10× longer. Spot it in the per-task time distribution.
- Small files: a daily load writes 2,000 files of 100 KB. Spot it from file count per partition. Compact toward 256 MB to 1 GB.
- Late data: a partition is rewritten after downstream reads. Spot it by comparing row counts across reruns.
- Wrong grain: order totals sit beside line items and a sum double counts. Catch it by reconciling against source control totals.
Trade-off. A star schema costs joins and a rebuild if the grain changes. A wide denormalised table is faster for one dashboard and expensive for everything else. I keep the star and add a pre-aggregated table only when a measured query misses its SLA.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Walk me through how you would solve two array and string coding questions in a 60-minute window, with clean code and edge cases.
Reported in Walmart DE3 onsite, did not get it but learned a lot
The first five minutes
Before touching the keyboard I restate each problem, ask about input bounds (length, value range, whether values can be negative, whether the string is ASCII or Unicode) and agree on the return value for empty input. Then I pick the approach and say its complexity out loud. Two problems in 60 minutes means roughly 20 minutes each, with 10 left for review, so I stop designing once I have a correct O(n) plan.
Problem 1: longest subarray with sum at most K
Given non-negative integers and a limit K, return the length of the longest contiguous subarray whose sum is at most K. Non-negativity is the assumption that makes a sliding window valid: shrinking from the left can only lower the sum, so the left edge never has to move backwards.
def longest_at_most_k(nums, k):
left = 0
total = 0
best = 0
for right, x in enumerate(nums):
total += x
while total > k:
total -= nums[left]
left += 1
best = max(best, right - left + 1)
return bestTrace with nums=[2,1,3,1,1], k=5: right=0 gives total 2, best 1. right=1 gives total 3, best 2. right=2 gives total 6, so left moves to 1 and total is 4, best stays 2. right=3 gives total 5, window [1,3,1], best 3. right=4 gives total 6, left moves to 2, total 5, window length 3. Answer 3.
Edge cases I check aloud: empty list returns 0; an element larger than K empties the window and the loop still returns a correct 0 for that position; all zeros returns n. Complexity is O(n) time, O(1) extra space, since each index enters and leaves the window once.
If the interviewer allows negatives, the window breaks. I would say so and propose prefix sums with a sorted structure, O(n log n), instead of pretending the window still works.
Problem 2: run-length encoding
Encode aaabcc as a3b1c2. Clarify whether the output must be shorter than the input and whether it should fall back to the original string when it is not. I would ask that, because it changes the code path.
def rle(s):
out = []
i = 0
n = len(s)
while i < n:
j = i
while j < n and s[j] == s[i]:
j += 1
out.append(f"{s[i]}{j - i}")
i = j
return "".join(out)Edge cases: empty string returns ""; a single character returns c1; a run longer than 9 is still written as a full decimal count, such as a12. Decoding is ambiguous when the input contains digits, because a11 could be one run or two, so I flag that rather than pretend the encoding round-trips. Complexity is O(n) time, with the output list as the only extra space.
Last ten minutes
I re-read each function looking for off-by-one errors in the window bounds and the run-end index, run my traces again, and name the one edge case I did not test. Saying that last part tends to matter more to the interviewer than a perfect solution.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6How does Spark actually work under the hood, and when would you use a given optimization technique?
Reported in Walmart DE3 onsite, did not get it but learned a lot
The 90-second answer
Spark turns your code into a DAG of operations, and the DAG is cut into stages at every shuffle. Narrow transformations (filter, select, map) run per partition with no data movement. Wide transformations (groupBy, join, distinct, orderBy) need every row with the same key on the same executor, so Spark writes shuffle files to local disk, and the next stage reads them over the network. Almost every performance problem I have seen in a Walmart-scale pipeline is a shuffle that moved more data than it needed to, or a partition that held far more data than its peers.
For DataFrame and SQL code, Catalyst rewrites the logical plan (predicate pushdown, column pruning, constant folding, join reordering) before Tungsten generates code for execution. That is why I write DataFrame or SQL rather than RDD code: the optimizer can only see what I express declaratively. Python UDFs break that visibility and pay a serialization cost per row, so I use built-in functions first.
Then I pick the technique by what the plan is doing wrong. I check the Spark UI, not my intuition.
| Symptom in Spark UI | Likely cause | Technique |
|---|---|---|
| One join task runs 20x longer than the median | Skewed key | AQE skew join, or salt the key |
| Small dimension table causes a sort-merge join with a big shuffle | Broadcast threshold not met | Broadcast hint, or raise spark.sql.autoBroadcastJoinThreshold |
| Thousands of tiny output files | Too many partitions on write | coalesce or repartition before write |
| Same DataFrame recomputed in three branches | No reuse | persist with a storage level |
| Scan reads every column of a wide table | No pruning | Select columns early, use Parquet or Delta |
Worked trace (hypothetical figures). A job joins orders (2 TB, 400 partitions after read) to stores (40 MB). The default autoBroadcastJoinThreshold is 10 MB, so Spark plans a sort-merge join and shuffles about 2 TB across spark.sql.shuffle.partitions, which defaults to 200. The fix is orders.join(broadcast(stores), "store_id"). The 40 MB table ships once to each executor and the orders side is never shuffled. Check the plan with explain("formatted") and confirm a BroadcastHashJoin node appears.
Where I would not use the technique. Broadcasting a table that is 2 GB on the driver and executors will fail with OOM or a broadcast timeout, so only broadcast what fits comfortably in executor memory. Caching a DataFrame used once adds a write and an eviction risk for no gain. Salting a key adds a second aggregation step and doubles the work for that key, so it only pays off when skew is real.
Failure modes to name. AQE, which has been on by default since Spark 3.2 (spark.sql.adaptive.enabled), can coalesce partitions and split skewed ones at runtime, but it cannot fix a skewed key on the non-shuffled side of a broadcast or a UDF that is itself slow. Driver-side collect() on a large result looks like a Spark slowdown but is a single-node bottleneck. Spill to disk shows as high Spill (memory) and Spill (disk) on a stage; that points to too few shuffle partitions or executor memory set too low, not to a bad join.
So the answer I give is: stages and shuffles explain cost, Catalyst and AQE handle what they can automatically, and I intervene only where the Spark UI shows a specific skew, spill or unnecessary shuffle, with the technique matched to that symptom.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Design an ETL pipeline, clarifying source systems, data volume, freshness requirements, consumers, and reliability expectations.
Reported in ETL Pipeline Design for Walmart
The 90-second answer
Before drawing anything I'd pin down five things: the sources and how changes are captured (log-based CDC, an event stream, or file drops), volume (rows per day, peak rate, record size), freshness (how stale each consumer can tolerate), consumers (who reads the output and in what shape), and reliability (what a failed run costs, and whether duplicates are acceptable). Those answers drive the architecture more than the choice of tool does.
Assume, labelled as hypothetical: 40 store and supply-chain systems, about 2 billion events a day, which averages to 2e9 / 86,400 ≈ 23k events/s with peaks near 60k/s. Inventory dashboards need data within 15 minutes. Finance needs it by 06:00 the next day.
Shape: land raw events append-only in object storage, partitioned by ingest hour (bronze). Transform incrementally into conformed tables (silver), then publish marts (gold). The 15-minute path runs micro-batches or streaming off the CDC topic. The daily path runs batch over the same transformation code, so the two cannot drift.
Idempotent loads. Every source record carries a business key and a source sequence number. Each load keeps only the newest version of a key, so a retried or replayed window produces the same table.
MERGE INTO silver.inventory_position t
USING (
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY store_id, sku ORDER BY source_seq DESC) AS rn
FROM bronze.inventory_events
WHERE ingest_hour >= :window_start
) WHERE rn = 1
) s
ON t.store_id = s.store_id AND t.sku = s.sku
WHEN MATCHED AND s.source_seq > t.source_seq THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;| Decision | Choice | Why |
|---|---|---|
| Capture | CDC or stream for high-churn OLTP sources; file drops for legacy | Avoids full scans of transactional systems |
| Landing | Append-only raw, partitioned by ingest hour | Replay without touching sources again |
| Load | MERGE on business key with source sequence | Retries and backfills are safe |
| Late data | 2-hour watermark; reprocess older partitions on arrival | Events arrive out of order |
| Serving | Partition by business date, cluster by store and SKU | Matches the filters consumers actually use |
Failure modes and detection
- Duplicate or missing rows after a retry: reconcile row counts and key checksums per source window against the silver table. Alert on any gap.
- Schema drift at a source: validate against a data contract at landing. Route violations to a quarantine table, not the silver layer, and page the owning team.
- Events arriving after the watermark: count them per hour. A rising count means the watermark is too tight or a source is lagging.
- Backfill overwriting newer data: the sequence guard in the MERGE blocks this. Verify it with a test that replays an old window.
- Hot partition skew (one large SKU or store dominating a task): watch p95 versus max task duration per stage. Salt the key if the gap is large.
Reliability target. Freshness is measured at gold as now() minus max(event_time) per consumer. The 15-minute SLO pages on breach, and the daily feed has a completion deadline with a retry budget of two reruns before escalation.
When not to build this
If a consumer needs data only once a day and the source is a small, stable table, a nightly batch job with the same MERGE pattern is cheaper to run and easier to debug. Streaming earns its cost only where the freshness requirement is measured in minutes.
What I'd confirm with the interviewer: whether duplicates are tolerable downstream, who owns schema changes at each source, and what happens to dashboards when the 15-minute path breaches.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Design the complete data model and architecture for a real-time ticket booking application handling high concurrent seat reservations.
Reported in Walmart Global Tech Data Engineer Interview Questions ...
The 90-second answer
I'd make Postgres the source of truth for inventory, with one row per seat per event. Seat availability is decided by a conditional update inside a transaction, not by reading a seat map and then writing. A hold has an expiry, so abandoned checkouts release seats without a human or a cron touching the orders. Real-time seat maps are a read-side projection fed by change events, and they are allowed to be a few seconds stale. Writes never trust that projection.
Assumptions I'd state first: one region, a single venue or event can have up to about 50,000 seats, peak is a few thousand seat-attempts per second on one hot event, and a hold lasts 10 minutes.
Data model
CREATE TABLE event_seats (
event_id bigint NOT NULL,
seat_id bigint NOT NULL,
status text NOT NULL CHECK (status IN ('available','held','sold')),
hold_id uuid,
hold_expires_at timestamptz,
price_cents integer NOT NULL,
version bigint NOT NULL DEFAULT 0,
PRIMARY KEY (event_id, seat_id)
);
CREATE TABLE holds (
hold_id uuid PRIMARY KEY,
event_id bigint NOT NULL,
customer_id bigint NOT NULL,
expires_at timestamptz NOT NULL,
status text NOT NULL CHECK (status IN ('active','converted','released'))
);The venue layout (venues, seats) is a template copied into event_seats when an event is published. Copying matters: a price change or a seat block on one event must not touch another. orders and order_items hold the purchase; payments is keyed by the payment provider's id so retries don't double-charge.
Reserving seats without double-booking
The whole reservation is one transaction. Seats are locked in ascending seat_id order, which prevents deadlocks when two buyers want overlapping pairs.
UPDATE event_seats
SET status = 'held', hold_id = $1, hold_expires_at = now() + interval '10 minutes', version = version + 1
WHERE event_id = $2 AND seat_id = $3
AND (status = 'available' OR (status = 'held' AND hold_expires_at < now()));If the row count is not equal to the number of seats requested, roll back and tell the client which seats failed. Expired holds are claimable in the same predicate, so no sweeper is needed for correctness. A sweeper still runs to keep the seat map honest.
Trace, two buyers, seat 17, same instant: A's update takes the row lock and returns 1. B's update blocks, then re-evaluates the predicate after A commits, sees held and a future expiry, and returns 0. B gets a conflict. Neither transaction needed an application-level lock.
Confirming the sale
Payment can outlive the hold. At confirmation, in one transaction, check that every seat still has hold_id equal to the hold and hold_expires_at > now(), then set them sold and mark the hold converted. If the check fails, refund the charge automatically. Don't assume the payment call was fast enough.
Read path and architecture
Writes go to the Postgres primary. Change events from the WAL (logical decoding or Debezium into Kafka) update a per-event bitmap in Redis that the seat map reads. Reconcile the bitmap from the table every few minutes, because a dropped event is otherwise silent drift.
Alternatives and when not to use them
Redis-only locks with SET NX PX are fast, but the lock is not the inventory, and a lost lock or failover can sell a seat twice. Use them only as a queue-admission layer in front of the database. A single row per event with a counter works for general admission, not for numbered seats. A distributed store with conditional writes (DynamoDB, Spanner) fits if you need multi-region, at the cost of more complex multi-seat transactions.
Failure modes and detection
- Paid after expiry: alert on a count of payments captured against holds with
expires_atin the past. This should be zero, and when it isn't, the refund path is firing. - Seat map drift: compare the cache count of available seats with
SELECT count(*)per event on the reconcile job; page when the gap persists beyond one reconcile cycle. - Hot-row contention: contention is per seat, not per event, so one event does not serialise all writes. Watch p99 lock wait on
event_seats; if it climbs past roughly 50 ms, the admission queue needs to be larger.
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 design an audit log pipeline that can efficiently process and identify the most frequently queried users from daily query logs?
Reported in Walmart Global Tech Data Engineer Interview Questions ...
The 90-second answer
I'd split this into an append-only ingest layer and a daily batch aggregation. The audit trail stays raw and immutable. The top-users answer is a derived table I can rebuild from it at any time. Before designing, I'd confirm three things: the log volume per day, whether late events arrive after the day closes, and whether query text is itself sensitive, because that decides what gets stored in the aggregates.
For a sizing check, assume 50 M events/day at roughly 200 bytes each. That is about 10 GB/day raw, which a Spark job on a modest cluster handles in minutes. The groupBy on user_id collapses 50 M rows to about 2 M distinct users, so the shuffle is small and the final ranking is cheap.
| Stage | Storage | Partitioning | Notes |
|---|---|---|---|
| Raw landing | object store, Parquet | dt=YYYY-MM-DD/hour=HH | immutable, kept for audit retention |
| Normalized events | Delta or Iceberg table | dt | dedupe on event_id, user_id hashed if PII rules apply |
| Daily user counts | table | dt | one row per user per day |
| Top-K view | small table | dt | top 100 per day, rebuildable |
# PySpark 3.5
events = spark.read.table("audit.query_events").where("dt = '2024-06-01'")
daily = (events.dropDuplicates(["event_id"])
.groupBy("dt", "user_id")
.agg(F.count("*").alias("query_count")))
top = (daily.withColumn("rk", F.row_number().over(
Window.partitionBy("dt").orderBy(F.desc("query_count"))))
.where("rk <= 100"))Why this shape. Deduplication on event_id is what makes retries safe: the collector may resend a batch after a timeout, and without the key the counts inflate. Keeping raw events separate from aggregates means a bad parser or a bug in the ranking can be fixed by re-running one partition, not by reconstructing history.
Alternatives. If the question becomes a rolling 7-day top-K, I'd keep a daily counts table and sum seven partitions, rather than rescanning raw logs. If the volume reached billions of events per day and exact ranks were not required, I'd use a sketch such as Space-Saving for heavy hitters, which keeps K counters in memory and gives bounded error. I would not use it for an audit answer that has to be exact.
Failure modes and detection.
- Late events: a partition is reprocessed for a few days after close. I'd schedule a reconciliation job that compares raw row counts per
dtwith the sum ofquery_countin the daily table. A mismatch above a set threshold pages the owner. - Duplicate events from retries: caught by the
dropDuplicatesstep. I'd alert if the duplicate ratio moves sharply, since that usually means a collector change. - Skewed bot accounts: a single service account can dominate the top list. I'd tag known service IDs and report human and service traffic separately.
- Clock skew across regions:
dtshould come from the event's own timestamp, with ingest time kept as a separate column, so late data lands in the right partition.
In a Walmart-scale loop I'd also say who can read the top-user table, since knowing who queried most is itself sensitive. Access goes through the same governance as the raw audit data, and the aggregate is not exposed more widely than the logs it came from.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Walk me through how you would design an algorithm that, given 10 key-value pairs, randomly updates the values for 2 keys and prints the overall system layout every 2 seconds.
Reported in Walmart Global Tech Data Engineer Interview Questions ...
The 90-second answer
I'd clarify three things first: whether the store is shared across threads or processes, whether "print the layout" must be a consistent snapshot, and whether the 2-second cadence has to hold under load. I'll assume one process, in-memory dict, single writer thread, and a snapshot print. Each tick picks two distinct keys, writes new values under a lock, then prints a copy of the whole map. The schedule uses a monotonic deadline, so the cadence doesn't drift by the cost of each tick.
import random, threading, time
store = {f'k{i}': random.randint(0, 99) for i in range(10)}
lock = threading.Lock()
def update_two_keys():
with lock:
for key in random.sample(list(store), 2): # 2 distinct keys, no repeats
store[key] = random.randint(0, 99)
def print_layout():
with lock:
snapshot = dict(store) # consistent copy, print outside the lock
print(time.strftime('%H:%M:%S'), snapshot)
def run(interval=2.0, ticks=5):
next_tick = time.monotonic()
for _ in range(ticks):
update_two_keys()
print_layout()
next_tick += interval
time.sleep(max(0, next_tick - time.monotonic()))
if __name__ == '__main__':
run()Trace (hypothetical values). Tick 0: random.sample returns ['k3', 'k7'], both are rewritten, and the snapshot prints all 10 pairs. next_tick moves from t0 to t0+2.0. If the print took 15 ms, sleep waits 1.985 s, not 2.0 s, so the cadence stays anchored to the start time. Without the deadline, five ticks drift by roughly 75 ms; with it, drift is bounded by scheduler jitter.
Why these choices
random.sampleover a list gives two distinct keys in one call. Two independentrandom.choicecalls can pick the same key twice, which silently updates one key and misreports the change.- The snapshot is taken under the lock and printed outside it. Printing while holding the lock blocks writers on slow stdout, which is the failure I'd look for first if this stalls.
threading.Timerchaining is the other common answer. It reschedules from the end of each tick, so it drifts. I'd only use it if the interval must be relative to completion.
Failure modes
- Tick overrun: if an update plus print takes longer than 2 s,
sleepgoes to zero and the loop runs back to back. Detect it by loggingnext_tick - time.monotonic()going negative. - Torn reads: a reader that iterates
storewithout the lock can see a half-applied update. The snapshot copy prevents this. - Key set changes:
list(store)on every tick is O(n). With 10 keys that's irrelevant. At 10 million keys, keep a key list alongside the dict and sample from it.
Scaling the same shape. Across processes, replace the dict with a Redis hash or a database table, the lock with a row or key lock, and the print with a published snapshot. The pattern is the same: choose the targets atomically, apply writes as a unit, and publish a copy that readers can trust.
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: