Idempotency guarantees at-most-once execution for side-effectful operations such as payment charges, order creation, webhook processing, and outbound API calls. Each operation is keyed by a client-supplied idempotency key.
Idempotency composes KeyValueStore and DistributedLock:
- If a completed outcome already exists for
key,Idempotencyreturns{ value, replayed: true }without running your function again. - If another request with the same
keyis in flight,Idempotencyfails withIdempotencyInProgressError(409, retryable). - If your handler succeeds,
Idempotencystores the typed result forttland returns{ value, replayed: false }. - If your handler fails,
Idempotencydoes not cache the failure as success. It releases the lock so the client can retry.
Declaring an Idempotency scope
Plain TypeScript SDK (@chimp-labs/keel/sdk)
import { k } from "@chimp-labs/keel/sdk"
export const ChargeIdempotency = k.idempotency(
"payments.charge",
k.object({
chargeId: k.string(),
amountCents: k.int(),
}),
{
ttl: "24 hours",
lockTtl: "30 seconds",
}
)
Configuration options
| Option | Type | Default | Description |
|---|---|---|---|
result |
SchemaLike |
Required | Schema that validates the cached success payload. |
ttl |
Duration.Input |
"24 hours" |
Duration that completed results remain stored for replay. |
lockTtl |
Duration.Input |
"30 seconds" |
In-flight lock duration that blocks concurrent duplicate execution. |
Effect v4 (@chimp-labs/keel/idempotency)
import { Schema } from "effect"
import { Idempotency } from "@chimp-labs/keel/idempotency"
const ReceiptSchema = Schema.Struct({
chargeId: Schema.String,
amountCents: Schema.Int,
})
export class ChargeIdem extends Idempotency("payments.charge", {
result: ReceiptSchema,
ttl: "24 hours",
}) {}
Attaching to a Service
export const BillingService = k.service("billing", {
resources: [InvoicesTable, ChargeIdempotency],
operations: { /* ... */ },
})
Operations reference
Executing idempotently
const outcome = await keel.chargeIdem.run(req.headers["idempotency-key"], async () => {
const charge = await stripe.charge({ orderId, amountCents })
return { chargeId: charge.id, amountCents }
})
// outcome: { value: { chargeId: string; amountCents: number }, replayed: boolean }
if (outcome.replayed) {
console.log("Replayed cached receipt:", outcome.value.chargeId)
}
SDK and Effect API mapping
SDK method (keel.<idem>.*) |
Effect function (@chimp-labs/keel/idempotency) |
Description |
|---|---|---|
run(key, fn) |
withIdempotency(idem, key, effect) |
Deduplicate execution by key and return { value, replayed }. |
Errors and failure modes
| Error tag | Category | HTTP status | Retryable | When it occurs |
|---|---|---|---|---|
IdempotencyInProgressError |
conflict |
409 |
Yes | Another request with the same key is executing. |
IdempotencyStoreError |
internal |
500 |
Yes | Underlying KV or lock store failure. |
SchemaError |
invalid |
400 |
No | Returned or cached result failed schema validation. |
Backends and infrastructure
Idempotency requires KeyValueStore and DistributedLock. The Memory, PostgreSQL 17 (KeelPostgresLive or backend: "postgres"), SQLite, and SurrealDB 4 bundles provide both. PostgreSQL 17 stores completed outcomes in keel_kv.
Testing in memory
await using keel = await createKeel({
backend: "memory",
resources: { chargeIdem: ChargeIdempotency },
})
let charges = 0
const first = await keel.chargeIdem.run("idem-1", async () => {
charges++
return { chargeId: "ch_1", amountCents: 4500 }
})
const second = await keel.chargeIdem.run("idem-1", async () => {
charges++
return { chargeId: "ch_2", amountCents: 4500 }
})
// charges === 1
// first === { value: { chargeId: "ch_1", amountCents: 4500 }, replayed: false }
// second === { value: { chargeId: "ch_1", amountCents: 4500 }, replayed: true }