Skip to content

fix(ratelimit): make in-memory Retry-After cover an empty minute bucket - #2489

Merged
Quick104 merged 2 commits into
mainfrom
fix/issue-2486-memory-retry-after
Oct 14, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/issue-2486-memory-retry-after

Conversation

@Quick104

@Quick104 Quick104 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2486
Related issue: #2483
Validation tasks: none

When the in-memory rate limiter refuses a request because a key has used up both its per-second and its per-minute budget, Retry-After gives only the per-second wait. A client that waits that long is refused again, and only the second 429 carries the real wait for the minute bucket. This affects every limit served by MemoryLimiter: request rate limits when Redis isn't configured (or ratelimit.backend = memory), and the person and trailer refresh limits, which always use it.

MemoryLimiter.Allow returned as soon as the per-second bucket refused, without looking at the minute bucket. It now reports the longer of the two waits.

Approach

When the per-second bucket refuses, the limiter reads how long the minute bucket needs to hold a whole token and uses that wait if it is longer. It reads the bucket with TokensAt, which takes no token. Reserving and cancelling instead, as the minute check further down does, can lose tokens when refused requests on one key overlap, so the new check avoids it. When the minute wait wins, ResetAt is that time rounded up to a whole second, because X-RateLimit-Reset carries whole seconds and a floored value would send a client back early.

Allow now calls an allowAt that takes the current time, so the tests use fixed instants instead of sleeping.

No contract or schema changes. Clients see a longer Retry-After and X-RateLimit-Reset on this one kind of refusal, which is the correct value. The Redis limiter has the same bug and is fixed separately in #2485; this PR doesn't touch redis.go.

Validation

  • A new test empties both buckets and checks that Retry-After covers the minute bucket's 30s, that a request after that wait is allowed, and that a client retrying at the X-RateLimit-Reset second from mid-second is allowed. Before the fix it failed with a 1s Retry-After. With the fix but without the rounding, the reset check failed. A second test checks that a per-second refusal with room in the minute bucket still waits 1s, and a third that a minute rate too slow for a Duration saturates Retry-After without putting X-RateLimit-Reset in the past.
  • Repeated refusals in the test show a refused request takes no minute tokens.
  • go build ./..., gofmt, go vet ./..., golangci-lint --new-from-patch, and make test-go pass. The ratelimit tests also pass with -race.
  • Not reproduced on a live deployment; the source path and the tests are the proof.

Evidence

Evidence: none, no user-visible change

Risks

None identified. Refused clients wait longer only when the minute bucket is also empty, which is the wait they would get on their next attempt anyway.

Found in review, predating this PR, and filed separately. The first two change lines this PR changes, so their fixes should follow it.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code in T3 Code
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated. No human has verified it yet.
  • Adversarial review: plan round skipped (a few-line fix where the source shows the root cause; nothing added). Code review with three read-only finders: their points on float overflow, a zero limit, and the floored reset header are fixed here; two older defects they found are filed separately (see Risks). Background review by gpt-6.1-sol on d7ebea7 found one older defect, the refresh handlers' rounding, filed as [bug] Person and trailer refresh limits round Retry-After down, so a client that honors it is refused again #2493. The Codex review bot found that a saturated minute wait overflowed the reset rounding; fixed in a2f392f. No findings left open.

🤖 Generated with Claude Code

Note

Make in-memory MemoryLimiter Retry-After cover an empty minute bucket

  • Fixes MemoryLimiter.Allow to report a RetryAfter that also accounts for an empty or slow per-minute bucket, not just the per-second wait. When the minute wait is longer, ResetAt is rounded up to a whole second
  • Extracts evaluation into MemoryLimiter.allowAt with an explicit timestamp, and adds a tokenDelay helper that computes the minute limiter's wait without consuming a token
  • Behavioral Change: callers of Allow see longer (combined) RetryAfter values and rounded-up ResetAt when the minute bucket is empty; unrepresentable minute delays report rate.InfDuration. See memory.go

Macroscope summarized a2f392f.

When the per-second bucket refused a request, MemoryLimiter returned its
delay without checking the per-minute bucket. With both empty, a client
that honored Retry-After was refused again. Report the longer of the two
waits, reading the minute bucket without taking a token, and round the
reset time up to a whole second.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-14T22:14:01.857634Z a2f392f New commits
🔒 Security Review ✅ Completed 2026-10-14T22:16:02.593609Z a2f392f New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@silo-kody

silo-kody Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 10 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9e998aa5-623b-4566-92e8-cde1958e7b56
📥 Commits

Reviewing files that changed from the base of the PR and between ece16f8 and a2f392f.

📒 Files selected for processing: 2
  • internal/ratelimit/memory.go
  • internal/ratelimit/memory_test.go
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@macroscopeapp

macroscopeapp Bot commented Oct 14, 2026

Copy link
Copy Markdown

The 429 response headers change and the Evidence section does not show them:

  • internal/ratelimit/memory.go: Retry-After now includes the minute-bucket wait; add before-and-after API response excerpts for the same rate-limited request.
  • internal/ratelimit/memory.go: X-RateLimit-Reset is rounded up to that wait; include it in those excerpts and name the API surface and build or commit.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 14, 2026

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d7ebea7158

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/ratelimit/memory.go Resolved

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adversarial review (gpt-6.1-sol, reviewed d7ebea7)

[P2] Round up the minute wait in the refresh response paths — internal/api/handlers/catalog_actions_service.go:90 and :260

The person and trailer refresh handlers still convert result.RetryAfter with max(1, int(result.RetryAfter.Seconds())). With their normal limit of 10 requests/second, 10/minute, burst 10, send ten requests 10ms apart and the next at T+91ms. The new minute check returns about 5.909s, but both handlers emit Retry-After: 5. At T+5.091s the minute bucket has only about 0.8485 tokens, so a client honoring that header receives another 429. Both the v1 writer and the v2 serviceProblem adapter forward the truncated integer unchanged. This rounding predates the PR, but it leaves the reported retry problem unresolved on these two affected callers. Round positive durations up at both conversions and test the emitted header with a fractional minute wait; the new tests exercise AllowResult directly and cannot catch this.

Verified from the source and an arithmetic check of the bucket updates. Go tests and live deployment validation were unavailable.

AI disclosure: Codex, gpt-6.1-sol.

@macroscopeapp

macroscopeapp Bot commented Oct 14, 2026

Copy link
Copy Markdown

Validation tasks: none omits the Server limits & audit logs Server case #1217 C1, which explicitly tests rate throttling. This PR changes the retry/reset values when both in-memory buckets are exhausted. C1 is currently Not run, so no recorded result is being invalidated.

Suggested line: Validation tasks: changes #1217 C1

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

…delay

When the minute bucket's wait saturates to rate.InfDuration, adding a
second to round it up overflowed and set X-RateLimit-Reset in the past.
Round the time instead, which saturates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104
Quick104 merged commit 43aa3e5 into main Oct 14, 2026
19 checks passed
@Quick104
Quick104 deleted the fix/issue-2486-memory-retry-after branch October 14, 2026 22:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] In-memory rate limit sends a too-short Retry-After when the minute bucket is also empty

1 participant