API

Idempotency

How ulex deduplicates writes: the Idempotency-Key header, the 24-hour replay window, response replay semantics, conflicts on replay, how it differs from X-Ulex-Request-Id, natural-key idempotency in MCP tools, and the operations that are never idempotent.

Network calls fail in the two worst ways: after the server did the work, or during it. Idempotency keys make the first case safe.

http
POST /api/v1/users HTTP/1.1
Authorization: Bearer ulex_sk_live_7Qm2KpLx9Tb4Ns8RfWy3Zc1Hjf6Ee0Au
Idempotency-Key: 3c9d1f77-0b2e-4a58-9d61-5e7a2c40b913

Send it on every POST that creates a resource. It is a header, never a body field, and never a query parameter.

#Semantics

ulex stores (tenant_id, method, path, key) → (status, body, headers) for 24 hours.

SituationFirst callRetry with the same key
Succeeds201 + body201 + the same body, byte for byte
Fails validation400 + body400 + the same body, not re-validated
Fails with 5xx500 + bodythe original 5xx is not cached; the request is retried for real
Connection drops after the writeunknown201 + the original body
Different body, same key—409 conflict

That last row is the important one:

json
{
  "error": {
    "type": "conflict_error",
    "code": "invalid_request",
    "message": "This Idempotency-Key was already used with a different request body.",
    "param": "Idempotency-Key",
    "request_id": "req_01M3PSW9R0175NAW62NYR403R8",
    "retryable": false,
    "hint": "Use a new key, or resend the original body byte for byte."
  }
}
http
HTTP/2 409 Conflict
Warning

A replayed response is the original response, including its original id and created_at. If you were expecting a freshly generated id on the retry, you will get the old one. That is the point: the retry is a read of the first outcome, not a second write.

#Key format

Any string, 1–64 characters. In practice use a UUID v4, or a deterministic key derived from the operation:

ts
import { createHash } from "node:crypto";

// Random: one key per logical create, reused across retries of that create.
const key = crypto.randomUUID();

// Deterministic: the same logical create always produces the same key, so a
// crash-and-retry from scratch converges instead of duplicating.
function stableKey(scope: string, ...parts: string[]): string {
  return createHash("sha256").update([scope, ...parts].join("")).digest("hex").slice(0, 32);
}
stableKey("user", "dana@acme.example");               // same key on every run
stableKey("org", "acme.example");                     // same key on every run
stableKey("conn", "org_01M3PSV8HGTKQFCAYF9GDWGN3C", "okta_oidc");

Deterministic keys are strictly better for fixture setup, because a script that is run twice produces the same tenant state rather than a second copy. Use random keys for operations where two runs genuinely should produce two results.

#Idempotency-Key versus X-Ulex-Request-Id

Different things. Use both, with different values.

Idempotency-KeyX-Ulex-Request-Id
Purposededuplicate the writelabel it in the audit log
Scope(method, path, key) per tenant, 24 hany string ≤ 64, stored forever
Reuse on a different body409harmless, just a shared label
Effectsuppresses the second writenone
Repeated with a different body409entries share the id, which is what you want for correlation
bash
# Correct: two distinct concepts, two distinct values.
curl -sS -X POST "$BASE/users" \
  -H "Authorization: Bearer $ULEX_API_KEY" \
  -H "Idempotency-Key: $CREATE_KEY" \
  -H "X-Ulex-Request-Id: $THIS_ATTEMPT" \
  -H "X-Ulex-Correlation-Id: $THIS_JOB" \
  -H "Content-Type: application/json" \
  -d "$BODY"

X-Ulex-Correlation-Id is the third: it groups every call in one logical job across retries, services, and agents. Use it for the workflow; use X-Ulex-Request-Id for the attempt.

#Which methods accept a key

MethodKey honouredNotes
POSTyesthe whole point
PATCH, PUTyesbody is compared; a different body is 409
DELETEyesa replayed delete returns the original {"deleted": true}
GETignoredreads are naturally idempotent
GET with side effects (/activate, /enable, /saml/login)ignoredthese are idempotent by design — see below

#Naturally idempotent operations

These need no key because repeating them is a no-op:

OperationWhy
POST /connections/{id}/activateactivating an active connection returns the same object
POST /webhooks/{id}/enableenabling an enabled endpoint is a no-op; failure_count is already 0
POST /users/{id}/suspendsuspending a suspended user revokes nothing further
POST /users/{id}/unsuspendsame
POST /oauth2/revokeRFC 7009: revoking an already-revoked token returns 200 {"revoked": true}
POST /connections/{id}/verifyit is a read that performs a fetch
PUT /groups/{id}/membersit is a full replace, so applying it twice is the same state
POST /organizations/{id}/membersit is an upsert on (organization_id, user_id)
GET /oauth2/introspecta read

And these are not idempotent, no matter how many keys you send:

OperationConsequence of a repeat
POST /oauth2/token with grant_type=refresh_tokenrotates; replaying the old refresh token revokes the family
POST /oauth2/token with grant_type=authorization_codeinvalid_grant — the code is consumed
POST /deploymentsa new deployment, a new dep_…
POST /deployments/{id}/rollbacka new rolled-back deployment
POST /scim/v2/Bulkre-applies; safe for POST /Users (409 on duplicate) but noisy for PATCH
POST /webhooks/{id}/testa new delivery each time
POST /simulator/authenticatea new session each time
POST /tenants/current/rotate-signing-keysa new key each time
POST /applications/{id}/rotate-secreta new secret each time; the previous one is invalidated at grace expiry
Warning

POST /oauth2/token is the dangerous one. A network timeout on a refresh is exactly the situation where you would retry, and a naive retry with the same refresh token kills the whole token family. If a refresh times out, do not retry with that token — introspect it. If it is still active, keep using it; if it is revoked, start a new login.

#MCP tools

Every ulex MCP tool that creates a resource accepts an idempotency_key argument with the same semantics and the same 24-hour window.

json
{ "name": "ulex_create_user", "arguments": {
  "email": "dana@acme.example",
  "idempotency_key": "3c9d1f77-0b2e-4a58-9d61-5e7a2c40b913"
} }

On top of that, several tools are naturally idempotent on a business key:

ToolNaturally idempotent on
ulex_bootstrap_app(application_name, organization_domain)
ulex_create_organizationslug
ulex_create_useremail
ulex_create_applicationslug
ulex_create_group(organization_id, slug)
ulex_add_organization_member(organization_id, user_id)
ulex_activate_connectionconnection state
ulex_reset_simulationresets to the same state
ulex_reset_tenantdeletes to the same state
Note

Natural-key idempotency means you can call ulex_create_user twice for the same email without a key and the second call returns 409 resource_exists rather than a duplicate. That is safe but noisy. A key converts the 409 into a clean 200 with the original body. If you expect to retry, send the key.

#SCIM

SCIM has no Idempotency-Key. It has something better for provisioning: userName and externalId are unique per directory, so a duplicate POST /scim/v2/Users returns 409 with scimType: "uniqueness" rather than creating a twin. That is the correct semantic and IdPs rely on it.

For bulk provisioning, reconcile rather than re-post: GET /scim/v2/Users?filter=userName eq "…" first, then POST only what is missing, then PATCH what changed.

#A correct create-with-retry

ts
export async function createUserSafe(input: CreateUserInput): Promise<User> {
  const key = input.idempotency_key ?? stableKey("user", input.email);

  for (let attempt = 0; attempt < 5; attempt++) {
    try {
      const { user } = await tools.ulex_create_user({ ...input, idempotency_key: key });
      return user;
    } catch (err) {
      const envelope = err as UlexEnvelope;
      if (envelope?.error?.retryable) {
        const wait = parseRetryAfterSeconds(envelope) ?? 0.5 * (attempt + 1);
        await new Promise((r) => setTimeout(r, Math.round(wait * 1000)));
        continue;
      }
      // 409 resource_exists on a natural key is not a failure to retry: the
      // user exists, which is the outcome we wanted. Fetch and return it.
      if (envelope?.error?.code === "resource_exists") {
        const { user } = await tools.ulex_get_user({ user_id: await findIdByEmail(input.email) });
        return user;
      }
      throw err;
    }
  }
  throw new Error(`createUserSafe exhausted retries for ${input.email}`);
}

Deeper: Errors, Rate limits, Patterns.