How to Re-index RAG Documents Atomically in ASP.NET Core 10 Using C#, PostgreSQL and pgvector (2026)
A retrieval API can return a mixture of old and new policy text if a re-index job updates searchable chunks in place. Deleting first creates a different problem. Searches can return nothing while embeddings are being generated. Both problems can be avoided by publishing a complete document revision atomically.
This tutorial builds an ASP.NET Core 10 revision API backed by PostgreSQL and pgvector. It uses deterministic vectors so you can reproduce the concurrency and rollback behavior without sending documents to a model provider. The existing ASP.NET PB RAG chatbot guide covers provider-backed ingestion and answer generation.
How do you replace a document without interrupting retrieval?
Keep each revision’s chunks under a unique version ID. Store the active revision on the document row. Insert the replacement and update the active pointer in the same PostgreSQL transaction. The search reads both tables in a single statement, so its snapshot sees only committed data. A transaction that fails leaves the old revision active.
| Strategy | Reader behavior | Tradeoff |
|---|---|---|
| Delete then rebuild | Temporary gaps | Simple but disruptive |
| Update chunks in place across several transactions | Possible mixed revisions | Poor reproducibility |
| Immutable revisions with active pointer | A complete committed revision per query | Additional retention and cleanup |
Generate embeddings before opening the write transaction. A slow embedding service should not hold a database connection and row lock. Carry an expected version from the start of the indexing attempt. A compare-and-swap update prevents a slower worker from replacing a newer revision. A version conflict is different from a provider timeout. On conflict, reread metadata and decide whether the old job still applies.
Prepare PostgreSQL and the API
Install .NET 10, PostgreSQL with the pgvector extension, and psql. Use a disposable development database. Run the schema as a role allowed to install the extension. Use a separate least-privilege app role with select, insert and update permissions for the two tables. This loopback lab has no public-facing authentication and uses toy vectors of three dimensions.
The PUT endpoint validates the entire payload before opening a transaction. It inserts a placeholder document if necessary, then changes the pointer only when expectedVersion matches. PostgreSQL serializes competing updates to the same row. If two writers start with the same revision, only one successfully changes that pointer. A failed comparison returns HTTP 409 and disposes the uncommitted transaction. The search query joins on both document ID and active version.
Use parameters for text, UUIDs and embeddings. The demo sends a validated vector string as a parameter and casts it to PostgreSQL’s vector type. Npgsql’s pgvector type mapping is another option. Do not interpolate user input into SQL. See Npgsql basic usage, PostgreSQL transaction isolation, and pgvector.
Reproduce success and a stale writer
Use one fixed ID on a disposable database. The first command succeeds with an empty expected version. Record the returned UUID.
Run the PUT again with the returned UUID as expectedVersion and text Refunds within 30 days. A subsequent search should only return the replacement. Repeat the PUT with the old expected version and confirm HTTP 409. For a rollback check in a disposable database, add a temporary CHECK constraint that rejects a known sentinel text, then submit a revision with that text and the current version. The pointer update and preceding inserts must roll back. Remove the test constraint afterward.
Return revision ID and ordinal as part of your source citation. Store a stable source identifier, title and page or section metadata when chunks come from an actual document. Keep cited revisions long enough for readers to verify the exact source they saw. To handle a lost response after commit, use a separately scoped idempotency record or reread the current revision and reconcile before retrying.
The C# project compiled with .NET SDK 10.0.100. PostgreSQL-backed runtime verification was not performed here.
Scale revision storage and diagnose failures
Exact cosine search is useful as a correctness baseline. If latency requires HNSW, test filtered recall and query plans with realistic active-to-retired ratios. An approximate index with a filter can return fewer candidates. Retiring stale revisions from the hot retrieval table or maintaining a separate history store may improve the plan. Benchmark your data and verify results with an exact search before tuning index settings.
Do retention cleanup with bounded background batches. Exclude active revisions, respect legal and product retention policies, and monitor table bloat. Multiple chunks in a single revision should share the same embedding model and dimensions. For a model migration, store the model identifier, keep incompatible embeddings in separate search paths, and switch readers only after the new index is ready.
| Symptom | Check |
|---|---|
| 409 after slow embedding generation | Another writer committed first |
| Search returns no rows | Document pointer, extension and test database |
| Historical revision appears | Join includes active version and document ID |
| pgvector rejects payload | Dimensions, finite components and invariant formatting |
| Large storage growth | Retention cleanup and duplicate revisions |
FAQ and references
Do readers lock the writer? A normal single-statement search reads an MVCC snapshot. Explicit locks or a different workload can change contention. Test the real plan.
Can I re-embed in the write transaction? Prepare vectors first and keep the transaction for the database changes. The expected version detects concurrent writers.
Is the revision ID an idempotency key? It identifies one saved revision. Use a distinct key to deduplicate client attempts, particularly after a lost response.
- PostgreSQL transactions.
- pgvector filtering and indexes.
- ASP.NET PB transactional outbox guide for durable publication of downstream indexing events.
Publish the revision only when all chunks are ready. Return the revision with each hit so downstream answers can cite a consistent source.
Comments
Post a Comment