Post-mortem: ~12h site-wide outage — Amazon affiliate link generation saturated all FastAPI workers
Summary
A ~12 hour site-wide outage was caused by Amazon affiliate link generation. Slow upstream Amazon API responses caused FastAPI workers to block for up to 10s per request and saturate all workers, taking down endpoints unrelated to affiliate links.
Production is currently running on a manual, undocumented hotfix that is not in git (see Current production state). A redeploy of ol-web[0-3] will silently reintroduce the outage. That is the most urgent item here.
The root cause is not just "Amazon was slow." A slow upstream should degrade one partial; instead it took down the site. Three independent amplifiers in our own code turned a third-party slowdown into total saturation.
Current production state (⚠️ hotfix not in git)
Applied by hand via docker exec into the ol-web[0-3] containers:
- Amazon metadata request timeout changed 10s → 2s
- The affiliate link partial changed to return
""
Neither change exists in the repository. Consequences:
- Any redeploy, container restart from image, or host rebuild of
ol-web[0-3]reverts both and reintroduces the outage, with no alert tied to the regression. - The running code no longer matches
master, so anyone debugging prod sees behavior that does not match the source.
First action should be landing the equivalent of this hotfix in git, so prod state is reproducible, then pursuing the real fix.
Impact
| Duration | ~12 hours |
| Scope | Site-wide — all FastAPI workers saturated, not just affiliate links |
| Trigger surface | Book/edition pages requesting the affiliate links partial with prices |
| Mitigation | Manual container edits on ol-web[0-3] (still in place) |
Still needed (not yet recorded): exact start/end timestamps, who responded, how it was detected (alert vs. user report), and the confirmed user-facing error rate. These are intentionally left blank rather than estimated — please fill in.
Root cause
Trigger: production is on the legacy PA-API, by deliberate choice
scripts/affiliate_server.py:657-667 selects the Amazon client. The comment directly above it says the opposite of what the code does:
# Prefer the new Creators API if credentials are configured; fall back to
# legacy PA-API (amazon_api) for side-by-side comparison during migration.
...
if all(legacy_args):
web.amazon_api = AmazonAPI(*legacy_args, throttling=0.9, proxy_url=http_proxy_url)
logger.info("AmazonAPI (legacy PA-API) Initialized")
elif all(creators_args):
web.amazon_api = AmazonCreatorsAPI(...)
Legacy is checked first. If both credential sets are present in openlibrary.yml — the expected state during a side-by-side migration — production silently runs the legacy PA-API and AmazonCreatorsAPI is never constructed.
This was intentional, not an accident: commit 035009c64 (2026-06-20, Drini Cami) — "Tweaks to affiliate server + switch to legacy API, which still works for now" — flipped the condition from if all(creators_args) to if all(legacy_args). The docstring was not updated to match, which is why this reads as a bug on inspection.
This confirms the legacy-PAPI-vs-Creators hypothesis, with the correction that it is a deliberate June switch rather than an accidental fallback. Verify on ol-web0 by grepping the affiliate server startup log for AmazonAPI (legacy PA-API) Initialized vs AmazonCreatorsAPI Initialized.
Amplifier 1: a blocking sync call on the async event loop
This is the reason a slow upstream became a site-wide outage.
openlibrary/fastapi/partials.py:64 awaits a native coroutine, so it runs directly on the worker's event loop — not in a threadpool:
return await AffiliateLinksPartial.generate_async(...)
Inside it, openlibrary/plugins/openlibrary/partials.py:309-312:
if should_fetch_prices and isbn:
bwb_metadata = await get_betterworldbooks_metadata(isbn) # async (httpx), timeout=3
if not bwb_metadata or not bwb_metadata.get("market_price"):
amz_metadata = get_amazon_metadata(isbn, resources="prices") # SYNC, blocking, timeout=10
The Better World Books call is properly async. The Amazon call is a synchronous requests.Session().get() (openlibrary/core/vendors.py:33, 680-683). Calling it from a coroutine blocks the entire event loop, so one slow Amazon response stalls every concurrent request that worker is serving — not just the affiliate partial. With every worker doing this, the whole pool saturates. This is exactly the observed "timing out on and saturating ALL fast_api workers."
Note the ordering also makes Amazon the fallback that runs precisely when BWB has no price — so BWB gaps drive traffic into the blocking path.
Introduced by 9f17e5422 (2026-05-13, #12731, "move affiliate store logic from template to Python"), which moved this logic into the async partial without converting the Amazon call to async.
Amplifier 2: a 10s timeout on the blocking path
openlibrary/core/vendors.py:648 — timeout: float = 10.0. The async BWB path uses timeout=3 (line 874). The one call that blocks the event loop had the most generous timeout, a 3.3× outlier.
Amplifier 3: failures deliberately bypass the cache
cached_get_amazon_metadata (openlibrary/core/vendors.py:799-819) ends with:
result = memoized_get_amazon_metadata(*args, **kwargs)
return result or memoized_get_amazon_metadata.update(*args, **kwargs)[0]
A falsy cached value triggers an immediate re-fetch. _get_amazon_metadata returns None on ConnectionError, on HTTPError, and when hit is absent — so during an Amazon or affiliate-server failure, memcache provides no protection at all: every request re-attempts the blocking call.
Worse, on this path the blocking call happens twice per request — once through the memoize read-through, once through .update() — so worst-case event-loop blocking per request is ~20s, not 10s.
The docstring explains the intent (retry through Amazon 503 throttling, cache {"price": None} so only None re-caches). That is reasonable for a cheap sync call, and actively harmful for a 10s call that blocks an event loop.
Why it cascaded
legacy PA-API slow/degraded (trigger)
→ sync requests.get on the event loop → blocks the whole worker, not one request
→ 10s timeout → each block is long
→ None result bypasses memcache, fires twice → every request re-attempts, ~20s worst case
→ all workers' event loops blocked → site-wide 12h outage
Any one amplifier alone is survivable. Together they convert a third-party slowdown into total unavailability. This will recur with any slow Amazon dependency — including after the Creators API migration — unless the amplifiers are fixed. Migrating to Creators removes this trigger, not the fragility.
Proposed fix
Ordered by urgency, not effort.
P0 — make prod reproducible
- [ ] Land the hotfix in git: Amazon metadata
timeout10s → 2s, and the affiliate partial's fail-open behavior. - [ ] Confirm
ol-web[0-3]containers matchmasterafterward, so the manual edits can be safely dropped.
P1 — remove the amplifiers (the actual bug)
- [ ] Stop blocking the event loop. Either convert the affiliate-server fetch to
httpxon the existingasync_session, or wrap the sync call inrun_in_threadpool/asyncio.to_thread. Preferred: make it genuinely async, matchingget_betterworldbooks_metadata. - [ ] Fail open, always. A missing price must never be able to fail a page render. Amazon price data is an enhancement; the affiliate link itself is built by
amazon_affiliate_url()from ISBN/ASIN with no network call, so links survive a total Amazon outage if prices are decoupled. - [ ] Cap the timeout at ~2s on any request in the page-render path.
- [ ] Negative-cache failures. Distinguish "Amazon says no price" from "Amazon is down," and short-TTL cache the latter (30-60s) instead of re-fetching. Removes the stampede and the double-call.
- [ ] Add a circuit breaker: after N consecutive failures, skip Amazon entirely for a cooldown window.
P2 — resolve the API question
- [ ] Confirm on
ol-web0which client is live, via the startup log line. - [ ] Decide whether the June "legacy still works for now" switch should stand, and fix the contradicting docstring either way — it currently states the opposite of the behavior.
- [ ] If moving to Creators: note
AmazonCreatorsAPIlazy-importsamazon_creatorsapi(vendors.py:387-396) and has a proxy-injection fallback path (~:419-437) that silently degrades to env-level proxy. Verify both in prod before cutting over. - [ ] Related and currently blocked on an architectural call: per-service Amazon proxy params, branch
12715/per-service-proxy-params— conflicts with master'sload_config()proxy changes in this same file.
P3 — detection
- [ ] Alert on FastAPI worker saturation / event-loop blocking, not just HTTP 5xx. A 12h duration suggests saturation itself was not alerting.
- [ ] Add a synthetic check on an edition page with prices enabled.
- [ ] Emit
statstiming around outbound affiliate calls (astats.clientalready exists inaffiliate_server.py:637).
Verification plan (ol-web0, team session)
- Read the affiliate server startup log; confirm legacy vs Creators.
- Time
curl http://{affiliate_server}/isbn/{isbn}directly to get real upstream latency. - Request the affiliate partial for an ISBN with no Amazon match — this is the pathological path (guaranteed
None, cache bypassed, double call). - Confirm the double-fetch empirically: one partial request should produce two upstream calls.
- With the 2s hotfix reverted on one node only, confirm concurrent unrelated requests to that worker stall — proving event-loop blocking rather than per-request slowness.
Files implicated
| File | Lines | Issue |
|---|---|---|
openlibrary/plugins/openlibrary/partials.py |
309-312 | sync Amazon call inside async def |
openlibrary/core/vendors.py |
648, 680-683 | 10s timeout, blocking requests session |
openlibrary/core/vendors.py |
799-819 | failure bypasses cache, double-fetch |
openlibrary/fastapi/partials.py |
64 | awaits the coroutine on the event loop |
scripts/affiliate_server.py |
641-669 | legacy-first precedence contradicts its docstring |
Discovery trail — two of the issue's premises are already resolved on master, and one new coupled bug
Verified against origin/master as of 2026-08-10, locating everything by content rather than the line numbers cited above (several have drifted).
1. Client precedence is already Creators-first. The docstring is already correct.
ad85f21b4 — "switch bookworm to use amz creators API" (2026-07-16) — flipped load_config back to if all(creators_args): first, reverting the June 035009c64 switch. Confirmed an ancestor of origin/master. The comment above the block and the code now agree, so the "docstring says the opposite of the code" item under P2 is stale.
This does not invalidate the root-cause analysis — it relocates it. If prod was serving legacy PA-API during the outage, then either ol-web[0-3]/the affiliate server had not been redeployed since 2026-07-16, or amazon_creators_api credentials are absent from prod openlibrary.yml so the elif all(legacy_args) branch is taken. Both are config/deploy facts, not code facts. The startup-log grep in the verification plan is still the right test and is now more important, since master's code alone no longer tells you which client is live.
2. The affiliate-partial half of the P0 hotfix already landed — in a stronger form than described.
e592f0ab8 — "Disable price fetching in AffiliateLinksPartial" (2026-08-06) — hardcodes prices=False in openlibrary/fastapi/partials.py::affiliate_links_partial, discarding the prices query param entirely. So price fetching is off in git today, not just on the containers.
3. The remaining P0 half cannot ship alone — the timeout change on its own makes things worse.
timeout: float = 10.0 in _get_amazon_metadata is confirmed still on master. But that function catches only ConnectionError and HTTPError, and:
ReadTimeout -> Timeout -> RequestException -> OSError # NOT a ConnectionError
ConnectTimeout -> ConnectionError -> Timeout # caught, incidentally
requests.exceptions.ReadTimeout is not caught. "Upstream reachable but slow" — the exact outage condition — raises ReadTimeout, and nothing downstream swallows it: cache.MemcacheMemoize.update() calls value = self.f(*args, **kw) bare, and neither AffiliateLinksPartial.generate_async nor the route wraps it. Cutting the timeout to 2s without adding fail-open converts a 10s hang into a 2s hang plus a 500. These two P0 bullets are one change, not two.
The same incomplete except ConnectionError / except HTTPError pair guards get_amazon_metadata() inside Edition.from_isbn (openlibrary/core/models.py). That path is a real page render (/isbn/<isbn>), not a lazily-loaded partial, and it passes high_priority through — where the affiliate server blocks and waits by design, making ReadTimeout the expected outcome rather than an edge case. r.json() raising InvalidJSONError on an HTML error page is uncaught at both sites as well.
4. Smaller confirmations
AmazonCreatorsAPI's lazyfrom amazon_creatorsapi import ...resolves — the module ships insidepython-amazon-paapi==6.3.0, already inrequirements.txt. Confirming inside the container during implementation.- The proxy-injection concern under P2 is real:
035009c64dropped theproxy_credsargument, and master passes**({"proxy": _proxy} if _proxy else {}), so an absenthttp_proxyconfig key silently yields no SDK proxy and env-level fallback, with no log line marking it. stage_bookworm_metadataissuessession.get(...)with no timeout at all — unbounded. Import path rather than page render, so tracking it separately from P0.
Scope I am taking, per the two-PR split requested: one PR landing timeout-cap + genuine fail-open together (they are inseparable, per 3), and one PR adding the regression coverage that precedence, the lazy import, and the proxy fallback have never had — the precedence has now been hand-flipped twice with zero tests guarding it.
Neither PR will re-enable prices=True. The sync requests.get still executes on the worker's event loop, so re-enabling prices before the P1 amplifier work reintroduces the outage no matter what the timeout is. P1 remains out of scope here and overlaps #11318.
Validation plan (Phase 3) — PR 1: land the P0 hotfix, coupled
Posting before implementing. No staff gate requested: the change is small, reversible, touches no auth/secrets/prod data, and the approach follows directly from the code. One scope judgement is flagged at the bottom for your call — it affects PR 2 only, so PR 1 is unblocked either way.
Approach
Ship the timeout cap and the fail-open as one commit, because the timeout alone regresses behavior (see point 3 of my previous comment). Fail-open means: broaden the exception handling on the Amazon metadata path from ConnectionError/HTTPError to requests.exceptions.RequestException, so ReadTimeout, Timeout, and InvalidJSONError all yield None rather than propagating. None is already the documented, fully-handled "no Amazon data" return value at every call site, so there is no new branch to teach callers.
Files to modify
| File | Change |
|---|---|
openlibrary/core/vendors.py |
_get_amazon_metadata: timeout: float = 10.0 -> 2.0. Replace the except ConnectionError / except HTTPError pair with except requests.exceptions.RequestException, keeping the two specific log messages by branching on the caught type so log greppability is preserved. |
openlibrary/core/vendors.py |
stage_bookworm_metadata: add an explicit timeout (currently unbounded) and the same broadened handling. Included because it is the identical defect three functions away, and leaving one session.get unbounded in this file invites the next person to copy it. |
openlibrary/core/models.py |
Edition.from_isbn: same broadening, so the /isbn/<isbn> page-render path cannot 500 on a slow affiliate server. |
openlibrary/fastapi/partials.py |
No behavior change. Expand the # Temporarily disabled comment to reference #13277 and state the precondition for re-enabling (P1 event-loop fix), so the next reader does not flip it back innocently. |
prices=False stays hardcoded. Re-enabling it is gated on P1.
Tests — openlibrary/tests/core/test_vendors.py
Extending the existing unittest.mock.patch pattern from test_get_amazon_metadata (docker/mockservices from the Core Vitals work is not on master, so there is no service-mock harness to reuse yet).
| Test | Input | Expected |
|---|---|---|
test_get_amazon_metadata_default_timeout_is_2s |
patched session.get, call get_amazon_metadata(isbn) |
session.get called with timeout=2.0 — asserts the value reaches the wire, not just the default |
test_get_amazon_metadata_returns_none_on_read_timeout |
session.get raises requests.exceptions.ReadTimeout |
returns None, does not raise (this is the regression the current code fails) |
test_get_amazon_metadata_returns_none_on_connect_timeout |
raises ConnectTimeout |
returns None |
test_get_amazon_metadata_returns_none_on_invalid_json |
r.json() raises requests.exceptions.InvalidJSONError |
returns None |
test_get_amazon_metadata_still_returns_none_on_connection_error |
raises ConnectionError |
returns None — guards the existing behavior against the refactor |
test_stage_bookworm_metadata_has_timeout |
patched session.get |
called with an explicit finite timeout |
test_from_isbn_returns_none_on_read_timeout |
get_amazon_metadata raises ReadTimeout |
Edition.from_isbn returns None rather than propagating |
Every timeout test is written to fail against current master first (TDD), which also serves as the proof that ReadTimeout really escapes today.
Success criteria
- Automated: the seven tests above pass; full
make test-py-uvgreen;pre-commitclean on changed files. - Manual: affiliate partial returns HTTP 200 with an ISBN that has no Amazon match, and
/isbn/<isbn>renders 200 with the affiliate server unreachable. Both exercised locally in Docker. - Not claimed: anything about production.
ol-web0verification is Mek's; PR 1's body will carry the copy-pasteable checklist from this issue's own verification plan (startup-log grep, directcurltiming, a no-match ISBN, double-fetch confirmation, single-node revert test), with no results filled in by me.
Out of scope (P1 — the actual fragility, tracked at #11318)
Converting the call to async / run_in_threadpool; negative-caching upstream failures; removing the result or ....update(...) double-fetch; the circuit breaker; re-enabling prices. Migrating to Creators removes the trigger, not the fragility — this PR is a safety net that bounds the blast radius of the next slow Amazon dependency. It does not stop a slow upstream from blocking the event loop, and after it merges a sufficiently slow Amazon can still stall a worker for 2s per call, twice per request on the cache-bypass path.
Risks
- Broadening to
RequestExceptioncould mask a genuinely novel failure mode. Mitigated by keepinglogger.exceptionon every path, so nothing becomes silent. - 2s may be too aggressive for
high_priority=TruefromEdition.from_isbn, where the affiliate server intentionally blocks for several seconds while staging an import — this could reduce the import hit rate. The timeout is a keyword arg with a default, so a follow-up can raise it for the import path specifically without touching the render path. Calling it out rather than pre-emptively splitting it. stage_bookworm_metadatagaining a timeout where it had none may surface import failures that previously hung. That is the intended trade.
Flagged for your call (PR 2 only)
Since ad85f21b4 already made master Creators-first, PR 2 has no behavior change left to make. I plan to repurpose it as pure regression coverage — precedence across all four credential combinations, the amazon_creatorsapi lazy import, and the silent proxy-fallback path — since the precedence has been hand-flipped twice with no test guarding it. If you would rather I drop PR 2 entirely, say so and I will close it out after PR 1.
P0 landed for review: #13295 · P1 split out to #13296
#13295 — codifies the hotfix. Timeout 10s -> 2s (AFFILIATE_SERVER_TIMEOUT_SECS) and fail-open on requests.RequestException, shipped together because the timeout alone regresses behavior: ReadTimeout is a subclass of neither ConnectionError nor HTTPError, so it escaped uncaught on exactly the "reachable but slow" path, and MemcacheMemoize.update() calls the wrapped function bare. Cutting to 2s without fail-open converts a 10s hang into a 2s hang plus a 500.
A/B against a real black-hole socket, through the public get_amazon_metadata():
| master | #13295 | |
|---|---|---|
| socket read timeout | 10.0s | 2.0s |
| outcome | raised ReadTimeout |
returned None |
| wall clock | 10.03s | 4.02s |
| upstream calls | 1 (raise short-circuited the retry) | 2 |
That last row empirically confirms Amplifier 3 — one logical request, two upstream calls. It also means worst case post-fix is 2 x 2s = 4s, not 2s; failing open correctly returns None, which re-engages the result or ....update(...) cache-bypass retry. Removing that second call is #13296's job.
Also fixed in the same PR: Edition.from_isbn carried the identical incomplete except pair on the /isbn/<isbn> page render path, and stage_bookworm_metadata had no timeout at all.
#13296 — the P1 amplifiers (event-loop blocking, double-fetch, negative caching, circuit breaker, re-enabling prices) with the P3 detection items folded in. Filed separately rather than reusing #11318: that issue is about the affiliate server being overwhelmed, whereas this is OL's client-side handling of upstream slowness. Complements, not duplicates.
Two items here can be checked off as already done
- P2 "fix the contradicting docstring" — stale.
ad85f21b4(2026-07-16) already reverted June's switch, so master is Creators-first and the comment matches the code. Whatever prod was serving during the outage is therefore a config/deploy fact, not a code fact — no redeploy since 2026-07-16, oramazon_creators_apimissing one ofkey/secret/idsoelif all(legacy_args)wins. The startup-log grep is now the only way to tell, which makes verification step 1 more important than before, not less. - P0 "the affiliate partial's fail-open behavior" — already in git as of
e592f0ab8(2026-08-06), which hardcodesprices=False. #13295 leaves that in place and documents the precondition for reversing it.
Also confirmed: AmazonCreatorsAPI's lazy from amazon_creatorsapi import ... resolves inside the container (python-amazon-paapi==6.3.0, already in requirements.txt), so the P2 concern about that import is clear.
Still yours, not claimed by me
I have no ol-web0 access and have verified nothing in production. #13295's body carries all five steps of the verification plan as copy-pasteable commands — startup-log grep, direct curl timing, how to pick a guaranteed-no-match ISBN, the double-fetch confirmation, and the single-node revert test — with no results filled in.
Still unrecorded in this issue and worth someone filling in: exact outage start/end timestamps, who responded, detection path (alert vs. user report), and the confirmed user-facing error rate.
@mekarpeles here's a PR to add proxy support to the async code path to your branch! With this moving to async should be easier. https://github.com/mekarpeles/python-amazon-paapi/pull/1
PR open to fix async from the OL side calling to affiliate server: https://github.com/internetarchive/openlibrary/pull/13305/
Closed by:
- #13271
- #13305 + https://github.com/mekarpeles/python-amazon-paapi/pull/1
- #13315 (in review)
With this work done, we will be able to re-enable amazon creator's api by undoing #13271