Scrivio Interview library
DesignPrincipal7 min read · updated 12 November 2026

Sort orders are embedded across your systems: in Comparable implementations, database ORDER BY clauses, search indexes and pagination cursors, and they disagree. How do you set a long-term approach to ordering?

I would treat ordering as part of the domain contract: each named ordering specifies its fields, directions, null handling, collation and a unique tie-breaker, and every layer derives its behaviour from that definition. In code that means explicit Comparator constants per use case instead of one natural order on entities; for large data sets, the data store does the sorting with a collation that Java matches or never second-guesses; and tests check that pages, cursors and sorted results agree across layers, because inconsistent orders break pagination, deduplication and merges.

Why this question is asked

In a system that has grown for years, "sorted by name" means one thing in a Comparable implementation, another in a SQL ORDER BY, a third in the search index and a fourth in the code that builds pagination cursors. Each one was reasonable when written. Together they produce bugs that are very hard to see: items that appear twice in an infinite scroll, merges that drop records, exports that disagree with the screen. Interviewers ask this design question at this level to see whether we can turn a scattered technical detail into a contract with an owner. In this answer, we will see exactly how disagreeing orders break things, then define ordering as a contract, decide where ordering lives in code and in the data store, handle cursors and search indexes, and make the layers prove they agree.

1How Disagreeing Orders Break Things

Take three names, apple, Zoe and zebra. Java's String.compareTo sorts by UTF-16 code units, so uppercase comes first: Zoe, apple, zebra. A PostgreSQL column with a linguistic collation such as en-US sorts them as a reader would: apple, zebra, Zoe. A search index keyword field typically sorts by bytes, like the first. Same data, two different orders.

Now imagine a paginated API whose first page is produced by the database and whose cursor is compared in Java, or a service that merges sorted results from two shards with a Java comparator while each shard sorted with its database collation. A merge assumes both inputs are in the same order as the merge itself; when they are not, it emits records out of order, and a deduplication step that only compares neighbours lets duplicates through. With cursors, a WHERE name > :last evaluated under one collation and a cursor computed under another skips or repeats rows at the page boundary.

One list, three orders
LayerRule usedOrder of apple, Zoe, zebra
Java String.compareToUTF-16 code unitsZoe, apple, zebra
PostgreSQL, linguistic collationLocale rules (libc or ICU)apple, zebra, Zoe
Search index keyword fieldBytes, typicallyZoe, apple, zebra
PostgreSQL, C collationUTF-8 bytesZoe, apple, zebra (differs from Java beyond the BMP)
Any two layers that disagree will eventually produce a wrong page or a broken merge.

2Ordering as Part of the Domain Contract

The long-term fix is to stop treating order as an implementation detail. Each ordering the product exposes, such as "customers by name" or "orders newest first", gets a definition that lists five things: the fields, in sequence; the direction of each; how nulls are placed; the collation for text fields, including locale and strength; and a unique tie-breaker, usually the primary key, so the order is total and deterministic.

That definition is written down once, in code, and the other forms are derived from it or checked against it.

Java
public enum CustomerOrdering {
BY_NAME(
Comparator.comparing(Customer::sortName, Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparingLong(Customer::id),
"sort_name ASC NULLS LAST, id ASC"),
NEWEST_FIRST(
Comparator.comparing(Customer::createdAt, Comparator.reverseOrder())
.thenComparing(Comparator.comparingLong(Customer::id).reversed()),
"created_at DESC, id DESC");
public final Comparator<Customer> comparator;
public final String sql;
CustomerOrdering(Comparator<Customer> c, String sql) { this.comparator = c; this.sql = sql; }
}

Notice that nulls are explicit on both sides. PostgreSQL places nulls last for ascending and first for descending order by default, while a Java comparator throws on null unless we choose; writing NULLS LAST and nullsLast together removes the guesswork. Keeping the comparator and the SQL next to each other also makes a reviewer notice when one changes without the other.

3Explicit Comparators Instead of One Natural Order

Making an entity Comparable gives it one natural order, and every TreeSet, sort call and stream sorted() picks it up silently. But entities are ordered differently for different purposes: by name on a screen, by creation time in an audit, by priority in a queue. Whichever one is chosen as natural is wrong for most uses, and changing it later changes behaviour everywhere at once.

So the standard should prefer named Comparator constants per use case, like the enum above, and reserve Comparable for true values whose order is obvious and unique, such as a version number or a money amount in one currency. A call such as customers.sort(CustomerOrdering.BY_NAME.comparator) says which contract it follows; customers.sort(null) does not.

4Let the Data Store Sort, and Match Its Collation

For large data sets, ordering belongs in the data store, next to the indexes that make it fast, and Java should not re-sort results the store has already ordered. Where Java must order the same data, for example when merging shards or sorting a cached copy, it must use the same rules as the store. That is harder than it sounds: a Java Collator and a database's ICU or libc collation for the same locale are not guaranteed to agree exactly, and their rules change between library versions (PostgreSQL warns about collation version mismatches after upgrades; check your version's behaviour).

A robust long-term approach is a stored sort key: a column computed once from the name, for example a normalised, case-folded form, compared with a binary collation in the database, as bytes in the search index, and as the same normalised string in Java. Then every layer compares the same bytes, and agreement no longer depends on matching collation libraries. Where linguistic collation is required, a single ICU version can generate the binary sort key that all layers store and compare.

Step throughWhere each part of the ordering lives
  1. Ordering contractfields, direction, nulls, collation, tie-breaker
  2. Java comparatorsnamed constants derived from the contract
  3. Database ORDER BY and indexessame fields, explicit NULLS, matching collation or sort key
  4. Search index sortsort-key field plus ID tie-breaker
  5. Pagination cursorsall ordering fields plus ID of the last row

5 layers, from the top down. Step through them one at a time.

One definition at the top, many derived forms below it.

5Cursors and Search Indexes

Cursor pagination, also called keyset pagination, only works if the cursor captures every ordering field and the tie-breaker. The next page is then a row comparison against those values, which PostgreSQL evaluates under the same collation as the ORDER BY when both use the same column.

SQL
SELECT id, sort_name FROM customer
WHERE (sort_name, id) > (:lastSortName, :lastId) -- continue strictly after the last row seen
ORDER BY sort_name, id
LIMIT 50;

Search engines have the same idea, usually called search_after: the client passes the sort values of the last hit, and the sort must include a unique field as the final tie-breaker. The cursor should be opaque to clients and versioned, so that if the ordering contract changes, old cursors are rejected cleanly instead of silently skipping rows.

6Proving the Layers Agree

Agreement between layers must be tested, because it breaks silently. A contract test loads a deliberately awkward data set, with mixed case, accents, combining characters, characters outside the Basic Multilingual Plane, nulls and duplicate names, into the database and the search index. It then pages through each API with a small page size and asserts two things: the concatenation of all pages equals the full result sorted by the contract's Java comparator, and no item is missing or repeated.

Running this test in CI for each ordering, and again after database, JDK or search engine upgrades, catches the collation drift that otherwise appears as a customer complaint. Finally, each ordering in the catalogue has an owner, and adding a new sortable field means adding it to the contract, the derived forms and the test together.

7Follow-up questions

Why not just use the C collation everywhere?

It makes the database agree with byte comparisons, which is simple and fast, but users then see uppercase before lowercase and accented names at the end. That is acceptable for codes and identifiers, not for names shown to people. A stored sort key gives byte-level agreement with a human-friendly order.

Does Java's String.compareTo match PostgreSQL's C collation exactly?

Not quite. The C collation compares UTF-8 bytes, which follows code point order, while Java compares UTF-16 code units. They agree for most text but disagree for characters outside the Basic Multilingual Plane, such as emoji, relative to some characters near the top of it. That edge is another reason to compare a stored key rather than raw strings in both places.

How would you migrate existing systems to the contract?

Start with the orderings behind paginated APIs and merges, because they cause the visible bugs. For each, write the contract, add the tie-breaker and explicit null handling, add the agreement test, and then fix the layers the test shows disagreeing. Comparable implementations on entities can be deprecated gradually as call sites switch to named comparators.

8Conclusion

In this answer, we saw that Java, the database and the search index often order the same strings differently, which breaks pagination, deduplication and merges. The long-term approach is an ordering contract with fields, directions, null handling, collation and a unique tie-breaker; named Comparator constants instead of a natural order on entities; sorting in the data store for large sets, with matching collation or a shared stored sort key; cursors that carry every ordering field and the ID; and tests that page through every layer and prove they agree.

What to say in the interviewAbout 90 seconds aloud

Open with

The root problem is that ordering is treated as a detail, so each layer picks its own rule. Java's String.compareTo uses UTF-16 code units, the database uses a locale collation, the search index sorts bytes, and when they disagree you get pages with duplicates or gaps, merges that emit records out of order and deduplication that misses neighbours.

Then, if they want more

So I would make ordering part of the domain contract. Each named ordering specifies the fields, the direction of each, where nulls go, the collation for text, and a unique tie-breaker, usually the ID.

In code, that becomes named Comparator constants per use case, defined next to their SQL form, rather than a Comparable natural order on entities, which is always wrong for half the uses.

For large data, the data store sorts and Java does not re-sort; where both must order the same data, I would either match collations carefully or, better, store a normalised sort key that every layer compares as bytes. Cursors carry every ordering field plus the ID and use row comparisons, and search uses search-after with a tie-breaker.

Then I would add a contract test with awkward data that pages through each API and asserts that the pages concatenate to the full sorted result with nothing missing or repeated, and run it again after every database, JDK or search upgrade.

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 documentation below. 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 "Sort orders are embedded across your systems: in Comparable implementations, database...": https://scrivio-interview-library.netlify.app/java/object-contracts/24fc5e7485/