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.
In JavaScript, what does the following log: 'for (var i=0;i<3;i++){setTimeout(()=>console.log(i),0)}'?
- A. 0 1 2
- B. 3 3 3 ✓
- C. 0 0 0
- D. undefined three times
Correct answer: B. var is function-scoped, so all callbacks share one i whose value is 3 after the loop ends.
By the SQL standard, which isolation level prevents non-repeatable reads but still permits phantom reads?
- A. Serializable
- B. Repeatable Read ✓
- C. Read Committed
- D. Read Uncommitted
Correct answer: B. By the SQL standard, Repeatable Read prevents non-repeatable reads but still permits phantom reads.
In a Node.js cluster with multiple workers, why can in-memory session storage cause bugs?
- A. It doubles memory usage globally
- B. A user's requests may hit a different worker that lacks their session ✓
- C. It corrupts the event loop
- D. It forces synchronous I/O
Correct answer: B. Each worker has separate memory, so a session stored on one worker is missing when a request is routed to another.
What is the N+1 query problem in ORMs?
- A. Running one query that returns N+1 rows
- B. Executing one query for a list then one additional query per item to load a relation ✓
- C. A query that fails after N retries plus one
- D. Indexing N+1 columns unnecessarily
Correct answer: B. The N+1 problem is issuing one query for the parent list then N extra queries to lazily load each item's relation.
When implementing optimistic concurrency control, which mechanism detects a conflicting concurrent update?
- A. Row-level exclusive locks held for the transaction
- B. A version or timestamp column compared during the UPDATE ✓
- C. A global mutex across the table
- D. Serializable isolation only
Correct answer: B. Optimistic concurrency compares a version/timestamp column at write time and rejects the update if it changed.
In HTTP/2, which feature primarily eliminates the application-layer head-of-line blocking of HTTP/1.1 pipelining?
- A. Server push
- B. Header compression with HPACK
- C. Multiplexing multiple streams over one connection ✓
- D. Binary framing of cookies
Correct answer: C. HTTP/2 multiplexes independent streams over a single connection so one slow response no longer blocks others.
Why can OFFSET-based pagination degrade badly on large offsets?
- A. OFFSET forces a full table lock
- B. The database must scan and discard all rows before the offset ✓
- C. OFFSET disables indexes entirely
- D. It returns duplicate rows
Correct answer: B. OFFSET N still reads and skips N rows, so deep pages get progressively slower; keyset pagination avoids this.
In React, what bug arises from a useEffect that reads state but has an empty dependency array?
- A. The effect runs on every render
- B. The effect captures the initial state value and never sees updates ✓
- C. The component never mounts
- D. State updates throw an error
Correct answer: B. An empty dependency array captures the state from the first render, so the effect keeps using the stale value.
In JavaScript, what is the result of '0.1 + 0.2 === 0.3'?
- A. true
- B. false ✓
- C. throws a RangeError
- D. NaN
Correct answer: B. IEEE-754 floating point cannot represent 0.1 and 0.2 exactly, so the sum is slightly off and the comparison is false.
In a microservices setup, what is the main trade-off introduced by the Saga pattern for distributed transactions?
- A. It requires a two-phase commit coordinator
- B. It replaces atomicity with eventual consistency via compensating actions ✓
- C. It forces all services to share one database
- D. It eliminates the need for retries
Correct answer: B. Sagas break a distributed transaction into local steps with compensations, trading strict atomicity for eventual consistency.
At the READ COMMITTED isolation level, which anomaly is still possible?
- A. Dirty reads
- B. Non-repeatable reads ✓
- C. Nothing, it is fully serializable
- D. Lost updates are impossible
Correct answer: B. READ COMMITTED prevents dirty reads but still allows non-repeatable reads (and phantoms).
In the CAP theorem, a network partition occurs. A system that keeps accepting writes on both sides is prioritizing which properties?
- A. Consistency and Partition tolerance
- B. Availability and Partition tolerance ✓
- C. Consistency and Availability
- D. Only Consistency
Correct answer: B. Serving writes on both partitions sacrifices consistency, choosing Availability and Partition tolerance (AP).
Your React app re-renders an expensive child even though its props are unchanged objects created inline. What is the correct combined fix?
- A. Wrap child in React.memo only
- B. Memoize props with useMemo/useCallback AND wrap child in React.memo ✓
- C. Use useEffect on the child
- D. Move the child to a portal
Correct answer: B. React.memo only helps if referentially stable props are passed, so inline objects must be memoized too.
Two concurrent transactions read a counter, increment it, and write it back, losing one update. Which technique avoids this without long locks?
- A. SELECT with no locking
- B. Optimistic concurrency with a version column ✓
- C. Increasing connection pool size
- D. Using READ UNCOMMITTED
Correct answer: B. A version column lets the write fail if the row changed since read, catching the lost-update conflict.
In HTTP/2, what feature primarily eliminates the head-of-line blocking that HTTP/1.1 had at the application layer?
- A. Larger headers
- B. Stream multiplexing over a single connection ✓
- C. Mandatory TLS
- D. Chunked transfer encoding
Correct answer: B. HTTP/2 multiplexes independent streams on one connection so one slow response doesn't block others (though TCP-level HOL remains).
You must serve a stale-tolerant, personalized dashboard fast. Which caching strategy fits best?
- A. Public CDN caching keyed by URL only
- B. Per-user cache with stale-while-revalidate ✓
- C. No-store on everything
- D. Caching by IP address
Correct answer: B. Per-user keys keep personalization correct while stale-while-revalidate serves fast and refreshes in background.
A Node.js event loop shows growing 'lag'. Which is the LEAST likely root cause?
- A. A large synchronous JSON.parse
- B. A tight synchronous loop
- C. Awaiting a fast async DB call ✓
- D. Heavy synchronous crypto hashing
Correct answer: C. Awaited async I/O yields to the loop, so it doesn't cause lag; synchronous CPU work does.
In a distributed system, you need idempotent payment processing over an at-least-once delivery queue. What is the standard mechanism?
- A. Retry with exponential backoff only
- B. An idempotency key stored to dedupe repeated requests ✓
- C. Increasing message TTL
- D. Disabling retries
Correct answer: B. Persisting an idempotency key lets the server detect and ignore duplicate deliveries of the same operation.
When would a database composite index on (a, b) NOT be usable for a query?
- A. Query filters on a only
- B. Query filters on b only ✓
- C. Query filters on a and b
- D. Query orders by a then b
Correct answer: B. A composite index follows a left-most prefix rule, so filtering on b alone cannot use it efficiently.
You deploy a new API version but must keep old mobile clients working. Which strategy avoids breaking them while evolving the schema?
- A. Rename fields in place
- B. Additive, backward-compatible changes with versioned endpoints ✓
- C. Delete deprecated fields immediately
- D. Change field types silently
Correct answer: B. Additive changes and explicit versioning let old clients keep working while new ones adopt new fields.