Skip to content

perf: reference page, cached aggregates, maps, snapshot window and Postgres settings - #460

Merged
rafaelpessoap merged 9 commits into
mainfrom
perf/site-performance-2026-11-25
Nov 25, 2026
Merged

rafaelpessoap merged 9 commits into
mainfrom
perf/site-performance-2026-11-25

Conversation

@rafaelpessoap

@rafaelpessoap rafaelpessoap commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Five performance fixes from the production investigation of 2026-11-25. The site has very few users and a large dataset on a 1 vCPU / 4 GB host; the cost was in a few queries and in when background work runs, not in capacity.

Closes #455
Closes #456
Closes #457
Closes #458
Closes #459

What changes

  • Region snapshot: run in a night window, never during working hours #459 — snapshot at night. The weekly region snapshot timer starts a run only from 02:00 to 05:00 UTC, when the last completed one is at least 6 days 12 hours old (so it stays on the same weekday). It used to drift into Friday mid-morning and hold the only CPU for about ten minutes. A fresh install still runs at once; build:snapshot is unchanged. RFC-78 R12.
  • Maps: compute the map list once per snapshot, not on every map request #458 — maps. traitMapValues / mapValues read only the requested trait's rows instead of aggregating the whole snapshot on every request (the web prefetches a category, which fired 13+ identical 0.5 s aggregates at once). The list itself is cached 10 minutes per platform, viewer class and snapshot. RFC-76 R5, R6, R9.
  • Reference page: count and list a reference's records without scanning trait_records #456 — reference page. recordCount is sum(reference_traits.record_count), the trigger-maintained counter, instead of a scan of trait_records (4 s mean, 38 s max). The record list under the default added sort reads one filtered page per role through the existing per-reference indexes instead of materialising every record id first (24 s mean, 80 s max). Other sorts keep the previous shape. RFC-61 R4, RFC-63 R9.
  • Trait distribution and dashboard summary: never recompute a cache miss inside the request #457 — cached aggregates. cachedJson gains opt-in stale-while-revalidate: past its window an entry is answered at once and recomputed in the background. Opted in: the trait distribution, stats:dataset, the per-trait species counts, the coverage totals and the unfiltered coverage grid (filtered coverage keeps its plain 10-minute expiry, so request-built keys cannot pile up). A change of visibility (species / trait / level active, plant type) raises a cache epoch that invalidates every such entry at once, so nothing a viewer may no longer see is served stale. A failed background refresh is logged. RFC-10 R15, new RFC-33 R12, RFC-62 R5/R7, RFC-69 R5/R6, RFC-72 R1.
  • Tune Postgres for the production host (memory, JIT, parallelism) #455 — Postgres settings. shared_buffers=1GB, work_mem=16MB, maintenance_work_mem=256MB, random_page_cost=1.1, jit=off, max_parallel_workers_per_gather=0. effective_cache_size keeps its 4 GB default. Measured gain on one aggregate: 1,558 ms to 1,295 ms; the larger effect expected is from shared_buffers surviving the nightly dump.

Deploy notes

  • The first deploy recreates the postgres container (new flags): a few seconds of failed requests.
  • No migration.
  • scripts/deploy.sh now also flushes maps:*.

Verification

  • pnpm lint, pnpm typecheck, pnpm rfc:check: clean.
  • pnpm test on the integrated branch before the last commit: 329 files, 2,872 tests passed; the files touched by the last commit re-run and pass.
  • New tests: night window and 6.5-day rule; per-trait maps equal the list's slice on both platforms; reference count across primary / secondary / both roles / record_references / copies / withdrawals; page-by-page pagination of a reference against the expected list (3 viewers × 6 filters × 2 orders × 2 page sizes); stale-while-revalidate, single-flight, forget and epoch races; a deactivated level leaves a restricted reader's distribution on the next read.
  • One independent review of the local branch; its findings are fixed in the last commit.

Known limits

  • Production plans are verified only on a 200k-row fixture; EXPLAIN (ANALYZE, BUFFERS) on the 1.5 M-record reference follows the deploy and goes into the issue's Outcome.
  • A reference list filtered by a q that few of its species match still walks most of the index.
  • The first visitor after a deploy still pays each aggregate once, since the deploy flushes the caches.
  • The import CLIs hold no Redis handle and do not raise the cache epoch; the runbooks gain the manual step.
  • The trait page's "Counted at …" sentence changed wording; not checked visually (text only).

🤖 Generated with Claude Code

rafaelpessoap and others added 8 commits November 25, 2026 11:59
shared_buffers 1GB, work_mem 16MB, maintenance_work_mem 256MB,
random_page_cost 1.1, jit off and no parallel workers per gather, as
flags on the postgres service. effective_cache_size keeps its 4 GB
default, which already matches the host.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
RFC-78 R12: the timer starts a snapshot only from 02:00 to 05:00 UTC and when the last completed one finished at least 6 days 12 hours ago, so it stays on the same weekday; with no completed snapshot it still runs at once. The build:snapshot command is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ot (#458)

traitMapValues and mapValues restrict the three group-bys to the requested trait instead of listing every map; GET /api/maps is cached 600 s per platform, viewer class and snapshot time (RFC-76 R5, R6, R9).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…background (#457)

cachedJson gains an opt-in staleWhileRevalidate option (RFC-10 R15): the entry is fresh for ttlSeconds and kept 30 days longer; a read past the window answers the stored entry at once and starts one background fill through the single-flight map, whose failure is swallowed so the next read tries again. Only a never-computed key is computed inside a request. The generation / forgetCached guarantees of #417 hold for the background fill.

Opted in: the trait distribution (RFC-62 R7), the species counts per trait (RFC-62 R5), the coverage totals and grid (RFC-69 R5, R6) and stats:dataset (RFC-72 R1). The per-viewer dashboard entry and platform health keep their plain expiry.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… filtered coverage keeps its plain ttl (#457)

Security review of 8be72438.

- coverageMetrics opts in to staleWhileRevalidate only for the unfiltered entry; a filtered key is caller-supplied and keeps the plain 600 s expiry (RFC-69 R6).
- A staleWhileRevalidate entry stores the cache epoch (Redis counter cache:epoch) its caller read; an entry of another epoch, or of none, is computed inside the request instead of answered, and a fill from before a bump is not joined after it (RFC-10 R15, RFC-33 R12). bumpCacheEpoch is called, best-effort after commit, by PATCH /api/species/:id, /api/traits/:id and /api/traits/:id/levels/:levelId when they set active, and by POST /api/species/:id/plant-type and /plant-type/confirm.
- The trait page says what its computed time means instead of promising a lag of a few minutes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
getReference summed a scan of trait_records per visit (4 s mean, 38 s max in production). recordCount is now the sum of the reference's reference_traits counters (RFC-61 R9), every trait included; the number is unchanged for every state the application can produce.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
)

The referenceId list under the default added sort materialised every record id of the reference before sorting and limiting. Each way of naming the reference (primary, secondary, record_references) now yields its own filtered, cursor-bound page of limit + 1 ids in id order, and the existing query sorts and limits that union. The other sorts keep the previous shape.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Log a failed background cache refresh instead of swallowing it, flush
maps:* on deploy, add the cache-epoch step to the import runbooks and a
guide changelog entry for the new freshness of cached summaries.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

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: d0e5958a-2617-47fd-a80c-7b6c5639a8fa
  • 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

…eout (#456)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment