Skip to content

feat(core): defer rate-limited queue messages through a RATE_LIMITED event - #657

Merged
d-klotz merged 19 commits into
nextfrom
feat/core-rate-limit-defer
Nov 24, 2026
Merged

d-klotz merged 19 commits into
nextfrom
feat/core-rate-limit-defer

Conversation

@d-klotz

@d-klotz d-klotz commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

A queue handler that hits a provider rate limit no longer gives its message back to SQS for a 30 minute redelivery that spends one of its three receives. Worker.run turns the error into a RATE_LIMITED event, the integration can decide what happens, and by default the message is put back so it runs at the time the provider said. For a long wait the user gets one client-safe RATE_LIMITED message. This is phase 2 of ADR-049 (#655), and it also carries phase 4 (the message), first opened as #658 (closed).

Stacked on #656. Merge #656 first. GitHub retargets this PR to next when #656 merges. #740 is stacked on #656 too and touches docs/reference/api-module-definition-and-functions.md, so the second of #657 and #740 to merge needs a small restack.

What problem this fixes

  • A long limit costs all three receives. A throttled handler rethrows and SQS redelivers 30 minutes later. The queue allows 3 deliveries, so a limit that lasts two hours sends the message to the DLQ, which only logs.
  • A sync split into many messages then stays open forever. One lost message means the run is never completed and never failed.
  • The user sees a run that looks stuck. Nothing says "waiting for the provider limit until 23:00 UTC".

What this PR does

The RATE_LIMITED event and the integration's handler

For an error with isRateLimited, Worker.run builds { retryAt, waitMs, reason, module, scopeKey, message, delivery: { messageId, receiveCount, deferrals, deferredMs } } (retryAt can be undefined) and calls the hook decideRateLimited(event). The queue worker of an integration calls the integration's RATE_LIMITED event handler there, with { data: event, context, delivery }, on the instance that ran the job (no second hydration).

Handler returns What the worker does
'defer', no value, or any other value The default handler runs (below)
'drop' Acknowledges the record (WARN record_dropped) and clears the wait the message set
'retry', or the handler throws Fails the record like any retryable error (deferral.skipped handler_retry / handler_failed)

The same event is meant to become the input of the ADR-047 orchestrator.

The default handler

Wait What the worker does Record
Up to 900 s Sends the same body again with DelaySeconds, then acknowledges the old message handled
Over 900 s, SCHEDULER_ROLE_ARN set Creates a one-time EventBridge schedule frigg-defer-<messageId> at retryAt that sends the body to the queue, then acknowledges (ConflictException counts as success) handled
Over 900 s, no scheduler Extends the visibility timeout to retryAt (12 h less 20 minutes at most: SQS counts the 12 h from the receive, and an extension does not reset it). This uses one receive reported failed
  • An unknown retryAt (a non-429 limit that classify names without a time) uses now plus FRIGG_QUEUE_RATE_LIMIT_PROBE_MS (default 1 h). It does not wait for the queue's visibility timeout.
  • The halt exemption. backend-utils.js no longer halts an error with isRateLimited, whatever its status, so a daily-limited 403 is deferred instead of discarded (ADR-049 §7: it lands with the deferral).
  • The new message goes out before the old one is acknowledged. Delivery stays at least once. A crash between the two can run the work twice, so handlers stay idempotent.
  • A deferred body carries _frigg: { deferrals, firstDeferredAt, deferralId }. It is reserved; handlers never see it. deferralId is the SQS id of the first message that was put back. The new message starts at receive count 1.
  • Two caps: FRIGG_QUEUE_MAX_DEFERRALS (default 30) and FRIGG_QUEUE_MAX_DEFERRED_MS (default 26 h, from the first deferral to the retry time). Past a cap, with no event source ARN, or on a FIFO queue, the record fails like any retryable error and delivery.isLastAttempt (feat(core): tell queue handlers their last delivery attempt #653) applies.

The queue worker's in-process budget is 0

MAX_IN_PROCESS_WAIT_MS.queueWorker goes from 60 s to 0, so a hinted wait never holds a worker slot: it throws RateLimitError at once and the default handler defers the message. See the release notes.

The user-facing message

The default handler writes one client-safe RATE_LIMITED integration warning { code, module, reason, retryAt (ISO UTC), actions: [{ type: 'RETRY_WHEN_READY' }, { type: 'LINK', label, url }] }, only when the wait is over 900 s, retryAt is unknown (it carries the probe time), or a cap ended the deferrals. The text and the links come from the userHints of the module's static rateLimit, keyed by reason.

  • One atomic write per adapter. appendRateLimitMessage appends only when no stored RATE_LIMITED message has the same code, module and a retryAt within 60 s, and keeps the newest 50: PostgreSQL one UPDATE … WHERE NOT EXISTS, MongoDB and DocumentDB one update with $nor/$elemMatch and $push/$slice. A write error from the raw MongoDB/DocumentDB command throws.
  • Kept from feat(core): tell the integration when a rate limit is too long to wait for #658: updateIntegrationMessages appends and keeps the newest 50 of each type (it used to overwrite); findIntegrationMessages, the repository read of the stored messages (no production caller yet); the message shape. Dropped: the Requester delegate (ADR-049 Alternative 7) and the read-then-append write.
  • A failing message hook logs WARN rate_limit_message_failed and never changes the outcome.

Run state

With a processId in the message, the worker writes, through RecordRateLimitWait and ClearRateLimitWait, Process.context.rateLimit = { status: 'WAITING' | 'EXHAUSTED', mechanism, retryAt, reason, module, deferrals, deferralId, updatedAt }. After a deferred or redelivered message ran, or was dropped by the handler, a WAITING value becomes null when that message set it (same deferralId), and for any other message only when its retryAt is past or within 5 s.

Also

  • A throttled token endpoint defers too. The fresh Error that OAuth2Requester builds for a non-definitive refresh failure keeps isRateLimited, retryAt, waitMs, reason, module and scopeKey, none of which is secret.
  • Devtools.
    • The one-time scheduler is provisioned when any API module declares static rateLimit.
    • The base role gains sqs:ChangeMessageVisibility on the stack's queues.
    • For ownership.queue: 'external', the functions get sqs:SendMessage, GetQueueUrl, GetQueueAttributes and ChangeMessageVisibility on that queue's ARN, and the scheduler role sqs:SendMessage on it. The ARN keeps the stack's partition, reads the region of every SQS host form, and lets CloudFormation split a queue.url that is a Serverless variable or a CloudFormation function.
  • One log record per outcome. Acknowledged: WARN record_deferred. Dropped: WARN record_dropped. Not acknowledged before the last receive: one WARN (record_deferral_capped, record_visibility_extended, or record_failed with deferral.skipped). Not acknowledged on the last receive: one ERROR record_lost_rate_limited with the same details, and no WARN.
  • The scheduler and SQS clients honour the local endpoint (awsConfigOptions()), so frigg start and LocalStack do not reach real AWS on a deferral.

Handler contract

Check the last attempt first, then rethrow. Do not catch a RateLimitError to defer the message yourself; the RATE_LIMITED handler decides that.

async processBatch({ data, delivery }) {
    try { await this.syncPage(data); }
    catch (error) {
        if (delivery?.isLastAttempt) return this.failRun(data.processId, error);
        throw error; // a RateLimitError too: core puts the message back at retryAt
    }
}

The delay and schedule tiers send a new message, so they never reach the last attempt. The visibility tier and a cap use a receive; on the last one the worker writes ERROR frigg.worker.record_lost_rate_limited, and the handler has that one chance to end the run.

Design choices worth a look

  • The mock scheduler is never used for a deferral. A schedule kept in memory would be lost with the acknowledged message. The worker builds the EventBridge adapter only when SCHEDULER_ROLE_ARN is set and SCHEDULER_PROVIDER is not mock.
  • The queue URL comes from record.eventSourceARN (GetQueueUrl by name, memoized per invocation). The base Worker has no integration name for a <NAME>_QUEUE_URL.
  • sqs:ChangeMessageVisibility is granted to every stack, because feat(core): honour Retry-After and let API modules declare rate limits #656 honours Retry-After for every module. ADR-049 §8 asks for a byte-identical template when no module declares rateLimit; this action string, and the statement for an external queue, are the deviations.
  • The handler runs on the instance that ran the job, through a WeakMap keyed by the parsed body that Worker.run passes through.

Caveats

  • Not run against real AWS. Every tier ran end to end against LocalStack before the rework and is unit-tested with aws-sdk-client-mock. Before production, run one throttled message per tier on a dev stack and check the queue, the schedule group and CloudTrail.
  • The atomic write is proven locally, not in CI. integration-repository-messages-parity.db.test.js (20 concurrent writers store one message) passed against MongoDB (replica set) and PostgreSQL 16 locally; the db job that would run it in CI fails at MongoDB start on next too (CI: fix long-standing red db and build (22.x) checks #739). DocumentDB itself was not run.
  • ReportBatchItemFailures and our own ChangeMessageVisibility. I believe Lambda does not reset the visibility of a reported failure, but I have not verified it. If it does, that tier falls back to the 30 minute redelivery.
  • A wait over 26 hours (a monthly quota) is capped at once. Raise FRIGG_QUEUE_MAX_DEFERRED_MS for an app that wants longer.
  • The run state is read, then written. Two workers that write in the same instant can keep the earlier retryAt. It is a UI signal only.
  • Twenty workers on one limit each defer their own copy. Nothing paces them yet (phase 5).

Not in this PR

Pacing (phase 5), the module policies (friggframework/api-module-library#102, draft until this core is released), and the reviewer's non-blocking #656 follow-ups (#740).

Test plan

  • core, all files in one jest worker (npx jest -i): 217 suites, 3,225 tests pass, 0 failures
  • devtools (npx jest): 101 suites, 2,114 tests pass (3 suites skipped, as on next)
  • core/Worker.deferral.test.js: the event, the four handler outcomes, the probe, the three tiers, the two caps, the message hook (only over 900 s, probe or cap), the wait cleared on drop, one log record per outcome
  • integration-defined-workers.test.js: the integration's RATE_LIMITED handler on the instance that ran the job (one hydration), an untimed classified 403 is not halted and is scheduled at +1 h, the warning written with the module's links on the integration that ran the job, and none for a wait of up to 15 minutes
  • the three adapters' appendRateLimitMessage and updateIntegrationMessages, the use case, the shared ARN helper (7 cases), the external-queue IAM statement
  • integration-repository-messages-parity.db.test.js against local MongoDB and PostgreSQL 16 (see caveats)
  • type declarations checked with tsc --strict
  • eslint: 0 errors on the changed files
  • CI: build (22.x), build (24.x), lint, SonarCloud green. db (CI: fix long-standing red db and build (22.x) checks #739) and release (checkout with ADMIN_TOKEN on labelled PRs) fail for reasons outside this PR

Release notes

  • Upgrade @friggframework/core and @friggframework/devtools together, and redeploy. Devtools grants the IAM actions and switches on the scheduler; core does the deferral.
  • The queue worker no longer sleeps for a hinted rate limit. Before, a 429 with Retry-After or a classified limit could wait in process (up to 60 s with feat(core): honour Retry-After and let API modules declare rate limits #656). Now the message is deferred at once and the handler runs again from the start at retryAt. So:
    • handlers must be idempotent (they already must be, delivery is at least once);
    • every deferral counts toward FRIGG_QUEUE_MAX_DEFERRALS (30). A job with many calls that keeps hitting a short burst limit can reach the cap and fail; keep each message's work small, or raise the cap;
    • a handler that catches every error now sees a RateLimitError that the Requester used to retry in process. Rethrow it.
      A 429 with no hint keeps the fixed backOff ladder, as before.
  • A rate-limited 4xx is no longer discarded. A provider limit signalled with a 403 is now deferred.
  • Optional: an integration can define a RATE_LIMITED event handler, and a module can add userHints text and links to its static rateLimit. New env var: FRIGG_QUEUE_RATE_LIMIT_PROBE_MS.

🤖 Generated with Claude Code

📦 Published PR as canary version: 2.0.0--canary.657.f16d20b.0

✨ Test out this PR locally via:

npm install @friggframework/admin-scripts@2.0.0--canary.657.f16d20b.0
npm install @friggframework/core@2.0.0--canary.657.f16d20b.0
npm install @friggframework/devtools@2.0.0--canary.657.f16d20b.0
npm install @friggframework/eslint-config@2.0.0--canary.657.f16d20b.0
npm install @friggframework/prettier-config@2.0.0--canary.657.f16d20b.0
npm install @friggframework/schemas@2.0.0--canary.657.f16d20b.0
npm install @friggframework/serverless-plugin@2.0.0--canary.657.f16d20b.0
npm install @friggframework/test@2.0.0--canary.657.f16d20b.0
npm install @friggframework/ui@2.0.0--canary.657.f16d20b.0
# or 
yarn add @friggframework/admin-scripts@2.0.0--canary.657.f16d20b.0
yarn add @friggframework/core@2.0.0--canary.657.f16d20b.0
yarn add @friggframework/devtools@2.0.0--canary.657.f16d20b.0
yarn add @friggframework/eslint-config@2.0.0--canary.657.f16d20b.0
yarn add @friggframework/prettier-config@2.0.0--canary.657.f16d20b.0
yarn add @friggframework/schemas@2.0.0--canary.657.f16d20b.0
yarn add @friggframework/serverless-plugin@2.0.0--canary.657.f16d20b.0
yarn add @friggframework/test@2.0.0--canary.657.f16d20b.0
yarn add @friggframework/ui@2.0.0--canary.657.f16d20b.0

@d-klotz d-klotz added release Create a release when this pr is merged prerelease This change is available in a prerelease. labels Sep 28, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 28, 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-09-28T23:44:40.707723Z ebe5c60 PR opened
ℹ️ 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.

d-klotz added a commit that referenced this pull request Sep 28, 2026
Records the answers to open questions 1 to 4 (Retry-After for every module,
a 5 minute in-process cap, a new message for a wait up to 15 minutes and the
scheduler beyond, 10 deferrals and 24 hours) and brings the text and the
sketches in line with the code in #656 and #657.

Changes to the text:
- the hint wins; the fixed ladder is used only when there is no hint, and it
  has no budget;
- classify runs for a 429 and any other 4xx or 5xx except 401, not for a 2xx,
  and may name only a reason;
- the invocation deadline lives in its own AsyncLocalStorage;
- the handler checks delivery.isLastAttempt first, then rethrows, because the
  visibility tier and a cap use a receive;
- the RATE_LIMITED message has no `scheduled` flag and is deduplicated;
- the base role gets sqs:ChangeMessageVisibility in every stack.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@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: ebe5c602d3

ℹ️ 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 packages/core/core/Worker.js Resolved
@d-klotz

d-klotz commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the automated review in the latest commit:

  • Shared context.rateLimit (Codex P2): the value is one per process, so an unrelated message that succeeded could clear it while another message still waited. The queue worker now compares times. A new wait replaces the stored one only when its retryAt is later, a WAITING value never hides an EXHAUSTED one, and after a deferred or redelivered message ran the worker clears the value only when it is WAITING and its retryAt is past or within 5 s (the scheduler fires up to a second early). Both hooks now read the process first; a failed read is logged and never changes the outcome. 15 tests cover it.
  • SonarCloud: defer() is split into one helper per tier, which brings its cognitive complexity under the limit. The two no-op hooks have a body. The redelivery check no longer negates a comparison, because !(receiveCount > 1) is not receiveCount <= 1 when the count is unknown.

This branch also merges the fixes made to #656 (the review of the Requester), so the stack stays in sync.

Full packages/core run: 2,769 pass, and the same 63 failures as origin/next in this environment.

@claude claude 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.

Beyond the inline findings, I also checked two other candidate issues and ruled them out: context.rateLimit (backend-utils.js) is a brand-new field with no prior usage anywhere in the codebase, so there's no overwrite risk for existing integration data; and the visibility-extension deferral path for externally-owned/non-scheduler queues is still bounded by SQS's native receive-count/isLastAttempt check (independent of the body-embedded deferral counter), so it can't extend visibility forever even though that counter itself doesn't advance on redelivery.

Extended reasoning...

This PR is a large, security/reliability-sensitive change to the queue worker's rate-limit deferral logic (Worker.js, backend-utils.js, oauth-2.js, scheduler-builder.js) with three confirmed findings already flagged inline (a scheduler IAM/deploy gap, a lost module name on OAuth rate limits, and a rate-limit-state clearing race across sibling messages). I independently traced two additional candidate concerns from the ruled-out list — a potential field-overwrite in backend-utils.js and a potential unbounded-visibility-extension loop for external queues in Worker.js — and confirmed via the code (grep for prior context.rateLimit usage, and the delivery.isLastAttempt gate at Worker.js's visibility branch) that neither holds up as a bug.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Comment thread packages/core/core/Worker.js Resolved

@claude claude 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 completed

Nothing new to post: everything this review found is already covered by existing comments on this pull request or didn't merit a separate one.

@claude claude 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 skipped — your organization has no extra usage available to pay for this review.

If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.

Once extra usage is available, comment @claude review on this pull request, or push a new commit, to trigger a review.

d-klotz added a commit that referenced this pull request Sep 30, 2026
ADR-049 section 4 said the run state is cleared only when its retryAt is
past or within 5 s. A local end-to-end run showed the gap: a job that
resumed before its retryAt finished, and its process kept
`status: 'WAITING'`. The deferred body now carries `_frigg.deferralId`, the
run state stores it, and the message that set a wait clears it at once;
other messages still clear it only after its retry time
(#657).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@cursor

cursor Bot commented Oct 24, 2026

Copy link
Copy Markdown

Frigg 2.0.1 review (Group 2) — COMMENT only

Checklist

  • Requeue / deferral decision lives in the worker or eventing, not the API module: pass
    • Worker.js + queues/queue-deferral.js catch RateLimitError, SQS DelaySeconds ≤15m, EventBridge Scheduler beyond that, visibility fallback if scheduler unavailable.
    • API/Requester still only waits in-process or throws (from #656).

Verdict (would): would approve

Findings

None blocking. One nit: ensure scheduler IAM / SCHEDULER_ROLE_ARN failure modes are called out in operator docs (tests cover visibility fallback). Stack on #656 as intended.

@claude claude 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 skipped — your organization's extra usage balance is too low to start another review, so this review was not started.

An organization admin can add extra usage credits at claude.ai/admin-settings/usage.

Once credits are available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.

Comment thread packages/core/core/Worker.js Resolved
d-klotz added a commit that referenced this pull request Nov 9, 2026
Phase 1 alone sent a rate-limited 403 back to SQS. With the generated
queue config (3 receives about 30 min apart) a daily limit then reached
the DLQ after about an hour, so the work was still lost. The halt
exemption moves to the deferral change (#657), which puts the message
back at its retry time. Phase 1 keeps the halt rule of next.

The reference doc now also says that a 429 reads all default parsers,
not only Retry-After.

Refs ADR-049 §7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@seanspeaks seanspeaks left a comment

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.

The mechanical side is in good shape: the delay / schedule / visibility tiers, ConflictException treated as success, the 30 min / 26 h caps, write-before-send on the delay tier, the deferralId clear rule, IAM, and the OAuth _transportFailureError field copy. The blockers are about matching the amended ADR-049 §3, which you'd already flagged a rework for.

Blocking

  1. packages/core/core/Worker.js, run() catch, the if (error.isRateLimited) branch: §3 wants Worker.run to build a RATE_LIMITED event and hand it to the integration's handler when one exists ('defer' / 'drop' / 'retry'), with the current tiers as the default handler. This still calls defer() directly. Please rework to that seam so it can also become the ADR-047 reducer's input later, rather than a parallel path.

  2. Worker.js defer(), the if (!retryAt) return { outcome: 'skipped', skipped: 'no_retry_at' } guard: an unknown retryAt should use FRIGG_QUEUE_RATE_LIMIT_PROBE_MS (default 1 h) instead of SQS's visibility timeout. With the halt exemption this PR adds in backend-utils.js, an untimed classified 403 is no longer halted but also isn't deferred, so it can still burn three receives and land on the DLQ. That's the failure mode phase 2 was meant to close.

  3. packages/core/core/invocation-deadline.js MAX_IN_PROCESS_WAIT_MS.queueWorker is still 60_000 (and integration-defined-workers.js is unchanged). §7 says phase 2 sets the queue-worker budget to 0 so a hinted wait doesn't hold one of the 20 worker slots. Please drop it to 0 here now that deferral exists.

  4. Per my note on #658: the user-facing rate-limit message should be written by the default handler in this PR (only past the 900 s delay tier, an unknown retryAt, or a cap), with an atomic dedup, rather than via the Requester delegate.

Also, build (22.x) is failing on this head. I haven't dug into the logs, so worth a look as part of the rework. Since #656 needs a rebase onto next first, this will need restacking after that anyway.

d-klotz added a commit that referenced this pull request Nov 23, 2026
Phase 1 alone sent a rate-limited 403 back to SQS. With the generated
queue config (3 receives about 30 min apart) a daily limit then reached
the DLQ after about an hour, so the work was still lost. The halt
exemption moves to the deferral change (#657), which puts the message
back at its retry time. Phase 1 keeps the halt rule of next.

The reference doc now also says that a 429 reads all default parsers,
not only Retry-After.

Refs ADR-049 §7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@d-klotz
d-klotz force-pushed the feat/core-rate-limit-requester branch from 602fc50 to 05978d8 Compare November 23, 2026 20:35
d-klotz and others added 6 commits November 23, 2026 17:43
Restack of the queue worker deferral (previously 30 commits and 4 merges
of feat/core-rate-limit-requester) onto the #656 branch rebased on next:
the delay, schedule and visibility tiers, the deferral caps, the
Process.context.rateLimit run state, the scheduler role and queue
permissions, and the token-refresh rate-limit field copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ADR-049 section 7 sets the queue-worker budget to 0 in phase 2. A hinted
wait then throws RateLimitError at once, the worker defers the message,
and the wait does not hold one of the worker slots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…time

ADR-049 section 3: an unknown retryAt uses now plus
FRIGG_QUEUE_RATE_LIMIT_PROBE_MS (default 1 h), not the visibility timeout
of the queue. The no_retry_at skip is gone. A classified 403 with no time
is not halted, and it now gets a deferral instead of three receives and
the DLQ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ADR-049 section 3: Worker.run builds one RATE_LIMITED event (retryAt,
waitMs, reason, module, scopeKey, message, delivery) and gives it to the
decideRateLimited hook. The queue worker of an integration calls the
integration's RATE_LIMITED event handler through the event dispatcher,
on the instance that ran the job, with no second hydration.

'defer' or no value runs the default handler (the deferral tiers),
'drop' acknowledges the record with one WARN record_dropped, and 'retry'
fails it. A handler that throws counts as 'retry'. The same event can
become the input of the ADR-047 reducer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… type

Carried from frigg#658, as the review asked. The MongoDB and PostgreSQL
adapters read integration.messages, which their records do not have, so
each write replaced the stored list with one item. They now append to the
stored list of the type, and every adapter keeps the newest 50 items.
updateIntegrationMessages takes one message item, so an item can carry
extra keys (code, module, retryAt, actions). findIntegrationMessages reads
the stored items of one type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ADR-049 section 5 and the frigg#658 review: twenty workers can meet the
same limit at once, so the write must not read, then append.
appendRateLimitMessage appends the item only when no stored item of the
type has the same code and module and a retryAt in the given window, and
keeps the newest items of the type. MongoDB and DocumentDB use one update
command with a $nor/$elemMatch filter and $push with $each/$slice
(DocumentDB 4.0+). PostgreSQL uses one UPDATE with a NOT EXISTS guard.

integration-repository-messages-parity.db.test.js runs every adapter
against real databases, with twenty concurrent writes of one limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
d-klotz and others added 4 commits November 23, 2026 19:30
ADR-049 section 5 and the frigg#657 and frigg#658 reviews: the component
that defers writes the message, not a Requester or module delegate. The
default handler calls the recordRateLimitMessage hook only when the wait
is over 900 s, retryAt is unknown (the message has the probe time), or a
cap ended the deferrals. It writes nothing for a short wait, for a
skipped deferral, or when the RATE_LIMITED handler drops or retries. A
failing hook logs rate_limit_message_failed and keeps the outcome.

The QueueWorker writes the warning through RecordRateLimitMessage on the
integration that ran the job. The use case builds the client-safe shape
kept from frigg#658 (code, module, reason, ISO UTC retryAt,
RETRY_WHEN_READY and LINK actions) with the text and links of the
userHints of the module that the event names, keyed by reason. It writes
through the atomic appendRateLimitMessage, so concurrent workers write
one warning, and the type keeps its newest 50 items.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
d-klotz added a commit that referenced this pull request Nov 23, 2026
The default handler of phase 2 writes the message, so phase 4 ships in
frigg#657 and frigg#658 closes. Also say that an unknown value from the
RATE_LIMITED handler counts as 'defer'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@d-klotz
d-klotz force-pushed the feat/core-rate-limit-defer branch from f16d20b to ef76df6 Compare November 23, 2026 22:44

@claude claude 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 skipped — your organization has no extra usage available to pay for this review.

If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.

Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.

d-klotz and others added 4 commits November 23, 2026 20:28
A virtual mock of @aws-sdk/client-scheduler is missed when an earlier test
file in the same jest worker (Worker.deferral.test.js) already resolved the
real package, so five lazy-loading tests failed in CI. The package is a
hard dependency, so a plain mock covers the same cases in any order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rror

The raw MongoDB and DocumentDB update command returns write errors in its
result instead of throwing, so a failed append looked like a stored
message. The Worker hook logs the throw as rate_limit_message_failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A dropped message never runs again, so a WAITING Process.context.rateLimit
that it set stayed until another wait replaced it. Clear it as after a
success, with the same deferralId rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SonarCloud S3403 read the string checks on the base hook's result as
always false and failed the reliability gate. A Map lookup states the
three outcomes in one place; any other value, also a prototype key,
still runs the default handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
d-klotz and others added 4 commits November 24, 2026 06:59
The RATE_LIMITED event carries scopeKey, but the token refresh transport
error copied every rate-limit field except it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/guides/LOGGING.md sets the eventName at the call site, so the full
frigg.worker.record_deferral_capped and record_visibility_extended names
now appear as literals and can be found with a search.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nd host

The scheduler role took the region from the second label of the queue
host and hard-coded the aws partition, so a legacy queue.amazonaws.com
URL got a wrong region, a China or GovCloud stack a wrong partition, and
a queue.url that resolves after the build (a Serverless variable or a
CloudFormation function) threw. The shared helper leaves the partition
to the stack, reads the region of every SQS host form, and lets
CloudFormation split a value that is not a URL yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The base role grants SendMessage, GetQueueUrl, GetQueueAttributes and
ChangeMessageVisibility only on the queues the stack names, so for
ownership.queue 'external' the delay and visibility tiers of a
rate-limit deferral were denied and fell back to SQS redelivery. ADR-049
gives the base role these actions in every stack, so the integration
builder now adds them on the external queue's ARN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cursor

cursor Bot commented Nov 24, 2026

Copy link
Copy Markdown

Bugbot is paused — on-demand spend limit reached

Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

@d-klotz

d-klotz commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Reworked to the amended ADR. Restacked on the rebased #656, so the old 30 commits + merges are one restack commit (667cbad) plus the rework on top.

Blocking

  1. RATE_LIMITED seam → 36f3948. Worker.run builds the §3 event and passes it to decideRateLimited. The queue worker calls the integration's RATE_LIMITED handler on the instance that ran the job (no second hydration). 'drop' acks, 'retry' / a throw fails the record, 'defer' / nothing runs the tiers.
  2. Probe → d29a4f4. Unknown retryAt = now + FRIGG_QUEUE_RATE_LIMIT_PROBE_MS (1 h). The no_retry_at skip is gone. Test for your case: an untimed classified 403 isn't halted and is scheduled at +1 h.
  3. Worker budget 0 → 9f0d94e. A hinted wait in the worker now throws at once, no sleep.
  4. Message from the default handler → 31e05c8 (+ 711daff, f1642d3). Only over 900 s, unknown retryAt or a cap. One atomic append per adapter (Postgres UPDATE … WHERE NOT EXISTS, Mongo/DocumentDB one update with $nor/$elemMatch + $push/$slice). Parity test: 20 concurrent writes store 1 message, on Mongo + Postgres.

#658: closed. Kept the append / keep-last-50 fix, the stored-messages read and the client-safe shape. Delegate path dropped.

Also

  • build (22.x): 3d11850. A virtual mock of the scheduler SDK missed when Worker.deferral.test.js ran first in the same jest worker. Core passes in band now (217 suites).
  • beaffd3: 'drop' clears the wait the message set. ff09135: a raw Mongo/DocumentDB write error now throws instead of reading as "already stored".
  • SonarCloud reliability gate (S3403, false positive on the base hook's undefined): 1e28f3f reads the decision from a Map.
  • From a review pass: 94c649a keeps scopeKey on the rate-limited token refresh error. d399c44 builds the external queue ARN for any partition / SQS host form (and lets CloudFormation split a queue.url that resolves after the build). 266102a grants the worker the SQS actions on an external queue, so the delay and visibility tiers work there too. e8c3969 writes the frigg.worker.* event names as literals.
  • ADR: §7 says phase 4 lands in feat(core): defer rate-limited queue messages through a RATE_LIMITED event #657; an unknown handler value counts as 'defer' (41023c7).
  • db is still red, same as next, see CI: fix long-standing red db and build (22.x) checks #739.

Not done (your non-blocking #656 list): TS2305, requestTimeoutMs: 0, ms reset headers, HTTP 429/503, the classify doc warning. I'll do those as a follow-up once #656 lands.

@d-klotz d-klotz changed the title feat(core): put a rate-limited queue message back at its retry time feat(core): defer rate-limited queue messages through a RATE_LIMITED event Nov 24, 2026
d-klotz added a commit that referenced this pull request Nov 24, 2026
Add resetDeltaUnit for a reset delta in milliseconds, the 429 answer of an
HTTP route, scopeKey on the rate-limited token error, and the queue
actions that the functions get on an external queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…it-defer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@d-klotz
d-klotz changed the base branch from feat/core-rate-limit-requester to next November 24, 2026 19:09
@d-klotz
d-klotz merged commit c4cca67 into next Nov 24, 2026
9 of 10 checks passed
d-klotz added a commit that referenced this pull request Nov 24, 2026
Keeps the requestTimeoutMs: 0 note from this branch and the 0 s queue-worker budget from #657.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@seanspeaks

Copy link
Copy Markdown
Contributor

🚀 PR was released in v2.0.0-next.129 🚀

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

Labels

prerelease This change is available in a prerelease. release Create a release when this pr is merged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants