openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

N+1 query problem in dynlinks.py (query_keys, ol_get_many_as_dict, get_isbn_editiondict_map)

Open WeiGuang-2099 opened this issue 7 months ago • 3 comments

Problem

While reviewing the codebase, multiple N+1 query patterns were identified in openlibrary/plugins/books/dynlinks.py and related files, particularly around resolving editions by identifiers (ISBN/LCCN) and fetching multiple documents. These can severely degrade performance during bulk operations or when handling arrays of identifiers.


1. get_isbn_editiondict_map + Edition.from_isbn (dynlinks.py:L572-L575, models.py:L424-L438)

get_isbn_editiondict_map iterates over ISBNs and calls Edition.from_isbn() for each one individually. Inside from_isbn, the code loops over multiple identifier forms (isbn_10, isbn_13, and optionally asin) and issues a separate site.things() call per form, followed by site.get() on the first match:

# models.py:L424-L438
for book_id in book_ids:
    if book_id == asin:
        query = {"type": "/type/edition", 'identifiers': {'amazon': asin}}
    else:
        query = {"type": "/type/edition", f'isbn_{len(book_id)}': book_id}

    if matches := web.ctx.site.things(query):   # one things() per identifier form
        return web.ctx.site.get(matches[0])     # one get() on match

This yields up to 3 DB/Infobase calls per ISBN:

  • things() for isbn_10 form
  • things() for isbn_13 form
  • get() when a match is found

For N ISBNs, the total call count grows to O(3N).


2. Hidden N+1 in ol_get_many_as_dict (dynlinks.py:L138-L141)

For standard keys, ol_get_many_as_dict correctly uses ol_get_many() to batch-fetch documents in a single call. However, keys containing an explicit revision suffix (e.g. /books/OL1M@1) fall through to a separate code path that calls site.get(key, revision) individually in a loop:

# dynlinks.py:L138-L141 (paraphrased)
for key in revision_keys:
    docs[key] = web.ctx.site.get(key, revision)  # one get() per versioned key

For N versioned keys, this results in N sequential get() calls with no batching.


3. query_keys per-identifier dispatch (dynlinks.py:L158-L168)

query_keys iterates over bib_keys and calls ol_query → web.ctx.site.things(query) for each identifier individually, with no grouping by identifier type:

# dynlinks.py:L158-L168 (paraphrased)
for bib_key in bib_keys:
    result = ol_query(bib_key)   # one things() per key

For a request containing N ISBNs, this issues N separate things() calls, even when all keys share the same identifier type and could be resolved in a single batched query.


Call sites (blast radius)

Edition.from_isbn is called in at least the following runtime paths:

Call site File Lines
Search ISBN redirect worksearch/code.py L710–L717
/isbn/<id> route handler openlibrary/code.py L705–L737
Books API dynlinks import fallback dynlinks.py L553–L581

Behavior or performance changes in from_isbn may therefore affect: search redirects, ISBN landing pages, and /api/books high-priority flows.

WeiGuang-2099 avatar Apr 12 '26 11:04 WeiGuang-2099

Thank you @WeiGuang-2099 for submitting this issue!

⚠️ Contributors, this issue will be ready to work on once:

  • [ ] Triage — maintainers will add Priority: * and Lead: @* to replace Needs: Triage and Needs: Lead
  • [ ] Needs: Investigation — the batching mechanism for site.things() queries needs confirmation before coding begins (see open questions below)
  • [ ] Needs: Breakdown — concrete implementation steps with target functions and acceptance criteria needed

Context

Code review confirmed all three patterns:

  • query_keys (dynlinks.py): iterates over bib_keys calling ol_query() → site.things() once per key. Infobase things() does not appear to support list/OR queries natively, so batching may require routing through Solr.
  • ol_get_many_as_dict (dynlinks.py): the @revision fallback issues site.get(key, revision) per key in a loop. This path is likely rare in practice but is a genuine N+1.
  • get_isbn_editiondict_map + Edition.from_isbn (dynlinks.py, core/models.py:403): from_isbn() issues up to two site.things() calls per ISBN (isbn_10 and isbn_13 forms). This path is only triggered for ISBNs not found by query_keys, so worst-case applies when many requested ISBNs are absent from OL.

Directly relevant precedent: issue #11205 documented an equivalent N+1 in process_result_for_details (per-document get_ia_availability() calls). Commit b5254026 resolved it by switching to a bulk Solr query — now reflected in the current add_availability() function in dynlinks.py. That approach may serve as a model for query_keys.

Tests exist at openlibrary/plugins/books/tests/test_dynlinks.py.

Issue Assessment

Open questions

  • Does infobase's site.things() support list/OR queries for a single field (e.g., {isbn_: ["9780140328721", "9780439064873"]})? If not, is Solr or parallel infobase calls the preferred batching path?
  • For ol_get_many_as_dict: how common is the @revision path in production requests? Is batching it worth the complexity cost?
  • For get_isbn_editiondict_map: Edition.from_isbn() contains ASIN/Amazon and staged import logic (allow_import). A batch refactor must explicitly preserve or consciously drop that behavior — what is the intended scope?

Action items

  • [ ] Confirm infobase batching capabilities (or document Solr as the preferred path) before implementation begins
  • [ ] Fill in the Requirements Checklist and Related files in the Breakdown section
  • [ ] Provide a benchmark baseline: observed query count at N=1, 5, 20, 50 (as outlined in repro steps) so the fix can be verified

Suggested breakdown

(Contingent on confirming the batching mechanism)

  • [ ] Batch query_keys ISBN/LCCN lookups — collect identifiers by type and issue one query per field type or route through Solr; use add_availability() as the model. Potentially Good First Issue once the batching path is confirmed and documented.
  • [ ] Batch get_isbn_editiondict_map — replace per-ISBN Edition.from_isbn() loop with a single query for all ISBN variants. Requires preserving ASIN/import interaction — not Good First Issue.
  • [ ] Evaluate ol_get_many_as_dict revision fallback — assess production frequency and decide whether a batch get-by-revision path is warranted or can be deprioritized. Could be a Good First Issue scoping task.
Full triage checklist (maintainers / Pam)
  • [ ] Triage — correct labels applied or removed: Needs: Breakdown, Needs: Investigation, Needs: Design, Needs: Staff Decision, Needs: Staff / Admin, Good First Issue, Blocked, Blocker
  • [x] Problem / opportunity — N+1 query patterns identified, audience (Books API callers) clear, actionable
  • [x] Scope — three distinct N+1 patterns in one file; well-bounded
  • [ ] Justification — qualitative impact stated but no quantitative data or urgency framing; no observed query counts attached
  • [ ] Success & testing criteria — repro steps suggest "query count stays constant" but no numeric target, test plan, or performance baseline defined
  • [ ] Proposal & breakdown — approach described conceptually but Requirements Checklist and Related files left blank; no concrete implementation plan
  • [x] If bug: environment & repro steps — repro steps present with curl commands and Python snippets; "local dev" environment noted
  • [ ] Risks, concerns, open questions — ASIN/import interaction with from_isbn not addressed; infobase batching capability unconfirmed
  • [x] Pam context — relevant code reviewed; related issue #11205 (precedent N+1 fix) and commit b5254026 reviewed; no duplicate found
  • [ ] References — no profiling data, benchmarks, or query logs attached

[!NOTE] This comment was automatically generated by Pam, Open Library's Project AI Manager, on behalf of @mekarpeles. Pam is designed to provide status visibility, perform basic project management functions and relevant codebase research, and provide actionable feedback so contributors aren't left waiting.

mekarpeles avatar Apr 12 '26 12:04 mekarpeles

I'd like to work on this issue. Could you assign it to me?

WeiGuang-2099 avatar Apr 12 '26 22:04 WeiGuang-2099

Hey @mekarpeles and @cdrini! I see @WeiGuang-2099 is ready to tackle the implementation, but this looks blocked on whether site.things() actually supports batching.

I'd love to help unblock this issue. I'm going to dig into the Infobase query parser today to see if it handles native OR queries, or if we should just recommend the Solr workaround from add_availability(). I'll report back with my findings so WeiGuang has a clear path forward!

harshgupta2125 avatar Apr 16 '26 11:04 harshgupta2125