Skip to main content

Using Idempotency Keys in eSIM Provisioning APIs

Updated 4 min readMarkdown

Provisioning APIs live on networks that fail. A client sends a request to create an eSIM order, the connection drops, and the client has no idea whether the server acted on it. It has two choices: give up and risk leaving a customer without a profile, or retry and risk a second profile. An idempotency key removes the dilemma. This post shows how to design and implement it for a provisioning API.

The idea

The client generates a unique key for each logical operation and sends it with the request. The server stores the result of the first execution under that key. Any later request with the same key returns the stored result and does not run the operation again. The retry becomes safe.

The convention is an Idempotency-Key HTTP header, and the key is usually a random UUID created before the first attempt:

POST /v1/orders HTTP/1.1
Idempotency-Key: 6f1c1d9e-3d52-4a73-9f0a-0b9d6d2f7e11
Content-Type: application/json

{"product_id": "data-5gb-30d", "customer_ref": "c_1842"}

What the server must guarantee

  1. First request: execute the operation, store the key, the request fingerprint and the response, then return the response.
  2. Repeat with the same key and the same request: return the stored response, with the same status code.
  3. Repeat with the same key but a different request body: reject with an error. Reusing a key for different work is a client bug and silently returning the old result would hide it.
  4. Concurrent requests with the same key: only one executes. The other must wait or get a conflict response that says an attempt is in progress.

A table that does the work

CREATE TABLE idempotency_keys (
    key           TEXT NOT NULL,
    scope         TEXT NOT NULL,        -- e.g. the API client or merchant
    request_hash  TEXT NOT NULL,        -- fingerprint of the body
    status        TEXT NOT NULL,        -- in_progress | completed
    response_code INTEGER,
    response_body JSONB,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (scope, key)
);

The composite primary key means that the same key from two different clients does not collide, and the database itself enforces uniqueness for concurrent attempts.

The handler

import hashlib, json

def handle_create_order(db, scope, key, body):
    fingerprint = hashlib.sha256(
        json.dumps(body, sort_keys=True).encode()
    ).hexdigest()

    with db.transaction():
        row = db.insert_if_absent(
            "idempotency_keys",
            scope=scope, key=key,
            request_hash=fingerprint, status="in_progress",
        )
        if not row.created:                      # key seen before
            existing = db.get("idempotency_keys", scope=scope, key=key)
            if existing.request_hash != fingerprint:
                return 422, {"error": "key reused with a different request"}
            if existing.status == "in_progress":
                return 409, {"error": "request in progress, retry later"}
            return existing.response_code, existing.response_body

        order = create_order_and_allocate_profile(db, body)   # same transaction
        response = (201, {"order_id": order.id})
        db.update("idempotency_keys", scope=scope, key=key,
                  status="completed",
                  response_code=response[0], response_body=response[1])
        return response

The important property is that the order, the profile allocation and the stored response commit together. If anything fails, the whole transaction rolls back, the key disappears, and the client may retry as if nothing had happened.

The harder part: calls to other systems

A database transaction cannot cover an HTTP call to a supplier. If your handler calls the SM-DP+ to prepare a profile and then crashes before it records the result, a retry would call the supplier again. Two approaches help:

  • Pass your own idempotency key downstream. If the supplier supports it, derive a stable key from your order ID so that repeating the call is safe on their side.
  • Record intent before the call, and the outcome after. Write a row that says that you are about to call, make the call, and write the result. A recovery job can finish half-done operations by asking the supplier for the order's status.

Expiry and key reuse

Keys do not need to live forever. A retention window of a day or a few days is common, long enough to cover any realistic retry. Document it for API consumers, and state that keys must be unique per logical operation.

Which operations need keys

  • Creating orders and allocating profiles: yes, always.
  • Sending activation codes by email or SMS: yes, or customers receive duplicates.
  • Refunds and cancellations: yes.
  • Pure reads: no, they are safe by nature.
  • Updates that set a value, such as setting a state to a specific value, are naturally idempotent. Updates that add to a value are not.

Takeaways

  • The client chooses the key, and the server stores and replays the result.
  • Store a fingerprint so that key reuse with a different body fails clearly.
  • Commit the work and the stored response in the same transaction.
  • Plan for downstream calls that a transaction cannot protect.

About the author: I work on content and web development at eSIMCircle, a travel eSIM provider. This series comes from the engineering side of that work.

About the author

  • eSIMCircle provides affordable global eSIM plans with reliable data in 200+ countries.

No comments yet. Be the first to comment.

More from this blog