Skip to content

feat(cloudflare): Instrument Cloudflare rate limiter bindings#22035

Merged
JPeer264 merged 5 commits into
getsentry:developfrom
PeterWadie:feat/cloudflare-rate-limit-instrumentation
Jul 17, 2026
Merged

feat(cloudflare): Instrument Cloudflare rate limiter bindings#22035
JPeer264 merged 5 commits into
getsentry:developfrom
PeterWadie:feat/cloudflare-rate-limit-instrumentation

Conversation

@PeterWadie

@PeterWadie PeterWadie commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Adds automatic tracing for Cloudflare Workers rate limiter bindings, mirroring the existing R2/Queue/D1 binding instrumentation. When a RateLimit binding is accessed on env, its limit() calls are wrapped in a span.

Details

  • New instrumentRateLimit wraps the binding in a Proxy and starts a span named rate_limit <binding> around limit(), with the standard auto.faas.cloudflare.rate_limit origin.
  • Detection uses a limit duck-type in isBinding, wired into instrumentEnv after the more specific Queue/R2/D1 checks so those win when a binding also happens to expose limit.
  • The rate limit key is intentionally not recorded, since it commonly contains user-identifying data (e.g. an IP address or user id).
  • Cloudflare does not emit a native span for the rate limiter binding, so no op or custom cloudflare.rate_limit.* attributes are set for now. These can be added later if/when they land in Sentry's semantic conventions.
  • Includes unit tests plus an integration suite covering both an allowed call and a rate-limited (success: false) call.

Fixes #20871

Automatically wraps limit() calls on Cloudflare rate limiter bindings in a span, mirroring the existing R2/Queue/D1 binding instrumentation. The rate-limited outcome is recorded via a span attribute rather than an error status, and the rate limit key is not recorded to avoid leaking PII.
Copilot AI review requested due to automatic review settings July 8, 2026 02:07
@PeterWadie
PeterWadie requested a review from a team as a code owner July 8, 2026 02:07
@PeterWadie
PeterWadie requested review from JPeer264, andreiborza and mydea and removed request for a team July 8, 2026 02:07

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Want reviews to match your repository better? Bugbot Learning can learn team-specific rules from PR activity. A team admin can enable Learning in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 53a0a03. Configure here.

Copilot AI 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.

Pull request overview

Adds first-class tracing support for Cloudflare Workers RateLimit bindings in @sentry/cloudflare. The implementation follows the existing env-binding model (D1 / Queue / R2) by detecting the binding on env access, proxy-wrapping it, and creating a span around each limit() call while recording the outcome as a span attribute (without capturing the key to avoid PII).

Changes:

  • Add isRateLimit duck-typing to detect RateLimit bindings (limit method + not JSRPC).
  • Instrument env access to wrap detected RateLimit bindings and cache the wrapped proxy.
  • Introduce instrumentRateLimit which creates a ratelimit span per limit() call and records cloudflare.rate_limit.success.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/cloudflare/src/utils/isBinding.ts Adds isRateLimit duck-type guard for RateLimit bindings.
packages/cloudflare/src/instrumentations/worker/instrumentRateLimit.ts New instrumentation proxy that wraps limit() with a span and records the success outcome.
packages/cloudflare/src/instrumentations/worker/instrumentEnv.ts Wires RateLimit detection into env proxying + caching alongside existing binding instrumentation.
packages/cloudflare/test/utils/isBinding.test.ts Adds unit coverage for isRateLimit behavior (including JSRPC proxy exclusion).
packages/cloudflare/test/instrumentations/worker/instrumentRateLimit.test.ts Adds unit tests for span creation/attributes, forwarding behavior, and avoiding key/PII capture.
packages/cloudflare/test/instrumentations/instrumentEnv.test.ts Adds tests for env detection, wrapping, forwarding, and caching of RateLimit bindings.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Adds an integration suite that exercises a real rate limiter binding through wrangler and asserts the emitted ratelimit span and its attributes, matching the coverage of the R2 and Queue binding instrumentations.

Copilot AI 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.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.

Comment on lines +1 to +18
import type { RateLimit } from '@cloudflare/workers-types';
import * as SentryCore from '@sentry/core';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { instrumentRateLimit } from '../../../src/instrumentations/worker/instrumentRateLimit';

function createMockRateLimit(success = true): RateLimit {
return {
limit: vi.fn().mockResolvedValue({ success }),
} as unknown as RateLimit;
}

describe('instrumentRateLimit', () => {
beforeEach(() => {
vi.clearAllMocks();
});

const startSpanSpy = vi.spyOn(SentryCore, 'startSpan');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Like copilot mentioned you could either do this, or move/copy startSpanSpy in every test individually as well.

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.

Moved the spy creation into beforeEach with vi.restoreAllMocks() in afterEach, so each test gets a fresh spy.

@github-actions

Copy link
Copy Markdown
Contributor

👋 @mydea, @JPeer264, @andreiborza — Please review this PR when you get a chance!

return startSpan(
{
op: OP,
name: `rate_limit ${bindingName}`,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

q: Did you cross-check with Cloudflare's own spans if these are the same there? We try to be as close to span naming as possible to what Cloudflare produces.

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.

Cross-checked: Cloudflare doesn't emit a native span for the rate limiter binding. It's not among their auto-traced bindings (KV/R2/DO), and their docs point to HTTP 429s or Analytics Engine for rate-limit observability rather than a span. So the op and cloudflare.rate_limit.* attributes had no Cloudflare-native equivalent to match. I've removed them and kept just the span plus the standard auto.faas.cloudflare.rate_limit origin.

export function instrumentRateLimit<T extends RateLimit>(rateLimit: T, bindingName: string): T {
return new Proxy(rateLimit, {
get(target, prop, receiver) {
if (prop === 'limit') {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

m: It would be nice if you could switch to a fail fast approach and start with the following:

if (prop !== 'limit') {
  return Reflect.get(target, prop, receiver);
}

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.

Done — the handler now returns early: if (prop !== 'limit') return Reflect.get(target, prop, receiver);.

op: OP,
name: `rate_limit ${bindingName}`,
attributes: {
'cloudflare.rate_limit.binding': bindingName,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

m: Before we add this we need to add it in our semantic conventions (I could add it). However, before this will be moved to semantic conventions, is this attribute in the original Cloudflare span as well? If it is not I don't think we should add it here for now

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.

Removed. It's not present in Cloudflare's native span (details in the cross-check thread), so it's out for now. Happy to re-add cloudflare.rate_limit.* if/when it's added to the semantic conventions.

import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';

const ORIGIN = 'auto.faas.cloudflare.rate_limit';
const OP = 'ratelimit';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

m: ratelimit is not part of our official span operations (yet). I have to clarify if we actually need that - but for now please remove the OP entirely. We can always add this later here and in the docs later on as a feature.

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.

Removed the op entirely.

},
async span => {
const outcome = await Reflect.apply(original, target, [options]);
span.setAttribute('cloudflare.rate_limit.success', outcome.success);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

m: Same as the others, is this attribute added in Cloudflare's spans?

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.

Removed for the same reason (not in Cloudflare's native span). The rate-limited (success: false) outcome is now covered by the integration test via the response instead of a span attribute.

const spans = findSpans(envelope, 'rate_limit MY_RATE_LIMITER');
expect(spans).toHaveLength(1);
const data = spanData(spans[0]!);
expect({

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

m: Please use the following syntax (I saw it slipped through in the R2 tests, I'll remove that there in a PR):

const event = envelopeItem(envelope);

expect(event.spans).toEqual([
  ...
])

You can check out the D1 tests, these should match the expected assertions.

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.

Switched to the D1-style assertion (const event = envelopeItem(envelope); expect(event.spans).toEqual([...])).

return span.data as Record<string, unknown>;
}

it('emits a ratelimit span with the binding name and success outcome', async ({ signal }) => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

m: It'd be nice if there would be a case to check if the .success is also false. Right now we only check agains true, but we would never know if this would be working correctly for the ratelimit to not be active/hitting

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.

Added a /ratelimit/blocked case: the binding's limit is set to 1, so the second limit() call within the period is rate limited. The test asserts the response is { success: false } and that both calls are still instrumented. Since the success attribute was removed, the rate-limited outcome is verified via the response.

Comment on lines +1 to +18
import type { RateLimit } from '@cloudflare/workers-types';
import * as SentryCore from '@sentry/core';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { instrumentRateLimit } from '../../../src/instrumentations/worker/instrumentRateLimit';

function createMockRateLimit(success = true): RateLimit {
return {
limit: vi.fn().mockResolvedValue({ success }),
} as unknown as RateLimit;
}

describe('instrumentRateLimit', () => {
beforeEach(() => {
vi.clearAllMocks();
});

const startSpanSpy = vi.spyOn(SentryCore, 'startSpan');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Like copilot mentioned you could either do this, or move/copy startSpanSpy in every test individually as well.

Remove the non-standard ratelimit span op and the cloudflare.rate_limit.* attributes (keeping the standard origin), fail-fast in the Proxy handler, and align the integration test with the D1 assertion style plus a rate-limited case.

Copilot AI 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.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 7 comments.

@@ -0,0 +1,31 @@
import type { RateLimit, RateLimitOptions, RateLimitOutcome } from '@cloudflare/workers-types';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';
Comment on lines +18 to +28
return function (this: unknown, options: RateLimitOptions): Promise<RateLimitOutcome> {
return startSpan(
{
name: `rate_limit ${bindingName}`,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,
},
},
() => Reflect.apply(original, target, [options]),
);
};
Comment on lines +49 to +57
expect(startSpanSpy).toHaveBeenLastCalledWith(
{
name: 'rate_limit MY_RATE_LIMITER',
attributes: {
'sentry.origin': 'auto.faas.cloudflare.rate_limit',
},
},
expect.any(Function),
);
Comment on lines +58 to +60
});

test('does not record the rate limit key (avoids leaking PII)', async () => {
Comment on lines +13 to +17
function findRateLimitSpans(envelope: Envelope): Array<Record<string, unknown>> {
if (envelopeItemType(envelope) !== 'transaction') return [];
const spans = (envelopeItem(envelope).spans as Array<Record<string, unknown>>) || [];
return spans.filter(s => s.origin === 'auto.faas.cloudflare.rate_limit');
}
Comment on lines +22 to +40
.expect((envelope: Envelope) => {
expect(envelopeItemType(envelope)).toBe('transaction');
const event = envelopeItem(envelope);

expect(event.spans).toEqual([
{
data: {
'sentry.origin': 'auto.faas.cloudflare.rate_limit',
},
description: 'rate_limit MY_RATE_LIMITER',
origin: 'auto.faas.cloudflare.rate_limit',
parent_span_id: expect.any(String),
span_id: expect.any(String),
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
trace_id: expect.any(String),
},
]);
})
Comment on lines +51 to +55
.expect((envelope: Envelope) => {
expect(envelopeItemType(envelope)).toBe('transaction');
// Both `limit()` calls on the blocked endpoint are instrumented.
expect(findRateLimitSpans(envelope)).toHaveLength(2);
})
@PeterWadie
PeterWadie requested a review from Copilot July 13, 2026 23:33

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@PeterWadie
PeterWadie requested a review from JPeer264 July 13, 2026 23:35
@PeterWadie
PeterWadie requested a review from Copilot July 14, 2026 20:27

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

Copy link
Copy Markdown
Contributor

👋 @mydea, @JPeer264, @andreiborza — Please review this PR when you get a chance!

@JPeer264 JPeer264 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. Thanks a lot for your contributions.

@JPeer264
JPeer264 merged commit ea3764e into getsentry:develop Jul 17, 2026
154 of 156 checks passed
nicohrubec pushed a commit that referenced this pull request Jul 17, 2026
This PR adds the external contributor to the CHANGELOG.md file, so that
they are credited for their contribution. See #22035

Co-authored-by: JPeer264 <10677263+JPeer264@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cloudflare instrument rate limiter

3 participants