Skip to main content

Encode a CDN path only as much as it needs

3 November 2026 · Field notes · the engineering team

The story

When our cleanup deletes objects, it asks the CDN to invalidate them. Each deleted key becomes a path, and past a cap of thirty paths we send one wildcard over the prefix instead. The function that turns a key into a path split the key on slashes and ran each segment through the standard URL component encoder. It also encoded a literal asterisk as %2A, so a key could never act as a wildcard.

That encoder is broader than the rule the CDN's API states. The API wants characters that are not safe in a URL encoded: space, non-ASCII, the percent sign, quotes, brackets, braces and a few more. It wants a reserved set left literal: ! $ & ' ( ) + , ; = : and @. The old line encoded the whole segment and had no step that put the reserved characters back.

The fix keeps the per-segment encoding and then turns the reserved set back into literal characters. The asterisk still becomes %2A, and a percent sign in a key stays %25. We pinned it with a test. A key with a space and a segment of $x+(1).png comes out as a%20b and $x+(1).png. An é becomes %C3%A9. A segment of !&',;=:@.js stays exactly as it was.

The pattern

Encode a path to match what the service documents, not to be as safe as possible. More encoding is not safer here, because the path is a name the service has to match. A path that spells a character differently from the rule names something else.

Two habits keep this small. Encode per segment, so the slash stays a separator and is never escaped. Then take the service's rule as two lists, what must be encoded and what must stay literal, and write both into the code, with a comment saying where the rule comes from. A general-purpose encoder knows neither list.

Keep the guard that is yours, not the service's. Our rule that a literal asterisk becomes %2A stayed as it was, because it stops a key from acting as a wildcard.

Try it

Find the place where you build a path or URL for an external API and check it against the API's own encoding rule.

  • Write down the characters the API says to encode and the characters it says to leave literal.

  • Check what your encoder does with each of them.

  • Add one test with a space, a non-ASCII character, a percent sign, an asterisk and a few reserved characters, and assert the exact output.

  • Where your encoder goes beyond the rule, put the characters back after encoding, and say why in a comment.

cdnencodinginvalidationtesting