A Node.js HTTP service degrades over hours: heap grows steadily, RSS climbs, and GC pauses lengthen until it OOMs. You take two `--inspect` heap snapshots 10 minutes apart under load and diff them. The 'Comparison' view shows a large positive delta on `(closure)` and `Array` retained by a single `Map` in a module-level variable used for request de-duplication keyed by request id. What is the correct root-cause conclusion and fix?
- A. The V8 old-space is simply too small; raise `--max-old-space-size` and the leak resolves itself
- B. Entries are inserted into the Map but never deleted, so it grows unbounded; bound it with a TTL/LRU eviction (or WeakMap keyed by an object) so entries are reclaimable ✓
- C. GC is failing because closures cannot be collected in V8; rewrite the code to avoid all closures
- D. The snapshots are misleading because heap snapshots include unreachable objects; ignore them and profile CPU instead
Correct answer: B. A module-scoped Map holding entries that are never evicted is a classic unbounded-cache leak, and bounding it with TTL/LRU (or a WeakMap) restores reclaimability.
You run this in Node.js:
```js
setTimeout(() => console.log('A'), 0);
setImmediate(() => console.log('B'));
Promise.resolve().then(() => console.log('C'));
process.nextTick(() => console.log('D'));
```
Assuming this is the top-level script (not inside an I/O callback), which single output ordering is guaranteed?
- A. A B C D
- B. D C A B ✓
- C. D C B A
- D. C D A B
Correct answer: B. After the sync script, microtasks drain first with nextTick (D) before promises (C), then the timers vs immediate order from the main module is deterministic here with the timer (A) firing before immediate (B).
A read-heavy product page reads from Redis with cache-aside. A popular key expires and thousands of concurrent requests miss simultaneously, all hammering the database and causing a latency spike. Which combination most directly prevents this specific thundering-herd/stampede without serving arbitrarily stale data forever?
- A. Increase the TTL to 24 hours so the key rarely expires
- B. Use a per-key mutex/lock (single-flight) so only one request recomputes while others wait, plus early/probabilistic recomputation before expiry ✓
- C. Switch from cache-aside to write-back caching so writes populate the cache
- D. Disable Redis eviction and add more read replicas to the database
Correct answer: B. Single-flight locking collapses concurrent misses into one recompute, and probabilistic early recomputation refreshes hot keys before they expire, together eliminating the stampede.
During a cross-region network partition, an e-commerce cart service must never lose items a user already added, yet remain usable (accept new adds) in each region even though regions cannot sync. Which data model choice best satisfies both goals, and what is the accepted trade-off?
- A. Strong single-leader consistency: reject writes in the non-leader region during the partition to guarantee correctness
- B. Model the cart as a state-based CRDT (e.g., OR-Set) so both regions accept writes and merge conflict-free on heal, accepting temporary divergence ✓
- C. Use a distributed lock per cart across regions so only one region can mutate it at a time
- D. Store the cart only client-side until the partition heals, then upload
Correct answer: B. An OR-Set CRDT lets both regions accept adds during the partition and merge without losing items on heal, trading away immediate cross-region consistency (temporary divergence) for availability and no-loss.
A mobile client that updates slowly hits your GraphQL API. You must rename the field `User.fullName` to `User.displayName` and change its formatting, without breaking old app versions still requesting `fullName`. What is the safest evolution strategy?
- A. Bump the schema to v2 at a new endpoint `/graphql/v2` and force clients to migrate immediately
- B. Add `displayName` as a new field, keep `fullName` resolving the old value, mark `fullName` with `@deprecated(reason: ...)`, and remove it only after telemetry shows old clients are gone ✓
- C. Change `fullName`'s resolver to return the new format, since GraphQL fields are not version-locked
- D. Make `fullName` non-nullable and add `displayName`, so clients are forced to adopt the new field
Correct answer: B. GraphQL evolves additively: add the new field, keep the old one working, deprecate it, and remove only after telemetry confirms no clients depend on it.
This React component re-renders and the expensive child re-renders on every keystroke even though its props look stable:
```jsx
function Parent(){
const [q,setQ]=useState('');
const onSelect = () => doThing();
return <><input value={q} onChange={e=>setQ(e.target.value)} />
<ExpensiveChild onSelect={onSelect} /></>;
}
const ExpensiveChild = React.memo(function C({onSelect}){ /*...*/ });
```
Why does `React.memo` fail to prevent the child's re-render, and what is the correct fix?
- A. `React.memo` only works on class components; convert ExpensiveChild to a class
- B. `onSelect` is a new function identity on every Parent render, breaking memo's shallow prop equality; wrap it in `useCallback` with a stable dependency list ✓
- C. State updates always bypass memoization; move `q` into a ref instead of state
- D. memo needs a custom comparator for all props; the default never compares functions
Correct answer: B. A fresh `onSelect` closure is created each render so memo's shallow compare sees a changed prop; `useCallback` stabilizes its identity.
An event-driven pipeline uses at-least-once delivery from a queue: a consumer charges a payment then publishes a 'charged' event. On redelivery (e.g., after a consumer crash before ack), you must avoid double-charging. Which design gives you effective exactly-once *processing* semantics?
- A. Switch the broker to exactly-once delivery mode, which guarantees the handler runs once
- B. Make the charge operation idempotent using a unique idempotency key persisted transactionally (dedup table) so redeliveries are no-ops ✓
- C. Acknowledge the message before processing so it is never redelivered
- D. Increase the visibility timeout so the message is never redelivered during processing
Correct answer: B. At-least-once delivery is unavoidable across crashes, so idempotency via a transactionally-persisted idempotency key makes redeliveries safe no-ops, yielding effective exactly-once processing.
A Postgres query `SELECT * FROM orders WHERE customer_id = $1 AND status = 'shipped' ORDER BY created_at DESC LIMIT 20;` is slow. `EXPLAIN ANALYZE` shows a Seq Scan + Sort. Which index best serves this query, letting Postgres avoid the sort and satisfy the filter efficiently?
- A. `CREATE INDEX ON orders (created_at);`
- B. `CREATE INDEX ON orders (customer_id, status, created_at DESC);` ✓
- C. `CREATE INDEX ON orders (status);` plus `CREATE INDEX ON orders (customer_id);`
- D. `CREATE INDEX ON orders (created_at, status, customer_id);`
Correct answer: B. A composite index with the equality columns first (customer_id, status) then created_at DESC matches the filter and provides pre-sorted rows so Postgres can skip the sort and stop at LIMIT.
You are decomposing a monolith and split 'Orders' and 'Inventory' into separate services with their own databases. A place-order operation must reserve inventory and create an order atomically, but you can no longer use a single ACID transaction across both DBs. Which pattern correctly handles this with well-defined failure semantics?
- A. Two-phase commit (2PC) coordinated by the API gateway across both service databases
- B. A saga: a sequence of local transactions with compensating actions (e.g., release reservation) triggered when a later step fails ✓
- C. Wrap both service calls in a distributed database transaction using `SERIALIZABLE` isolation
- D. Have Orders synchronously call Inventory and roll back Orders' DB if Inventory throws
Correct answer: B. Across independent service databases you use a saga of local transactions with compensating actions, which provides eventual consistency and defined rollback semantics without a cross-service ACID transaction.
You must build a JWT-based auth system where access tokens are stateless but you also need the ability to revoke a compromised session before its expiry. What is the standard architecture that preserves statelessness for the common path while enabling revocation?
- A. Make access tokens long-lived and delete them from the client on logout
- B. Use short-lived access tokens (stateless, checked by signature) plus long-lived refresh tokens tracked server-side, so revoking the refresh token/session stops renewal ✓
- C. Store every access token in the database and query it on each request
- D. Encrypt the JWT payload so it cannot be reused after logout
Correct answer: B. Short-lived stateless access tokens keep the hot path stateless, while server-side-tracked refresh tokens provide a revocation point that cuts off renewal for a compromised session.