跪拜 Guibai
← All articles
Frontend · Agent

Don't Let Five Clicks Cost Five Token Bills: Idempotency Discipline for RAG Platforms

By 去伪存真 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

In production RAG, retries and impatient users are routine; without server-side idempotency, token bills quintuple and retrieval quality collapses into duplicate-flooded, stuttering answers. These patterns let a platform absorb repeated clicks and network flakiness at zero extra cost and keep the vector store clean.

Summary

Client retries and impatient users are a fact of life in production RAG. A single 50MB upload, re-submitted five times, can quintuple the token bill and flood the vector store with five identical chunks, so Top-K retrieval returns the same passage five times and the LLM stutters. The fix is concentrated on the server: no frontend button-disable can stop network proxies, SDKs, or malicious scripts from retrying.

The architecture works in four layers. The API facade checks an Idempotency-Key against a partial unique index, pairs it with a versioned request fingerprint to reject same-key-different-payload replays, and uses transaction-level advisory locks scoped to person, credential, and key. Below that, content-hash deduplication on the file bytes skips parsing and embedding entirely when the same file arrives again under a new key. Downstream, an in-memory asyncio lock plus a single-transaction DELETE+INSERT snapshot replacement guarantees only one clean chunk set per document. Finally, cancellation itself is idempotent: cancel markers and leases persist so a restarted container can resume cleanup until the system converges.

Takeaways
— Use partial unique indexes with `WHERE idempotency_key IS NOT NULL` and normalize empty keys to NULL, otherwise a second client without a key hits a 500.
— Pair an Idempotency-Key with a versioned request fingerprint; same key with different payload must return 409 Conflict.
— Use `pg_advisory_xact_lock` scoped to person+credential+key to serialize retries without blocking other users and eliminate TOCTOU races.
— Content-hash deduplication at the facade skips parsing and embedding when the same file bytes are re-uploaded, even with a different key.
— Never reuse the content hash of a previously failed document; force a new document ID or background garbage collection can delete the new file.
— In downstream chunking, use a single-transaction DELETE+INSERT snapshot replacement instead of row-level diff upserts to avoid incomplete deletions.
— Persist cancellation status and distributed leases so a recovering container can idempotently resend Cancel and clean orphan chunks after a crash.
— For staged uploads, commit should look up an accepted immutable receipt before the upload session's TTL, so large byte streams are never wasted.
Conclusions

Frontend button disabling is ineffective because proxies, SDKs, and malicious scripts all retry independently; the server must own idempotency end to end.

Binding idempotency to credential identity prevents privilege escalation when a high-privilege token is revoked and a lower-privilege token retries with the same key.

Content-hash dedup must respect lifecycle state: reusing a hash from a failed parse can cause the new, valid file to be garbage-collected.

Single-transaction snapshot replacement is simpler and more reliable than diff-based row updates when chunk boundaries shift.

Idempotent cancellation requires persisting intent and leases so recovery coroutines can converge the system to a clean state after crashes.

Concepts & terms
Idempotency-Key
A client-supplied unique identifier that tells the server to treat multiple requests with the same key as one logical operation, so retries don't cause duplicate work.
Versioned request fingerprint
A hash of the full request payload (including file names, content hashes, and metadata) plus a version number; used with an idempotency key to reject same-key requests with different content.
Partial unique index
A PostgreSQL index that only enforces uniqueness on rows satisfying a WHERE clause, letting NULL or missing keys bypass the constraint.
Advisory lock
A database-level lock that can be scoped to arbitrary keys; `pg_advisory_xact_lock` releases automatically at transaction end, allowing narrow serialization without blocking unrelated traffic.
Content-hash deduplication
Comparing a new upload's SHA-256 against previously stored hashes to reuse existing processing results and skip downstream compute.
TOCTOU race
Time-of-check to time-of-use; a condition where a token or resource is validated but changes before it is actually used, exploitable in retry scenarios.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗