Web Development

Conditional Requests: HTTP Cache and Integrity Guide

Implement conditional requests to optimize bandwidth and ensure data integrity. Learn how HTTP headers like ETags and If-Match prevent lost updates.

30
conditional requests
Monthly Search Volume

Conditional requests are HTTP requests that execute differently based on the value of specific headers. These headers establish a "precondition" that the server must test against the current state of a resource before fulfilling the request. Using these allows you to save bandwidth by only downloading changed files and avoid data loss when multiple people edit the same document.

What are Conditional Requests?

A conditional request functions like a standard HTTP request but includes "validators" in the header. The server compares these validators to the version of the resource it currently holds. If the condition is met, the server performs the requested action, such as sending a file or saving an update. If the condition fails, the server returns a specific status code, such as 304 Not Modified or 412 Precondition Failed.

[The Hypertext Transfer Protocol (HTTP) uses these mechanisms to manage distributed, collaborative information systems] (RFC7232).

Why Conditional Requests matter

  • Bandwidth efficiency: You can avoid downloading a large file if your browser already has the current version cached.
  • Faster load times: Servers respond significantly faster with a small status header than with a full page or image.
  • Data integrity: They prevent "lost updates" where one user accidentally overwrites another person's changes.
  • Resume-friendly downloads: They allow browsers to pick up a failed download exactly where it left off without corrupting the file.
  • Crawl budget optimization: Search engine bots use them to identify which pages have changed, allowing them to crawl your site more efficiently.

How Conditional Requests work

The process relies on "validators," which are pieces of metadata that describe the version of a resource. There are two primary types:

  1. Last-Modified: The specific date and time the server last changed the file.
  2. ETag (Entity Tag): A unique, opaque string (often a hash) that identifies a specific version of a document.

Validation Types

Servers use two methods to compare these validators:

  • Strong validation: This requires a byte-for-byte match. It is mandatory for resuming downloads and ensuring strict data integrity.
  • Weak validation: This considers two versions "identical" if the core content is the same, even if minor details like a date in the footer or an advertisement are different. [Weak ETags are identified by a "W/" prefix] (HTTP.dev).

Key Conditional Headers

  • If-Match: Succeeds if the ETag on the server is exactly the same as the one provided. This is used for "unsafe" methods like PUT.
  • If-None-Match: Succeeds if the ETag on the server is different from the one provided. This is the primary tool for cache validation.
  • If-Modified-Since: Only fetches the resource if it has changed since a specific date.
  • If-Unmodified-Since: Only processes the request if the resource has not changed since a specific date.
  • If-Range: Used with partial downloads to fetch only the missing pieces of a file, provided the file hasn't changed.

Common Use Cases

Cache Updates

When your browser cache becomes "stale," it issues a conditional request using If-None-Match. [If the file is unchanged, the server returns a 304 Not Modified response, and any required metadata like Cache-Control or ETag must be included in that response] (RFC7232).

Optimistic Locking

This prevents a race condition when two clients try to update a file at the same time. The first client to submit their change succeeds. The second client’s request, based on an old version of the file, results in a 412 Precondition Failed error. This forces the second client to reconcile their changes with the new version.

Safe First Uploads

You can prevent overwriting an existing file by using If-None-Match: *. The upload only succeeds if no file currently exists with that name on the server.

[Amazon S3 supports these preconditions for operations like PUT, CompleteMultipartUpload, or CopyObject to prevent unintentional overwrites] (Amazon S3).

Precedence of Evaluation

When a request contains multiple conditional headers, the server must evaluate them in a specific order to ensure logical consistency. [The standard evaluation order requires checking If-Match before If-None-Match or If-Modified-Since] (RFC7232).

  1. If-Match: Checked first by the origin server.
  2. If-Unmodified-Since: Checked if If-Match is not present.
  3. If-None-Match: Evaluated next; returns 304 for GET/HEAD if it fails.
  4. If-Modified-Since: Evaluated for GET/HEAD if If-None-Match is not present.
  5. If-Range: Evaluated last for partial content requests.

Common Mistakes

  • Mistake: Using weak validators for sub-range requests (resuming downloads).
    • Fix: Always use strong ETags for partial downloads to avoid file corruption.
  • Mistake: Failing to update the ETag after a content encoding change (like gzipping).
    • Fix: Ensure your server modifies the ETag when compressing a file to distinguish it from the uncompressed version.
  • Mistake: Implementing custom headers like "x-if-ready" for standard document transfers.
    • Fix: Use standard HTTP headers and status codes so that general-purpose tools like browsers and proxies can understand the request.

FAQ

What is the difference between a 304 and a 412 status code? A 304 Not Modified is used for "safe" requests like GET. It tells the browser that its cached version is still good, so no new data is sent. A 412 Precondition Failed is used for "unsafe" requests like PUT or DELETE. It tells the client that the file on the server has changed since they last checked, so the requested update was rejected.

Why should I use ETags instead of Last-Modified dates? ETags are generally more accurate because they identify the specific version of a file. A date-based validator might fail if a file is modified twice in a single second or if a server's clock is improperly synced. Additionally, some file systems may inadvertently update the modification date without the content actually changing.

Are there any security risks with conditional requests? [ETags can potentially be exploited as persistent identifiers to re-identify users or their browsers across different sessions] (RFC7232). To mitigate this, browsers should clear the cache when a user clears cookies or enters a private browsing mode.

Does a 304 response have a body? No. A 304 response is always terminated by the first empty line after the header fields. It cannot contain a message body.

Start Your SEO Research in Seconds

5 free searches/day • No credit card needed • Access all features