[Epic] Migrate FastAPI SQL call paths to the async psycopg3 pool
Problem / Opportunity
The async PostgreSQL pool is available in openlibrary/core/async_db.py, and the yearly reading-goal feature is the first end-to-end migration example. Several FastAPI request paths still reach SQL through the synchronous database driver, either directly through a model or indirectly through a shared helper. Synchronous SQL can block FastAPI request processing, especially when called from an async def handler.
This epic tracks an initial audit of those SQL-backed FastAPI paths and proposes a migration order from easiest to hardest. Please review the inventory, difficulty estimates, and file counts and adjust them as needed.
Most Open Library catalog data is stored in Infobase. This work concerns direct SQL access to feature tables and related database-backed workflows; it does not move Infobase data to SQL.
Proposal and existing pattern
Migrate each selected FastAPI request path to the async psycopg3 pool while preserving existing web.py callers through synchronous bridges where needed. Follow docs/core/database.md and the yearly reading-goal implementation:
- Async model methods use the plain method name.
- Synchronous compatibility methods use a
_syncsuffix andasync_bridge.run. - FastAPI handlers call and await async model methods directly.
- Use
execute,fetch_all,fetch_one, andfetch_valfor single statements; useconnection()for multi-statement transactions.
Reference files:
openlibrary/core/async_db.pyopenlibrary/core/yearly_reading_goals.pyopenlibrary/fastapi/yearly_reading_goals.pyopenlibrary/plugins/upstream/yearly_reading_goals.pydocs/core/database.md
Initial endpoint inventory — easiest to hardest
File counts are rough estimates and include likely tests. Some groups share models and may be combined. The inventory includes two conditional import paths for review; they reach SQL only for particular inputs or workflows.
| Order | Endpoint group | FastAPI route(s) | Main SQL-backed code | Estimated files | PR |
|---|---|---|---|---|---|
| 1 | Check-ins | POST /works/OL{work_id}W/check-ins[.json]; DELETE /check-ins/{check_in_id} |
BookshelvesEvents methods called by fastapi/checkins.py |
4–6 | #13859 (merged) |
| 2 | Monthly login count | GET /api/monthly_logins.json |
get_unique_logins_since in core/admin.py |
3–4 | #13903 (merged) |
| 3 | Ratings | GET/POST /works/OL{work_id}W/ratings.json |
Ratings methods and the ratings summary helper |
4–6 | #13904 (merged) |
| 4 | Booknotes | POST /works/OL{work_id}W/notes[.json] |
Booknotes add/remove methods |
4–6 | #13922 (merged) |
| 5 | Follows / PubSub | GET/POST /people/{username}/follows.json; POST /account/login when action=follow:…; GET /partials/BPListsSection.json when list cards need subscription state |
PubSub methods, including subscribe, unsubscribe, get_following, and is_subscribed |
5–8 | #13957 (merged) |
| 6 | Reading State partial | GET /partials/ReadingState.json |
get_reading_state and its batch queries in Bookshelves, Ratings, and BookshelvesEvents |
6–9 | #13976 (merged) |
| 7 | Observations metrics | GET /observations.json |
get_observation_metrics and Observations aggregation queries |
4–7 | #14055 (merged) |
| 8 | Bookshelves API | GET/POST /works/OL{work_id}W/bookshelves.json |
Bookshelves and BookshelvesEvents, reached through shared helpers in plugins/openlibrary/api.py |
6–9 | #14069 (merged) |
| 9 | Public reading log | GET /people/{username}/books/{key}.json |
Bookshelves.get_users_logged_books; the method is async but still calls the synchronous database driver |
5–8 | #14076 (merged) |
| 10 | Bestbook awards | POST /works/OL{work_id}W/awards.json; GET /awards/count.json |
Bestbook, including the Bookshelves read-status check used during validation |
6–9 | #14112 (merged) |
| 11 | Author merge requests | POST /authors/merge.json |
CommunityEditsQueue calls reached through perform_merge_update |
5–8 | #14155 (merged) |
| 12 | Account anonymization | POST /account/anonymize.json |
Multiple SQL-backed models, including booknotes, ratings, observations, bookshelves, merge requests, and bestbooks | 8–12 | #14156 (merged) |
Conditional import paths for review
| Candidate | FastAPI route(s) | Condition | Estimated files |
|---|---|---|---|
| Books API import path | GET /api/books[.json] |
High-priority import behavior with applicable ASIN input | 5–9 |
| Import preview | GET/POST /import/preview.json |
Internet Archive import needs staged-item metadata | 6–10 |
Decision: We will leave these along for now. They are not part of the epic since they'll require more consideration and aren't in the critical path.
First migration: Check-ins
Start with:
POST /works/OL{work_id}W/check-insPOST /works/OL{work_id}W/check-ins.jsonDELETE /check-ins/{check_in_id}
These handlers currently call synchronous BookshelvesEvents methods to select, create, update, and delete events. Migrate the request path to async database access, preserve sync bridges for legacy callers, and add or update model and endpoint tests.
Notes
get_unique_logins_sinceis cached; preserve the existing cache behavior when migrating it.- The follow-related calls share
PubSubbut are used from several FastAPI modules. Include all listed call sites when migrating that model. - The public reading-log route awaits an async model method, but that method still uses synchronous SQL.
- Account anonymization and author merge combine SQL with broader account or Infobase workflows. Review transaction boundaries and preserve existing behavior.
- The legacy web.py observations write routes are not FastAPI endpoints. Keep their callers working if the shared model is migrated, but do not count those routes as FastAPI migration targets.
BookshelvesEvents.count_distinct_work_ids_by_user_type_and_yearand the reading-goal progress path already use async database access.
Acceptance criteria
For each migrated route group:
- The FastAPI request path no longer uses synchronous SQL access.
- Async model methods use the plain method name; sync compatibility methods use
_syncbridges withasync_bridge.run. - Existing web.py callers continue to work.
- Route behavior remains compatible, including authentication, authorization, response shape, validation, caching, and write semantics.
- Tests cover model queries and endpoint behavior.
- Add PostgreSQL integration tests where needed for query syntax, schema behavior, transactions, or PostgreSQL-specific features, following
docs/core/database.md. - Update the database guide if the migration establishes a reusable pattern.
- Put tests in the module's normal test file (
openlibrary/tests/core/test_<module>.py, e.g.test_observations.py), unit and integration tests together. Don't create new*_async.pytest files: once a model is migrated, "async" no longer distinguishes anything, and a second file splits one module's tests in two.
Before closing this epic
- [ ] Fold the remaining
*_async.pytest files into their module's main test file (everything will be async soon). Already done:test_observations.py(#14055),test_bookshelves.pyandtest_ratings.py(#14069),test_bestbook.py(#14112). Remaining:test_booknotes_async.py,test_bookshelves_events_async.py(intotest_bookshelves_events.py),test_follows_async.py,test_yearly_reading_goals_async.py. Update thetest_yearly_reading_goals_async.pyreference indocs/core/database.mdat the same time.
Stakeholders
- @RayBB — please review the endpoint inventory, difficulty ranking, and proposed first migration.
References
- Database guide:
docs/core/database.md - Async DB helpers:
openlibrary/core/async_db.py - Reading-goals reference:
openlibrary/core/yearly_reading_goals.py,openlibrary/fastapi/yearly_reading_goals.py, andopenlibrary/plugins/upstream/yearly_reading_goals.py - Sync bridge:
openlibrary/utils/async_utils.py
Thank you @Sanket17052006 for submitting this issue!
⚠️ Contributors, this issue will be ready to work on once:
- [ ] Triage — maintainers will add
Priority: *andLead: @* - [ ] Needs: Staff Decision — confirm whether the two "conditional import path" candidates (Books API import path, Import preview) belong in this epic, and whether the proposed migration order/difficulty estimates should be adjusted
Context
Codebase research confirms the inventory in this epic is accurate as of ada0335 (current master):
- The foundational async pool landed yesterday: PR #13676 "Add async psycopg3 pool support" (merged 2026-10-06), closing the gap this epic's "Problem/Opportunity" section describes.
- The reference implementation this epic points to is real and already follows the exact pattern it describes —
YearlyReadingGoalshas async methods (e.g.select_by_username_and_year) plus_syncbridges viaasync_bridge.run: https://github.com/internetarchive/openlibrary/blob/ada0335cdc9521a0c401931c814528ce7fd5da4c/openlibrary/core/yearly_reading_goals.py#L40-L46 - The proposed first migration target (check-ins) checks out exactly as described:
openlibrary/fastapi/checkins.py'sasync defhandlers call fully synchronousBookshelvesEventsmethods (select_by_id,create_event,update_event,delete_by_id): https://github.com/internetarchive/openlibrary/blob/ada0335cdc9521a0c401931c814528ce7fd5da4c/openlibrary/fastapi/checkins.py#L86-L132 — while one method on the same class,count_distinct_work_ids_by_user_type_and_year, is already async, matching the epic's note that this method and the reading-goal progress path are already migrated: https://github.com/internetarchive/openlibrary/blob/ada0335cdc9521a0c401931c814528ce7fd5da4c/openlibrary/core/bookshelves_events.py#L131-L145 get_unique_logins_since(group 2) is confirmed@cache.memoize-decorated and still synchronous, matching the epic's caching caveat: https://github.com/internetarchive/openlibrary/blob/ada0335cdc9521a0c401931c814528ce7fd5da4c/openlibrary/core/admin.py#L168-L178- All classes named in the inventory exist and match the described groups:
PubSub(openlibrary/core/follows.py),Bestbook,Observations,CommunityEditsQueue(openlibrary/core/edits.py),Booknotes,Ratings,Bookshelves. - This epic is a direct continuation of #13667 "Add async PostgreSQL access with Psycopg 3 (start: reading goal endpoint)", authored by @RayBB, which this same author (@Sanket17052006) is already assigned to. #13667's described deliverable (pool + reading-goal endpoint) now appears complete via PR #13676 and the merged #11816 "Migrate Yearly Reading Goals to FastAPI" — maintainers may want to confirm whether #13667 can be closed now that this epic exists to track the follow-on work.
Issue Assessment
Open questions
- [x] Does the async psycopg3 pool referenced as a prerequisite actually exist yet? (Answer: Yes — merged in PR #13676 on 2026-10-06.)
- [x] Does the yearly reading-goal reference implementation actually follow the async +
_syncbridge pattern described? (Answer: Yes, confirmed inopenlibrary/core/yearly_reading_goals.py.) - [ ] Should the two conditional import paths (Books API import, Import preview) be tracked inside this epic or split into a separate issue? (author explicitly asks for this decision)
- [ ] Are the per-group file-count and difficulty estimates in the inventory table acceptable as-is, or does a maintainer want them adjusted before sub-issues are cut?
🔔 Stakeholders
@RayBB — authored the prerequisite issue (#13667) this epic builds on, is tagged as its lead, and owns the FastAPI migration effort generally; best placed to confirm the migration order and the import-path scoping question.
Full triage checklist
- [x] Triage — correct labels applied (
Type: Epic,Module: FastAPI,Affects: Server,Affects: Database,Theme: Performance,Needs: Triage,Needs: Lead,Needs: Staff Decision) - [x] Problem / opportunity — clear: sync SQL in async FastAPI handlers blocks the event loop; builds on a just-merged prerequisite (#13676)
- [x] Scope — large by nature (epic), but broken into 12 ordered groups plus 2 explicitly-flagged edge cases rather than one undifferentiated task
- [ ] Justification — impact is stated qualitatively (blocking under load) but not quantified; acceptable for an epic but worth noting
- [x] Success & testing criteria — explicit acceptance criteria per migrated group, including test and documentation requirements
- [x] Proposal & breakdown — concrete inventory table, reference files, and a fully specified first migration (check-ins) with exact routes
- [ ] If bug: environment & repro steps — n/a, this is a refactor/epic, not a bug
- [x] Risks, concerns, open questions — author explicitly flags the import-path scoping question and asks for inventory review
- [x] Richy context — relevant code, prior PRs (#13676, #11816, #13156), and the originating issue (#13667) reviewed; no duplicate found
- [x] References — reference files and doc (
docs/ai/database.md) all verified to exist and match description
[!NOTE] This comment was automatically generated by Richy, Open Library's issue enrichment assistant, on behalf of @mekarpeles. This is NOT a sign-off. This issue needs lead review before work begins.
@Sanket17052006 nice work, I think it looks great. Do ahead and start opening PRs for the first few!
@Sanket17052006 feel free to open the next two in a row.
@Sanket17052006 btw please feel free to open keep opening new ones as we merge some in. Ideally 2-3 open at a time!
@Sanket17052006 look forward to the next 2 endpoints to be migrated and then a final PR to fold the tests in (see updated issue description)
@Sanket17052006 really great job here this is a huge win for our migration and it's impressive you carried it all the way though. We're good to close for now!