Logo vun Backend Idempotency

Backend Idempotency

Communautéit
j4flmao
backend-idempotency

Use this skill when the user says 'idempotency', 'idempotent', 'idempotency key', 'exactly-once', 'retry safety', 'deduplication', 'duplicate detection', 'idempotent endpoint', 'safe retry'. This skill implements idempotency keys and exactly-once semantics so retries never result in duplicate side effects. Applies to any backend stack. Do NOT use for: read-only endpoints (they are naturally idempotent), optimistic concurrency, or database-level unique constraints alone.

Iwwersiicht

Editeurj4flmao
Repositoryagent-skills
Skill-Nummbackend-idempotency
Stären
41
Forks
6
Matgeliwwert Fichieren
8
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 8 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    Vum j4flmao op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Backend Idempotency an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/idempotency
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/universal/idempotency .claude/skills/backend-idempotency
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Backend Idempotency an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Backend Idempotency automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Backend Idempotency net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Backend Idempotency

Purpose

Guarantee exactly-once execution for mutating operations using idempotency keys, enabling safe retries without duplicate side effects. Idempotency is the foundation of reliable distributed systems — without it, network retries cause duplicate orders, double charges, and inconsistent state.

Agent Protocol

Trigger

Exact user phrases: "idempotency", "idempotent", "idempotency key", "exactly-once", "retry safety", "deduplication", "duplicate detection", "idempotent endpoint", "safe retry".

Input Context

  • Which endpoints need idempotency guarantees.
  • Existing data store (Redis, PostgreSQL, DynamoDB).
  • Current retry configuration.

Output Artifact

Idempotency key handling design. No file unless requested.

Response Format

Endpoint: {method} {path}
Key Source: {client-provided|server-generated}
Storage: {store type}
TTL: {duration}

Completion Criteria

  • Idempotency key storage implemented with TTL.
  • Key uniqueness enforced at database level.
  • Response caching: same key returns same response.
  • Expired keys handled gracefully.
  • Concurrent requests with same key resolved (first wins or lock).

Max Response Length

4 lines per endpoint. 15 lines for full solution.

Architecture Decision Tree

Which Idempotency Strategy?

Is the operation naturally idempotent? (PUT, DELETE, same result every time)
  ├── Yes → No key needed, just use the resource identifier
  └── No → Is the operation a creation (POST, different result each time)?
            ├── Yes → Client-provided idempotency key required
            │         ├── Does the client always retry on network errors?
            │         │   ├── Yes → Always require key on mutating endpoints
            │         │   └── No → Still require it — clients are unreliable
            │         └── Is the key collision possible?
            │             ├── Yes → Use UUID v4 or v7 for key generation
            │             └── No → Use business key (invoice ID, order number)
            └── No → Server-generated idempotency based on request hash
                      ├── Same request body within TTL → deduplicate
                      └── Different body → new operation

Key Source Decision

Who controls the idempotency key?
  ├── Client-provided (Idempotency-Key header)
  │   ├── PRO: Client controls retries, predictable semantics
  │   ├── CON: Badly-behaved clients can exhaust keys
  │   └── Use when: External API, third-party integrations
  └── Server-generated (request hash or business key)
      ├── PRO: No client cooperation needed
      ├── CON: Same body always returns same result (may not be desired)
      └── Use when: Internal services, idempotent by design

Storage Backend Decision

What are your latency and consistency requirements?
  ├── Redis → Fast (~1ms), TTL-based expiry, atomic operations
  │   ├── PRO: Low latency, built-in TTL
  │   ├── CON: Data loss on node fail (if not persisted)
  │   └── Use when: High-throughput, short TTL (< 24h)
  ├── PostgreSQL → Durable, transactional, complex queries
  │   ├── PRO: ACID compliant, survives crashes
  │   ├── CON: Slower (~5-10ms), requires cleanup job
  │   └── Use when: Financial operations, long TTL (> 24h)
  └── DynamoDB → Serverless, auto-scaling, TTL built-in
      ├── PRO: No ops, pay-per-use
      ├── CON: Eventually consistent by default
      └── Use when: AWS ecosystem, variable throughput

Workflow

Step 1: Client Sends Idempotency Key

Clients include Idempotency-Key header (UUID v4 or v7) on POST/PUT/PATCH requests. The key is a client-generated unique identifier for the operation.

Step 2: Server Checks Storage

javascript
async function handleRequest(req, res) {
  const key = req.headers['idempotency-key'];
  if (!key) return res.status(400).json({ error: 'Idempotency-Key header required' });

  const existing = await idempotencyStore.get(key);
  if (existing) {
    // Return cached response — including error responses
    return res.status(existing.status).json(existing.body);
  }
  // Process the request
  const result = await processPayment(req.body);
  await idempotencyStore.set(key, { status: 200, body: result }, { ttl: 3600 });
  return res.json(result);
}

Step 3: Handle Concurrent Requests

When two requests with the same key arrive simultaneously, only one should succeed. Use database-level locking:

sql
-- PostgreSQL: INSERT ... ON CONFLICT
INSERT INTO idempotency_keys (key, status, body, created_at)
VALUES ($1, 'pending', null, NOW())
ON CONFLICT (key) DO NOTHING
RETURNING *;
-- If no row returned, another request holds the key — return 409 Conflict
typescript
// Redis: SET NX with TTL
const acquired = await redis.set(`idempotency:${key}`, 'pending', {
  NX: true,
  EX: 3600, // TTL in seconds
});
if (!acquired) {
  // Key exists — wait for completion or return 409
  const existing = await redis.get(`idempotency:${key}:result`);
  if (existing) return JSON.parse(existing);
  return res.status(409).json({ error: 'Request already in progress' });
}

Step 4: Process and Update

After processing, update the idempotency row with the result:

sql
UPDATE idempotency_keys SET status = 'completed', body = $2, updated_at = NOW() WHERE key = $1;
typescript
// Store result in Redis
await redis.set(`idempotency:${key}:result`, JSON.stringify(result), { EX: 3600 });

Step 5: Handle idempotency for Error Responses

Critical: error responses must also be cached. If the first attempt returns a 503 and the client retries, the second attempt should return the same 503 — not process the request again:

javascript
async function handleWithIdempotency(req, res) {
  const key = req.headers['idempotency-key'];
  const cached = await store.get(key);
  if (cached) return res.status(cached.status).json(cached.body);

  try {
    const result = await processRequest(req);
    await store.set(key, { status: 200, body: result }, TTL);
    res.json(result);
  } catch (error) {
    // ALSO cache error responses for idempotency
    const errorResponse = { status: 502, body: { error: 'Upstream failed' } };
    await store.set(key, errorResponse, TTL);
    res.status(502).json(errorResponse.body);
  }
}

Step 6: Clean Up Expired Keys

Use a TTL index (Redis) or a background job (PostgreSQL) to delete keys after the TTL window:

sql
-- PostgreSQL: background cleanup
DELETE FROM idempotency_keys WHERE created_at < NOW() - INTERVAL '24 hours';

Implementation Patterns

Express Middleware Pattern

typescript
function idempotencyMiddleware(store: IdempotencyStore, ttl: number = 86400) {
  return async (req: Request, res: Response, next: NextFunction) => {
    if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();

    const key = req.headers['idempotency-key'] as string;
    if (!key) return res.status(400).json({ error: 'Idempotency-Key header required' });

    const existing = await store.get(key);
    if (existing) {
      if (existing.status === 'pending') return res.status(409).json({ error: 'In-flight' });
      return res.status(existing.status).json(existing.body);
    }

    await store.set(key, { status: 'pending' }, ttl);
    const originalJson = res.json.bind(res);
    res.json = function (body: any) {
      store.set(key, { status: res.statusCode, body }, ttl);
      return originalJson(body);
    };
    next();
  };
}

Decorator Pattern (NestJS)

typescript
@Post()
@Idempotent({ ttl: 3600 })
async createOrder(@Body() dto: CreateOrderDto): Promise<Order> {
  return this.orderService.create(dto);
}

// Decorator implementation
function Idempotent(options: { ttl?: number } = {}) {
  return (target: any, key: string, descriptor: PropertyDescriptor) => {
    const original = descriptor.value;
    descriptor.value = async function (...args: any[]) {
      const req = args.find(a => a?.headers?.raw);
      const idempotencyKey = req?.headers['idempotency-key'];
      if (!idempotencyKey) throw new BadRequestException('Idempotency-Key required');
      const store = this.idempotencyStore;
      const existing = await store.get(idempotencyKey);
      if (existing) return existing;
      const result = await original.apply(this, args);
      await store.set(idempotencyKey, result, options.ttl ?? 86400);
      return result;
    };
  };
}

Database-Backed Idempotency

typescript
class PostgresIdempotencyStore {
  constructor(private pool: Pool) {}

  async get(key: string): Promise<IdempotencyRecord | null> {
    const result = await this.pool.query(
      'SELECT * FROM idempotency_keys WHERE key = $1 AND created_at > NOW() - INTERVAL \'24 hours\'',
      [key]
    );
    return result.rows[0] || null;
  }

  async set(key: string, value: IdempotencyValue, ttl: number): Promise<void> {
    await this.pool.query(
      `INSERT INTO idempotency_keys (key, status, response_status, response_body, created_at)
       VALUES ($1, $2, $3, $4, NOW())
       ON CONFLICT (key) DO UPDATE
       SET status = $2, response_status = $3, response_body = $4, updated_at = NOW()`,
      [key, value.status, value.statusCode, JSON.stringify(value.body)]
    );
  }
}

Production Considerations

TTL Strategy

ScenarioRecommended TTLRationale
Payment processing24 hoursEnough for payment confirmation
Order creation7 daysLong enough for any retry window
Email sending1 hourShort window, email is idempotent
File upload24 hoursLarge uploads may retry over hours
Webhook delivery7 daysLongest possible retry window

Storage Comparison

StorageLatencyDurabilityTTLCostBest For
In-memory (Map)<1μsNoneManualFreeSingle-node, dev
Redis~1msConfigurableBuilt-inLow-MedHigh-throughput
PostgreSQL~5msFullManualLowFinancial, durable
DynamoDB~10msFullBuilt-inPer-useServerless, AWS
Memcached~1msNoneBuilt-inLowSimple caching

Race Condition Handling

Concurrent requests with the same key must be handled:

  1. First wins: Use DB unique constraint or Redis SET NX. First request acquires the key, subsequent requests get 409 or wait.
  2. Lock-based: Acquire a distributed lock on the key. First holder processes, others wait.
  3. Optimistic: Use CAS (compare-and-swap) to update the key record.
typescript
// Wait pattern: poll for completion
async function handleConcurrent(key: string, maxWaitMs = 5000): Promise<Response> {
  const pollInterval = 100;
  let waited = 0;
  while (waited < maxWaitMs) {
    const record = await store.get(key);
    if (record && record.status !== 'pending') {
      return { status: record.responseStatus, body: record.responseBody };
    }
    if (!record) break; // No concurrent request, proceed
    await sleep(pollInterval);
    waited += pollInterval;
  }
  return null; // Timeout — proceed with processing
}

Security

Key Entropy

Idempotency keys must be unpredictable. Never use sequential integers or timestamps:

typescript
// GOOD: UUID v4 — random, unpredictable
const key = crypto.randomUUID();

// GOOD: UUID v7 — time-ordered, random
const key = uuidv7();

// BAD: Sequential — attacker can enumerate keys
const key = `${timestamp}-${counter++}`;

Key Validation

Validate idempotency keys on input — never process a malformed key:

typescript
function validateIdempotencyKey(key: string): boolean {
  // UUID format check
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  if (!uuidRegex.test(key)) return false;
  return true;
}

Replay Attack Prevention

Without careful design, idempotency keys can enable replay attacks:

  • Always include a timestamp in the idempotency record
  • Reject keys older than the TTL window (even if they haven't expired)
  • Rate-limit idempotency key submissions per client
  • Log all idempotency key hits for audit

Performance

Key Size and Storage

  • UUID v4: 36 bytes per key
  • Response body: Variable — use compression for large responses
  • Storage grows with request volume: keys_created - keys_expired + keys_in_flight
  • Target: keep idempotency storage under 1GB per service instance

Throughput Impact

StorageReads/sWrites/sP99 Latency
In-memory1M+1M+<100μs
Redis100K100K~1ms
PostgreSQL10K5K~5ms

Cache Eviction

For Redis-based storage, configure eviction policy:

yaml
maxmemory-policy: allkeys-lru  # Evict oldest keys first
maxmemory: 512mb                # Cap idempotency storage

Anti-Patterns

  1. No idempotency on payment endpoints: Most expensive mistake. A single network retry without idempotency creates duplicate charges. Every financial operation must have idempotency.
  2. Expiring keys too early: If the TTL is shorter than the maximum retry window, retries after expiry create duplicates. Set TTL to at least max_retry_duration × 2.
  3. Not caching error responses: If you only cache success responses, a retry after a timeout will re-process and potentially succeed — but if the original actually succeeded, you get a duplicate.
  4. Application-level dedup only: Idempotency must be enforced at the database level with unique constraints, not application-level locking.
  5. Reusing keys across different requests: Each unique operation gets its own idempotency key. Reusing keys across different request bodies causes false deduplication.
  6. Idempotency on GET/HEAD: These are naturally idempotent. Adding idempotency key requirements to read endpoints adds complexity with no benefit.
  7. No monitoring on deduplication rate: A high deduplication rate indicates excessive client retries or network issues. Monitor idempotency key hit rate as a signal.

Design Pattern Comparison

PatternMechanismScopeUse Case
Idempotency KeyClient-provided key, server dedupSingle operationMutating API endpoints
Optimistic LockingVersion field, CASResource updateConcurrent edits
Pessimistic LockingDB row lockResource accessLong-running operations
Unique ConstraintDB unique indexRow creationPreventing duplicate entities
Event IdempotencyEvent ID dedupEvent processingConsumer-side deduplication
State MachineGuard transitionsStateful operationsWorkflow engines

Rules

  • Idempotency keys are required on all mutating endpoints — no exceptions.
  • Keys expire after a fixed window (minimum 24 hours, maximum 7 days).
  • Return the same response for the same key within the TTL window — including error responses.
  • Use database-level uniqueness for the idempotency key column, not application-level locking.
  • Never reuse idempotency keys across different request bodies.
  • Log idempotency key hits for observability.
  • GET, HEAD, OPTIONS are inherently idempotent — no key needed.
  • Validate idempotency key format before processing.
  • Monitor idempotency key hit rate as a signal of client reliability.
  • Always include a timestamp in the idempotency record.

References

  • references/exactly-once-strategies.md — Exactly-Once Execution Strategies
  • references/idempotency-distributed.md — Distributed Idempotency
  • references/idempotency-failure-modes.md — Idempotency Failure Modes
  • references/idempotency-keys.md — Idempotency Keys
  • references/idempotency-middleware.md — Idempotency Middleware Patterns
  • references/idempotency-patterns.md — Idempotency Key Implementation Patterns
  • references/idempotency-storage.md — Idempotency Storage Backends
  • references/idempotency-testing.md — Idempotency Testing

Handoff

No artifact produced unless requested. Next skill: distributed-locking — coordinate access to shared resources across services. Carry forward: idempotency key storage, TTL configuration, endpoint list.

  • Review code for security, performance, and correctness before merging.

Matgeliwwert Fichieren

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Backend Idempotency?

Use this skill when the user says 'idempotency', 'idempotent', 'idempotency key', 'exactly-once', 'retry safety', 'deduplication', 'duplicate detection', 'idempotent endpoint', 'safe retry'. This skill implements idempotency keys and exactly-once semantics so retries never result in duplicate side effects. Applies to any backend stack. Do NOT use for: read-only endpoints (they are naturally idempotent), optimistic concurrency, or database-level unique constraints alone.

Firwat Backend Idempotency op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Backend Idempotency besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Backend Idempotency an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/idempotency an. TypingMind liest d'Datei SKILL.md, bündelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Backend Idempotency benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Backend Idempotency benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Backend Idempotency domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Backend Idempotency gratis?

Jo. De Skill gëtt vum j4flmao ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇