capgo icon indicating copy to clipboard operation
capgo copied to clipboard

fix: rate limit translation queue requests

Open Sauvikn98 opened this issue 6 months ago β€’ 6 comments

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.

Review Change Stack

Sauvikn98 avatar May 11 '26 15:05 Sauvikn98

πŸ“ Walkthrough

Walkthrough

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.

Changes

Translation Worker Rate-Limiting

Layer / File(s) Summary
Constants and Type Definitions
cloudflare_workers/translation/index.ts
Cache path, TTL, and default limit constants defined. RateLimitEntry type holds per-IP count and resetAt timestamp.
Environment Configuration
cloudflare_workers/translation/index.ts
Worker 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.ts
checkTranslationRequestRateLimit() 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.ts
errorResponse() now includes Retry-After header when status code is 429.
Handler Integration
cloudflare_workers/translation/index.ts
handleTranslationMessages() calls rate-limit check before queueing translation work.
Test Infrastructure and Cases
tests/translation-queue.unit.test.ts
stubStatefulWorkerCache() 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

  • Cap-go/capgo#2108: Modifies handleTranslationMessages in the same translation worker file.
  • Cap-go/capgo#2046: Implements the queue consumer and translation flow that this PR's rate-limiting now protects.

Poem

πŸ‡ 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

πŸš₯ 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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
πŸ§ͺ Generate unit tests (beta)
  • [ ] Create PR with unit tests

[!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.

❀️ Share

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

coderabbitai[bot] avatar May 11 '26 15:05 coderabbitai[bot]

Merging this PR will not alter performance

βœ… 43 untouched benchmarks
⏩ 2 skipped benchmarks[^skipped]


Comparing Sauvikn98:fix-translation-rate-limit (485fc58) with main (ee54a9c)

Open in CodSpeed

[^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.

codspeed[bot] avatar May 11 '26 16:05 codspeed[bot]

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 headers value is inferred as { 'Retry-After': string } | { 'Retry-After'?: undefined }, which is not assignable to HeadersInit. A small fix is to annotate it as HeadersInit or build a Headers object only for the 429 case.
  • Line 234: globalThis.caches?.default does not typecheck because TypeScript sees globalThis.caches as CacheStorage, which does not expose Cloudflare's default cache 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.

Serve63 avatar May 11 '26 16:05 Serve63

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?

subhajitlucky avatar May 12 '26 14:05 subhajitlucky

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().

digzrow-coder avatar May 13 '26 18:05 digzrow-coder