The interview problem

Practice prompt

Design a read-only SQL service for analysts querying an object-storage data lake. A typical query joins a large event table to customer attributes and computes grouped aggregates. The service has 50 workers, supports concurrent tenants, and must survive a worker dying halfway through a large query. Explain planning, data movement, memory limits, skew and retry correctness.

Original system-design practice, not a reported interview question. Architecture and calculations are original. Primary technical references retrieved September 27, 2026; interview date not applicable.

1. Define the query contract

Start with batch analytical SELECT queries over immutable table snapshots. Support filters, projections, equijoins and common grouped aggregates. Exclude transactional writes and user functions with external side effects. Return a query ID immediately, expose progress and cancellation, and publish a paginated result after successful completion.

Resolve and retain input snapshot identifiers at admission. A table snapshot does not automatically provide a transactionally consistent snapshot across unrelated tables. If the question requires that stronger guarantee, use a coordinated catalog version or a supplied consistent snapshot bundle; otherwise state the per-table consistency contract.

Pin schema, execution settings and function versions. Evaluate query-time constants once. Restrict volatile functions or define their replay behavior so a retry does not silently change a query's meaning. Retain source snapshots long enough for execution and recovery.

Use exact decimal arithmetic for monetary sums when required. Floating-point aggregation can vary with reduction order; deterministic input does not itself promise bit-identical floating-point results after repartitioning. State the numerical contract explicitly.

2. Separate planning, execution and durable outputs

SQL client → authentication + tenant admission
                         ↓
             coordinator / query state
                         ↓
       catalog snapshots + statistics → planner
                         ↓
           stage DAG and task scheduler
                         ↓
  scan workers → exchange storage → join workers
                                      ↓
                             partial aggregation
                                      ↓
                     exchange → final aggregation
                                      ↓
                      committed result manifest

The coordinator parses and validates SQL, checks access, resolves snapshots and produces a physical plan. Workers execute bounded tasks over input splits or exchange partitions. The coordinator handles metadata and scheduling, not every intermediate row.

Represent the plan as stages separated by data exchanges. Within a stage, pipeline compatible operators in batches. At selected recovery boundaries, write immutable intermediate blocks to durable exchange storage. A downstream task reads the committed block manifest for each required upstream task.

A control store records query state, plan version, input snapshots, stage dependencies, task attempts and committed output references. Keep result pages outside coordinator memory. Scope storage access by tenant and query, encrypt intermediate data, and apply retention and cleanup policies.

For the worked design, materialize exchanges at stage boundaries. This adds I/O and can delay the first result, but makes large-query recovery explicit. A low-latency interactive mode could pipeline more aggressively and accept broader re-execution after failures.

3. Reduce work before distributing it

Prune partitions and row groups using predicates and metadata. Read only needed columns. Push filters into scans when their semantics match the query. Keep SQL null behavior, outer-join semantics and access restrictions intact; moving a filter across an outer join can change the result.

Estimate filtered row counts, row widths, distinct keys and key-frequency distributions. Choose join order to avoid large intermediate results. Compare estimated and actual stage sizes during execution, and allow replanning at safe materialization boundaries when estimates are badly wrong.

For a small build input, broadcast it to join workers. Otherwise partition both inputs compatibly by the join key. Broadcast feasibility depends on the expanded hash table and concurrent operator state, not only compressed file size. Existing compatible partitioning can avoid a shuffle, but a directory naming convention alone is not proof that rows are colocated correctly.

Push partial aggregation before an exchange when it preserves semantics. For an average, merge sums and counts rather than averaging local averages. For example, partitions with sum/count of 10/1 and 180/9 have a global mean of 190/10 = 19. Averaging their local means instead gives (10 + 20)/2 = 15, which is wrong. Exact distinct counts need a correct deduplication strategy; summing local distinct counts double-counts shared values.

4. Compare concrete resource budgets

Assume decimal units. A 2 TB event dataset becomes 200 GB of physical reads after pruning. The selected rows and columns produce 80 GB of exchange payload. The filtered dimension contributes 2 GB of exchange payload, but expands threefold when represented as a hash table. These are separate measurements, not interchangeable compression ratios.

ChoiceIllustrative costConsequence
Broadcast dimension to 50 workers50 × 2 GB = 100 GB delivered payload; 6 GB hash state per workerDoes not fit a 4 GB per-task build-memory budget
Partition both inputs80 + 2 = 82 GB logical exchange payloadUnder uniform distribution, 6/50 = 0.12 GB dimension hash state per worker
Durably materialize that exchange82 GB written and 82 GB read = 164 GB storage I/OExcludes replication, retries, metadata and later exchanges

The partitioned plan is a reasonable starting choice here. The 0.12 GB average does not guarantee a maximum, and multiple concurrent tasks multiply memory use. Broadcast delivery can use a distribution tree, but every receiving worker still needs the build state.

aggregate scan rate = 50 × 100 MB/s = 5 GB/s
scan-only lower bound = 200 GB / 5 GB/s = 40 seconds
one 82 GB transfer at effective 10 GB/s = 8.2 seconds

The scan rate is assumed measured under the relevant workload. The transfer calculation is a bandwidth floor for one traversal, not total query latency. Durable exchange entails both writes and reads, shared storage may throttle, and decoding, joins, scheduling and skew add work. If phases overlap, do not blindly sum every floor; if a stage barrier separates them, account for that dependency.

Admission control should reserve estimated memory, execution slots and I/O budget. Fifty workers do not provide this full bandwidth independently to every admitted query. Queue excess work by tenant and workload class, with deadlines and bounded queue sizes.

5. Treat hot keys as a different problem from too few partitions

Suppose one join key accounts for 40% of the 80 GB event payload: 32 GB. With 200 hash partitions, the average event partition is 0.4 GB, but the hot key alone makes its destination at least 80 times that average. Increasing the number of ordinary hash buckets still sends the same key to one bucket.

For an inner equijoin to a dimension with one row per key, route rows for the known hot key across 16 deterministic salt buckets using a stable event identifier. Replicate its dimension row to all 16 matching buckets. Each hot subpartition receives about 32/16 = 2 GB if the secondary hash is balanced.

Every fact row receives exactly one salt, so it joins its one corresponding dimension copy once. Splitting is valid only if the join semantics are preserved. Independently salting both sides loses matches. Replicating both sides without an ownership rule can duplicate matches. Outer joins require special care to emit unmatched rows exactly once.

For grouped sums, compute partial sums across salts and merge them by the original key. For order-sensitive operations or exact distinct aggregation, the merge state is more involved. A bounded scalar sum has a very different memory profile from collecting every value into an array.

Skew handling cannot remove inherently large output. A many-to-many key with one million left rows and 100,000 right rows produces 100 billion pairs. At 64 bytes per pair, that is 6.4 TB before overhead. Confirm whether the query is intended, enforce output/work limits and reject or cancel infeasible work; more reducers do not change the pair count.

6. Bound memory and apply backpressure

Account for hash state, input/output buffers, decompression, aggregation state and concurrent operators. Reserve headroom rather than allocating all worker memory to query operators. Limit per-query and per-tenant use so one query cannot make every worker fail.

When a hash partition exceeds its memory allowance, an external algorithm can partition or spill operator state and process it in smaller pieces. Distinguish local spill from durable exchange: spill helps a live task use bounded memory; exchange materialization provides a replay boundary. Losing a worker can lose its local spill even when its upstream exchange survives.

Spill needs free disk capacity, I/O limits and a progress strategy. If the same oversized key returns to the same memory-hungry operator, rerunning unchanged will fail again. Repartition, choose a different algorithm, reduce task concurrency or fail with a useful resource explanation.

Bound queues between producers and consumers. Slow consumers should reduce upstream production rather than cause unbounded buffering. The scheduler must avoid filling the cluster exclusively with blocked producers while giving no resources to consumers or spill work.

7. Commit one task output despite multiple attempts

Use a logical task ID plus an attempt ID and coordinator epoch. An attempt writes blocks to its own immutable namespace, checks their integrity, then proposes a complete output manifest. An atomic control-store operation selects one winning manifest for that logical task under the current epoch.

  1. Task T, attempt A, finishes its blocks but loses its acknowledgement.
  2. The scheduler starts attempt B after detecting failure or a timeout.
  3. If A already committed, the scheduler finds that committed manifest and uses it; B cannot replace it.
  4. If no attempt committed, one eligible attempt wins the guarded commit. Downstream readers use only that manifest, never the union of A and B.
  5. Unreferenced attempt blocks are cleaned after a grace period that protects active writers and readers.

Durable output must exist and be readable before its manifest is committed. Store block sizes and checksums so missing or corrupt data is detectable. A manifest is not proof that its blocks remain available forever; retention must cover downstream execution and recovery.

A downstream retry restarts from a defined input boundary. If it resumes partial progress, it needs durable input offsets and operator state committed consistently; otherwise recompute its whole task and publish a new winning attempt. Merely deduplicating upstream filenames does not prevent double-counting rows in a partially resumed sum.

This gives one selected output per logical task, not a universal exactly-once guarantee for arbitrary side effects. The read-only, replayable query contract is what makes retries tractable.

8. Recover the coordinator and finish results safely

A replacement coordinator acquires a fenced ownership epoch, reloads committed task state and schedules missing work. Workers and control-store commits reject obsolete epochs. Persist enough plan and assignment metadata to make recovery meaningful; a coordinator backup process without durable execution state cannot reconstruct progress reliably.

Use bounded retries with delay and a query-wide work budget. Retry transient worker or storage faults. Do not repeatedly retry syntax errors, deterministic function failures or a memory failure without changing the resource plan. Speculative attempts can help isolated stragglers but worsen broad storage throttling.

Once final tasks commit, atomically publish a result manifest and terminal success state. Result pages use stable identifiers and cursors; a client can fetch the same page again without appending a second logical page. No row order is promised without ORDER BY. A global ordering requirement adds merge/sort work and a defined tie policy where stable pagination requires it.

Cancellation fences new commits, signals workers and eventually reclaims intermediate data. A canceled query may still have in-flight storage operations; cleanup must not race active leases. Bound retained results, explain expiry to clients and keep retries within the authorized data-access lifetime.

Failure analysis and self-review

  • Broadcast OOM: compare expanded state with concurrent memory budgets; do not trust file size alone.
  • One reducer dominates: inspect key frequencies and output cardinality before adding generic partitions.
  • Retry doubles aggregates: consume one committed attempt and replay downstream state from a consistent boundary.
  • Inputs change during recovery: pin snapshots and retain them, including schema and function contracts.
  • Exchange storage fills: enforce quotas, admission limits and reference-aware cleanup.
  • All workers are busy but nothing progresses: inspect blocked queues, consumer scheduling and shared I/O saturation.

Track queue time, scanned bytes, planned versus actual cardinality, exchange bytes, spill volume, peak memory, partition-size percentiles, task attempts and useful work versus retry work. Validate with worker loss before and after manifest commit, coordinator failover, corrupt blocks, skewed joins, insufficient spill capacity and cancellation during publication.

Follow-ups: When would you prefer pipelined execution? How would a full outer join change salted skew handling? Which aggregates can combine locally? What changes if the service supports INSERT? How would you isolate a tenant that runs many small queries instead of one large query?

A strong answer connects query semantics to stages, resource budgets and failure recovery. An excellent answer calculates actual data movement, distinguishes spill from durable exchange, preserves join multiplicity under skew handling and explains why replay requires more than simply restarting a worker.

Sources and attribution

Retrieved September 27, 2026; exact page publication dates unstated. These references validate relevant engineering mechanisms. The proposed manifest protocol, service contract and numerical scenarios are original, not a claim about either engine's exact internals or a company's interview questions.

Continue your preparation

Choose a connected learning path or browse more System design questions. Read our editorial method and attribution policy.