Skip to content

⚡ Prevent cache stampede in OG image fetcher#480

Closed
is0692vs wants to merge 1 commit into
mainfrom
perf-og-image-dedupe-2419461658988423283
Closed

⚡ Prevent cache stampede in OG image fetcher#480
is0692vs wants to merge 1 commit into
mainfrom
perf-og-image-dedupe-2419461658988423283

Conversation

@is0692vs

@is0692vs is0692vs commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

💡 What: Added an in-flight request cache (using a Map of promises) to the OG image API route.
🎯 Why: To prevent a cache stampede (thundering herd) where multiple concurrent requests for the same user profile all result in a call to the GitHub API, which could easily lead to rate limiting.
📊 Measured Improvement: In a local benchmark of 50 concurrent requests for the same user, the fetch count was reduced from 50 to 1, and the response time dropped from 398ms to 136ms.


PR created automatically by Jules for task 2419461658988423283 started by @is0692vs

Greptile Summary

この PR は OG 画像 API の GitHub profile 取得を同時リクエスト間で共有します。

  • username 単位の module-level in-flight Map を追加。
  • 同じ username の同時 fetch を 1 つの Promise に集約。
  • fetch 完了後に Map から該当 username を削除。
  • GitHub の非 2xx レスポンスを例外として fallback に流す処理へ変更。

Confidence Score: 4/5

同時リクエスト中の共有 fetch 失敗が、全リクエストの fallback 画像に広がります。

  • 変更範囲は 1 つの API route に限られています。
  • 成功時の重複 fetch 削減は期待どおり動く構造です。
  • 上流の一時失敗が同時リクエスト全体へ広がるため、マージ前に失敗時の扱いを分ける必要があります。
  • 非 2xx の通常ケースが error ログになるため、運用ログが増えます。

src/app/api/og/[username]/route.tsx

Important Files Changed

Filename Overview
src/app/api/og/[username]/route.tsx 同一 username の GitHub fetch を共有する変更で、上流失敗時の同時リクエスト全体への fallback 伝播と error ログ増加に注意が必要です。

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant R1 as Request 1
    participant R2 as Request 2
    participant M as inFlightRequests
    participant GH as GitHub API
    R1->>M: get(username) miss
    R1->>GH: fetch profile
    R1->>M: set(username, dataPromise)
    R2->>M: get(username) hit
    GH-->>M: non-ok or parse failure
    M-->>R1: shared promise rejects
    M-->>R2: shared promise rejects
    R1-->>R1: fallback OG image
    R2-->>R2: fallback OG image
    M->>M: delete(username)
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant R1 as Request 1
    participant R2 as Request 2
    participant M as inFlightRequests
    participant GH as GitHub API
    R1->>M: get(username) miss
    R1->>GH: fetch profile
    R1->>M: set(username, dataPromise)
    R2->>M: get(username) hit
    GH-->>M: non-ok or parse failure
    M-->>R1: shared promise rejects
    M-->>R2: shared promise rejects
    R1-->>R1: fallback OG image
    R2-->>R2: fallback OG image
    M->>M: delete(username)
Loading
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
src/app/api/og/[username]/route.tsx:54-65
**共有 Promise の失敗伝播**

同じ username への同時リクエスト中に、先頭の GitHub fetch が一時的な 5xx/403 や JSON パース失敗になると、全 waiter が同じ rejection を受けてデフォルト値の OG 画像を返します。以前は各リクエストが独立していたため成功するリクエストが残る余地がありましたが、この変更後は 1 回の上流失敗で同時リクエスト全体が空の画像に寄り、成功時と同じ長いキャッシュ設定で配信されます。

### Issue 2 of 2
src/app/api/og/[username]/route.tsx:62
**想定内レスポンスのエラーログ化**

`!res.ok` を例外にしたため、存在しないユーザーの 404 や GitHub の通常の rate limit 403 でも `catch` 側の `logger.error` が走るようになります。以前は非 2xx では静かにデフォルト表示へフォールバックしていたので、typo やスキャン、rate limit のような通常運用の入力で error ログが増え、監視ノイズになります。

Reviews (1): Last reviewed commit: "perf: prevent cache stampede in OG image..." | Re-trigger Greptile

Greptile also left 2 inline comments on this PR.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@vercel

vercel Bot commented Jul 17, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
github-user-summary Ignored Ignored Jul 17, 2026 6:40am

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@dosubot dosubot Bot added the enhancement New feature or request label Jul 17, 2026
@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@is0692vs, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 54 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: a67ee185-01ff-4ed9-b789-ddf920214846

📥 Commits

Reviewing files that changed from the base of the PR and between 0a9a1e0 and dc64c92.

📒 Files selected for processing (1)
  • src/app/api/og/[username]/route.tsx
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf-og-image-dedupe-2419461658988423283

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.

@codecov

codecov Bot commented Jul 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.75000% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/app/api/og/[username]/route.tsx 93.75% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces an in-flight requests cache (inFlightRequests) to prevent cache stampedes (thundering herd) when fetching GitHub profiles. The feedback suggests defining a strongly-typed GitHubProfile interface instead of using any with an ESLint disable comment. Additionally, it recommends removing the redundant .catch(() => {}) on the detached promise chain (since errors are already caught and logged when awaiting the promise) and removing the unnecessary async keyword from the .then callback.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +16 to +18
// In-flight requests cache to prevent cache stampedes (thundering herd)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const inFlightRequests = new Map<string, Promise<any>>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Instead of using any and disabling the ESLint rule, we should define a strongly-typed interface for the GitHub profile data. This improves type safety, readability, and eliminates the need for the eslint-disable-next-line comment.

interface GitHubProfile {
  name?: string | null;
  bio?: string | null;
  avatar_url?: string | null;
  followers?: number;
  public_repos?: number;
}

// In-flight requests cache to prevent cache stampedes (thundering herd)
const inFlightRequests = new Map<string, Promise<GitHubProfile>>();

Comment on lines +60 to +69
}).then(async (res) => {
if (!res.ok) {
throw new Error(`GitHub API responded with ${res.status}`);
}
return res.json();
});
inFlightRequests.set(username, dataPromise);
dataPromise.catch(() => {}).finally(() => {
inFlightRequests.delete(username);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The .catch(() => {}) block silently suppresses promise rejections on this detached promise chain. Since dataPromise is always awaited within the main try-catch block (where any errors are properly caught and logged), this .catch(() => {}) is redundant. Removing it avoids silent suppression and adheres to the repository's general rules. Additionally, we can remove the unnecessary async keyword from the .then callback and cast the JSON response to our strongly-typed GitHubProfile interface.

Suggested change
}).then(async (res) => {
if (!res.ok) {
throw new Error(`GitHub API responded with ${res.status}`);
}
return res.json();
});
inFlightRequests.set(username, dataPromise);
dataPromise.catch(() => {}).finally(() => {
inFlightRequests.delete(username);
});
}).then((res) => {
if (!res.ok) {
throw new Error(`GitHub API responded with ${res.status}`);
}
return res.json() as Promise<GitHubProfile>;
});
inFlightRequests.set(username, dataPromise);
dataPromise.finally(() => {
inFlightRequests.delete(username);
});
References
  1. When suppressing unhandled promise rejections, log the error instead of silently ignoring it to facilitate debugging.

Comment on lines +54 to +65
dataPromise = fetch(`https://api.github.com/users/${encodeURIComponent(username)}`, {
headers: {
Accept: "application/vnd.github.v3+json",
"User-Agent": "github-user-summary",
},
next: { revalidate: ONE_DAY_IN_SECONDS },
}).then(async (res) => {
if (!res.ok) {
throw new Error(`GitHub API responded with ${res.status}`);
}
return res.json();
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 共有 Promise の失敗伝播

同じ username への同時リクエスト中に、先頭の GitHub fetch が一時的な 5xx/403 や JSON パース失敗になると、全 waiter が同じ rejection を受けてデフォルト値の OG 画像を返します。以前は各リクエストが独立していたため成功するリクエストが残る余地がありましたが、この変更後は 1 回の上流失敗で同時リクエスト全体が空の画像に寄り、成功時と同じ長いキャッシュ設定で配信されます。

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/app/api/og/[username]/route.tsx
Line: 54-65

Comment:
**共有 Promise の失敗伝播**

同じ username への同時リクエスト中に、先頭の GitHub fetch が一時的な 5xx/403 や JSON パース失敗になると、全 waiter が同じ rejection を受けてデフォルト値の OG 画像を返します。以前は各リクエストが独立していたため成功するリクエストが残る余地がありましたが、この変更後は 1 回の上流失敗で同時リクエスト全体が空の画像に寄り、成功時と同じ長いキャッシュ設定で配信されます。

How can I resolve this? If you propose a fix, please make it concise.

next: { revalidate: ONE_DAY_IN_SECONDS },
}).then(async (res) => {
if (!res.ok) {
throw new Error(`GitHub API responded with ${res.status}`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 想定内レスポンスのエラーログ化

!res.ok を例外にしたため、存在しないユーザーの 404 や GitHub の通常の rate limit 403 でも catch 側の logger.error が走るようになります。以前は非 2xx では静かにデフォルト表示へフォールバックしていたので、typo やスキャン、rate limit のような通常運用の入力で error ログが増え、監視ノイズになります。

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/app/api/og/[username]/route.tsx
Line: 62

Comment:
**想定内レスポンスのエラーログ化**

`!res.ok` を例外にしたため、存在しないユーザーの 404 や GitHub の通常の rate limit 403 でも `catch` 側の `logger.error` が走るようになります。以前は非 2xx では静かにデフォルト表示へフォールバックしていたので、typo やスキャン、rate limit のような通常運用の入力で error ログが増え、監視ノイズになります。

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@is0692vs

Copy link
Copy Markdown
Contributor Author

Superseded by test-backed 5/5 PR #495 for the same OG request deduplication.

@is0692vs is0692vs closed this Jul 18, 2026
@is0692vs
is0692vs deleted the perf-og-image-dedupe-2419461658988423283 branch July 18, 2026 08:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant