CodingNeed.

Production engineering workshop · 55 MIN

Express / NestJS · Design an idempotent write

A retry should reuse the original result without repeating the business effect.

Clients retry after network uncertainty. Bind an idempotency key to the authenticated owner, method, route and canonical payload hash. Insert its reservation and business effect in one transaction; a competing insert waits for the first transaction and then reads its committed result. Reject reuse with a different payload. The service pattern below can be called from an Express handler or NestJS controller after DTO validation and authentication.

First reproduce the normal path. Then force a failure at each boundary and inspect what remains true.

Read the example

type Input={ownerId:string;key:string;amountCents:number};
// db.transaction and tx.* are application repository interfaces.
async function createOrder(input:Input) {
  const hash=sha256(canonicalJson({route:"POST /orders",amountCents:input.amountCents}));
  return db.transaction(async tx => {
    // insertOrRead must serialize on UNIQUE(owner_id,key).
    const record=await tx.idempotency.insertOrRead(input.ownerId,input.key,hash);
    if (record.payloadHash!==hash) throw new Conflict("Key reused for a different request");
    if (record.response!==null) return record.response;
    const order=await tx.orders.create({ownerId:input.ownerId,amountCents:input.amountCents});
    const response={status:201,body:{id:order.id}};
    await tx.idempotency.complete(input.ownerId,input.key,response);
    return response;
  });
}
// Never perform an irreversible external payment inside a retriable DB transaction.
// Persist an outbox event and use the payment provider’s idempotency support.
Check the expected output
Review the behavior in the stated project environment.

Your challenge

Implement the database operations shown below against MySQL or PostgreSQL. Create a UNIQUE(owner_id,key) constraint. Simulate two concurrent equal requests, then the same key with a different amount. Add a response-loss test where the first commit succeeds but the client never receives it.

Solution cost: Indexed key lookup plus one transaction; lock wait depends on contention. time · One retained response per key until the documented retention period. space

Common trap

An in-memory Map loses idempotency records on restart and does not coordinate multiple instances.

Study the project implementation
type Input={ownerId:string;key:string;amountCents:number};
// db.transaction and tx.* are application repository interfaces.
async function createOrder(input:Input) {
  const hash=sha256(canonicalJson({route:"POST /orders",amountCents:input.amountCents}));
  return db.transaction(async tx => {
    // insertOrRead must serialize on UNIQUE(owner_id,key).
    const record=await tx.idempotency.insertOrRead(input.ownerId,input.key,hash);
    if (record.payloadHash!==hash) throw new Conflict("Key reused for a different request");
    if (record.response!==null) return record.response;
    const order=await tx.orders.create({ownerId:input.ownerId,amountCents:input.amountCents});
    const response={status:201,body:{id:order.id}};
    await tx.idempotency.complete(input.ownerId,input.key,response);
    return response;
  });
}
// Never perform an irreversible external payment inside a retriable DB transaction.
// Persist an outbox event and use the payment provider’s idempotency support.

Further reading: Official documentation

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.