Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Several teams implement their own in-memory search over reference data (binary search over arrays, ad hoc tries, linear scans with filters). Lookups are slow and inconsistent across services. How would you decide what belongs in a shared library, what belongs in a search engine or database, and how to roll it out?

We start by classifying what each team actually needs: exact key lookups, range and prefix queries, fuzzy or ranked text search, or analytics. Exact and range lookups over small, slowly changing reference data belong in one shared, well-tested library built on immutable snapshots; fuzzy and relevance-ranked text belongs in a search engine; large or frequently changing data belongs in a database or cache with proper indexes. We then roll out with benchmarks, memory budgets and a reference implementation, migrating the slowest services first and retiring the ad hoc copies.

Background to this question

When every team writes its own lookup code, the company pays several times for the same work and gets several kinds of bugs: one service misses entries at array boundaries, another scans 300,000 rows per request, a third uses a trie that nobody can maintain. A senior engineer is expected to turn that mess into a small number of clear choices that teams follow because they are easier, not because they are ordered to. In this answer, we will classify the kinds of search the teams are doing, decide where each kind belongs, look at what the shared library should contain, plan the rollout with measurements, and set up ownership so the problem does not come back.

1Start With an Inventory, Not a Library

The tempting first move is to write a great library and ask everyone to use it. The problem is that we do not yet know what the teams need. So the first step is a short inventory: for each service, what data it searches, how big the data is, how often it changes, which query shapes it runs and what latency it sees today. A spreadsheet with twenty rows, filled in from code reading and production metrics, is usually enough.

This also gives us the baseline we will use later to prove the change helped. If the slowest service spends 40 milliseconds per request in a linear scan, we write that down now.

2Classifying the Kinds of Search

Once the inventory is in, the needs usually fall into four groups, and each group maps to a different structure or system. An exact key lookup asks "what is the record for code GB-LON" and needs a hash map or a sorted array. A range or prefix query asks "all postcodes starting with SW1" or "all rates valid between two dates" and needs ordered data: a sorted array with binary search, a TreeMap or a database index. A fuzzy text query asks "products similar to wireles headphnes" and needs tokenising, typo tolerance and relevance ranking, which is what a search engine is built for. An analytical query asks "count products by category and region" and needs aggregation, which belongs in a database or an analytics store.

The reason to classify first is that most of the slowness comes from a mismatch: a linear scan with filters doing the job of an index, or a hand-written trie trying to do fuzzy matching.

Where each kind of search belongs
NeedExampleBelongs in
Exact key lookupcountry by ISO codeshared library: immutable hash or sorted array
Range or prefixrates valid on a date, postcode prefixshared library if small, else database index
Fuzzy or ranked textproduct search with typossearch engine such as OpenSearch or Elasticsearch
Aggregationcounts by category and regiondatabase or analytics store
Large or fast-changing data10 million customer recordsdatabase or cache with indexes
The size and change rate of the data matter as much as the query shape.

3Drawing the Lines Between Library, Engine and Database

Data size and change rate decide whether data should live in each service's heap at all. Reference data of a few hundred thousand rows that changes daily, such as currencies, countries or tax codes, is a good fit for in-memory lookup: it costs a few tens of megabytes and answers in microseconds. Data in the tens of millions of rows, or data that changes every second, should not be copied into every instance's heap. Twenty instances each holding 2 GB of the same customer table waste 40 GB and each one is slightly out of date. That data belongs in a database with the right indexes, perhaps fronted by a cache.

Fuzzy and relevance-ranked text search is a different problem. It needs analysers, stemming, typo tolerance and scoring, and building those correctly in a shared Java library would take years. A search engine already does this well. So a rule of thumb we can publish is: exact and range lookups over small reference data go in the library, anything with relevance or typos goes to the search engine, and anything large or fast-changing goes to the database.

Step throughDeciding where a lookup belongs
  1. Does the query need typo tolerance or ranking?
    YesSearch engineNoContinue
  2. Is the data under about 1 million rows and changed hourly or less?
    YesContinueNoDatabase or cache with indexes
  3. Exact key or range and prefix only?
    YesShared library snapshotNoDatabase query
  4. Agree the memory budgetfor example under 100 MB per service

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

4What the Shared Library Contains

The library should be small and boring. It offers an immutable snapshot type built from a list of records, with exact lookup by key, range and prefix queries over a sorted key, and maybe one or two secondary keys. It handles the refresh: building a new snapshot off to the side and swapping a volatile reference, so no service has to get publication right on its own. It records metrics, such as the snapshot size, its age and the lookup latency, so teams can see what it is doing.

What it should not contain is just as important. No fuzzy matching, no query language, no general-purpose indexing engine. Every feature we add is a feature we must keep working for every team.

Java
public interface ReferenceSnapshot<K extends Comparable<K>, V> {
Optional<V> get(K key); // exact lookup
List<V> range(K fromInclusive, K toExclusive); // ordered range
List<V> withPrefix(String prefix); // only for String keys
int size();
Instant loadedAt();
}
ReferenceTable<String, Country> countries = ReferenceTable.load("countries", source, Duration.ofHours(1));
countries.current().get("GB"); // Optional[Country[code=GB, name=United Kingdom]]

Notice the loadedAt() method. A common hidden failure is a refresh that stopped working weeks ago, and exposing the snapshot age as a metric with an alert catches it.

5Rolling It Out Based on Measurements

We publish three things alongside the library: a benchmark suite written with JMH that shows its lookup times for 10,000, 1 million and 5 million entries; a memory budget per snapshot (for example, data above 100 MB per instance must go to the database); and a reference implementation in one real service that others can copy.

Then we migrate in order of measured pain. The inventory tells us which services spend the most time in lookups or suffer the most incidents. If one service spends 40 milliseconds per request in a linear scan and moving it to a snapshot takes it to 0.2 milliseconds, that result sells the library to the other teams better than any document. We migrate the worst offenders first, ideally pairing with the owning team, and we leave services that work well alone until they need changes anyway.

6Owning the Library and Retiring the Copies

A shared library without an owner becomes another ad hoc copy within a year. One team owns it, with semantic versioning, a changelog and a support channel, and treats breaking changes as expensive. Each ad hoc implementation that the library replaces is marked deprecated, listed in a tracker with its owning team and a target date, and removed once migrated. Code review and architecture guidelines point new work to the library or to the search engine, so the decision rule we published becomes the default path.

7Follow-up questions

What if a team says its trie is faster than the library?

Then we measure both with the same JMH harness on that team's data. If the trie really wins and the need is common, we can bring that structure into the library with tests. If it wins only on an unusual case, the team can keep it, documented and owned, but the default remains the shared code.

How do you stop the library from growing into a search engine?

We write down its scope at the start, exact and range lookups over small immutable snapshots, and treat requests outside it as signals that the data belongs in the search engine or database. Saying no is part of owning the library.

Why not just put everything in the database?

For small reference data used on every request, a network round trip of half a millisecond or more is wasted when an in-memory lookup takes a microsecond and the data barely changes. The database is the right home when data is large, changes often or must be consistent across services at once.

8Conclusion

In this answer, we saw that the way out of inconsistent home-made search is to classify the needs first: exact lookups, ranges and prefixes, fuzzy text, and analytics. Small reference data with exact or range queries goes into one shared library of immutable snapshots, fuzzy and ranked search goes to a search engine, and large or fast-changing data stays in a database or cache with indexes. We roll out with benchmarks, memory budgets and a reference implementation, migrate the slowest services first, and keep the library owned and versioned while deprecating the copies.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start with an inventory rather than a library: for each service, what data it searches, how big it is, how often it changes, what query shapes it uses and what latency it sees.

Then, if they want more

Those needs fall into a few classes. Exact key lookups and range or prefix queries over small, slowly changing reference data, say under a million rows refreshed hourly, belong in one shared library that builds immutable snapshots and swaps them atomically on refresh.

Fuzzy or relevance-ranked text belongs in a search engine like OpenSearch, because typo tolerance and scoring are not something we should rebuild. Large or frequently changing data belongs in a database or cache with indexes, not copied into every instance's heap.

With that rule written down, I would ship the library with JMH benchmarks, a memory budget per snapshot and one reference service, then migrate the worst offenders first based on measured latency, because a service going from 40 milliseconds to under one is the best argument for the rest.

Finally, one team owns the library with versioning and a changelog, and the ad hoc copies are deprecated with owners and target dates so the problem does not grow back.

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 "Several teams implement their own in-memory search over reference data (binary search...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/7f4e2c256d/