A dashboard can display old information even when its server returns a perfectly reasonable status code. A language switch can reuse the wrong response. An optimization can reduce transferred bytes while leaving database work untouched. HTTP caching bugs become easier to diagnose when you separate the decisions behind those outcomes, then give every decision an observable test.
Use DeepSeek to challenge your caching contract, suggest missing cases, and review a small implementation. Keep the final judgment in executable checks and primary documentation. This guide builds an offline Python lab for representation-specific ETags and conditional GET and HEAD requests. You will examine what changes a validator, why a matching condition produces a bodyless response, and which production questions this deliberately small model cannot answer.
The examples, prompts, and expected results are authored for this tutorial. They are not transcripts of a model session. No DeepSeek request, paid API call, or model benchmark is needed to run the lab. Documentation was checked on October 5, 2026, and the accompanying tests were executed with Python 3.12.14. The topic is HTTP response caching, separate from caching model prompt prefixes.
Runnable download: download the HTTP conditional-request lab ZIP, including the implementation, 15-test tutorial suite, 21-test independent suite, run instructions, and captured offline results.
Separate storage, freshness, and validation
Start a debugging session by asking three questions in order. May this response be stored? May this stored response satisfy the present request without contacting another server? If another check is necessary, does the selected representation still match a validator the client supplied? Combining these questions into a single “cache enabled” switch hides the very distinctions you need when investigating a wrong result.
Freshness describes whether a stored response is young enough for reuse under the applicable policy. Validation checks a stored response against the current selected representation. A fresh response may avoid a network exchange; a validation attempt still involves a request. A stale response can remain useful as the candidate for validation rather than being immediately discarded. Mozilla’s caching guide provides the underlying terminology. [3]
Consider a public product description that tolerates a brief delay after editing. A team might choose an explicit freshness period for that response. Now consider an account settings screen where each visit should check for updates. The same validator mechanism can serve both designs, but the decision to contact the server differs. Ask the product owner about acceptable delay before asking a model to select a header.
The offline lab begins only after a request has reached the validation decision. It does not store responses, advance a cache clock, or calculate freshness from response age. This boundary makes its results readable: a returned status tells you what the validator comparison decided, not whether a browser would have sent the request in the first place. Keep that distinction beside every test result.

Choose a policy before adding validators
The unqualified response directive private prevents shared-cache storage while permitting private-cache storage subject to other rules. no-cache permits storage but requires successful validation before reuse. no-store prohibits cache storage of the exchange. These instructions solve different problems; the names are easy to misread. Our lab deliberately returns private, no-cache so that its validation exercise has a clear intended policy. [2, 4]
Imagine a response containing a user’s preferred dashboard layout. The lab policy is a useful starting point for discussing browser reuse because shared storage is excluded and each reuse requires checking. It is still a product decision whether the layout should remain in a private cache at all. If the requirement says the browser must not retain a cacheable copy, redesign the policy around that requirement instead of copying this example.
For a response with an explicit freshness lifetime, its age matters. A response that spent time in an intermediary does not receive a brand-new lifetime merely because a browser just downloaded it. Avoid a test plan that checks only elapsed time on the client. In an integration environment, capture the relevant timing and age headers and establish whether the response was already old when it arrived. [4]
Do not treat a caching directive as a complete security control or a deletion mechanism. A screenshot, application database, service worker, diagnostic log, or malicious recipient can create a separate copy. Define the privacy requirement at the system level, then identify which storage layers the HTTP policy controls. A test that verifies one response header establishes only that header’s presence at the observed boundary.
Write the lab contract before requesting code
The lab accepts one existing representation, an uppercase method, an optional conditional field value, and an optional aware clock value. The representation has already been chosen and the requester has already been authorized. The response object contains a status, a header dictionary, and body bytes. Treat that description as an explicit function boundary; it prevents a short tutorial from quietly becoming a partial web framework.
Only GET and HEAD are supported. For either method, If-None-Match uses weak entity-tag comparison: an otherwise identical opaque value matches even when the supplied candidate has the weak prefix. A match for an existing representation produces 304. A nonmatch allows the normal response. Other methods have different conditional semantics and are rejected by the lab rather than being assigned a misleading result. [1]
The normal GET response is 200 with the selected bytes. The normal HEAD response carries the corresponding metadata and no body. A 304 also has no body, while retaining the validation and cache-policy headers that this model would send on 200. This is a narrow implementation of the response requirements, including Date, ETag, Vary, and Cache-Control; it does not implement every possible response field. [7]
The optional condition is already a single field value, not raw HTTP input. Missing and empty are deliberately different: an absent condition requests the normal response, while an empty string is outside the accepted syntax. Invalid or unsupported input raises a Python exception. A real adapter must decide how that exception maps into the framework’s established request-handling policy; the lab does not claim that every such input requires a particular HTTP error.
These boundaries are worth writing before any generation prompt. They let a reviewer distinguish an implementation defect from an intentional omission. If your team already maintains request and response contracts, add caching cases to the same review process described in DeepSeek API contract testing. A separate optimization should not acquire an undocumented set of endpoint rules.
Give each representation its own validator
An entity tag is an opaque validator, not a database identifier or a universal checksum format. The server chooses how to generate it. A strong validator needs to distinguish relevant changes to representation data; a weak validator expresses a weaker equivalence. The client should preserve the supplied value rather than infer its structure. This tutorial chooses a content-derived strong tag for a small, fully materialized representation. [5]
Our example hashes a version marker, the selected language, the media type, and the exact body bytes. The metadata is serialized as a compact JSON array before a separator and the body are appended. Encoding the metadata this way avoids ambiguous concatenation between fields. The version marker gives the teaching example an explicit place to change the validator recipe without pretending that two different recipes describe the same contract.
Including language means that two fixtures can produce different validators even when their bodies happen to contain the same text. Including the media type makes the representation choice visible to the exercise. These are design choices for this lab, not a demand that all applications construct validators from the same fields. The important review question is whether any transformation can change the served representation without changing the validator it carries.
The English and French fixtures therefore test more than translation. They reveal whether the code validates the representation the requester actually selected. If an English validator is checked against an English object before the server notices that the request selects French, the comparison can be internally consistent and still produce the wrong response. Put selection before comparison in both the architecture diagram and the integration test.
Vary: Accept-Language tells caches that this request header participates in selecting a response. It complements the validator; it does not replace selection logic or turn the tag into a cache key. The model receives an already-selected language and emits that Vary value, but does not parse language preferences. A deployed endpoint needs matching negotiation and cache behavior, including whatever fallback rules the product supports. [6]

Ask DeepSeek to find missing decisions
Give DeepSeek the contract, the small fixture set, and the relevant standard sections before requesting a rewrite. Ask it to identify assumptions that the tests cannot currently distinguish. This produces a review task with checkable outputs: a proposed edge case should name a concrete input, an expected result, and the rule or local design decision behind that result. A general assurance that the implementation is robust is not enough.
Review this offline HTTP conditional-request contract before suggesting code.
It accepts an existing, authorized, already-selected representation.
Only GET and HEAD are supported. The content coding is identity.
The strong ETag depends on the exact body, language, media type, and recipe version.
If-None-Match uses weak comparison and can contain an ASCII tag list or '*'.
The parser intentionally excludes empty list members and non-ASCII opaque values.
Responses use private, no-cache and Vary: Accept-Language.
Identify missing tests or ambiguous assumptions. For each issue, provide:
1. The smallest concrete input that exposes it.
2. The expected status, headers, and body, or the required policy decision.
3. The relevant RFC section or a clearly labeled local design choice.
Do not expand this into an HTTP server or claim the tests prove full compliance.
The prompt is intentionally explicit about unsupported syntax. Without that boundary, a model may “fix” the parser by accepting a different subset while keeping the same explanation. Review proposed changes against the contract rather than against the confidence of the response. If a suggestion expands scope, decide whether that expansion belongs in this teaching component or in a production library with a broader interoperability test suite.
You can use a DeepSeek interface already available to you for this review. If you automate the interaction, consult the official API documentation for current request details rather than embedding a model name from an old example. The lab needs no SDK, credential, or remote response. Keeping the verification local lets you repeat the same tests regardless of which model or interface produced a suggestion. [11]
Send only synthetic request samples and the minimum code needed to explain the question. Remove authorization values, cookies, customer identifiers, and private URLs from traces. A cache key can disclose information even when the response body is absent. The workflow in DeepSeek API privacy and data minimization is a useful companion when preparing a sanitized debugging example.
Build the offline conditional-request model
Save the following file as conditional_lab.py. It imports only Python standard-library modules. It opens no socket, writes no cache, and contacts no model service. The response dictionary is a teaching representation of headers rather than a wire-format message. A real server adapter would still own header validation, duplicate field handling, protocol framing, connection behavior, and framework-specific response construction.
"""Offline GET/HEAD validation lab; not an HTTP server or a complete cache."""
from dataclasses import dataclass
from datetime import datetime, timezone
from email.utils import format_datetime
from hashlib import sha256
import json
import re
# Deliberate subset: ASCII entity tags, no empty list members, one field value.
# Backslash is literal here; it does not escape a quote in an entity tag.
TAG = re.compile(r'(?:W/)?"([\x21\x23-\x7e]*)"')
def parse_if_none_match(value):
"""Return '*' or opaque tag strings; reject unsupported/malformed input."""
value = value.strip(" \t")
if value == "*":
return "*"
if not value or len(value) > 4096:
raise ValueError("empty or oversized conditional field")
tags = []
pos = 0
while True:
match = TAG.match(value, pos)
if match is None:
raise ValueError("expected an ASCII entity tag")
tags.append(match.group(1))
if len(tags) > 32:
raise ValueError("too many tags for this lab")
pos = match.end()
while pos < len(value) and value[pos] in " \t":
pos += 1
if pos == len(value):
return tags
if value[pos] != ",":
raise ValueError("expected a list separator")
pos += 1
while pos < len(value) and value[pos] in " \t":
pos += 1
if pos == len(value):
raise ValueError("empty list member is outside the lab subset")
@dataclass(frozen=True)
class Representation:
body: bytes
language: str
content_type: str = "application/json"
@property
def etag(self):
# Identity content coding only. Version and metadata are deliberate.
metadata = json.dumps(["lab-v1", self.language, self.content_type],
ensure_ascii=True, separators=(",", ":"))
digest = sha256(metadata.encode("ascii") + b"\0" + self.body).hexdigest()
return '"' + digest + '"'
@dataclass(frozen=True)
class Response:
status: int
headers: dict
body: bytes
def matches_existing_representation(value, etag):
candidates = parse_if_none_match(value)
# Validate the whole field before comparing any candidate.
return candidates == "*" or etag[1:-1] in candidates
def respond(rep, method="GET", if_none_match=None, *, now=None):
"""Evaluate one already-authorized, already-selected, existing representation."""
if method not in {"GET", "HEAD"}:
raise ValueError("this lab supports only GET and HEAD")
now = now or datetime.now(timezone.utc)
if now.tzinfo is None or now.utcoffset() is None:
raise ValueError("now must be timezone-aware")
headers = {
"Date": format_datetime(now.astimezone(timezone.utc), usegmt=True),
"ETag": rep.etag,
"Cache-Control": "private, no-cache",
"Vary": "Accept-Language",
}
if (if_none_match is not None
and matches_existing_representation(if_none_match, rep.etag)):
return Response(304, headers, b"")
headers.update({
"Content-Type": rep.content_type,
"Content-Language": rep.language,
"Content-Length": str(len(rep.body)),
})
return Response(200, headers, rep.body if method == "GET" else b"")
The validator property uses SHA-256 through Python’s hashlib module and wraps the hexadecimal digest in the entity-tag quotation marks. SHA-256 is available through the standard interface used here. This is a practical content-derived validator recipe, not an authorization token, a digital signature, or a promise that mathematical collisions are impossible. The tests establish deterministic behavior for the chosen fixtures and transformations. [8]
The clock is injected so a test can compare complete header dictionaries without racing the wall clock. The implementation converts an aware datetime to UTC and formats the HTTP date using the standard-library utility. Rejecting a naive datetime makes the caller’s time assumption visible. The fixed test timestamp is illustrative; changing the test machine’s local time zone should not alter this fixture’s Date header. [10]
Notice that this function computes the validator after the body already exists. That placement makes the relationship between bytes and tag easy to inspect, but it does not demonstrate how to avoid generating an expensive response. Keep this choice when teaching correctness. Revisit it later when performance measurements show whether body construction, database access, compression, or transfer dominates the endpoint’s cost.
Review the supported field syntax honestly
The parser accepts an asterisk by itself or a nonempty list of quoted ASCII entity tags, with optional space or tab around list boundaries. Uppercase W followed immediately by a slash marks a weak candidate. The parser stores only the opaque values because this comparison is deliberately weak. The current validator must be the strong tag generated by this lab; the helper is not a comparator for arbitrary supplied current tags. It keeps character case inside each value and recognizes an empty quoted opaque value as a valid member of the supported subset.
A comma inside quotation marks belongs to the tag. Splitting the field with a simple comma operation would turn one opaque value into several fragments. The regular expression consumes an entire quoted tag before the loop looks for a list separator. The test containing an embedded comma is therefore a useful guard against a tempting simplification that might look clean in a generated refactor.
Backslash is treated literally in this parser, rather than borrowing string-escaping behavior from JSON. Do not replace the scanner with a general quoted-string parser without checking the entity-tag grammar. The exercise also validates the complete field before returning a match. A valid first candidate must not hide a malformed later member, because that would make the accepted input depend on the current resource version.
The restrictions are real. The lab excludes non-ASCII opaque values and empty list members, although HTTP permits non-ASCII obs-text in opaque tags and requires recipients to tolerate a reasonable number of empty list members. It is therefore not a general standards-conformant recipient parser. It limits the value after stripping outer spaces and tabs to 4,096 characters, and a list to 32 tags, as local teaching safeguards. Repeated field lines, transport-level decoding, and full interoperability are outside scope. Those limits are not presented as universal HTTP requirements.
Ask a reviewer to defend every parser shortcut against this stated boundary. “This matches the fixtures” is weaker than “this accepts exactly the documented subset.” When production requires a broader grammar, use the framework or a maintained parser where suitable and test its integration. Extending a tutorial regex until it resembles a general protocol implementation usually makes both the teaching goal and the failure modes less clear.
Run independent tests before trusting a suggestion
Save the next file beside the implementation as test_conditional_lab.py. These tests use Python’s unittest framework and ordinary assertions; no package installation is required. The fixed fixtures keep the expected behavior small enough to reason about independently. Several cases deliberately test relationships between responses rather than hard-coding a long digest, so a harmless change to the versioned recipe does not obscure the behavior being checked. [9]
from datetime import datetime, timezone
import unittest
from conditional_lab import (
Representation, matches_existing_representation,
parse_if_none_match, respond,
)
NOW = datetime(2026, 10, 5, 12, 0, 0, tzinfo=timezone.utc)
EN = Representation(b'{"message":"Ready"}', "en")
FR = Representation(b'{"message":"Pret"}', "fr")
class ConditionalTests(unittest.TestCase):
def test_get_returns_complete_representation(self):
result = respond(EN, now=NOW)
self.assertEqual(result.status, 200)
self.assertEqual(result.body, EN.body)
self.assertEqual(result.headers["Content-Length"], str(len(EN.body)))
self.assertEqual(result.headers["Content-Type"], "application/json")
self.assertEqual(result.headers["Content-Language"], "en")
self.assertEqual(result.headers["Date"], "Mon, 05 Oct 2026 12:00:00 GMT")
def test_same_inputs_have_same_validator(self):
self.assertEqual(EN.etag, Representation(EN.body, "en").etag)
def test_body_language_and_media_type_change_validator(self):
alternatives = [
Representation(EN.body + b"\n", "en"),
Representation(EN.body, "fr"),
Representation(EN.body, "en", "text/plain"),
]
for rep in alternatives:
with self.subTest(rep=rep):
self.assertNotEqual(EN.etag, rep.etag)
def test_304_retains_validation_headers_and_has_no_body(self):
full = respond(EN, now=NOW)
result = respond(EN, if_none_match=EN.etag, now=NOW)
self.assertEqual(result.status, 304)
self.assertEqual(result.body, b"")
for field in ("Date", "ETag", "Cache-Control", "Vary"):
self.assertEqual(result.headers[field], full.headers[field])
self.assertNotIn("Content-Length", result.headers)
self.assertNotIn("Content-Type", result.headers)
def test_weak_candidate_matches_strong_current_tag(self):
result = respond(EN, if_none_match="W/" + EN.etag, now=NOW)
self.assertEqual(result.status, 304)
def test_unmatched_candidate_returns_full_200(self):
result = respond(EN, if_none_match='"old"', now=NOW)
self.assertEqual((result.status, result.body), (200, EN.body))
def test_another_language_does_not_validate(self):
result = respond(FR, if_none_match=EN.etag, now=NOW)
self.assertEqual((result.status, result.body), (200, FR.body))
def test_head_uses_get_status_and_representation_length(self):
head = respond(EN, "HEAD", now=NOW)
get = respond(EN, "GET", now=NOW)
self.assertEqual(head.status, 200)
self.assertEqual(head.body, b"")
self.assertEqual(head.headers, get.headers)
self.assertEqual(respond(EN, "HEAD", EN.etag, now=NOW).status, 304)
def test_list_and_comma_inside_opaque_tag(self):
self.assertEqual(parse_if_none_match(' "old,tag", W/"a,b" '),
["old,tag", "a,b"])
self.assertTrue(matches_existing_representation('"x", W/"a,b"',
'"a,b"'))
field = '"unrelated,tag", W/' + EN.etag
self.assertEqual(respond(EN, if_none_match=field, now=NOW).status, 304)
def test_wildcard_for_existing_representation(self):
for method in ("GET", "HEAD"):
self.assertEqual(respond(EN, method, "*", now=NOW).status, 304)
def test_case_sensitive_opaque_values(self):
self.assertFalse(matches_existing_representation('"ABC"', '"abc"'))
def test_empty_opaque_tag_and_literal_backslash(self):
self.assertEqual(parse_if_none_match('""'), [""])
self.assertEqual(parse_if_none_match('"a\\b"'), ["a\\b"])
def test_unsupported_or_malformed_fields_are_rejected(self):
fields = ["", '"a",', ',"a"', '"a",,"b"', '* , "a"',
'w/"a"', 'W/ "a"', '"a" junk', '"has space"',
'"caf\u00e9"', '"a\nb"', '"unterminated',
','.join(['"a"'] * 33), '"' + "x" * 4096 + '"']
for value in fields:
with self.subTest(value=value):
with self.assertRaises(ValueError):
parse_if_none_match(value)
def test_match_does_not_hide_later_malformed_member(self):
with self.assertRaises(ValueError):
respond(EN, if_none_match=EN.etag + ', broken', now=NOW)
def test_method_and_clock_boundaries(self):
with self.assertRaises(ValueError):
respond(EN, "POST", now=NOW)
with self.assertRaises(ValueError):
respond(EN, now=datetime(2026, 10, 5))
if __name__ == "__main__":
unittest.main()
Run the named suite from the directory containing both files. The recorded run for this article passed 15 test methods on Python 3.12.14. That count describes this local run only. It is not a measure of standards coverage, model quality, browser compatibility, or production readiness. Retain the interpreter version and test output with any proposed change so another reviewer can reproduce the same evidence.
python -m unittest -v test_conditional_lab
The body-and-metadata tests establish the lab’s validator recipe. The matching and nonmatching cases establish the two response paths. The HEAD checks prevent an easy mistake where body suppression also accidentally changes the advertised representation length. The field tests exercise the parser’s accepted subset and rejection boundaries. Together they make specific promises visible, while leaving out system behavior that the function does not own.
Expand from these examples by changing one dimension at a time. Try longer bodies, additional selected languages, and lists with the matching candidate in different positions. Keep the same expected relationships. If you use generated test data, retain a minimal failing example and the generation settings. The approach in DeepSeek property-based testing can help turn these relationships into a larger search without giving the model authority over the expected answer.
Turn failures into explanations rather than patches
Suppose a reviewer changes the weak comparison into ordinary string equality. The test with a weak candidate then fails even though the resource bytes did not change. Explain the failure in terms of the comparison required by this conditional field, then make the smallest correction. Do not fix the test by removing the weak prefix merely to recover a green run; that would erase the behavior the test exists to protect.
Suppose another edit removes language from the hash input. The same-body, different-language case catches that local contract change. This failure is different from the previous one: it concerns the lab’s chosen representation identity recipe. A team could intentionally redesign that recipe, but it should update the contract and supporting tests together. Labeling every failing assertion a protocol violation would make the review less accurate.
A third useful exercise is to make the HEAD branch advertise a length of zero. The body assertion alone would still pass, because HEAD sends no body. The header comparison reveals the problem. This is why a response test should inspect status, selected metadata, and body behavior together. A status-only test can miss almost the entire caching contract while still producing reassuring output.
Diagnose this failing caching test without rewriting unrelated code.
Separate an HTTP requirement from a local contract choice.
Explain the smallest cause supported by the input and assertion.
Propose one minimal correction and one regression test.
List what the test still cannot establish about browsers, proxies, or authorization.
Do not change the expected result unless you justify a contract correction first.
Keep the failure evidence alongside the proposed change: the input, previous output, new output, and relevant assertion. If DeepSeek offers several explanations, test the cheapest discriminating case before making a broad edit. For example, an incorrect tag on one language variant suggests a selection or serialization problem; an incorrect tag on every repeated request suggests unstable bytes or a nondeterministic recipe. These hypotheses lead to different experiments.
Keep authorization and privacy ahead of reuse
The function’s “already authorized” assumption is essential. An application must not return a validating response solely because a requester knows an old tag. Put authentication and resource-access decisions ahead of the function boundary. Add an integration case where a user loses access between two requests; the second request should follow the endpoint’s access policy even if it carries a previously valid validator.
Shared caching of responses to requests carrying Authorization has specific restrictions and explicit exceptions in RFC 9111. Treat any decision to enable it as an endpoint-level review, rather than adding public or a shared-cache directive to improve a hit-rate graph. The standard’s storage permission does not establish that your application has removed all user-specific information from the response. [2]
Use two synthetic accounts with unmistakably different response markers when testing a personalized route. Alternate requests through the same proxy path, including a request carrying the other account’s validator. Check response bodies, cache-policy headers, and any visible cache diagnostics. The goal is to show that account boundaries survive the complete delivery path. A unit test against an already-selected representation cannot establish that property.
Avoid placing raw account identifiers or secrets in a tag. Even an opaque-looking digest can become a correlation signal when its input space is small or predictable. Choose a validator recipe with the endpoint’s disclosure risk in mind, and keep private traces out of model prompts. Caching work is often framed as performance engineering, but a wrong reuse decision can become a data-exposure problem.
Check compression, proxies, and deployments
The lab supports identity content coding only. If a deployment serves compressed bytes, revisit where the validator is generated relative to that transformation. Strong validators for different encoded representations need appropriate distinction. An intermediary that rewrites a body also changes the question the validator answers. Trace the actual path from serializer through middleware to proxy instead of assuming the application’s response object is exactly what the client receives. [1]
Build one integration fixture that is large enough for your real compression configuration to act on it. Request each supported encoding and record the final headers and bytes at the client boundary. If your framework deliberately emits weak validators after transformation, document that choice and test the relevant conditional behavior. Do not copy the offline lab’s strong-tag claim into a route whose representation pipeline differs.
Deployments introduce another source of variation. A serializer change, localization update, or template release can alter bytes without changing the database record version. If production uses a record revision as its validator input, ask whether every output dependency contributes to that revision. A useful review artifact is a short dependency list beside the generation rule, with a test for each dependency that can change the representation.
Rolling deployments deserve a repeated-request test across multiple instances. Alternate identical requests and compare validators and bytes. Unexpected oscillation can reveal mismatched versions or nondeterministic rendering, while an unchanging tag beside changing bytes suggests a correctness defect. Keep a distinction between “safe but inefficient” validator churn and “unsafe reuse” caused by failing to change a validator when required.
Design stale serving and invalidation separately
A validator lets a recipient ask about a representation; it does not push an update to every stored copy. Plan invalidation separately. For a mutable resource, define how soon clients need to observe a change and what happens to intermediaries that already hold a response. For versioned assets, changing the resource URL can be part of the deployment strategy. Neither approach should be assumed from the mere presence of an ETag.
The stale-while-revalidate and stale-if-error extensions describe bounded circumstances for reusing stale responses during revalidation or errors. Their suitability depends on the endpoint’s semantics and cache support. An old public illustration may be acceptable during an outage; an old access-control decision may be unacceptable. The lab implements neither extension, so its 304 tests say nothing about these policies. [12]
Write the outage scenario before selecting a stale window. Identify what the reader would see, how old it could be, and which failures permit that behavior. Then exercise the actual cache with a controlled origin failure and a response whose age is known. Avoid substituting a fresh-response happy path for this experiment. The important evidence is the observed behavior after the freshness boundary has been crossed.
For a CDN, test both the application’s headers and the effective provider configuration. A rule that overrides origin policy, changes the cache key, or bypasses a route can dominate the result. Record the configuration revision with the integration trace. A successful purge request is also only one event in an invalidation workflow; verify that the intended variants actually stop being served from the locations your test can observe.
Measure what validation actually saves
Returning 304 can avoid transferring a representation body, but the origin may still perform authorization, database queries, serialization, and hashing. In this lab it does all body preparation before comparison. Report that honestly. A smaller response is useful evidence about transferred content, while an origin CPU reduction needs its own measurement. The distinction helps keep optimization claims aligned with what an experiment actually observed.
Measure a few named paths separately: a full response, an unchanged conditional request, a changed conditional request, and a request satisfied by a cache without origin work. Keep the fixture, concurrency, connection conditions, and cache state explicit. Comparing a warm path to a cold path without saying so can make the apparent improvement mostly an artifact of the test setup.
If body generation dominates cost, consider a revision-based validator that can be obtained cheaply, but inventory every dependency before adopting it. The saved work is valuable only if the revision accurately tracks the selected representation. Use the content-derived lab as a reference fixture during that redesign: for controlled updates, compare when the cheap validator changes with when the resulting representation changes.
Prepare a reviewable production change
A useful change description names the endpoint, supported methods, selection dimensions, validator recipe, and cache policy. It also names the layer that performs authorization and the layer that emits the final headers. These details give reviewers a map for locating missing tests. A screenshot of a successful request is helpful context, but it should accompany the reproducible assertions rather than substitute for them.
Keep unit evidence and integration evidence separate in the review. The former establishes the small function’s behavior. The latter checks framework conversion, negotiation, compression, proxies, and the client-visible result. Record unresolved gaps as concrete questions, such as whether repeated field lines are merged by the server or whether a CDN rule honors the selected language. That is more actionable than a generic warning to test thoroughly.
Choose a rollback condition before release. Examples include unexpected cross-variant reuse, a validator that oscillates across identical requests, or increased origin load after a policy change. Use privacy-safe diagnostics that reveal the selected variant and decision path without recording credentials. If the rollout fails, these observations help distinguish a policy problem from a parser defect or a deployment mismatch.
Resolve common design questions
Does 304 mean the whole request succeeded?
It is a response for a conditional retrieval that allows an appropriate stored representation to be reused; it supplies no replacement body. A client needs the corresponding stored data and must apply the response in the correct context. Do not interpret 304 as successful completion of an arbitrary application operation or hand an empty body to a JSON decoder as though it were a fresh representation. [7]
Can this helper be used for conditional updates?
Keep it limited to its stated retrieval contract. Update concurrency introduces other methods, preconditions, state transitions, and failure handling. Reusing a helper that rejects every non-retrieval method would conceal those requirements behind an exception. Start a separate design with explicit update examples and establish the expected response for each condition before sharing implementation details between the two workflows.
Should the lab add Last-Modified as well?
Only if the teaching or application requirement calls for another validator. Adding a date-based path also adds precedence, timestamp precision, and clock assumptions to review. The current lab intentionally handles only If-None-Match, so it makes no claim about combined preconditions. A focused, correctly bounded example is more useful than an enlarged helper whose additional branches are barely tested.
What should DeepSeek contribute to the final decision?
Use it to generate candidate explanations, expose missing assumptions, and suggest concrete experiments. Require each recommendation to point to a local contract, a relevant source, or a reproducible observation. Keep the executed tests and deployment evidence as the basis for acceptance. The useful outcome is a caching change whose behavior another developer can explain and verify, even without seeing the conversation that helped produce it.
Sources & References
Primary standards, Python documentation, DeepSeek’s own API documentation, and Mozilla’s HTTP documentation were checked on October 5, 2026. The lab and scenarios are original teaching material. Reference numbers identify the supporting documents without placing external links throughout the article.
- RFC 9110: HTTP Semantics. Sections 8.8.3, 9.3.2, 13.1.2, and 15.4.5 cover entity tags, HEAD, If-None-Match, and 304.
- RFC 9111: HTTP Caching. Sections 3.5, 4.1, 4.2, 4.3, and 5.2 cover authenticated requests, selection, freshness, validation, and directives.
- MDN: HTTP caching. Browser and intermediary caching concepts.
- MDN: Cache-Control. Directive meanings and response age.
- MDN: ETag. Opaque validators and validation examples.
- MDN: Vary. Request-header-dependent response selection.
- MDN: 304 Not Modified. Conditional retrieval and bodyless validation responses.
- Python: hashlib. SHA-256 constructors and hexadecimal digests.
- Python: unittest. Standard-library tests and command-line execution.
- Python: email.utils. Formatting aware date values with GMT.
- DeepSeek: official API documentation. Current API request setup for optional model-assisted review.
- RFC 5861: HTTP Cache-Control Extensions for Stale Content. Stale-while-revalidate and stale-if-error.
