Skip to content
Console

Conditional requests

Conditional requests make S4 perform an operation only when a condition holds. Use them on reads to avoid repeated downloads, and on writes to prevent overwriting each other, which lets you build distributed locks and optimistic-locking updates.

Write conditions are atomic: if multiple clients write the same key with the same condition at the same time, at most one succeeds.

Conditional headers

HeaderThe condition holds when
If-Match: "<etag>"The current ETag equals the given value
If-Match: *The object exists
If-None-Match: *The object does not exist
If-None-Match: "<etag>"The current ETag differs from the given value
If-Unmodified-Since: <date>The object has not been modified since that time
If-Modified-Since: <date>The object has been modified since that time
  • You can give multiple ETags separated by commas; matching any one is enough. Weak ETags (with the W/ prefix) are compared like regular ETags.
  • Dates use the HTTP format, for example Tue, 24 Nov 2026 08:00:00 GMT. Dates that cannot be parsed are ignored.
  • Time precision is one second. Use ETags when you need an exact comparison.

Supported operations

OperationHeaders
GetObject, HeadObjectThe four standard conditional headers
PutObjectThe four standard conditional headers
CreateMultipartUploadThe four standard conditional headers. Checked immediately, and kept to be evaluated again at Complete
CompleteMultipartUploadThe four standard conditional headers
CopyObject, move (destination conditions)The four standard conditional headers, or btf-copy-destination-if-*
CopyObject, move, UploadPartCopy (source conditions)x-amz-copy-source-if-*
DeleteObjectOnly If-Match is supported; other conditional headers are ignored
UploadPart, form upload, DeleteObjectsNot supported; conditional headers are ignored

Conditional reads

HeaderWhen the condition fails
If-Match、If-Unmodified-Since412
If-None-Match, If-Modified-Since304, no content returned

When both appear, If-Match causes If-Unmodified-Since to be ignored, and If-None-Match causes If-Modified-Since to be ignored. The 304 and 412 responses to reads have no response body.

curl -I -H 'If-None-Match: "9a0364b9e99bb480dd25e1f0284c8555"' \
  "https://my-bucket.s3.bitiful.net/config.json"

Conditional writes

Create only if the object does not exist

If-None-Match: * guarantees that an existing object is not overwritten. Use it to acquire locks, enforce unique keys, and avoid duplicate writes.

from botocore.exceptions import ClientError

try:
    s3.put_object(Bucket="my-bucket", Key="locks/job-1", Body=b"worker-a", IfNoneMatch="*")
    print("Lock acquired")
except ClientError as e:
    if e.response["ResponseMetadata"]["HTTPStatusCode"] == 412:
        print("Already taken")
    else:
        raise

Optimistic-locking update (CAS)

Read the content and ETag first, modify it, then write it back with If-Match. If someone else changed the object in the meantime, S4 returns 412; read it again and retry.

import json, random, time
from botocore.exceptions import ClientError


def update(bucket, key, change, attempts=10):
    for i in range(attempts):
        obj = s3.get_object(Bucket=bucket, Key=key)
        data = change(json.loads(obj["Body"].read()))
        try:
            return s3.put_object(
                Bucket=bucket, Key=key, Body=json.dumps(data).encode(),
                ContentType="application/json", IfMatch=obj["ETag"],
            )
        except ClientError as e:
            if e.response["ResponseMetadata"]["HTTPStatusCode"] not in (409, 412):
                raise
            time.sleep(random.uniform(0, 0.1 * 2 ** i))
    raise RuntimeError("Too many conflicts")

When the object does not exist

HeaderResult
If-Match (any value)404 NoSuchKey
If-Modified-Since412
If-None-Match, If-Unmodified-SinceThe condition holds; the write proceeds normally

When a write request carries multiple conditional headers, all of them must hold; there is no precedence. This differs from conditional reads.

Multipart uploads

  • Putting conditions on CreateMultipartUpload lets you find out they are not met before uploading parts, which saves traffic. The conditions are kept and still apply at Complete even if you do not repeat the headers.
  • Conditions on CompleteMultipartUpload are evaluated at the moment of submission.
  • If you put conditions on both, both sets must hold.
  • When a condition fails, the uploaded parts are retained. Call AbortMultipartUpload when you no longer need them.

Conditional delete

If-Match makes the deletion happen only if the ETag matches (or *, meaning the object exists).

Python (boto3)
s3.delete_object(Bucket="my-bucket", Key="locks/job-1", IfMatch=etag)

If the object does not exist, S4 returns 404; if the ETag does not match, it returns 412. Directory objects (keys ending in /) do not support conditional delete.

Conditional copy and move

Source conditions test the object being copied, and destination conditions test the location being written. You can use both at once.

HeaderApplies to
x-amz-copy-source-if-matchSource
x-amz-copy-source-if-none-matchSource
x-amz-copy-source-if-unmodified-sinceSource
x-amz-copy-source-if-modified-sinceSource
btf-copy-destination-if-matchDestination
btf-copy-destination-if-none-matchDestination
btf-copy-destination-if-unmodified-sinceDestination
btf-copy-destination-if-modified-sinceDestination
  • A failed source condition returns 412. When several source conditions appear together, precedence is the same as for conditional reads.
  • Destination conditions can also use the standard If-* headers directly. If both forms of the same condition are present, btf-copy-destination-if-* takes precedence.
  • Move (?move=true) also supports source and destination conditions.

Copy only if the destination does not exist:

curl -X PUT "https://my-bucket.s3.bitiful.net/backup/a.txt" \
  --aws-sigv4 "aws:amz:cn-east-1:s3" --user "<AccessKey>:<SecretKey>" \
  -H "x-amz-copy-source: /my-bucket/a.txt" \
  -H "btf-copy-destination-if-none-match: *"

Required permissions

ConditionPermissions required
If-None-Match: *Write permission
Other write conditions, conditional deleteWrite permission plus read permission on the destination object
Source conditionsRead permission on the source object, which copying requires anyway

These conditions reveal the object's ETag or modification time, so they require read permission. Insufficient permission returns 403 AccessDenied. For how to grant permissions, see Sub-user permissions.

Anonymous requests cannot use write conditions that require read permission.

Status codes and retries

StatusCodeMeaningRecommendation
304Conditional read: the content has not changedUse the local cache
403AccessDeniedNo read permission required by the conditionAdjust the grant
404NoSuchKeyThe object targeted by If-Match does not existDecide based on your use case whether to create it with If-None-Match: * instead
409OperationAbortedConflicts with a concurrent writeWait and retry
412PreconditionFailedThe condition does not holdDo not retry as is. Read the latest state, then decide whether to write
500, 503InternalError, ServiceUnavailableServer errorThe write outcome is uncertain; read the object to confirm before retrying

If a request with If-None-Match: * is retried automatically after a network timeout, the first attempt may actually have succeeded, and the second gets 412. After receiving 412, read the object to confirm whether you wrote it, for example by writing a unique ID into the content.

When you upload a large file and the condition fails, S4 returns 412 and closes the connection before receiving the content. A client that does not use Expect: 100-continue may only see the connection reset. Mainstream SDKs handle this by default.