Skip to content

ADR: The search index

ADR: The search index

Status
accepted
Date
2026-09-03
Shipped as
1.0.0.35

The README listed this as open work: "precompute each vehicle's lowercase haystack at startup instead of rebuilding it per request."

In plain words

Search used to rebuild the text it searches for every row on every request. Now each row's searchable text is built once when the site starts, so a search only compares. A test that ships with it measures the difference, and the record says plainly that a visitor saw no change end to end.

What that is worth: search does less work on every request, and because the record reports what changed and what did not, the organization knows which speedups are worth paying for.

Context

Free-text search is a full scan. Every one of the hundred thousand rows is tested against the query, and the version before this one built the thing it tested against inside that loop:

string haystack =
    ($"{vehicle.Year} {vehicle.Make} {vehicle.Model} {vehicle.Trim} " +
     $"{vehicle.BodyStyle} {vehicle.TitleStatus} {vehicle.Province} {vehicle.City} " +
     $"{AuctionSchedule.StatusFor(vehicle.Id, clock)}")
    .ToLowerInvariant();
return Query
    .ToLowerInvariant()
    .Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)
    .All(haystack.Contains);

Three separate pieces of waste, and none of them depends on the row being tested at that moment:

  • The nine-field interpolation and its lowercase copy: two allocations per row, a hundred thousand times, for text that has not changed since startup.
  • AuctionSchedule.StatusFor: an FNV-1a hash and date arithmetic per row, run whether or not the query has anything to do with auction status.
  • Query.ToLowerInvariant().Split(...): the user typed the query once, and it was lowercased and split a hundred thousand times.

Decision

Each vehicle's searchable text is built once, when the dataset loads. VehicleSearchIndex holds it, keyed by vehicle id and built beside the by-id dictionary that was already built there.

The query's tokens are computed once per request. VehicleFilter.Compile returns a predicate with the tokens already lowercased and split. Matches is still there for a caller holding one vehicle; a scan compiles once and reuses.

The auction status stays out of the index. It is the one searchable value the clock decides rather than the data, so it cannot be precomputed. It is computed only for a token the static text did not already satisfy, which for most queries is never. This gives the same answer the single concatenated string gave, because tokens are split on whitespace and so can never straddle the space between the two parts.

Keyed by id, not by reference. The bid overlay rebuilds each vehicle with with before filtering, so the instance the predicate sees is never the instance the index was built from. Ids survive that; references do not.

What it bought, measured

The suite carries the measurement, so it is reproducible rather than remembered: SearchIndexBenchmarkTests scans the same hundred thousand rows with both predicates, no HTTP, no sorting and no serialisation in the way. Median of five scans, three separate runs, Release build:

text rebuilt per row index
run 1 45 ms 21 ms
run 2 37 ms 14 ms
run 3 36 ms 17 ms

The scan itself is roughly halved. A whole request improves by about the same absolute amount and a smaller share: GET /api/vehicles?q=ford&limit=24 against the local API went from a 138 ms median to 111 ms, because what remains is dominated by ordering nine thousand matches and serialising a page of twenty-four. That is the honest shape of this change. It removes two hundred thousand allocations from a text query and about twenty milliseconds of work; it does not make the endpoint twice as fast, and the record would be worth less if it claimed otherwise.

The test asserts only that the indexed path is not slower. A tight timing assertion on a shared build agent fails for reasons unrelated to the code, and a suite people learn to re-run is worse than no suite.

And on the live container, nothing changed

Worth writing down because it is the part that would be easy to leave out. The same five queries were timed against the running site before and after, warm both times, twelve calls each:

query 1.0.0.34 1.0.0.35
q=ford 236 ms 228 ms
q=ford ontario clean 239 ms 231 ms
q=live 256 ms 246 ms
no query 201 ms 209 ms
make=Ford 171 ms 193 ms

That is noise, in both directions. On one vCPU behind a proxy, twenty milliseconds of scan is not what a request costs; TLS, the hop through the edge, ordering the matches and serialising the page are. The change is still right, because the work it removes is work that never needed doing and the cost of not doing it grows with the dataset. But a record claiming the site got faster would be claiming something these numbers do not show.

The first pass at this measurement did show a large regression, which was an artefact: the 1.0.0.35 numbers were taken ten seconds after the container rolled, against 1.0.0.34 numbers taken twelve minutes into its life. A cold JIT reads as a slow release. The table above is warm on both sides.

In the code

The index, and the text it holds (api/TheYard.Domain/Shared/Auction/VehicleSearchIndex.cs):

/// <summary>
/// Every searchable field that does not depend on the clock: identity
/// (year, make, model, trim) plus the fields the dropdown filters cover
/// and the city. Single-spaced and lowercased once, because the query
/// tokens are lowercased once too and a token can never contain a space.
/// </summary>
public static string TextFor(Vehicle vehicle) =>
    string.Join(' ',
        vehicle.Year, vehicle.Make, vehicle.Model, vehicle.Trim,
        vehicle.BodyStyle, vehicle.TitleStatus, vehicle.Province, vehicle.City)
    .ToLowerInvariant();

Live from api/TheYard.Domain/Shared/Auction/VehicleSearchIndex.cs, region text, read from this build at 99df7a8.

/// <summary>
/// The indexed text for a vehicle, or a freshly computed one when the
/// vehicle is not in the index. The fallback matters: the bid overlay
/// rebuilds each vehicle with `with`, and a test can hand the filter a
/// vehicle this index never saw. Keying by id rather than by reference is
/// what makes the overlay free here, because an overlay only rewrites the
/// bid figures and never the text.
/// </summary>
public string For(Vehicle vehicle) =>
    _byId.TryGetValue(vehicle.Id, out string? text) ? text : TextFor(vehicle);

Live from api/TheYard.Domain/Shared/Auction/VehicleSearchIndex.cs, region lookup, read from this build at 99df7a8.

Compiling the filter once (api/TheYard.Domain/Shared/Auction/VehicleFilter.cs):

/// <summary>
/// Turns this filter into a predicate, doing once whatever does not depend
/// on the vehicle. That is the query's tokens: lowercasing and splitting
/// them inside the loop meant repeating the same two allocations for every
/// row scanned, which on the synthetic 100,000-row dataset is 100,000
/// copies of a string the user typed once (ADR: The search index).
///
/// <paramref name="index"/> is optional so that a caller with one vehicle
/// can read <c>filter.Matches(vehicle, clock)</c>. Without it the searchable
/// text is computed per vehicle.
/// </summary>
public Func<Vehicle, bool> Compile(AuctionClock clock, VehicleSearchIndex? index = null)
{
    string[] tokens = string.IsNullOrWhiteSpace(Query)
        ? []
        : Query.ToLowerInvariant().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
    return vehicle => MatchesQuery(vehicle, clock, tokens, index) && MatchesFields(vehicle, clock);
}

Live from api/TheYard.Domain/Shared/Auction/VehicleFilter.cs, region compile, read from this build at 99df7a8.

The scan, and why the status is checked separately:

/// <summary>
/// Every token must be held by the vehicle's searchable text, as the start of a word or, under
/// three characters, anywhere (VehicleSearchIndex.Holds). The
/// text splits in two: the part that never changes, which the index holds,
/// and the auction status, which the clock decides. A token that the
/// static part already satisfies never triggers the status computation, so
/// the common query pays for the hash and the date math zero times instead
/// of once per row.
///
/// This is the same answer the single concatenated haystack gave, because
/// tokens are split on whitespace and so can never straddle the space
/// between the two parts.
/// </summary>
private static bool MatchesQuery(
    Vehicle vehicle, AuctionClock clock, string[] tokens, VehicleSearchIndex? index)
{
    if (tokens.Length == 0)
    {
        return true;
    }
    string text = index is null ? VehicleSearchIndex.TextFor(vehicle) : index.For(vehicle);
    string? status = null;
    foreach (string token in tokens)
    {
        if (VehicleSearchIndex.Holds(text, token))
        {
            continue;
        }
        status ??= AuctionSchedule.StatusFor(vehicle.Id, clock).ToString().ToLowerInvariant();
        if (!VehicleSearchIndex.Holds(status, token))
        {
            return false;
        }
    }
    return true;
}

Live from api/TheYard.Domain/Shared/Auction/VehicleFilter.cs, region query, read from this build at 99df7a8.

Where the two meet (api/TheYard.Application/Shared/Auction/Stock.cs):

/// <summary>
/// Vehicles matching <paramref name="filter"/> (statuses derived from <paramref name="clock"/>),
/// ordered by <paramref name="sort"/>, paged by <paramref name="limit"/>/<paramref name="offset"/>,
/// with the total counting every match. <paramref name="overlay"/> (everybody's bids and the
/// room's) is laid on before filtering, so price bounds and the price sorts see the figures
/// the page displays.
/// </summary>
public async Task<SearchResult> SearchAsync(
    VehicleFilter filter,
    AuctionClock clock,
    VehicleSort sort = VehicleSort.EndingSoonest,
    int limit = int.MaxValue,
    int offset = 0,
    ListingOverlay? overlay = null,
    CancellationToken cancellation = default)
{
    var (warm, catalogue) = await ReadyAsync(cancellation);
    offset = Math.Max(0, offset);
    limit = Math.Max(0, limit);
    if (CatalogueFilterResolver.Resolve(filter, clock, warm.Facets) is not { } resolved)
    {
        return new SearchResult(0, []);
    }

    // #region overlay
    // A bid or the room moves a price, and the store holds the dataset's figure. When the move
    // can change which vehicles match or where they sort, the store leaves those vehicles out,
    // they are worked out here from their raised figures, and the two ordered lists are merged
    // at the page. Otherwise the store's page is the page, and the moves are laid on its rows.
    bool overlayMatters = overlay is { Ids.Count: > 0 }
        && (sort is VehicleSort.PriceAsc or VehicleSort.PriceDesc or VehicleSort.MostBids
            || filter.PriceMin is not null || filter.PriceMax is not null);
    if (!overlayMatters)
    {
        var (total, rows) = await _listing.StorePageAsync(catalogue, resolved, sort, offset, limit, cancellation);
        return new SearchResult(total, [.. rows.Select(entry => Finish(entry.Vehicle, warm, overlay))]);
    }

    var matches = filter.Compile(clock);
    var moved = await _listing.FindEntriesAsync(catalogue, overlay!.Ids, cancellation);
    var raised = moved
        .Select(entry => entry with { Vehicle = overlay.Apply(entry.Vehicle) })
        .Where(entry => matches(entry.Vehicle))
        .OrderBy(entry => Key(entry, sort, resolved.SinceAnchorMs))
        .ToList();
    int skip = Math.Max(0, offset - raised.Count);
    int take = (int)Math.Min(int.MaxValue, (long)offset + limit - skip);
    var (storeTotal, stored) = await _listing.StorePageAsync(catalogue, resolved with { Exclude = overlay.Ids }, sort, skip, take, cancellation, moved);
    return new SearchResult(
        storeTotal + raised.Count,
        // The raised vehicles already stand at their price and the store's rows are none of
        // the moved ones, so nothing is laid on twice.
        [.. Merge(stored, raised, sort, resolved.SinceAnchorMs, skip, offset, limit).Select(entry => Finish(entry.Vehicle, warm, null))]);
    // #endregion overlay
}

/// <summary>
/// The page of the merged order: the store's rows from <paramref name="skip"/> on and every
/// raised vehicle, walked together. A row's place is how many store rows and raised vehicles
/// came before it; a raised vehicle that sorts before the first fetched row is counted but
/// never on the page, because at most <paramref name="raised"/>'s count of them can precede it.
/// </summary>
private static IEnumerable<CatalogueEntry> Merge(IReadOnlyList<CatalogueEntry> stored, IReadOnlyList<CatalogueEntry> raised, VehicleSort sort, long since, int skip, int offset, int limit)
{
    int s = 0, r = 0;
    long place = skip;
    while ((s < stored.Count || r < raised.Count) && place < (long)offset + limit)
    {
        bool takeRaised = r < raised.Count
            && (s >= stored.Count || Key(raised[r], sort, since).CompareTo(Key(stored[s], sort, since)) < 0);
        var next = takeRaised ? raised[r++] : stored[s++];
        if (place >= offset)
        {
            yield return next;
        }
        place++;
    }
}

/// <summary>The order every store sorts by, as one comparable key: the segment band, the order's figure, and the expansion's place.</summary>
private static (int Band, long Figure, int Seq) Key(CatalogueEntry entry, VehicleSort sort, long since)
{
    var vehicle = entry.Vehicle;
    if (sort == VehicleSort.EndingSoonest)
    {
        var slot = CatalogueSlot.For(vehicle.Id);
        return slot.SegmentAt(since) switch
        {
            CatalogueSegment.Live => (0, slot.EndOffsetMs, entry.Seq),
            CatalogueSegment.Upcoming => (1, slot.StartOffsetMs, entry.Seq),
            _ => (2, -slot.EndOffsetMs, entry.Seq),
        };
    }
    return sort switch
    {
        VehicleSort.PriceAsc => (0, CatalogueSlot.PriceOf(vehicle), entry.Seq),
        VehicleSort.PriceDesc => (0, -CatalogueSlot.PriceOf(vehicle), entry.Seq),
        VehicleSort.Condition => (0, -(long)Math.Round(vehicle.ConditionGrade * 1_000), entry.Seq),
        VehicleSort.MostBids => (0, -vehicle.BidCount, entry.Seq),
        _ => (0, 0, entry.Seq),
    };
}

Live from api/TheYard.Application/Shared/Auction/Stock.Search.cs, region search, read from this build at 99df7a8.

Consequences

  • Startup does slightly more work: one lowercase string per vehicle, held for the process's life. At a hundred thousand rows that is a few megabytes, traded for the allocations above. On a container with 1.5 GB it is not close to a concern; on a dataset ten times larger it would be worth revisiting, and the honest answer at that size is a real inverted index rather than a bigger string per row.
  • A query whose tokens are all auction statuses ("live", "ended") still pays for the hash and the date math per row, because it must. That case did not get faster and the numbers above show it.
  • The index is built once and never invalidated, which is correct only because the dataset never changes after load. A system where vehicles are edited would need the index to change with them, and that is a different design: this one is right for a read-only dataset and would be wrong for a mutable one.
  • VehicleFilter.Matches is now Compile(clock)(vehicle). A caller in a loop that keeps using it gets the old cost, so the scan is the one place that matters and the one place that was changed.

Where it sits

The work is Domain code (VehicleSearchIndex.cs and VehicleFilter.Compile), built once by Application's InventoryService when the catalogue loads. The index holds only what cannot change while the process runs, each row's lowercase text; auction status stays out because the clock changes it. The price is a few megabytes held for the life of the process, for a speedup no visitor could measure on the live site. A catalogue that changes after load, or one ten times larger, would need an index that updates with its rows or a real inverted index.

Files

Addendum, 2026-09-17: the facets are built with the index

The index exists because a per-request walk over a hundred thousand rows is work that never changes its answer, and the same was true of a neighbour it left alone. /api/facets, the four sorted distinct lists behind the filter dropdowns, walked the whole catalogue four times on every call, 12 ms on the live container by the proof card's own measurement at 1.0.0.94, for an answer fixed the moment the catalogue loads. And the page asked for it more than it needed to: the effect that fetched the facets ran on every listing refresh, which on the inventory page is four times a minute, so an idle minute signed out was four listing reads and four facet reads (the runner's measurement on 1.0.0.139, mentor\logs\lane0917-963-perflane-measure.log).

Two changes, shipped as 1.0.0.142. The facets are built in BuildAsync beside the dictionary and the index, for the reason those two are, and Facets() hands back that one instance; StockTests holds it by reference equality, which is the fact worth holding, since a rebuild would return a new object with the same values and a value comparison would not notice. On the page the effect asks until the facets have landed and then returns before it asks: the reload nonce stays in its dependency list so a first fetch that failed, the API still booting under npm start, is tried again with the listing, and once there is an answer nothing asks again. No cache middleware and no memory cache: the catalogue is immutable for the life of the process and the facets are a field of it, which is the cheapest cache there is and the only one a reader has to trust.

/// <summary>
/// The values behind the catalogue's filters, read from the store once at warm-up and handed
/// back by reference, because they cannot change after the fill and walking the catalogue for
/// them on every request is the cost ADR: The search index took out (its addendum).
/// </summary>
public async Task<InventoryFacets> FacetsAsync(CancellationToken cancellation) => (await WarmTask(cancellation)).Facets;

Live from api/TheYard.Application/Shared/Auction/Stock.cs, region facets, read from this build at 99df7a8.

// The filter dropdowns' options (facets) come from the API, because the page only holds a
// slice of the data. If the request fails, the dropdowns are empty rather than broken.
//
// Asked until answered, then never again: the server builds the options once and they cannot
// change while the page is open (ADR-025). reloadNonce stays in the dependencies so a failed
// first try (the API still booting under `npm start`, say) is retried along with the listing.
useEffect(() => {
  // The dropdowns belong to the inventory too, so the landing page skips them.
  if (!needsListing || facets !== EMPTY_FACETS) return;
  const controller = new AbortController();
  fetchFacets(controller.signal)
    .then(setFacets)
    .catch(() => {});
  return () => controller.abort();
}, [reloadNonce, facets, needsListing]);

Live from src/app/hooks/useInventory.ts, region facets-once, read from this build at 99df7a8.

The server-side number is read off the container's own request ring (/api/admin/metrics, by_path) after twenty reads, before and after, and the idle minute is counted the same way as before; both are on the Performance page.

Addendum, 2026-10-05 (1.0.3.80): the schedule order

Steve asked why the listing was uneven on a warm site. Measured on the live containers, the server's own time for a page of a hundred vehicles was 406 ms at the median on the Azure SQL site and 692 ms on the Azure Cosmos DB site, with the listing taking 0.4 to 1.4 s through the edge. Timed on his machine by the shape of the query, the default listing took 90 to 100 ms, the same page sorted by price 35 to 45 ms, and one make with one row 25 to 30 ms. The difference was the default order itself: every request worked out all hundred thousand auction windows and sorted every match by them to keep a hundred.

A vehicle's window depends only on its id and the day's anchor, so for one day it never changes. What moves with the clock is which band each vehicle is in. ScheduleOrder holds the catalogue sorted twice, by end and by start, built once for each anchor, and reads the ending-soonest order off them at any instant: live by closest end, then upcoming by soonest start, then ended by most recent end, a tie in catalogue order. InventoryService keeps one per day and walks it until the page is full; the filter still runs down every row, because the total counts every match. Nothing is stored: the order is the schedule derived again and held in memory for the day it belongs to, so the rule that schedule facts are derived and never persisted still holds.

On the same machine the default listing went from 90 to 100 ms to 25 to 34 ms. ScheduleOrderTests holds the order to the full sort at every three hours across a week, ties included, and InventoryServiceTests holds the page and the total to the full sort under six filters and offsets.

Addendum, 2026-10-18: the search moved to the store

From 1.0.3.178 the site no longer builds this index. The searchable text is written once beside each vehicle in the store, and a typed word is a substring test there: CONTAINS on Cosmos DB's indexed search path, instr or CHARINDEX on the Catalogue table, each one still able to match a status word ("live", "ended") as the in-memory version did. The schedule order this record added is replaced by one index per order in each store. Both classes stay in Domain with their tests, unused by the site, because that change was held to leaving Domain as it was (ADR: The store does the work).

Enforced by

One rule in the rulebook cites this record, each held by a test on every release.

The rule What holds it In the last gate
The default listing reads its page off the day's schedule order, and that order is the full ending-soonest sort at every instant, ties included ScheduleOrderTests 152 of 152 passed
Store

The Yard, home

Steven StoutStaff .NET engineerRemote

Production .NET that stays up. Built with AI, measured on every version.

Steven Stout

Hi, I'm Steve. I build the systems that make delivery boring in the best way, then coach people inside them.

  • 200+

    production releases, none took the platform down

    Conway Investment Research, 2019 to 2024. Sole engineer for the first three years on a live financial advisory platform.

    See how
  • 50%

    shorter release cycle

    Storee Construction, 2024 to 2026. Four ASP.NET applications onto one .NET 10 platform on Azure, with a four-person team I hired and mentored.

    See how

01Verified

Steven Stout

A real person, and the work is mine.

  • Identity

    Checked by LinkedIn, not by me.

    LinkedIn verified my government ID.

  • Running system

    You are looking at it.

    Version 1.0.5.273 is live. Nothing ships unless it passes the automated gates first.

That's who I am. Here's how I work.

02Strengths

Ten strengths, each with the proof beside it. The numbers match my resume and LinkedIn, and the live ones are read from this site as you look.

  • 01

    Keeps production alive

    200+ releases on a live financial platform, and none took it down. Sole engineer for the first three years.

    See the Conway work

  • 02

    Simplifies messy systems

    Four ASP.NET applications onto one .NET 10 platform on Azure, and a release cycle 50% shorter.

    See the Storee work

  • 03

    Marries dev and infrastructure

    Blue-green releases at Storee that flipped in about 5 seconds with nobody signed out, and Azure Front Door at two employers.

    See this site's cloud

  • 04

    Designs data that holds up

    White-label clients on one shared database, the isolation built into the data, and no cross-client issues.

    See the Conway work

  • 05

    Keeps AI-written code honest

    15 quality numbers that may only improve: 273 releases in a row with none worse.

    See the quality numbers

  • 06

    Resourceful

    $30,000+ cut from Azure and vendor spend at Conway. This site's Azure bill is public, resource by resource.

    See the bill

  • 07

    Builds people up

    Hired and mentored a four-person team. 13 colleagues recommend me by name.

    Read the recommendations

  • 08

    Takes ideas to production

    This site: designed, built and run solo, with 352 versions measured through one gate.

    How it was built

  • 09

    Writes clearly

    Posts on real engineering problems, in plain words.

    Read the blog

  • 10

    Owns decisions

    153 decision records, each with its tradeoff and the call I made.

    See the decision records

Built with AI. Gated so quality never slides.

Steven Stout’s showcase: a used-vehicle auction on .NET and React, built and run by one engineer, live on Azure, with its decisions written down.

No quality number has gotten worse at any release since 1.0.5.1 on 10 November: 273 releases in a row.

One engineer, an AI agent and a gate that checks 15 quality numbers on every release. 352 versions measured, with every result public, the worst days included.

82 releases in the last 7 days, each through the same gate.

Async methods with no CancellationToken, may only fall

11091.0.3.1391.0.5.2731.0.4.115, the ratchet
Every number, on the Quality page

TheYard, right nowLive

Answering in

unread

02505007501,000

server time at p95, the usual five minutes of the last day.

Azure this month

unread

the bill, by resource, read from Azure. The Admin tab shows every line.

Since the last roll

unread

 

rolled in place by the pipeline, behind one gate.

People who have visited

unread

30 days agotoday

Scanners, my own tools' and my own reads left out.

03Start here

04Where teams are heading

How I see engineering with AI, and the setup on this site that backs it.

AI-augmented teams · Architecture and ownership

AI writes more of the code. Someone still has to own what ships.

Teams are going to be heavily AI-augmented. That moves the senior job toward architecture and technical ownership: deciding what to build in pieces small enough to verify, and owning what ships.

  • Task tracking will get automated too. Judgment stays human: seeing a design fail at scale before it does.
  • On this site the AI's first design held the whole catalogue in memory. I caught it when the App Service plan hit 82 per cent and moved the work to the store.

What the AI wrote, what I decided

07Tech stack

  •    
  •    
  •    

Read from the build, never typed by hand

What TheYard runs on

What we use, where it runs, its AWS twin, the version as built, and the file that proves it.

Cloud patterns, not one vendor: every Azure piece in this stack has a named AWS twin. Mapped, not yet run on AWS.

  • .NET 1114 projects
  • React 19.3TypeScript 7.0
  • Azure9 Bicep files
  • 11GitHub Actions workflows
The whole stack, with the file that proves each line

The last release the gate stopped was 1.0.5.258 on 2 December, at its browser 1 of 2 job.

08How it is built

09How it is run

10Who and why

Next step

11What has to work, where is it today, and what does success look like?

Book 20 minutes opens an email to me with those three questions in it, and I answer with a time.

Book 20 minutes

Your email app should have opened with this message. If it did not, copy it and send it from any mailbox.

Or message me on LinkedIn