Cache (type_key, property_name) -> datatype lookups in find_datatype
Feature Request
Follow-up to #14078 / internetarchive/infogami#284, which @RayBB asked be filed separately: "the invalidation question deserves its own issue."
Problem / Opportunity
internetarchive/infogami#284 made Thing.get_property resolve only the matching property instead of all of them — 94 store lookups down to 2 on production's /type/edition. The remaining 2 are still paid on every call, and type schemas almost never change, so (type_key, property_name) -> datatype is cacheable.
Raised by @Prabh0608 in review on internetarchive/infogami#284.
Why it isn't a one-line dict
The headroom is now small (2 lookups, ~6 µs), so this is only worth doing if the invalidation is right:
- Type docs are editable at runtime. A process-lifetime dict has no invalidation path, so a type edit wouldn't take effect until every worker restarts. Infobase's existing doc cache doesn't have this problem because it is write-through:
dbstore.py:194puts every saved doc intoweb.ctx.new_objects, andcache.unloadhookpushes that intoglobal_cacheat the end of the request. A derived datatype cache isn't refreshed by that path and needs its own hook. - The key must carry site identity.
Thing._storeis aSiteStorebound to one site, so two sites defining the same type key must not share an entry. (@Prabh0608's point.) - Placement.
find_datatypeis a module-level function, so the obvious home for a dict is module scope — exactly the scope that's hard to invalidate. It probably belongs next to the existing layers incache.py.
Proposal
- Decide where the cache lives —
cache.pyalongside the existing layers, vs. local toreadquery. - Key on
(site, type_key, property_name). - Invalidate on type-document save, hooking the same
new_objects/unloadhookpath the doc cache uses, rather than relying on a TTL. - Benchmark before and after against
/type/edition, since the remaining headroom is small enough that the cache has to earn its complexity.
Open question
Is this worth doing at all now that the lookup is 2 fetches? Worth a staff call before anyone writes it — a cache with a correctness risk and ~6 µs of upside may be a net negative.
Stakeholders
@RayBB — you asked for this to be its own issue
@Prabh0608 — you raised the caching idea; say the word and it's yours
Thank you @MohitSAGAR11 for submitting this issue!
⚠️ Contributors, this issue will be ready to work on once:
- [ ] Triage — maintainers will add
Priority: *andLead: @* - [ ] Needs: Staff Decision — is the remaining ~6 µs / 2-lookup savings on
/type/editionworth a cache with its own invalidation path, now that #14078 fix has shrunk the headroom this far?
Context
- The baseline this issue measures against has not landed on
masteryet: #14078 (the parent issue) is still OPEN, and its closing PR, internetarchive/openlibrary#14395 (bump vendor/infogami to 2f85288), is still unmerged. Until that PR merges,Thing.get_propertyis still doing the full ~94-lookup walk per call, not the ~6 µs / 2-lookup baseline this issue is built on. (gh issue view 14078,gh pr view 14395) - Same reporter/assignee thread: @MohitSAGAR11 (this issue author) is also the assignee on #14078 and the author of PR #14395. This issue is a direct continuation of that work, not a fresh report.
- A structurally identical cache already exists in this repo, for a different caller: https://github.com/internetarchive/openlibrary/blob/2033d3229997d84f711bb8b598faef8980d12aab/openlibrary/core/infobase_async.py#L38-L41 keeps module-level
_type_ids,_type_datatypes(type_key -> property_name -> datatype), and_property_idsdicts, populated once per process by_datatypes()— https://github.com/internetarchive/openlibrary/blob/2033d3229997d84f711bb8b598faef8980d12aab/openlibrary/core/infobase_async.py#L56-L70. The comment there gives the same rationale this issue gives ("Types and properties almost never change, so these are looked up once per process") — and it has the same gap: no invalidation hook of any kind. That cache backs the asyncthings()helper for/api/books(notreadquery.find_datatype/Thing.get_property), so it is a parallel concern rather than a duplicate, but any invalidation mechanism built for this issue should probably account for, or replace, that existing uninvalidated cache too, rather than leaving two separate "trust the process lifetime" dicts in the codebase. - Note for whoever picks this up: the repo has two unrelated modules named
cache.py—openlibrary/core/cache.py(memcache-backedmemcache_memoize, unrelated) andvendor/infogami/infogami/infobase/cache.py(the layered in-process doc cache withunloadhookthis issue refers to). The Proposal "cache.py" reference is the infogami one.vendor/infogamiis not checked out in this research pass (submodule not initialized here), so thedbstore.py:194/cache.unloadhookdetails in the issue body are reported as the issue describes them, not independently re-verified against infogami source.
Issue Assessment
Open questions
- Is the ~6 µs/call savings worth the correctness risk and added invalidation surface, given the fix it depends on (#14078 / PR #14395) has not merged yet? (Explicitly flagged by the author as needing a staff call — this is why
Needs: Staff Decisionwas applied.) - Should this cache and the existing uninvalidated one in
infobase_async.pyshare a single invalidation mechanism, or is building two independent ones acceptable? - Where should the cache physically live —
vendor/infogamicache.py(reuses the existingunloadhook/new_objectsplumbing described in the issue) or local toreadquery.py? The issue leans towardcache.pyfor exactly that reuse reason but leaves it open.
Action items
- [ ] Land #14078 / PR #14395 first (or confirm it is about to) — this issue cost/benefit numbers assume that baseline is in place.
- [ ] Get the staff call this issue explicitly asks for before any implementation starts.
🔔 Stakeholders @RayBB — Lead on #14078 (the issue this is a direct follow-up to) and already tagged by the author as the one who asked for this to be split out.
Full triage checklist
- [x] Triage — labels applied (
Needs: Triage,Needs: Lead,Needs: Staff Decision,Theme: Performance,Affects: Server,Module: Infogami) - [x] Problem / opportunity — clear and quantified (2 lookups, ~6 µs), but conditioned on a fix that has not merged yet
- [x] Scope — single, narrow proposal; does not try to do multiple things
- [ ] Justification — impact is explicitly marginal (~6 µs) and the author themselves questions whether it is worth it; no case made that it clears the bar
- [x] Success & testing criteria — "benchmark before and after against
/type/edition" is concrete and verifiable - [x] Proposal & breakdown — 4-step plan is concrete enough to act on once the staff decision is made
- [ ] If bug: environment & repro steps — n/a, this is a proposal, not a bug report
- [x] Risks, concerns, open questions — invalidation correctness and site-identity keying are already called out in detail by the author
- [x] Richy context — dependency on #14078/#14395, prior-art cache, and
cache.pynaming ambiguity checked; no duplicate issue found - [x] References — permalinks to the analogous existing cache provided above
[!NOTE] This comment was automatically generated by Richy, Open Library issue enrichment assistant, on behalf of @mekarpeles. This is NOT a sign-off. This issue needs lead review before work begins.
Hi @MohitSAGAR11, thanks for asking! However, I already have an assigned issue to work on, so I'll have to pass on this one for now.
Happy for you you to explore this and let me know what performance gains you see and if it's worth it!
Thanks @RayBB. Numbers first, then my honest answer on whether it's worth it.
internetarchive/infogami#288 is up and green.
What I measured
A /type/edition-shaped type (47 properties), 20,000 repeated lookups of one property:
| per call | store lookups | |
|---|---|---|
| before | 8.134 µs | 40,000 |
| after | 1.058 µs | 0 |
So ~7 µs and 2 store lookups saved per find_datatype call, on top of what #284 already took out.
What I did not measure
That's a synthetic in-memory store, so a "lookup" there is a dict access plus a json.dumps. In production it goes through infobase's Cache, which for a hot type should be an in-process hit plus a JSON parse — probably the same ballpark, but I can't prove that from here.
More importantly I have no end-to-end number. find_datatype is called once per query condition plus once for the sort, so a 3-condition things() query saves roughly 28 µs. Against the ~1.4 ms /api/books is doing after #284, that's on the order of 2% — not a headline. Getting a real figure needs a running stack with Postgres, which I don't have; you'd get a truer answer from a production trace in a minute than I would in a day.
Is it worth it — my read
On the gain alone, no. 2% of a request that #284 already made ~3x cheaper is not a change I'd argue for on its merits.
On cost, yes, because the cost is close to zero:
- A miss does exactly what the uncached path does, so it is never slower.
- The thing that made this scary — a stale cache after a type edit — is gone rather than managed. The key carries the type's revision, so an edit makes the old entry unreachable instead of wrong. No invalidation hook, nothing to keep in step with
dbstore's write-through doc cache. - A type document with no revision isn't cached at all, so a fixture can't pin a wrong answer.
So: a small, permanent win for ~40 lines and no new invalidation surface. I'd take it, but I won't pretend it's more than it is, and I'd understand closing it if you'd rather not grow the surface for 2%.
One thing worth separating out either way: openlibrary/core/infobase_async.py keeps _type_datatypes as a module-level dict with no invalidation at all, backing the async things() helper. That one can go stale on a type edit. It's a different caller so it isn't fixed by this PR, but if the revision-keying approach here looks right, the same trick would close that hole. Happy to file it separately.