Real Interview Questions for the Software Engineer at Walmart Global Tech
NewInterview Q&A
Q&A-1Design an in-memory cache with TTL expiration, configurable eviction, and predictable behavior under concurrent access.
Reported in Walmart Global Tech Software Engineer Interview Questions 2026
The 90-second answer
I'd build a bounded map split into lock stripes. Each entry carries its own expiry timestamp, checked on read under the same lock as the value. Eviction is chosen per cache at construction. First I'd confirm three things: the cache is per process, values are immutable, and the loader can be slow. I'll assume all three.
There are 16 stripes, each guarded by a ReentrantLock and holding its own LinkedHashMap. A key hashes to one stripe, so threads only contend when they touch the same stripe. A total capacity of 10,000 becomes 625 per stripe. Under skewed keys the global bound is approximate, and I'd state that in the contract.
final class TtlCache<K, V> {
enum Eviction { LRU, FIFO }
private static final class Entry<V> {
final V value; final long expiresAt;
Entry(V value, long expiresAt) { this.value = value; this.expiresAt = expiresAt; }
}
private static final class Stripe<K, V> {
final ReentrantLock lock = new ReentrantLock();
final LinkedHashMap<K, Entry<V>> map;
final int capacity;
Stripe(int capacity, boolean lru) {
this.capacity = capacity;
this.map = new LinkedHashMap<>(16, 0.75f, lru); // accessOrder=true gives LRU
}
}
private final Stripe<K, V>[] stripes;
private final long ttlNanos;
@SuppressWarnings("unchecked")
TtlCache(int capacity, int stripeCount, Duration ttl, Eviction policy) {
this.ttlNanos = ttl.toNanos();
this.stripes = new Stripe[stripeCount];
for (int i = 0; i < stripeCount; i++)
stripes[i] = new Stripe<>(capacity / stripeCount, policy == Eviction.LRU);
}
private Stripe<K, V> stripe(K key) {
return stripes[Math.floorMod(key.hashCode(), stripes.length)];
}
V get(K key) {
Stripe<K, V> s = stripe(key);
s.lock.lock();
try {
Entry<V> e = s.map.get(key);
if (e == null) return null;
if (System.nanoTime() - e.expiresAt >= 0) { s.map.remove(key); return null; }
return e.value;
} finally { s.lock.unlock(); }
}
void put(K key, V value) {
Stripe<K, V> s = stripe(key);
s.lock.lock();
try {
s.map.put(key, new Entry<>(value, System.nanoTime() + ttlNanos));
while (s.map.size() > s.capacity) {
Iterator<K> it = s.map.keySet().iterator();
it.next();
it.remove();
}
} finally { s.lock.unlock(); }
}
}Imports are omitted. The subtraction in the expiry check is deliberate: it stays correct when System.nanoTime() wraps.
Trace. Capacity 625 per stripe, TTL 30 s, policy LRU. put("sku-1") at t=0 stores expiresAt = t0 + 30 s. get("sku-1") at t=12 s returns the value and, because access order is on, moves the entry to the tail so it is evicted last. get at t=31 s finds the deadline passed, removes the entry and returns null. The caller reloads. Nothing expired is ever returned, because the check and the read share one lock acquisition.
Eviction. LRU uses access order, FIFO uses insertion order. Both are O(1) per operation. Expired entries should go before live ones. When a stripe is full, scan at most 8 entries from the eldest end for an expired one and evict that first, falling back to the eldest live entry. The bound keeps put O(1) and stops a long scan from holding the lock.
Stampede. If 200 threads miss the same key the moment it expires, they all call the loader and hit the backend 200 times. Keep an in-flight FutureTask per key in a side map, updated under the stripe lock. The first thread runs the loader and the rest wait on the future. A failed load is not cached: the future is removed so the next caller retries. Put a timeout on the loader so a hung backend cannot pin a stripe.
Failure modes and detection
- Hot key: one stripe saturates. Detect it with lock wait time per stripe, watching p99. The fix is a read-mostly path or a per-key value holder.
- Clock:
System.currentTimeMillis()jumps under NTP correction. UsenanoTimeonly. - Memory: entry count is the wrong bound when values vary in size. Cap by bytes if sizes differ widely.
- Stale overwrite: a slow load can finish after a newer
put. Carry a version and reject older writes.
| Approach | Get cost | Contention | Eviction | Use when |
|---|---|---|---|---|
Single LinkedHashMap under one lock | O(1) | one lock | LRU or FIFO | low QPS, simplest correct version |
| Striped (this design) | O(1) | 1/16 of traffic per lock | LRU or FIFO | default for an owned in-process cache |
| Caffeine | O(1), lock-free reads | internal | W-TinyLFU, expireAfterWrite | production, unless the eviction policy is the thing being studied |
I'd defend the striped design in the interview, then say that in production I'd use Caffeine and explain why.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Design an asynchronous email notification system with reliable retries, idempotency, and failure recovery.
Reported in Walmart Global Tech Software Engineer Interview Questions 2026
The 90-second answer
I'd split this into three parts: an outbox that turns order events into notification intents, a durable queue with per-stage workers, and a send state machine that makes each email idempotent at the point of sending. I'll assume order events arrive on a Kafka topic at about 2,000 events/s at peak (hypothetical, for sizing), that the email provider is a third party with rate limits and no guaranteed deduplication, and that a duplicate email is annoying but a missing shipping notification is a support ticket.
Flow
Order service writes the state change and an outbox row in one transaction. A relay publishes order.shipped to Kafka keyed by customer_id, so one customer's notifications stay ordered. A consumer computes the notification identity notification_key = sha256(order_id | event_type | event_version | channel) and inserts a row into notifications with status = PENDING. The unique constraint on that key is the first idempotency gate: a redelivered event hits the constraint and is dropped.
Send state machine
| State | Meaning | Transition |
|---|---|---|
| PENDING | intent stored | worker claims row, sets ATTEMPTING with lease |
| ATTEMPTING | lease held | provider 2xx, sets SENT with provider message id |
| RETRY_WAIT | transient failure | next_attempt_at reached, back to ATTEMPTING |
| DEAD | 6 attempts or permanent 4xx | operator replay or drop |
The provider call is the risky step. If the worker crashes after the provider accepted the email but before it writes SENT, the lease expires and a second worker resends. I pass the notification_key as the provider's idempotency header where the provider supports one, and otherwise accept a rare duplicate and say so. I would not claim exactly-once delivery to a mailbox; no sender can promise that.
Retries
Transient failures (timeouts, 5xx, 429) use exponential backoff with full jitter, starting at 1 minute and capped at 2 hours. On 429 I honour Retry-After over my own schedule. Permanent failures (invalid address, 4xx that is not 429) go straight to DEAD. Trace for one notification:
attempt 1 14:00:00 → 503 / attempt 2 14:01:12 → 429 Retry-After 300 / attempt 3 14:06:14 → 202, status SENT
Failure recovery
Three things keep this honest. The outbox means a crashed order service cannot lose an intent. Leases mean a crashed worker cannot strand a row in ATTEMPTING. A DEAD queue with a replay tool means a provider outage of several hours is recovered by replaying after the outage, not by hand-editing rows. I alert on the age of the oldest PENDING row and on DEAD count per hour, not on error rate, because retries hide error rate.
Trade-offs
A single Kafka consumer writing straight to the provider is simpler, but one slow provider then blocks every order event. Separating intent from send lets a Black Friday spike queue without losing events. The cost is a second table and a relay to operate, which I'd accept at this scale.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Design a UPI-like payment system with consistent transfers, idempotent APIs, and scalable transaction processing.
Reported in Walmart Global Tech Software Engineer Interview Questions 2026
The 90-second answer
First I'd pin down scope. Assume transfers between accounts on our own ledger, not settlement through an external payment network. Assume a peak of 5,000 transfers per second, a p99 of 300 ms for the transfer call, and one region. Money is stored as integers in minor units, never floats. Two rules drive everything: money must never be debited without a matching credit or a reversal, and a client retry must never move money twice.
The core is a double-entry ledger. A transfer writes two rows that sum to zero: a debit on the sender and a credit on the receiver. Both writes, and the balance updates, happen in one database transaction when both accounts live on the same shard. The invariant I'd check continuously, not only in tests: the sum of all ledger entries is zero, and every stored balance equals the sum of that account's entries.
Idempotent API. The client sends Idempotency-Key. The server inserts (client_id, idem_key, request_hash, status) into an idempotency_keys table with a unique constraint, in the same transaction as the money movement. Same key and same hash: replay the stored response. Same key, different hash: 422 with code: idempotency_key_reused. Same key while the first request is still in flight: 409 with code: in_progress. Because the key row commits atomically with the money, a crash cannot leave money moved without a record of the key.
BEGIN;
INSERT INTO idempotency_keys (client_id, idem_key, request_hash, status)
VALUES ($1, $2, $3, 'in_progress'); -- unique violation: read the existing row instead
UPDATE accounts SET balance = balance - $4
WHERE account_id = $5 AND balance >= $4; -- 0 rows updated: insufficient_funds
UPDATE accounts SET balance = balance + $4 WHERE account_id = $6;
INSERT INTO ledger_entries (transfer_id, account_id, amount)
VALUES ($7, $5, -$4), ($7, $6, $4);
UPDATE idempotency_keys SET status = 'done', response = $8
WHERE client_id = $1 AND idem_key = $2;
COMMIT;Lock ordering matters. Always update the two accounts in ascending account_id order, or two opposing transfers between the same pair will deadlock under load.
Scaling. Shard by account_id. Arithmetic with hypothetical sizing: 5,000 TPS across 16 shards is about 312 transfers per second per shard. Each transfer is roughly six statements, so about 1,900 statements per second per shard, which a single well-indexed Postgres primary handles comfortably. Same-shard transfers stay in one transaction. Cross-shard transfers do not use two-phase commit, because a coordinator failure would hold locks across shards. Instead:
- Debit on shard A with
transfer.status = PENDING_CREDIT, written through a transactional outbox. - A credit consumer applies the credit on shard B, guarded by a unique constraint on
transfer_id, so duplicate messages are harmless. - A reconciler scans transfers stuck in
PENDING_CREDITfor more than 60 s and either retries the credit or posts a reversal.
Failure modes and detection
| Failure | What happens | Detection |
|---|---|---|
| Client times out after commit | Retry hits the stored key and gets the original response | Ratio of replayed responses per minute |
| Crash between cross-shard debit and credit | Money sits in PENDING_CREDIT | Count of transfers older than 60 s, alert above zero |
| Duplicate credit message | Unique transfer_id rejects the second insert | Count of unique violations on the credit path |
| Hot account (merchant receiving bursts) | One row serialises all writes, p99 climbs | Lock wait time per account, per-account queue depth |
| Ledger drift from a bug | Sum of entries no longer zero | Invariant job every minute, page on any nonzero sum |
Trade-offs. Sharding makes cross-account reporting harder, so feed the ledger to the warehouse with change data capture rather than querying shards. If an external scheme settles the money, I would rely on its settlement files and reconcile against them, not build my own clearing. The reversal path needs the same care as the forward path: a reversal is a new transfer with its own key, never an update to the original.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Write a complete Java program where two separate threads increment a shared counter to 5000 in strictly alternating order.
Reported in Walmart Global Tech Software Engineer Interview Questions 2026
The 90-second answer
I'd treat the counter as shared state guarded by a monitor, with an explicit turn variable saying whose move it is. Each thread waits until turn names it, increments once, hands the turn over, and wakes the other thread. I'm assuming 5000 is the total count across both threads, so thread 0 produces 1, 3, 5, ... and thread 1 produces 2, 4, 6, ... up to 5000. I'd state that before coding. I'd target Java 17 or later; the same code runs unchanged on virtual threads in Java 21.
public class AlternatingCounter {
private static final int TARGET = 5000;
private final Object lock = new Object();
private int counter = 0;
private int turn = 0;
public int get() {
synchronized (lock) { return counter; }
}
public void run(int id) throws InterruptedException {
synchronized (lock) {
while (counter < TARGET) {
while (turn != id && counter < TARGET) {
lock.wait();
}
if (counter >= TARGET) {
break;
}
counter++;
turn = 1 - id;
lock.notifyAll();
}
}
}
public static void main(String[] args) throws InterruptedException {
AlternatingCounter c = new AlternatingCounter();
Thread a = new Thread(() -> {
try { c.run(0); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread b = new Thread(() -> {
try { c.run(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
a.start();
b.start();
a.join();
b.join();
System.out.println(c.get());
}
}Why it works. wait() releases the monitor, so the other thread can enter, and the while re-checks the condition after every wakeup, which covers spurious wakeups. The thread that makes the final increment sets turn and calls notifyAll(). The waiting thread wakes, sees counter >= TARGET, and exits. Without that exit check, the loser blocks forever and join() never returns.
Trace with TARGET = 4. Thread 0 sees turn == 0, sets counter to 1, sets turn to 1. Thread 1 sets counter to 2, turn to 0. Thread 0 sets counter to 3. Thread 1 sets counter to 4, and the loop ends for both threads. Output: 4.
Alternatives.
- Two
Semaphores, one per thread, starting at 1 and 0. Each thread acquires its own and releases the other's. It's shorter and has no spurious-wakeup loop, but the end condition still needs care. ReentrantLockwith twoConditionobjects. It wakes exactly the thread that needs to run, so there's nonotifyAllthundering herd. That matters at higher thread counts, not for two.AtomicIntegeralone does not alternate. It makes each increment atomic but lets one thread run ahead.
Failure modes to name.
- Using
notify()instead ofnotifyAll(): with a single waiter and a single notifier this often works, but a later edit adding a third thread can wake the wrong one and hang. - Checking
turnwith anifinstead ofwhile: a spurious wakeup lets a thread increment out of turn. - Busy-spinning on a
volatileturn: correct, but it burns a core for the whole run. - Missing the exit path: one thread finishes, the other waits on a turn that never comes, and the process never exits. A thread dump shows it parked in
Object.wait.
In production I'd want the alternation contract written into the class's Javadoc, since the locking is the whole point of the exercise.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Implement a scheduler whose executeAll method runs added tasks in time order, then clears them.
Reported in Walmart Global Tech Interview Process & Questions · Walmart Labs Interview Guide
The 90-second answer
I'd keep it to a list of (run_at, seq, task) entries. add appends in O(1). executeAll swaps the list out, sorts the batch, runs each task, and returns. The sequence number makes ties run in insertion order, so the sort never compares tasks. Before coding I'd confirm three things: whether run_at is an absolute timestamp or a delay, whether a task that raises should stop the batch, and whether executeAll can be called from several threads.
# Python 3.12
import itertools
import threading
from typing import Callable
class Scheduler:
def __init__(self) -> None:
self._pending: list[tuple[float, int, Callable[[], object]]] = []
self._seq = itertools.count()
self._lock = threading.Lock()
def add(self, run_at: float, task: Callable[[], object]) -> None:
with self._lock:
self._pending.append((run_at, next(self._seq), task))
def executeAll(self) -> list[object]:
with self._lock:
batch, self._pending = self._pending, []
batch.sort() # compares (run_at, seq) only; seq is unique
return [task() for _, _, task in batch]Why the swap matters. Tasks added while executeAll runs go into the new list and wait for the next call. Without the swap, a task that schedules another task would extend the loop, and the clear would race with the adds.
Trace. Assume run_at values are seconds.
| Step | Call | _pending after | Output |
|---|---|---|---|
| 1 | add(5.0, A) | [(5.0,0,A)] | |
| 2 | add(1.0, B) | [(5.0,0,A),(1.0,1,B)] | |
| 3 | add(5.0, C) | [(5.0,0,A),(1.0,1,B),(5.0,2,C)] | |
| 4 | executeAll() | [] | runs B, A, C |
| 5 | executeAll() | [] | returns [] |
Step 4 runs B first (1.0), then A before C because both are 5.0 and A has the lower sequence number.
Trade-offs. A heap (heapq) gives O(log n) insert and lets you peek or run tasks that are due now, which this spec does not require. It's the right choice if executeAll becomes "run what is due" instead of "run everything and clear". For a batch API, sort-on-execute is simpler and costs O(n log n) once.
Failure modes.
- A task raises. The batch is already detached, so the tasks after it are dropped silently. Either catch per task and collect errors, or re-queue the remainder in a
finally. Pick one and say which. run_atis NaN. Comparisons with NaN are false, so the sort order is undefined. Reject non-finite values inadd.- Two threads call
executeAllat once. The lock makes the swap atomic, so each task runs exactly once. - Unbounded growth if
executeAllis never called. Cap the list or document that the caller owns the cadence.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Walk me through how you would find two indices whose values sum to a target, where among ties you return the smallest i, then the smallest j.
Reported in Walmart Global Tech Interview Process & Questions · Walmart Labs Interview Guide
The 90-second answer
Assumptions: nums is an integer array of length n, unsorted, duplicates allowed, and i < j with the same index never used twice. Return (i, j), or None if no pair exists. Ties mean lexicographic order on (i, j).
The brute-force double loop already gives the right answer. Iterating i in order, then j in order, and stopping at the first hit returns the lexicographic minimum by construction. That's O(n²). The hash-map version is O(n) and keeps the same ordering guarantee.
Scan left to right. For each j, look up target - nums[j] in a map holding the first index of each value seen so far. The stored index is the smallest i that can pair with j. Record the candidate (first_index, j) and keep the lexicographic minimum over all j.
def two_sum_lex(nums, target):
first = {} # value -> smallest index seen so far
best = None
for j, x in enumerate(nums):
need = target - x
if need in first:
cand = (first[need], j)
if best is None or cand < best:
best = cand
first.setdefault(x, j) # insert after the lookup, so i < j
return bestWhy it's correct: take the true minimum (i*, j*). At j*, the first occurrence f of the complement value satisfies f ≤ i*, so (f, j*) is a valid pair. By minimality it must equal (i*, j*), so the scan finds it.
Trace. nums = [3, 1, 4, 2, 3], target = 6
| j | x | need | found in map? | candidate | best |
|---|---|---|---|---|---|
| 0 | 3 | 3 | no | None | |
| 1 | 1 | 5 | no | None | |
| 2 | 4 | 2 | no | None | |
| 3 | 2 | 4 | yes, at 2 | (2, 3) | (2, 3) |
| 4 | 3 | 3 | yes, first at 0 | (0, 4) | (0, 4) |
Returning on the first hit would give (2, 3). That's wrong, because (0, 4) is lexicographically smaller. The fix is to keep scanning and take the minimum.
Complexity. O(n) time, O(n) extra space for the map in the worst case.
Alternatives. Sorting (value, index) pairs and running two pointers is O(n log n) and makes the tie rule harder to get right, since you must enumerate every matching pair to find the smallest i. I'd only use it when memory is tight and the values are small enough to reason about in place.
Failure modes to name.
- Storing the last index instead of the first:
setdefaultkeeps the earliest, and a plain assignment in the loop does not. - Inserting before the lookup: when
targetis twicex, the element pairs with itself. - Early return on the first hit: correct for brute force, wrong for the map scan.
- Integer overflow in fixed-width languages when computing
target - xnear the type's limits. Python is immune; Java and Go need a range check or a wider type. - Empty input or no match: return the documented sentinel, and say which one you chose before coding.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Each day, plants with more pesticide than their surviving left neighbor die. How many days until none die?
Reported in Walmart Global Tech Interview Process & Questions · Walmart Labs Interview Guide
The 90-second answer
The plant at index 0 has no left neighbor, so it never dies. Any other plant dies on day d only if its nearest surviving left neighbor has less pesticide, and that neighbor's own death day sets when the gap closes. I'd use a monotonic stack. Each plant is pushed once and popped at most once, so the pass is O(n) time and O(n) space. The answer is the maximum death day across all plants, and 0 if nothing ever dies.
Assumptions I'd state: pesticide values are integers, all plants that qualify die simultaneously each day, and "more than" is strict, so equal neighbors both survive.
Core idea. Keep a stack of (value, death_day) for plants still standing relative to the prefix seen so far. For a new plant x, pop every entry with value >= x and record cur as the max death day among them. If the stack is then empty, x has no weaker left survivor and never dies (day 0). Otherwise the left survivor is smaller, so x dies on day cur + 1.
def days_until_stable(p):
stack = [] # (value, death_day)
ans = 0
for x in p:
cur = 0
while stack and stack[-1][0] >= x:
cur = max(cur, stack.pop()[1])
day = cur + 1 if stack else 0
stack.append((x, day))
ans = max(ans, day)
return ansTrace on p = [6, 5, 8, 4, 7, 10, 9]:
| i | x | popped (value, day) | cur | stack after push | day |
|---|---|---|---|---|---|
| 0 | 6 | none | 0 | (6,0) | 0 (stack empty) |
| 1 | 5 | (6,0) | 0 | (5,0) | 0 (stack empty) |
| 2 | 8 | none | 0 | (5,0),(8,1) | 1 |
| 3 | 4 | (8,1),(5,0) | 1 | (4,0) | 0 (stack empty) |
| 4 | 7 | none | 0 | (4,0),(7,1) | 1 |
| 5 | 10 | none | 0 | (4,0),(7,1),(10,1) | 1 |
| 6 | 9 | (10,1) | 1 | (4,0),(7,1),(9,2) | 2 |
Answer: 2. Check by simulation: on day 1, 8 (left 5), 7 (left 4) and 10 (left 7) die. On day 2, 9 now has left 4 and dies. Nothing else does, so the answer is 2.
Why the pops are correct. A popped entry with value >= x can never again be the nearest left survivor for anything to the right of x, because x sits between them and is at least as large. Removing it loses no information. Each entry is pushed and popped once, which gives the amortized O(n) bound.
Alternatives. Simulating the days directly, removing dying plants and rescanning, is O(n * days) and can reach O(n^2) on inputs like a long increasing run followed by a small value. I'd mention it as the baseline, then move to the stack. A DP on the left survivor, where die[i] = 1 + max(die[j]) over the popped j, is the same idea written as a recurrence, and it helps when the interviewer asks for a proof.
Failure modes to test. Empty input should return 0. A strictly decreasing array should return 0, because each plant is smaller than its left neighbor. An all-equal array should return 0, which tests the strict inequality. A strictly increasing array of length n >= 2 should return 1: every plant after the first is larger than its left neighbor, so all of them die on day 1 together. Off-by-one errors usually come from returning the last death day as a count, or from forgetting the +1 when the left survivor exists, so I'd check the output against a hand simulation on a 3-element input.
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 a UPI-like payment system (transaction consistency, scaling).
Reported in UPI-like Payment System
The 90-second answer
First I'd pin down scope: a UPI-like system moves money between accounts held at different banks through a central switch, with a synchronous debit-credit leg and a per-transaction status the payer can query. I'd assume roughly 10k TPS at peak, p99 under 2 s end to end, and that a payer must never be debited twice for one intent. Consistency is the hard part; scaling is mostly about keeping the hot path off a single lock.
The core invariant: a transaction moves through explicit states (INITIATED → DEBITED → CREDITED → COMPLETED, or → REVERSED), and each transition is a durable write keyed by a client-supplied txn_id. The client generates the id once and retries with the same id. A duplicate id returns the stored outcome, never a second debit.
| Concern | Choice | Why |
|---|---|---|
| Intent dedupe | txn_id unique index on the transactions table | Retries after timeout cannot double-post |
| Balance update | Conditional debit: UPDATE accounts SET bal = bal - :amt WHERE id = :id AND bal >= :amt | Row-level atomicity, no read-modify-write race |
| Cross-bank leg | Outbox + saga, not 2PC | Banks don't join our transaction; 2PC blocks on the slowest participant |
| Ledger | Append-only double-entry rows | Reconciliation is a sum check, not a mutable balance trust |
| Scaling | Shard accounts by account_id hash | Each debit touches one shard; cross-shard only for the credit leg |
Why not a distributed transaction. Two-phase commit across the payer bank and the payee bank would hold locks for the full round trip. If one bank stalls for 30 s, every transaction touching its accounts stalls with it. The saga instead records DEBITED locally, publishes a credit command from the outbox, and treats the credit as retryable until it succeeds or a timeout triggers compensation.
Trace of a timeout. Payer app sends txn_id=t9 for 500. The switch debits account A (bal 1200 → 700), writes DEBITED, and calls bank B. Bank B takes 4 s and the switch times out at 3 s. The switch does not retry blindly. It queries bank B with t9. Bank B's credit either exists (mark CREDITED, COMPLETED) or does not (mark a reversal: bal 700 → 1200, state REVERSED). The payer's second tap with t9 returns whatever state was reached, never a new debit.
Failure modes and detection.
- Stuck
DEBITEDrows older than the credit SLA: a sweeper alerts when the count exceeds baseline, and the reconciler resolves them. - Duplicate debit: detected by the
txn_idunique constraint, which should make it impossible; a daily ledger sum check against the bank statement catches anything that slips through. - Hot account (a merchant receiving thousands of credits a second): a single row becomes the lock point. Mitigate by splitting the balance into sub-ledgers and summing them at read time.
- Outbox lag: if publish lags past 5 s, customer-facing status goes stale. Monitor oldest unpublished outbox row age.
Scaling numbers. At 10k TPS with 2 writes per transaction plus an outbox row, that is about 30k writes/s. Spread over 16 shards that is roughly 2k writes/s per shard, well within a single primary's capacity, so sharding is for headroom and blast radius rather than raw throughput.
When not to build this. If the scale is a few hundred TPS and both accounts sit in one bank, a single database transaction with SELECT ... FOR UPDATE on both rows is simpler and fully consistent. The saga and outbox only earn their cost once a second party is outside your database.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9What is the difference between HashMap and ConcurrentHashMap internally?
Reported in Rajat Gajbhiye's Post
The 60-second answer
Both are hash tables with the same bin layout: an array of slots, each holding a linked list that becomes a red-black tree once it reaches 8 nodes in a table of at least 64 slots (Java 8+). The lookup path is nearly identical. The difference is how writes are guarded and what readers are promised. HashMap has no synchronization. ConcurrentHashMap lets most reads take no lock and most writes lock a single bin, never the whole table.
| Aspect | HashMap | ConcurrentHashMap |
|---|---|---|
| Thread safety | none; concurrent writes can lose updates or corrupt state | safe for concurrent reads and writes |
| Read path | plain field reads | volatile reads of Node fields, no lock |
| Empty-bin insert | direct write | CAS on the bin slot |
| Non-empty-bin write | direct write | synchronized on the bin's head node |
| Resize | single-threaded, stop-the-world for the caller | transferred in chunks; ForwardingNode lets readers and writers help |
size() | exact field | sum of a CounterCell array, approximate under concurrent writes |
| Null key or value | one null key, null values allowed | both rejected with NullPointerException |
| Iterators | fail-fast via modCount, best effort | weakly consistent, never throw ConcurrentModificationException |
Why HashMap loses updates. Two threads run check-then-act on the same key. Both read 0, both write 1, one increment disappears. Nothing in HashMap prevents this, and the fail-fast iterator only detects some structural changes, not races, so it is not a correctness mechanism.
// HashMap: read and write are separate steps, so two threads can both read 0
Map<String, Integer> m = new HashMap<>();
m.put("hits", m.getOrDefault("hits", 0) + 1);
// ConcurrentHashMap: the remapping runs under the bin lock
Map<String, Integer> c = new ConcurrentHashMap<>();
c.merge("hits", 1, Integer::sum);Trade-offs and when not to use CHM. Confine a HashMap to one thread, or guard it with an external lock when you need several operations to be atomic together. Collections.synchronizedMap gives one lock and simple semantics, which is fine at low contention. Pick ConcurrentHashMap for shared maps with many readers and writers spread over many keys. It does not make compound logic atomic: if (!containsKey) put still races. Use putIfAbsent, merge or compute.
Failure modes to name.
- A hot key serializes every writer on one bin lock, so throughput drops to one thread for that key.
- A slow or blocking function passed to
computeholds the bin lock for its whole duration. Calling back into the same map from it can throwIllegalStateException(Java 9+) or deadlock. size()and iteration can reflect some concurrent writes and miss others. Do not use them for exact invariants.- Java 7
HashMapcould corrupt its chain during concurrent resize. Java 8 removed that, but the lost-update problem remains.
Detection. Under contention, thread dumps show threads BLOCKED on the same bin head node. Lost-update bugs show up as counters that finish below the expected total, so the check is a deterministic test with many threads, not a code read.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10What does @SpringBootApplication actually do internally?
Reported in Rajat Gajbhiye's Post
The 90-second answer
@SpringBootApplication is a meta-annotation. It bundles three annotations, and each does a separate job at startup:
@SpringBootConfigurationis a specialised@Configuration. The class becomes a source of bean definitions.@ComponentScanwith nobasePackagesscans the annotated class's package and every subpackage. That is why the main class has to sit at the root of the source tree.@EnableAutoConfigurationimportsAutoConfigurationImportSelector. The selector reads the candidate list fromMETA-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports(Spring Boot 2.7 and later; older releases usedspring.factories), filters it with@Conditionalannotations, and registers whatever survives.
The filtering is the part people get wrong. Nothing is switched on by the annotation itself. Each candidate is a regular @Configuration guarded by conditions, for example DataSourceAutoConfiguration requires the DataSource class on the classpath (@ConditionalOnClass) and backs off if you have declared your own DataSource bean (@ConditionalOnMissingBean).
A worked trace for an order service with spring-boot-starter-web and spring-boot-starter-data-jpa on the classpath:
@SpringBootApplication // expands to @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}| Step | What happens | Condition that decides it |
|---|---|---|
| 1 | Scan com.walmart.orders.** for @Component, @Service, @Repository | package of the main class |
| 2 | Load about 150 auto-config candidates | imports file on the classpath |
| 3 | DataSourceAutoConfiguration activates | DataSource and an embedded or configured URL are present |
| 4 | DispatcherServletAutoConfiguration activates | servlet web application |
| 5 | Your @Bean DataSource is kept, auto-config skipped | @ConditionalOnMissingBean |
The exact candidate count depends on the starters, so treat it as illustrative. Ordering matters too: @AutoConfigureAfter and @AutoConfigureBefore sort the candidates, so a DataSource bean exists before JPA reads it.
Failure modes and how you spot them
- Main class in the default package. Component scan starts at the root of the classpath and picks up every annotated class in every jar. Startup gets slow and bean names collide.
- A transitive dependency switches on behaviour nobody asked for. Spring Security on the classpath gives you a default login page and a generated password. Detect it with
--debugordebug=true, which prints the condition evaluation report, or with/actuator/conditionsif Actuator is enabled. - A shared library in a sibling package is not scanned at all, so its beans are missing at runtime while the unit tests pass. Fix it with an explicit
scanBasePackagesor an auto-configuration class registered in the imports file. - Auto-config you do not want. Use
@SpringBootApplication(exclude = ...)orspring.autoconfigure.exclude. Exclusion by name is more reliable than relying on a class being absent from the classpath.
When not to use it
Do not use @SpringBootApplication in a shared library. A library should ship its own narrow @AutoConfiguration class with @ConditionalOnClass guards, so importing it has no side effects. For a service you control, the annotation is the right default. For a test slice, use @WebMvcTest or @DataJpaTest so the context loads only the layer under test.
In an interview, close the answer by saying the annotation is three annotations, the scan is package-relative, and auto-config is a conditional filter over a list. That is what the candidate can check against a real startup log.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Design an inventory service that handles high concurrency without degrading the user experience.
Reported in Walmart Global Tech System Design Interview: Reported Questions
The 90-second answer
I'd split this into two paths with different consistency rules. Availability reads (product pages, store pickup badges, search filters) are high volume and can be slightly stale. Reservations (add to cart, checkout) are low volume per SKU and must never oversell. Most designs fail because they put both on the same locked row.
Assumptions I'd confirm first: stock is tracked per SKU per node (store or DC), reads outnumber reservations by roughly 50 to 1, and a reservation holds stock for 15 minutes before it expires.
Reads never touch the write path. Availability comes from a cache keyed by SKU and node with a 5 s TTL, refreshed from the authoritative counters. The API returns coarse buckets (in_stock, low, out) rather than exact counts under load, plus an as_of timestamp. If the service misses its latency budget, the product page serves the last known bucket and the checkout remains the authority.
Reservations are atomic decrements with a single owner per counter. The guard lives in the write itself:
UPDATE stock_bucket SET qty = qty - 2
WHERE sku_id = 'SKU-8812' AND node_id = 'store-3051' AND bucket = 7 AND qty >= 2;Rows affected = 1 means the hold succeeded. Zero means try another bucket or reject. Never read, check in application code, then write.
Hot SKUs are the real concurrency problem. One row serializes every writer. Hypothetical numbers: with a 2 ms commit, one row tops out near 500 decrements per second. Split the counter into 16 buckets that sum to the available quantity. Ceiling becomes about 8000 per second, and contention drops per row. The cost is that one bucket can run empty while others hold stock, so the reject path must retry a second bucket before failing the customer.
Idempotency and expiry. Each checkout line carries an idempotency key, so a retried reserve call returns the same hold instead of taking stock twice. Holds live in a table with expires_at. A sweeper returns expired quantity; a Redis Lua script is an alternative if the bucket counters live there, since it runs atomically in one round trip.
| Path | Consistency | Latency target | Failure if broken |
|---|---|---|---|
| Availability read | Eventual, 5 s staleness | p99 under 50 ms | Stale badge (tolerable) |
| Reserve at cart | Strong per bucket | p99 under 150 ms | Oversell or false out-of-stock |
| Release on expiry | At least once, idempotent | Within 60 s of expiry | Phantom stock held |
Failure modes and how I'd detect them
- Oversell from a read-then-write race. Detect with a nightly ledger reconciliation of holds against physical counts. Any nonzero drift pages the owner.
- Stuck holds when the sweeper lags. Detect with an alert on the oldest unexpired hold past its
expires_at. - Hot bucket saturation. Detect with p99 per shard. If one bucket dominates, increase bucket count for that SKU only.
- Cache showing in stock for an empty node. Track the rate of reserve rejections that followed a cached
in_stockresponse. That rate is the true staleness cost.
I would not promise exact counts on product pages at peak. That promise is what drives the locking that hurts the user.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Design an order management system covering every stage from placing an order, to payment, to delivery.
Reported in Walmart Global Tech System Design Interview: Reported Questions
The 90-second answer
I'd make the order service the single owner of order state, and treat payment, inventory and delivery as separate services that report results back to it. Each stage is a transition in one state machine, and each transition is driven by an event, not a synchronous call chain. That keeps a payment timeout or a carrier outage from corrupting the order record.
Before designing, I'd confirm scope: single region, checkout plus fulfilment for marketplace and first-party orders, and a hypothetical peak of 2,000 orders/s with 3 line items on average. That puts roughly 6,000 inventory reservations/s on the write path, which decides the storage choice.
State machine
PLACED -> RESERVED -> PAID -> FULFILLING -> SHIPPED -> DELIVERED
PLACED|RESERVED|PAID -> CANCELLED
PAID|SHIPPED -> REFUND_PENDING -> REFUNDEDOnly the order service writes these states. Every other service emits an event such as payment.authorized or shipment.delivered with the order id and an event id. A transition is valid only from its listed predecessor, so a late payment.authorized on a cancelled order becomes a refund request, not a state change.
Flow
- Place: write the order as
PLACEDand an outbox row in the same transaction. - Reserve inventory with a 15-minute TTL. Reservations are keyed by
(order_id, sku), so retries are no-ops. - Authorize payment. Authorization is asynchronous, with the payment service calling back on completion.
- Capture on shipment, not on order, to avoid captured money for stock that never ships.
- Hand off to fulfilment, then delivery, each reporting an event.
Trace of a payment timeout: the authorization call times out at 3 s. The order stays RESERVED. A reconciliation job queries the payment provider by order_id after 60 s. If the provider shows an authorization, the order moves to PAID. If not, the reservation expires and the order moves to CANCELLED. The timeout never guesses.
Failure modes and detection
- Payment succeeds but the order write fails. The outbox guarantees the event is published once the order commits. The daily ledger diff between orders and payments catches anything that slipped through. Alert on any non-zero count.
- Overselling under concurrent checkouts. Use a conditional decrement on available stock, never read-then-write. Detect with a stock invariant check: reserved plus sold must not exceed on-hand.
- Duplicate events. Consumers dedupe on event id and apply transitions only from valid predecessors. Detect with a counter of rejected transitions, which should be near zero and rising is a bug.
- Stuck orders. Alert on orders older than their stage SLA, such as
PAIDwith noFULFILLINGafter 4 h.
When not to build this
If volume is a few hundred orders a day, one relational database with a single transactional checkout and a cron job for stuck orders is simpler and easier to debug. The event-driven design earns its cost once payment and fulfilment are owned by separate teams with independent deploys.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13Design a payment gateway that supports several payment methods (UPI, bank transfer) with the Strategy pattern, choosing the strategy at runtime.
Reported in Walmart Global Tech System Design Interview: Reported Questions
The 90-second answer
Strategy fits because UPI and bank transfer differ in request shape, completion model and failure surface, while the caller's contract stays the same. I keep the gateway as the owner of the payment state machine and idempotency. The rail becomes a strategy that only knows how to talk to its network and report what it saw.
Assumptions I state first: UPI completes asynchronously through a collect request and a callback, bank transfer settles on a later batch, and the caller sends a method field plus an Idempotency-Key.
public enum PaymentMethod { UPI, BANK_TRANSFER }
public interface PaymentStrategy {
PaymentMethod method();
ProviderAck initiate(PaymentIntent intent);
ProviderStatus queryStatus(String providerRef);
}
public final class PaymentGateway {
private final Map<PaymentMethod, PaymentStrategy> strategies;
public PaymentGateway(List<PaymentStrategy> all) {
this.strategies = all.stream()
.collect(Collectors.toUnmodifiableMap(PaymentStrategy::method, s -> s));
}
public Payment pay(PaymentIntent intent) {
PaymentStrategy s = strategies.get(intent.method());
if (s == null) throw new UnsupportedMethod(intent.method());
Payment p = store.insertPendingIfAbsent(intent.idempotencyKey(), intent);
ProviderAck ack = s.initiate(intent);
return store.recordAck(p.id(), ack);
}
}The strategy is chosen at runtime from the request, but only from an immutable map built at startup. An unknown method is rejected with a 422. The client never supplies a class name or a provider URL.
| UPI | Bank transfer | |
|---|---|---|
| Completion | async, callback or status poll | async, settles in a later batch |
| Timeout outcome | unknown until queried | unknown until queried |
| Reversal | separate refund flow | separate return flow |
| Duplicate signal | repeated callback | repeated settlement file row |
Trace (hypothetical figures). Intent pay_91 for 500.00 INR via UPI. The gateway inserts a PENDING payment keyed on the idempotency key, then calls initiate. The provider does not answer within 3 s. The gateway does not mark the payment FAILED, because the debit may have happened. It schedules queryStatus at 5 s, 30 s and 5 min. The second poll returns SUCCESS. The callback arrives later carrying the same providerRef, is matched to the existing payment, and produces no second debit.
Failure modes and detection
- Timeout treated as failure. Detect it by counting FAILED payments whose provider later reports SUCCESS during reconciliation.
- Callback arriving before the
initiateresponse is recorded. Handle it by makingrecordAckand callback handling both upsert onproviderRef, so order does not matter. - Duplicate callbacks double-crediting. Enforce a unique constraint on
(provider, providerRef)and alert on any constraint hit. - Provider fields leaking into the domain model. Keep provider types inside the strategy and map them to
ProviderAckat the boundary. - A strategy writing ledger rows itself. This splits the state machine across rails. Only the gateway writes payment state.
- PENDING rows aging past the SLA. Alert on the age of the oldest PENDING row per method, separately for UPI and bank transfer, since their SLAs differ.
When not to use this. With two rails that will never grow, an explicit branch on the enum is simpler and just as correct. The pattern pays off when rails are added per market, and when each rail needs its own polling and reconciliation schedule that the gateway should not know about.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Design Walmart's checkout system. What considerations matter at retail scale?
The 90-second answer
I'd first fix the scope: checkout runs from cart to confirmed order and covers price and promotions, inventory reservation, payment authorization and order creation. Fulfilment and returns sit downstream. I'll assume a hypothetical peak of 30,000 checkouts per minute, which is 500 requests per second into checkout, and a hot SKU with 2,000 units and 5,000 carts holding it.
Checkout spans services that cannot share one database transaction, so I'd treat it as a workflow. Each step is idempotent, progress lives in an order state machine, and failures are repaired by compensation or reconciliation rather than assumed away.
The flow:
- Quote. Freeze the price and promotion ids in a quote with a 15 minute expiry.
- Reserve. Per SKU, run
UPDATE reservations SET held = held + :qty WHERE sku = :sku AND available - held >= :qty. Zero rows updated means out of stock. Reservations carry a TTL. - Authorize. Call the payment provider with
Idempotency-Key = order_id. - Confirm. Capture the payment, convert the reservation to committed stock, and write
OrderPlacedto an outbox in the same transaction as the order row.
Trace of the failures that matter:
| Step | Failure | Handling |
|---|---|---|
| reserve | 2,001st buyer on a 2,000-unit SKU | conditional update affects 0 rows, return out_of_stock |
| authorize | 3 s timeout, outcome unknown | retry with the same key; provider returns the original result |
| confirm | crash after capture, before commit | reconciler finds PAYMENT_CAPTURED with no commit and completes it |
| reserve | buyer abandons | TTL releases stock; alert when expired holds spike |
At 500 requests per second with four downstream calls at 150 ms p99 each, sequential calls put the p99 near 600 ms before queueing. Price and promotion checks should run in parallel to bring that down, and admission control should shed load early with 503 and Retry-After instead of letting requests pile up to the timeout.
Considerations at scale
- Hot SKUs are the contention point. Sharding reservations by SKU keeps the contention local, but a single very hot SKU still serializes on one row, so I'd consider a pre-allocated stock pool per region for it.
- Retries multiply load. Use bounded retries with jitter, and a circuit breaker on payment so a degraded provider does not stall every checkout.
- Pre-scale for known peaks. Autoscaling reacts too slowly for a sale that starts at a fixed time.
- Keep the page's price consistent with the charge. A quote that expires mid-checkout should be re-priced and shown to the buyer, never silently charged at a new price.
Failure modes and detection
Oversell shows up as reserved stock exceeding physical stock in the nightly reconciliation. Double charges show up as captures with no matching order. Stuck workflows show up as orders older than the p99 completion time in a non-terminal state. Each needs its own alert, because a healthy p99 can hide all three.
Alternative and when not to use it
A single synchronous database transaction across inventory and orders is simpler and correct, but only while inventory and orders share one database. Once stock is sharded by SKU, that transaction is gone and the workflow with compensation is the realistic choice. For a single store with low volume, the simpler design is the better answer.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Design a parcel delivery system that effectively assigns packages to delivery partners.
Reported in Walmart Global Tech India Interview Experience (Backend / SSE) – Detailed Breakdown
The 90-second answer
First I'd pin down scale and the SLA. I'll assume 2M parcels a day in one metro, a 3x peak, about 60k active partners reporting location every 5 s, and a 2-hour pickup window per parcel. I'll assume batched assignment on a 30 s cycle, which trades a little latency for denser routes.
The design has three parts. Intake publishes ParcelReady events to a Kafka topic keyed by hub id, so each hub's work stays ordered. A per-hub assignment service runs a solver every 30 s over pending parcels and available partners. A dispatch layer pushes offers to partners and tracks acceptance with a TTL.
Candidate generation. Index partner locations in a geo grid (H3 at resolution 8, about 0.7 km² per cell). Each parcel scores only partners within two rings, so the search stays local.
Cost. For each candidate pair the cost is road ETA to pickup, plus the detour added by inserting the parcel into the partner's current route, plus a penalty when capacity is tight or the parcel's SLA slack is small. Partners already at their load cap are excluded.
Arithmetic. 2M parcels a day is about 23/s on average and about 70/s at peak. At peak a hub sees roughly 2,000 parcels per 30 s cycle against about 400 partners. With about 40 candidates per parcel that is about 80,000 pair scores per cycle, which is well inside the cycle budget. These are hypothetical figures to be replaced by measured ones.
Assignment. Process parcels in earliest-deadline order and give each its lowest-cost feasible partner. This is O(n·k) and should land close to optimal at typical density. I would only move to a Hungarian solve if measured route cost shows a real gain that justifies the CPU.
Offers and idempotency. Store an assignment as (parcel_id, partner_id, version, status) with a unique constraint on parcel_id where status is offered or accepted. An offer expires after 45 s and the parcel returns to the pool. Accepting uses compare-and-set on version, so a late accept after reassignment fails with 409 and the partner is told the job is gone.
Failure modes and detection
- Stale GPS (no update for more than 30 s): drop the partner from candidates. Detect with a staleness gauge per hub.
- Solver overrun: cycle p99 exceeds 30 s. Detect from cycle duration metrics, then fall back to greedy-only for that cycle.
- Double assignment after failover: prevented by the unique constraint plus a fencing token on the hub's lease. Detect with a periodic check for parcels with two live assignments, which should be zero.
- Hot partner: one partner collects a disproportionate share of parcels. Cap per-partner load and alert on assignments-per-partner skew.
Trade-off. Batching improves route density and cost per parcel but adds up to 30 s before a parcel is offered. For same-day express, where the SLA slack is minutes, assign on arrival instead and accept lower density.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Design a Music Streaming Application (Spotify / Prime Music).
Reported in Walmart Global Tech India Software Engineer Interview Experience
The 90-second answer
First I'd pin down scope: catalog size, peak concurrent listeners, start-of-playback latency target, and whether offline downloads and free tiers are in. I'll assume (hypothetically) 80M tracks, 10M concurrent listeners at peak, p95 time-to-first-audio under 300 ms, and offline downloads for premium users only.
Split the system in two. The control plane handles catalog, playlists, search, recommendations and entitlements. These are small, read-heavy JSON responses served from regional caches in front of a replicated catalog store. The data plane serves audio bytes from a CDN. Audio for a given track version and bitrate never changes, so it is an ideal edge-cache object with a long TTL and a version in the path.
Playback is a two-step handshake. The client calls POST /playback/sessions with a track id and a preferred bitrate. The service checks entitlement, picks a bitrate the network can sustain, and returns short-lived signed URLs for the segment list (HLS or DASH, roughly 6 s segments). The client then fetches segments directly from the CDN and prefetches the next track when about 30 s of the current one remain.
The arithmetic that matters: 160 kbps audio is 20 KB/s, so a 4-minute track is about 4.8 MB. 10M concurrent listeners at 160 kbps is 10^7 × 160 kbit/s = 1.6 Tbit/s of egress. No origin serves that, so the design only works if the CDN hit ratio is above 99%. Keep the origin for misses only.
| Concern | Choice | Why |
|---|---|---|
| Audio bytes | CDN, keyed by track_id/version/bitrate | Immutable objects, cacheable forever |
| Entitlement | Signed token, 15 min TTL | Avoids a database call per segment |
| Play events | Kafka, partitioned by user id | Feeds counting, recommendations, royalties |
| Offline licence | Device-bound key, revalidated every 30 days | Revocation without deleting files |
Start-latency budget (hypothetical): entitlement and URL signing 30 ms, first segment from a warm edge 80 ms, decoder spin-up and buffer fill 100 ms. That totals about 210 ms, which leaves headroom for a cold edge.
Failure modes and how I'd detect them
- New-release stampede: a hot album gets requested in the first minute, the edge misses, and the origin sees a spike. Detect with edge miss ratio per track id. Mitigate by pushing popular releases to edges before the release time.
- Play-count double counting: Kafka is at-least-once, so a retry double-counts a stream. Dedupe on
(user_id, track_id, session_id, play_start_ts)in the batch job that produces royalty reports. Streaming dashboards can tolerate duplicates, royalties cannot. - Stale entitlement: a cancelled subscriber keeps streaming for up to the token TTL. That is an accepted 15-minute window, and I'd say so to the interviewer rather than pretend it is zero.
- Offline licence drift: devices that never reconnect keep playing after revocation. Put a hard expiry on the licence and surface it in the client UI.
Trade-offs
Segmented adaptive streaming costs more to package and cache than one progressive file with HTTP range requests. Range requests are simpler and fine for a small catalog or a single bitrate. Segments win once you need bitrate switching on flaky mobile networks, which is the case here.
If the interviewer asks about recommendations, keep them off the playback path entirely. Playlist and home-page ranking are precomputed and served from a cache, so a slow model never delays audio.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Walk me through the tradeoffs of one system design versus another system design.
Reported in Tradeoffs Between Two Systems
Before picking sides I'd ask what the two designs are and what the constraint is. I'll use a shape common in Walmart order flow: checkout calls inventory synchronously and fails the order if stock can't be reserved, versus accepting the order immediately and reserving stock asynchronously from an event stream, with compensation when the reservation fails.
The synchronous design is simpler to reason about. The customer gets a definitive answer in the same request. If the order and the reservation commit in one datastore, they can share a transaction. Failures surface at the edge as a 409 or 503. The cost is coupling. Checkout latency includes the inventory call. Hypothetical figures: if inventory p99 is 180 ms and two other calls on the path take 60 ms each, checkout p99 is at least 300 ms before queueing. If inventory saturates at 20 connections per pod, checkout requests queue behind it. Retries make this worse: three attempts with 2 s timeouts can hold a worker thread for 6 s.
The asynchronous design decouples the two. Checkout writes the order in state PENDING_INVENTORY and publishes an event. A consumer decrements stock with a conditional update, then emits RESERVED or REJECTED. Checkout stays fast, and the inventory tier can fall behind without taking checkout down. The cost is that the customer's answer is eventual, so the UI needs a pending state. A rejected reservation becomes a compensating cancellation with a refund path. Under at-least-once delivery, duplicates are certain, so the reservation must be idempotent, keyed on order_id plus line_id.
| Concern | Synchronous reserve | Async reserve with events |
|---|---|---|
| Customer answer | definitive in the request | eventual, needs a pending state |
| Checkout p99 | includes inventory p99 | independent of inventory |
| Failure surface | 503 at checkout | consumer lag, compensations |
| Correctness hazard | timeout after reservation committed | duplicate or out-of-order events |
| How you detect it | checkout error rate, inventory p99 | consumer lag, age of oldest PENDING_INVENTORY order |
I'd choose synchronous for a low-volume, high-value item with one inventory source, where a definitive answer matters more than latency. I'd choose asynchronous when stock is spread across many stores and checkout traffic spikes faster than inventory can scale. The case to name explicitly is the timeout. If inventory commits the reservation and the response is lost, the client retries. The reservation key therefore has to be the order line, not a fresh request id, or the retry double-reserves stock.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18Implement LRU Cache.
Reported in Walmart Interview Questions, Process & Experiences (2026) - Aced (formerly Exponent)
The 90-second answer
I'd clarify three things first: the key and value types, whether the cache is shared across threads, and whether a null value is legal. I'll assume a single-threaded core with a lock added at the boundary, and that get and put must both be O(1). The structure is a HashMap from key to node, plus a doubly linked list ordered most-recent at the head. The map gives O(1) lookup. The list gives O(1) move-to-front and O(1) eviction of the tail, because a node can be unlinked without walking the list.
import java.util.HashMap;
import java.util.Map;
public class LRUCache<K, V> {
private static final class Node<K, V> { K key; V val; Node<K, V> prev, next; }
private final int capacity;
private final Map<K, Node<K, V>> index = new HashMap<>();
private final Node<K, V> head = new Node<>(), tail = new Node<>();
public LRUCache(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this.capacity = capacity;
head.next = tail; tail.prev = head;
}
public V get(K key) {
Node<K, V> n = index.get(key);
if (n == null) return null;
unlink(n); pushFront(n);
return n.val;
}
public void put(K key, V val) {
Node<K, V> n = index.get(key);
if (n != null) { n.val = val; unlink(n); pushFront(n); return; }
if (index.size() == capacity) {
Node<K, V> lru = tail.prev;
unlink(lru); index.remove(lru.key);
}
n = new Node<>(); n.key = key; n.val = val;
index.put(key, n); pushFront(n);
}
private void unlink(Node<K, V> n) { n.prev.next = n.next; n.next.prev = n.prev; }
private void pushFront(Node<K, V> n) { n.next = head.next; n.prev = head; head.next.prev = n; head.next = n; }
}Trace. Capacity 2. put(1,a) gives list [1]. put(2,b) gives [2,1]. get(1) returns a and moves 1 to the front: [1,2]. put(3,c) finds the map full, takes tail.prev which is 2, removes it from list and map, then inserts 3: [3,1]. get(2) returns null.
Edge cases to name. get mutates the list, so a read is a write and a ReadWriteLock buys nothing here. A miss returns null, which is ambiguous if null is a legal value; I'd use Optional or a sentinel. put on an existing key must refresh recency, not evict. Remove from the map and the list in the same critical section or the two structures drift.
Concurrency. The simplest correct choice is synchronized on both methods, or a ReentrantLock. That serializes every operation, so under contention throughput flattens near one core's worth of list manipulation. For a hot catalog or pricing lookup I'd shard by key hash into N independent LRUs, each with capacity/N. Eviction is then per shard, so the global LRU order is approximate. That trade-off should be stated out loud.
Alternative. LinkedHashMap with accessOrder=true and an overridden removeEldestEntry does the same job in about ten lines. In an interview I'd write the explicit version to show I understand the pointer work, then mention the library option as what I'd ship. Production choice: Caffeine if hit rate and expiry matter, since it uses a frequency-aware policy that beats pure LRU on scan-heavy traffic.
Failure modes. Cache stampede on a cold key under load: fix with per-key loading locks. Memory growth when values are large: capacity counts entries, not bytes, so a weigher is needed. Stale data after an upstream price change: LRU does not invalidate, so pair it with a TTL.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Tell me about a mistake that affected others. How did you handle it?
Reported in Top Walmart Global Tech Behavioral Interview Questions (and How to Answer Them)
The 90-second answer
Pick a mistake that was yours, reached real users or another team, and that you can describe with numbers. Cover three things in order: what it cost, how you contained it, and what changed so it cannot recur the same way. Keep the blame on the system and your own decisions, not on other people.
Illustrative example (hypothetical figures): I shipped a change to a shared inventory-reservation client that retried every 5xx response with no backoff cap and no retry budget. A brief upstream slowdown turned into a retry storm. Calls to the reservation service rose from about 1,200 requests per second to roughly 4,800 for eleven minutes. Checkout p99 went from 380 ms to over 6 s, and two dependent teams saw timeouts on their own paths.
| Stage | Time | Signal |
|---|---|---|
| Deploy | T+0 | retries 0.4% of calls |
| Upstream slowdown | T+6 min | retries 9% of calls, rising |
| Detected on dashboard | T+12 min | retry ratio, not traffic, was the driver |
| Rollback complete | T+27 min | retries back under 0.5% |
Containment. I rolled back rather than patching forward, because a forward fix needed a release train of about 40 minutes and the rollback was a single config revert. Before fixing anything else, I told the on-call lead and the two affected teams the time window, and listed the request ids they should check. I did not wait for them to ask. Telling people early mattered more than the fix, because the other teams could then stop their own debugging and rely on our timeline.
Repair. The rollback restored service but left the design flaw in place, so I fixed the client itself: retries capped at 3, jittered exponential backoff, and a retry budget of 10% of requests, so a dependency under load cannot be multiplied by its callers. I added a load test in staging that injects 20% 5xx responses and asserts request volume stays under 1.5x baseline. I also added an alert on retry ratio above 5% for five minutes.
Writing it up. I wrote a short postmortem with the timeline, the root cause, what the rollback did and did not fix, and the owners for each follow-up. I sent it to the affected teams before the review meeting, so the discussion was about the fixes rather than the facts.
What an interviewer will probe. Expect questions on why the retry logic passed code review, how you would measure the blast radius without the request logs, and whether the retry budget could itself hide a real outage. Have a concrete answer for each. Name what you would still get wrong under pressure, and what you checked afterwards rather than assumed.
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: