Amazon CloudFront and Edge Delivery
Learners open a lesson player from continents your Regional ALB never sat in. Sending every video chunk, slide deck, and JavaScript bundle through a single Region’s Application Loa
Amazon CloudFront and Edge Delivery
AWS Cloud & DevOps Engineering · Lesson 13 · AWS Application Platform
Lesson Overview
Learners open a lesson player from continents your Regional ALB never sat in. Sending every video chunk, slide deck, and JavaScript bundle through a single Region’s Application Load Balancer wastes latency and often money on repeated origin fetches. Amazon CloudFront is AWS’s content delivery network: edge locations and regional edge caches that terminate viewer connections closer to users, cache what you allow, and forward what must be dynamic to origins you control—S3 for static course assets, ALB for the progress API, or custom origins when required.
Module 2 continues: Elastic Load Balancing and Route 53 made the Regional API reachable. This lesson places CloudFront in front of static media and, carefully, in front of dynamic APIs when caching rules are explicit. You will design distributions, origins, origin access controls, cache behaviors, TTLs, invalidations, and signed URL patterns for premium lesson media—without inventing CDN features or quoting stale price folklore. AWS WAF, Shield and Edge Security deepens edge security later; here you build delivery hygiene that WAF can later wrap.
TechLearningPro’s teaching shape: S3-origin static lesson assets via CloudFront with origin locked from public bucket surfing; optional ALB origin for HTML shell or API with cache disabled or carefully keyed; Route 53 alias to the distribution; budgets watching transfer and request dimensions.
Learning Objectives
By the end of this lesson you will be able to:
- Explain why edge delivery exists for global learners beyond a single Regional ALB.
- Define CloudFront distributions, price classes, and alternate domain names (CNAMEs/aliases).
- Configure origins for S3 and ALB/custom HTTP origins with correct protocol policies.
- Protect S3 origins with Origin Access Control (OAC) patterns so buckets are not world-listable.
- Design cache behaviors by path pattern: static assets vs API paths.
- Reason about cache keys, TTLs, and
Cache-Controlheaders without magical thinking. - Create and scope invalidations deliberately; prefer versioned object names when possible.
- Describe signed URLs and signed cookies for premium media access at a conceptual level.
- Attach ACM certificates in the correct Region for CloudFront viewer HTTPS.
- Alias Route 53 to CloudFront for learner-facing hostnames.
- Compare CloudFront vs ALB-only vs S3 website hosting for TechLearningPro assets.
- Identify cost drivers (requests, transfer, invalidations, price class) and verify live pricing.
- Troubleshoot cache misses, 403 origin access failures, and TLS hostname mismatches.
- Clean up lab distributions, OAC configs, and test objects; leave budgets enabled.
- Preview how WAF association and Shield fit later without implementing them here.
Prerequisites
- Lesson 12 concepts: ALB, target health, Route 53 alias mental model.
- Storage Services: S3, EBS and EFS for buckets, encryption, and Block Public Access.
- Budget alert before creating distributions and generating traffic.
- Optional custom domain and ACM certificate issued for CloudFront use (typically requested in
us-east-1for CloudFront viewer certificates—verify current ACM/CloudFront certificate Region rules in docs). - Least privilege IAM for lab users; no long-lived access keys in lesson players.
Detailed Core Concepts
What CloudFront is for
CloudFront is a CDN: viewers connect to nearby edge locations, which may satisfy requests from cache or forward to an origin. A distribution is the configurable unit: origins, behaviors, TLS certificates, logging, and restrictions. TechLearningPro uses it so a learner in a distant city does not pull a 50 MB lesson package from your API Region on every navigation when the object is identical for everyone.
CloudFront is not a substitute for application architecture. It does not fix a single-AZ database. It does not replace authentication design. It accelerates and shields delivery when configured with honest cache rules and protected origins.
Distributions and price classes
When you create a distribution you choose settings that affect global footprint. Price classes limit which edge location groups serve traffic, trading coverage for cost. Exact class definitions live in current pricing/docs—pick consciously for labs (often a cheaper class is enough for sandbox demos). Do not assume “all edge locations” is free performance.
Alternate domain names (www, lessons, cdn) must match certificates. The default *.cloudfront.net domain works for labs without custom DNS.
Origins: S3 and ALB
S3 origins serve object storage directly. Modern practice prefers Origin Access Control (OAC) so the bucket policy allows CloudFront’s service principal for your distribution and Block Public Access stays on. Legacy Origin Access Identity (OAI) still appears in older stacks; prefer OAC for new work per current AWS guidance, verifying the latest recommended pattern in documentation.
Custom origins include ALBs, NLBs, or other HTTP endpoints. Protocol policy chooses HTTP-only, HTTPS-only, or match viewer when forwarding to origin. For ALB origins, keep instances private; CloudFront reaches the ALB’s public endpoint (or use patterns documented for private origins when you adopt them—do not invent PrivateLink-to-CloudFront features). Security groups on ALB may later restrict to CloudFront IP managed prefix lists where that pattern is supported—verify current guidance before locking; mis-lockouts cause global outages.
Behaviors and path patterns
A distribution has a default behavior and optional ordered path behaviors (/assets/*, /api/*, /media/*). Each behavior selects origin, viewer protocol policy (redirect HTTP to HTTPS), allowed methods, cache policy, origin request policy, response headers policy, and compression settings.
TechLearningPro pattern:
/assets/*or*.js,*.css,versioned hashed files→ S3 origin, long TTL, cache optimized./api/*or progress paths → ALB origin, caching disabled or cache policy that respects authorization (usually do not cache authenticated progress API responses).- HTML shell → short TTL or cache carefully if personalized.
Wrong default: caching GET /api/progress for one learner and serving it to another. That is a privacy incident, not a performance win.
Cache keys, policies, and headers
Historically, CloudFront forwarded and cached based on whitelists you configured. Modern distributions commonly use cache policies and origin request policies (managed or custom). Managed policies cover common static and dynamic cases—prefer managed policies when they fit; customize when you must include/exclude specific query strings or cookies in the cache key.
Cache-Control and Expires from the origin influence TTLs when behaviors honor origin headers. Versioned filenames (app.3f2a1c.js) beat emergency invalidations. Query string cache keys explode cardinality if every analytics parameter is included—exclude noise.
Invalidations
Invalidation requests remove or expire cached objects by path (/assets/player.js, /assets/*). They are tools for mistakes and emergency content correction, not a deploy strategy. Prefer immutable versioned objects. Invalidations have quotas and pricing dimensions—check current docs/pricing; do not invent free unlimited wildcards folklore. Wildcards can be necessary; use sparingly.
Signed URLs and signed cookies
Premium course videos should not be permanently world-readable at a guessable URL. Signed URLs grant time-bounded access to specific objects; signed cookies can authorize access to a path prefix for a session. Signing uses key pairs you manage per CloudFront trusted key group patterns (verify current trusted key group / key pair process in docs). Application servers generate signatures after authorizing the learner in TechLearningPro’s identity layer. Never embed master signing private keys in mobile apps or frontend JavaScript.
Signed access complements OAC: OAC stops anonymous bucket listing; signed URLs stop anonymous CDN fetches of premium objects when you require signatures on the behavior.
Viewer TLS and ACM
CloudFront serves HTTPS to viewers with certificates. For custom domains, request/validate an ACM certificate in the Region CloudFront requires for viewer certs (commonly us-east-1—confirm in current ACM docs). Attach the certificate to the distribution. Redirect HTTP to HTTPS on viewer protocol policy.
Geo restrictions and WAF preview
CloudFront can allowlist/blocklist countries. Useful for licensing constraints; blunt for security. WAF web ACLs associate with distributions for Layer 7 rules—implement in the security module. Do not claim WAF features you have not configured.
Logging and observability
Standard logging (and newer logging options as documented) send access logs to S3 or other supported destinations. Enable for incident response and cache-hit analysis. Lifecycle log prefixes. Real-time logging exists for advanced ops—optional for this lesson. Metrics for requests, 4xx/5xx, and bytes appear in CloudWatch—use them before guessing cache hit ratios.
Cost drivers without fake numbers
Typical dimensions: data transfer out to internet, HTTP/HTTPS requests, invalidations, optional features, price class footprint. Regional data transfer to origins also matters when miss rates are high. Always open the current CloudFront pricing page when estimating. Labs: small objects, limited requests, delete distributions when done—distributions themselves may not bill like ALB hours the same way, but traffic and origins can; unused custom certs and forgotten buckets still cost.
S3 website hosting vs CloudFront
S3 website endpoints are not a full CDN and have different HTTPS story. For TechLearningPro public lesson marketing pages and course assets, CloudFront + S3 origin + OAC is the production-shaped pattern. S3 website mode appears in older tutorials; prefer REST API origin with OAC for new designs per current AWS recommendations.
Architecture and Design Diagrams
Static assets and API through one hostname:
mermaidflowchart TBLearner["Learner viewer"]CF["CloudFront distribution"]S3["S3 origin\nOAC protected assets"]ALB["ALB origin\nprogress API"]ASG["Private ASG targets"]Learner --> CFCF -->|"/assets/* cacheable"| S3CF -->|"/api/* no cache"| ALB --> ASG
OAC trust boundary:
textPublic Internet ─▶ CloudFront ─OAC─▶ S3 bucket (Block Public Access ON)Anonymous S3 URL ─X─▶ denied by bucket policy
Signed premium media:
mermaidflowchart LRApp["TechLearningPro auth"]Sign["Signed URL minting"]CF["CloudFront behavior requires signature"]Obj["Premium object"]App --> Sign --> LearnerFetch["Learner GET"]LearnerFetch --> CF --> Obj
Technical Explanation
Request path on a cache hit
Viewer resolves Route 53 alias to CloudFront. TLS terminates at the edge with your certificate. Behavior matches path. Object found in edge or regional cache per CloudFront’s caching architecture; response returns without contacting S3. Headers follow policy. This is why versioned assets after deploy can leave old edges serving previous versions until TTL expires—hence versioned names or targeted invalidation.
Request path on a cache miss
Edge forwards to origin per origin request policy. S3 or ALB responds. CloudFront stores according to TTLs and cache policy if the response is cacheable. Authenticated API responses should be non-cacheable: Cache-Control: private, no-store from origin helps when policies honor origin.
Origin protocol and host headers
When forwarding to ALB, the Host header and HTTPS certificate on the ALB must make sense. Some designs use the ALB DNS as origin domain; others use a custom origin domain with matching cert. Misaligned Host headers cause 502s or wrong virtual host routing on shared ALBs. Document the origin domain name setting explicitly.
Compression and modern encodings
CloudFront can compress eligible content for viewers when configured. Ensure origin does not double-confuse encodings. For already-compressed video, do not expect magical recompression gains. Broader media strategy (adaptive bitrate) is product-owned; CDN caches the segments you publish.
Continuous deployment and staging distributions
CloudFront supports safe configuration rollout patterns (staging distributions / continuous deployment features as documented). Use them when changing cache policies on production learning traffic. Labs can edit a single distribution carefully; production should prefer staged config changes.
Multi-origin failover
Origin groups can fail over between primary and secondary origins when CloudFront sees certain failure statuses—verify current failover criteria. Useful for static assets replicated to a second Region’s bucket. Not a substitute for database multi-Region. Use for read-mostly object failover stories.
Field-level and edge compute awareness
CloudFront Functions and Lambda@Edge run lightweight logic at the edge (header rewrites, simple auth checks, A/B). They have constraints on runtime, libraries, and regional execution differences—read current limits before designing. This lesson’s core lab does not require edge compute; mention for interview depth. Do not invent Node APIs that do not exist in CloudFront Functions.
Privacy and cache poisoning mindset
If the cache key ignores a header that changes personalized content, one learner’s response can be served to another. If the cache key includes too much, hit ratio collapses. Prefer: static = broad cache key; dynamic personalized = no cache. Authorization headers generally should not create shared cache entries of private JSON.
Practical Implementation or Design Walkthrough
Problem
Publish versioned static assets to S3, front them with CloudFront using OAC, add a behavior that forwards /api/* to your lesson 12 ALB (or a documented mock) with caching disabled, alias a hostname if available, prove anonymous S3 access fails while CloudFront succeeds, run one invalidation experiment, then clean up.
Steps
- Confirm budget alert. Tag
Project=tlp-lesson13. - Create or reuse a private S3 bucket with Block Public Access on, default encryption on, versioning optional for lab.
- Upload
assets/app.<hash>.jsandassets/style.<hash>.cssplus a smallindex.htmlreferencing them (illustrative names). - Create CloudFront distribution with S3 origin + OAC; update bucket policy as console/CLI wizard documents for OAC—do not make the bucket public.
- Viewer protocol redirect HTTP→HTTPS; default root object
index.htmlif using this distribution for a static shell. - Add behavior
/api/*to ALB origin with cache policy that disables caching (managed “CachingDisabled” or equivalent current managed policy name—verify in console). - Attach custom domain + ACM cert if you have them; else use
cloudfront.netdomain for tests. - Success tests: fetch asset via CloudFront URL; fetch same object via direct S3 website/REST URL and expect deny.
- Failure tests: (a) remove OAC permission temporarily in a controlled way—or use a second bucket policy deny—to observe 403; restore. (b) Request
/api/progressand confirmCache-Control/ age headers show no shared caching of private data (use two different auth headers if API auth exists; otherwise document as design proof). - Change an unversioned file, create invalidation for that path, wait for completion, verify update—then rewrite the deliverable to prefer versioned names next time.
- Cleanup: disable/delete distribution (deletion may require disable wait—follow current console flow), delete OAC if unused, delete lab objects or bucket, leave ALB cleanup per your shared lab plan, remove lab DNS aliases.
Deliverable
Diagram; bucket policy intent; behavior table; proof of private bucket; invalidation note; cost dimensions listed without fake rates; cleanup evidence.
Enterprise Real-World Scenarios
TechLearningPro: open bucket “because CDN needs it”
A contractor enabled public read on the media bucket so CloudFront “could work,” then published guessable URLs for unpaid premium courses. Fix: OAC + Block Public Access + signed URLs for premium paths. Public marketing assets can still be distributed without public buckets.
Cached progress JSON
A behavior used the default static cache policy for all paths. Learners saw another user’s progress briefly. Incident response: invalidate, disable caching on /api/*, add regression test that checks Cache-Control on progress responses, review cache policies in peer review.
Invalidation as CI step for every deploy
Pipelines invalidated /* on each commit, burned invalidation quota/budget, and still served mixed versions due to races. Fix: content-hashed filenames; invalidate only index.html when needed; treat wildcard invalidation as break-glass.
Price class surprise
A global launch used all edge locations for a tiny admin app used by ten employees in one country. Cost rose without user benefit. Fix: appropriate price class; CloudFront reserved for learner-facing heavy assets.
ALB origin lockout
Team restricted ALB SG to an outdated CloudFront IP list copied from a blog. Global 502. Fix: use AWS-managed prefix lists where supported or keep ALB public with application auth while a reviewed restriction design lands; never copy stale IP lists.
Best Practices
- Default to S3 + OAC + Block Public Access for static course assets.
- Version static filenames; invalidate sparingly.
- Separate behaviors for static vs API; never cache personalized progress.
- Redirect viewers to HTTPS; attach correct Region ACM certs for custom domains.
- Prefer managed cache/origin request policies until you need custom keys.
- Alias Route 53 to CloudFront for stable learner hostnames.
- Lifecycle access logs; tag distributions and log buckets.
- Use signed URLs/cookies for premium media after authz in the app.
- Choose price class intentionally for labs vs production.
- Measure cache hit ratio before blaming origin compute.
- Document origin Host/TLS settings for ALB origins.
- Keep WAF/Shield as explicit follow-ups, not imaginary controls.
- Budget before load tests against CloudFront.
- Delete lab distributions when finished.
- Review response headers for security (HSTS, CSP) via response headers policies where appropriate—verify current managed policies.
Common Mistakes and Anti-Patterns
Public S3 bucket for CloudFront. Symptom: data leaks, ransomware listing. Fix: OAC + BPA.
Caching authenticated API responses. Symptom: cross-user data bleed. Fix: CachingDisabled behavior; origin no-store.
Using invalidation as primary deploy mechanism. Symptom: cost and inconsistency. Fix: versioned objects.
Wrong ACM Region for viewer certificate. Symptom: cannot attach cert. Fix: follow current CloudFront/ACM Region rules.
Forgetting alternate domain names on distribution. Symptom: cert name mismatch. Fix: add aliases matching cert SANs.
Stale CloudFront IP allowlists on ALB. Symptom: outage. Fix: managed prefix lists or redesign; no blog scrapes.
Putting signing private keys in frontend code. Symptom: anyone mints URLs. Fix: server-side signing only.
Single behavior for all paths. Symptom: impossible TTL trade-offs. Fix: path behaviors.
Ignoring Cache-Control from origin. Symptom: surprise TTLs. Fix: align policy with origin headers.
Leaving unused distributions and large log prefixes forever. Symptom: bill noise. Fix: cleanup checklist.
Troubleshooting and Design Review
403 from CloudFront to S3. OAC not allowed in bucket policy; wrong bucket ARN; KMS key policy missing CloudFront permission when using SSE-KMS—verify KMS grants. Read CloudFront error response body carefully.
200 from S3 public URL unexpectedly. Block Public Access off or public ACL—close immediately.
Viewer certificate error. Alias not listed; cert not issued; wrong distribution.
API suddenly slow globally. Cache miss storm after invalidation or disabled caching; origin overload—check hit ratio metrics.
Old JS after deploy. TTL not expired; filename not versioned; invalidation incomplete; browser cache—use hashed names and long TTL.
502 from ALB origin. Origin domain, SG, health, TLS policy between CloudFront and ALB.
Design review exit: BPA on; OAC evidenced; behavior table; no cached private API; HTTPS viewers; tags; cleanup plan; pricing dimensions named without invented rates.
Interview Questions and Answers
Q1. Why CloudFront in front of S3 for course assets?
Lower latency via edge caches, controlled egress, OAC keeps bucket private, HTTPS and custom domains, optional signing and WAF later.
Q2. OAC vs public bucket?
OAC lets only CloudFront read objects (per policy); public buckets allow anyone who knows URLs to fetch—unacceptable for many premium objects.
Q3. Should /api/progress be cached at the edge?
Generally no for personalized authenticated data. Cache only when responses are explicitly public and identical for all viewers.
Q4. Versioned objects vs invalidations?
Versioned names avoid stale cache by changing the URL; invalidations purge—use for emergencies and non-versioned HTML entrypoints.
Q5. Where must ACM certificates live for CloudFront viewers?
Follow current AWS docs (commonly us-east-1 for viewer certs). Wrong Region is a frequent failure.
Q6. Signed URL purpose?
Time-bounded authorized access to objects without making the bucket public.
Q7. Price class meaning?
Restricts which edge location groups serve traffic, trading geographic performance for cost—verify current class definitions.
Q8. How does Route 53 attach to CloudFront?
Alias A/AAAA to the distribution domain name for custom hostnames.
Q9. Cache key too wide vs too narrow?
Too wide: low hit ratio. Too narrow (missing vary dimension): wrong content served. Design deliberately.
Q10. Lambda@Edge vs CloudFront Functions?
Both edge compute with different triggers, languages, limits, and use cases—read current comparison docs; do not invent capabilities.
Q11. What metrics show CDN health?
Requests, 4xx/5xx, bytes downloaded, cache hit rate (as available), origin latency.
Q12. How do you restrict premium media?
Auth in app, signed URLs/cookies on CloudFront behavior, OAC on S3, least privilege signing keys.
Hands-On Exercises
Budget alert and cleanup (required)
Confirm budgets before distribution create. After lab: disable/delete distribution, delete lab objects, remove DNS aliases, purge or lifecycle logs, confirm tagged inventory. Note billing delay for transfer metrics.
Exercise: Static + dynamic behaviors
Implement the walkthrough. Evidence: private S3 proof, CloudFront 200 for assets, API behavior non-caching notes, one invalidation with lesson learned favoring versioning.
Challenge ADR
Decide whether the lesson HTML shell is served from CloudFront default object or from ALB. Include cache, deploy, and auth implications. Budget: no second Region replication this week unless paper-designed.
Worked narrative: TechLearningPro media cutover
The content team uploads hashed lesson bundles to s3://tlp-lesson-assets-prod/. Platform attaches CloudFront with OAC. Marketing site www and media cdn aliases point to the distribution. Progress remains api → ALB from lesson 12, optionally exposed as /api/* behavior with caching disabled if a single domain is required for cookie reasons—product chooses single-site vs subdomain architecture deliberately (cookies and CORS differ). Premium video path requires signed cookies issued after purchase check. Game day: revoke signing keys procedure documented; invalidation break-glass documented; BPA alarms via Config later.
Deep dive: cache headers for engineers
Cache-Control: public, max-age=31536000, immutable for hashed static assets. Cache-Control: no-store for progress JSON. Cache-Control: max-age=60 for near-static curriculum catalogs that can tolerate minute-old reads. CloudFront TTL max/min/default settings interact—read the behavior’s policy. When in doubt, prefer origin headers + managed policy that honors them.
Deep dive: CORS at the edge
If the lesson player on app. fetches assets on cdn., browsers require CORS headers. Serve them from S3 CORS config and/or CloudFront response headers policies. Misconfigured CORS looks like a CDN outage but is a browser security feature. Test with the real player origin, not only curl.
Deep dive: cost of miss storms
After a bad invalidation of /*, every learner refetches large videos from origin. S3 request and CloudFront origin fetch patterns spike; ALB may spike if HTML was included. Mitigations: staged rollouts, versioned URLs, rate-aware publish, avoiding wildcard invalidations during peak Monday classes.
Deep dive: dual delivery hostname strategy
cdn.techlearningpro.example → CloudFront → S3. api.techlearningpro.example → Route 53 → ALB. Simple mental model, separate failure domains, clear cache rules. Single hostname through CloudFront is also valid but demands careful behaviors and CORS simplicity trade-offs. Pick one in the ADR and stick to it for the course projects.
Extended troubleshooting
| Symptom | Likely cause | Check |
|---|---|---|
| 403 Access Denied | OAC/bucket/KMS | Policy simulator / bucket policy |
| Cert warning | Alias/cert SAN | Distribution aliases |
| Stale asset | TTL/versioning | Filename hash, Age header |
| CORS error | Missing headers | Browser console, response headers |
| High origin load | Low hit ratio | Policies, query strings in key |
Interview story
“We moved lesson assets to CloudFront with OAC and hashed filenames. Progress API stayed on ALB with caching disabled. Premium video used signed URLs minted after entitlement checks. We stopped using public buckets and stopped invalidating star on every deploy.”
Operator cadence
Weekly: 4xx/5xx on distributions; unexpected traffic; log bucket size. After publish: spot-check hashed URLs. Quarterly: review price class and unused distributions; rotate signing keys if used.
Student self-check
Can you explain OAC? Can you say why progress is not cached? Did you budget and clean up? Did you avoid fake prices? Did you link current docs for certificate Region rules?
Extended scenario: acquisition CDN sprawl
Acquired LMS has three CloudFront distributions, two public buckets, and one wildcard invalidation cron. Consolidation plan: one asset distribution, OAC, hashed assets, delete public access, kill cron, attach WAF later. Cost Explorer tags reveal which distribution serves paid content.
Extended scenario: teacher uploads
Teachers upload slides to a staging bucket; a pipeline promotes to the CloudFront origin bucket with new hashes. CloudFront never sees unauthenticated PUT from browsers directly to the origin bucket—uploads go through authenticated APIs and server-side PutObject with least privilege. This prevents open write surfaces disguised as “CMS convenience.”
Connection forward
Lambda may process upload events for virus scan or transcoding triggers. API Gateway may front signed URL minting endpoints. WAF may attach to the distribution. Keep delivery concerns modular.
Cleanup checklist
- Disable and delete lab distribution
- Delete OAC if unused
- Empty/delete lab bucket or clear lab prefix
- Delete lab DNS aliases
- Lifecycle or delete access logs
- Confirm BPA still on for retained buckets
- Budget remains enabled
Notes on documentation currency
OAC configuration JSON, managed policy names, and logging options evolve. Cite the date you verified docs in homework. Invented “CloudFront private ALB origin” claims without a documented pattern fail review in this course.
Final synthesis
CloudFront brings lesson assets close to learners while S3 stays private. Behaviors separate cacheable media from non-cacheable progress. Signing protects premium objects. Route 53 aliases give stable names. Budgets and cleanup keep sandboxes from becoming permanent CDNs for abandoned experiments. Next lessons introduce Lambda compute for event-driven platform work that often sits behind API Gateway—and still may mint the signed URLs this edge expects.
Extended technical explanation: regional edge caches and viewer proximity
CloudFront’s caching architecture uses edge locations and additional caching layers described in current AWS documentation as regional edge caches for many object types. The operational takeaway for TechLearningPro engineers is not to memorize every hierarchical cache name, but to understand that a miss at the nearest edge may still hit an intermediate cache before your origin. That is why invalidations and versioned object strategies must be deliberate: you are coordinating coherence across a global system, not across a single nginx process on one instance. When Monday traffic spikes in one geography, edges in that geography absorb repeated GETs for hashed assets while your ALB continues to spend capacity on uncacheable progress writes.
When you load-test, generate traffic from more than one network path if you can. A single office IP exercising CloudFront teaches less about global hit ratios than a staged canary in a second Region’s users. Still, never invent synthetic multi-Region user bases in homework—describe the limitation honestly if you only have one laptop.
Extended technical explanation: HEAD requests, range requests, and video
Video lesson delivery often uses HTTP range requests. CloudFront and S3 support range patterns commonly used by players—verify current behavior for your encoding pipeline. Caching partial responses has subtleties; many platforms cache full segment files for HLS/DASH rather than one giant MP4 with constant range misses. TechLearningPro should prefer segmented streaming media architecture owned by the media team, with CloudFront caching segments as ordinary objects with long TTLs and hashed paths. A single multi-gigabyte object with poor cache behavior is an expensive miss magnet.
HEAD requests appear in probes and some players. Ensure behaviors allow the methods you need without opening write methods on static behaviors. Static asset behaviors often allow GET and HEAD only; PUT/POST belong on authenticated API origins, not on the public asset behavior.
Extended enterprise scenario: exam-day traffic spike
During a certification-style mock exam event, concurrent learners open the same problem set assets within minutes. CloudFront hit ratio climbs; origin request rate stays flat; progress API ALB CPU climbs because answers are uncacheable POSTs. The correct scaling move is ASG policies on the API tier, not disabling CloudFront. Finance sees CloudFront transfer rise and asks to “turn off the CDN for a week.” Turning it off shifts transfer and latency back to the origin Region and may cost more while degrading experience. Bring hit ratio and origin request graphs to that conversation. Lesson 11 cost habits apply: attribute costs with tags on distributions and explain reliability/performance spend in writing.
Extended enterprise scenario: GDPR deletion and CDN copies
A learner exercises deletion rights on uploaded avatar images. Deleting the S3 object is necessary but not always sufficient while edges hold copies until TTL expires. Operational pattern: delete origin object; invalidate sensitive paths or use short TTLs for personal media; prefer non-personalized placeholders where possible. Document CDN purge in the privacy runbook. This is operational excellence at the edge, not only in the database.
Extended best practices deepener: response headers policies
Security headers—Strict-Transport-Security, X-Content-Type-Options, Content-Security-Policy (carefully), Referrer-Policy—can be applied via CloudFront response headers policies without changing every origin. Miswritten CSP can break the lesson player; stage changes. Managed security headers policies provide a starting point—verify names and contents in current docs before asserting exact header sets in an exam-like answer.
Extended interview set
Explain a cache poisoning privacy bug in one minute. Explain OAC with Block Public Access. Explain when to use signed cookies versus signed URLs for a curriculum path. Explain why us-east-1 appears in many CloudFront certificate answers and how you would verify today. Explain how you would prove a distribution is safe to delete in a shared account.
Hands-on narrative expansion: measuring Age and X-Cache
Curl the asset twice through CloudFront and inspect headers such as Age and X-Cache (header names and presence can vary—note what you actually observe and cite). The first request may show a miss; the second a hit. After invalidation, observe miss again. Write the observed headers into the lab evidence rather than copying blog screenshots. If headers differ from older tutorials, trust your distribution’s current behavior and the official documentation.
Hands-on narrative expansion: intentional 404 caching caveats
CloudFront may cache error responses according to custom error response settings and TTLs. A mistaken delete of a popular asset can cause edges to cache 404s and continue failing after you restore the object until error TTL expires or you invalidate. For TechLearningPro, configure error caching thoughtfully—short TTLs for 404 on mutable paths—or rely on versioned URLs so restores use new keys. Document the chosen error TTL in the runbook.
Module continuity paragraph
Module 1 taught private data stores and replaceable compute. Lesson 12 taught Regional health-aware entry. Lesson 13 teaches that most bytes learners download should never touch that compute path. Later serverless and container lessons must not accidentally reintroduce public buckets or cached private APIs when they add upload and webhook features. Edge delivery is a standing architectural constraint for the rest of the course.
Self-assessment rubric detail
| Area | Weight |
|---|---|
| OAC + BPA correctness | 25% |
| Behavior split static vs API | 20% |
| Evidence of tests | 20% |
| Versioning/invalidation judgment | 15% |
| Cleanup + budget | 20% |
Extended design walkthrough: single distribution versus two
Some TechLearningPro teams want one distribution that routes / and /assets/* to S3 and /api/* to ALB so cookies can be set on a shared parent domain without cross-site gymnastics. Others prefer cdn. for assets and api. for ALB to isolate blast radius: a bad cache policy cannot accidentally cover API paths if API never shares the distribution. Both are valid. The shared distribution demands ruthless behavior review and automated tests that fail the build if a cache policy on /api/* enables caching. The split-hostname design demands CORS and possibly duplicate TLS certificates. Write the choice as an ADR with the Monday board and the lesson player as named clients. Do not leave the choice implicit in console clicks.
When using a shared parent domain for cookies, remember that CloudFront and ALB both need correct HTTPS. Learners hate mixed content warnings. Redirect policies must be consistent. HSTS at the edge can lock browsers into HTTPS—good when you are ready, painful when a lab certificate is wrong. Stage HSTS with short max-age first.
Extended design walkthrough: environment separation
Do not point production CloudFront at a staging bucket “temporarily.” Create tlp-assets-staging and tlp-assets-prod (illustrative names) with separate distributions or separate behaviors/origins. IAM promotion roles can copy objects between buckets. Tag every distribution with Environment. Cost Explorer then shows when staging traffic is unexpectedly high—often a DNS mistake sending real learners to staging. Route 53 weighted or explicit hostname separation (staging-cdn. vs cdn.) beats hopeful memory.
Deep dive: origin request policies and headers to origins
Origin request policies control which viewer headers, cookies, and query strings CloudFront forwards to origins even when they are not part of the cache key. Forwarding all cookies to S3 is useless noise. Forwarding Authorization to ALB is required for bearer token APIs. Forwarding Host carefully matters for virtual hosting. Managed policies exist for “AllViewer” versus minimal forwarding—read the managed policy descriptions in the console and docs rather than inventing header lists. A common mistake is using a cache policy that excludes Authorization from the cache key while still accidentally enabling caching of responses that vary by user—remember: for private APIs, disable caching entirely.
Deep dive: compression, Brotli, and content types
CloudFront can compress text-like assets when viewer accepts encodings and content types are eligible. Already gzipped content and most video formats should not be forced through irrelevant compression settings. Ensure Content-Type is correct on S3 objects; wrong types break both browsers and compression eligibility. CI should set content types on upload. The lesson player’s .js served as application/octet-stream can cause cryptic failures blamed on CloudFront.
Deep dive: Web Application Firewall preview without implementing
Associating AWS WAF with CloudFront is a common production control for rate-based rules, managed rule groups, and geo matching beyond CloudFront’s simple geo restriction. This lesson does not configure WAF; it prepares you to leave a clean distribution identity that Module 4 can protect. If you “turn on WAF” casually in a sandbox without understanding managed rule false positives, you can block legitimate lesson traffic. Wait for the dedicated lesson unless your organization mandates it now—and if so, follow org runbooks, not improvisation.
Deep dive: Shield Standard versus Shield Advanced awareness
Shield Standard protections exist at the edge for many AWS services as part of the platform’s baseline DDoS posture—exact entitlements are defined by AWS. Shield Advanced is a paid engagement with additional features and operational support patterns. Do not claim Shield Advanced features in architecture reviews unless the account actually subscribes. For TechLearningPro labs, do not purchase Shield Advanced to “try it.” Note the distinction in interview answers.
Extended troubleshooting: KMS-encrypted objects and OAC
When S3 objects use SSE-KMS, the bucket policy OAC grant is not always enough: the KMS key policy must allow CloudFront to decrypt under the conditions AWS documents for OAC. Missing KMS grants present as 403s that look identical to bucket policy failures. Diagnostic order: CloudFront request ID, S3 server access logs if enabled, KMS key policy, bucket policy, OAC identity. Do not widen the bucket to public to “test,” which trains a dangerous reflex.
Extended troubleshooting: alternate domain stuck deploying
Distribution updates are asynchronous. Engineers sometimes thrash settings because the console still shows “In Progress.” Wait for deployment to finish before concluding TLS is broken. If a previous alias is associated with another distribution, CloudFront will reject the alias until freed. Document ownership of alternate domain names in the team wiki so two squads do not fight over cdn..
Extended scenario: partner content on your CDN
A content partner wants you to distribute their PDFs under your CloudFront domain. Legally and operationally you become the egress path. Require contracts, malware scanning on ingest, separate origin prefixes, and clearer cache TTLs. Prefer a dedicated behavior prefix /partner/* with stricter WAF later. Do not mix partner writes into the same upload IAM role as core curriculum without isolation.
Extended scenario: cost attribution for media
Finance asks how much CDN costs per paid learner. You cannot answer from raw CloudFront bills alone without tags and product analytics joining bytes to entitlements. Practical approach: tag distributions by product line; use access logs sampling to estimate heavy paths; allocate shared distribution cost by weighted bytes. Perfect precision is rare; honest allocation beats invented per-learner CDN unit prices in slide decks.
Hands-on expansion: negative testing matrix
- Direct S3 object URL → deny.
- CloudFront GET asset → 200.
- CloudFront GET missing asset → 404 with documented error TTL behavior.
/api/*with CachingDisabled → response headers show no shared cache hit of private data.- HTTPS required → HTTP redirects.
- Optional: expired signed URL → deny when signing is configured.
Capture request IDs. Redact account IDs in shared homework.
Hands-on expansion: cleanup timing
CloudFront deletes are not always instantaneous. Disable the distribution, wait until deployed, then delete. If you must keep the ALB for the same afternoon’s Lambda labs, leave a note with owner and expiry timestamp in the tag Expiry=YYYY-MM-DD. Untagged “temporary” distributions become permanent.
Architecture decision record template for this lesson
Title: CloudFront for TechLearningPro lesson assets
Context: Global learners, large static assets, private buckets required, progress API personalized.
Decision: Split hostnames: cdn → CloudFront → S3/OAC; api → ALB; hashed filenames; signed URLs for premium video; no caching of progress.
Consequences: CORS required for browser player; two certificates; clearer failure domains; invalidations rare.
Rejected alternatives: Public bucket; single cache policy for all paths; DNS-only “CDN” via multiple A records to instances.
Performance efficiency notes tied to Well-Architected
Edge caching is performance efficiency and often cost optimization for repeated bytes. It is not performance efficiency to cache wrong data. Measure TTFB and player start time before and after CloudFront for a cold and warm asset. Include the methodology in the lab write-up. If you cannot measure, do not claim victory.
Security notes tied to Well-Architected
OAC, BPA, HTTPS viewers, signed premium content, least privilege upload roles, no signing keys in clients—these are the security pillar evidences for this lesson. Add access logging when the org requires audit of object reads at the CDN layer. Remember CloudTrail and S3 data events as complementary controls later.
Reliability notes
Origin failover groups help static assets. They do not repair an ALB with zero healthy targets. Keep lesson 12 health discipline. For CloudFront, reliability also means avoiding self-inflicted lockouts via bad geo restrictions or bad WAF rules.
Sustainability notes
Serving assets from edges closer to users can reduce longer-haul transfer energy proxies; more importantly, high hit ratios reduce repeated origin fetches. Deleting unused large media versions and applying S3 lifecycle on noncurrent versions reduces storage waste—connect to lesson 9 habits.
Operator runbook snippet: “Learners see old player JS”
- Confirm deploy published new hashed filename and HTML references it.
- If HTML cached, invalidate HTML path or wait TTL.
- Confirm CloudFront behavior for HTML TTL.
- Ask learner to hard-refresh only after origin/HTML verified.
- If only some geos affected, expect edge variance until TTLs elapse.
Prefer prevention via hashed assets over panicking invalidations during live class.
Operator runbook snippet: “403 on all assets”
- Check recent bucket policy edits.
- Check OAC association on origin.
- Check KMS key policy if applicable.
- Check for SCP deny on
s3:GetObject. - Roll back the last IAM/bucket change via ticket.
Do not flip BPA off.
Student submission checklist
- Diagram with behaviors
- Bucket policy intent + BPA screenshot
- Behavior table
- Test evidence including deny on direct S3
- ADR on hostname strategy
- Cleanup confirmation
- Budget confirmation
- No invented prices/features
Continuity to Lambda
The next lesson’s image-processing workflow often starts when a teacher uploads to S3. CloudFront should serve only the cleaned, promoted assets—not the raw upload bucket. Keep raw and public-distribution buckets separate. Lambda reacts to ObjectCreated on the raw bucket; a promotion step copies to the CDN origin bucket. That separation prevents serving half-scanned objects at the edge.
Continuity to containers
When the lesson player later runs on ECS, it still should not serve large media from container local disk. Containers fetch configuration and signed URLs; CloudFront remains the byte path. Remembering this prevents overcrowded task storage and slow rolling deploys of multi-gigabyte images that mistakenly baked media into images—an anti-pattern lesson 16 will also attack.
Final extended synthesis for TechLearningPro
A learner in a distant city starts a course. DNS for cdn. aliases to CloudFront. The edge holds hashed JavaScript, CSS, and video segments. The player calls api. on the ALB for progress. Premium segments require signatures minted after entitlement checks. The origin bucket never grants public s3:GetObject to the world. Invalidations are rare. Cost Explorer shows CloudFront transfer correlated with launch weeks, not with idle ALB mistakes from forgotten labs. Security reviews find OAC and BPA in evidence packets. That is edge delivery done like a platform team, not like a tutorial that opened a bucket and called it done.
Lesson Summary
Amazon CloudFront extends TechLearningPro from a Regional ALB story to global edge delivery. Distributions, OAC-protected S3 origins, careful cache behaviors, versioned objects, and optional signed URLs form the professional pattern. Do not cache personalized progress. Do not open buckets for convenience. Verify certificate Region rules and pricing live. Clean up lab distributions.
AWS Lambda and Serverless Fundamentals begins event-driven compute for the platform—uploads, webhooks, and asynchronous work that pairs naturally with S3 and later API Gateway.
Further Reading
- Amazon CloudFront Developer Guide
- Restricting access to an Amazon S3 origin
- Cache and origin request policies
- Serving private content with signed URLs and cookies
- CloudFront pricing — verify live
- ACM certificates for CloudFront — verify Region requirements