Sr. Content Developer at Microsoft, working remotely in PA, TechBash conference organizer, former Microsoft MVP, Husband, Dad and Geek.
165567 stories
·
33 followers

8 ways to reduce the cost of evals

1 Share

I was at an event last week, and spent a lot of time discussing the same objection to evals from different AI engineers. They all said evals cost too much to run, especially in these times where engineering management are becoming very cost conscious.

Some had stopped running evals against development builds, others were holding back on scoring production traffic. We all agreed that evals are important to not ship on vibes, but to ship tested, measurable changes, so I wanted to put together a guide with some ways to reduce your eval costs.

Most of what an eval costs comes from defaults: the largest judge, the whole trace as input, reasoning switched on, every trace scored. These defaults often have cheaper alternatives that hold their accuracy. Eval cost is mostly a design choice, not a fixed tax.

In this post I cover 8 ways you can reduce your eval costs. Every eval and agent is different, so review these suggestions, and see which ones will work for your use cases.

1. Use code where code fits

Defaulting to an LLM judge can be a quick way to rack up unnecessary costs. Some evals simply don’t need a model, and every one of those that goes to a judge is paying for a judgement no one needs.

Code costs nothing to run, so the question is which evals can it handle. A good litmus test is whether two people looking at the same span with the same rubric could ever disagree on the answer. If they couldn’t, use a code evaluator. Schema checks, format checks and comparisons against a known answer fall on the code side. Questions about meaning, such as whether a reply is a refusal or is concise, stay with an LLM judge. Arize AX ships pre-built code evals for the common cases, including JSON Parsable, Matches Regex and Exact Match, and you can write your own in Python.

Code also doesn’t have to replace the judge. The Arize AX docs recommend stacking the two: a code check validates the shape of the output or settles the clear-cut cases, and an LLM judge scores only what’s left. Two things to plan for: how you write the check matters as much as whether you use code, and code is only as good as the reference answers it compares against, so audit those first.

From my testing. I tried code two ways: on its own, and as a first check in front of an LLM judge.

Cost per 1,000 evals: Math-Verify is free at 99.8% against a $3.46 judge, and a schema check in front of the judge cuts tool-call cost by 38%

Code on its own. I graded 1,500 answers to MATH-500 problems against the known correct answer. Math-Verify, a library that checks whether two answers are mathematically equal, was 99.8% accurate and cost nothing. Sonnet 5.5 as the judge was 99.9% accurate and cost $3.46 per 1,000.

Code plus a judge. I checked 890 tool calls from the Berkeley Function Calling Leaderboard (BFCL), half correct and half with one thing broken. A schema check ran first and failed every call with a structural error, such as a missing argument or a wrong type. That settled 38% of calls for free. It can’t tell that the user asked for Paris and the call says Lyon, so the calls that passed it went to a Sonnet 5.5 judge. Judge cost fell from $2.17 to $1.34 per 1,000, and accuracy stayed about the same, going from 96.4% to 96.5%.

How much you save depends on how much code can settle. On PII leaks, simple pattern rules settled only 18% of documents, because spotting a name or an address is mostly a judgement call. Check your scenarios and see where code fits in.

2. Reduce your eval runs by sampling production and keeping datasets small

Scoring every production trace feels thorough, but past a certain point each extra trace adds cost without adding information. The same goes for development datasets that grow without limit: a large, stale dataset costs more per experiment run and tells you less about today’s traffic.

You don’t need every trace to know your pass rate, only enough of them. Arize AX sets this with a sampling rate on each online eval task. There is an exception: for guardrail-style evals that hunt rare failures, sampling defeats the purpose. You can combine sampling with code, with a code eval on every span for the objective checks, and an LLM judge on a smaller sample of the same traffic.

In development, a few hundred examples that reflect real traffic give more signal per dollar. The Arize AX Dataset Coverage agent compares recent production spans with a dataset and adds real spans that fill gaps, up to a size cap you set. That cap is what keeps each experiment run bounded, which matters most when experiments run as CI/CD regression gates on every pull request.

From my testing. In the RAGTruth test set, 35% of responses contain a hallucination.

Daily cost of scoring 10,000 traces with Opus 5 against a random sample of 500 with Opus 5 or Haiku 5.5

Treat a measure like this as the true rate in your production traffic, and score a random sample of traces:

Traces scored Measured rate, 95% of the time Cost with Opus 5 Cost with Haiku 5.5
100 35% ± 9 points $1.45 $0.02
500 35% ± 4 points $7.27 $0.09
1,000 35% ± 3 points $14.53 $0.17
10,000 35% ± 1 point $145.30 $1.70

Costs use my measured cost per 1,000 hallucination evals: $14.53 for Claude Opus 5 at high effort and $0.17 for Claude Haiku 5.5.

The range narrows with the square root of the sample size, so every extra trace buys less. Going from 1,000 traces to 10,000 costs 10x as much and only narrows the range from ±3 points to ±1.

For a service producing 10,000 traces a day, scoring all of them with Opus costs about $145 a day. Scoring a random 500 costs about $7.27, a 20th of that, and still gives the rate to within ±4 points. Sampling and a cheaper judge multiply: 500 traces scored by Haiku cost 9 cents.

Comparing two versions needs more traces than tracking one. To catch a rise from 35% to 40% hallucinations between versions, with 95% confidence and an 80% chance of spotting it, you need about 1,500 traces per version. A 10-point rise needs about 380 per version, and a 2-point rise about 9,000. Size the sample to the smallest change you need to catch, not to your total traffic.

3. Evaluate at the right session, trace, or span level

An eval scoped wider than its question pays for context it never uses. Asking whether an agent picked the right tool doesn’t need the whole trace, but if the eval runs at trace level, the judge reads it anyway.

The fix is to pick the narrowest evaluation level that can answer the question. A span evaluator typically sees a few hundred tokens of context, while a session evaluator can see tens of thousands.

“Did the agent pick the right tool?” is a span question. “Did the agent loop?” needs the trace. “Did the user’s problem get solved?” needs the session. In Arize AX, scope is a setting on each evaluator, span, trace or session, used by online evals on traces. Trace and session evals are there for the failures that only show up across a whole request or conversation. Scope decides which spans the judge sees, and the next section, trimming, decides which fields it gets.

From my testing. In 199 expert-labelled web-agent traces from AgentRewardBench, a typical trace had 18 LLM spans.

A span question answered from one span reads 7,700 tokens instead of 120,000 for the whole trace

One span’s input was about 7,700 tokens, and all 18 were about 120,000. A span question answered from one span costs about 1/16th of the same question answered from the whole trace. A trace question answered from a code-trimmed trace needed about 5,600 tokens, 21x fewer than every raw span.

4. Send the judge only what it needs

A common setup maps a whole trace into the judge’s prompt. In agent traces that input can be mostly noise: system prompts, tool schemas, repeated chat history and full page dumps at every step. You pay for every token of it, and the noise can make the judge worse.

The fix is to extract the fields the question needs before the judge sees anything. In Arize AX, two task settings do much of this without custom code. Variable mapping fills each template placeholder from one span attribute, so the judge gets the fields you name rather than the whole span. For trace and session evals, the evaluator data filter chooses which spans reach the prompt. Without it, every span in every qualifying session goes to the judge, including internal LLM calls, tool spans and retrieval spans, and you pay for all of them. For extraction that needs real logic, such as keeping only the final page, run your trimming code in a remote evaluator before it calls the judge. If you can’t write extraction code, a cheap model can summarise the input first.

There’s one rule to hold to: trim boilerplate, history and page dumps, never the evidence. A judge that can’t see the evidence can’t verify the claims it’s checking.

From my testing. On AgentRewardBench, a whole trace averaged about 155,000 tokens.

Code-trimmed agent traces cost 20x to 24x less to judge than full traces, for four judges, with the same or better accuracy

Code that kept only the user’s goal, the agent’s reasoning, action and any error at each step, and the final page brought that to about 6,500.

Judge (agent success task) Full trace Code-trimmed trace
Sonnet 5.5 56.0%, $154.84 70.0%, $6.58
Haiku 5.5 58.5%, $15.52 65.5%, $0.71
Kimi K3, reasoning off 77.0%, $20.80 78.5%, $1.04
DeepSeek V4.1 Flash, reasoning off 69.5%, $2.44 75.4%, $0.11

Accuracy is balanced accuracy against the expert labels.

Trimming cut cost by 20x to 24x, and every judge was as accurate or more accurate at its default cutoff. The page dumps made judges reluctant to call a run a success, matching the AgentRewardBench authors’ finding that more page data lowered judge performance.

5. Use a decision model

A generative judge writes its verdict out as text, and you pay for every output token, at the highest rate on the bill with output tokens typically 5x the cost of input tokens. For an eval with a fixed set of answers, such as pass or fail, that text adds cost and latency without adding anything.

A decision model returns a probability for each of a fixed set of options instead of generating text, so it produces no output tokens, with no output charge. Arize AX runs decision models directly as a Decision Judge. The JEV-as-a-Judge paper found decision models strong where the verdict can be read from the text, and weaker on maths, code and multi-step logic. They suit classification-style evals such as hallucination, relevance or tone.

From my testing. On the hallucination task, 1,338 labelled responses from the test half of RAGTruth (the split used in Arize’s Jev-as-a-Judge benchmark), Jev scored 85.4% at $0.046 per 1,000.

Jev decision model at $0.046 per 1,000 hallucination evals and 85.4% accuracy, against Opus 5 at $14.53 and 84.9%

My large-judge baseline, Claude Opus 5 at high effort, scored 84.9% at $14.53. Jev’s median latency was 82 milliseconds, against 3.2 seconds for Opus. Orders of magnitude cheaper and faster, with similar accuracy.

6. Use a cheaper judge

Where an eval does need a generative judge, many teams default to the largest model they have, on the assumption that a larger model is a better judge. For many evals a much smaller model is close enough, at a fraction of the price.

The most direct saving is to keep the eval prompt and change the model. Switching doesn’t always mean rewriting the evaluator, switch your model and test, then tune the eval prompt if needed.

Some of the gap between a small and a large judge is calibration rather than capability. A small judge can rank cases well but set its pass/fail line in the wrong place, so tune the cutoff against human labels before you write it off. And test each eval separately: a cheap judge that works on one eval tells you nothing about the next.

From my testing. On the hallucination task:

Cost per 1,000 hallucination evals and accuracy for Opus 5 and four cheaper judges

Judge (hallucination task) Accuracy Cost per 1,000 evals
Claude Opus 5, high effort 84.9% $14.53
Kimi K3, reasoning off 85.4% $0.44
Claude Haiku 5.5 82.3% $0.17
DeepSeek V4.1 Flash, reasoning off 83.1% $0.024
GPT-6 Luna 74.6% $0.14

DeepSeek V4.1 Flash, an open-weight model, came within 2 points of Opus for about 1/600th of the cost. It held up elsewhere too: 95.6% on tool calls for $0.018 per 1,000, against Claude Sonnet 5.5’s 96.4% for $2.17.

Haiku 5.5 ranked cases almost as well as Opus but flagged too many responses at its default cutoff. Tuning that cutoff against human labels, with two-fold cross-validation, lifted Haiku to 86.3%, level with Opus at about 1% of the cost.

GPT-6 Luna shows why each eval needs its own test: it was among the best on tool calls (96.5%) and maths (99.9%), and 10 points behind Opus on hallucination.

7. Change how you call the judge

Even with the right judge, the way you call it can multiply the bill. Reasoning tokens are billed as output, and output costs far more than input. A judge that thinks at length before a one-word verdict pays for an essay nobody reads. Standard real-time API pricing and repeated, uncached context add more.

Run judges with reasoning off by default, and turn it on only where a test shows it pays. If you need to keep a large judge, lower its effort setting, use the Anthropic Message Batches API or your provider’s equivalent (half the standard rate), and turn on prompt caching for the shared part of the prompt. If you run several evals over the same span, put the shared context first so it can be cached. Batch billing doesn’t suit online evals, but it fits development builds, nightly suites and CI experiments: the runs the engineers at the event had stopped doing.

In Arize AX, most of these levers sit on the evaluator itself. You choose the judge model and AI provider when you create the evaluator, and an LLM override on the task lets you swap in a cheaper model for one task without touching the template. The evaluator also stores invocation parameters and whether to include explanations. Invocation parameters are where you set reasoning effort and output limits, for providers that expose them. Explanations are output tokens, so they’re worth having while you check a new judge and worth turning off once you trust it. Batch pricing and prompt caching are different: AX calls the provider for you, so those depend on the provider. If you need batch pricing for a large offline suite, run the judge in your own code as an experiment from the SDK and log the results to AX.

Whichever settings you change, check the effect: Arize AX shows evaluation cost inline for Playground runs, and through cost tracking for production tasks.

From my testing. DeepSeek at its lowest reasoning setting still produced about 2,000 reasoning tokens per hallucination eval, which made it dearer than Haiku.

Lower effort, batch and caching cut Opus 5 cost 5x; turning reasoning off cuts Kimi K3 11x and DeepSeek 7x

Reasoning didn’t reliably buy accuracy:

  • Hallucination: DeepSeek fell from 83.1% to 75.5% with reasoning on, at 7x the cost. Kimi K3 went from $0.44 to $4.82 per 1,000 and lost 1.4 points.
  • Tool calls: DeepSeek rose about a point, from 95.6% to 96.7%, and cost 3x more.
  • PII: DeepSeek rose from 95.0% to 98.6%, catching 99.6% of leaks for $0.05 per 1,000. That matches Sonnet 5.5’s 98.8% at about 1/40th of the price.

I also reran Opus 5 on the hallucination task at low effort, through the Batch API, with caching on. Cost fell from $14.53 to $3.09 per 1,000, and accuracy went from 84.9% to 86.0%. Low effort cut Opus’s average output from 213 tokens to 46, because a verdict doesn’t need an essay.

8. Escalate only when the cheap judge is unsure

Running every case through an expensive judge pays the top price for cases a cheap judge would have got right. Most cases are clear-cut. The expensive judge earns its cost only on the hard ones.

A cascade runs a cheap judge first and sends a case to an expensive judge only when the cheap judge is unsure. Code checks from section 1 can sit in front of both. This matches published work: Trust or Escalate (ICLR 2025) uses cheaper models as the first judges and escalates to stronger ones only when needed, and Arize’s guide to LLM evaluation costs recommends keeping expensive judges and human review for uncertain or high-stakes cases.

The uncertainty band has to be set on data you hold out from your test set. To run escalation logic like this in Arize AX, host it as a remote evaluator: you keep the scoring logic, and Arize handles orchestration, retries and writing results back to traces.

From my testing. On the hallucination task I ran Jev first and escalated to Opus 5 when Jev’s probability fell inside a band chosen on the tuning half.

Jev first, escalating 8% of cases, costs 10x less than Opus 5 alone with Opus and 69x less with Sonnet 5.5

That sent 8% of cases to Opus. The cascade scored 86.8% at $1.40 per 1,000: more accurate than Opus alone, at about 1/10th of the cost. Escalating to Sonnet 5.5 instead scored 86.6% at $0.21.

Let Arize AX find the spend

Two Arize AX agents target eval cost:

  • The Eval Health agent reviews a project’s evaluators every six hours. Its “Optimize eval” recommendation moves an evaluator to a cheaper judge or replaces it with a code eval: techniques 6 and 1 above. It never creates or edits an eval on its own, so each change is yours to review and apply.
  • The Cost Agent looks for expensive models doing low-complexity work and recommends cheaper routing, with savings calculated from your span data rather than estimated. Its docs focus on application spend, but traced judge calls appear in the same data. Because the agent works from span data, set up cost tracking early: eval costs are only recorded from the point tracking is switched on, not backfilled.

Test on your own data before you switch

The spread in results is the reason you need to test on your own data. For example, GPT-6 Luna scored 74.6% on hallucination and 99.9% on maths. Reasoning helped on PII and hurt on hallucination. Trimming improved one eval and damaged another. A result on my data is a hypothesis about yours.

The check itself is cheap. Take a few hundred examples from one eval with known answers. Run your current judge and two or three candidates: a smaller model with reasoning off, the same judge on a trimmed input, and a code check if the eval has a structural part. Compare accuracy and cost per 1,000. In my experiments that cost between a few cents and a few dollars per eval, and an Arize AX experiment keeps the results side by side.

For development and CI, the best combination in my tests was a cheap judge with reasoning off, batch billing and a small dataset that tracks production. For production, it was code checks in front of a cheap judge, a cascade for uncertain cases, trimmed inputs at the narrowest level that answers the question, and a sample of traffic rather than all of it.

The cost of an eval comes from the choices made when it was set up. Each of those choices can be measured and changed, and once the cost is known, there’s no longer a reason not to run the eval.

Read the whole story
alvinashcraft
11 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Introducing the Syncfusion .NET Document Chunking Library for AI Applications

1 Share

Introducing the Syncfusion .NET Document Chunking Library for AI Applications

TL;DR: Learn to retrieve relevant information from large documents without processing entire files in AI applications. Explore how the new Syncfusion® .NET Document Chunking Library organizes Excel, Word, PDF, PowerPoint, and Markdown documents into meaningful, structure-aware chunks for embedding generation, semantic search, vector indexing, and Retrieval-Augmented Generation (RAG) workflows. Discover how to use it in an ASP.NET Core application to prepare content for semantic search and RAG solutions.

Building AI-powered applications often involves processing thousands of Word documents, PDFs, spreadsheets, and presentations. However, extracting text is only the first step. Preserving the context within headings, tables, worksheets, and slides is equally important for effective information retrieval.

The new Syncfusion® .NET Document Chunking Library, introduced in Essential Studio® 2026 Volume 3, addresses this challenge by dividing supported documents into meaningful chunks while retaining their structure, metadata, and citation details. The library is available across multiple platforms, including ASP.NET MVC, Blazor, Windows Forms, WPF, WinUI, and .NET MAUI.

In this blog, we’ll explore its key features and see how to use the .NET library in an ASP.NET Core application to upload documents, generate structured chunks, and retrieve their content and source information.

Meet the Syncfusion .NET Document Chunking Library

Traditional text splitters divide content primarily by character or token count. This approach can separate headings from their explanations or split tables into unrelated fragments.

The new Syncfusion .NET Document Chunking Library uses document structure to create meaningful chunks. It provides a unified processing workflow for:

  • Word documents
  • PDF files
  • Excel workbooks
  • PowerPoint presentations
  • Markdown files

The library also supports configurable chunk sizes, token overlap, metadata extraction, and citation generation.

These capabilities help developers prepare structured content for applications such as:

  • Retrieval-Augmented Generation (RAG)
  • Semantic search
  • Enterprise search
  • Knowledge assistants
  • Document intelligence platforms

How document chunking works

The library follows a straightforward processing workflow:

  1. Load a supported document from a file or stream.
  2. Configure the chunking options, including token limits, overlap, metadata, and citations.
  3. Process the document using format-specific rules.
  4. Generate chunks based on meaningful document boundaries.
  5. Review the extracted content, metadata, and citation details.
  6. Pass the generated chunks to embedding models or search services for indexing and retrieval.
Document Chunking Library workflow
Document Chunking workflow

For example, consider a quarterly report containing a heading, a paragraph explaining revenue growth, and a table showing revenue by region.

A basic text splitter may separate these elements based on its configured size limit. A structure-aware approach can use the selected chunking mode to preserve relevant content boundaries and source information.

This helps retrieval systems work with more meaningful content instead of disconnected text fragments.

Get started with the .NET Document Chunking Library in ASP.NET Core

Let’s integrate the library into an ASP.NET Core application and process supported documents.

Prerequisites

Before you begin, ensure your development environment includes:

  • Visual Studio 2022 (17.0 or later)
  • .NET 10 SDK or later
  • A supported Word, PDF, Excel, PowerPoint, or Markdown document

Install the required NuGet package

Create a new ASP.NET Core Web App (Model-View-Controller) project and select .NET 10 or a later target framework.

Install the following NuGet package:

dotnet add package Syncfusion.DocumentChunking.Net.Core

Add the required namespace to your controller:

using Syncfusion.DocumentChunking;

Create a document upload page

Add the following code to Views/Home/Index.cshtml to create a form that accepts supported document formats:

@{
    ViewData["Title"] = "Document Chunking";
}

<h1>Document Chunking</h1>

<form asp-controller="Home"
      asp-action="ChunkDocument"
      method="post"
      enctype="multipart/form-data">

    <div>
        <label for="document">Select a document</label>

        <input id="document"
               name="document"
               type="file"
               accept=".xlsx,.xls,.xlsm,.xlsb,.docx,.doc,.pdf,.ppt,.pptx,.pptm,.potx,.md"
               required />
    </div>

    <br />

    <button type="submit">Chunk Document</button>
</form>
Document chunking upload form
Document chunking upload form

The upload form accepts the following formats:

FormatSupported extensions
Excel.xlsx, .xls, .xlsm, .xlsb
Word.docx, .doc
PDF.pdf
PowerPoint.ppt, .pptx, .pptm, .potx
Markdown.md

The HTML accept attribute helps users select supported files in the browser. Always validate uploaded files on the server before processing them.

Generate chunks from uploaded documents

Once a document is uploaded, create a ChunkingService instance and configure the chunking options.

The following example detects the uploaded file format and selects the corresponding document-specific chunking options.

Add this action method to HomeController.cs:

public IActionResult ChunkDocument(IFormFile document)
{
    if (document == null || document.Length == 0)
    {
        return BadRequest("Select a document to chunk.");
    }

    string fileName = document.FileName;
    string extension = Path.GetExtension(fileName).ToLowerInvariant();

    ChunkingService chunkingService = new ChunkingService();

    using Stream fileStream = document.OpenReadStream();

    ChunkingOptions options =
        new ChunkingOptions
        {
            MaxTokens = 500,
            OverlapTokens = 0,
            IncludeMetadata = true,
            IncludeCitation = true
        };

    switch (extension)
    {
        case ".xlsx":
        case ".xls":
        case ".xlsm":
        case ".xlsb":
            options.SourceOptions =
                new ExcelChunkingOptions
                {
                    ChunkingMode = ExcelChunkingMode.Auto
                };
            break;

        case ".docx":
        case ".doc":
            options.SourceOptions =
                new WordChunkingOptions
                {
                    ChunkingMode = WordChunkingMode.Section
                };
            break;

        case ".pdf":
            options.SourceOptions =
                new PdfChunkingOptions
                {
                    ChunkingMode = PdfChunkingMode.Auto
                };
            break;

        case ".pptx":
        case ".ppt":
        case ".pptm":
        case ".potx":
            options.SourceOptions =
                new PowerPointChunkingOptions
                {
                    ChunkingMode = PowerPointChunkingMode.Auto
                };
            break;

        case ".md":
            options.SourceOptions =
                new MarkdownChunkingOptions
                {
                    ChunkingMode = MarkdownChunkingMode.Table
                };
            break;

        default:
            return BadRequest(
                $"The file format '{extension}' is not supported.");
    }

    IChunkingResult result =
        chunkingService.Chunk(fileStream, fileName, options);

    DisplayChunkingResult(result);

    return Content(
        "The document was chunked successfully. " +
        "See the application console for the chunking results.");
}

In this example:

  • MaxTokens sets the maximum token count for each chunk.
  • OverlapTokens determines how many tokens are shared between consecutive chunks.
  • IncludeMetadata enables source document and chunk metadata.
  • IncludeCitation enables source-location information.
  • SourceOptions selects the chunking mode for the uploaded document format.

Here, token overlap is disabled by setting OverlapTokens to 0. You can configure it based on how much context you want to retain between consecutive chunks.

The example uses Auto mode for Excel, PDF, and PowerPoint, Section mode for Word, and Table mode for Markdown. You can change these modes according to your document structure and application requirements.

Review generated chunks, metadata, and citations

The ChunkingService returns an IChunkingResult containing the generated chunks.

Each IChunk provides the extracted content and can include metadata and citation information, depending on the configured options.

Add the following helper method to display the generated results in the application console:

private static void DisplayChunkingResult(
    IChunkingResult result)
{
    Console.WriteLine(
        $"Chunk Count: {result.Chunks.Count}");

    foreach (IChunk chunk in result.Chunks)
    {
        Console.WriteLine("================================");

        Console.WriteLine($"Chunk ID: {chunk.ChunkId}");
        Console.WriteLine($"Chunk Index: {chunk.ChunkIndex}");

        Console.WriteLine(
            $"Content:{Environment.NewLine}{chunk.Content}");

        Console.WriteLine(
            $"Citation: {chunk.Citation?.DisplayText}");

        Console.WriteLine("Citation Location Details");

        if (chunk.Citation?.LocationDetails != null)
        {
            foreach (KeyValuePair<string, object> item
                in chunk.Citation.LocationDetails)
            {
                Console.WriteLine(
                    $"Location Key: {item.Key}, " +
                    $"Location Value: {item.Value}");
            }
        }

        Console.WriteLine(
            $"Metadata SourceDocumentId: " +
            $"{chunk.Metadata?.SourceDocumentId}");

        Console.WriteLine(
            $"Metadata File Name: " +
            $"{chunk.Metadata?.FileName}");

        Console.WriteLine(
            $"Metadata File Type: " +
            $"{chunk.Metadata?.FileType}");

        Console.WriteLine(
            $"Metadata Token Count: " +
            $"{chunk.Metadata?.TokenCount}");

        Console.WriteLine(
            $"Metadata Character Count: " +
            $"{chunk.Metadata?.CharacterCount}");
    }
}

This method displays the generated chunk content, identifiers, citation details, and metadata in the application console.

A typical chunking result can include:

  • Unique chunk identifiers and indexes
  • Extracted chunk content
  • Source document identifiers
  • File names and file types
  • Token and character counts
  • Citation text and source-location details
Generated document chunking output
Generated document chunking output

For detailed setup instructions and additional examples, refer to the official .NET Document Chunking Library documentation.

Explore document-specific chunking modes

Different document formats have different structures. The library provides format-specific chunking modes so developers can choose how content is divided.

Document typeAvailable chunking modes
WordAuto, Paragraph, Table, Section
PDFAuto, Paragraph, Table, Page
ExcelAuto, Table, Worksheet
PowerPointAuto, Table, Notes, Slide
MarkdownAuto, Paragraph, Table, Heading

For example:

  • Paragraph: Creates chunks based on paragraph boundaries in Word or PDF documents.
  • Table: Processes table content in supported document formats.
  • Worksheet: Organizes Excel content by worksheet.
  • Slide: Creates PowerPoint chunks based on individual slides.
  • Heading: Organizes Markdown content around its heading structure.

The Auto mode selects a suitable chunking approach based on the document’s content and structure.

These options help developers prepare content according to its source format rather than relying only on fixed-size text splitting.

Preserve metadata and citations for enterprise AI workflows

Enterprise AI applications often need to identify where retrieved information came from. The library supports metadata enrichment and citation generation to help maintain this traceability.

Metadata provides information about the source document and generated chunk, including:

  • Source document identifier
  • File name and file type
  • Token count
  • Character count
  • Format-specific document attributes
Chunk metadata with format-specific document attributes

Citation information identifies the original location of the extracted content. Depending on the document format, it can include:

Document formatExample source reference
ExcelWorksheet names and cell ranges
WordHeading paths and content types
PDFPage numbers and page ranges
PowerPointSlide numbers and titles
MarkdownHeading paths and line ranges

For example, a citation for an Excel chunk may identify a worksheet and cell range, while a Markdown citation may include its heading hierarchy and line numbers.

This information helps applications trace retrieved content to its original source and display relevant references to users.

The generated chunks can then be passed to embedding models and stored in search indexes or vector databases. Embedding generation, indexing, and AI model integrations are implemented separately within your application.

Frequently Asked Questions

How does the .NET Document Chunking Library differ from basic text splitting?

Traditional text splitters divide content primarily by character or token limits. The .NET Document Chunking Library processes documents based on their native structure and supports format-specific chunking modes. It can preserve relevant relationships between headings, paragraphs, tables, worksheets, slides, and pages while retaining metadata and citation information.

Does the .NET Document Chunking Library require Microsoft Office?

No. The library uses Syncfusion document-processing components and does not rely on Microsoft Office Interop for supported document-processing operations. This makes it suitable for server-side and cross-platform application scenarios.

Can the generated chunks be used with vector databases and RAG applications?

Yes. Generated chunks can be passed to embedding models and used in semantic search, vector indexing, document question answering, and RAG workflows. Metadata helps organize and filter indexed content, while citation information helps trace chunks to their original document locations. Integrations with embedding models, search services, vector databases, and AI models must be implemented separately in your application.

Why is document-aware chunking important for AI applications?

Enterprise documents often contain headings, tables, worksheets, sections, and slides that provide important context. Preserving these structural relationships during chunking helps retrieval systems work with more meaningful content and provides source information for traceability.

Syncfusion .NET Document Chunking Library for RAG and semantic search. Chunk Word, PDF, Excel, PowerPoint, and Markdown files.

Conclusion

Preparing enterprise documents for AI applications starts with preserving the context within them. The new Syncfusion .NET Document Chunking Library helps developers divide Word, PDF, Excel, PowerPoint, and Markdown documents into structured chunks with configurable chunking modes, metadata, and citation information.

Use the generated chunks as a foundation for semantic search, vector indexing, and RAG applications.

Explore the live demo and documentation to see how the library can simplify document preparation for your AI-powered applications.

You can also explore the What’s New and Release Notes to discover the latest document-processing features.

For existing Syncfusion customers, the latest version of Essential Studio is available from the License and Downloads page. New users can explore the library through the 30-day free trial.

If you have questions or feedback, reach out through our support forums, feedback portal, or support portal.

Read the whole story
alvinashcraft
18 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Add the Microsoft Learn MCP server for .NET in Claude Code

1 Share

Make Claude Code search the official docs before it writes C# 15 code, with one setup command, a CLAUDE.md rule and a test of what it knows without it.

Read the whole story
alvinashcraft
30 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

PostgreSQL bloat after VACUUM: why it happens, and how to fix it

1 Share

VACUUM in PostgreSQL makes the space held by dead row versions reusable, but doesn’t shrink tables, compact half-empty pages, or remove rows an older transaction can still see.

That’s why tables and indexes keep growing, and queries keep slowing down, even when autovacuum is running and n_dead_tup looks healthy.

If your busiest tables keep getting bigger, sequential scans read more pages every month, and a query that took 20ms last quarter now takes 60 (with nobody having changed anything), this is the likely reason.

This article covers four causes of bloat that health checks often miss, plus where fillfactor helps, all reproduced on a PostgreSQL 18.4 server with a workload you can run on a laptop.

For each one, you’ll see what happens inside the table and its indexes, how to spot it with tools PostgreSQL already ships, and what to do about it.

The final section is a remediation playbook: which settings to change per table, what to monitor, and how to rebuild a bloated table or index safely.

PostgreSQL bloat after VACUUM: the four causes at a glance

SymptomWhat you seeWhy VACUUM doesn’t fix itFix
1. Table stays the same sizen_dead_tup is 0, but free space is high and full scans read the same number of pagesVACUUM marks space reusable but doesn’t move rows. It only truncates empty pages at the end of the fileUsually nothing. After a one-off mass delete, rewrite with pg_repack or VACUUM FULL
2. Indexes keep growingIndex size stays flat or grows, leaf density drops (as low as 9.2%) and deleted pages pile upA B-tree page is only freed when every entry on it is gone. Timestamp-style keys never refill old gapsREINDEX INDEX CONCURRENTLY, and stop indexing columns that change on every update
3. autovacuum falls behindDead rows build to hundreds of thousands before a run startsTrigger is 50 + 20% of rows, and the launcher only checks once per autovacuum_naptimePer-table scale factor (0.01–0.05), higher cost limit, shorter naptime
4. One old transaction blocks cleanupVACUUM reports rows “dead but not yet removable”. Heap and indexes growThe xmin horizon applies to the whole databaseEnd the session or drop the slot, and set idle_in_transaction_session_timeout

What UPDATE and DELETE leave behind in PostgreSQL

Everything in this article follows from one design decision, so it’s worth being precise about it before we look at any numbers.

Firstly, PostgreSQL never changes a row in place. When you run an UPDATE, it writes a complete new version of the row, and marks the old version as expired by your transaction.

Then, a DELETE simply marks the current version as expired, and the old versions stay exactly where they were – in the same 8 kB page – because other transactions that started earlier may still need to see them.

This is multi-version concurrency control (MVCC), and it’s the reason readers never block writers in PostgreSQL.

Once no running transaction can possibly see an old version any more, it becomes a dead tuple – and dead tuples are pure waste.

They take up space in the page, they are still read by sequential scans, and indexes still point at them – and that’s where VACUUM comes in.

VACUUM removes dead tuples and marks their space as reusable inside the same page, but it only returns space to the operating system when completely empty pages sit at the end of the file.

The page itself stays in the file, which doesn’t get smaller.

Here’s the life of a single page through that cycle:

Figure 1: A heap page through DELETE, VACUUM and INSERT. VACUUM turns dead row versions into free space that new rows can reuse, but the page, and the file, stay the same size.
A heap page through DELETE, VACUUM, and INSERT. VACUUM turns dead row versions into free space that new rows can reuse, but the page, and the file, stay the same size.

So, vacuumed means the dead space can be reused – but the table is still not compact, neither is it healthy. I’ll now explain where these two ideas drift apart.

How we tested: lab setup and autovacuum defaults

Everything that follows was run on PostgreSQL 18.4 (Homebrew build) on a MacBook with an Apple M5 Max (48GB memory) using the server’s default configuration.

The settings

The settings that matter most here are the autovacuum defaults:

autovacuum_naptime = 60s

autovacuum_vacuum_scale_factor = 0.2

autovacuum_vacuum_threshold = 50

autovacuum_vacuum_cost_limit = -1 (which falls back to vacuum_cost_limit = 200)

autovacuum_vacuum_cost_delay = 2ms

autovacuum_max_workers = 3

PostgreSQL 18 also added autovacuum_vacuum_max_threshold, which caps the trigger point at 100 million dead rows. (Our tables are far smaller than that, so this never comes into play.)

image showing the server and autovacuum settings used for this guide.

The server and autovacuum settings used throughout this article. (Recorded terminal session.)

What PostgreSQL contributor extensions do I need to follow this guide?

In this guide, I’ll use three contributor extensions that ship with PostgreSQL, plus pg_repack:

Where to find the lab repository

The scripts, SQL, and load generator are in the lab repository (also linked to at the end of the guide), so you can reproduce every number on your own machine.

To keep the measurements comparable, most of the examples use a small helper function that runs a query under EXPLAIN (ANALYZE, BUFFERS) and returns the number of 8 kB pages it touched.

Timings on a warm laptop cache move around a lot, unlike the number of pages a query has to read. This is what turns into I/O (input/output) on a real server.

Symptom 1: a vacuumed PostgreSQL table doesn’t get smaller

You delete half the rows in a table and run VACUUM. The dead rows are gone, so you would expect the table to be roughly half the size, and a full scan to read roughly half as many pages – but that’s not what happens.

What actually happens to table size after VACUUM

Shown below is a table with a scattered 50% delete. It’s a one-million-row orders table, with autovacuum switched off for this table only (so we can control exactly when VACUUM runs.) We then delete every second row, and vacuum:

CREATE TABLE orders (
  id          bigint PRIMARY KEY,
  customer_id int NOT NULL,
  status      text NOT NULL,
  amount      numeric(10,2) NOT NULL,
  note        text NOT NULL,
  created_at  timestamptz NOT NULL
) WITH (autovacuum_enabled = off);
CREATE INDEX orders_customer_idx ON orders (customer_id);

INSERT INTO orders
SELECT g, (random() * 50000)::int, 'shipped', round((random() * 500)::numeric, 2),
       md5(g::text) || repeat('x', 60), now() - g * interval '1 second'
FROM generate_series(1, 1000000) g;
VACUUM ANALYZE orders;

DELETE FROM orders WHERE id % 2 = 0;   -- 500,000 rows, spread across every page
VACUUM (VERBOSE) orders;

VACUUM reports that it did its work. The interesting lines of its output are:

pages: 0 removed, 19231 remain, 19231 scanned (100.00% of total), 0 eagerly scanned
tuples: 20 removed, 500000 remain, 0 are dead but not yet removable
index scan needed: 19231 pages from table (100.00% of total) had 500000 dead item identifiers removed

Only 20 tuples were reported as removed because the full scan we ran straight after the DELETE had already pruned nearly all the dead rows inside their pages.

Note that PostgreSQL does this opportunistically when a query reads a page that is nearly full.

VACUUM then finished the job by removing the 500,000 leftover item pointers and the matching index entries, and the dead rows are now gone.

Now, look at what the table looks like at each of the six steps (measured with pgstattuple and the page-count helper):

StageHeapIndexesLive rowsDead rowsFree spacePages read by SELECT count(*), sum(amount)
1. Loaded150.2 MB30.7 MB1,000,00000.7 %19,231
2. Deleted half, before VACUUM150.2 MB30.7 MB500,000500,0000.7 %19,231
3. After VACUUM150.2 MB30.7 MB500,000049.0 %19,231
4. After inserting 250,000 new rows150.2 MB36.1 MB750,000024.8 %19,231
5. After emptying the last 20% of pages and VACUUM120.2 MB36.1 MB650,010018.8 %15,385
6. After VACUUM FULL97.7 MB19.4 MB650,01000.7 %12,501

Stage 3 is the one that catches people out. VACUUM ran, dead rows are zero, and the table is exactly the same size: 150MB, now 49% empty.

A full scan still reads all 19,231 pages to find half as many rows, so every row now costs twice the I/O it did before:

image showing the heap size and pages read by a full scan of orders at each stage.
Heap size and pages read by a full scan of orders at each stage. Only removing pages from the end of the file (stage 5) or rewriting the table (stage 6) makes either number go down.

You can see the same behavior in a couple of minutes on a smaller table. In the session shown below, a 200,000-row table is 27MB. Half its rows are deleted and the table is vacuumed: pgstattuple now counts 100,000 live rows, no dead ones, and 48.8% free space, and the table is still 27MB.

Only VACUUM FULL brings it down to 13MB:

Image showing: dead rows go to zero after VACUUM, free space goes to 48.8%, and the size doesn't move until VACUUM FULL
Dead rows go to zero after VACUUM, free space goes to 48.8%, and the size doesn’t move until VACUUM FULL. (Recorded terminal session.)

Why VACUUM can’t shrink the table

This happens because VACUUM works page-by-page. Each page that held deleted rows now holds half as many live rows, and a lot of free space. This is confirmed below, showing the free space inside the table after VACUUM:

SELECT count(*) AS pages,
       count(*) FILTER (WHERE avail >= 4000) AS pages_half_or_more_free,
       round(avg(avail)) AS avg_free_bytes
FROM pg_freespace('orders');

 pages | pages_half_or_more_free | avg_free_bytes
-------+-------------------------+----------------
 19231 |                   19231 |           4000

Every single page is now about half empty. The rows that survived are still spread across all 19,231 pages, so any query that has to look at all of them, or even a large range of them, reads twice as many pages as it would in a compact table.

That space is not wasted forever, though. In stage 4, despite inserting 250,000 new rows, the table didn’t grow by a single page; PostgreSQL found room for every one of them in the gaps VACUUM had left.

That’s the good news – and is why a table that churns at a steady rate usually settles at a stable size instead of growing without limit.

How does plain VACUUM give space back?

The only way plain VACUUM gives space back to the operating system is by cutting off completely empty pages at the end of the file. Stage 5 shows it: we deleted every row stored in the last 20% of the file and then VACUUM reported truncated 19231 to 15385 pages.

PostgreSQL doesn’t move rows around during a normal VACUUM, so any empty pages in the middle of the file can’t be returned. To actually compact the table you need to rewrite it – exactly what VACUUM FULL did in stage 6.

How to spot table bloat when n_dead_tup is zero

n_dead_tup is zero, so is of no help here. The signal is free space (a table whose pgstattuple free percentage stays high, or whose size stays flat while its live row count falls.)

On large tables, meanwhile, pgstattuple reads the whole relation – so for routine checks use pgstattuple_approx(), which skips pages the visibility map says are all-visible (plus, is much cheaper!)

We’ll return to monitoring in the playbook at the end of the guide.

What to do about a bloated table

Nothing, most of the time. A table that’s 20 or 30% free and stable in size is doing exactly what MVCC tables do, and the free space will be used by the next inserts.

The problem cases are a table that had a one-off mass delete and will never refill that space, or a table whose size is climbing enough that VACUUM can’t keep up (as detailed in Symptom 3 later), or is being blocked (Symptom 4).

For the first case, a rewrite with pg_repack or VACUUM FULL is the answer. The playbook covers how to do that safely.

Symptom 2: PostgreSQL indexes keep growing after VACUUM

VACUUM cleans indexes as well as the table. When it removes a dead row, it also removes the index entries that pointed at it.

So, after a big delete and a VACUUM, you’d expect the indexes to shrink along with the data – and index scans to get cheaper – but that’s not what happens…

What actually happens to a B-tree index after deletes and updates

As shown below, it builds an events table with a million rows and an index on created_at, then runs the kind of retention job many systems have: keep one row in ten, delete the rest, and vacuum:

CREATE TABLE events (id bigint PRIMARY KEY, created_at timestamptz NOT NULL, payload text NOT NULL)
  WITH (autovacuum_enabled = off);
INSERT INTO events
SELECT g, timestamptz '2026-01-01' + g * interval '1 second', repeat('e', 40)
FROM generate_series(1, 1000000) g;
CREATE INDEX events_created_idx ON events (created_at);
VACUUM ANALYZE events;

DELETE FROM events WHERE id % 10 <> 0;   -- keep 1 row in 10
VACUUM ANALYZE events;

SELECT pg_relation_size('events_created_idx') / 8192 AS pages, leaf_pages, deleted_pages,
       round(avg_leaf_density::numeric, 1) AS avg_leaf_density
FROM pgstatindex('events_created_idx');

pgstatindex (from the pgstattuple extension) describes the B-tree page-by-page. Before the delete, the index had 2,745 pages and its leaf pages were 90% full. After the delete and VACUUM, however, it still had 2,745 pages, and they were 9.2% full.

Additionally, a query that counts the rows in a three-day window read 715 pages before the delete, and 712 after – even though it now returns a tenth as many rows.

After REINDEX INDEX CONCURRENTLY, the same index was 276 pages and the same query read 74.

Here are the three states:

Image showing a timestamp index before and after a retention delete
The created_atindex BEFORE and AFTER a retention delete. VACUUM removes the dead entries but leaves each leaf page in place, so a range scan walks the same number of pages. Only a rebuild packs the survivors together.

Shown below is a repeat of the experiment interactively on a copy of the table. The index stays at 21MB and 2,733 leaf pages after the delete and VACUUM, while leaf density drops from 90% to 9.2%.

REINDEX INDEX CONCURRENTLY brings it down to 2,208kB:

Image showing the index keeping its size after a retention delete and VACUUM, while only a rebuild shrinks it.
The index keeps its size after a retention delete and VACUUM; only a rebuild shrinks it. (Recorded terminal session.)

The second pattern is more common and harder to see. As shown below, it updates 20% of an accounts table in each of ten rounds and changes updated_at every time – exactly what an application does when it stamps every row it touches.

There’s also an index on updated_at, and VACUUM runs after every round:

UPDATE accounts
SET balance = balance + 1, updated_at = clock_timestamp()
WHERE id % 5 = :round % 5;
VACUUM accounts;

The index grew from 551 to 1,208 pages over the first six rounds and then stopped growing. Stopping sounds like good news until you look at what pgstatindex says about it:

    stage     |  size   | pages | leaf_pages | deleted_pages | avg_leaf_density
--------------+---------+-------+------------+---------------+------------------
 B0 fresh     | 4408 kB |   551 |        547 |             0 |             90.0
 B6 round 6   | 9664 kB |  1208 |        547 |           657 |             89.9
 B10 round 10 | 9664 kB |  1208 |        547 |           656 |             89.9

The live part of the index is the same 547 leaf pages it started with, packed to the same 90% density. More than half the file (656 pages) is made up of pages that VACUUM emptied and marked as deleted.

PostgreSQL will reuse them for future splits in this index, which is why growth levelled off, but it will never hand them back without a rebuild.

This is the index version of Symptom 1, and it’s well-hidden – the density figure most bloat queries look at say 90%.

Why B-tree pages aren’t reclaimed

A B-tree only frees a leaf page when every entry on it is gone. When some entries are deleted and some survive, the page keeps its place in the tree with whatever is left.

Inserts can only refill the gaps if new keys belong in that part of the key range – and, for a timestamp index, they never do. New keys always go to the right-hand end, so the emptied pages on the left stay emptied.

There’s one piece of genuinely good news here, though, and it shows up in the third and fourth runs of the same experiment. PostgreSQL has two defenses against index growth from updates that do not change any indexed column.

They are HOT (heap-only tuple) updates (which avoid creating index entries entirely) and, since PostgreSQL 14, bottom-up index deletion, which removes entries for old row versions when a leaf page is about to split.

Both need the old row versions to be dead already.

Here’s a comparison of the three patterns:

Image showing the index on updated_atunder three update patterns.
The index on updated_atunder three update patterns. Changing the indexed column doubles the index, whereas leaving it alone costs nothing if the work is committed in small transactions.

With one big UPDATE per round, the first round doubled the index to 1,099 pages. Every table page was full, so each new row version went to a different page and needed a new index entry.

Also, the old versions weren’t dead yet, since the statement that made them hadn’t committed.

When the same work was done as 40 transactions of 1,000 rows each, 96% of the updates were HOT (383,604 of 400,000), and the index didn’t grow by a single page.

The bottom line is, the shape of your write transactions matters just as much as the schema.

How to spot index bloat with pgstatindex

Compare an index’s size with the number of pages it actually needs.

For example, pgstatindex gives you leaf_pages, deleted_pages, and avg_leaf_density. Here, deleted_pages is a large share of the total and is carrying dead weight wherever density is low.

So, watch for indexes that have grown much faster than their table, and/or range scans whose buffer counts climb while the number of rows they return does not.

On very large indexes, pgstatindex reads the whole index, so run it off-peak or on a replica.

How to fix index bloat

Rebuild the index with REINDEX INDEX CONCURRENTLY, which builds a fresh copy alongside the old one and swaps it in without blocking reads or writes.

Just be aware that it needs enough disk for a second copy of the index, it takes longer than a plain REINDEX, and it’ll leave an invalid index behind (which you must drop) if it fails part-way. The playbook covers all these details.

Longer term, take frequently changing columns such as updated_at out of indexes (unless a query really needs them), and prioritize many small committed transactions over having a single large one on HOT tables.

Symptom 3: autovacuum is running, but falling behind on busy tables

autovacuum is on, it runs regularly, and the logs show it finishing. It’s therefore natural to assume it’s keeping every table (close to) clean, but that’s not actually happening.

What actually happens: the autovacuum trigger grows with table size

In reality, autovacuum doesn’t look at a table until it has accumulated enough dead rows to cross a threshold – and that threshold grows with the table:

vacuum threshold = autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor x reltuples
                 = 50 + 0.2 x (number of rows)          -- with the defaults

(PostgreSQL 18 also caps the result at autovacuum_vacuum_max_threshold 100 million by default.)

For a table of two million rows, the default trigger is 400,050 dead rows. For a table of 200 million rows, it’s 40 million. The bigger and more important the table, the more garbage it’s allowed to collect before anybody looks at it.

To see what that means in practice, the lab ran a steady load against a sessions table of two million rows (300MB of heap and 56MB of indexes). Four workers updated 2,000 random rows per second in small transactions, with each update setting last_seen and incrementing a counter.

It ran for seven minutes (first with the default settings and then with the per-table settings shown below), while a sampler recorded pg_stat_user_tables and pg_stat_progress_vacuum every five seconds:

ALTER TABLE sessions SET (
  autovacuum_vacuum_scale_factor = 0.01,   -- trigger at 1% dead rows instead of 20%
  autovacuum_vacuum_threshold    = 1000,
  autovacuum_vacuum_cost_limit   = 2000    -- let this table's vacuum do 10x more work per cycle
);
Image showing dead rows in the sessionstable under the same load.
Dead rows in the sessionstable under the same load. With the defaults, autovacuum waited until nearly half a million dead rows had built up. With per-table settings, it ran every minute.

As can be seen, the dead rows climbed in a straight line for three and a half minutes with the defaults (in orange).

Here, once the count passed 400,050 (at about 206 seconds), autovacuum started. It needed roughly 45 seconds to work through the table, by which time the peak was 489,294 dead rows.

As soon as it finished, the count started climbing again towards the next trigger.

With the per-table settings (in blue), autovacuum ran seven times in the same seven minutes. Each run took around five seconds, and the peak was 125,211.

Here’s seven minutes of the same load:

 Default settingsPer-table settings
autovacuum runs17
Peak dead rows489,294125,211
Dead rows at the end404,32782,899
Heap size, start to end301 to 309 MB301 to 306 MB
Index size, start to end56 to 73 MB56 to 73 MB

There are two things of note here.

First, the tuned table still carried about 120,000 dead rows before each run (far above its 21,000 trigger) – a result of autovacuum_naptime.

The launcher only checks each database once a minute, and at 2,000 updates per second a minute’s worth of changes is 120,000 dead rows. A per-table scale factor can’t make autovacuum look any more often than that.

Second, the sizes barely differ after seven minutes; 840,000 updates spread over two million rows had plenty of free space to fall into!

The difference is the trend. The default table is carrying three times as many dead rows as the tuned one, every page of which is read by every scan, and the next time it crosses 400,000 the cycle starts again.

And, over days rather than minutes, that’s exactly how a table drifts.

The indexes grew by the same amount in both runs. Every update changed last_seen, which is indexed – so none of the 840,000 updates was HOT, and each one added an index entry no matter how often VACUUM ran.

With Symptom 2, we’ve already seen why that growth stays.

Three settings decide how fast autovacuum can keep up with a table:

  1. How much garbage it waits for (autovacuum_vacuum_scale_factor and autovacuum_vacuum_threshold).

  2. How often it looks (autovacuum_naptime, global).

  3. How fast it works once it starts (autovacuum_vacuum_cost_limit and autovacuum_vacuum_cost_delay).

The defaults are sensible for a database with many modest tables. However, for a handful of large, HOT tables, they’re far too relaxed.

This is because, with only three autovacuum workers by default, a few slow runs on big tables can delay the others.

Get started with PostgreSQL – free book download

‘Introduction to PostgreSQL for the data professional’, written by Grant Fritchey and Ryan Booz, covers all the basics of how to get started with PostgreSQL.
Download your free copy

How to spot autovacuum falling behind

The early warning signs are visible in pg_stat_user_tables long before anyone notices slower queries.

Here’s the query I would put on a dashboard, showing the tables where autovacuum is falling behind:

SELECT relname,
       n_live_tup,
       n_dead_tup,
       round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
       last_autovacuum,
       now() - last_autovacuum AS since_last_autovacuum,
       autovacuum_count,
       pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_stat_user_tables
WHERE n_dead_tup > 10000
ORDER BY n_dead_tup DESC
LIMIT 20;

A HOT table whose dead percentage keeps climbing between runs, whose last_autovacuum is far older than you would expect for its write rate, or which appears in pg_stat_progress_vacuum for a large part of the day, is a table that autovacuum is not keeping up with.

How to tune autovacuum for large tables

Tune the HOT tables individually rather than changing the global defaults.

A scale factor of 0.01 to 0.05 and a fixed threshold suited to the table’s size is a good starting point, while a higher per-table cost limit lets each run finish quickly.

If your hottest tables change faster than one naptime can absorb, lower autovacuum_naptime for the whole server and consider more autovacuum_max_workers. Just remember that workers share the cost limit!

Also, make sure to look again at which columns you index. An index on a column that changes on every update will grow regardless of how aggressively you vacuum.

Symptom 4: one old transaction stops VACUUM across the whole database

You’ve tuned autovacuum for the HOT tables. It runs every minute and finishes quickly. The table should stay close to clean – but it doesn’t.

What actually happens (how an old snapshot blocks dead-row removal)

VACUUM can only remove a dead row version when no running transaction could still need it.

PostgreSQL tracks the oldest snapshot that any session is still using – often called the xmin horizon – and every dead row newer than that horizon has to stay, in every table of the database, no matter how often VACUUM runs.

In brief:

Image showing where the new row version goes.
While one old snapshot is open, the row versions that later updates leave behind are still visible to it, so VACUUM must keep them. Once it ends, they can all be removed together.

To measure the effect, the lab repeated the tuned run from Symptom 3 with the exact same table and per-table settings, and the same 2,000 updates per second.

There was just one difference: a separate session opened a REPEATABLE READ transaction at 90 seconds, ran one small query to take its snapshot, and then sat idle until 240 seconds.

That’s the shape of a reporting job that opens a transaction and spends two and a half minutes thinking – or of an application that forgets to commit.

A manual VACUUM revealed exactly what was going on just two minutes into that window:

pages: 0 removed, 42693 remain, 42693 scanned (100.00% of total), 0 eagerly scanned
tuples: 0 removed, 2219884 remain, 219892 are dead but not yet removable
removable cutoff: 1350952, which was 4401 XIDs old when operation ended

It scanned the whole table and removed nothing. The removable cutoff (1350952) is the snapshot of the idle report.

The recorded session shown below reproduces the same situation by hand on a smaller table, and ends with the query that finds the culprit:

image showing a REPEATABLE READ transaction that reads the table once.
Session 1 opens a REPEATABLE READ transaction and reads the table once. Session 2 updates a quarter of the rows, runs VACUUM (VERBOSE), and then looks for the session holding the oldest backend_xmin. (Recorded terminal session.)

Here’s a comparison of the two runs over the full seven minutes:

The same load and the same autovacuum settings, with and without a 150-second snapshot.
The same load and the same autovacuum settings, with and without a 150-second snapshot.

As shown above, dead rows follow the familiar one-minute sawtooth and the heap stays flat at 306MB without the long transaction (in blue).

With the long transaction (in orange), however, autovacuum still ran at 141 and 201 seconds, and both runs finished – but the dead-row count went straight through them and reached 351,374.

Updates that couldn’t find reusable space went into new pages, increasing the heap from 306 to 345MB and the indexes from 60 to 93MB while the snapshot was open.

What happened when the report ended?

When the report ended, the next autovacuum cleared the backlog in one pass, but the file sizes didn’t come back down. The run finished with 39MB more heap and 26MB more index than the run without the snapshot.

And, as Symptom 1 demonstrated, a plain VACUUM won’t return that space – which is why having one long transaction is worth considering.

Every table updated during those two and a half minutes carries the extra pages from then on. On a production system with a report that runs every hour, the damage accumulates!

Why the xmin horizon is database-wide

MVCC promises that a transaction sees a consistent snapshot of the database for as long as it needs one – and the only way to keep that promise is to keep every row version the snapshot might read.

PostgreSQL doesn’t know which tables the report will touch next, though, so the horizon applies to the whole database.

Long-running transactions are the most common culprit, but not the only one. It could be an abandoned replication slot, a forgotten prepared transaction, or a standby with hot_standby_feedback.

When it comes to running a long query, they all hold the horizon back in the same way.

How to find what’s holding back cleanup

All the usual suspects are listed in the command below. Run it whenever VACUUM (VERBOSE) reports rows that are “dead but not yet removable”, or put it on a dashboard and alert on the age:

-- sessions, oldest snapshot first
SELECT pid, usename, application_name, state, backend_xmin,
       age(backend_xmin) AS xmin_age,
       now() - xact_start AS transaction_age,
       left(query, 60) AS last_query
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC
LIMIT 10;

-- replication slots, including ones nobody is reading any more
SELECT slot_name, active, xmin, catalog_xmin, age(xmin) AS xmin_age
FROM pg_replication_slots;

-- prepared transactions that were never committed or rolled back
SELECT gid, prepared, owner, database FROM pg_prepared_xacts;

In the lab, the first query found the report straight away: a session idle in transaction, one minute and 49 seconds old, with a backend_xmin 4,397 transactions behind everyone else.

How to stop long transactions blocking VACUUM

Keep transactions short and let the server enforce it. idle_in_transaction_session_timeout ends sessions that sit idle inside an open transaction, and transaction_timeout (new in PostgreSQL 17) puts a ceiling on any transaction.

Set them per-role for applications and reporting users rather than globally, so that a legitimate batch job doesn’t get cut off.

You should also run long reports against a replica and, if that replica uses hot_standby_feedback, remember: its long queries now hold back cleanup on the primary!

So, drop replication slots you no longer need, and make monitoring on age (backend_xmin) as routine as monitoring on disk space.

When lowering fillfactor reduces bloat (and when it doesn’t)

A common piece of advice for update-heavy tables is to lower fillfactor so that each page keeps some free space for future versions of its rows. The hope is for more HOT updates, fewer index entries, and less bloat.

However, that’s not the reality.

What actually happens (how fillfactor changes HOT updates and heap size)

The advice is sound, but its value depends heavily on how you update.

As shown below, HOT is only possible when the new row version fits in the same page as the old one and no indexed column changes:

An image showing the new version staying in the same page.
With free space in the page, the new version stays in the same page and no index changes (a HOT update). When the page is full, the new version goes elsewhere, and every index gets a new entry.

The lab loaded 200,000 rows into an items table at fillfactor 100, 90, 80 and 70 respectively. It then ran five rounds, each updating an unindexed stock column in 20% of the rows, with a VACUUM after each round.

It did that twice for each fillfactor – once with the work split into transactions of 1,000 rows, and once as a single UPDATE per round.

That’s shown below:

an image showing HOT updates and heap size for four fillfactors and two update patterns.
HOT updates and heap size for four fillfactors and two update patterns.

As can be seen, fillfactor 100 already achieved 94.5% HOT updates when the transactions were small (the green columns).

This is because PostgreSQL prunes dead versions inside a page as it goes, and the space they free is enough for the next update.

fillfactor 90, on the other hand, took that to 100% and stopped the heap growing at the price of a table that was 12% bigger from the moment it was loaded.

Meanwhile, with one large UPDATE per round (in orange), fillfactor made a real difference. Here, only 60% of updates were HOT at 100, 78% at 90, and 100% at 80 or 70.

Then, at fillfactor 100, the heap grew by 22% – and at 80, it didn’t grow at all, but started 25% larger!

There’s also the case where fillfactor can’t help at all. When the same five rounds updated the indexed category column instead, the result was 0% HOT at both fillfactor 100 and 70.

The 70 table simply wasted 40% more space for nothing.

Why fillfactor only helps in some workloads

fillfactor reserves free space when rows are first written into a page. That space matters most in the window before VACUUM or page pruning has freed anything else, which is exactly what a large update of recently loaded rows hits.

In a steady OLTP workload of small transactions, pruning keeps recycling space inside each page, and the extra reserve matters less – but neither can help when the update changes an indexed column, because a HOT update is ruled out regardless of how much room there is.

When to lower fillfactor

Lower fillfactor for tables that receive large batches of updates to non-indexed columns, or whose rows are updated soon after insertion; 80 to 90 is usually enough.

Leave it at 100 for insert-only tables and for tables whose updates mostly change indexed columns, and check the effect with n_tup_hot_upd against n_tup_upd in pg_stat_user_tables.

Changing fillfactor with ALTER TABLE ... SET (fillfactor = 90) only affects pages written from then on. To apply it to existing data, you need a rewrite – which brings us nicely to the playbook…

PostgreSQL bloat remediation playbook

All the symptoms above have different causes but, in practice, you deal with them in the same order: stop the bloat from growing, find out where it already is, and then remove it.

While removing the bloat first is tempting (because it gives an immediate result), it doesn’t work in the long run, because a table rebuilt on Monday under the same conditions will be bloated again by Friday!

Step 1: give the HOT tables their own autovacuum settings

Most databases have a handful of tables that take most of the writes. Give each of them per-table settings, as covered earlier: a scale factor between 0.01 and 0.05, a fixed threshold sized to the table, and a cost limit high enough for each run to finish quickly.

In the lab, those three settings cut the peak backlog on the sessions table from 489,294 dead rows to 125,211. Leave the global defaults alone unless many tables need the same change and, if the busiest tables still build up a large backlog within one autovacuum_naptime, shorten the naptime.

At the same time, set idle_in_transaction_session_timeout for application roles, find out which reports run for minutes rather than seconds, and check for unused replication slots.

Symptom 4 showed that just one open snapshot can undo every single autovacuum setting you have.

Step 2: measure where the bloat is

Shown below is a reasonable weekly check using pgstattuple_approx(), which reads only the pages the visibility map can’t vouch for (so is cheap enough to run on large tables):

SELECT s.relname,
       pg_size_pretty(pg_table_size(s.relid)) AS table_size,
       pg_size_pretty(pg_indexes_size(s.relid)) AS index_size,
       round(a.dead_tuple_percent::numeric, 1) AS dead_pct,
       round(a.approx_free_percent::numeric, 1) AS free_pct,
       to_char(s.last_autovacuum, 'YYYY-MM-DD HH24:MI') AS last_autovacuum
FROM pg_stat_user_tables s
CROSS JOIN LATERAL pgstattuple_approx(s.relid) a
WHERE pg_table_size(s.relid) > 10 * 1024 * 1024
ORDER BY pg_table_size(s.relid) DESC
LIMIT 10;

On the lab database at the end of the experiments, it gave the following (abbreviated):

  relname   | table_size | index_size | dead_pct | free_pct | last_autovacuum
------------+------------+------------+----------+----------+------------------
 sessions   | 346 MB     | 101 MB     |      0.0 |     13.0 | 2026-09-27 03:53
 orders     | 98 MB      | 19 MB      |      0.0 |      0.7 |
 events     | 89 MB      | 24 MB      |      0.0 |     85.9 |
 items      | 41 MB      | 8304 kB    |      0.0 |     30.5 |

Since events has no dead rows at all and is 85.9% empty, it has a retention delete that will never be refilled and is therefore a clear candidate for a rewrite.

On the other hand, sessions is 13% free – much of it from the long transaction in Symptom 4 – so that space will be reused by future updates. It’s therefore worth just watching this, rather than fixing, for now.

Then we have items, which is 30% free because it was (intentionally) loaded with fillfactor 70.

Remember, the numbers alone don’t decide anything – it’s just the history of the table that does!

For indexes, run pgstatindex on the large indexes of the HOT tables (Symptom 2), and compare their size with the size of a fresh build. You can estimate this from a copy of the table or a recent rebuild.

Step 3: rebuild bloated indexes with REINDEX CONCURRENTLY

An index is much cheaper to fix than a table, and in Symptom 2 the index was usually the bigger problem.

REINDEX INDEX CONCURRENTLY builds a new copy and swaps it in, and reads and writes carry on while it works, but keep four things in mind:

  • It cannot run inside a transaction block, and needs disk space for a second copy of the index while it runs.

  • It waits for transactions that started before it, so a long-running report will also hold up the rebuild.

  • If it fails or is cancelled, it leaves an invalid index behind (with a _ccnew suffix) that still has to be maintained on every write. Check it with SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid, and drop what you find.

  • Rebuild one large index at a time. Each rebuild does a full index build with its own I/O and WAL.

Step 4: rewrite a table with pg_repack or VACUUM FULL (but only when you must)

When a table like events has a lot of free space that it will never reuse, the only way to give that space back is to rewrite the table.

PostgreSQL’s built-in way to do that is VACUUM FULL, and its cost is the lock – as shown below on a table with four million rows (half of them deleted):

image showing what happens while VACUUM FULL runs
While VACUUM FULL runs, pg_locks shows it holding an AccessExclusiveLock, and an ordinary SELECT in the other session waits 5.9 seconds for it to finish. (Recorded terminal session.)

VACUUM FULL took 10 seconds and, during that time, the table couldn’t be read (let alone written) – so the SELECT in session 2 simply waited.

On a production table many times larger, this could amount to tens of minutes, or even hours, of outage.

pg_repack does the same rewrite online. It copies the table into a new one, records the changes made during the copy in a log table, replays them, and then swaps the files, holding an ACCESS EXCLUSIVE lock only briefly at the start and at the end – as shown below in the same table:

pg_repack rewrites the table from 539MB to 269MB, while the query in session 2 keeps running every two seconds. No read took longer than 2.5 ms. (Recorded terminal session.)

But, it’s not free!

It’s not free, though!

pg_repack needs the extension installed in the database and is normally run as a superuser, the table must have a primary key or a unique index on non-NULL columns, and it needs free disk space for a full copy of the table and its indexes.

Plus, its short locks can still be held up by a long-running transaction, so run it outside the reporting window.

It also carries the table’s storage parameters over to the new copy. When we set fillfactor = 70 on the same table and repacked it, for example, it grew from 269MB to 391MB, with 31.4% free space.

That makes a repack a convenient moment to apply a new fillfactor – and is also a reason to check that setting before you start!

Step 5: which fix for which symptom

What you seeWhat it meansWhat to do
High n_dead_tup that keeps growingautovacuum is behindTune that table first (Step 1)
VACUUM (VERBOSE) reports rows “dead but not yet removable”Something is holding the xmin horizonRun the three queries from Symptom 4 → “How to find what’s holding back cleanup”, then end the session or drop the slot
No dead rows, lots of free space the workload will reuseNormal MVCC behaviourLeave it alone
No dead rows, lots of free space that will never be reusedTypically a one-off mass deleteRewrite with pg_repack, or VACUUM FULL in a maintenance window
Index much larger than a fresh build, or low leaf densityIndex bloatREINDEX INDEX CONCURRENTLY, then ask whether the indexed column needs to change so often
Many non-HOT updates, and updates don’t touch indexed columnsNot enough room in pagesLower fillfactor and apply it at the next rewrite

Summary: what VACUUM does and doesn’t do

VACUUM does exactly one thing well – it makes the space held by dead row versions available again. To summarize:

  • A vacuumed table keeps its size. The space is reused by new rows, and only empty pages at the end of the file are returned.

  • Indexes keep their pages after a mass delete, and indexes on frequently changing columns grow under every update that is not HOT.

  • With default settings, autovacuum on a large, busy table starts late and rarely runs. Per-table settings fix most of that, but autovacuum_naptime still sets a floor.

  • One old snapshot stops cleanup across the whole database, and the growth it causes stays after it ends.

  • fillfactor helps bulk updates to non-indexed columns, helps small transactions much less, and does nothing when an indexed column changes.

None of this means autovacuum is broken – it’s more that vacuumed is a statement about dead rows rather than size, and a healthy system needs both.

Tune the HOT tables, watch the horizon, measure free space and index density, and rebuild only what will not recover by itself.

When done in that order, you’re no longer asking VACUUM for something it never promised, so it stops looking like it’s lying.

How to reproduce the lab

The lab is available on GitHub. You need PostgreSQL with the contrib extensions (the scripts were run on 18.4 and use only standard features), and Python 3.10 or later for the load generator.

Each experiment is a separate script and takes between a few seconds and about 15 minutes.

git clone https://github.com/chandanshukla1989/postgres-vacuum-bloat
cd postgres-vacuum-bloat
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
createdb bloat_lab
psql -d bloat_lab -f sql/00_helpers.sql

./experiments/01_vacuumed_not_smaller.sh    # Symptom 1
./experiments/02_index_bloat.sh             # Symptom 2
./experiments/03_autovacuum_outpaced.sh     # Symptom 3 (two 7-minute runs)
./experiments/04_long_transaction.sh        # Symptom 4
./experiments/05_fillfactor.sh              # Fillfactor

Results go to evidence/raw (the psql output) and data (CSV files).

The pg_repack example also needs the pg_repack extension, created with CREATE EXTENSION pg_repack;, and the matching pg_repack client on your PATH.

The exact numbers will differ a little on other hardware and versions, but the shapes should not.

Free desktop tool for fast PostgreSQL monitoring and diagnostics

Stay in control of PostgreSQL performance with Redgate pgNow – a free desktop tool for fast, focused diagnostics. No agents, no setup, just actionable insights when you need them.
Learn more & download now

FAQs: PostgreSQL bloat and VACUUM

1. Why is my PostgreSQL table still large after VACUUM?

Plain VACUUM marks dead row versions as reusable free space, but it doesn’t move rows or shrink the file. It only returns space to the operating system when empty pages sit at the end of the file. A table with free space scattered through it stays the same size until you rewrite it with VACUUM FULL or pg_repack.

2. Does VACUUM shrink PostgreSQL indexes?

No. VACUUM removes dead index entries but leaves leaf pages in place, so after a mass delete an index keeps its size while leaf density can drop below 10%. B-tree pages are only freed when every entry on them is gone. Rebuild with REINDEX INDEX CONCURRENTLY, which doesn’t block reads or writes.

3. Why is autovacuum running but dead rows keep building up?

Usually for one of two reasons. By default, autovacuum only triggers once dead rows pass 50 plus 20% of the table’s rows, so large tables collect hundreds of thousands first. Alternatively, an old transaction, replication slot or prepared transaction is holding back the xmin horizon, so VACUUM reports rows as “dead but not yet removable”.

4. Should I use VACUUM FULL or pg_repack to reclaim space?

VACUUM FULL holds an ACCESS EXCLUSIVE lock for the whole rewrite, so the table can’t be read or written. pg_repack rewrites online and only locks briefly at the start and end, but needs the extension, a primary key or unique index, and disk space for a full copy. Only use VACUUM FULL in a maintenance window.

5. Does lowering fillfactor reduce PostgreSQL bloat?

It can. A fillfactor of 80 to 90 leaves room in each page for HOT updates, which helps most with large batch updates to non-indexed columns. It helps little with small transactions (fillfactor 100 already reached 94.5% HOT in the lab) and nothing when an indexed column changes. It only applies to newly written pages until you rewrite the table.

The post PostgreSQL bloat after VACUUM: why it happens, and how to fix it appeared first on Simple Talk.

Read the whole story
alvinashcraft
36 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Podcast: Simulation Can Tell You What Your Agents are Actually Doing: A Conversation with Zhou Yu

1 Share

Michael Stiefel spoke to Zhou Yu about using dynamic simulations to evaluate AI agents. One particular focus was conversational agents where actions depend on prior responses, and the non-deterministic nation of LLMs means you cannot rely on static, reference-based benchmarks. You need to test them using dynamic simulations that incorporate different personas, goals, and corner cases.

By Zhou Yu
Read the whole story
alvinashcraft
41 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Publish Events, Send Commands

1 Share

A command with no owner is a request nobody has to answer.

Publish-subscribe exists to broadcast events: the sender puts a message on a topic, the broker hands a copy to every interested consumer, and the sender never needs to know who they are.

But a topic doesn't check what kind of message you put on it. OrderPlaced or ChargeCustomer, it carries whatever bytes you give it. So publishing a command works. In my opinion, it's also the shortcut that leads teams into their first double charge.

Commands vs events: two kinds of ownership

I can't emphasize this enough: there is a fine line between a command and an event(at least in when you start with async messaging), and I keep hearing about teams that walk right over it.

An event says something already happened. OrderPlaced. PaymentReceived. Past tense, because it's a fact and you can't argue with it. The publisher owns the contract. It decides what the event looks like, and it doesn't care who listens. Zero subscribers, one, or twelve - the publisher's job ended when the order was placed and the event message goes out.

A command says "do this". ChargeCustomer. CreateOrder. Imperative, because it's a request, and a request that shouldn't be refused. The receiver should own the contract, because the receiver is the one who knows how to do that specific work. And there is exactly one logical receiver. The sender cares a lot that someone acts on it. That's the whole reason it sent the message.

The tense on the name is only a hint. What separates the two is who is responsible. Events move responsibility away from the sender. Commands hand it to one specific owner.

What publishing a command actually does

Publishing means "whoever subscribed/is interested gets a copy". That's great when the sender doesn't care who reacts. For a command, it breaks the one thing you needed: a single owner.

Here's how it goes wrong. Your checkout service publishes ChargeCustomer. The payments service subscribes. Everything works for a year.

Then someone splits payments into a card service and a wallet service. During the migration both subscribe to ChargeCustomer, because both know how to charge. Each one gets its own copy, and each one charges. The customer pays twice, and no code "failed". The broker did exactly what you asked: it delivered a published message to every subscriber.

The opposite failure is quieter. The payments team renames their endpoint, or a subscription gets dropped during a deployment. Now ChargeCustomer goes out with zero subscribers. On most brokers that means the message vanishes. No error, no dead-letter entry, no exception in the sender. Orders ship and nobody pays for them until finance asks why the numbers don't match.

With a send, both of those are loud. You send to a specific queue. If the queue doesn't exist, the send fails. If a second service wants to handle the command, it has to become the owner. Two teams have to talk about that before it happens.

Left panel, Send: Checkout sends ChargeCustomer to a payments queue with a single Payments owner. Right panel, Publish: Checkout publishes ChargeCustomer to a topic that fans out to a Card service and a Wallet service, both of which charge, while a second topic with no subscribers receives it and nothing happens.

The code should say which one you mean

In NServiceBus, the verb is the decision:

// A request with one owner
await context.Send(new ChargeCustomer(orderId, amount));

// A fact, for whoever cares
await context.Publish(new OrderPlaced(orderId, customerId));

NServiceBus goes further and enforces it. The docs on messages, events, and commands say a command "should be sent to the logical owner" and "cannot be subscribed to", while an event "should be published by the logical owner". Get it wrong and it throws. Publish a command and you get:

"Pub/Sub is not supported for Commands. They should be sent directly to their logical owner."

Send an event and you get:

"Events can have multiple recipients so they should be published."

This enforcement is on by default. You can switch it off per endpoint with routing.DoNotEnforceBestPractices() or per message with options.DoNotEnforceBestPractices(). If you find yourself reaching for either, stop and ask which message you are really sending.

MassTransit is more relaxed. Its message docs use the same vocabulary: a command "tells a service to do something, and typically a command should only be consumed by a single consumer", while events "are published (using Publish)". But the docs also say commands may be published and will be routed to the consumer. Nothing stops you. So I treat it as a convention you enforce in code review: Send to an endpoint for commands, Publish for events.

When a command wants to be an event

Sometimes a published command is a sign the message is named wrong.

If checkout publishes SendConfirmationEmail, UpdateLoyaltyPoints and NotifyWarehouse, checkout knows far too much about the rest of the system. Flip it. Checkout publishes OrderPlaced and stops there. The email service, the loyalty service and the warehouse each decide what OrderPlaced means to them. That's the decoupling pub/sub promised in the first place.

If you can't flip it, because the sender needs one specific thing to happen and needs to know it did, then it's a command. Send it. If the sender also needs an answer back, pub/sub won't give it one. The channels are one-way, so you want request-reply.

A useful test: if nobody handles this message, is that a bug? If yes, it's a command. If no, it's an event.

When pub/sub is the wrong tool

There are a few cases where I'd skip pub/sub altogether:

  • A few consumers that each need very different data. The broker adds complexity with no scaling benefit, and separate queues may fit better.
  • A caller that needs an answer now. Pub/sub adds latency through the broker.
  • Strict ordering. Pub/sub generally doesn't guarantee order across subscribers.
  • One atomic transaction across publisher and consumers. Pub/sub is eventually consistent. Use a local transaction or a saga.

Notice how many of these describe commands in disguise. "I need an answer now" and "it must happen exactly once as part of my transaction" are things a sender says about work it depends on. I wrote about the saga side of this in When Business Processes Outlive Your Request: the orchestrator sends commands and reacts to events, and it never mixes the two up.

Who owns the schema

Ownership shows up again when messages change.

For events, the publisher owns the contract, so versioning is the publisher's job. Prefer additive changes like new optional fields, and for breaking changes, version through the topic name (orders.v1, orders.v2) or a version field in the metadata. Subscribers should ignore fields they don't recognise. That last rule is what lets a publisher add a field on Tuesday without coordinating a release with five teams.

For commands, it's the other way around. The receiver owns the contract, and senders adapt to it. If payments needs a currency code on ChargeCustomer, payments decides that, and every sender updates. Publish a command and this breaks too: which of the unknown subscribers gets to define the contract?

What this means in practice

  • Name commands in the imperative (ChargeCustomer) and events in the past tense (CustomerCharged). If a name doesn't fit either, you don't know yet what the message is.
  • Send commands to one named endpoint. Publish events and let subscribers come and go.
  • Ask "is it a bug if nobody handles this?" for every new message.
  • Make handlers idempotent anyway. Even a correctly sent command can arrive twice under at-least-once delivery.

Pub/sub is a great way to tell the world something happened. It's a terrible way to make sure one thing gets done, because it deliberately doesn't know who is listening.

The broker will carry your commands. It just won't tell you who picked them up, or that nobody did.

PS: have you been bitten by a published command, or a sent event? Ping me, I'd love to hear the story.

Read the whole story
alvinashcraft
49 seconds ago
reply
Pennsylvania, USA
Share this story
Delete
Next Page of Stories