> ## Documentation Index
> Fetch the complete documentation index at: https://openloop.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Retries and idempotency

> Which calls are safe to retry, how an email read avoids duplicate patients you cannot delete, and why a repeated subscription update adds a line.

A request timed out and you do not know whether it landed. This page tells you which calls you can
send again as they are, which ones quietly create a second record when you do, and what to read
instead of guessing.

## What you'll do

**1. Send a key where the platform takes one**

Two appointment writes **require** an `Idempotency-Key`; nine billing writes accept one.

**2. Look before you create**

`GET /v0.1/patients?email=<address>` is the de-duplication read — there is no upsert.

**3. Re-send only what is safe**

Reads are safe. A create without a key is not, and a key already spent on a finished attempt
replays that attempt instead of making a new one.

**4. Report a duplicate you already made**

Two patients, two ids, one email — keep one, and ask OpenLoop to remove the other. You cannot
delete it yourself.

## Which calls are safe to send again

| Call | Safe to retry? | What a second send does |
| - | - | - |
| Any `GET` | **Yes** | Nothing. Note the read-back lag below before you trust a fresh read |
| `POST /v0.1/appointments`, `PATCH /v0.1/appointments/{id}` | **Yes, with the same key** | Replays the stored response. Without a key the call never reaches validation |
| The nine billing `POST`s | **Yes, with the same key** | Replays the stored response — including a stored *failure*. **Without a key, `POST /v0.1/subscriptions` creates a second subscription** |
| `POST /v0.1/patients`, `/questionnaire-responses`, `/reservations` | **No** | Creates a second record with a new id. These routes take no key |
| `PUT /v0.1/subscriptions/{provider_subscription_id}` | **No** | Applies the change again — an `items` entry carrying only a `provider_price_id` adds another line |

## Recipe · Send an Idempotency-Key where the platform takes one

`Idempotency-Key` is a **request header**, and the published reference declares it on twelve
write operations. On two of them it is required:

| Operation | Key | Missing key |
| - | - | - |
| `POST /v0.1/appointments` | **Required** | `400` `missing-idempotency-key` |
| `PATCH /v0.1/appointments/{id}` | **Required** | `400` `missing-idempotency-key` |
| `POST /v0.1/coupons`, `/promotion-codes` | Optional | Accepted; a retry creates a second resource |
| `POST /v0.1/checkouts/sessions` | Optional | Accepted; a retry creates a second session |
| `POST /v0.1/subscriptions`, `/billing-customers`, `/intents/setups` | Optional | Accepted; a retry of `/subscriptions` creates a second subscription, and of `/intents/setups` a second setup intent |
| `POST /v0.1/billing-portals/{id}/sessions` | Optional | Accepted; a retry creates a second session |
| `POST /v0.1/invoices/{provider_invoice_id}/payments`, `/refunds` | Optional | Accepted; paying an invoice that is already paid returns the invoice, and an identical refund request within 24 hours is treated as a retry |
| `POST /v0.1/laboratories` | Optional | Accepted; a retry without a key, for the same patient and the same tests as an earlier order also placed without a key, returns that order. A keyed order retried without its key is placed again. See *Lab ordering* |

Omitting the header on either appointment write is rejected **before any body or id validation** —
a `PATCH` at an id that does not exist still answers the key, not a `404`:

```bash curl theme={null}
curl -X PATCH https://api-staging.openloophealth.com/v0.1/appointments/<appointment id> \
  -H "authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{ "cancel": { "reason": "Zz synthetic reason" } }'
```

```json 400 — the same call with the header omitted theme={null}
{ "error": { "message": "The Idempotency-Key request header is required on write endpoints. Generate a UUIDv4 per logical booking attempt and resubmit.",
             "error_code": "missing-idempotency-key" },
  "request_id": "..." }
```

> [!TIP]
>
> Locked by check `idempotency-key-required-on-appointment-writes`.

### The key is not the same shape everywhere

The reference asks for a different kind of value per family, and the difference matters:

* **Appointments** — a fresh UUID **per action**. The key is global to your integration, not scoped
  to an endpoint or an appointment, so a key already spent on a booking will replay that booking if
  you send it on a later cancel or reschedule. Failures are stored too: change the request or search
  for a new slot, and you need a new key.
* **`POST /v0.1/subscriptions`** — a **deterministic, order-scoped** value such as
  `initial-subscription:{provider_customer_id}:{order_id}`, so that re-sending *the same attempt*
  de-duplicates: a client that mints a fresh random value on retry creates a second subscription.
  **But the key is per attempt, not per order.** Reusing it after the attempt has reached a terminal
  outcome replays the stored response instead of doing the work again — a retry after a `400`
  decline returns that same `400`, even when the patient has supplied a replacement card, and an
  `items` array changed under an unchanged key is rejected as an idempotency conflict rather than
  retried. Mint a new key for a genuinely new purchase attempt. The replay window (roughly 24 hours)
  also outlives the subscription's own `incomplete_expired` deadline (roughly 20 hours), so a key
  can still be replaying a decline long after the attempt it belongs to has expired. *Payment
  failure* documents that `400` (a declined off-session charge on `POST /v0.1/subscriptions`) and
  what it leaves behind.
* **`POST /v0.1/checkouts/sessions`** — an opaque random value such as a UUID.

A replayed response comes back with `x-idempotency-replayed: true` and the original body, and the
stored response lives for roughly 24 hours.

> [!NOTE]
>
> The header semantics above — the replay window, `x-idempotency-replayed`, the per-family key advice,
> and the replay of a stored `400` decline — are the published reference's own description of these
> parameters, read 2026-09-11. The checks on this page exercise the **absence** of a key, which is
> what the harness can send; they do not measure replay behaviour.

## Recipe · De-duplicate a patient before you create one

There is no upsert and no key on `POST /v0.1/patients`, so the read is the de-duplication step:

```bash curl theme={null}
curl "https://api-staging.openloophealth.com/v0.1/patients?email=jordan.avery@example.com" \
  -H "authorization: Bearer $TOKEN"
```

```json Response — already created theme={null}
{ "items": [ { "id": "<patient id>", "email": "jordan.avery@example.com", "active": true } ],
  "request_id": "..." }
```

```json Response — not created yet theme={null}
{ "items": [], "request_id": "..." }
```

```json 400 — a raw + in the query string theme={null}
{ "error": { "message": "email: Invalid email", "error_code": "VALIDATION_ERROR" },
  "request_id": "..." }
```

A non-empty `items` array means you already created this patient — take `items[0].id` rather than
posting again.

**Percent-encode the address.** A raw `+` in the query string arrives as a space and the filter
rejects it:

| Query | Result |
| - | - |
| `?email=jordan.avery+test@example.com` | `400` — `email: Invalid email` (`VALIDATION_ERROR`) |
| `?email=jordan.avery%2Btest@example.com` | `200` with the matching `items` |

> [!TIP]
>
> Locked by check `dedup-by-email-before-create`.

## Recipe · What a repeated create actually does

Sending the same `POST /v0.1/patients` twice returns `201` twice, with **two different ids**. The
email filter then returns both records. Nothing rejects the duplicate — de-duplication is yours.

```bash curl theme={null}
# sent twice, byte for byte
curl -X POST https://api-staging.openloophealth.com/v0.1/patients \
  -H "authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' \
  -d '{ "first_name": "Jordan", "last_name": "Avery",
        "email": "jordan.avery@example.com", "phone": "+13125550199",
        "birth_date": "1990-01-01", "gender": "male" }'
```

```json Response — both attempts theme={null}
{ "data": { "id": "<a different id each time>" }, "request_id": "..." }
```

```json Then the email read returns both theme={null}
{ "items": [ { "id": "<first id>" }, { "id": "<second id>" } ], "request_id": "..." }
```

So write your own mapping from your identifier to the platform `id` **before** you send the create,
and reconcile it against the email read when a request times out. **There is no partner delete
to undo the duplicate**. Keep using the id you mapped, and ask your OLH implementation contact to remove the
other — say whether intake was submitted against it, because a completed submit has already created
an encounter. See *User migration*. The same holds for a duplicated `/questionnaire-responses`
create: correct an in-progress response with `PUT /v0.1/questionnaire-responses/{id}` (published)
rather than posting again, and ask OpenLoop to remove a duplicate.

> [!TIP]
>
> Locked by check `repeat-create-makes-a-second-patient`.

## Recipe · Read after a write

**The read after a write can be stale.** Immediately after a patient write answered `200`,
`GET /v0.1/patients/{id}` was observed still returning the previous state, and the new state a
moment later (verified on staging 2026-09-11; the write observed was a patient delete, which is no
longer partner-callable, and the lag has not been re-measured on `PUT`). Read-back is eventually
consistent, so a read that still shows the old state is not proof your write was lost. Wait and
read again before you re-send anything.

## Recipe · Why a repeated subscription update adds a line item

`PUT /v0.1/subscriptions/{provider_subscription_id}` takes no `Idempotency-Key`, and its `items`
array is addressed by id:

| Entry | Meaning |
| - | - |
| `provider_item_id` | Update the existing subscription item |
| `provider_item_id` + `deleted: true` | Remove that item |
| `provider_price_id` only | **Add a new item** |

An upgrade written as `items: [{ provider_price_id: "price_…" }]` therefore adds a line **every time
it is sent**. Retry it after a timeout and the subscriber ends up paying for two of the same thing.

After a timeout on a plan change:

1. `GET /v0.1/subscriptions/{provider_subscription_id}` and compare `items` against what you meant
   to send.
2. If the change did land, stop — the response to a `PUT` is the subscription, not the payment
   result, so also read `status` and `/invoices?status=open` per *Upsell and cross-sell*.
3. If you must re-send, address the existing item by `provider_item_id` rather than adding a price.

> [!NOTE]
>
> The `items` semantics above are the published request schema for this route, read 2026-09-11, not
> something the checks on this page measured — exercising it needs a paid subscription in your tenant.

## What comes back

| Field | Meaning | You key on it for |
| - | - | - |
| `data.id` on a create | A **new** id on every attempt — there is no upsert and no key on `POST /v0.1/patients` | Storing your own mapping *before* you send, so a timeout is reconcilable |
| `items[]` on `?email=` | The de-duplication read. Empty means not created; two entries mean you already retried | Reconciling after a timeout. Percent-encode a `+` in the address |
| `error.error_code` | `missing-idempotency-key` on an appointment write with no key | Branching: add the header and resend with a fresh key |
| `x-idempotency-replayed` (response header) | Published reference, read 2026-09-11: set when the platform replayed a stored response rather than doing the work again. Not exercised by the checks on this page. The billing endpoints don't set it, so a replayed `400` decline on `POST /v0.1/subscriptions` looks the same as a fresh one | Telling a replay from a fresh attempt, on the endpoints that set it |
| `request_id` | Present on every response, success or failure | Escalation. Log it on the **first** attempt as well as the retry |

## Gotchas

> [!WARNING]
>
> **A replayed key is not a second attempt.** Retrying `POST /v0.1/subscriptions` under the key from a
> declined attempt returns the stored `400`, so a replacement card looks as though it failed too, and
> an edited `items` array comes back as an idempotency conflict. Scope the key to the attempt, not to
> the order: a new card or a changed basket is a new key. See *Payment failure* for what to read and
> what to tell the patient. (Published reference, read 2026-09-11 — not measured here.)

> [!WARNING]
>
> **A read immediately after a write can still show the old state.** Do not treat a stale read as
> evidence that your write was lost and re-send it — for a create, that is how you get two patients.
> Read again after a pause, and reconcile on `?email=` rather than on a single read — that filter is
> itself a collection read and can trail a create by a moment.

> [!NOTE]
>
> **The clinical writes take no idempotency key at all.** `POST /v0.1/patients`,
> `/questionnaire-responses` and `/reservations` declare no such header in the published reference,
> so the platform has nothing to de-duplicate on. Guard these client-side.

> [!WARNING]
>
> **An appointment key is global to your integration.** Reusing a key that was already spent on a
> booking will replay that booking when you send it on a later cancel or reschedule. Mint a fresh UUID
> per action; never derive one from the appointment id.

> [!NOTE]
>
> Every response carries `request_id`, success or failure. Log it on the first attempt as well as the
> retry — it is what an escalation is keyed on. See *Errors* for the envelope.

## Related

> [card] [Integration flow](https://openloop.mintlify.site/cookbook/integration-flow.md)
>
> The happy path these retries interrupt: create the patient, submit intake, pay

> [card] [Appointments and scheduling](https://openloop.mintlify.site/cookbook/appointments-and-scheduling.md)
>
> The two writes that require an `Idempotency-Key` before they will run at all

> [card] [Upsell and cross-sell](https://openloop.mintlify.site/cookbook/upsell-and-cross-sell.md)
>
> The subscription update whose retry adds a line item

> [card] [Payment failure](https://openloop.mintlify.site/cookbook/payment-failure.md)
>
> What a `400` decline on `POST /v0.1/subscriptions` leaves behind, and why retrying it under the old key replays it

> [card] [Errors](https://openloop.mintlify.site/cookbook/errors.md)
>
> The error envelope, `request_id`, and what each status means


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.