Skip to content

fix(node): count event bytes correctly so the size limits are enforced - #1390

Open
sarmah-rup wants to merge 1 commit into
segmentio:masterfrom
sarmah-rup:fix/node-event-size-guard
Open

fix(node): count event bytes correctly so the size limits are enforced#1390
sarmah-rup wants to merge 1 commit into
segmentio:masterfrom
sarmah-rup:fix/node-event-size-guard

Conversation

@sarmah-rup

Copy link
Copy Markdown

What I hit

Sending server-side events with @segment/analytics-node, oversized events weren't being caught by the client's size guard, so they'd ship and the API would reject the whole batch. It turned out the 32 KB per-event and 480 KB batch limits were not being enforced at all.

Root cause

ContextBatch.calculateSize (packages/node/src/plugins/segmentio/context-batch.ts) is a broken copy of the well-known "count UTF-8 bytes" idiom encodeURI(str).split(/%..|./).length - 1:

encodeURI(JSON.stringify(ctx.event)).split(/%..|i/).length

The . (match any character) was mistyped as a literal i, and the trailing - 1 was dropped. So instead of counting bytes it counts %XX escapes plus the letter "i". A ~39 KB event measures as ~21, passes the 32 KB guard, and gets sent. This has been the case since batching was added in #640.

Fix

Restore the correct byte count:

-    return encodeURI(JSON.stringify(ctx.event)).split(/%..|i/).length
+    return encodeURI(JSON.stringify(ctx.event)).split(/%..|./).length - 1

After the fix, calculateSize equals Buffer.byteLength(json, 'utf8') across ASCII, multibyte, and URL-reserved inputs.

Test

Added packages/node/src/plugins/segmentio/__tests__/context-batch.test.ts: a ~39 KB event is now rejected ("Event exceeds maximum event size of 32 KB"), a small event is still accepted. Verified fail before / pass after (revert the regex and the size test fails). The existing 500 KB test is unaffected. Included a patch changeset for @segment/analytics-node.

@tvs-twilio-segment

Copy link
Copy Markdown

✅ TVS Validation Passed

View full report

Show details

All validation checks have successfully completed.

@changeset-bot

changeset-bot Bot commented Jul 21, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: a876f56

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@segment/analytics-node Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

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.

1 participant