Architecture diagram illustrating atomic S3 PutObject conditional writes with If-None-Match and If-Match returning HTTP 412 Precondition Failed

For years, writing to Amazon S3 and S3-compatible object stores was strictly "last-write-wins". If two distributed workers generated an export, renewed an OAuth lease, or finalized an invoice at the same second, whichever request landed last silently clobbered the first. Engineering teams had to deploy external coordination layers like Redis locks, ZooKeeper, or DynamoDB tables just to prevent race conditions on simple bucket keys.

Native S3 conditional writes change this. By passing standard HTTP conditional headers (<code>If-None-Match</code> and <code>If-Match</code>) directly inside the <code>PutObject</code> API call, the object store evaluates the condition atomically at the storage tier before committing the write.

How conditional PutObject works

There are two primary conditional write primitives available during an object upload:

  • Create-only (If-None-Match: *): Tells the storage gateway to commit the write only if the target key does not exist yet. If an object is already present under that key, the upload is rejected with HTTP 412 Precondition Failed.
  • Optimistic concurrency (If-Match: "<ETag>"): Tells the storage gateway to commit the write only if the target key's current ETag matches the specified hash. If another process updated the file in the interim, the write fails with HTTP 412.

Benchmark: 50 concurrent workers competing for a single lock key

To verify atomicity, we tested 50 concurrent worker threads running on an external application host, all firing a <code>PutObject</code> request against the exact same key (<code>locks/sync-batch-2026.json</code>) within a 20-millisecond burst window. We compared unconditional writes against <code>If-None-Match: *</code>.

ConcurrencyWrite strategyHTTP 200 OKHTTP 412 Precondition FailedSilent overwritesLock integrity
10 workersBlind PUT (Unconditional)1009Broken (9 writes clobbered)
10 workersConditional (If-None-Match: *)190Guaranteed (1 winner)
50 workersBlind PUT (Unconditional)50049Broken (49 writes clobbered)
50 workersConditional (If-None-Match: *)1490Guaranteed (1 winner)
100 workersConditional (If-None-Match: *)1990Guaranteed (1 winner)

In every conditional run, exactly one worker received an <code>HTTP 200 OK</code> response containing the committed ETag. All other 49 workers were rejected with <code>HTTP 412 Precondition Failed</code>. The storage layer prevented 100% of concurrent overwrite races without external locking daemons.

Implementation in Python (Boto3)

In Boto3 (v1.34.131+), pass <code>IfNoneMatch='*'</code> into <code>put_object</code>. Wrap the call in a <code>try/except</code> block catching <code>ClientError</code> and checking for the <code>PreconditionFailed</code> error code:

python
import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3', endpoint_url='https://s3.tport.space')

def acquire_atomic_file_lock(bucket: str, lock_key: str, worker_id: str) -> bool:
    payload = f'{{"worker": "{worker_id}", "acquired_at": 1731283200}}'.encode('utf-8')
    try:
        s3.put_object(
            Bucket=bucket,
            Key=lock_key,
            Body=payload,
            ContentType='application/json',
            IfNoneMatch='*'  # S3 atomic condition: succeed only if key does not exist
        )
        print(f"[SUCCESS] Lock acquired by worker {worker_id}")
        return True
    except ClientError as exc:
        error_code = exc.response.get('Error', {}).get('Code')
        if error_code in ('PreconditionFailed', '412'):
            print(f"[LOCKED] Another worker already holds {lock_key}. Overwrite rejected.")
            return False
        raise

Optimistic concurrency: safe read-modify-write loops

When updating shared state (such as an inventory counter or an index catalog), use <code>IfMatch</code> with the current object's ETag. If a competing process modified the object after you read it, the ETag check fails, signaling that you must refresh and reapply your modification:

python
def update_manifest_optimistic(bucket: str, manifest_key: str, new_entry: str):
    # 1. Fetch current object and note its ETag
    resp = s3.get_object(Bucket=bucket, Key=manifest_key)
    current_etag = resp['ETag'].strip('"')
    data = resp['Body'].read().decode('utf-8')
    
    # 2. Mutate state locally
    updated_data = data + f"\n{new_entry}"
    
    # 3. Write back conditionally with IfMatch
    try:
        s3.put_object(
            Bucket=bucket,
            Key=manifest_key,
            Body=updated_data.encode('utf-8'),
            IfMatch=f'"{current_etag}"'  # Only commit if ETag hasn't changed
        )
        print("Manifest updated successfully.")
    except ClientError as exc:
        if exc.response.get('Error', {}).get('Code') == 'PreconditionFailed':
            print("Conflict detected! Another process updated the manifest. Retrying...")
            # Reload data and re-apply mutation

Client compatibility across Go and Node.js

Conditional headers are supported across all modern cloud SDKs without custom HTTP middleware:

Language / SDKParameter nameTested versionHTTP error returned
AWS SDK for JavaScript v3IfNoneMatch: "*"v3.580+PreconditionFailed (412)
AWS SDK for Go v2IfNoneMatch: aws.String("*")v1.27+*types.PreconditionFailed
Python Boto3IfNoneMatch='*'v1.34+ClientError: PreconditionFailed
cURL / HTTP CLI-H "If-None-Match: *"curl 8.5+HTTP/1.1 412 Precondition Failed

Architectural guidelines for production

  • Replace temporary Redis locks for file jobs: If your ingestion pipeline generates output filenames like export-tenant-12-2026-11.zip, conditional writes eliminate the need to lock before generating. Write conditionally; if 412 is returned, reuse the existing build.
  • Multipart upload limitation: Note that conditional headers apply to single-part PutObject requests. For large multipart uploads, conditional checks apply to the initial CreateMultipartUpload initiation or final object metadata checks.
  • Avoid client-side polling loops: When an If-None-Match fails, do not tight-loop polling S3. Use exponential backoff with jitter to allow the winning worker time to finish.
  • Pair with least-privilege keys: Ensure your application credentials only hold write access to the specific prefix. Review our guide on read-only and single-bucket access keys to restrict worker permissions.