Skip to content

perf: page /payments from the index and cut page-load waterfalls - #1182

Open
Klakurka wants to merge 2 commits into
masterfrom
ccr-b62297cf-awgd35-payments-perf
Open

Klakurka wants to merge 2 commits into
masterfrom
ccr-b62297cf-awgd35-payments-perf

Conversation

@Klakurka

@Klakurka Klakurka commented Dec 3, 2026

Copy link
Copy Markdown
Member

Related to #1122, #1072

Description

Why /payments was slow (#1122). Every page ran:

SELECT * FROM Transaction
WHERE addressId IN (<user's addresses>) AND isPayment = 1
ORDER BY timestamp DESC LIMIT 10 OFFSET n

The only usable index was (addressId, isPayment), so MariaDB read every payment row of the user and filesorted all of them to keep 10. ANALYZE on a 300k-payment user shows r_rows: 300000 and Using filesort for page 0. Each page change and re-sort paid that cost again, as did the count request that was re-sent with every page. The cost grows linearly with a merchant's history, which is why #1124's index and parallel counts weren't enough. The "sort by button" path was much worse (5+ s). It joined and JSON_ARRAYAGG'd every price link and invoice of every payment before sorting.

Changes

  1. Index (addressId, isPayment, timestamp), replacing (addressId, isPayment). The new index covers every lookup the old one served.
  2. Paging by timestamp from the index (fetchTxIdPageByTimestamp). Each address's payments are already in timestamp order in the index, so a page is the merge of each address's first offset + limit entries. That is one UNION ALL subquery per address, and the outer query keeps limit rows. Page 0 now reads (#addresses × 10) index entries, however many payments the user has. Above 200 addresses it falls back to a single query, which is still index-only thanks to the new index. Only the page's txs are then loaded with prices/buttons/invoices. The button page's tx list (/api/paybutton/transactions/[id]) uses the same path.
  3. Sort by button name: the page is chosen from (tx, button) id pairs, and prices and invoices are fetched only for those txs. This path now also honours the year/date filters. Before, the count applied them and the list didn't.
  4. Payment years: MIN/MAX per address (Using index for group-by) plus one index probe per candidate year, instead of reading every tx of the user. The list now only includes years with payments, since it feeds the payments filter.
  5. Stable ordering: ties are broken by id, so payments that share a timestamp (or amount) are no longer repeated or skipped across pages.
  6. Button filters resolve the user's addresses in one query instead of two.

Navigation / client (#1072)

  • /payments no longer blocks the table on /api/paybuttons and /api/transaction/years. It used to fetch those one after the other and only then start loading payments. They are now fetched together, alongside the table.
  • /payments no longer fetches the first page twice on mount, and only re-fetches the count when the filters change, not on every page change and sort.
  • The button page fetches its tx page and count in parallel instead of one after the other.
  • getServerSideProps (runs on every navigation): fetchUserWithSupertokens fetches the DB profile and the supertokens-core user in parallel, which affects most pages. The payments and account pages also fetch their other data in parallel.

Can /payments use the payment summary table from f9d06f2? I looked at this and decided not to. The summary stores 15-minute buckets, so it can't produce the rows of a page. For the count, it would only be correct for addresses whose summary is built and not stale, and the count must match the listing exactly. With the new index the count is an index-only range scan (~50 ms for 300k payments, 14 ms for a year), and the client now only asks for it when the filters change. That left little to gain for the staleness risk. If counts for very large merchants still show up, SUM(paymentCount) over built summaries is the next step.

Measurements

Local MariaDB (latest image, 1 GB buffer pool). User with 300k payments (+30k outgoing txs) over 6 addresses/buttons, 600k txs belonging to other users, 2 price links per tx, 500 invoices. Service-level timings, median of 3 warm runs. "Cold" means first call after a DB restart with the OS page cache dropped.

call before after
page 0, newest first (the default view) 365 ms (cold 723 ms) 7 ms (cold 17 ms)
page 0, 100 rows 340 ms 14 ms
page 1000 485 ms (cold 582 ms) 49 ms (cold 66 ms)
last page (page 29000) 799 ms 255 ms
page 0, oldest first 307 ms 5 ms
sorted by button name 5356 ms 608 ms
filtered by year 82 ms 8 ms
filtered by one button 8 ms 7 ms
count, year filter 64 ms 14 ms
count, date range 27 ms 7 ms
count, no filter 51 ms 52 ms (now fetched once per filter change)
payment years 74 ms 6 ms
button page txs (242k txs, page 0) 374 ms 5 ms
sorted by amount / network 311 / 490 ms 387 / 583 ms (unchanged path, see remarks)

All of these grow linearly with history before the change and stay flat after (except deep pages and the remarks below). That fits the reporter's 5–20 s on accounts with far more payments.

Correctness check: a throwaway script compared the old and new fetchAllPaymentsByUserIdWithPagination on that dataset for 13 combinations of page, size, sort direction, button/year/date filters, amount sort and button-name sort, plus count and years. All results were identical, apart from tie order where the old query had none.

Test plan

  • make github-test-unit: 19 suites, 416 tests pass. New unit tests cover the merged-page SQL (per-address limits, ranges, direction, fallback above the address limit, no query when nothing can match), page order after hydration, single-query button address lookup, the button-name path (filters applied, prices not joined), payment years, and the button tx page.
  • Integration tests against MariaDB + Redis + supertokens: 4 suites, 115 tests pass. New tests/integration-tests/paymentsPagination.test.ts pages through every payment of a user, with ties within and across addresses and page sizes 1/4/7/100, in both directions and through both the merged and the single-query path. It checks the result against a reference ordering, plus counts, button/year filters, button-name order (once per button), amount sort stability, years and the button tx page.
  • prisma migrate diff between the migrations and the schema shows no difference. The migration applies on the 930k-tx dataset in ~1 s.
  • npx tsc --noEmit -p .: no new errors in the touched files. The repo has existing errors elsewhere.
  • Not exercised in a browser: the client-side changes on /payments (no blocking on the filter data, single initial fetch, cached count). Worth a quick manual check that filters, paging, sorting and CSV export still behave.

Remarks

  • Sorting by amount or network still sorts all of the user's payments (~0.4–0.6 s at 300k). Those sorts are rarely used. Fixing them needs either an index per sort key or treating network as (network, timestamp).
  • Deep pages cost O(offset) index entries, about 255 ms for the last page at 300k. Keyset pagination would fix that but needs UI changes.
  • The migration builds an index on Transaction. MariaDB does this online (in-place, no lock on writes), but on a large production table it will take a while.
  • Payment years use UTC years, as before (YEAR(FROM_UNIXTIME()) on a UTC server). They now come from payments only.

Generated by Claude Code

A page of /payments ran `WHERE addressId IN (<user's addresses>) AND
isPayment ORDER BY timestamp LIMIT 10 OFFSET n`. With an index on
(addressId, isPayment) only, MariaDB read every payment row of the user and
sorted them all to keep ten, so each page, page change and re-sort cost
time proportional to the merchant's whole history.

- Index (addressId, isPayment, timestamp), replacing (addressId, isPayment).
- Pages in timestamp order are the merge of each address's own index range,
  read only as far as the page reaches (one UNION ALL subquery per address,
  falling back to one query over all addresses above 200 of them). Only the
  page's txs are then fetched with their prices, buttons and invoices. The
  button page's tx list uses the same path.
- Ordering by button name picks the page from (tx, button) pairs and fetches
  prices and invoices only for it, instead of joining and JSON-aggregating
  every price link and invoice of every payment before sorting. It now also
  applies the year and date filters, which the count already did.
- Payment years are found with one index lookup per address and per year
  instead of reading every tx of the user, and only count payments.
- txs with the same sort value are ordered by id, so they are neither
  repeated nor skipped across pages.
- Button filters resolve the user's addresses in one query instead of two.

Measured on a local MariaDB (1G buffer pool) with a user with 300k payments
over 6 addresses, warm (cold, after a restart and dropped page cache):
  first page, newest first  365ms (723ms) -> 7ms (17ms)
  page 1000                 485ms (582ms) -> 49ms (66ms)
  last page                 799ms         -> 255ms
  sorted by button name     5356ms        -> 608ms
  filtered to a year         82ms         -> 8ms
  count for a year           64ms         -> 14ms
  payment years              74ms         -> 6ms
  button page (242k txs)    374ms         -> 5ms
The results are identical to the previous implementation's for the same
inputs, except for ties, which are now ordered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019G564i2sNiHJYQR95m8zGq
- Payments page: the table no longer waits for the button and year lists,
  which are now fetched together; the first page isn't fetched twice on
  mount; and the payment count is only fetched again when the filters
  change, not on every page change and sort.
- Button page: the tx page and the tx count are fetched in parallel.
- getServerSideProps of most pages: the user profile and the supertokens
  user are fetched in parallel, and the payments and account pages fetch
  their other data alongside them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019G564i2sNiHJYQR95m8zGq
@coderabbitai

coderabbitai Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 43 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 31da54db-12f5-4f25-98c5-a9595879a453
Commits

Reviewing files that changed from the base of the PR and between f9d06f2 and 8a184e9.

Files selected for processing: 10

  • components/Transaction/PaybuttonTransactions.tsx
  • constants/index.ts
  • pages/account/index.tsx
  • pages/payments/index.tsx
  • prisma-local/migrations/20261203000000_payment_timestamp_index/migration.sql
  • prisma-local/schema.prisma
  • services/transactionService.ts
  • services/userService.ts
  • tests/integration-tests/paymentsPagination.test.ts
  • tests/unittests/transactionService.test.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants