Skip to content

fix(api): add response caching to /insurance/:slab [BUG-106] - #222

Open
Morenikeoa wants to merge 1 commit into
dcccrypto:mainfrom
Morenikeoa:fix/insurance-route-caching
Open

fix(api): add response caching to /insurance/:slab [BUG-106]#222
Morenikeoa wants to merge 1 commit into
dcccrypto:mainfrom
Morenikeoa:fix/insurance-route-caching

Conversation

@Morenikeoa

@Morenikeoa Morenikeoa commented Jun 26, 2026

Copy link
Copy Markdown

Problem

GET /insurance/:slab is wrapped by neither cacheMiddleware nor withDbCacheFallback — every single request, concurrent or not, runs two sequential un-batched Supabase queries (market_stats then insurance_history) with zero protection. Its sibling /open-interest/:slab (same query shape, same data source) already has cacheMiddleware(15).

Impact

A burst of concurrent clients hitting this endpoint (e.g. a dashboard polling insurance data for multiple markets) directly multiplies into 2N concurrent Postgres queries with no caching layer to absorb repeat/concurrent traffic, unlike every comparable route.

Fix

Applied the identical cacheMiddleware(15) already used by /open-interest/:slab.

Test fix needed alongside this

The existing test file didn't call clearCache() between tests. Several tests reuse the same slab address across different mock setups (expecting different DB responses each time) — once caching was added, the second+ test using the same path started getting the first test's cached response instead of hitting its own mock, breaking 4 unrelated tests. Added clearCache() to beforeEach, matching the convention already used in open-interest.test.ts.

Proof of Fix

New test: two requests for the same slab — the second is served from cache (X-Cache: HIT header) with no additional Supabase calls.

Verified this is a genuine regression test: reverted just the source change and reran — failed because X-Cache was never set (no caching existed). Restored the fix and it passes.

  • All existing tests pass — output attached.
  • New regression test passes against the fix, fails against pre-fix code (verified locally).
  • tsc --noEmit clean (no separate lint script in this repo).

Test Output

✓ tests/routes/insurance.test.ts (11 tests) 64ms

Full suite: 295/296 passed (294 baseline + 1 new). The 1 failure (tests/sdk-smoke.test.ts) is pre-existing and unrelated — it asserts on an exact @percolatorct/sdk error-message string that has drifted from the locally-resolved SDK version in this environment.

Related

Found during a broader API audit; no existing open issue/PR covers this.

Summary by CodeRabbit

  • New Features
    • Added response caching for insurance slab requests, helping repeated lookups return faster.
  • Tests
    • Added coverage to verify cached responses are served on repeat requests.
    • Updated test setup to clear cached data between cases for reliable results.

/insurance/:slab was wrapped by neither cacheMiddleware nor
withDbCacheFallback — every single request, concurrent or not, ran two
sequential un-batched Supabase queries (market_stats then
insurance_history) with zero protection. Its sibling /open-interest/:slab
(same query shape, same data source) already has cacheMiddleware(15).

Applied the identical cacheMiddleware(15) to /insurance/:slab, matching
the established pattern for this class of route.

The existing test file didn't call clearCache() between tests, which the
new caching behavior exposed: several tests reusing the same slab address
across different mock setups started getting cached responses from
earlier tests instead of hitting their own mocks. Added clearCache() to
beforeEach, matching open-interest.test.ts's existing convention.

Added a regression test proving a second request for the same slab is
served from cache (X-Cache: HIT, no additional Supabase calls). Verified
it fails against the pre-fix code (no caching, X-Cache header absent) and
passes against the fix.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
@vercel

vercel Bot commented Jun 26, 2026

Copy link
Copy Markdown

@Princessdada is attempting to deploy a commit to the Khubair Nasir's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 26, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

GET /insurance/:slab now uses cache middleware, and the insurance route tests reset cache state before each test and verify repeated requests return a cache hit without another Supabase query.

Changes

Insurance route caching

Layer / File(s) Summary
Route caching middleware
src/routes/insurance.ts
GET /insurance/:slab now imports cacheMiddleware and applies cacheMiddleware(15) before validateSlab.
Cache test coverage
tests/routes/insurance.test.ts
The test suite imports clearCache, resets cached responses in beforeEach, and adds a cache-hit test that checks X-Cache: HIT and no extra Supabase from(...) call.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

A bunny hopped by, ears up high,
“Cache the slab and let it fly!”
One hop says “miss,” the next says “hit,”
No extra fetches—just a fit. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: adding response caching to the insurance slab route.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/routes/insurance.ts`:
- Line 35: The current cacheMiddleware(15) usage on app.get("/insurance/:slab")
only caches completed responses and still allows concurrent requests to trigger
duplicate Supabase work on a cold miss. Update the cache layer itself, not just
the route, to add in-flight request coalescing for the same cache key so the
first request runs the handler and others await its result before hitting the
two Supabase queries. Use the cacheMiddleware contract and its underlying
storage/next flow to locate the fix, ensuring concurrent burst protection is
handled centrally.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a5fcd924-02ff-487f-ab48-40b995cd771a

📥 Commits

Reviewing files that changed from the base of the PR and between b2751f4 and 63b35ba.

📒 Files selected for processing (2)
  • src/routes/insurance.ts
  • tests/routes/insurance.test.ts

Comment thread src/routes/insurance.ts
* }
*/
app.get("/insurance/:slab", validateSlab, async (c) => {
app.get("/insurance/:slab", cacheMiddleware(15), validateSlab, async (c) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

cacheMiddleware(15) does not prevent concurrent cold-miss stampedes.

At Line 35, this only helps once a response is already cached. The current cache contract checks storage before next() and writes after the handler finishes, so two same-key requests arriving together will still both run the two Supabase queries. If concurrent burst protection is part of this fix, it needs in-flight request coalescing in the cache layer, not just TTL caching.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/routes/insurance.ts` at line 35, The current cacheMiddleware(15) usage on
app.get("/insurance/:slab") only caches completed responses and still allows
concurrent requests to trigger duplicate Supabase work on a cold miss. Update
the cache layer itself, not just the route, to add in-flight request coalescing
for the same cache key so the first request runs the handler and others await
its result before hitting the two Supabase queries. Use the cacheMiddleware
contract and its underlying storage/next flow to locate the fix, ensuring
concurrent burst protection is handled centrally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant