# How to make PUT and DELETE safe to retry without a key

> Make a retried PUT or DELETE harmless with If-Match and no Idempotency-Key: 428 for a missing condition, 412 for a stale write, 2xx for one already applied.

Source: https://voxgig.com/howto/retry-put-and-delete-safely-without-a-key

- Audience: api-producer
- Level: intermediate
- Languages: typescript, go
- Verified: 2026-11-19
- Published: 2026-11-19

## Short answer

Require `If-Match` on every PUT and DELETE, and answer a retry of a write you already applied with success instead of 412. Return 428 when the header is missing, 412 when the `ETag` is stale and the body would change the stored state, and 204 for a DELETE of a resource you deleted. A client generated by sdkgen, Kiota, or Swagger Codegen can then repeat either method without an `Idempotency-Key`.

---
## You will need

Node 22 or later, and an API whose resources return an `ETag`. The API here is `api.json`, a Tariffs
API with a GET, a PUT, and a DELETE on `/tariffs/{tariffId}`. It declares `If-Match` as a required
[header parameter](https://swagger.io/docs/specification/v3_0/describing-parameters/#header-parameters)
on both writes, which is what the three generators read. sdkgen's packages declare Node 24, and
they installed on Node 22 with `EBADENGINE` warnings. Regenerating the clients takes `generate.sh`
and Java, and that script switches off the Kiota CLI's telemetry with
`KIOTA_CLI_TELEMETRY_OPTOUT=true`.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Idempotency-Key on every unsafe method](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/) | One rule for every write, POST included, and clients that never read first | A key store with a retention window, and no view of a concurrent change | A lost update is worse for you than a duplicate |
| [If-Match with an `ETag`](https://www.rfc-editor.org/rfc/rfc9110.html#section-13.1.1) | PUT and DELETE on a resource the client has read | Every client reads before it writes, and the server remembers what it deleted | The write is a POST, which has no representation to match |
| [Kiota request headers and retry handler](https://learn.microsoft.com/en-us/openapi/kiota/query-parameters-request-headers) | Kiota clients, whose default middleware already repeats a 503 on PUT and DELETE | `If-Match` is an untyped header, so no compiler asks for it | You want the required header enforced where the call is written |
| [sdkgen header arguments and retry feature](https://github.com/voxgig/apidef/blob/main/docs/reference/model.md) | One SDK for each language from one model, with retry a feature you switch on | The `ETag` arrives only in a hook, and the generated types omit `if_match` | Callers must hold the `ETag` without writing a feature |
| [Swagger Codegen header parameters](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/about/) | You want `ifMatch` as a required, typed argument on every write | No retry at all, and in `typescript-fetch` no `ETag` except through your own `fetch` | You need the client to retry for you |
| [Version column checked in the update](https://www.postgresql.org/docs/current/sql-update.html) | The validator has to travel in the JSON body, through clients that drop headers | A version field in every representation, and a status convention of your own | Caches and proxies should understand the precondition |

Voxgig maintains sdkgen. It is one of six options here, not the recommendation.

The first two rows are the choice an API owner makes. A key turns two copies of one request into
one write, but it accepts a write based on a stale read. `If-Match` refuses the stale write, and
the price is that every client reads first. The three generators differ in who has to remember
the `ETag`. Swagger Codegen makes it an argument, Kiota a header you add, and sdkgen a hook.

## Answer a repeated write with success and a stale one with 412

`tariffs.mjs` holds the whole decision as one function over a store, so it moves to any framework.

```js title="tariffs.mjs"
export function write(store, { method, id, condition, body }, { appliedIsSuccess = true, rememberDeletes = true } = {}) {
  // RFC 6585 section 3: this API requires every write to be conditional.
  if (condition === undefined) return { status: 428 }

  const row = store.tariffs.get(id) ?? null

  if (method === 'DELETE') {
    // An earlier request applied this delete, perhaps the caller's own first attempt.
    if (!row && rememberDeletes && store.deleted.has(id)) return { status: 204 }
    if (!row) return { status: 404 }
    if (!ifMatch(condition, etagOf(row))) return { status: 412, etag: etagOf(row) }
    store.tariffs.delete(id)
    store.deleted.add(id)
    return { status: 204 }
  }

  const wanted = tariffFrom(body)
  if (!wanted) return { status: 400 }
  if (!row) return { status: 404 }

  if (!ifMatch(condition, etagOf(row))) {
    // RFC 9110 section 13.1.1: a change that appears to have been applied already may answer 2xx.
    if (appliedIsSuccess && same(row, wanted)) return { status: 200, etag: etagOf(row), row }
    return { status: 412, etag: etagOf(row) }
  }

  Object.assign(row, wanted, { version: row.version + 1 })
  return { status: 200, etag: etagOf(row), row }
}
```

Two branches make a retry safe. A PUT with a stale `ETag` and a body that is already the stored
state gets 200 with the current `ETag`.
[RFC 9110 allows that](https://www.rfc-editor.org/rfc/rfc9110.html#section-13.1.1) for a change
that appears to have been applied already. A DELETE of a tariff this server deleted gets 204, from
a set of deleted ids that a database would keep as a `deleted_at` column. The rest is the plain
rule: [428](https://www.rfc-editor.org/rfc/rfc6585.html#section-3) with no `If-Match`, and 412
when it is stale.[^2] The comparison is the strong one, so a weak tag such as `W/"v1"` never
matches.

## Carry the validator through the generated SDK

`generate.sh` scaffolds an sdkgen project from `api.json` with two features and generates the
TypeScript SDK.

```bash title="generate.sh"
npx --yes @voxgig/create-sdkgen@0.31.9 tariffs --def api.json --target ts --feature retry --feature idempotency
cd tariffs-sdk/.sdk
npm run generate
```

The model step reads `If-Match` as a header argument named `if_match` on `update` and `remove`,
and the SDK sends it. Two things are missing in the version run here. The generated TypeScript
types leave `if_match` out, so `tsc` refuses the call with `TS2353`. An operation also returns
the record and not the response headers, so the `ETag` has to be caught in a hook. A small feature
does both jobs, as a class that extends the SDK's own
[`BaseFeature`](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md).

```js title="conditional.mjs"
  // Before the request is sent. An if_match the caller passed is left alone.
  PreRequest(ctx) {
    if (ctx.op.name !== 'update' && ctx.op.name !== 'remove') return
    const etag = this.etags.get(this.key(ctx))
    if (etag !== undefined && ctx.spec.headers['if-match'] === undefined) ctx.spec.headers['if-match'] = etag
  }

  // After a response that carried a validator: the newest one replaces what was kept.
  PreDone(ctx) {
    const key = this.key(ctx)
    const etag = ctx.result?.headers?.etag
    if (key === null || !ctx.result?.ok || typeof etag !== 'string') return
    this.etags.delete(key)
    this.etags.set(key, etag)
    // A Map keeps insertion order, so the first key is the one touched longest ago.
    if (this.etags.size > this.max) this.etags.delete(this.etags.keys().next().value)
  }
```

`retry.mjs` builds each client with `feature: { retry: { active: true } }` and
`extend: [new ConditionalWrites()]`, then loses two responses on purpose.

```bash
node retry.mjs
```

```text output
  call                           writes the server saw      result, then what is stored
  update, response lost once     PUT "v1", PUT "v1"         resolved, "v2" 150
  update from a stale read       PUT "v1"                   412, "v2" 95
  update with no read            PUT no If-Match            428, "v2" 95
  remove, response lost once     DELETE "v2", DELETE "v2"   resolved, gone
  remove again                   DELETE "v2"                resolved, gone
```

The first row is the failure this page opened with. The server stored the price and dropped the
connection, the retry feature sent the same request with the same `If-Match`, and the client got
200 with one stored state. The second row lost a race to another client and was refused, as an
error whose `status` is 412. The third never read the tariff, so it had no `ETag` to send. The last
two rows sent three DELETEs and reported no failure.

## Keep the key for POST

sdkgen's idempotency feature is the first table row in running form. Its defaults put a key on
every PUT and DELETE as well as every POST, and its `methods` and `ops` options narrow that.

```bash
node keys.mjs
```

```text output
idempotency: { active: true }
  PUT    If-Match "v1"   Idempotency-Key of 24 characters
  DELETE If-Match "v2"   Idempotency-Key of 24 characters
idempotency: { active: true, methods: ['POST'], ops: ['create'] }
  PUT    If-Match "v1"   no Idempotency-Key
  DELETE If-Match "v2"   no Idempotency-Key
```

A key beside `If-Match` does no harm. It is a second record for the server to store and expire,
for a request the validator already covers.

## Send If-Match from a Kiota client

Kiota's documentation says it generates no type for request headers, and the run agrees: the
generated `put` and `delete` take a request configuration, and nothing in the output is named
after `If-Match`. The header goes in `headers`, and the `ETag` comes back through an inspection
option.

```js title="kiota.mjs"
export async function read(client, id) {
  const inspect = new HeadersInspectionOptions({ inspectResponseHeaders: true })
  const tariff = await client.tariffs.byTariffId(id).get({ options: [inspect] })
  return { tariff, etag: inspect.getResponseHeaders().tryGetValue('etag')?.[0] }
}
```

```bash
node kiota.mjs
```

```text output
  call                           writes the server saw                result, then what is stored
  put with no headers            PUT no If-Match                      428, "v1" 120
  put, one 503 first             PUT "v1", PUT "v1" Retry-Attempt 1   resolved, "v2" 150
  put, response lost             PUT "v2"                             TypeError, "v3" 160
  the same put again             PUT "v2"                             resolved, "v3" 160
  delete, sent twice             DELETE "v3", DELETE "v3"             resolved, gone
```

The default [retry handler](https://learn.microsoft.com/en-us/openapi/kiota/middleware) repeated
the PUT after a 503 and marked the repeat with a `Retry-Attempt` header.[^3] It acts on a status
code and not on a dropped connection, so the lost response surfaced as a `TypeError` and the
caller sent the PUT again. `kiota info` reports the TypeScript target as Preview and the Go target
as Stable, and the Go output carries the same `Headers` and `Options` fields.

## Pass the validator as a required argument in Swagger Codegen

Swagger Codegen turns the required header parameter into a required argument, checked before any
request is built.

```js title="swagger/api.js"
            // verify required parameter 'ifMatch' is not null or undefined
            if (ifMatch === null || ifMatch === undefined) {
                throw new RequiredError('ifMatch', 'Required parameter ifMatch was null or undefined when calling replaceTariff.');
            }
```

```bash
node swagger.mjs
```

```text output
  call                           writes the server saw      result, then what is stored
  replaceTariff(body, id)        none                       RequiredError, "v1" 120
  with the ETag, one 503 first   PUT "v1"                   503, "v1" 120
  the same call again            PUT "v1"                   resolved, "v2" 150
  next change, response lost     PUT "v2"                   TypeError, "v3" 160
  the same call again            PUT "v2"                   resolved, "v3" 160
  deleteTariff, sent twice       DELETE "v3", DELETE "v3"   resolved, gone
```

The first row sent nothing, which neither of the other two clients can claim. Nothing is retried
either: a 503 is thrown as the `Response`, and the repeat is your loop. The `typescript-fetch`
client returns the body of a GET without its headers, so `swagger.mjs` reads the `ETag` in the
`fetch` it hands to the constructor. The `go` output returns the `*http.Response` beside the
model.

## Check it worked

The test that matters most sends one PUT twice with the `ETag` it was based on.

```js title="conditional.test.mjs"
test('the same PUT again, with the ETag it was based on, is a success and not a second write', () => {
  const store = createStore()
  put(store, '"v1"')
  const again = put(store, '"v1"')
  assert.equal(again.status, 200)
  assert.equal(again.etag, '"v2"', 'the validator of the stored state, so the client can go on from it')
  assert.equal(store.tariffs.get('trf_day').version, 2, 'not applied twice')
})
```

```bash
node --test conditional.test.mjs
```

```text output
1..21
# tests 21
# suites 0
# pass 21
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

`# pass 21` covers the function, the HTTP server, and all three clients. The stored version is
`2` after two identical PUTs.

## When it goes wrong

The client reports a failed update for a price that is stored. The server answers every stale
`If-Match` with 412, its own applied write included. `pitfall.mjs` runs the SDK against that
server and against one with both branches switched off.

```bash
node pitfall.mjs
```

```text output
  response lost once, retried    the server above       a strict server
  update                         resolved, "v2" 150     412, "v2" 150
  remove                         resolved, gone         404, gone
```

Both strict answers are correct for a first attempt and wrong for a repeat. Add the two branches.

A client sends `If-Match: *` and overwrites a change it never read. That value satisfies the 428
rule, and RFC 9110 makes it true for any current representation, so `write` applies the change.
Answer 428 to `*` as well if every write must follow a read.

Every write answers 412 behind a proxy that rewrites the `ETag` as it compresses. nginx has
[changed strong entity tags to weak ones](https://nginx.org/en/CHANGES-1.8) on responses it
modifies since 1.7.3, and a weak tag never matches `If-Match`. Compress in the service itself, or
leave the API's responses alone.

## When not to do this

Do not answer 2xx to a repeated write on a resource that clients use as a counter or a lock. RFC
9110 makes the exception itself: similar changes from clients that are not cooperating would each
be told they succeeded. Answer 412 every time there.

Do not use `If-Match` for POST. A POST creates something that has no `ETag`, which is what a key is
for, and sdkgen's idempotency feature narrowed to POST supplies it.

Do not reach for sdkgen when callers must hold the `ETag` themselves. Its operations return records
and its types omit the header argument. Swagger Codegen's `go` client hands back the response and
takes `ifMatch` as an argument. Kiota repeats a 503 on PUT and DELETE with no feature to add.

Do not keep the deleted ids forever. They are a store too, smaller than a key store, and they
need the same expiry: longer than the longest retry any client makes.

## Related how-tos

- [Make queue consumer writes safe under redelivery](/howto/queue-consumer-writes-under-at-least-once)

- [Retry fetch calls with exponential backoff in Node.js](/howto/retry-fetch-with-backoff-in-node)

- [Generate your first SDK with sdkgen](/howto/first-sdk-with-sdkgen)

- [Add an Idempotency-Key header to every POST from a client](/howto/add-idempotency-key-to-every-post-request)

## Last verified

Verified 2026-11-19 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen` 4.44.3,
Kiota 1.38.0 with its 1.0.0-preview.114 TypeScript packages, and Swagger Codegen 3.0.85 on Java
21. Every output block is what the command preceding it printed. All three generators ran on
`api.json`, and their TypeScript output is committed as compiled JavaScript. The Go output of
Kiota and Swagger Codegen was generated and read, not run. nginx was not run.

[^1]: RFC 9110 calls both methods idempotent and is careful about what that buys. Repeating the
request has the same intended effect, [section 9.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2)
says, and then adds five words: though the response might differ. The whole of this page lives in
that clause.

[^2]: [RFC 6585](https://www.rfc-editor.org/rfc/rfc6585.html#section-3) defined 428 in April 2012
and asks that the response explain how to resubmit. Its own example does so in an HTML page whose
one paragraph tells the reader that the request is required to be conditional, and to try using
If-Match. The stand-in here says the same in a problem document's `detail`.

[^3]: The [IANA registry of HTTP field names](https://www.iana.org/assignments/http-fields) lists
`If-Match` and `Retry-After` as permanent, both by way of RFC 9110. It has no entry for
`Retry-Attempt`, which Kiota's handler sends, or for `Idempotency-Key`. So `If-Match`, the header
this page relies on, is the only one of those three with an entry.