Vector search allows applications to find information based on semantic meaning rather than exact keyword matches. Many modern .NET applications use embeddings to support document search, product recommendations, knowledge-base search, and AI-powered question answering.
However, generating an embedding is only one part of implementing vector search. An application must also keep embeddings synchronized with the actual database records.
Consider a document management application. A user creates a document, and the application generates an embedding from its title and content. Later, the user edits the document. If the application updates the document but does not regenerate its embedding, the database will contain outdated semantic information.
The same problem can occur when a document is deleted, when an embedding request fails, or when multiple updates happen at nearly the same time.
These situations can cause vector search to return outdated or incomplete results.
In this article, we will explore how to keep embedding updates consistent with EF Core database changes. We will use PostgreSQL, pgvector, and ASP.NET Core to implement a reliable approach for creating, updating, and deleting embeddings.
Understanding the Embedding Synchronization Problem
An embedding is a numerical representation of text or other content. An embedding model converts input content into a vector that captures semantic information.
For example, consider a document:
Title: Securing ASP.NET Core APIs
Content: Learn how to protect ASP.NET Core APIs
using authentication, authorization, JWT tokens,
and secure configuration.
The application sends the document content to an embedding model. The model returns a vector, which is stored in PostgreSQL.
A simplified database record looks like this:
Id | Title | Embedding |
|---|
101 | Securing ASP.NET Core APIs | Vector generated from document content |
Now imagine that the user changes the content:
Title: Securing ASP.NET Core APIs
Content: Learn how to protect APIs using OAuth 2.0,
OpenID Connect, access tokens, and secure
authentication workflows.
If the application updates only the title and content, the old embedding remains in the database.
The record now contains two different versions of information:
This creates an inconsistency between the source data and its semantic representation.
A vector search may continue returning the document based on its previous content, even though the user has changed it.
Why Embedding Consistency Matters
Embedding consistency is important because vector search depends on the relationship between stored content and its generated vector.
Several problems can occur when the two become inconsistent.
Outdated Search Results
When a document changes but its embedding is not regenerated, vector search uses an old semantic representation.
A user may search for the updated topic and receive results based on the document's previous content.
Missing Search Results
A newly created document may be saved successfully while embedding generation fails.
If the application does not have a retry mechanism, that document may remain unavailable through semantic search.
Deleted Records With Existing Embeddings
When a document is deleted, its embedding should also be removed.
If embeddings are stored separately from their source records, an application may accidentally retain vectors that refer to deleted documents.
Concurrent Update Problems
Suppose two users update the same document at nearly the same time.
The first update generates embedding A, while the second update generates embedding B.
If embedding requests complete in a different order from the database updates, an older embedding might overwrite the newer one.
These problems become more important as the application grows and multiple users, background workers, and embedding requests operate simultaneously.
Designing the Database Model
Let's build a document management example using EF Core and PostgreSQL.
We will store the document content and its embedding in the same database table.
This approach makes it easier to manage their relationship because both values belong to the same database record.
Create the document entity:
using Pgvector;
public class Document
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public Vector? Embedding { get; set; }
public bool EmbeddingPending { get; set; }
public DateTime UpdatedAt { get; set; }
public DateTime? EmbeddingUpdatedAt { get; set; }
public long ContentVersion { get; set; }
}
The entity contains a few additional properties to manage embedding synchronization.
Property | Purpose |
|---|
Embedding | Stores the generated vector |
EmbeddingPending | Indicates whether embedding generation is required |
UpdatedAt | Tracks the latest document modification |
EmbeddingUpdatedAt | Tracks when the current embedding was generated |
ContentVersion | Identifies the version of the source content |
The ContentVersion property is particularly useful when multiple updates happen while embedding generation is in progress.
It helps identify whether an embedding was generated from the latest version of a document.
Configuring EF Core and PostgreSQL
Install the PostgreSQL provider and pgvector integration packages:
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Pgvector.EntityFrameworkCore
Enable the pgvector extension in PostgreSQL:
CREATE EXTENSION IF NOT EXISTS vector;
Configure the EF Core context:
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(
DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Document> Documents => Set<Document>();
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasPostgresExtension("vector");
modelBuilder.Entity<Document>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.Title)
.HasMaxLength(250);
entity.Property(x => x.Embedding)
.HasColumnType("vector(1536)");
entity.Property(x => x.ContentVersion)
.IsConcurrencyToken();
});
}
}
The embedding column uses 1536 dimensions in this example. The dimension must match the output of the embedding model used by the application.
The ContentVersion property is configured as a concurrency token. EF Core uses it to detect conflicting updates when saving changes.
Create and apply the migration:
dotnet ef migrations add AddDocumentEmbeddingTracking
dotnet ef database update
Generating Embeddings Through a Service
Embedding generation should be separated from database persistence.
This separation makes it easier to replace the embedding provider, introduce retries, and test the database logic independently.
Create an embedding service interface:
public interface IEmbeddingService
{
Task<float[]> GenerateAsync(
string text,
CancellationToken cancellationToken);
}
The implementation can call an embedding API or a locally hosted embedding model.
For this article, we will keep the provider implementation abstract because the synchronization design should not depend on a particular AI provider.
The service receives text and returns a numerical vector.
A production implementation should also validate the returned vector dimension before saving it.
Updating a Document and Its Embedding
A simple implementation might update the document, generate an embedding, and save both values in one operation.
However, external embedding generation introduces an important problem.
The embedding API may take several seconds to respond. Keeping a database transaction open while waiting for an external service is usually undesirable.
It can increase transaction duration, hold database resources, and make the application more sensitive to network failures.
A better approach is to save the document change and mark its embedding as pending.
public class DocumentService
{
private readonly AppDbContext _dbContext;
public DocumentService(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task UpdateAsync(
int documentId,
string title,
string content,
CancellationToken cancellationToken)
{
var document = await _dbContext.Documents
.FirstOrDefaultAsync(
d => d.Id == documentId,
cancellationToken);
if (document == null)
{
throw new InvalidOperationException(
"Document not found.");
}
document.Title = title;
document.Content = content;
document.ContentVersion++;
document.EmbeddingPending = true;
document.UpdatedAt = DateTime.UtcNow;
await _dbContext.SaveChangesAsync(
cancellationToken);
}
}
This method performs a database update without calling the embedding provider.
The existing embedding remains available temporarily, but it represents the previous document version.
The EmbeddingPending property identifies that the embedding needs to be regenerated.
For applications where stale embeddings must never be used, the search query should exclude pending records:
var results = await dbContext.Documents
.AsNoTracking()
.Where(d =>
!d.EmbeddingPending &&
d.Embedding != null)
.OrderBy(d =>
d.Embedding!.CosineDistance(queryEmbedding))
.Take(10)
.ToListAsync();
This approach prioritizes consistency over search availability for documents that are being updated.
Another option is to continue returning the previous embedding until the new one is ready. That provides better availability but allows temporary stale search results. The correct choice depends on the application's requirements.
Creating an Embedding Processing Worker
After saving the document update, a background worker can generate the embedding.
The worker should:
Find documents that need embedding generation.
Read their current content and version.
Generate an embedding.
Verify that the source document has not changed.
Save the embedding only if the version still matches.
Let's define a background processing service.
public class EmbeddingProcessor
{
private readonly AppDbContext _dbContext;
private readonly IEmbeddingService _embeddingService;
public EmbeddingProcessor(
AppDbContext dbContext,
IEmbeddingService embeddingService)
{
_dbContext = dbContext;
_embeddingService = embeddingService;
}
public async Task ProcessAsync(
int documentId,
CancellationToken cancellationToken)
{
var document = await _dbContext.Documents
.AsNoTracking()
.FirstOrDefaultAsync(
d => d.Id == documentId,
cancellationToken);
if (document == null ||
!document.EmbeddingPending)
{
return;
}
var contentVersion = document.ContentVersion;
var text = $"{document.Title}\n{document.Content}";
var values = await _embeddingService.GenerateAsync(
text,
cancellationToken);
if (values.Length != 1536)
{
throw new InvalidOperationException(
"The embedding dimension is invalid.");
}
var vector = new Pgvector.Vector(values);
var currentDocument = await _dbContext.Documents
.FirstOrDefaultAsync(
d => d.Id == documentId,
cancellationToken);
if (currentDocument == null)
{
return;
}
if (currentDocument.ContentVersion != contentVersion)
{
return;
}
currentDocument.Embedding = vector;
currentDocument.EmbeddingPending = false;
currentDocument.EmbeddingUpdatedAt =
DateTime.UtcNow;
await _dbContext.SaveChangesAsync(
cancellationToken);
}
}
The important part is the version comparison:
if (currentDocument.ContentVersion != contentVersion)
{
return;
}
The worker generates the embedding using a particular version of the document.
Before saving the result, it checks whether the document has changed.
If another update occurred while the embedding API was processing the request, the version numbers will be different. The worker discards the outdated result instead of overwriting a newer document state.
The pending flag remains set so that a later processing attempt can generate an embedding for the latest content.
This example demonstrates the synchronization logic. A production worker should also include retry handling, bounded concurrency, logging, and a durable mechanism for scheduling work.
Why a Database Outbox Is More Reliable
The previous example uses an EmbeddingPending flag to identify records that need processing.
This can work for simple applications, but it becomes difficult to manage when multiple workers process records simultaneously.
For example:
Two workers may select the same document.
A worker may crash after generating an embedding.
The application may save a document update but fail before scheduling background work.
A retry may process an old request after a newer update has already been saved.
The transactional outbox pattern helps solve the problem of reliably scheduling background work.
Instead of saving a document and sending a message separately, the application saves both the document update and an outbox record in the same database transaction.
If the transaction commits, both records exist. If it rolls back, neither is saved.
Create an outbox entity:
public class OutboxMessage
{
public long Id { get; set; }
public string EventType { get; set; } = string.Empty;
public int DocumentId { get; set; }
public long ContentVersion { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? ProcessedAt { get; set; }
public int RetryCount { get; set; }
}
Add the corresponding DbSet:
public DbSet<OutboxMessage> OutboxMessages =>
Set<OutboxMessage>();
Now update the document and create an outbox message in the same EF Core operation:
public async Task UpdateDocumentAsync(
int documentId,
string title,
string content,
CancellationToken cancellationToken)
{
await using var transaction =
await _dbContext.Database.BeginTransactionAsync(
cancellationToken);
var document = await _dbContext.Documents
.FirstOrDefaultAsync(
d => d.Id == documentId,
cancellationToken);
if (document == null)
{
throw new InvalidOperationException(
"Document not found.");
}
document.Title = title;
document.Content = content;
document.ContentVersion++;
document.EmbeddingPending = true;
document.UpdatedAt = DateTime.UtcNow;
_dbContext.OutboxMessages.Add(
new OutboxMessage
{
EventType = "DocumentEmbeddingRequested",
DocumentId = document.Id,
ContentVersion = document.ContentVersion,
CreatedAt = DateTime.UtcNow
});
await _dbContext.SaveChangesAsync(
cancellationToken);
await transaction.CommitAsync(
cancellationToken);
}
The document update and the outbox message are committed together.
A background dispatcher can periodically read unprocessed outbox messages and send them to the embedding processor.
This avoids the common problem of successfully updating a document but failing to schedule its embedding job.
The outbox does not automatically guarantee exactly-once processing. Messages can be delivered more than once, so consumers must be designed to handle duplicate processing safely.
Processing Outbox Messages Safely
An outbox dispatcher should claim messages, process them, and mark them as completed.
For applications with multiple workers, simply selecting pending messages without coordination can cause the same message to be processed concurrently.
PostgreSQL supports FOR UPDATE SKIP LOCKED, which can be used to claim available rows without waiting for rows locked by another worker.
A simplified PostgreSQL query looks like this:
SELECT *
FROM outbox_messages
WHERE processed_at IS NULL
ORDER BY id
FOR UPDATE SKIP LOCKED
LIMIT 20;
This query should run inside a transaction. The worker can then process the selected messages and update their status.
For long-running embedding API calls, avoid holding row locks for the entire external request. A common production design is to claim messages in a short transaction by setting a processing status and lease expiration, commit the claim, and then perform the external call.
If the worker crashes, another worker can reclaim messages after the lease expires.
Also consider:
A maximum retry count.
Exponential backoff.
A dead-letter status for messages that repeatedly fail.
Logging of provider errors.
Idempotent message processing.
Monitoring of the age of the oldest pending message.
These features help prevent a temporary embedding provider failure from permanently leaving documents without updated embeddings.
Handling Document Deletion
When a document is deleted, its embedding should no longer be available for search.
If the embedding is stored in the same table as the document, deleting the record also deletes the embedding.
public async Task DeleteDocumentAsync(
int documentId,
CancellationToken cancellationToken)
{
var document = await _dbContext.Documents
.FirstOrDefaultAsync(
d => d.Id == documentId,
cancellationToken);
if (document == null)
{
return;
}
_dbContext.Documents.Remove(document);
await _dbContext.SaveChangesAsync(
cancellationToken);
}
This is one advantage of storing embeddings alongside their source records.
However, if embeddings are stored in a separate table or external vector database, deletion requires additional coordination.
For example, the application may need to create a deletion event in the outbox and let a background worker remove the corresponding vector.
The search layer should also verify that returned vector references still point to valid and authorized source records.
Handling Concurrent Updates
Concurrency is one of the most important problems in embedding synchronization.
Consider the following sequence:
A user updates a document to version 2.
The application starts generating embedding A.
Another user updates the document to version 3.
The application starts generating embedding B.
Embedding B finishes first.
Embedding A finishes later.
Without version validation, embedding A could overwrite embedding B.
The application would then store the embedding for version 2 alongside the content from version 3.
The ContentVersion property prevents this problem when the worker verifies the version before saving.
For stronger database-level protection, use a conditional update that succeeds only when the stored version still matches the version used to generate the embedding.
For example, EF Core's ExecuteUpdateAsync() can be used for a conditional update:
var updated = await _dbContext.Documents
.Where(d =>
d.Id == documentId &&
d.ContentVersion == contentVersion &&
d.EmbeddingPending)
.ExecuteUpdateAsync(
setters => setters
.SetProperty(d => d.Embedding, vector)
.SetProperty(d => d.EmbeddingPending, false)
.SetProperty(
d => d.EmbeddingUpdatedAt,
DateTime.UtcNow),
cancellationToken);
if (updated == 0)
{
// The document changed or is no longer pending.
// Do not overwrite the current embedding.
}
This operation performs the version check and update in the database.
It is important that the update does not increment the content version because the content itself has not changed. Only its derived embedding has been updated.
The application should still have a strategy to schedule another embedding operation when the document changes during processing.
Keeping Search Results Consistent
Even with reliable background processing, there may be a short period when document content and embeddings represent different versions.
The application must decide how to handle that period.
There are two common approaches.
Approach | Behavior | Suitable for |
|---|
Keep old embedding available | Search continues using the previous embedding until replacement | Applications that prioritize search availability |
Exclude pending embeddings | Updated documents are temporarily excluded from vector search | Applications that prioritize freshness |
For the second approach, include the pending flag in the search query:
var results = await _dbContext.Documents
.AsNoTracking()
.Where(d =>
!d.EmbeddingPending &&
d.Embedding != null)
.OrderBy(d =>
d.Embedding!.CosineDistance(queryEmbedding))
.Take(10)
.ToListAsync(cancellationToken);
For the first approach, retain the old embedding while generating the new one. Once the new embedding is ready and its content version has been validated, replace the old vector.
A more advanced design stores embeddings as versioned records. The application can then distinguish between the currently active embedding and embeddings generated from previous content versions.
The correct design depends on how much temporary inconsistency the application can tolerate.
Common Mistakes to Avoid
Generating Embeddings Before Saving the Document
Calling an external embedding service before saving a document can increase request time and create unnecessary database transaction complexity.
A better approach is to save the document and schedule embedding generation through a background process.
Updating Content Without Marking the Embedding as Pending
If the application changes document content but does not mark the embedding as outdated, the worker may never regenerate it.
Every content change that affects the embedding input should create an embedding update request.
Saving an Embedding Without Checking the Content Version
An embedding request can take longer than expected.
Always verify that the source content has not changed before saving the generated vector.
Depending Only on In-Memory Background Jobs
If a process crashes after saving the document but before scheduling a background task, the embedding update may be lost.
Use a durable queue or transactional outbox when reliable processing is required.
Ignoring Duplicate Messages
Outbox messages and background jobs may be delivered more than once.
Design processing so that repeating the same request does not create incorrect state or overwrite a newer embedding.
Keeping Database Transactions Open During API Calls
External AI requests can be slow or fail due to network issues.
Avoid holding database transactions and row locks while waiting for an embedding provider. Use short database operations before and after the external call.
Best Practices for Production Applications
Keep Source Content and Embedding Ownership Clear
Decide which service is responsible for generating and updating embeddings.
The application should have one clearly defined workflow for marking embeddings as outdated, scheduling processing, and saving generated vectors.
Use Durable Background Processing
Use an outbox, persistent queue, or another durable job mechanism when embedding updates must not be lost.
An in-memory task queue is not sufficient for critical synchronization workflows because pending work disappears when the application process stops.
Use Version-Based Validation
Associate each embedding generation request with the version of the source content.
Before saving the result, verify that the source version is still current.
Make Processing Idempotent
The same event may be processed more than once.
Use document identifiers and content versions to ensure that duplicate requests do not overwrite newer embeddings.
Add Retry and Failure Handling
Embedding providers can fail because of network problems, rate limits, timeouts, or temporary service outages.
Use bounded retries with backoff. Track messages that repeatedly fail so that they can be investigated and reprocessed.
Monitor Embedding Synchronization
Track useful operational metrics such as:
Number of documents waiting for embeddings.
Age of the oldest pending embedding request.
Number of failed embedding jobs.
Average embedding generation time.
Number of outdated embedding results discarded.
Number of retries and permanently failed jobs.
These metrics help identify synchronization problems before they significantly affect search quality.
Validate Embedding Dimensions
The vector dimension must match the database column definition.
Validate the returned embedding before saving it. Also consider storing the embedding model identifier and version so that the application can identify vectors generated by different models.
When changing embedding models, remember that vectors generated by different models are not necessarily compatible. A model migration may require regenerating existing embeddings.
Advantages and Disadvantages of Background Embedding Synchronization
Advantages | Disadvantages |
|---|
Keeps embedding generation outside the user request | Search results may temporarily be stale |
Avoids long-running database transactions | Requires background processing infrastructure |
Supports retry and failure recovery | Requires monitoring and operational management |
Handles concurrent document updates | Needs version validation |
Supports large document collections | Adds database and queue complexity |
For small applications, a pending flag and a background worker may be sufficient. Larger systems with multiple application instances and high update volumes benefit from a transactional outbox and durable processing.
Summary
Keeping embeddings consistent with database changes is an important part of building reliable vector search applications.
When a document is created or updated, its embedding must represent the latest content. When a document is deleted, its vector should no longer be available for search. Concurrent updates must also be handled carefully so that an older embedding cannot overwrite a newer one.
EF Core and PostgreSQL provide the database foundation for this workflow. A pending flag, content version, background worker, and transactional outbox can help manage embedding generation reliably.
The most important production principle is to treat embeddings as derived data that must remain synchronized with their source records. Use durable processing, version validation, retry handling, and monitoring to keep semantic search accurate as application data changes.
Join the conversation! Your thoughts help the community grow.