fix: rate limit translation queue requests
Summary
- add an IP-based per-minute limit before public translation requests can enqueue Workers AI translation work
- hash client IPs before using them in Cache API keys
- return a 429 with Retry-After when the translation request limit is exceeded
Why
The public translation endpoint can enqueue paid Workers AI translation jobs. Cached ready translations are still served normally, but cache misses now have a small per-IP guardrail so repeated public requests cannot keep queueing translation work unchecked.
Tests
- npx vitest run tests/translation-queue.unit.test.ts --config vitest.config.cloudflare.ts
Summary by CodeRabbit
-
New Features
- Translation requests are now rate-limited per client IP with a configurable limit (default: 30 requests).
- Requests exceeding the limit return HTTP 429 with retry timing headers for proper client handling.
-
Tests
- Added tests verifying rate-limiting behavior across multiple requests.
The translation worker now enforces per-IP rate-limiting on translation requests. The change introduces cache-backed counters for each client IP, configurable request limits via environment binding, and HTTP 429 responses with Retry-After headers for rate-limited requests. A rate-limit check is inserted before translation work is queued. Translation Worker Rate-Limiting π A rabbit hops to rate each hop,
By IP hash and cached clock,
Too quick? A 429 shall appear,
"Try again," the headers cheer,
Requests flow, but not too near! π π― 2 (Simple) | β±οΈ ~10 minutes βοΈ Tip: You can configure your own custom pre-merge checks in the settings.π Walkthrough
Walkthrough
Changes
Layer / File(s)
Summary
Constants and Type Definitions
cloudflare_workers/translation/index.tsCache path, TTL, and default limit constants defined.
RateLimitEntry type holds per-IP count and resetAt timestamp.
Environment Configuration
cloudflare_workers/translation/index.tsWorker bindings interface extended with optional
TRANSLATION_MESSAGES_RATE_LIMIT string to configure the per-IP request limit.
Rate-Limit Checking Logic
cloudflare_workers/translation/index.tscheckTranslationRequestRateLimit() helper extracts client IP from Cloudflare/forwarded headers, hashes it, reads/updates per-IP counter and reset timestamp in caches.default, and throws HTTP 429 when limit is exceeded.
Error Response Enhancement
cloudflare_workers/translation/index.tserrorResponse() now includes Retry-After header when status code is 429.
Handler Integration
cloudflare_workers/translation/index.tshandleTranslationMessages() calls rate-limit check before queueing translation work.
Test Infrastructure and Cases
tests/translation-queue.unit.test.tsstubStatefulWorkerCache() provides a stateful cache mock backed by Map. New concurrency test verifies first request succeeds with HTTP 202, second request from same IP returns 429 with retry-after: 60, and queue send is called only once.Possibly related PRs
handleTranslationMessages in the same translation worker file.Poem
π₯ 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
Title check
β
Passed
The title accurately summarizes the main change: adding rate limiting to translation queue requests, which aligns with the code changes that implement IP-based per-minute rate limiting.
Description check
β
Passed
The PR description includes a clear summary of changes, rationale, and testing instructions, though it lacks the full checklist items and manual testing steps from the template.
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)
[!TIP]
π¬ Introducing Slack Agent: The best way for teams to turn conversations into code.
Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
- Generate code and open pull requests
- Plan features and break down work
- Investigate incidents and troubleshoot customer tickets together
- Automate recurring tasks and respond to alerts with triggers
- Summarize progress and report instantly
Built for teams:
- Shared memory across your entire orgβno repeating context
- Per-thread sandboxes to safely plan and execute work
- Governance built-inβscoped access, auditability, and budget controls
One agent for your entire SDLC. Right inside Slack.
π Get started
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.
Comment @coderabbitai help to get the list of available commands and usage tips.
Merging this PR will not alter performance
β
43 untouched benchmarks
β© 2 skipped benchmarks[^skipped]
Comparing Sauvikn98:fix-translation-rate-limit (485fc58) with main (ee54a9c)
[^skipped]: 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
Quality Gate passed
Issues
0 New issues
0 Accepted issues
Measures
0 Security Hotspots
0.0% Coverage on New Code
0.0% Duplication on New Code
I checked the failing "Run tests" job and the PR currently breaks at bun typecheck, before the worker tests run.
The two blocking errors are both in cloudflare_workers/translation/index.ts:
- Line 153: the conditional
headersvalue is inferred as{ 'Retry-After': string } | { 'Retry-After'?: undefined }, which is not assignable toHeadersInit. A small fix is to annotate it asHeadersInitor build aHeadersobject only for the 429 case. - Line 234:
globalThis.caches?.defaultdoes not typecheck because TypeScript seesglobalThis.cachesasCacheStorage, which does not expose Cloudflare'sdefaultcache property. This needs a Cloudflare-compatible type cast/wrapper before reading.default.
So even after the counter reset issue from CodeRabbit is addressed, this PR still needs those two type fixes for CI to pass.
The limiter is built as a read/modify/write on caches.default, so concurrent requests from the same IP can all read the same cached count before any put() wins. In a burst, each request computes the same next count and they can all proceed even when the configured limit is 1 or 30, which is exactly the traffic pattern this endpoint needs to control. The current test only sends requests sequentially, so it cannot catch this. Could we move the counter to something atomic/durable for this worker path (for example D1/KV with a compare/update strategy or a Durable Object), or at least add a concurrent-request regression test that demonstrates the chosen primitive rejects requests beyond the limit?
The rate limiter here is not concurrency-safe enough to protect the queue from the burst it is meant to stop. checkTranslationRequestRateLimit() does a cache.match() / increment / cache.put() read-modify-write against caches.default, but that operation is not atomic. If a single IP sends a parallel burst, each isolate/request can read the same cached entry (or a miss), compute the same next count, and then all enqueue before the last put() wins. The new regression only covers serial requests, so it would not catch this.
For this to actually cap translation queue pressure, the counter needs an atomic backing store or serialized owner, e.g. a Durable Object keyed by IP hash, or a D1/KV design with an atomic conditional update. At minimum I would add a parallel-request regression that fires Promise.all() over more than TRANSLATION_MESSAGES_RATE_LIMIT requests and asserts only the allowed number reaches queue.send().