Ramiz RajaBook a call
← Writing
Backend

Idempotency in REST API Design: What Happens When You Retry a Booking?

Three places a serverless booking API has to survive a retry: the client POST, a stream consumer, and a workflow step. What each one protects, and what its tests do and do not prove.

Ramiz RajaNovember 24, 20268 min read
Idempotency in REST API Design: What Happens When You Retry a Booking?

Your client sends POST /events/{id}/bookings for two seats and the connection dies at the timeout. The app cannot tell whether the server booked the seats or never saw the request. It retries. Depending on what your handler does, the user now holds two bookings, or one booking and an error, or exactly the booking they asked for.

In a REST API, idempotency means repeating the same request has the same intended effect on the server as making it once. That is about the effect, not the bytes of the response: a retry may get back a replayed copy of the first response, or a different status, as long as no second booking happens. HTTP defines GET, PUT and DELETE as idempotent; POST carries no such guarantee, so a booking POST is safe to retry only if the server makes it so.

Below are three places where that mattered in an undeployed AWS booking showcase (API Gateway, Lambda, DynamoDB, Step Functions; source on GitHub), backed by unit tests, DynamoDB Local integration tests and CDK template assertions.

Place 1: the idempotency key on a booking POST

The client sends an Idempotency-Key header. The rule for a mobile client: generate one key per logical booking. Before the first send, persist the key with the event ID and seat count. After a timeout or app restart, resend those same inputs with the same key. A new booking gets a fresh key. A replacement key bypasses response replay, although the attendee guard (below) can still reject a second active booking.

There is an IETF Internet-Draft for this header (draft-ietf-httpapi-idempotency-key-header), still a work in progress. It recommends a UUID or similar random value, a 422 when a key is reused with a different payload, and a 409 when a retry arrives while the first request is still running. My handler returns those codes. One difference: the draft defines the header value as a Structured Field String, and this API reads the raw header value instead.

I did not write the storage layer. The booking use case is wrapped with the Powertools for AWS Lambda idempotency utility, which keeps a record per key in a DynamoDB table. The config, trimmed:

export const IDEMPOTENCY_TTL_SECONDS = 24 * 60 * 60;

new IdempotencyConfig({
  eventKeyJmesPath: "[userId, idempotencyKey]",
  payloadValidationJmesPath: "[eventId, seats]",
  throwOnNoIdempotencyKey: true,
  expiresAfterSeconds: IDEMPOTENCY_TTL_SECONDS,
});

The record is keyed on the user and the header; eventId and seats are the inputs compared on a retry.

Three retries, three outcomes:

  • Same key, same eventId and seats, first call completed: the stored result comes back. Replay only applies to a completed record that has not expired. An integration test against DynamoDB Local books two seats, calls again with the same key, and asserts the two booking objects are equal, the event has 8 of 10 seats left, and a fake publisher received one event. A separate HTTP unit test asserts both calls return 201 with equal bodies.
  • Same key reused on a completed, unexpired record with changed eventId or seats: 422 IDEMPOTENCY_KEY_REUSED. Powertools raises IdempotencyValidationError and the adapter maps it to a business error.
  • Same key while the first call's in-progress record is still valid: 409 REQUEST_IN_PROGRESS. A unit test holds the first call open, fires the retry, then lets the first finish.

Why the key includes the user

With [userId, idempotencyKey], two users who send the same key string get two records. Without the user, a client that picks a predictable key could be handed another person's booking. A unit test sends the same key from two users and expects two bookings. The header is validated as 8 to 128 visible ASCII characters with no spaces; a missing one is a 400 before the use case runs.

What happens when the call fails

Powertools documents that an exception escaping the wrapped function deletes the in-progress record, so a retry with the same key runs the use case again. For this API that is the point: a booking that fails with SOLD_OUT should be retryable, because a seat may free up later. Caching that failure for 24 hours would keep returning the old no.

A timeout is different: the function never throws, so the in-progress record stays. The handler registers the Lambda context with Powertools, so a retry can run again once that record's in-progress deadline passes. That leaves a sharp edge. Suppose the booking transaction commits and the function times out before Powertools saves the result. The booking is real, but there is no completed record to replay. On retry, the attendee condition (below) blocks a second active booking, but the client may get an error instead of its 201. To recover, the client calls GET /me/bookings and looks for the event in the paginated results.

My tests do not cover this edge, or the plain same-key retry after a failure. The existing failure test changes both the key and the seat count. The test I would add is the same key and payload, retried after availability changes.

Why the idempotency table is separate

The records live in their own table with a TTL attribute, so short-lived records never mix with business data and the booking function's write access stays narrow. DynamoDB typically deletes expired items within a few days, so nothing here depends on a record vanishing on time.

Under all of this, the booking is a conditional DynamoDB transaction: it decrements seatsRemaining only if enough seats remain, and writes an attendee marker only if none exists. The key protects a retry of the same request. The marker prevents a second active booking for the same user and event while it exists; cancelling deletes it.

Place 2: a stream projection that must not count twice

The second place has no client. Organizer stats (confirmed bookings, cancellations, seats booked, waitlist counts) are a projection: a Lambda reads changes from the table's DynamoDB Stream and adds to counters on one STATS item per event.

AWS says each stream record appears once in the stream, while the Lambda event source mapping processes records at least once. The mapping here filters for booking and waitlist items, and configures five retries, batch bisection and partial batch failure reporting. Lambda can retry from the lowest reported failed sequence number, which can repeat later records that already succeeded. A counter that adds on every invocation would double count.

The fix is a marker per stream record, keyed by its eventID, written in the same transaction as the counter update:

await transactWrite(db, [
  { Put: { TableName: dedupeTable,
           Item: { id: `stats#${changeId}`, expiration },
           ConditionExpression: "attribute_not_exists(id)" } },
  { Update: { TableName: table, Key: Keys.stats(eventId),
              UpdateExpression: "SET ... ADD #c0 :c0, ..." } },
], (reasons) => (failedAt(reasons, 0) ? new AlreadyCounted() : undefined));

The counter only moves if this record's marker was not already there, and both writes succeed or fail together.

If the marker exists, the transaction cancels, the adapter returns "duplicate", and the batch carries on. The integration test calls the repository directly: it passes the same stream record ID twice, sees "duplicate" the second time, then applies a distinct cancellation delta; the counters end at one confirmed, one cancelled and zero seats.

Why one transaction? Write the marker first and fail the counter, and that change is never counted. Update the counter first and fail the marker, and a retry counts it twice. That is reasoning, not a crash test.

The marker TTL is two days, which covers the stream's native retention of up to 24 hours. Records sent to the failure destination queue and replayed later by some other process would need their own dedupe; the marker may have expired by then. The markers live in the Place 1 table, and the stats function gets only PutItem on it.

Place 3: which steps of a workflow may retry

When a booking is cancelled, a Step Functions Standard workflow handles each freed seat in sequence: it offers the seat to the next person on the waitlist, waits 15 minutes when it makes an offer, then resolves it: accepted, or expired and offered to the next in line.

OfferSeat takes a seat off the event and marks someone OFFERED. ResolveOffer checks the outcome and, if the offer expired, gives the seat back. Both tasks keep the CDK LambdaInvoke default, retryOnServiceExceptions: true, which retries Lambda service errors only.

A review pass of the repo flagged a risk: if ResolveOffer hit an application error such as throttling on a hot item, the execution would fail and the seat would stay held. I had not seen that happen; it came from reading the code. The fix:

resolveOffer.addRetry({
  errors: ["States.TaskFailed"],
  interval: Duration.seconds(2),
  backoffRate: 2,
  maxAttempts: 8,
});

Only ResolveOffer gets the broad application-error retry.

An integration test against DynamoDB Local resolves the same expired offer twice; both calls return "expired" and the seat count goes up by one, not two. A second run may still emit expiry telemetry again. The focused CDK assertion checks that the definition contains States.TaskFailed, which the Step Functions error handling docs define as any known error except States.Timeout.

The backoff waits add up to about 8.5 minutes (2 + 4 + ... + 256 seconds). That excludes the time each invocation takes and the separate service-exception retrier. If the seat has yet to be returned when the retries are exhausted, it can remain held. OfferSeat keeps only the service-exception default.

What the next review round found

The same pass found that OfferSeat could hand a seat to someone who had meanwhile booked directly. The fix adds a condition check on the attendee marker inside the offer transaction and moves on to the next person; an integration test covers it. The second round caught that the offer function's IAM grant lacked dynamodb:ConditionCheckItem, which that new check needs, and a CDK test now asserts it. For more on fixes that break the code next to them, see a correct fix that quietly broke the feature next to it.

Where this fits

I have not measured how often Lambda times out or streams redeliver. I added these checks because the documentation says those things can happen.

The idempotent wrapper is an adapter around the use case, so BookSeats knows nothing about keys; the same idea runs through keeping agent-written code clean. If you inherited a mobile backend that double-writes when clients retry, that is the kind of defect I look for in an app rescue. For another backend choice shaped by what happens after a client has gone, see SSE vs WebSockets.

An idempotent API checklist

Ask these of every handler a retry can reach:

  1. Who can retry it: a client, a Lambda timeout, a queue, a stream? List them all.
  2. Does the client keep one key per logical operation across timeouts and restarts?
  3. Is the key scoped to the caller, so one user's key cannot replay another's result?
  4. Are the inputs compared, so a reused key with different input is refused with a 422?
  5. Which failures can run again safely, and how does the client recover if the write committed before the result was saved?
  6. What does a retry see while the first call is running? Return a 409, not a second run.
  7. For stream or queue consumers, is the dedupe marker written in the same transaction as the effect, and does it outlive every replay path?
  8. For each workflow step, would running it twice change the result? Retry broadly only where it would not.
  9. Does a test fail if you remove the dedupe, and does one cover the same-key retry?
  10. After every new guard, does the role that runs it still have permission to do it?