Skip to content

Idempotency keys on every agent action

Require an Idempotency-Key on run creation — retries and double-clicks return the same run.

nestjs-realtime-stream-idempotency-keys

Why it matters

Failure modes if this rule is ignored
StakeIf ignored
Double charge
  • Unreliable networks + client retries = duplicate runs of the same prompt = double charges.
  • Double-clicks spawn two runs for the same user intent.

How to fix

The client sends an Idempotency-Key header on every run-creation request. If the request arrives twice (network, retry, double-click) — the server returns the same run, doesn't create a new one.

Examples

Bad
ts
@Post('runs')
async startRun(@Body() dto: StartRunDto, @CurrentUser() user: User) {
  const run = await this.runs.create({ userId: user.id, prompt: dto.prompt });
  return { runId: run.id };
}
Good
ts
@Post('runs')
async startRun(
  @Body() dto: StartRunDto,
  @Headers('idempotency-key') idempotencyKey: string,
  @CurrentUser() user: User,
) {
  if (!idempotencyKey) throw new BadRequestException('Idempotency-Key header required');

  const existing = await this.runs.findByIdempotencyKey(user.id, idempotencyKey);
  if (existing) return { runId: existing.id, deduplicated: true };

  const run = await this.runs.create({ userId: user.id, prompt: dto.prompt, idempotencyKey });
  return { runId: run.id };
}

Contribute

Released under the MIT License.

esc