A walk through how CloudFront Functions actually work.
Step-by-step — both in terms of architecture and execution flow.
1. Where They Run
- CloudFront has over 400+ edge locations
worldwide (Points of Presence, or PoPs).
- A CloudFront Function is deployed to every
single PoP, so it runs as close as possible to the viewer (the
client/browser).
- This is why it can execute in sub-milliseconds — no long network hops to a central server.
2. Trigger Points
CloudFront Functions only run at two
event stages in the request/response lifecycle:
- Viewer Request
– right after the viewer (browser, app) sends a request to CloudFront, before
CloudFront decides where to fetch the content from.
- Viewer Response
– right before CloudFront sends a response back to the viewer.
Important to note: CloudFront Functions never see “origin request” or “origin response” events — that’s Lambda@Edge territory.
3. Deployment & Versioning
- twtech writes the function in JavaScript (ECMAScript
5.1).
- When twtech publishes it, CloudFront replicates it to
all PoPs globally in seconds.
- Functions are versioned — twtech associates a
specific version with a CloudFront distribution behavior.
- Since they are tied to behaviors, twtech can apply different functions to different paths or cache behaviors.
4. Execution Environment
- Sandboxed
JavaScript runtime (isolated, no network or filesystem access).
- Memory: ~2 MB
- Execution limit: < 1 ms per invocation
(measured at the edge).
- Deterministic: No async calls, no external libraries,
only built-in JavaScript features.
- Output must be a modified HTTP request or response object (immutable input → you clone/modify → return).
5. Request/Response Flow Example
Let’s say twtech has a viewer-request
CloudFront Function that redirects all twtechapp.com traffic to
https://www.twtechapp.com.
Flow:
- User request:
# vbnet
GET
/index.html
Host: twtechapp.com
- CloudFront edge location receives request.
- Viewer-request function runs:
# javascript
function
handler(event) {
var request = event.request;
if (request.headers.host.value === 'twtechapp.com') {
return {
statusCode: 301,
statusDescription: 'Moved Permanently',
headers: {
'location': { value: 'https://www.twtechapp.com' }
}
};
}
return request;
}
- If redirect condition is met → sends redirect immediately
from the edge.
- If not → passes request on to normal CloudFront caching/origin logic.
6. Advantages of This Model
- Speed
– Runs in microseconds, no origin round trip.
- Cost-efficiency
– Pricing is per request with microsecond granularity.
- Scalability
– Runs at every PoP automatically, no provisioning.
- Security – No external network calls possible, minimizing attack surface.
7. Limitations
- Can’t fetch data from APIs, S3, or databases.
- No async/await or timers.
- No origin-level logic (use Lambda@Edge for that).
- Only lightweight transformations — heavy parsing or
computation will hit limits.
No comments:
Post a Comment