Idempotent Imports: Avoiding Duplicate Vouchers

2026-12-05来源 dev.toEnglish

Any import that runs over a network will eventually run twice: the user double-clicks, a timeout fires after the server already saved, or a retry job wakes up. If every run creates new rows, you get duplicate invoices, double stock and wrong ledgers. The fix is to make the import idempotent: running it twice has the same effect as running it once.

1. Give every document a stable external key

The source system must send a key that never changes for that document, for example a GUID created when the bill is saved, or (SourceId, DocumentNumber, FinancialYear). Never use the auto-increment id of the receiving table as the identity.

CREATE TABLE dbo.PurchaseVoucher ( VoucherId INT IDENTITY PRIMARY KEY, ExternalKey UNIQUEIDENTIFIER NOT NULL, SupplierId INT NOT NULL, BillNo NVARCHAR(30) NOT NULL, BillDate DATE NOT NULL, Total DECIMAL(18,2) NOT NULL, PayloadHash BINARY(32) NOT NULL, ImportedOn DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME() ); CREATE UNIQUE INDEX UX_PurchaseVoucher_ExternalKey ON dbo.PurchaseVoucher(ExternalKey); 

The unique index is the real guard. Application checks alone race under concurrency.

2. Upsert, do not insert (C# with Dapper)

public async Task<ImportOutcome> ImportAsync(VoucherDto v, CancellationToken ct) { var hash = SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(v)); await using var con = new SqlConnection(_cs); await con.OpenAsync(ct); await using var tx = (SqlTransaction)await con.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); var existing = await con.QuerySingleOrDefaultAsync<(int Id, byte[] Hash)?>( @"SELECT VoucherId, PayloadHash FROM dbo.PurchaseVoucher WITH (UPDLOCK, HOLDLOCK) WHERE ExternalKey = @k", new { k = v.ExternalKey }, tx); if (existing is { } e && e.Hash.AsSpan().SequenceEqual(hash)) { await tx.CommitAsync(ct); return ImportOutcome.AlreadyImported; // same data, do nothing } if (existing is { } changed) { await ReplaceLinesAsync(con, tx, changed.Id, v, hash, ct); // reverse old stock, write new await tx.CommitAsync(ct); return ImportOutcome.Updated; } await InsertAsync(con, tx, v, hash, ct); await tx.CommitAsync(ct); return ImportOutcome.Created; } 

UPDLOCK, HOLDLOCK takes a key-range lock, so two parallel imports of the same key serialize instead of both inserting. If one still slips through, the unique index throws error 2601/2627: catch it and re-run the lookup.

3. Hash the payload

Storing a hash lets you tell "same document sent again" (skip) from "document corrected at source" (update). Without it, you either ignore real corrections or rewrite rows on every retry.

4. Stock and ledger side effects

Side effects must live in the same transaction as the voucher row. On update, reverse the old stock and ledger lines and write the new ones; do not apply a "difference" calculated in memory, because a retry may have already applied it.

5. Return a clear outcome

Return Created, Updated or AlreadyImported to the caller and log it. Support teams can then answer "did my bill import twice?" from the log instead of from the database.

Checklist

  • Stable external key from the source, unique index on it.
  • Lookup with UPDLOCK, HOLDLOCK inside the transaction.
  • Payload hash to separate retries from corrections.
  • All side effects in the same transaction.
  • Handle 2601/2627 as "someone else imported it first".

I work on Speed Plus 9, a GST billing and ERP app for Indian shops, where automatic purchase import depends on this pattern.

原文:https://www.a8q9.cn/en/article/idempotent-imports-avoiding-duplicate-vouchers-5481ed.html

相关文章