cswork / libraryOpen practice workspace

Articles

CloudFront Cache Interview Questions: Cache Keys, Origins, and Stale Responses

Prepare for CloudFront cache interviews with cache-key examples, TTL traps, origin policies, stale-response diagnosis, and a safe invalidation exercise.

A CloudFront cache interview is usually a reasoning exercise about response identity. Start by naming which viewer requests may safely receive the same bytes, then separate cache-key policy, origin forwarding, freshness, and invalidation. A high hit ratio is useful only after those boundaries are correct. Caching another customer's account page quickly is still a serious failure.

This article is for backend and infrastructure candidates diagnosing incorrect or stale responses. AWS documentation supplies the platform facts; the incident and replay tests below are original practice exercises, not reported employer questions.

What does a CloudFront cache key actually identify?

A cache key identifies a reusable response within a cache. Requests sharing that identity can receive the stored representation without contacting the origin. The engineering decision is therefore which request differences affect response bytes or permission to reuse them.

AWS lets a cache policy select headers, cookies, and query parameters for the key. Reducing key dimensions can improve reuse, but only if the omitted values do not distinguish responses. The policy is attached to a cache behavior. AWS cache-key documentation

Consider an original exercise: /products/42?currency=USD&utm_source=newsletter. The application renders different prices for currency but uses utm_source only for analytics. Our proposed key includes currency and omits the campaign parameter. That is an inference about this application's contract, not a universal AWS recommendation. If a campaign changes a promotional price, the proposal is wrong.

Ask about defaults and normalization as well. Does a missing currency mean USD? Is usd accepted? Are repeated parameters legal? Normalizing two requests into one key is safe only when the origin interprets them identically. Otherwise the edge and application disagree about identity even though the configuration looks tidy.

Why is forwarding a cookie different from keying on it?

An origin request policy controls information sent to the origin; a cache policy controls reuse. AWS automatically forwards values included in the cache key. An origin request policy can forward additional values without adding them to that key. Those additional values might be suitable for telemetry, but forwarding a value does not isolate responses by it. AWS origin-request policies

Here is the central incident. An account endpoint uses a session cookie. The origin receives that cookie and returns the correct account on a miss. The edge key omits it. User A warms the cache, then User B receives the cached A response. Testing only an empty cache would miss the problem.

The first repair question is whether the endpoint should be shared-cacheable at all. For this exercise, choose a behavior with caching disabled for personalized account responses and verify the origin's cache headers. Merely adding a session cookie to the key creates many entries, retains private bytes at the edge, and requires careful treatment of authentication expiry. It is not automatically the best design.

Also separate viewer authorization from origin access. Protecting an S3 bucket or requiring a private origin connection does not establish that two authenticated viewers may share an object. Origin protection answers who may fetch from the backend; response reuse answers who may receive cached bytes.

Work the four-request incident before changing production

Use synthetic accounts and a non-sensitive marker such as account_fixture=A. Do not log real sessions or customer bodies. Assume the broken configuration caches /account for sixty seconds and forwards cookies without including them in the key.

RequestControlled inputExpected safe resultBroken behavior to look for
A1A cookie, cold objectA markerEstablishes the initial fill
B1B cookie, same pathB markerA marker reveals cross-user reuse
A2A cookie, repeated requestA markerChecks repeat behavior
N1No cookie, same pathUnauthorized responseA marker reveals anonymous exposure

Run the sequence in both A-first and B-first order. If the wrong answer follows whichever account filled the object, key collision becomes a strong hypothesis. If every request is wrong even when sent directly to an authorized staging origin, investigate application authentication instead.

Capture response status, a safe body digest, Cache-Control, Age when present, X-Cache, and the request identifier. A cache-hit header supports the diagnosis; it is not sufficient by itself. Compare the identity markers. A successful HTTP status with somebody else's bytes is the failed assertion.

After the change, repeat the sequence with a fresh browser context and with an already-used context. Confirm that the deployed cache behavior matches /account, rather than inspecting an unrelated default behavior. In an interview, explaining that configuration-selection step often matters more than remembering a console label.

How should you explain minimum, default, and maximum TTL?

Time to live, or TTL, is the period during which a cached object can be treated as fresh under the applicable policy. It is not a promise that the object remains resident, nor proof that every browser has the same copy.

AWS documents interactions among policy TTLs and origin freshness headers. A particularly important exception is that a positive minimum TTL can cause CloudFront to cache despite origin no-cache, no-store, or private directives. CloudFront can also evict objects before expiry. AWS expiration rules

For an interview calculation, state assumptions explicitly: minimum zero, maximum 600 seconds, default 120 seconds, and no other relevant directive. An origin freshness lifetime of 30 seconds gives a 30-second target. A lifetime of 900 seconds is capped at 600. If freshness information is absent, the default supplies the starting policy value. Treat these as a simplified exercise, then check the full AWS rules for the actual headers.

A second calculation separates browser and shared-cache intent: max-age=0, s-maxage=120 describes different lifetimes for the browser and shared cache. Do not conclude that a browser refresh necessarily fetches from the application. It may contact CloudFront and receive a still-fresh edge response.

The diagnostic question is therefore: which layer is stale relative to which business requirement? A two-minute-old public catalog might meet its contract; a revoked entitlement might not. Choose freshness around consequences before optimizing origin traffic.

When is a stale response intentional?

AWS supports stale-while-revalidate and stale-if-error, subject to CloudFront's documented limits. The former permits serving an expired response during background refresh; the latter can preserve availability when refreshing encounters an eligible error. These directives describe bounded trade-offs, not an unrestricted license to return old data. AWS stale-content behavior

In our original catalog scenario, suppose the business tolerates brief price-display lag but checkout must revalidate the actual purchase price. A bounded stale display might be acceptable if the interface handles price changes honestly. For account access or revocation, that same tolerance may be unacceptable. State the separation between display data and the authoritative action.

To investigate a stale-response report, record the deployment time, origin object version, response validator, policy version, and observation time. Compare a safe origin request with the edge response. If the origin itself still serves the old version, an edge invalidation will only fetch the old bytes again.

Do not equate every 304 Not Modified with a fault. Revalidation can correctly confirm an existing representation. The useful question is whether the origin's validator changes when the representation changes. An application that reuses an incorrect validator can make a healthy cache preserve a bad answer.

Does invalidation fix a bad cache policy?

Invalidation removes cached objects; it does not correct how the next response will be keyed. In the account exercise, purging before fixing the behavior merely lets the next visitor seed another unsafe response.

AWS documents case-sensitive invalidation paths, a wildcard restricted to the end, and additional considerations for query-string variants and rewritten URIs. Header and cookie variants cannot be selectively purged by individual header or cookie value through a path invalidation. AWS invalidation-path rules

A defensible repair sequence for the exercise is: stop unsafe sharing, verify configuration deployment, remove affected stored variants, then replay the identity matrix. Treat browser-held responses separately because an edge purge cannot recall copies already delivered to clients. If actual private content was exposed, the operational response also needs the organization's incident process.

For routine static-asset releases, versioned filenames provide a cleaner identity change. If HTML references app.abc123.js, deploy the new asset before switching HTML to app.def456.js. Retain the old asset while older documents can still reference it. This is our deployment recommendation, consistent with AWS guidance on updating existing files.

Do not propose /* as your first troubleshooting move. Explain the necessary scope, the cold-cache refill traffic it may create, and how you will know the replacement representation is correct. A purge that increases origin failures can make the incident worse.

What evidence distinguishes the remaining failure modes?

Suppose only one region reports old images. Compare the exact URL, query parameters, content encoding, response headers, and object version before blaming regional propagation. Two screenshots are not evidence that the underlying request identities match.

If misses return stale content while hits behave as expected, inspect origin selection, application caches, and deployment consistency. If a new query parameter appears to fix the page, establish whether the parameter is actually in the key; otherwise the apparent fix may be timing. If the error appears only after login, inspect both the authenticated request and any previously cached anonymous response.

An interview answer should also mention negative caching. A missing asset requested before deployment may leave a cached error after the file becomes available. Inspect error-cache behavior and origin status rather than repeatedly uploading the same object. Keep the diagnosis distinct from a stale successful response.

Build a small evidence bundle: exact sanitized requests, expected identity, observed digest, relevant policy fields, origin version, and before/after outcomes. This lets another engineer reproduce the finding. Avoid declaring success from one browser reload or a distribution deployment notification.

Sources and Further Reading