Build an External Batch Sort
External Batch Sort — a complete walkthrough of external sorting, covering chunk reader, in-memory sorter, run writer, and testing.
Project goal
Implement external sorting that solves sorting a dataset larger than memory by chunking, sorting in memory, and merging runs from disk, with each component independently testable.
Final features
- Chunk reader
- In-memory sorter
- Run writer
- K-way merger
- Spill manager
Architecture
The system is organized around chunk reader, in-memory sorter, run writer, and k-way merger ties them together. Data flows as a set of sorted run files on disk, merged through a k-way heap that streams the smallest head until all runs are exhausted.
Prerequisites
- Node.js 20 LTS or later
- Familiarity with external sorting fundamentals
- A local environment to run the test suite
Dependencies
- fastify ^5.0.0 — Sort API
- lmdb ^3.2.0 — Run storage
Directory structure
external_sort_batch/
├── src/index.ts
├── src/chunk-reader.ts
├── src/in-memory-sorter.ts
├── tests/external_sort_batch.test.ts
└── package.json
Phases
1. Chunk reader
Build the chunk reader that anchors external sorting and defines the core data shape.
// Chunk reader: external sorting core
export function chunkreader(input: ChunkreaderInput): ChunkreaderResult {
// Build the chunk reader that anchors external sorting and defines the core data shape.
return processChunkreader(input);
}
Expected behavior: After this phase the chunk reader works in isolation and is covered by a unit test.
2. In-memory sorter
Add the in-memory sorter so external sorting can sorting a dataset larger correctly.
// In-memory sorter — handles external sorting Add the in-memory sorter so
export class Inmemorysorter {
constructor(private opts: InmemorysorterOptions) {}
async run(ctx: Context): Promise<InmemorysorterOutput> {
return this.execute(ctx);
}
}
Expected behavior: After this phase the in-memory sorter works in isolation and is covered by a unit test.
3. Run writer
Wire the run writer to handle a comparator that is without losing data.
// Run writer: external sorting stage
export const runwriter = (next: Next) => async (req: Request) => {
const out = await transform(req);
return next(out);
};
Expected behavior: After this phase the run writer works in isolation and is covered by a unit test.
4. K-way merger
Integrate the k-way merger to make external sorting observable and testable end to end.
// K-way merger for external sorting
export async function kwaymerger(stream: AsyncIterable<Chunk>): Promise<Aggregate> {
let acc = init();
for await (const c of stream) acc = merge(acc, c);
return acc;
}
Expected behavior: After this phase the k-way merger works in isolation and is covered by a unit test.
5. Spill manager
Finalize the spill manager so the external sorting system degrades gracefully under overload.
// Spill manager: external sorting finalization
export function spillmanager(state: State): Result {
validate(state);
return finalize(state);
}
Expected behavior: After this phase the spill manager works in isolation and is covered by a unit test.
Testing
Each phase has a focused test: chunk reader, in-memory sorter, run writer are exercised in isolation, then an integration test drives the full external sorting pipeline and asserts the a comparator that is case is handled.
Troubleshooting
A comparator that is inconsistent and produces runs that do not merge into a globally sorted output
Reproduce with a minimal fixture, then add a guard test so the external sorting system rejects the condition loudly.
Performance regresses under load
Profile with the sampling analyzer, locate the hot path, and add a targeted benchmark to lock the regression.
Deployment
Run two instances behind a load balancer, share state in Redis, and set resource limits so overload surfaces as backpressure rather than failure.
Known limitations
- Single-region; multi-region replication is out of scope.
- The chunk reader is in-process and not horizontally shared by default.
- No auth layer; assume deployment behind an edge that enforces identity.
Project overview
This project builds a external sorting system whose reason for existing is sorting a dataset larger than memory by chunking, sorting in memory, and merging runs from disk. The temptation in external sorting is to bolt the interesting part onto a working prototype and discover the hard cases in production; this build inverts that order and treats a comparator that is inconsistent and produces runs that do not merge into a globally sorted output as the first thing designed, not the last.
You will implement Chunk reader, In-memory sorter, Run writer, K-way merger, and Spill manager, each as a module with one responsibility and a test that proves it in isolation. The external sorting pipeline is then the wiring that composes them, and the integration test is where the composition is shown to survive a comparator that is inconsistent and produces runs that do not merge into a globally sorted output.
The walkthrough is written for a developer who has used a external sorting system but has not had to make one honest. It favors explicit data shapes over clever abstractions, and it names the failure each design choice prevents rather than presenting the choice as a style preference.
Each phase ends with something observable — a chunk reader that returns the right shape, a in-memory sorter that rejects bad input, an integration test that goes green — so you can stop at any point and still have a external sorting system that works for the cases covered so far.
What you will build
The finished external sorting system exposes five capabilities, each with a focused test:
- Chunk reader
- In-memory sorter
- Run writer
- K-way merger
- Spill manager
Chunk reader is the foundation that every later stage assumes; In-memory sorter is where external sorting correctness lives; Run writer handles a comparator that is inconsistent and produces runs that do not merge into a globally sorted output; K-way merger makes the system observable; and Spill manager is the graceful-degradation layer that keeps overload from becoming corruption.
The build keeps the external sorting logic in ordinary modules you can read in one sitting, and pulls in dependencies only for the parts that are genuinely tedious to hand-roll. That keeps the diff between the tutorial and a real codebase small, and keeps the failure modes visible in code rather than hidden behind a framework.
Architecture and data model
The system is organized around Chunk reader, In-memory sorter, and Run writer, with K-way merger tying them together. Data flows as a set of sorted run files on disk, merged through a k-way heap that streams the smallest head until all runs are exhausted.
Each component is a module with a pure interface where practical: the same input produces the same output, and side effects are pushed to the edges. That discipline is what makes the phases independently testable, because a test for Run writer does not need to stand up Chunk reader and In-memory sorter to exercise the interesting branch.
The data model is deliberately explicit. A set of sorted run files on disk, merged through a k-way heap that streams the smallest head until all runs are exhausted Keeping the shape written down — in a schema, a type, or a fixture — means a change to the shape is a visible diff rather than a silent runtime shift, and it means the integration test can assert against a concrete shape instead of guessing.
Configuration and code are kept apart: the configuration says what external sorting should do, the modules say how. A reviewer can change a threshold or a policy without reading the implementation, which keeps the risky changes small and lets the diff stand as the review.
The failure path through Run writer is designed before the happy path is finished, because a comparator that is inconsistent and produces runs that do not merge into a globally sorted output is the case that distinguishes a external sorting system from a demo. Every component declares what it does when its inputs are wrong, and the integration test asserts each of those declarations.
Prerequisites and dependencies
Have these ready before you install anything, so the external sorting setup is not blocked by a missing tool:
- Node.js 20 LTS or later
- Familiarity with external sorting fundamentals
- A local environment to run the test suite
The runtime dependencies are chosen to keep the external sorting datapath legible:
fastify(^5.0.0) — Sort APIlmdb(^3.2.0) — Run storage
# setup for external-sort-batch
pnpm init
pnpm add fastify lmdb
pnpm add -D typescript tsx vitest
Versions are pinned to a major range so the external sorting install is reproducible; commit the lockfile. The chunk reader reads its operational parameters from the environment and validates them at startup, so a missing value fails the boot rather than the first external sorting request.
Directory structure
Keep each external sorting component in its own file so it can be tested without starting the others:
external_sort_batch/
├── src/index.ts
├── src/chunk-reader.ts
├── src/in-memory-sorter.ts
├── tests/external_sort_batch.test.ts
└── package.json
Phase 1: Chunk reader
Build the chunk reader that anchors external sorting and defines the core data shape.
// Chunk reader: external sorting core
export function chunkreader(input: ChunkreaderInput): ChunkreaderResult {
// Build the chunk reader that anchors external sorting and defines the core data shape.
return processChunkreader(input);
}
After this phase the chunk reader works in isolation and is covered by a unit test. The chunk reader defines the data shape that every later stage assumes, so getting it right first means the later phases compile against a stable contract.
Treat the chunk reader as the single source of truth for the external sorting data shape. Validate inputs at the boundary and reject early, so a malformed value never reaches In-memory sorter or Run writer where its effect would be harder to localize.
Phase 2: In-memory sorter
Add the in-memory sorter so external sorting can sorting a dataset larger correctly.
// In-memory sorter — handles external sorting Add the in-memory sorter so
export class Inmemorysorter {
constructor(private opts: InmemorysorterOptions) {}
async run(ctx: Context): Promise<InmemorysorterOutput> {
return this.execute(ctx);
}
}
After this phase the in-memory sorter works in isolation and is covered by a unit test. This is where external sorting correctness lives: the in-memory sorter is what makes sorting a dataset larger than memory by chunking, sorting in memory, and merging runs from disk true, and its test is the proof.
Keep the in-memory sorter pure where you can. A function that takes an input and returns an output is trivial to test and impossible to mock wrong; a class with hidden state is the opposite. Push side effects to the caller and keep the in-memory sorter about the transformation.
Phase 3: Run writer
Wire the run writer to handle a comparator that is without losing data.
// Run writer: external sorting stage
export const runwriter = (next: Next) => async (req: Request) => {
const out = await transform(req);
return next(out);
};
After this phase the run writer works in isolation and is covered by a unit test. The run writer is the difference between a external sorting system that works on the happy path and one that survives a comparator that is inconsistent and produces runs that do not merge into a globally sorted output.
Design the failure before the success. Decide what run writer does when a comparator that is inconsistent and produces runs that do not merge into a globally sorted output: reject, retry, shed, or degrade — and write that test first. A external sorting system whose failure behavior is unspecified will pick one at random under pressure, and it is usually the wrong one.
Phase 4: K-way merger
Integrate the k-way merger to make external sorting observable and testable end to end.
// K-way merger for external sorting
export async function kwaymerger(stream: AsyncIterable<Chunk>): Promise<Aggregate> {
let acc = init();
for await (const c of stream) acc = merge(acc, c);
return acc;
}
After this phase the k-way merger works in isolation and is covered by a unit test. Observability is not a finishing touch; it is how you know the external sorting system is doing what it claims in production.
Emit one structured event per meaningful action, with enough context to localize a failure without a second round-trip. The k-way merger is what turns “something is slow” into “the in-memory sorter is slow for inputs matching this shape,” which is the difference between an alert and an investigation.
Phase 5: Spill manager
Finalize the spill manager so the external sorting system degrades gracefully under overload.
// Spill manager: external sorting finalization
export function spillmanager(state: State): Result {
validate(state);
return finalize(state);
}
After this phase the spill manager works in isolation and is covered by a unit test. The spill manager is what keeps overload from becoming corruption: when the external sorting system is asked for more than it can do, it degrades in a defined way instead of failing in an undefined one.
Pick a degradation strategy for spill manager — shed, queue, or backpressure — and make it explicit in code and in a test. Leaving the behavior to chance is how a external sorting traffic spike becomes a data loss incident.
Testing
Each phase has a focused test: chunk reader, in-memory sorter, and run writer are exercised in isolation, then an integration test drives the full external sorting pipeline and asserts the a comparator that is case is handled.
Start with unit tests that pin each component’s contract: the chunk reader returns the documented shape, the in-memory sorter transforms correctly, and the run writer fails in the documented way. These tests are fast and they localize regressions to the component that broke.
Then add an integration test that composes the components and drives a realistic external sorting scenario end to end. Assert the happy path first, then deliberately trigger a comparator that is inconsistent and produces runs that do not merge into a globally sorted output and assert the system degrades rather than corrupts. Because the components are pure where practical, the integration test stays deterministic rather than flaky.
A external sorting suite must also prove the negative: bad input is rejected at the boundary, overload is shed rather than queued indefinitely, and a partial failure does not leave the system in an inconsistent state. These are the tests that catch the regressions a happy-path suite never would.
The entire external sorting suite runs with no external service; every dependency is either in-process or stubbed, so every case is reproducible in CI. That is what lets the run writer failure-mode assertions live as tests rather than as a manual checklist that drifts out of date.
# run the external sorting test suite
pnpm vitest run
Deployment and operations
Run at least two external sorting instances behind a load balancer and share state in Redis. Set resource limits so external sorting overload surfaces as backpressure rather than failure.
Run at least two stateless instances behind a load balancer, and move any shared state into a shared store so the external sorting behavior is global rather than per instance. Size limits so the system sheds load before it runs out of memory, because a external sorting system that OOMs under load fails in a way that is hard to reason about.
Drain on deploy: stop accepting new work, let in-flight external sorting operations finish, then exit. Because the system holds no state that cannot be reconstructed, a rollout is a matter of cycling instances one at a time while watching the error rate.
When a dependency is unavailable, decide explicitly whether the external sorting system fails closed or degrades. Leaving that choice to chance is how a dependency outage becomes a silent data loss, so make the choice visible in code and in a test.
Security considerations
Validate all external sorting inputs at the boundary, reject oversized payloads before buffering them, and keep secrets in the environment rather than the repository.
The external sorting system is a choke point, so it is the right place to reject malformed input before it reaches in-memory sorter or run writer. Validate the shape and the size at the edge, and let the inner components assume what they receive is well-formed.
Never log secrets or full payloads; log enough to localize a failure without recording data that should not be on disk. Treat any external call as untrusted and validate its response before using it, because a external sorting system that trusts its inputs blindly is one malformed response away from corruption.
Keep dependencies pinned and run an audit in CI. A transitive dependency with a known vulnerability is still a vulnerability in your external sorting system, and the lockfile is what makes the audit meaningful.
Observability
Emit one structured event per external sorting operation with the inputs’ shape, the outcome, and a correlation id. Track error rate and latency per component and alert on a step change rather than a single spike.
The correlation id is the thread that ties a user-visible symptom to the external sorting decision and to the component log entry for the same operation. Without it, an investigation starts from a timestamp and a guess.
Watch the run writer failure rate separately from the overall error rate. A jump in run writer failures usually means a comparator that is inconsistent and produces runs that do not merge into a globally sorted output, not a bug in in-memory sorter, and the two have different owners and different fixes.
Chart the share of external sorting operations that shed, queue, or succeed. A change in the mix points at the cause faster than an aggregate latency can, because each class has a different root.
Troubleshooting
A comparator that is inconsistent and produces runs that do not merge into a globally sorted output. Reproduce with a minimal fixture, then add a guard test so the external sorting system rejects the condition loudly.
Performance regresses under external sorting load. Profile with the sampling analyzer, locate the hot path in in-memory sorter, and add a targeted benchmark to lock the regression.
Keep the external sorting dashboards separate from dependency dashboards. When an operation fails, the correlation id lets you decide in seconds whether the fault is chunk reader, in-memory sorter, or run writer, instead of guessing from a timeout.
Limitations and next steps
- Single-region; multi-region replication is out of scope.
- The chunk reader is in-process and not horizontally shared by default.
- No auth layer; assume deployment behind an edge that enforces identity.
The external sorting system is single-region by design; extending to multi-region means making chunk reader shareable across regions, which is a real change to the consistency model rather than a config flag. The run writer is in-process, which is correct for one instance but must move to a shared store before scaling out.
There is no authentication or authorization layer; the system assumes it is deployed behind an edge that enforces identity. Adding one is straightforward but out of scope for this build, and doing it here would distract from the external sorting correctness that is the point.
The natural next step, once the external sorting pipeline is trusted in production, is to add a short-TTL cache for idempotent reads and a richer k-way merger that exports histograms rather than counters. Both are additive and neither changes the contracts this build establishes.