S3 conditional uploads: reconcile the existing object
An existing object needs an identity check before a retried export can be called complete.
Quick answer
An S3 conditional upload with `If-None-Match: *` prevents replacement of an existing current object, but a precondition failure does not prove that your earlier upload succeeded. Reconcile the existing object's trusted operation identity and payload identity before treating a retry as complete. Keep a conflicting object, an unreadable object and an ambiguous transport failure as distinct outcomes.
On this page
An S3 conditional upload with If-None-Match: * prevents replacement of an existing current object, but a precondition failure does not prove that your earlier upload succeeded. Reconcile the existing object's trusted operation identity and payload identity before treating a retry as complete. Keep a conflicting object, an unreadable object and an ambiguous transport failure as distinct outcomes. [1][2]
What does a precondition failure actually prove?#
It proves that the requested condition was not satisfied, rather than proving business equivalence between your request and the existing object. With a conditional create, another object at the same name is enough to reject the operation. That object might be your earlier upload, another caller's upload or data left behind by a different workflow. [1]
Scenario: a fictional export service writes an immutable tenant statement to a general purpose S3 bucket. The export job has a durable operation identifier and a fixed input revision. Its final object key is derived from that identity before any upload begins. Retrying the same job uses the same key and the same finalized bytes.
The service wants to avoid overwriting a completed statement. It also wants to recover when the upload finishes but the response never reaches the worker. A missing acknowledgement leaves the worker with another question: whose statement is now at that key? Preventing overwrite protects the existing object; deciding that an operation completed requires evidence that the protected object represents the intended statement.
S3's conditional write documentation explains the object-name rule, concurrent completion and current-version behavior. In a versioned bucket, a current delete marker can permit a conditional create. This is therefore not a permanent tombstone for every name ever used. If a business identifier must never be reused, enforce that lifecycle separately. [1]
The missing upload response#
Treat an upload timeout as an unknown result until the service reconciles it. The absence of a success response does not tell the worker whether the object store accepted the object. Generating a new operation identifier on retry would avoid the name conflict while also abandoning the original deduplication boundary.
The illustrative service records a tuple containing tenant, statement period, input revision, operation identifier, final key and a digest of the exact finalized payload. It calculates that digest after serialization. A second serialization that adds a different timestamp or orders data differently is a different byte sequence, even when a reader considers the statement equivalent.
Decide whether the contract requires identical bytes or semantic equivalence. This example requires identical bytes, so retries reuse a retained payload artifact. If the service instead regenerates output, its canonicalization rules and revision inputs must be part of the contract. Do not hide a change of meaning behind the word “idempotent.”
Persist the operation record and finalized payload identity.
Use the recorded key for every attempt.
Send PutObject with If-None-Match: *.
On acknowledged success, record the returned object identity.
On precondition failure or ambiguous delivery, reconcile the existing object.
On mismatch, stop the operation and preserve the conflicting evidence.This is our workflow design, not an AWS transaction recipe. It does not atomically commit a database operation record together with the uploaded object. A recovery worker must be able to reconcile either side after interruption. If later notification or accounting effects must happen once, give those effects their own durable acceptance boundary.
How do you reconcile the existing object?#
Read the object metadata using HeadObject under the intended bucket, key and owner context. A HEAD response provides metadata without transferring the body. Compare the stored operation identifier and declared payload digest with the durable operation record, while checking that the metadata came from a writer whose contract you trust. [4]
def reconcile(expected, observed):
"""Pure decision example; the caller performs authenticated I/O."""
if observed['state'] == 'unreadable':
return 'HOLD_UNREADABLE'
if observed['state'] == 'missing':
return 'RETRY_CONDITIONAL_CREATE'
if observed['state'] != 'present':
return 'HOLD_UNKNOWN'
if not observed.get('trusted_writer'):
return 'VERIFY_PAYLOAD_OR_HOLD'
fields = ('tenant', 'operation_id', 'payload_sha256')
if all(observed.get(k) == expected[k] for k in fields):
return 'ACCEPT_EXISTING'
return 'HOLD_CONFLICT'The function receives normalized observations so an SDK error name cannot decide the business outcome. It makes the business decision visible, while leaving authentication, metadata normalization, checksums and transport handling to an adapter. Unit-testing this function can establish its branch behavior. It cannot establish that an SDK sends a conditional header or that a real bucket returns the expected metadata.
The trusted_writer flag is an integration precondition, not a value copied from object metadata. In this example, only the export service can write the relevant prefix, and that service computes the digest from the exact bytes it uploads. An arbitrary uploader who may claim any digest can forge the declaration. If that trust assumption is false, obtain and verify the payload or use another trustworthy content-verification path.
Do not equate every ETag with a universal payload hash. AWS documents ETag behavior that depends on how an object was uploaded and encrypted. Retain an explicit payload identity appropriate to the upload path, or use the documented checksum facilities after verifying their exact semantics for that path. Comparing a guessed hash format is weaker than retaining a clear application contract. [5]
User-defined metadata is attached to the upload and cannot be edited in place; changing it requires an object copy. That supports recording creation context, but does not make metadata independent evidence of correctness. The statement's tenant, revision and business contents still need validation before upload. Metadata cannot rescue a wrong payload merely because its fields look consistent. [5]
Which failures permit another upload?#
Separate a failed condition from a conflicting operation and from a failure to observe the result. AWS documents 412 Precondition Failed when the create condition fails and 409 ConditionalRequestConflict for a conflicting operation. The PutObject API documents retrying the latter. Keep retry attempts conditional and bounded; never remove the header as a recovery shortcut. [1][2]
| Observation | Service decision | Evidence needed next |
|---|---|---|
| Acknowledged create | Record the completed upload | Saved operation and object identity |
| Precondition failed | Reconcile the current object | Trusted identity and payload match |
| Conditional conflict | Retry within budget or reconcile | Unchanged operation key and bytes |
| Response lost | Preserve unknown outcome | Authenticated observation of the key |
| Existing object differs | Hold the operation | Conflict investigation, not overwrite |
If HEAD reports an access error, the worker has not established that the object is missing. S3's documented responses for an absent object depend partly on listing permission. Keep this classification in the adapter, and hold an unreadable state rather than turning it into permission to create or widen access. The existing HeadObject diagnosis develops that distinction. [4]
There is also a read-after-observation race if another authorized writer can replace the object after you inspect it. The illustrative immutable-prefix contract excludes unconditional overwrites and unreviewed deletes. If your workload requires mutable objects, this acceptance algorithm is incomplete: retain the relevant version identity or design a separate conditional-update protocol.
Stop retries when the saved operation deadline or attempt budget is exhausted. Persist enough information that a restart continues the same operation rather than beginning a new logical upload. Record the terminal reason when the budget expires. “Unresolved after bounded reconciliation” is an honest state; labelling it successful because an object probably exists is not.
Where do multipart and policy change the contract?#
Multipart upload has a different recovery boundary from a single PutObject. The condition is relevant at completion, and the CompleteMultipartUpload API documents reinitiating the multipart upload and re-uploading parts after the specified conditional conflict. Do not reuse the single-request retry branch without reviewing that API path. [3]
The adapter must also handle the completion response correctly. AWS warns that a completion response can carry an embedded error after an initial success status. Prefer the SDK's documented handling and verify it with the actual client version. An HTTP status observed too early is not enough evidence that the final object was accepted. [3]
Keep unfinished multipart state in the operation journal when using that upload mode. The operation identifier and final payload identity remain stable, but the upload identifier may change during recovery. Confusing the two identities makes it hard to tell a retried transport session from a new business operation.
Bucket policy can enforce conditional writes for an intended general purpose bucket scope. That prevents one cooperating writer from preserving the protocol while another path silently uses unconditional writes. The policy must account for multipart setup and part operations, which do not all accept the conditional headers used at object creation. [6]
Review the actual upload paths before applying such a policy. A script, managed transfer tool, copy workflow or service integration may behave differently from your application's PutObject call. Start with a dedicated test prefix and inspect allowed and rejected requests. This article does not provide a universal policy that is safe to attach to every bucket.
Normalize the adapter's observations before calling the decision function. Distinguish a missing metadata field from an empty string, and retain the exact digest algorithm and representation used by the operation record. A case conversion or encoding assumption should not make different payload identities compare equal. Reject malformed observations before they can enter the accepted branch; do not silently invent defaults for identity fields.
How should you verify the decision before rollout?#
Begin with the pure decision cases, then test the real adapter separately. Supply a matching existing object, a different operation identifier, a different digest, a tenant mismatch, an unreadable state and a missing state. Verify that only the authorized matching object is accepted and that conflicts remain held without an overwrite attempt.
Next test loss of the upload response. In an integration environment, arrange for the service to lose the acknowledgement after the object is accepted, then resume with the same durable operation record. The desired result is acceptance of the existing matching object, with no second logical statement. This run's synthetic decision checks do not claim that provider-level fault injection was performed.
Check the request emitted by the actual SDK and the values returned by HEAD. Retain its version, request parameters, redacted metadata, object version if applicable and the recovery decision. Do not put credentials, signed URLs or sensitive payload contents in the editorial or operational evidence bundle.
Include a negative control with an existing object from a different operation. The service must hold the conflict even if the bytes happen to match, because the chosen contract requires operation identity as well as payload identity. If the business wants content-addressed deduplication instead, change the contract explicitly and test that distinct rule.
Finally, verify the downstream behavior. An accepted object is not proof that a notification was sent, a database record was finalized or a customer download remains authorized. Our transactional outbox guide is relevant when recording completion must trigger another durable effect. Keep the evidence for each effect separate.
What else should you check?#
- Should every retry generate a fresh object key?
- Use the same key when retrying the same logical upload under this immutable-output contract. A new key changes the identity boundary and can create another object. Generate a new operation only when the business has actually requested different work.
- Can matching bytes alone mean the operation succeeded?
- That depends on the chosen business contract. The example requires matching tenant, operation identity and payload identity. Identical content from a different operation is held. Content-addressed deduplication is another valid design, but its acceptance rule must be explicit.
- What belongs in object metadata?
- Use small, nonsecret identifiers that help reconcile the upload, such as a normalized operation identifier and payload digest computed by the trusted writer. Keep credentials and private business contents out. Metadata is a declaration whose trust depends on writer permissions and implementation.
- Does conditional creation replace an outbox?
- No. Protecting the object name does not atomically record a separate database change or deliver a notification. Use an explicit recovery protocol for those effects. If a database completion record must trigger delivery, consider an outbox with its own acceptance and retry rules.