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?

A transaction stages a new revision and changes the active pointer. Concurrent readers see the old complete revision or the new complete revision.
A transaction stages a new revision and changes the active pointer. Concurrent readers see the old complete revision or the new complete revision.

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.

Apply the schema and start the API
psql "$ADMIN_DATABASE_URL" -v ON_ERROR_STOP=1 -f schema.sql
# Set ConnectionStrings__Db in the API process using an Npgsql connection string.
dotnet run --no-launch-profile -- --urls http://127.0.0.1:5080
schema.sql
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE documents (
    id uuid PRIMARY KEY,
    active_version uuid
);
CREATE TABLE chunks (
    document_id uuid NOT NULL REFERENCES documents(id),
    version_id uuid NOT NULL,
    ordinal integer NOT NULL CHECK (ordinal >= 0),
    content text NOT NULL,
    embedding vector(3) NOT NULL,
    PRIMARY KEY (document_id, version_id, ordinal)
);
Lab.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
  <ItemGroup><PackageReference Include="Npgsql" Version="10.0.3" /></ItemGroup>
</Project>
Program.cs
using Npgsql;
using System.Globalization;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(_ => NpgsqlDataSource.Create(
    builder.Configuration.GetConnectionString("Db") ?? throw new InvalidOperationException("Set ConnectionStrings__Db.")));
var app = builder.Build();

app.MapPut("/documents/{id:guid}", async (Guid id, Revision body, NpgsqlDataSource db, CancellationToken ct) =>
{
    if (body.Chunks is not { Length: >= 1 and <= 32 } ||
        body.Chunks.Any(c => c is null || string.IsNullOrWhiteSpace(c.Text) || c.Text.Length > 2000 ||
            !ValidVector(c.Vector)))
        return Results.BadRequest("Provide 1–32 chunks with text and a nonzero finite vector.");

    var version = Guid.NewGuid();
    await using var conn = await db.OpenConnectionAsync(ct);
    await using var tx = await conn.BeginTransactionAsync(ct);
    await using (var doc = new NpgsqlCommand("""
        INSERT INTO documents(id) VALUES (@id) ON CONFLICT DO NOTHING
        """, conn, tx))
    {
        doc.Parameters.AddWithValue("id", id);
        await doc.ExecuteNonQueryAsync(ct);
    }

    // Compare-and-swap prevents a stale writer from replacing a newer revision.
    await using (var activate = new NpgsqlCommand("""
        UPDATE documents SET active_version = @version
        WHERE id = @id AND active_version IS NOT DISTINCT FROM @expected
        """, conn, tx))
    {
        activate.Parameters.AddWithValue("id", id);
        activate.Parameters.AddWithValue("version", version);
        activate.Parameters.Add("expected", NpgsqlTypes.NpgsqlDbType.Uuid).Value =
            (object?)body.ExpectedVersion ?? DBNull.Value;
        if (await activate.ExecuteNonQueryAsync(ct) != 1)
            return Results.Conflict("Revision changed. Read the current version before retrying.");
    }

    for (int i = 0; i < body.Chunks.Length; i++)
    {
        var c = body.Chunks[i];
        await using var insert = new NpgsqlCommand("""
            INSERT INTO chunks VALUES (@id, @version, @ordinal, @content, CAST(@embedding AS vector))
            """, conn, tx);
        insert.Parameters.AddWithValue("id", id);
        insert.Parameters.AddWithValue("version", version);
        insert.Parameters.AddWithValue("ordinal", i);
        insert.Parameters.AddWithValue("content", c.Text);
        insert.Parameters.AddWithValue("embedding", Vector(c.Vector));
        await insert.ExecuteNonQueryAsync(ct);
    }

    await tx.CommitAsync(ct);
    return Results.Ok(new { version, chunks = body.Chunks.Length });
});

app.MapGet("/documents/{id:guid}", async (Guid id, NpgsqlDataSource db, CancellationToken ct) =>
{
    await using var command = db.CreateCommand("SELECT active_version FROM documents WHERE id = @id");
    command.Parameters.AddWithValue("id", id);
    return await command.ExecuteScalarAsync(ct) is Guid version
        ? Results.Ok(new { version }) : Results.NotFound();
});

app.MapPost("/search", async (Search query, NpgsqlDataSource db, CancellationToken ct) =>
{
    if (!ValidVector(query.Vector)) return Results.BadRequest("Invalid vector.");
    await using var cmd = db.CreateCommand("""
        SELECT c.document_id, c.version_id, c.ordinal, c.content
        FROM chunks c JOIN documents d ON d.id = c.document_id AND d.active_version = c.version_id
        ORDER BY c.embedding <=> CAST(@embedding AS vector), c.document_id, c.ordinal
        LIMIT 5
        """);
    cmd.Parameters.AddWithValue("embedding", Vector(query.Vector));
    await using var reader = await cmd.ExecuteReaderAsync(ct);
    var hits = new List<object>();
    while (await reader.ReadAsync(ct))
        hits.Add(new { documentId = reader.GetGuid(0), version = reader.GetGuid(1),
            ordinal = reader.GetInt32(2), text = reader.GetString(3) });
    return Results.Ok(hits);
});
await app.RunAsync();

static bool ValidVector(float[]? values) => values is { Length: 3 } &&
    values.All(float.IsFinite) && values.Any(v => v != 0);
static string Vector(float[] values) => "[" + string.Join(",",
    values.Select(v => v.ToString("R", CultureInfo.InvariantCulture))) + "]";

record Chunk(string Text, float[] Vector);
record Revision(Guid? ExpectedVersion, Chunk[] Chunks);
record Search(float[] Vector);

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.

Index the first revision and retrieve it
id=11111111-1111-1111-1111-111111111111
curl -i -X PUT "http://127.0.0.1:5080/documents/$id" \
  -H 'Content-Type: application/json' \
  -d '{"expectedVersion":null,"chunks":[{"text":"Refunds within 14 days","vector":[1,0,0]}]}'

curl -sS http://127.0.0.1:5080/search \
  -H 'Content-Type: application/json' -d '{"vector":[1,0,0]}'

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.

Publish the revision only when all chunks are ready. Return the revision with each hit so downstream answers can cite a consistent source.

Comments