Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 28 additions & 37 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,43 +260,34 @@ Remaining limitations:

### Scalability

The brief puts no ceiling on catalog size, so the search path is measured against
synthetic catalogs much larger than the real one (100,000 and 1,000,000 albums),
in separate performance databases that no deployment touches. Headline numbers at
one million albums:

| Operation | 100,000 | 1,000,000 |
| --------------------------------------------------- | ------: | --------: |
| Selective artist search, relevance order | 2.6 ms | 11.7 ms |
| Broad search that matches every row | 16.3 ms | 83.7 ms |
| Complete broad `searchAlbums` request (with facets) | ~100 ms | ~580 ms |
| Page 500,000 rows in, cursor | - | 254 ms |
| Page 500,000 rows in, `OFFSET` | - | 1184 ms |
| Same page, row comparison plus a matching index | - | 0.08 ms |

What that says:

- Sorting, filtering and faceting stay in SQL, so the cost of one page does not
depend on how many pages came before it.
- Cursor paging discards before sorting instead of producing and throwing away
skipped rows, so it does not grow with depth the way `OFFSET` does: 254 ms
against 1184 ms at 500,000 rows in. It is not constant time, though - with no
index on the sort key it still scans and sorts the tail.
- A matching `(lower(title), id)` index - 47 MB at one million albums - only pays
off together with the row comparison `(a, b) > (x, y)` that turns it into an
index condition: 0.08 ms. With the predicate `searchAlbums` runs today, an OR,
the same index gives 322 ms, slower than the 254 ms without it. The index and
the predicate have to change together.
- The GIN index is worth 5-6x on selective search, and is correctly bypassed for
a query that matches most of the catalog.
- Neither the composite indexes nor the row comparison for the album sorts are in
the schema yet - the seven sort modes would need several indexes, each costing
write time and 47 MB. That work is
[#74](https://git.ntnu.no/IT2810-H26/T19-Project-2/issues/74).

The method, the full tables, the query plans and the reproduction steps are in
[docs/scalability.md](docs/scalability.md). The scripts are read-only and
committed: `server/scripts/benchmark.sh` runs all of them.
The search path is measured against synthetic catalogs of 100,000 and 1,000,000
albums in separate performance databases. At one million albums, selective artist
search took 11.7 ms, while a broad search matching every row took 83.7 ms. A full
broad `searchAlbums` request with facets took about 580 ms because counts and
facets cover the full matching set.

Issue #74 adds composite cursor indexes for title, release year and rating sorts.
At a 500,000-row depth, a local benchmark measured indexed cursor pages at
0.09–8.01 ms; the earlier OR predicates took 274 ms–9.70 s, and `OFFSET` took
79–752 ms. The six indexes occupy about 508 MiB on a million-row catalog. Their
individual sizes are measured with `pg_relation_size`:

| Sort index | Size |
| ---------------------------------- | ------: |
| `album_title_lower_id_idx` | 88 MiB |
| `album_title_lower_desc_id_idx` | 88 MiB |
| `album_release_year_asc_id_idx` | 68 MiB |
| `album_release_year_desc_id_idx` | 68 MiB |
| `album_average_rating_asc_id_idx` | 94 MiB |
| `album_average_rating_desc_id_idx` | 102 MiB |

A million-row seed took 151 s with the indexes on PostgreSQL 18.6. Importing the
500-album MusicBrainz snapshot into that catalog took 6.43 s (500 new, 0
matched). The earlier seed-only measurement before the indexes was 88.91 s.
These timings are hardware-dependent; [the method, query plans and reproduction steps](docs/scalability.md)
explain the measurements and tradeoffs. The benchmark runner is
`server/scripts/benchmark.sh`; the cursor-index benchmark modifies ratings only
in a disposable database whose name ends in `_perf`.

### Accessibility

Expand Down
146 changes: 73 additions & 73 deletions docs/scalability.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ This document holds the method, the full tables and the plans behind them.

## Method

- PostgreSQL 18.3, Fedora, 15 GB RAM developer laptop, unix socket, warm cache.
Every query was run five times and the median is reported; paging and HTTP
were run three times because they take longer. Timings vary by roughly 10-30 %
between runs on this machine.
- Earlier search/filter measurements used PostgreSQL 18.3 on Fedora (15 GB RAM,
unix socket); the #74 cursor-index measurements used PostgreSQL 18.6 on macOS
through Homebrew. The #74 500,000-row plans are single local runs, so timings
vary with cache and hardware. Use the query plans and relative work as the
primary evidence, not the exact milliseconds.
- 100,000 and 1,000,000 deterministic albums. Seeding took **10 s** and **95 s**.
The 100,000-album database is 41 MB with a 11 MB GIN index; the
1,000,000-album database is 350 MB with a 75 MB GIN index (489 MB total).
Expand All @@ -23,12 +24,12 @@ This document holds the method, the full tables and the plans behind them.
dataset. The 500,000-row case is a deep page and needs the 1,000,000-album
database, so it is passed explicitly with `-v offset=500000`. A depth larger
than the table is rejected rather than measured against an unset cursor.
- The scripts are committed and read-only: `server/scripts/benchmark.sh` runs all
of them. It checks the name in the URL _and_ asks the server for
`current_database()`, because a `dbname` parameter or a service file can point
the connection somewhere else; both must end in `_perf`. The check matters
because the index experiments take an exclusive lock on `album`. Seeding is a
separate, destructive step and is deliberately not part of the script.
- `server/scripts/benchmark.sh` checks the name in the URL and asks the server
for `current_database()`, because a `dbname` parameter or service file can
point the connection somewhere else; both must end in `_perf`. Most benchmark
queries only read data, but `paging-index-perf.sql` writes a deterministic
`average_rating` pattern so rating sorts include rated and unrated rows.
Seeding and importing are separate from the benchmark.
- These results were measured on a laptop, not on the VM. The VM runs the same
PostgreSQL major version, but the numbers are hardware-specific and should be
read as orders of magnitude and plan shapes rather than as VM guarantees.
Expand Down Expand Up @@ -68,12 +69,12 @@ Without the index PostgreSQL falls back to a parallel sequential scan that reads
every row and discards all but the matches. The ratio is not larger because the
synthetic artist name repeats often; a rarer term gains more.

## Paging depth: cursor vs OFFSET
## Baseline before #74: cursor vs OFFSET

`server/scripts/paging-perf.sql` compares the keyset page `searchAlbums` runs with
the `OFFSET` alternative, for the same rows and the same order (`TITLE_ASC`).

The keyset predicate is the one `afterCursor` builds in
Before #74, `afterCursor` used the following predicate in
`server/src/search/search.ts`:

```sql
Expand Down Expand Up @@ -108,65 +109,58 @@ and at 500,000 the sort spills 12 MB to disk. The cursor page does not do that,
which is why it is slightly _faster_ at 500,000 than at 50,000 - the filter leaves
fewer rows to sort.

It is still not constant time, and the reason is worth stating plainly: there is
no index on the sort key, so the keyset query also scans and sorts the remaining
rows. Keyset is faster because it discards before sorting, not because the scan
is avoided. Any claim that cursor paging is depth-independent needs the index as
well, which is what the next section measures.

## The index that paging wants - and the predicate it needs

`server/scripts/paging-index-perf.sql` creates the missing index inside a
transaction, measures three queries, and rolls the transaction back, so the
schema is unchanged afterwards:

```sql
CREATE INDEX album_title_lower_id_perf_idx ON album (lower(title), id);
```

At one million albums the index is **47 MB**. Same index, same depth, three
predicates:

| Dataset | Rows already scrolled | OR (what `searchAlbums` runs) | Row comparison | OFFSET |
| --------- | --------------------: | ----------------------------: | -------------: | -----: |
| 100,000 | 50,000 | 32 ms | 0.09 ms | 15 ms |
| 1,000,000 | 50,000 | 33 ms | 0.08 ms | 16 ms |
| 1,000,000 | 500,000 | 322 ms | 0.08 ms | 154 ms |

The row comparison becomes an index condition and reads 20 entries at any depth:

```
Limit (cost=0.42..4.24 rows=20) (actual time=0.070..0.092 rows=20 loops=1)
-> Index Scan using album_title_lower_id_perf_idx on album
Index Cond: (ROW(lower(title), id) > ROW('synthetic album 549998'::text, 549998))
```

The OR form cannot use the index condition, so it walks the index and filters
every entry it passes - 500,000 of them at this depth, each with a heap lookup:

```
-> Index Scan using album_title_lower_id_perf_idx on album (actual time=323.604..323.620 rows=20)
Filter: ((lower(title) > 'synthetic album 549998'::text) OR (...))
Rows Removed by Filter: 500000
```

At 500,000 rows in, that is **322 ms - slower than the 254 ms without any index**,
because a sequential scan reads the table in order while the filtered index scan
jumps around it. An index on the sort key is only worth its 47 MB together with
the row comparison; on its own it makes this query worse. `OFFSET` does use the
index, but it still walks and discards every skipped entry:

```
Limit (actual time=180.073..180.083 rows=20 loops=1)
-> Index Scan using album_title_lower_id_perf_idx on album (actual time=0.027..169.267 rows=500020 loops=1)
```

That pairing is the shape the architecture decision describes. The index is not in
the schema yet: the seven sort modes would need several composite indexes, each
one costs write time on seed and import, and the extra 47 MB per index is a
bærekraft tradeoff that deserves its own measurement and review. It is filed as a
follow-up rather than slipped into this milestone, and the numbers above are the
argument for doing it - as one change, not two.
This was still not constant time because there was no index on the sort key.
The index and predicate changes in #74 address that baseline for unfiltered
browse sorts.

## Composite indexes for cursor sorts (#74)

The search path now uses composite B-tree indexes that match each supported
browse order and its stable `album.id` tie-breaker. Title uses one
`(lower(title), id)` index, which PostgreSQL can scan in either direction.
Nullable release-year and rating sorts have separate ASC and DESC indexes with
nulls last. The query uses row comparisons for non-null cursor ranges. For a
nullable cursor with a value, it fetches the next non-null rows and a bounded
batch from the null partition separately, then merges those small batches. This
preserves nulls-last ordering without an `OR ... IS NULL` predicate that scans
the deep prefix of an index.

`server/scripts/paging-index-perf.sql` compares the former OR predicate, the
indexed cursor query, and `OFFSET` for six browse orders at 50,000 rows in (or
500,000 with `-v offset=500000`). In a local 1,000,000-row run at 500,000 rows
in, the indexed cursor queries took **0.09–8.01 ms**; matching plans used
composite indexes and read at most two page-sized ranges. The old OR queries took
**274 ms–9.70 s** in the same run, while `OFFSET` took **79–752 ms**. Timings
are one local run and vary with cache and hardware; the important result is the
plan shape and bounded index range for the cursor query.

There are six new sort indexes, totaling about **508 MiB** on a freshly seeded
1,000,000-album catalog. Their measured sizes after the seed and MusicBrainz
import were:

| Index | Size |
| ---------------------------------- | ------: |
| `album_title_lower_id_idx` | 88 MiB |
| `album_title_lower_desc_id_idx` | 88 MiB |
| `album_release_year_asc_id_idx` | 68 MiB |
| `album_release_year_desc_id_idx` | 68 MiB |
| `album_average_rating_asc_id_idx` | 94 MiB |
| `album_average_rating_desc_id_idx` | 102 MiB |

On this PostgreSQL 18.6 macOS run, seeding one million synthetic albums with
the indexes took **151 s**. Importing the committed 500-album MusicBrainz
snapshot into that catalog then took **6.43 s** (500 new, 0 matched). The
seed-only run before #74 took **88.91 s**; the indexed seed measured earlier
took **133.68 s** on a different run. These are single local measurements, not
VM guarantees, and import time depends on the catalog state. Faster browsing
costs disk space and write time; the indexes trade both for bounded keyset page
reads.

Index sizes were read from `pg_relation_size` for each named index. The seed and
import timings used the repository's `db:seed:large` and
`db:import:musicbrainz` commands against a disposable `*_perf` database on
PostgreSQL 18.6. Import timing starts after the seed has completed and does not
include fetching the MusicBrainz snapshot.

## Prefix search (#55)

Expand Down Expand Up @@ -198,8 +192,8 @@ The read-only benchmark is available in

```bash
# A separate database. Never the application's `crate` database.
createdb crate_perf
export DATABASE_URL='postgres://t19:password@127.0.0.1:5432/crate_perf'
createdb crate_1000000_perf
export DATABASE_URL='postgres://t19:password@127.0.0.1:5432/crate_1000000_perf'

pnpm --filter @t19/server db:migrate
ALBUM_COUNT=1000000 pnpm db:seed:large
Expand All @@ -214,6 +208,12 @@ psql "$DATABASE_URL" -v offset=500000 -f server/scripts/paging-perf.sql
psql "$DATABASE_URL" -v offset=500000 -f server/scripts/paging-index-perf.sql
```

`paging-index-perf.sql` deterministically fills `average_rating` in the
throwaway performance database so rated and unrated cursor paths can be
measured; it is not read-only. It refuses databases without the `_perf` suffix.
`db:seed:large` is destructive to its configured database and should only be
run against the separate performance database.

`psql` does not read `DATABASE_URL` by itself; it is passed explicitly above.
The same variable is what the API reads, so the HTTP numbers come from a server
built against the performance database:
Expand Down
6 changes: 6 additions & 0 deletions server/drizzle/0007_album_sort_cursor_indexes.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
CREATE INDEX "album_title_lower_id_idx" ON "album" USING btree (lower("title"),"id");--> statement-breakpoint
CREATE INDEX "album_title_lower_desc_id_idx" ON "album" USING btree (lower("title") DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint
CREATE INDEX "album_release_year_asc_id_idx" ON "album" USING btree ("release_year","id");--> statement-breakpoint
CREATE INDEX "album_release_year_desc_id_idx" ON "album" USING btree ("release_year" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint
CREATE INDEX "album_average_rating_asc_id_idx" ON "album" USING btree ("average_rating","id");--> statement-breakpoint
CREATE INDEX "album_average_rating_desc_id_idx" ON "album" USING btree ("average_rating" DESC NULLS LAST,"id" DESC NULLS LAST);
Loading