Scrivio Interview library
DesignAdvanced8 min read · updated 12 November 2026

A reporting service must sort 500 GB of order events by customer and timestamp every night, and the machine has 32 GB of heap. How would you design the sort, and when would you push the work to the database or a data platform instead?

I would use an external merge sort: read chunks that fit comfortably in memory, sort each with a stable in-memory sort on (customer, timestamp), write each as a sorted run file in a compact binary format, and then k-way merge the runs with a PriorityQueue holding the head of each run. Partitioning by customer hash first lets partitions be sorted in parallel and independently, and checkpointing finished runs means a failure does not redo the whole night. But before writing this, I would check whether a database ORDER BY over a suitable index, or a Spark or warehouse job, does the same work more cheaply to operate.

Why this question is asked

Sorting data larger than memory is a classic problem that most engineers never solve by hand, because databases and data platforms do it for us. When a service does have to do it, the naive approaches fail badly: loading everything causes OutOfMemoryError, and sorting with random disk access takes days. Interviewers ask this at the fifteen-year level to see whether we can design the algorithm with real numbers, handle failures, and also judge when custom code is the wrong answer. In this answer, we will size the problem, design the two phases of an external merge sort, add partitioning for parallelism, make the job restartable, and then compare it with pushing the work to a database or data platform.

1Sizing the Problem

500 GB of events cannot be sorted in a 32 GB heap, and the real usable space is much smaller than 32 GB. As Java objects, events take far more memory than their raw size: each object has a header, each field reference costs bytes, and strings carry their own overhead, so 1 GB on disk can easily become 3 GB of objects. The garbage collector also needs headroom, and TimSort needs up to half the array again as a temporary buffer.

A safe design budget is therefore to sort around 6 to 8 GB of raw data per chunk, held in compact form, which gives roughly 500 / 8, about 63 to 80 sorted runs. With a disk that reads and writes sequentially at around 500 MB per second, simply reading and writing 500 GB once takes about 1,000 seconds each way, so the whole job is IO-bound and every extra pass over the data costs another half hour or more. The design goal is to read and write the data as few times as possible.

Step throughExternal merge sort for 500 GB with a 32 GB heap
  1. Read the next chunk of about 8 GBsequential, buffered reads
  2. Encode records compactlyfixed-width key: customer id, timestamp
  3. Sort the chunk in memorystable sort on (customer, timestamp)
  4. Write a sorted run file and record itcheckpoint: run 17 of 63 done
  5. More input left?
    YesRead the next chunkNoStart the merge
  6. k-way merge all runsPriorityQueue of run heads, one buffered reader per run
  7. Write the final sorted outputatomic rename when complete

7 steps in order. Play them, or step through them one at a time.

2Phase 1: Creating Sorted Runs

In the first phase we turn the unsorted input into many sorted files. We read a chunk, decode each event into a compact representation, sort it, and write it out as a run. The compact representation matters a lot: instead of millions of rich Event objects, we can keep the sort key, customer id and timestamp as two longs, in a primitive array alongside the offset of the full record in a byte buffer. Sorting keys and offsets is far cheaper than sorting objects, and the encoded binary form on disk is smaller than JSON or CSV, which cuts IO in both phases.

The in-memory sort must be stable if events with the same customer and timestamp must keep their input order, which an audit report may require. TimSort on objects is stable; if we sort primitive keys ourselves, we can add the input sequence number as a final key, which makes any sort effectively stable. Run files are written with large buffered sequential writes, never small random ones.

3Phase 2: The k-way Merge

In the second phase we merge all runs into one sorted output. Each run is already sorted, so the smallest remaining element overall is always one of the runs' current heads. A priority queue, a min-heap, gives us that smallest head in O(log k) time for k runs.

Java
record Head(Event event, int run) {}
Comparator<Event> byCustomerThenTime =
Comparator.comparingLong(Event::customerId).thenComparingLong(Event::timestamp);
PriorityQueue<Head> heap = new PriorityQueue<>(
Comparator.comparing(Head::event, byCustomerThenTime).thenComparingInt(Head::run)); // run index keeps it stable
for (int i = 0; i < runs.size(); i++) {
Event e = runs.get(i).next(); // each RunReader has its own large read buffer
if (e != null) heap.add(new Head(e, i));
}
while (!heap.isEmpty()) {
Head h = heap.poll(); // smallest event across all runs
out.write(h.event());
Event next = runs.get(h.run()).next();
if (next != null) heap.add(new Head(next, h.run()));
}
// N events, k runs: O(N log k) comparisons, every byte read once and written once

Breaking ties by run index keeps the merge stable, because runs were created in input order. The heap only ever holds k elements, so the merge itself needs very little memory. What does need memory is the read buffers: one per run, plus a large output buffer.

4Choosing the Merge Fan-In

The fan-in k is the number of runs merged at once. A larger k means fewer merge passes, but each run needs its own read buffer, and smaller buffers mean more disk seeks as the reader jumps between files. With 63 runs and 64 MB of buffer each, the buffers take about 4 GB, which fits easily, so we merge everything in a single pass. If we had 2,000 runs, 64 MB buffers would need 128 GB; we would either shrink buffers, which on spinning disks makes seeks dominate, or merge in two passes, for example 45 groups of about 45 runs, then a final merge of the 45 results.

So we choose k as large as possible while keeping each buffer big enough for efficient sequential reads on our storage, typically tens of megabytes for disks and less for fast SSDs. One pass is the goal, because each extra pass reads and writes the full 500 GB again.

5Partition by Customer First for Parallelism

Because the sort key starts with customer, we can split the problem before sorting. In a first pass, each event goes to one of, say, 64 partition files chosen by hash(customerId) % 64. Every partition is about 8 GB, holds complete customers, and can be sorted completely independently, often entirely in memory, or with a small external sort if a partition is larger than expected because of a very busy customer.

This gives parallelism almost for free: several partitions can be sorted at the same time on different cores or even different machines, and a failure affects only one partition. There is one subtlety. Hash partitioning gives each customer's events in timestamp order, but the output as a whole is not globally ordered by customer id. For a report that processes each customer separately, that is enough. If the consumer needs one globally sorted stream, we use range partitioning by customer id instead, choosing the ranges from a sample of the data so partitions are balanced.

6Designing for Restarts

A job that runs for hours will eventually fail halfway: a node is replaced, a disk fills up, a deployment restarts the pod. Without checkpoints, the whole night's work is lost. So each finished run or partition is written to a temporary name, flushed, then atomically renamed, and recorded in a small manifest file. On restart, the job reads the manifest, skips everything already finished and continues from the first missing piece.

The final output is also written to a temporary location and renamed only when complete, so downstream readers never see half a file. Making every step deterministic and idempotent, so running it twice gives the same result, keeps restarts simple.

7When to Push the Work Elsewhere

Building this is a few weeks of careful work, and someone must operate and debug it for years. So the design review should ask whether we need to build it at all.

Options for the nightly sort
OptionStrengthsCosts and risks
Custom external merge sortfull control, no new platformweeks to build, our own restart and ops logic
Database ORDER BY on index (customer_id, ts)no sort step: index already orderedindex upkeep on writes, long reads on primary
Spark job over files in object storagebuilt-in spill, parallelism, retriescluster cost, team needs Spark skills
Data warehouse querysimplest code, scales elasticallyper-query cost, data must be loaded there
Choose on operating cost, team skills and restart behaviour, not only on speed.

If the events already live in a database, an index on (customer_id, timestamp) means reading in index order needs no sort at all, though a 500 GB read should run against a replica so it does not hurt production traffic. If the company already runs Spark or a warehouse, a job there handles spilling to disk, parallelism and task retries for us. I would choose the custom external sort mainly when the data lives in files our service owns, no suitable platform exists, and the team is comfortable owning the code.

8Follow-up questions

How do you choose k for the merge?

From memory and storage. Each run needs a read buffer large enough for efficient sequential IO, so k is about the memory available for buffers divided by the buffer size. If the number of runs is at or below that k, merge in one pass; otherwise merge in groups over multiple passes. Fewer passes always win, because each pass reads and writes the whole dataset again.

Why not just give the JVM a 600 GB heap on a large machine?

Even if such a machine is available, garbage collection over hundreds of gigabytes of objects is expensive, object overhead may push the requirement beyond the machine, and a single failure loses all progress. Memory-mapped files or off-heap buffers help, but an external sort with checkpoints is usually more predictable and cheaper.

How would you test the job?

Run it on a small input with a deliberately tiny chunk size, so many runs and multi-pass merges happen, and compare the output with a simple in-memory sort of the same data. Add tests that kill the job at each phase and check that a restart produces identical output.

9Conclusion

In this answer, we designed a nightly sort of 500 GB with a 32 GB heap as an external merge sort: sorted runs of about 8 GB in compact binary form, then a single-pass k-way merge with a PriorityQueue of run heads, with fan-in chosen against buffer memory and disk throughput. Partitioning by customer hash lets partitions be sorted in parallel, checkpointed runs and atomic renames make the job restartable, and we compared the custom job with a database ORDER BY on an index, Spark and a warehouse, choosing by operating cost, skills and restart behaviour.

What to say in the interviewAbout 100 seconds aloud

Open with

First I'd size it. 500 gigabytes won't fit in a 32 gigabyte heap, and as Java objects it would be several times bigger, so I'd plan to sort about 8 gigabytes of compactly encoded data at a time, which gives roughly 63 runs.

Then, if they want more

The job is IO bound, so the goal is to read and write the data as few times as possible. Phase one reads a chunk, encodes the key as customer id and timestamp, sorts it with a stable sort, and writes a sorted run file with large sequential writes.

Phase two is a k-way merge: a PriorityQueue holds the current head of each run, I repeatedly take the smallest, write it, and refill from that run, breaking ties by run index to stay stable.

That's N log k comparisons and a single pass if I can afford a decent read buffer per run; 63 runs at 64 megabytes is about 4 gigabytes, which is fine. With many more runs I'd merge in two passes.

To parallelise, I'd first partition events by a hash of customer id into, say, 64 files, each sortable independently and in parallel, noting that the result is ordered per customer, not globally. I'd checkpoint finished runs with atomic renames and a manifest so a failure resumes instead of restarting.

But before building it, I'd ask whether the data could be read in order from a database index on customer and timestamp, or sorted by an existing Spark or warehouse job, which might be cheaper to operate than our own code.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A reporting service must sort 500 GB of order events by customer and timestamp every...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/3bffa4ddae/