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
| Header | The 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
| Operation | Headers |
|---|---|
| GetObject, HeadObject | The four standard conditional headers |
| PutObject | The four standard conditional headers |
| CreateMultipartUpload | The four standard conditional headers. Checked immediately, and kept to be evaluated again at Complete |
| CompleteMultipartUpload | The 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-* |
| DeleteObject | Only If-Match is supported; other conditional headers are ignored |
| UploadPart, form upload, DeleteObjects | Not supported; conditional headers are ignored |
Conditional reads
| Header | When the condition fails |
|---|---|
If-Match、If-Unmodified-Since | 412 |
If-None-Match, If-Modified-Since | 304, 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:
raiseimport { PutObjectCommand } from "@aws-sdk/client-s3";
try {
await s3.send(new PutObjectCommand({
Bucket: "my-bucket", Key: "locks/job-1", Body: "worker-a", IfNoneMatch: "*",
}));
console.log("Lock acquired");
} catch (e) {
if (e.$metadata?.httpStatusCode === 412) console.log("Already taken");
else throw e;
}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")import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
async function update(Bucket, Key, change, attempts = 10) {
for (let i = 0; i < attempts; i++) {
const obj = await s3.send(new GetObjectCommand({ Bucket, Key }));
const data = change(JSON.parse(await obj.Body.transformToString()));
try {
return await s3.send(new PutObjectCommand({
Bucket, Key, Body: JSON.stringify(data),
ContentType: "application/json", IfMatch: obj.ETag,
}));
} catch (e) {
if (![409, 412].includes(e.$metadata?.httpStatusCode)) throw e;
await new Promise((r) => setTimeout(r, Math.random() * 100 * 2 ** i));
}
}
throw new Error("Too many conflicts");
}When the object does not exist
| Header | Result |
|---|---|
If-Match (any value) | 404 NoSuchKey |
If-Modified-Since | 412 |
If-None-Match, If-Unmodified-Since | The 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).
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.
| Header | Applies to |
|---|---|
x-amz-copy-source-if-match | Source |
x-amz-copy-source-if-none-match | Source |
x-amz-copy-source-if-unmodified-since | Source |
x-amz-copy-source-if-modified-since | Source |
btf-copy-destination-if-match | Destination |
btf-copy-destination-if-none-match | Destination |
btf-copy-destination-if-unmodified-since | Destination |
btf-copy-destination-if-modified-since | Destination |
- 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
| Condition | Permissions required |
|---|---|
If-None-Match: * | Write permission |
| Other write conditions, conditional delete | Write permission plus read permission on the destination object |
| Source conditions | Read 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
| Status | Code | Meaning | Recommendation |
|---|---|---|---|
| 304 | Conditional read: the content has not changed | Use the local cache | |
| 403 | AccessDenied | No read permission required by the condition | Adjust the grant |
| 404 | NoSuchKey | The object targeted by If-Match does not exist | Decide based on your use case whether to create it with If-None-Match: * instead |
| 409 | OperationAborted | Conflicts with a concurrent write | Wait and retry |
| 412 | PreconditionFailed | The condition does not hold | Do not retry as is. Read the latest state, then decide whether to write |
| 500, 503 | InternalError, ServiceUnavailable | Server error | The 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.