Home / OCI

OCICheat sheetAdvanced

OCI Object Storage conditional requests cheat sheet: ETags, safe overwrites and concurrent writers

Stop concurrent jobs from overwriting each other in Object Storage. CLI and Python patterns for create-once, compare-and-swap, conditional copy, retries and leases.

Deepak Bhardwaj7 min read

Applies toOCI Object Storage native API, OCI CLI, OCI Python SDK

When to use this

  • Two jobs update the same manifest and one update disappears.
  • A retried pipeline overwrites a published file.
  • A cleanup job deletes an object that was replaced after it was listed.
  • You copy an object while something else writes it.

Each object has an ETag that changes when the object is replaced. A conditional request tells the service to act only if the ETag is, or is not, what you expect. The check happens in the service, so it closes the gap between "check" and "write".

Quick reference

Goal Native API condition CLI
Create only if absent If-None-Match: * put --no-overwrite
Replace only the version I read If-Match: <etag> put --if-match
Delete only the version I checked If-Match: <etag> delete --if-match
Download only if unchanged If-Match: <etag> get --if-match
Download only if changed If-None-Match: <etag> get --if-none-match
Copy without overwriting the target Destination If-None-Match: * copy --destination-object-if-none-match-e-tag '*'
Copy a specific source revision Source If-Match copy --source-object-if-match-e-tag
Rename without overwriting New object If-None-Match: * rename --new-obj-if-none-match-e-tag '*'

Two limits to note: oci os object put has no general --if-none-match option, and on destination conditions * is the only valid if-none-match value.

Read ETags

NS=$(oci os ns get --query data --raw-output)
BUCKET=release-manifests
OBJ=prod/current.json

ETAG=$(oci os object head -ns "$NS" -bn "$BUCKET" --name "$OBJ" \
  --query etag --raw-output)
echo "$ETAG"

# ETags for a prefix
oci os object list -ns "$NS" -bn "$BUCKET" --prefix prod/ --all \
  --fields name,etag,size,timeModified \
  --query 'data[].{name:name,etag:etag,size:size}' --output table

Treat an ETag as opaque. Don't calculate it, compare it across buckets or use it as a content checksum. Use the MD5 or a stronger checksum for integrity.

Create once

oci os object put -ns "$NS" -bn "$BUCKET" \
  --name builds/4812/app.tar.gz --file app.tar.gz --no-overwrite

--no-overwrite suits interactive use and simple scripts. Check its exit code and output in your CLI version, because a skipped upload may look different from a failed one. For a race between writers, use the SDK, where the condition and status are explicit:

import oci

signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner()
client = oci.object_storage.ObjectStorageClient(config={}, signer=signer)
ns = client.get_namespace().data

def create_once(bucket, name, body):
    try:
        r = client.put_object(ns, bucket, name, body, if_none_match="*")
        return r.headers["etag"]
    except oci.exceptions.ServiceError as e:
        if e.status == 412:
            return None          # it already exists
        raise

Branch on HTTP status 412 and log e.code and e.request_id. Error code names differ by condition and operation.

Compare-and-swap update

Read content and ETag from the same response. A get followed by a separate head can return the body of one revision and the ETag of the next.

import json, random, time

def update_json(bucket, name, change, attempts=6):
    for n in range(attempts):
        got = client.get_object(ns, bucket, name)
        etag = got.headers["etag"]
        doc = change(json.loads(got.data.content))
        try:
            r = client.put_object(
                ns, bucket, name,
                json.dumps(doc).encode(),
                if_match=etag,
                content_type="application/json",
            )
            return r.headers["etag"]
        except oci.exceptions.ServiceError as e:
            if e.status not in (409, 412):
                raise
            time.sleep(random.uniform(0, 0.2 * 2 ** n))
    raise RuntimeError(f"{name}: still contended after {attempts} attempts")

On a conflict, re-read and re-apply the change. Never resend the old body with a new ETag; that is the lost update you are trying to prevent. The change function can run several times, so it must have no side effects.

The CLI equivalent:

oci os object put -ns "$NS" -bn "$BUCKET" --name "$OBJ" \
  --file new-current.json --if-match "$ETAG" --force

--force only skips the confirmation prompt here. --if-match still guards the write.

The ambiguous retry problem

A write succeeds, but the response is lost to a timeout. The client retries with the old ETag and gets 412 because its own first attempt changed the object.

Put a unique operation ID in the metadata and check it before treating a 412 as a conflict:

import uuid

op = str(uuid.uuid4())
try:
    client.put_object(ns, "release-manifests", "prod/current.json", body,
                      if_match=etag, opc_meta={"operation-id": op})
except oci.exceptions.ServiceError as e:
    if e.status != 412:
        raise
    h = client.head_object(ns, "release-manifests", "prod/current.json").headers
    if h.get("opc-meta-operation-id") != op:
        raise                    # another writer won

Another writer may replace the object between your success and the retry. If you must distinguish that case, store the operation history inside the document. Apply the same care to SDK automatic retries.

Safe delete, copy and rename

Delete only the revision that you inspected:

oci os object delete -ns "$NS" -bn "$BUCKET" --name "$OBJ" \
  --if-match "$ETAG" --force

Caution

--force removes the prompt. Without versioning, a successful delete can't be undone. Always pass --if-match in cleanup jobs that work from a listing.

Copy a fixed source revision to a new name:

oci os object copy -ns "$NS" -bn "$BUCKET" \
  --source-object-name "$OBJ" \
  --source-object-if-match-e-tag "$ETAG" \
  --destination-bucket release-archive \
  --destination-object-name 2026-11-25/current.json \
  --destination-object-if-none-match-e-tag '*'

Copy is asynchronous. Accepting the request isn't proof of completion, so check the work request and the destination object.

oci os object rename -ns "$NS" -bn "$BUCKET" \
  --source-name staging/app.tar.gz --new-name release/app.tar.gz \
  --new-obj-if-none-match-e-tag '*'

Large uploads

In the native API, commit_multipart_upload accepts if_match and if_none_match. Set the condition there, since the commit is what publishes the object:

client.commit_multipart_upload(
    ns, bucket, name, upload_id,
    oci.object_storage.models.CommitMultipartUploadDetails(
        parts_to_commit=parts),
    if_none_match="*",
)

When a commit fails with 412, abort the upload, or the uncommitted parts keep costing money.

A lease, and why it isn't enough

You can create locks/job-a with if_none_match="*", store an owner and expiry, and take over an expired lease with if_match.

Warning

A paused process can wake after its lease expires and continue to write. The lock object can't stop it. Protect the final write with if_match, or have the target reject old fencing tokens.

Release with a conditional delete, so that you never delete a lease that another worker has taken over. Use a database or queue when you need fairness, high contention or multi-object transactions.

Enforce it with IAM

Conditions are voluntary: a client that omits them can still overwrite. For append-only producers, grant create without overwrite or delete:

Allow dynamic-group release-writers to manage objects in compartment Prod where all {target.bucket.name='release-manifests', any {request.permission='OBJECT_CREATE', request.permission='OBJECT_INSPECT'}}

Test with the real principal. Other broader policies can still grant OBJECT_OVERWRITE.

Troubleshooting

Result Cause Action
412 on create Object exists Read it; decide whether it is your earlier attempt
412 on update Revision changed Re-read and re-apply
412 on every attempt Stale cached ETag Read body and ETag together
304 on conditional GET Object hasn't changed Use the cached copy
404 with a correct name Missing object or no permission Check IAM and namespace
Lost updates continue One writer is unconditional Find it; remove OBJECT_OVERWRITE

Prevent it next time

  • Publish immutable objects under unique names and switch one small pointer with if_match.
  • Enable versioning on pointer buckets. Versioning helps recovery; it doesn't prevent lost updates.
  • Count 412 responses per job. A rising rate means that you need partitioning or a queue.
  • Test with two writers and an injected timeout, not only with a single process.