Skip to main content
  • About
  • Archive
  • Tags

Szołkowski's Blog

Blog about Optimizely CMS development, .NET, and technical content

16 October 2026

Surviving a Dirty Feed. Part 3: Error Handling and Event Batching

by Stanisław Szołkowski
Tags: .NET (13) catalog (8) commerce (8) episerver (21) error handling (1) import (5) optimizely (21)

In Part 2 we built a writer that upserts one catalog entry through the DTO API. In this part I will cover the other requirement from Part 1: commit record by record, and give back a report of every row that failed and why.

That requirement turned out to shape the design more than speed did.

How should errors be handled?

The main requirement is simple: one bad row can’t stop the whole import.

In my implementation, an expected failure is returned as an outcome, and an unexpected failure is an exception. Neither of them is allowed to end the run on its own. The circuit breaker below is the one exception, and it still ends with a report.

What does “record by record” mean in practice?

  • There is no transaction for the whole run, and there shouldn’t be one for a batch either. Each row is committed on its own, so one bad row won’t roll back the other 499 rows in its 500-row batch. The only all-or-nothing scope in the whole design is the create path from Part 2, and it covers a single entry.
  • A partial run is still a successful run. The report is what we are after here! Whoever reads it (an API caller getting the rejections in the response body, or an editor reading the job summary) needs the counts and the failed rows, and an exception gives them neither.

That gives us three layers. A row can fail at any of them, and it comes out looking the same to whoever reads the report.

Here are the types that carry the report:

public sealed record ParsedRow<T>(int RowNumber, T? Record, string? Error)
{
    public bool Succeeded => Error is null;
}

public sealed record RejectedRecord(string Identifier, int RowNumber, string Error);

public sealed class ImportSection
{
    // The count is always exact; only the detail list is capped, so a fully-rejecting
    // 250,000-row feed cannot retain a quarter of a million objects for the whole run.
    public const int MaxRetainedRejections = 1_000;

    private readonly List<RejectedRecord> _rejections = new();

    public int Received { get; private set; }
    public int Accepted { get; private set; }
    public int Rejected { get; private set; }
    public IReadOnlyList<RejectedRecord> Rejections => _rejections;

    /// <summary>True when rejections were dropped from the list but still counted.</summary>
    public bool RejectionsTruncated => Rejected > MaxRetainedRejections;

    public void Receive() => Received++;

    public void Accept() => Accepted++;

    public void Reject(string identifier, int rowNumber, string error)
    {
        Rejected++;

        if (_rejections.Count < MaxRetainedRejections)
        {
            _rejections.Add(new RejectedRecord(identifier, rowNumber, error));
        }
    }
}

public sealed class ImportResult
{
    public ImportSection Products { get; } = new();
    public TimeSpan Duration { get; set; }
    public bool Stopped { get; set; }

    // Giving up early is an outcome too - recorded and explained, never thrown, because
    // throwing would destroy the report that is the whole point of the run.
    public bool Aborted { get; set; }
    public string? AbortReason { get; set; }
}

// The job's side of the conversation. Status drives the progress line in the
// scheduled-jobs UI; Rejected and Info become log entries.
public interface IImportObserver
{
    bool StopRequested { get; }

    void Status(string message);

    void Rejected(string message);

    void Info(string message);
}

ParsedRow<T> is layer one. A CSV reader configured with BadDataFound set to record-and-continue never throws for a bad row. Instead, it produces a row-shaped error carrying the physical line number.

Layer two is the writer returning WriteOutcome.Failure(...) for anything it can anticipate.

Layer three is one try/catch per record for everything else.

The counts on ImportSection are always exact, but the detail list is capped. It keeps the first 1,000 rejections (MaxRetainedRejections), so a fully rejected 250,000-row feed doesn’t hold a quarter of a million objects for the whole run.

The job log is capped even lower. The importer lists only the first 200 rejections one by one (MaxIndividuallyReportedRejections), and then prints the exact total in the summary. So “every row that failed” means every row is counted, but only the first 1,000 come with details.

Here is the full importer:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;

using EPiServer.Authorization;
using EPiServer.Security;

using Microsoft.Extensions.Logging;

#nullable enable

namespace CatalogImport;

/// <summary>
/// Drives the import: chunk the rows, verify each one, write it, and record the outcome.
/// A single bad row is an outcome to report, never a reason to stop.
/// </summary>
public class CatalogBulkImporter
{
    // Big enough that the per-batch overhead disappears, small enough that a Stop click
    // lands within a few seconds and progress reporting stays useful.
    private const int BatchSize = 500;

    // Logging every batch is noise; logging none of them is a black box.
    private const int BatchLogInterval = 10;

    // Past this many rejections we stop narrating them one by one. See Reject below.
    private const int MaxIndividuallyReportedRejections = 200;

    // Consecutive THROWN failures that mean "the dependency is down", not "the feed is dirty".
    // Returned failures - a missing price, an unknown category - are bad data and do not count:
    // a feed can legitimately be 100% rejects and that is a report, not an outage.
    private const int MaxConsecutiveFailures = 100;

    private readonly ICatalogEntryWriter _writer;
    private readonly IPrincipalAccessor _principalAccessor;
    private readonly ILogger<CatalogBulkImporter> _logger;

    private int _consecutiveFailures;

    public CatalogBulkImporter(
        ICatalogEntryWriter writer,
        IPrincipalAccessor principalAccessor,
        ILogger<CatalogBulkImporter> logger)
    {
        _writer = writer;
        _principalAccessor = principalAccessor;
        _logger = logger;
    }

    public ImportResult Import(IEnumerable<ParsedRow<ProductImportItem>> rows, IImportObserver observer)
    {
        var result = new ImportResult();
        var totalStopwatch = Stopwatch.StartNew();

        // Per-run state, reset per run. As an instance field it would otherwise carry over: end
        // one run at 99 consecutive failures and the next would trip on its first row.
        _consecutiveFailures = 0;

        var batchNumber = 0;
        var processed = 0;

        foreach (var batch in rows.Chunk(BatchSize))
        {
            // Stop is cooperative and checked at batch boundaries only. Rows already written
            // stay written - a stopped import is a partial success, and the report says so.
            if (observer.StopRequested)
            {
                result.Stopped = true;
                break;
            }

            batchNumber++;
            var batchStopwatch = Stopwatch.StartNew();

            ProcessBatch(batch, result, observer);

            batchStopwatch.Stop();

            // Break here, before any counting or narration. An aborting batch stops partway
            // through its rows, so adding batch.Length would report rows we never attempted and
            // the throughput line below would divide a partial batch by a full one. In a design
            // whose whole claim is that the report is the deliverable, a final status line that
            // overstates what happened is not a rounding error.
            if (result.Aborted)
            {
                break;
            }

            processed += batch.Length;

            observer.Status($"Products: processed {processed} rows");

            if (batchNumber == 1 || batchNumber % BatchLogInterval == 0)
            {
                var seconds = batchStopwatch.Elapsed.TotalSeconds;
                var rate = seconds > 0 ? $"{batch.Length / seconds:N0} rows/s" : "n/a";
                observer.Info($"Batch {batchNumber}: {batch.Length} rows in {seconds:N2} s ({rate})");
            }
        }

        totalStopwatch.Stop();
        result.Duration = totalStopwatch.Elapsed;

        // The counts are always exact; the narration and the detail list are capped. Say so as
        // soon as the narration stopped (row 201 promised "see the summary"), otherwise a caller
        // reading "every failed row" off a truncated log draws the wrong conclusion silently.
        if (result.Products.Rejected > MaxIndividuallyReportedRejections)
        {
            // Two different caps, and they are easy to confuse: this narration stops at
            // MaxIndividuallyReportedRejections, while the in-memory detail list on the result
            // stops at MaxRetainedRejections. Only the totals are uncapped.
            var retained = Math.Min(result.Products.Rejected, ImportSection.MaxRetainedRejections);
            observer.Info(
                $"{result.Products.Rejected:N0} rejections in total. " +
                $"{MaxIndividuallyReportedRejections:N0} were listed individually above and " +
                $"{retained:N0} are retained on the result; " +
                "the total is exact.");
        }

        return result;
    }

    private void ProcessBatch(
        ParsedRow<ProductImportItem>[] batch,
        ImportResult result,
        IImportObserver observer)
    {
        // The DTO API reads the ambient principal, and a scheduled job has not got one.
        // Elevate for the batch, restore afterward - and open the event batch in the same
        // scope so exactly one coalesced catalog event is raised per 500 rows.
        var previousPrincipal = _principalAccessor.Principal;
        _principalAccessor.Principal = new GenericPrincipal(
            new GenericIdentity(nameof(CatalogBulkImporter)),
            new[] { Roles.Administrators });

        try
        {
            // Begin() throws if a scope is already open on this flow. That is a caller bug, but it
            // must not become an exception that escapes Import and takes the report with it - the
            // same reasoning as the circuit breaker below. Record it as an abort instead.
            IDisposable scope;
            try
            {
                scope = CatalogChangeBatch.Begin();
            }
            catch (InvalidOperationException ex)
            {
                result.Aborted = true;
                result.AbortReason = "Could not open a catalog change batch: " + ex.Message;
                observer.Info(result.AbortReason);
                return;
            }

            // Note the explicit `using` block rather than `using var`. A `using var` here would
            // dispose at the end of the METHOD - after the finally below has already restored the
            // principal - so the coalesced broadcast, and every subscriber it runs synchronously,
            // would execute unelevated. That is the exact condition the elevation exists to
            // prevent, and it is an easy one to introduce by "tidying" this into a using var.
            using (scope)
            {
                foreach (var row in batch)
                {
                    if (result.Aborted)
                    {
                        break;
                    }

                    result.Products.Receive();
                    ProcessRow(row, result, observer);
                }
            }
        }
        finally
        {
            _principalAccessor.Principal = previousPrincipal;
        }
    }

    private void ProcessRow(
        ParsedRow<ProductImportItem> row,
        ImportResult result,
        IImportObserver observer)
    {
        // Layer 1 - the row never parsed. It still gets counted and reported, with its
        // physical line number, because "row 148213 had an unescaped quote" is the only
        // thing that lets anyone fix the feed.
        if (!row.Succeeded || row.Record is null)
        {
            Reject(result, observer, "(unparseable)", row.RowNumber, row.Error ?? "Row could not be parsed.");
            return;
        }

        var item = row.Record;
        var identifier = item.Sku ?? "(no sku)";

        // Layer 2 - expected failures. The writer returns them, it does not throw them.
        // Reserve exceptions for the genuinely unexpected.
        WriteOutcome outcome;
        try
        {
            outcome = _writer.Upsert(item);
        }
        // Layer 3 - the unexpected. One try/catch per record is the whole soft-fail mechanism:
        // this row is lost, the other 249,999 are not. Note the filter: OutOfMemoryException is
        // not a bad row, it is a dead process, and "carry on and reject the remaining 249,000
        // one at a time" is the worst possible response to it.
        //
        // And note that the filter walks the tree rather than testing `ex` directly. The writer
        // wraps a failed rollback in an AggregateException, so an OOM can arrive here already
        // nested - at which point a top-level test matches nothing and the guard silently does
        // not guard. Same trap the writer's own stale-node check documents.
        catch (Exception ex) when (!ExceptionTree.Flatten(ex).Any(e => e is OutOfMemoryException))
        {
            _logger.LogError(ex, "Unexpected error importing {Sku} at row {RowNumber}.", identifier, row.RowNumber);
            Reject(result, observer, identifier, row.RowNumber, "Unexpected error: " + ex.Message);

            // A run of consecutive failures is not a bad feed, it is a broken dependency - a
            // dropped connection, a full disk. Rejecting every remaining row individually would
            // take hours and produce a report nobody can read, so stop and say why.
            //
            // Note what this does NOT do: throw. `result` is a local, so throwing out of here
            // would destroy every count and every rejection gathered so far and hand the caller
            // one row's exception message instead of the report. Aborting is an outcome like any
            // other failure in this design - it is recorded, it is explained, and the partial
            // report still comes back.
            if (++_consecutiveFailures >= MaxConsecutiveFailures)
            {
                result.Aborted = true;
                result.AbortReason =
                    $"{MaxConsecutiveFailures} rows threw in a row (last: {ex.Message}); aborting " +
                    "rather than rejecting the rest of the feed one row at a time.";
                observer.Info(result.AbortReason);
            }

            return;
        }

        if (outcome.Succeeded)
        {
            // Reset only on an actual success. Resetting on a RETURNED failure too would mean one
            // malformed row interleaved among timeouts keeps the breaker permanently disarmed.
            _consecutiveFailures = 0;
            result.Products.Accept();
        }
        else
        {
            Reject(result, observer, identifier, row.RowNumber, outcome.Error!);
        }
    }

    /// <summary>
    /// Records a rejection and reports it in one place, so a rejection can never be counted
    /// without being reported or reported without being counted.
    ///
    /// Individual reporting is capped. Every observer.Rejected call is a log write, and a log
    /// write is a database round trip - so a feed that rejects every row would otherwise turn
    /// into 250,000 round trips serialized on the job thread, which is slower than importing the
    /// file successfully and looks exactly like a hang. The counts stay exact; only the
    /// row-by-row narration stops.
    /// </summary>
    private static void Reject(
        ImportResult result,
        IImportObserver observer,
        string identifier,
        int rowNumber,
        string error)
    {
        result.Products.Reject(identifier, rowNumber, error);

        if (result.Products.Rejected <= MaxIndividuallyReportedRejections)
        {
            observer.Rejected($"Row {rowNumber} - {identifier} - {error}");
        }
        else if (result.Products.Rejected == MaxIndividuallyReportedRejections + 1)
        {
            observer.Rejected(
                $"More than {MaxIndividuallyReportedRejections} rejections; further rows will be " +
                "counted but not listed individually. See the summary for the total.");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;

using EPiServer.Authorization;
using EPiServer.Security;

using Microsoft.Extensions.Logging;

#nullable enable

namespace CatalogImport;

/// <summary>
/// Drives the import: chunk the rows, verify each one, write it, and record the outcome.
/// A single bad row is an outcome to report, never a reason to stop.
/// </summary>
public class CatalogBulkImporter
{
    // Big enough that the per-batch overhead disappears, small enough that a Stop click
    // lands within a few seconds and progress reporting stays useful.
    private const int BatchSize = 500;

    // Logging every batch is noise; logging none of them is a black box.
    private const int BatchLogInterval = 10;

    // Past this many rejections we stop narrating them one by one. See Reject below.
    private const int MaxIndividuallyReportedRejections = 200;

    // Consecutive THROWN failures that mean "the dependency is down", not "the feed is dirty".
    // Returned failures - a missing price, an unknown category - are bad data and do not count:
    // a feed can legitimately be 100% rejects and that is a report, not an outage.
    private const int MaxConsecutiveFailures = 100;

    private readonly ICatalogEntryWriter _writer;
    private readonly IPrincipalAccessor _principalAccessor;
    private readonly ILogger<CatalogBulkImporter> _logger;

    private int _consecutiveFailures;

    public CatalogBulkImporter(
        ICatalogEntryWriter writer,
        IPrincipalAccessor principalAccessor,
        ILogger<CatalogBulkImporter> logger)
    {
        _writer = writer;
        _principalAccessor = principalAccessor;
        _logger = logger;
    }

    public ImportResult Import(IEnumerable<ParsedRow<ProductImportItem>> rows, IImportObserver observer)
    {
        var result = new ImportResult();
        var totalStopwatch = Stopwatch.StartNew();

        // Per-run state, reset per run. As an instance field it would otherwise carry over: end
        // one run at 99 consecutive failures and the next would trip on its first row.
        _consecutiveFailures = 0;

        var batchNumber = 0;
        var processed = 0;

        foreach (var batch in rows.Chunk(BatchSize))
        {
            // Stop is cooperative and checked at batch boundaries only. Rows already written
            // stay written - a stopped import is a partial success, and the report says so.
            if (observer.StopRequested)
            {
                result.Stopped = true;
                break;
            }

            batchNumber++;
            var batchStopwatch = Stopwatch.StartNew();

            ProcessBatch(batch, result, observer);

            batchStopwatch.Stop();

            // Break here, before any counting or narration. An aborting batch stops partway
            // through its rows, so adding batch.Length would report rows we never attempted and
            // the throughput line below would divide a partial batch by a full one. In a design
            // whose whole claim is that the report is the deliverable, a final status line that
            // overstates what happened is not a rounding error.
            if (result.Aborted)
            {
                break;
            }

            processed += batch.Length;

            observer.Status($"Products: processed {processed} rows");

            if (batchNumber == 1 || batchNumber % BatchLogInterval == 0)
            {
                var seconds = batchStopwatch.Elapsed.TotalSeconds;
                var rate = seconds > 0 ? $"{batch.Length / seconds:N0} rows/s" : "n/a";
                observer.Info($"Batch {batchNumber}: {batch.Length} rows in {seconds:N2} s ({rate})");
            }
        }

        totalStopwatch.Stop();
        result.Duration = totalStopwatch.Elapsed;

        // The counts are always exact; the narration and the detail list are capped. Say so as
        // soon as the narration stopped (row 201 promised "see the summary"), otherwise a caller
        // reading "every failed row" off a truncated log draws the wrong conclusion silently.
        if (result.Products.Rejected > MaxIndividuallyReportedRejections)
        {
            // Two different caps, and they are easy to confuse: this narration stops at
            // MaxIndividuallyReportedRejections, while the in-memory detail list on the result
            // stops at MaxRetainedRejections. Only the totals are uncapped.
            var retained = Math.Min(result.Products.Rejected, ImportSection.MaxRetainedRejections);
            observer.Info(
                $"{result.Products.Rejected:N0} rejections in total. " +
                $"{MaxIndividuallyReportedRejections:N0} were listed individually above and " +
                $"{retained:N0} are retained on the result; " +
                "the total is exact.");
        }

        return result;
    }

    private void ProcessBatch(
        ParsedRow<ProductImportItem>[] batch,
        ImportResult result,
        IImportObserver observer)
    {
        // The DTO API reads the ambient principal, and a scheduled job has not got one.
        // Elevate for the batch, restore afterward - and open the event batch in the same
        // scope so exactly one coalesced catalog event is raised per 500 rows.
        var previousPrincipal = _principalAccessor.Principal;
        _principalAccessor.Principal = new GenericPrincipal(
            new GenericIdentity(nameof(CatalogBulkImporter)),
            new[] { Roles.Administrators });

        try
        {
            // Begin() throws if a scope is already open on this flow. That is a caller bug, but it
            // must not become an exception that escapes Import and takes the report with it - the
            // same reasoning as the circuit breaker below. Record it as an abort instead.
            IDisposable scope;
            try
            {
                scope = CatalogChangeBatch.Begin();
            }
            catch (InvalidOperationException ex)
            {
                result.Aborted = true;
                result.AbortReason = "Could not open a catalog change batch: " + ex.Message;
                observer.Info(result.AbortReason);
                return;
            }

            // Note the explicit `using` block rather than `using var`. A `using var` here would
            // dispose at the end of the METHOD - after the finally below has already restored the
            // principal - so the coalesced broadcast, and every subscriber it runs synchronously,
            // would execute unelevated. That is the exact condition the elevation exists to
            // prevent, and it is an easy one to introduce by "tidying" this into a using var.
            using (scope)
            {
                foreach (var row in batch)
                {
                    if (result.Aborted)
                    {
                        break;
                    }

                    result.Products.Receive();
                    ProcessRow(row, result, observer);
                }
            }
        }
        finally
        {
            _principalAccessor.Principal = previousPrincipal;
        }
    }

    private void ProcessRow(
        ParsedRow<ProductImportItem> row,
        ImportResult result,
        IImportObserver observer)
    {
        // Layer 1 - the row never parsed. It still gets counted and reported, with its
        // physical line number, because "row 148213 had an unescaped quote" is the only
        // thing that lets anyone fix the feed.
        if (!row.Succeeded || row.Record is null)
        {
            Reject(result, observer, "(unparseable)", row.RowNumber, row.Error ?? "Row could not be parsed.");
            return;
        }

        var item = row.Record;
        var identifier = item.Sku ?? "(no sku)";

        // Layer 2 - expected failures. The writer returns them, it does not throw them.
        // Reserve exceptions for the genuinely unexpected.
        WriteOutcome outcome;
        try
        {
            outcome = _writer.Upsert(item);
        }
        // Layer 3 - the unexpected. One try/catch per record is the whole soft-fail mechanism:
        // this row is lost, the other 249,999 are not. Note the filter: OutOfMemoryException is
        // not a bad row, it is a dead process, and "carry on and reject the remaining 249,000
        // one at a time" is the worst possible response to it.
        //
        // And note that the filter walks the tree rather than testing `ex` directly. The writer
        // wraps a failed rollback in an AggregateException, so an OOM can arrive here already
        // nested - at which point a top-level test matches nothing and the guard silently does
        // not guard. Same trap the writer's own stale-node check documents.
        catch (Exception ex) when (!ExceptionTree.Flatten(ex).Any(e => e is OutOfMemoryException))
        {
            _logger.LogError(ex, "Unexpected error importing {Sku} at row {RowNumber}.", identifier, row.RowNumber);
            Reject(result, observer, identifier, row.RowNumber, "Unexpected error: " + ex.Message);

            // A run of consecutive failures is not a bad feed, it is a broken dependency - a
            // dropped connection, a full disk. Rejecting every remaining row individually would
            // take hours and produce a report nobody can read, so stop and say why.
            //
            // Note what this does NOT do: throw. `result` is a local, so throwing out of here
            // would destroy every count and every rejection gathered so far and hand the caller
            // one row's exception message instead of the report. Aborting is an outcome like any
            // other failure in this design - it is recorded, it is explained, and the partial
            // report still comes back.
            if (++_consecutiveFailures >= MaxConsecutiveFailures)
            {
                result.Aborted = true;
                result.AbortReason =
                    $"{MaxConsecutiveFailures} rows threw in a row (last: {ex.Message}); aborting " +
                    "rather than rejecting the rest of the feed one row at a time.";
                observer.Info(result.AbortReason);
            }

            return;
        }

        if (outcome.Succeeded)
        {
            // Reset only on an actual success. Resetting on a RETURNED failure too would mean one
            // malformed row interleaved among timeouts keeps the breaker permanently disarmed.
            _consecutiveFailures = 0;
            result.Products.Accept();
        }
        else
        {
            Reject(result, observer, identifier, row.RowNumber, outcome.Error!);
        }
    }

    /// <summary>
    /// Records a rejection and reports it in one place, so a rejection can never be counted
    /// without being reported or reported without being counted.
    ///
    /// Individual reporting is capped. Every observer.Rejected call is a log write, and a log
    /// write is a database round trip - so a feed that rejects every row would otherwise turn
    /// into 250,000 round trips serialized on the job thread, which is slower than importing the
    /// file successfully and looks exactly like a hang. The counts stay exact; only the
    /// row-by-row narration stops.
    /// </summary>
    private static void Reject(
        ImportResult result,
        IImportObserver observer,
        string identifier,
        int rowNumber,
        string error)
    {
        result.Products.Reject(identifier, rowNumber, error);

        if (result.Products.Rejected <= MaxIndividuallyReportedRejections)
        {
            observer.Rejected($"Row {rowNumber} - {identifier} - {error}");
        }
        else if (result.Products.Rejected == MaxIndividuallyReportedRejections + 1)
        {
            observer.Rejected(
                $"More than {MaxIndividuallyReportedRejections} rejections; further rows will be " +
                "counted but not listed individually. See the summary for the total.");
        }
    }
}

Key points:

  • Carry the row number through, since the writer knows SKUs and the reader knows lines
  • Count and report a rejection in the same place, never separately
  • The natural key does the idempotency work, so replay is safe
  • Stop is cooperative and checked between batches
  • Stopped and Aborted are different outcomes and both need rendering
  • The circuit breaker is a recorded outcome, so it doesn’t throw

Row numbers

The writer only knows SKUs, and the person fixing the feed only knows line numbers.

If we keep RowNumber on the rejection, people act on the report. Without it, the report gets ignored.

Counting and reporting

A single Reject helper means a rejection can’t be counted without being reported, or reported without being counted.

When those two drift apart, we get an annoying bug to chase, and I would prefer not to chase it twice.

Idempotency

The writer upserts on SKU and guards every field, so re-running the same feed in effect changes nothing.

There is no run id and no “have I imported this file already?” check. I don’t think we need one, as long as the key is the feed’s own and every write is guarded.

Stop and abort

Stop is cooperative and is checked between batches. Rows already written stay written.

A stopped import is a partial success, and the report should say exactly that, so it doesn’t look like a failure.

Stopped and Aborted are separate flags. A human pressing Stop sets the first one, and the circuit breaker sets the second. Anything that shows “was this a partial run?” needs to check both.

The circuit breaker

A hundred consecutive rows that throw mean a dropped connection or a full disk. Rejecting the remaining 249,000 rows one at a time would take hours and produce a report nobody can read.

So we stop the run and set Aborted plus a reason on the result. It doesn’t throw, because throwing would destroy the counts and rejections gathered so far, and they are the whole point of the run.

We count throws only. Returned failures are bad data, and a feed can be 100% rejects. That should still end with a report, so the breaker doesn’t react to it.

What would I fix first?

The writer from Part 2 retries one exact FK and nothing else, and here is why that gap matters.

A transient SQL timeout and a really invalid row both land in that last catch, and both come out as “unexpected error”.

That makes the rejection list a list for diagnosis, and we can’t use it as a retry queue.

If we give the two cases separate outcomes, we can retry one and report the other.

Batching and the event storm

When we bypass the content layer, no catalog events are raised for us.

The obvious fix is to raise one event per row, and it is worse than the problem. On a multi-instance setup every raised catalog event is a message on the bus, so 250,000 rows means 250,000 messages.

What I wanted was one coalesced event per batch. I used an AsyncLocal ambient scope, so we don’t have to pass a batch object through every method signature:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

using Mediachase.Commerce.Catalog.Events;

#nullable enable

namespace CatalogImport;

/// <summary>
/// Collects catalog changes made through the DTO API and raises a single coalesced
/// Commerce event when the scope closes, instead of one event per written row.
///
/// The DTO API raises nothing on your behalf. Without this, either nobody hears about
/// the import at all, or - if you raise per row - a 250,000-row feed turns into 250,000
/// event broadcasts, which on a multi-instance setup is 250,000 Service Bus messages.
/// </summary>
public static class CatalogChangeBatch
{
    // AsyncLocal, not a plain static: the ambient batch follows the logical call stack, so a
    // writer several layers down can report a change without every method signature growing a
    // batch parameter, and two independent imports do not share one batch.
    //
    // READ THAT LAST CLAUSE CAREFULLY - it means two independent *flows*. AsyncLocal flows INTO
    // child tasks, so parallelizing the row loop (Parallel.ForEach, Task.WhenAll over rows) gives
    // every worker the SAME Batch instance, concurrently mutating plain HashSet<int> fields and
    // doing a non-atomic |= on the parent flags. That is a corrupted-hashtable bug, not a
    // lost-update bug, and parallelizing the loop is the most obvious next optimization for an
    // importer running at a few rows per second. If you go there, lock the batch or swap the sets
    // for ConcurrentDictionary<int, byte> first.
    private static readonly AsyncLocal<Batch?> _current = new();

    /// <summary>
    /// Invoked when a subscriber throws during the batch broadcast. Wire this to your logging once
    /// at startup. Leaving it null swallows the failure - which is the right trade for an import
    /// (a bad subscriber must not kill the run) and the wrong one for silence, so wire it up.
    /// </summary>
    public static Action<Exception>? OnBroadcastFailed { get; set; }

    /// <summary>
    /// Opens a batch scope. One per batch, and they do not nest.
    ///
    /// Nesting used to be "supported" here, which meant an inner scope raised its own events and
    /// its ids were never folded into the outer one - the opposite of coalescing, dressed up as a
    /// feature. Rather than half-support it, this throws: a nested Begin() is a bug in the caller,
    /// and finding out at the call site beats finding out from a missing broadcast.
    /// </summary>
    public static IDisposable Begin()
    {
        if (_current.Value is not null)
        {
            throw new InvalidOperationException(
                "A catalog change batch is already open on this flow. Batches do not merge - open " +
                "exactly one per batch.");
        }

        var batch = new Batch();
        _current.Value = batch;
        return batch;
    }

    public static void EntryChanged(int catalogId, int entryId, int nodeId, bool parentChanged)
    {
        var batch = _current.Value;

        // No open scope means no event. This is deliberate - but it is also the trap:
        // a writer called outside Begin() writes rows and tells nobody. If you split the
        // writers out for reuse, make the scope a precondition, not an assumption.
        if (batch is null)
        {
            return;
        }

        Add(batch.CatalogIds, catalogId);
        Add(batch.EntryIds, entryId);
        Add(batch.EntryParentNodeIds, nodeId);
        batch.EntryParentChanged |= parentChanged;
    }

    /// <summary>
    /// For the category writer, which this post does not show. Nothing in the entry writer calls
    /// it - noted so you can tell which paths here are exercised and which are the same shape
    /// waiting for the sibling class.
    /// </summary>
    public static void NodeChanged(int catalogId, int nodeId, bool parentChanged)
    {
        var batch = _current.Value;
        if (batch is null)
        {
            return;
        }

        Add(batch.CatalogIds, catalogId);
        Add(batch.NodeIds, nodeId);
        batch.NodeParentChanged |= parentChanged;
    }

    /// <summary>
    /// Also unused by the writer shown here. Note what does NOT call it: the rollback in
    /// CatalogEntryWriter.Create. That is deliberate - the entry was created and deleted inside
    /// one failed row, nothing downstream ever heard it existed, and announcing a delete for it
    /// would be noise about a row that never logically arrived.
    /// </summary>
    public static void EntryDeleted(int catalogId, int entryId)
    {
        var batch = _current.Value;
        if (batch is null)
        {
            return;
        }

        Add(batch.CatalogIds, catalogId);
        Add(batch.DeletedEntryIds, entryId);
    }

    /// <summary>
    /// Ids come back as 0 from rows that were never persisted. Sets also give us
    /// de-duplication for free: a SKU touched twice in one batch is reported once.
    /// </summary>
    private static void Add(HashSet<int> set, int id)
    {
        if (id > 0)
        {
            set.Add(id);
        }
    }

    private sealed class Batch : IDisposable
    {
        private bool _disposed;

        public HashSet<int> CatalogIds { get; } = new();

        public HashSet<int> NodeIds { get; } = new();

        public HashSet<int> EntryIds { get; } = new();

        public HashSet<int> EntryParentNodeIds { get; } = new();

        public HashSet<int> DeletedEntryIds { get; } = new();

        public bool NodeParentChanged { get; set; }

        public bool EntryParentChanged { get; set; }

        public void Dispose()
        {
            // Disposing twice would re-raise every event. `using` never does this, but Begin()
            // hands out a public IDisposable and callers do surprising things with those.
            if (_disposed)
            {
                return;
            }

            _disposed = true;

            // Clear the slot BEFORE broadcasting, not after. RaiseEvent runs subscriber code
            // synchronously, and a subscriber that writes catalog rows of its own would otherwise
            // either accumulate them into a batch that has already broadcast (lost silently) or
            // call Begin() and hit the "already open" throw. Once we are past the last write,
            // no batch is open as far as anyone else is concerned.
            _current.Value = null;

            // Each raise is isolated. RaiseEvent runs subscriber code synchronously, so one
            // badly-behaved subscriber would otherwise (a) suppress the two broadcasts below it
            // and (b) throw out of Dispose, out of the caller's `using`, and kill an import that
            // has spent three sections of this post learning not to die on one bad row.
            if (NodeIds.Count > 0)
            {
                RaiseSafely(CatalogEventBroadcaster.CatalogNodeUpdatedEventType,
                    NodeIds, Array.Empty<int>(), NodeParentChanged);
            }

            if (EntryIds.Count > 0)
            {
                RaiseSafely(CatalogEventBroadcaster.CatalogEntryUpdatedEventType,
                    EntryParentNodeIds, EntryIds, EntryParentChanged);
            }

            if (DeletedEntryIds.Count > 0)
            {
                RaiseSafely(CatalogEventBroadcaster.CatalogEntryDeletedEventType,
                    Array.Empty<int>(), DeletedEntryIds, hasChangedParent: false);
            }
        }

        private void RaiseSafely(
            string eventType,
            IReadOnlyCollection<int> nodeIds,
            IReadOnlyCollection<int> entryIds,
            bool hasChangedParent)
        {
            try
            {
                Raise(eventType, nodeIds, entryIds, hasChangedParent);
            }
            catch (Exception ex)
            {
                // Guarded too. The post tells you to wire this to your logging, and a logging sink
                // that throws would recreate the exact failure RaiseSafely exists to prevent.
                try { OnBroadcastFailed?.Invoke(ex); }
                catch { /* a failing failure handler is not this class's problem */ }
            }
        }

        private void Raise(
            string eventType,
            IReadOnlyCollection<int> nodeIds,
            IReadOnlyCollection<int> entryIds,
            bool hasChangedParent) =>
            CatalogEventBroadcaster.RaiseEvent(new CatalogContentUpdateEventArgs
            {
                EventType = eventType,

                // Copies, though the properties are IEnumerable<int> and would accept the sets
                // directly. Three allocations per batch - not per row - to avoid handing a
                // subscriber a live reference to collections this class still owns.
                CatalogIds = CatalogIds.ToArray(),
                CatalogNodeIds = nodeIds.ToArray(),
                CatalogEntryIds = entryIds.ToArray(),
                HasChangedParent = hasChangedParent,
            });
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

using Mediachase.Commerce.Catalog.Events;

#nullable enable

namespace CatalogImport;

/// <summary>
/// Collects catalog changes made through the DTO API and raises a single coalesced
/// Commerce event when the scope closes, instead of one event per written row.
///
/// The DTO API raises nothing on your behalf. Without this, either nobody hears about
/// the import at all, or - if you raise per row - a 250,000-row feed turns into 250,000
/// event broadcasts, which on a multi-instance setup is 250,000 Service Bus messages.
/// </summary>
public static class CatalogChangeBatch
{
    // AsyncLocal, not a plain static: the ambient batch follows the logical call stack, so a
    // writer several layers down can report a change without every method signature growing a
    // batch parameter, and two independent imports do not share one batch.
    //
    // READ THAT LAST CLAUSE CAREFULLY - it means two independent *flows*. AsyncLocal flows INTO
    // child tasks, so parallelizing the row loop (Parallel.ForEach, Task.WhenAll over rows) gives
    // every worker the SAME Batch instance, concurrently mutating plain HashSet<int> fields and
    // doing a non-atomic |= on the parent flags. That is a corrupted-hashtable bug, not a
    // lost-update bug, and parallelizing the loop is the most obvious next optimization for an
    // importer running at a few rows per second. If you go there, lock the batch or swap the sets
    // for ConcurrentDictionary<int, byte> first.
    private static readonly AsyncLocal<Batch?> _current = new();

    /// <summary>
    /// Invoked when a subscriber throws during the batch broadcast. Wire this to your logging once
    /// at startup. Leaving it null swallows the failure - which is the right trade for an import
    /// (a bad subscriber must not kill the run) and the wrong one for silence, so wire it up.
    /// </summary>
    public static Action<Exception>? OnBroadcastFailed { get; set; }

    /// <summary>
    /// Opens a batch scope. One per batch, and they do not nest.
    ///
    /// Nesting used to be "supported" here, which meant an inner scope raised its own events and
    /// its ids were never folded into the outer one - the opposite of coalescing, dressed up as a
    /// feature. Rather than half-support it, this throws: a nested Begin() is a bug in the caller,
    /// and finding out at the call site beats finding out from a missing broadcast.
    /// </summary>
    public static IDisposable Begin()
    {
        if (_current.Value is not null)
        {
            throw new InvalidOperationException(
                "A catalog change batch is already open on this flow. Batches do not merge - open " +
                "exactly one per batch.");
        }

        var batch = new Batch();
        _current.Value = batch;
        return batch;
    }

    public static void EntryChanged(int catalogId, int entryId, int nodeId, bool parentChanged)
    {
        var batch = _current.Value;

        // No open scope means no event. This is deliberate - but it is also the trap:
        // a writer called outside Begin() writes rows and tells nobody. If you split the
        // writers out for reuse, make the scope a precondition, not an assumption.
        if (batch is null)
        {
            return;
        }

        Add(batch.CatalogIds, catalogId);
        Add(batch.EntryIds, entryId);
        Add(batch.EntryParentNodeIds, nodeId);
        batch.EntryParentChanged |= parentChanged;
    }

    /// <summary>
    /// For the category writer, which this post does not show. Nothing in the entry writer calls
    /// it - noted so you can tell which paths here are exercised and which are the same shape
    /// waiting for the sibling class.
    /// </summary>
    public static void NodeChanged(int catalogId, int nodeId, bool parentChanged)
    {
        var batch = _current.Value;
        if (batch is null)
        {
            return;
        }

        Add(batch.CatalogIds, catalogId);
        Add(batch.NodeIds, nodeId);
        batch.NodeParentChanged |= parentChanged;
    }

    /// <summary>
    /// Also unused by the writer shown here. Note what does NOT call it: the rollback in
    /// CatalogEntryWriter.Create. That is deliberate - the entry was created and deleted inside
    /// one failed row, nothing downstream ever heard it existed, and announcing a delete for it
    /// would be noise about a row that never logically arrived.
    /// </summary>
    public static void EntryDeleted(int catalogId, int entryId)
    {
        var batch = _current.Value;
        if (batch is null)
        {
            return;
        }

        Add(batch.CatalogIds, catalogId);
        Add(batch.DeletedEntryIds, entryId);
    }

    /// <summary>
    /// Ids come back as 0 from rows that were never persisted. Sets also give us
    /// de-duplication for free: a SKU touched twice in one batch is reported once.
    /// </summary>
    private static void Add(HashSet<int> set, int id)
    {
        if (id > 0)
        {
            set.Add(id);
        }
    }

    private sealed class Batch : IDisposable
    {
        private bool _disposed;

        public HashSet<int> CatalogIds { get; } = new();

        public HashSet<int> NodeIds { get; } = new();

        public HashSet<int> EntryIds { get; } = new();

        public HashSet<int> EntryParentNodeIds { get; } = new();

        public HashSet<int> DeletedEntryIds { get; } = new();

        public bool NodeParentChanged { get; set; }

        public bool EntryParentChanged { get; set; }

        public void Dispose()
        {
            // Disposing twice would re-raise every event. `using` never does this, but Begin()
            // hands out a public IDisposable and callers do surprising things with those.
            if (_disposed)
            {
                return;
            }

            _disposed = true;

            // Clear the slot BEFORE broadcasting, not after. RaiseEvent runs subscriber code
            // synchronously, and a subscriber that writes catalog rows of its own would otherwise
            // either accumulate them into a batch that has already broadcast (lost silently) or
            // call Begin() and hit the "already open" throw. Once we are past the last write,
            // no batch is open as far as anyone else is concerned.
            _current.Value = null;

            // Each raise is isolated. RaiseEvent runs subscriber code synchronously, so one
            // badly-behaved subscriber would otherwise (a) suppress the two broadcasts below it
            // and (b) throw out of Dispose, out of the caller's `using`, and kill an import that
            // has spent three sections of this post learning not to die on one bad row.
            if (NodeIds.Count > 0)
            {
                RaiseSafely(CatalogEventBroadcaster.CatalogNodeUpdatedEventType,
                    NodeIds, Array.Empty<int>(), NodeParentChanged);
            }

            if (EntryIds.Count > 0)
            {
                RaiseSafely(CatalogEventBroadcaster.CatalogEntryUpdatedEventType,
                    EntryParentNodeIds, EntryIds, EntryParentChanged);
            }

            if (DeletedEntryIds.Count > 0)
            {
                RaiseSafely(CatalogEventBroadcaster.CatalogEntryDeletedEventType,
                    Array.Empty<int>(), DeletedEntryIds, hasChangedParent: false);
            }
        }

        private void RaiseSafely(
            string eventType,
            IReadOnlyCollection<int> nodeIds,
            IReadOnlyCollection<int> entryIds,
            bool hasChangedParent)
        {
            try
            {
                Raise(eventType, nodeIds, entryIds, hasChangedParent);
            }
            catch (Exception ex)
            {
                // Guarded too. The post tells you to wire this to your logging, and a logging sink
                // that throws would recreate the exact failure RaiseSafely exists to prevent.
                try { OnBroadcastFailed?.Invoke(ex); }
                catch { /* a failing failure handler is not this class's problem */ }
            }
        }

        private void Raise(
            string eventType,
            IReadOnlyCollection<int> nodeIds,
            IReadOnlyCollection<int> entryIds,
            bool hasChangedParent) =>
            CatalogEventBroadcaster.RaiseEvent(new CatalogContentUpdateEventArgs
            {
                EventType = eventType,

                // Copies, though the properties are IEnumerable<int> and would accept the sets
                // directly. Three allocations per batch - not per row - to avoid handing a
                // subscriber a live reference to collections this class still owns.
                CatalogIds = CatalogIds.ToArray(),
                CatalogNodeIds = nodeIds.ToArray(),
                CatalogEntryIds = entryIds.ToArray(),
                HasChangedParent = hasChangedParent,
            });
    }
}

We open exactly one of these per 500-row batch, in the same scope where we elevate the principal, because the DTO API reads the ambient principal and a scheduled job doesn’t have one.

Here is a simplified excerpt. The full CatalogBulkImporter above also turns a failing Begin() into an abort, stops on result.Aborted, and counts every received row:

var previousPrincipal = _principalAccessor.Principal;
_principalAccessor.Principal = new GenericPrincipal(
    new GenericIdentity(nameof(CatalogBulkImporter)),
    new[] { Roles.Administrators });

try
{
    // An explicit using block, not `using var`. A `using var` disposes at the end of the
    // method - after the finally below has restored the principal - so the broadcast would
    // run unelevated, which is the one thing the elevation exists to prevent.
    using (CatalogChangeBatch.Begin())
    {
        foreach (var row in batch)
        {
            ProcessRow(row, result, observer);
        }
    }
}
finally
{
    _principalAccessor.Principal = previousPrincipal;
}

Key points:

  • HashSet<int> gives us de-duplication for free, so a SKU touched twice in one batch is reported once
  • Without an open scope, the write is announced to nobody
  • Clear the AsyncLocal before broadcasting, every time
  • Reject nested scopes instead of half-supporting them
  • Guard the failure handler, because a logging sink that throws undoes the isolation

The open scope

With no batch open, EntryChanged returns silently and the write is announced to nobody.

I made it that way on purpose, since it keeps the writers usable outside an import, but it is exactly the kind of silence I would expect to cause trouble six months later. If you split the writers out for reuse, make the missing scope loud.

Clearing the AsyncLocal

If a subscriber throws during Dispose and the slot is left pointing at a disposed batch, every later write in that flow goes into an object whose Dispose is already a no-op. Those writes are announced to nobody, permanently.

Clearing the slot only “if we’re still the innermost scope” is exactly how you get there. So Dispose clears the slot first, before it raises anything. A subscriber that writes catalog rows of its own then doesn’t add them to a batch that has already broadcast, and doesn’t hit the “already open” throw from Begin().

Nested scopes

Letting scopes nest and restoring the parent on dispose works against coalescing. The inner scope raises its own broadcast, and its ids are never folded into the outer one.

So wrapping a run in an outer scope would give us one broadcast per inner scope, and nothing from the outer one.

That is why we make Begin() throw if a scope is already open. I would rather not support nesting at all than half-support it.

The failure handler

OnBroadcastFailed is where you wire your logging. A logging sink that throws there would bring back the exact failure the isolation is there to prevent, so the class guards that call too, and a handler that throws is swallowed.

The supporting types

The importer’s own result model, the same types as in the first listing above, as one compilable file:

// ---------------------------------------------------------------------------------------------
// Supporting types for the bulk importer (Part 3).
//
// Requires WriterContracts.cs from Part 2. CatalogBulkImporter reaches into it for
// ProductImportItem, WriteOutcome, ExceptionTree and ICatalogEntryWriter; this file adds only
// the parse-and-report types the importer introduces on its own.
//
// Neither file is needed by the benchmark jobs in Part 5, which are self-contained.
// ---------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;

#nullable enable

namespace CatalogImport;

// ---------------------------------------------------------------------------------------------
// The importer's result model and its side of the job conversation.
// ---------------------------------------------------------------------------------------------

public sealed record ParsedRow<T>(int RowNumber, T? Record, string? Error)
{
    public bool Succeeded => Error is null;
}

public sealed record RejectedRecord(string Identifier, int RowNumber, string Error);

public sealed class ImportSection
{
    /// <summary>
    /// How many rejections are kept in full. The COUNT is always exact; this only bounds the
    /// detail list. Without a cap, a feed that rejects every row retains one object per row for
    /// the whole run - a quarter of a million of them on the file this post is about - and the
    /// summary built from them is unreadable anyway.
    /// </summary>
    public const int MaxRetainedRejections = 1_000;

    private readonly List<RejectedRecord> _rejections = new();

    public int Received { get; private set; }

    public int Accepted { get; private set; }

    public int Rejected { get; private set; }

    public IReadOnlyList<RejectedRecord> Rejections => _rejections;

    /// <summary>True when rejections were dropped from the detail list but still counted.</summary>
    public bool RejectionsTruncated => Rejected > MaxRetainedRejections;

    public void Receive() => Received++;

    public void Accept() => Accepted++;

    public void Reject(string identifier, int rowNumber, string error)
    {
        Rejected++;

        if (_rejections.Count < MaxRetainedRejections)
        {
            _rejections.Add(new RejectedRecord(identifier, rowNumber, error));
        }
    }
}

public sealed class ImportResult
{
    public ImportSection Products { get; } = new();

    public TimeSpan Duration { get; set; }

    /// <summary>
    /// Set when a human pressed Stop. NOT set by an abort - the two are different outcomes and a
    /// consumer that renders "partial run" off this flag alone will render an abort as a complete
    /// one. Check both, or check Received against Accepted + Rejected.
    /// </summary>
    public bool Stopped { get; set; }

    /// <summary>
    /// Set when the run gave up early because the failures stopped looking like bad data and
    /// started looking like a broken dependency.
    ///
    /// Note that this is a FLAG, not an exception. Aborting still has to produce the report -
    /// the counts and the rejections gathered up to this point are the deliverable, and throwing
    /// them away to signal "something went wrong" would defeat the entire point of the design.
    /// </summary>
    public bool Aborted { get; set; }

    public string? AbortReason { get; set; }
}

/// <summary>
/// The job's side of the conversation. Status drives the progress line in the scheduled-jobs UI;
/// Rejected and Info become log entries.
/// </summary>
public interface IImportObserver
{
    bool StopRequested { get; }

    void Status(string message);

    void Rejected(string message);

    void Info(string message);
}
// ---------------------------------------------------------------------------------------------
// Supporting types for the bulk importer (Part 3).
//
// Requires WriterContracts.cs from Part 2. CatalogBulkImporter reaches into it for
// ProductImportItem, WriteOutcome, ExceptionTree and ICatalogEntryWriter; this file adds only
// the parse-and-report types the importer introduces on its own.
//
// Neither file is needed by the benchmark jobs in Part 5, which are self-contained.
// ---------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;

#nullable enable

namespace CatalogImport;

// ---------------------------------------------------------------------------------------------
// The importer's result model and its side of the job conversation.
// ---------------------------------------------------------------------------------------------

public sealed record ParsedRow<T>(int RowNumber, T? Record, string? Error)
{
    public bool Succeeded => Error is null;
}

public sealed record RejectedRecord(string Identifier, int RowNumber, string Error);

public sealed class ImportSection
{
    /// <summary>
    /// How many rejections are kept in full. The COUNT is always exact; this only bounds the
    /// detail list. Without a cap, a feed that rejects every row retains one object per row for
    /// the whole run - a quarter of a million of them on the file this post is about - and the
    /// summary built from them is unreadable anyway.
    /// </summary>
    public const int MaxRetainedRejections = 1_000;

    private readonly List<RejectedRecord> _rejections = new();

    public int Received { get; private set; }

    public int Accepted { get; private set; }

    public int Rejected { get; private set; }

    public IReadOnlyList<RejectedRecord> Rejections => _rejections;

    /// <summary>True when rejections were dropped from the detail list but still counted.</summary>
    public bool RejectionsTruncated => Rejected > MaxRetainedRejections;

    public void Receive() => Received++;

    public void Accept() => Accepted++;

    public void Reject(string identifier, int rowNumber, string error)
    {
        Rejected++;

        if (_rejections.Count < MaxRetainedRejections)
        {
            _rejections.Add(new RejectedRecord(identifier, rowNumber, error));
        }
    }
}

public sealed class ImportResult
{
    public ImportSection Products { get; } = new();

    public TimeSpan Duration { get; set; }

    /// <summary>
    /// Set when a human pressed Stop. NOT set by an abort - the two are different outcomes and a
    /// consumer that renders "partial run" off this flag alone will render an abort as a complete
    /// one. Check both, or check Received against Accepted + Rejected.
    /// </summary>
    public bool Stopped { get; set; }

    /// <summary>
    /// Set when the run gave up early because the failures stopped looking like bad data and
    /// started looking like a broken dependency.
    ///
    /// Note that this is a FLAG, not an exception. Aborting still has to produce the report -
    /// the counts and the rejections gathered up to this point are the deliverable, and throwing
    /// them away to signal "something went wrong" would defeat the entire point of the design.
    /// </summary>
    public bool Aborted { get; set; }

    public string? AbortReason { get; set; }
}

/// <summary>
/// The job's side of the conversation. Status drives the progress line in the scheduled-jobs UI;
/// Rejected and Info become log entries.
/// </summary>
public interface IImportObserver
{
    bool StopRequested { get; }

    void Status(string message);

    void Rejected(string message);

    void Info(string message);
}

This one doesn’t build on its own: CatalogBulkImporter also uses ProductImportItem, WriteOutcome, ExceptionTree, and ICatalogEntryWriter, which ship with Part 2. Take all five files across Parts 2 and 3, and they build together against a clean Commerce 15 project.

What’s next?

At this point the import is correct: it writes what it should, survives what it should not, and explains itself afterward.

Unfortunately, it is still far too slow. I measured about five rows a second on a restored production database, which is about 14 and a half hours for our 252,670-row file. Part 4 counts the database round trips behind each row and goes through the four fixes I would apply first.

Summary

A dirty feed is the normal case, so we build the import to finish in spite of one and to explain itself afterward. What does that ask of the design?

  • Three layers of failure with one report shape: a bad CSV row, an anticipated write failure, and an unexpected throw all reach the reader looking the same.
  • We don’t use a transaction for the whole run, because wrapping a batch would let one bad row roll back 499 good ones.
  • Nothing throws out of the run. The per-row catch lets OutOfMemoryException through on purpose, since there is nothing useful to report after one. The counts and the rejections are the point of the run, so even the circuit breaker is a recorded outcome.
  • The row number travels with the rejection, because the writer knows SKUs and whoever fixes the feed knows lines.
  • One coalesced catalog event per batch, since raising one per row would put 250,000 messages on the bus.

That’s it for error handling! Do you handle per-row import failures differently? Let me know in the comments!

Thank you for reading, and stay tuned for Part 4.

This Post is Part of a Series

  • Part 1: Why the DTO API
  • Part 2: The Writer
  • Part 3: Error Handling and Event Batching - (this post)
  • Part 4: Counting Round Trips
  • Part 5: Process Uptime and the Benchmark

Related posts

  • What Mattered More Than the API. Part 5: Process Uptime and the Benchmark (October 2026)
  • The Low-Level API Is Not Automatically Fast. Part 4: Counting Round Trips (October 2026)
  • Writing a Catalog Entry the Low-Level Way. Part 2: The Writer (October 2026)
  • Share on Facebook
  • Tweet
  • Submit to Reddit
  • Share on LinkedIn
  • Send email

Tags

.NET (13) OptiPowerTools (4) OptiPowerTools.Hangfire (2) OptiPowerTools.ScheduledJobsInsights (2) apple silicon (3) application insights (1) arm (3) background jobs (5) benchmark (1) blazor (2) catalog (8) ci (2) commerce (8) database (3) devops (2) docker (1) dxp (1) episerver (21) error handling (1) github (2) hangfire (4) import (5) indexes (1) m1 (3) maintenance (2) memory-optimization (1) nuget (4) open-source (4) optimizely (21) patterns (2) performance (5) pipeline (2) scheduled jobs (9) sonarcloud (1) sonarqube (1) sql server (4) workflow (2)

Stanisław Szołkowski — Platinum Optimizely MVP & .NET engineer. More about me →

LinkedIn · GitHub · Optimizely World

Read more articles · Browse by tag · subscribe via RSS

This site uses Google Analytics to understand which posts are useful. No ads, no tracking across other sites. You can decline and the rest of the page works exactly the same.