Skip to content

Default sort=name for usage=unused (skip a wasted ORDER BY query_count) #541

Description

@nicolastakashi

Context

The default sort field for /api/v1/seriesMetadata is queryCount (descending), set in routes.seriesMetadata:

params := db.SeriesMetadataParams{
    ...
    SortBy:    "queryCount",
    SortOrder: "desc",
    ...
}

This is a great default for the UI's "what's getting queried most" view. But for the specific filter ?usage=unused, by definition every row in the result set has query_count = 0. The ORDER BY COALESCE(s.query_count, 0) DESC still runs — the sort node materialises and sorts the entire pre-LIMIT result set even though it's not breaking any ties (the rows come back in physical order anyway, after a fully wasted sort step).

For a high-throughput client that always sends usage=unused (e.g. a tooling layer that drops metrics deemed unused by the inventory), this is steady-state overhead with no observable benefit.

Proposal

When usage = "unused" and no explicit sortBy was supplied by the caller, default to name (which has a primary-key index — sort is a no-op against the existing index order):

// inside routes.seriesMetadata, just after parsing params:
if params.Usage == db.SeriesMetadataUsageUnused && req.FormValue("sortBy") == "" {
    params.SortBy = "name"
}

Equivalent in GetSeriesMetadata if preferred (centralises the rule in the DB layer rather than the HTTP layer).

The default for usage=all and usage=used stays at queryCount — that case has meaningful variance and the sort is useful.

Impact

For usage=unused callers without an explicit sort preference, the postgres sort step disappears entirely. On large result sets this is a measurable CPU saving plus a reduction in temp memory.

Acceptance criteria

  • ?usage=unused without an explicit sortBy returns rows sorted by name ascending (or in PK order, equivalent).
  • Explicit ?usage=unused&sortBy=queryCount continues to work unchanged.
  • EXPLAIN on the unused-default path no longer shows a Sort node.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestgoPull requests that update Go codegood first issueGood for newcomershelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions