<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
  <title>Nikolay Stanev — Blog</title>
  <subtitle>Software architecture, pragmatic engineering, and justified complexity.</subtitle>
  <link href="https://nstanev.com/blog/feed.xml" rel="self" />
  <link href="https://nstanev.com/" />
  <updated>2026-09-22T00:00:00Z</updated>
  <id>https://nstanev.com/</id>
  <author>
    <name>Nikolay Stanev</name>
  </author>
  <entry>
    <title>A database constraint beats an async validator</title>
    <link href="https://nstanev.com/blog/database-constraint-beats-async-validator/" />
    <updated>2026-09-01T00:00:00Z</updated>
    <id>https://nstanev.com/blog/database-constraint-beats-async-validator/</id>
    <content type="html">&lt;p&gt;Two people sign up with &lt;code&gt;dana@acme.example&lt;/code&gt;, three milliseconds apart. Maybe it&#39;s the same person double-clicking, maybe it&#39;s a retry from a flaky mobile connection. Both requests ask &amp;quot;is this email taken?&amp;quot; Both get &amp;quot;no&amp;quot;. Both rows are saved.&lt;/p&gt;
&lt;p&gt;Your validator was correct both times. The table still has a duplicate.&lt;/p&gt;
&lt;p&gt;Heraclitus, as Plato reports him in the &lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.01.0172:text=Crat.:section=402a&quot;&gt;&lt;em&gt;Cratylus&lt;/em&gt;&lt;/a&gt;, said you can&#39;t step into the same river twice. Your validator looked at the table once, and by the time the insert arrived it was a different table.&lt;/p&gt;
&lt;p&gt;This article shows why a uniqueness check in application code can&#39;t guarantee uniqueness, what to do instead, and what to keep from the validator. Examples use ASP.NET Core, EF Core and PostgreSQL, but the reasoning holds for any stack and any database with unique constraints.&lt;/p&gt;
&lt;video controls=&quot;&quot; preload=&quot;none&quot; playsinline=&quot;&quot; width=&quot;1280&quot; height=&quot;720&quot; poster=&quot;https://nstanev.com/blog/images/constraint-beats-validator-poster.jpg&quot;&gt;
  &lt;source src=&quot;https://nstanev.com/blog/videos/constraint-beats-validator-v2.mp4&quot; type=&quot;video/mp4&quot;&gt;
  &lt;a href=&quot;https://nstanev.com/blog/videos/constraint-beats-validator-v2.mp4&quot;&gt;Watch the 40-second video (MP4)&lt;/a&gt;
&lt;/video&gt;
&lt;p&gt;&lt;em&gt;The whole argument in 40 seconds.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;The version everyone writes first&lt;/h2&gt;
&lt;p&gt;A validator that asks the database whether the email exists:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;sealed&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;RegisterUserValidator&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token type-list&quot;&gt;&lt;span class=&quot;token class-name&quot;&gt;AbstractValidator&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;RegisterUser&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;RegisterUserValidator&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;AppDbContext&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token function&quot;&gt;RuleFor&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;x &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; x&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;NotEmpty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;EmailAddress&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;MustAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
                &lt;span class=&quot;token operator&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Users&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;AnyAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;u &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; u&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Email &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; email&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;WithMessage&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;This email is already registered.&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The handler then trusts the validator and inserts:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; user &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token constructor-invocation class-name&quot;&gt;User&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;command&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Email&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; command&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Name&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Users&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; TypedResults&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Created&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token interpolation-string&quot;&gt;&lt;span class=&quot;token string&quot;&gt;$&quot;/users/&lt;/span&gt;&lt;span class=&quot;token interpolation&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token expression language-csharp&quot;&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Id&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Id&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It passes tests that exercise one request at a time. It works in the demo. It works in production for months, until two requests arrive close enough together.&lt;/p&gt;
&lt;h2&gt;Why it fails&lt;/h2&gt;
&lt;p&gt;The check and the insert are two separate moments, and nothing stops another request from running between them:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/check-then-insert-race.svg&quot; alt=&quot;Timeline of two signups: both checks finish while the table is still empty, then both inserts save a row for the same email.&quot;&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Time&lt;/th&gt;
&lt;th&gt;Request A&lt;/th&gt;
&lt;th&gt;Request B&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;0 ms&lt;/td&gt;
&lt;td&gt;&lt;code&gt;SELECT&lt;/code&gt; email: not found&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1 ms&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;SELECT&lt;/code&gt; email: not found&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2 ms&lt;/td&gt;
&lt;td&gt;&lt;code&gt;INSERT&lt;/code&gt; dana@acme.example&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3 ms&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;INSERT&lt;/code&gt; dana@acme.example&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Both checks see an empty table, because neither insert has happened yet. This is the classic check-then-act race, and it gets more likely exactly when you least want it: retries, double submits, load tests and traffic spikes.&lt;/p&gt;
&lt;p&gt;Two common &amp;quot;fixes&amp;quot; don&#39;t close it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Wrapping the check and the insert in a transaction.&lt;/strong&gt; Under PostgreSQL&#39;s default isolation level, Read Committed, a transaction doesn&#39;t stop another transaction from inserting the same row between your &lt;code&gt;SELECT&lt;/code&gt; and your &lt;code&gt;INSERT&lt;/code&gt;. Serializable isolation would detect it, but then you have to handle serialization failures and retry, which is more machinery than the problem needs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Making the validator faster or caching the lookup.&lt;/strong&gt; That shrinks the window; it doesn&#39;t remove it. A cache can even make it wider.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Juvenal asked the right question in his &lt;a href=&quot;https://www.thelatinlibrary.com/juvenal/6.shtml&quot;&gt;&lt;em&gt;Satires&lt;/em&gt;&lt;/a&gt;: &lt;em&gt;quis custodiet ipsos custodes?&lt;/em&gt;, who will guard the guards themselves? The validator guards the table, but nothing guards the moment between its answer and your insert.&lt;/p&gt;
&lt;p&gt;Only one component can enforce a rule across every writer: the database. So the rule has to live there.&lt;/p&gt;
&lt;h2&gt;The fix: let the database say no&lt;/h2&gt;
&lt;h3&gt;1. Add a unique index&lt;/h3&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;protected&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;override&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;OnModelCreating&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;ModelBuilder&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    b&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;Entity&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;User&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;HasIndex&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;u &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; u&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;IsUnique&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;HasDatabaseName&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;ix_users_email&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The migration produces something like:&lt;/p&gt;
&lt;pre class=&quot;language-sql&quot;&gt;&lt;code class=&quot;language-sql&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;CREATE&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;UNIQUE&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;INDEX&lt;/span&gt; ix_users_email &lt;span class=&quot;token keyword&quot;&gt;ON&lt;/span&gt; users &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now the two rows can&#39;t both be committed, however close together the requests are. PostgreSQL makes the second insert wait for the first transaction. If that one commits, the waiting insert gets a unique violation; if it rolls back, the waiting insert goes through.&lt;/p&gt;
&lt;p&gt;A maxim that goes back to &lt;a href=&quot;https://droitromain.univ-grenoble-alpes.fr/Corpus/CJ8.htm&quot;&gt;Roman law&lt;/a&gt; fits exactly: &lt;em&gt;prior tempore, potior iure&lt;/em&gt;, first in time, stronger in right. A unique index applies it to commits: whichever insert commits first holds the value, and the other is refused. That is not always the request that arrived first.&lt;/p&gt;
&lt;h3&gt;2. Normalise before you store&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;Dana@Acme.example&lt;/code&gt; and &lt;code&gt;dana@acme.example&lt;/code&gt; are different strings, so the index would happily store both. This application treats email addresses as case-insensitive account identifiers: it trims surrounding whitespace and stores a lower-case value, in one place, such as the &lt;code&gt;User&lt;/code&gt; constructor or a value object, before the value reaches the database.&lt;/p&gt;
&lt;p&gt;That is a product decision, not a rule of email. SMTP allows the part before the &lt;code&gt;@&lt;/code&gt; to be case-sensitive, so if you send mail to the address, keep it as the user typed it in a second column. PostgreSQL&#39;s &lt;code&gt;citext&lt;/code&gt; type or a unique index on &lt;code&gt;lower(email)&lt;/code&gt; enforces case-insensitive uniqueness inside the database; neither removes whitespace, so handle that separately.&lt;/p&gt;
&lt;h3&gt;3. Turn the violation into a clear answer&lt;/h3&gt;
&lt;p&gt;Without this step the client gets a 500. With Npgsql, a unique violation arrives as a &lt;code&gt;DbUpdateException&lt;/code&gt; wrapping a &lt;code&gt;PostgresException&lt;/code&gt; with SQL state &lt;code&gt;23505&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;try&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;catch&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;DbUpdateException&lt;/span&gt; ex&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;when&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ex&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;InnerException &lt;span class=&quot;token keyword&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;PostgresException&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    SqlState&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; PostgresErrorCodes&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;UniqueViolation&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token named-parameter punctuation&quot;&gt;ConstraintName&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;ix_users_email&quot;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; TypedResults&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Problem&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;token named-parameter punctuation&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;Email already registered&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;token named-parameter punctuation&quot;&gt;detail&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;An account with this email already exists.&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;token named-parameter punctuation&quot;&gt;statusCode&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; StatusCodes&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Status409Conflict&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Checking &lt;code&gt;ConstraintName&lt;/code&gt; matters once a table has more than one unique index: a clash on a different column deserves a different message. On SQL Server the same check looks at &lt;code&gt;SqlException.Number&lt;/code&gt; 2601 or 2627. If you&#39;d rather not write this per database, the &lt;code&gt;EntityFrameworkCore.Exceptions&lt;/code&gt; packages translate provider errors into a common &lt;code&gt;UniqueConstraintException&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Why 409 and not 400 or 422? The request is well formed and valid on its own; it conflicts with the current state of the server. That&#39;s what 409 Conflict is for. Retrying the request unchanged won&#39;t help while that state stays the same.&lt;/p&gt;
&lt;h2&gt;Keep the validator, change its job&lt;/h2&gt;
&lt;p&gt;You don&#39;t have to delete the async check. It gives a nicer message in the common case, for example on a signup form that checks the email as the user types. Just be clear about what it is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The validator is a convenience.&lt;/strong&gt; It catches most duplicates early, with a friendly message, and it can be wrong.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The constraint is the guarantee.&lt;/strong&gt; It catches every duplicate, including the ones that slip past the validator.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The handler is the translator.&lt;/strong&gt; It turns the constraint&#39;s error into a 409. A validation failure is normally a 400, so for the client to see one consistent answer, the endpoint has to answer the validator&#39;s &amp;quot;already registered&amp;quot; failure with 409 as well. The companion sample does that by giving that rule its own error code and checking for it.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If the pre-check costs a database round trip on every request and the form doesn&#39;t need live feedback, drop it. The constraint alone is enough for correctness, and you skip a query. Leave format rules (not empty, valid email, maximum length) in the validator: those depend only on the request, so there&#39;s no race.&lt;/p&gt;
&lt;h2&gt;When one unique index isn&#39;t enough&lt;/h2&gt;
&lt;p&gt;Real rules are rarely &amp;quot;this column is unique everywhere&amp;quot;. Most of them still fit in the database:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Rule&lt;/th&gt;
&lt;th&gt;Database tool&lt;/th&gt;
&lt;th&gt;EF Core / SQL&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Email unique per tenant&lt;/td&gt;
&lt;td&gt;Composite unique index&lt;/td&gt;
&lt;td&gt;&lt;code&gt;HasIndex(u =&amp;gt; new { u.TenantId, u.Email }).IsUnique()&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Unique among active rows only (soft delete)&lt;/td&gt;
&lt;td&gt;Filtered (partial) unique index&lt;/td&gt;
&lt;td&gt;&lt;code&gt;.IsUnique().HasFilter(&amp;quot;deleted_at IS NULL&amp;quot;)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;One active subscription per customer&lt;/td&gt;
&lt;td&gt;Partial unique index on the status&lt;/td&gt;
&lt;td&gt;&lt;code&gt;CREATE UNIQUE INDEX ... ON subscriptions (customer_id) WHERE status = &#39;active&#39;&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;No overlapping bookings for a room&lt;/td&gt;
&lt;td&gt;Exclusion constraint&lt;/td&gt;
&lt;td&gt;&lt;code&gt;EXCLUDE USING gist (room_id WITH =, during WITH &amp;amp;&amp;amp;)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;A rule no constraint can express&lt;/td&gt;
&lt;td&gt;Advisory lock or &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt; on a parent row&lt;/td&gt;
&lt;td&gt;Serialise the check and the write for that one key&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The last row is the escape hatch, not the default. A lock makes the check-then-act safe by forcing requests for the same key to queue, but you now own the lock&#39;s scope, timeouts and deadlocks. Reach for it only when the rule genuinely can&#39;t be written as a constraint.&lt;/p&gt;
&lt;p&gt;One more option for inserts that may legitimately repeat, such as importing the same record twice: &lt;code&gt;INSERT ... ON CONFLICT DO NOTHING&lt;/code&gt; (or &lt;code&gt;DO UPDATE&lt;/code&gt;). That turns the duplicate into a no-op instead of an error, which is the right behaviour for idempotent writes and the wrong one for a signup, where the user needs to know.&lt;/p&gt;
&lt;h2&gt;The rule&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Validate shape in code.&lt;/strong&gt; Format, length and required fields depend only on the request, so a validator can decide them alone.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Enforce uniqueness in the database.&lt;/strong&gt; A unique index, not a lookup. It&#39;s the only place that can enforce the rule across every writer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Turn the violation into a 409.&lt;/strong&gt; Catch the specific constraint, return Problem Details, and keep the friendly pre-check only as a convenience.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The general version applies well beyond emails: every invariant you care about should have exactly one place that can&#39;t be bypassed. &lt;a href=&quot;https://archive.org/stream/pappialexandrin04pappgoog/pappialexandrin04pappgoog_djvu.txt&quot;&gt;Pappus of Alexandria&lt;/a&gt; records Archimedes saying &amp;quot;give me a place to stand, and I will move the earth&amp;quot;. Your invariants need the same thing, one fixed place to stand, and for data shared between requests that place is almost always the database.&lt;/p&gt;
&lt;h2&gt;Run it yourself&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/constraint-beats-validator&quot;&gt;companion sample&lt;/a&gt; is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. It exposes the same signup twice: &lt;code&gt;POST /naive/users&lt;/code&gt;, guarded only by the async validator, and &lt;code&gt;POST /users&lt;/code&gt;, guarded by the unique index. A small client fires 20 concurrent signups for the same email at each one, with a fresh address on every run so you can repeat it.&lt;/p&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose up &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;--build&lt;/span&gt;
&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose run &lt;span class=&quot;token parameter variable&quot;&gt;--rm&lt;/span&gt; race&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The API and the race client both run in containers alongside PostgreSQL, so Docker is the only thing you need installed. The README also shows how to run the API with the .NET SDK against the same database container.&lt;/p&gt;
&lt;p&gt;One run on my machine:&lt;/p&gt;
&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;POST /naive/users  20 concurrent signups for dana+9acca3dd@acme.example: 18 x 201, 2 x 409
POST /users        20 concurrent signups for dana+9acca3dd@acme.example: 1 x 201, 19 x 409&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Eighteen accounts for one email on the naive endpoint, exactly one on the constrained endpoint. The naive numbers change from run to run. The constrained ones stay at one 201 and nineteen 409s as long as every request completes, because the address is new and only one insert can commit. The client adds a 30 ms delay between check and insert on both endpoints to stand in for real work, so the race shows up every time instead of once a month in production.&lt;/p&gt;
&lt;h2&gt;Further reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/ef/core/modeling/indexes&quot;&gt;EF Core: indexes, including unique and filtered indexes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/ddl-constraints.html&quot;&gt;PostgreSQL: constraints, including unique and exclusion constraints&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/transaction-iso.html&quot;&gt;PostgreSQL: transaction isolation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.fluentvalidation.net/en/latest/async.html&quot;&gt;FluentValidation: asynchronous validation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9110#name-409-conflict&quot;&gt;RFC 9110: 409 Conflict&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9457&quot;&gt;RFC 9457: Problem Details for HTTP APIs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;p&gt;This article is part of &lt;em&gt;Justified Complexity: Building Backends One Decision at a Time&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Updated 2026-11-11: corrected the description of how a unique index resolves competing inserts (it does not guarantee that the first request wins), stated that lower-casing emails is this application&#39;s policy, clarified what &lt;code&gt;citext&lt;/code&gt; and &lt;code&gt;lower(email)&lt;/code&gt; cover, and explained how the validator&#39;s duplicate becomes a 409. The companion sample now handles a missing email without an error, and its race client can be rerun. The classical references now link to their sources, and the maxim &lt;em&gt;prior tempore, potior iure&lt;/em&gt; is described as going back to Roman law, where it began as a ruling on competing pledges.&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>400 or 422?</title>
    <link href="https://nstanev.com/blog/400-or-422/" />
    <updated>2026-09-04T00:00:00Z</updated>
    <id>https://nstanev.com/blog/400-or-422/</id>
    <content type="html">&lt;p&gt;A signup form sends &lt;code&gt;{&amp;quot;email&amp;quot;: &amp;quot;not-an-email&amp;quot;}&lt;/code&gt;. One endpoint of your API answers 400. Another, written by a colleague a year later, answers 422 for the same mistake. A third answers 400 with a bare string where the others send JSON. Someone opens a pull request to tidy this up, and the review turns into a debate where every comment cites an RFC.&lt;/p&gt;
&lt;p&gt;Both sides can cite one, which is why the debate never ends.&lt;/p&gt;
&lt;p&gt;This article gives you a policy you can adopt in an afternoon: three status codes, one question for each, and one place in the code that applies them. Examples use ASP.NET Core minimal APIs, but the reasoning holds for any stack.&lt;/p&gt;
&lt;h2&gt;The version everyone writes first&lt;/h2&gt;
&lt;p&gt;Nobody decides, so every endpoint decides for itself:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;// Endpoint 1: the framework default&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; Results&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ValidationProblem&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;result&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToDictionary&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;              &lt;span class=&quot;token comment&quot;&gt;// 400, Problem Details&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// Endpoint 2: written after reading about 422&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; Results&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;UnprocessableEntity&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; error &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;Invalid email&quot;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;  &lt;span class=&quot;token comment&quot;&gt;// 422, custom JSON&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// Endpoint 3: written in a hurry&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; Results&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;BadRequest&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Email already registered&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;                &lt;span class=&quot;token comment&quot;&gt;// 400, a bare string&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each line is reasonable on its own. Each one passed review, because the reviewer was looking at one endpoint.&lt;/p&gt;
&lt;h2&gt;Why it fails&lt;/h2&gt;
&lt;p&gt;Look at the API from the client&#39;s side:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Endpoint&lt;/th&gt;
&lt;th&gt;What went wrong&lt;/th&gt;
&lt;th&gt;Status&lt;/th&gt;
&lt;th&gt;Body&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;POST /users&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Email has no &lt;code&gt;@&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;400&lt;/td&gt;
&lt;td&gt;Problem Details with &lt;code&gt;errors&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;POST /invites&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Email has no &lt;code&gt;@&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;422&lt;/td&gt;
&lt;td&gt;&lt;code&gt;{ &amp;quot;error&amp;quot;: &amp;quot;...&amp;quot; }&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;POST /teams&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Name already taken&lt;/td&gt;
&lt;td&gt;400&lt;/td&gt;
&lt;td&gt;&lt;code&gt;&amp;quot;Name already taken&amp;quot;&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The client can&#39;t write one error handler. It needs a branch per endpoint, and each branch is a guess that breaks when the endpoint changes. &lt;a href=&quot;https://penelope.uchicago.edu/Thayer/E/Roman/Texts/Tacitus/Annals/3B%2A.html&quot;&gt;Tacitus&lt;/a&gt; wrote of the late Roman Republic: &lt;em&gt;corruptissima re publica plurimae leges&lt;/em&gt;, the more corrupt the state, the more numerous its laws. A client with a special case for every endpoint is talking to an API that never decided.&lt;/p&gt;
&lt;p&gt;The standards won&#39;t decide for you either:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;400 Bad Request&lt;/strong&gt; started as &amp;quot;the syntax is wrong&amp;quot;. Current HTTP semantics define it broadly, as anything the server perceives as a client error; that wording dates from RFC 7231 in 2014, and RFC 9110 kept it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;422 Unprocessable Content&lt;/strong&gt; came from WebDAV and joined core HTTP in 2022. It covers a request whose syntax is correct but whose instructions the server can&#39;t process.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A mistyped email fits both descriptions. Ecosystems picked differently: the GitHub REST API, Rails and FastAPI answer validation errors with 422. ASP.NET Core answers them with 400, in every place it validates for you: &lt;code&gt;[ApiController]&lt;/code&gt; model validation, &lt;code&gt;Results.ValidationProblem&lt;/code&gt;, and the built-in minimal API validation in .NET 10.&lt;/p&gt;
&lt;p&gt;So the question &amp;quot;which one is correct?&amp;quot; has no answer. The useful question is different: what can the client do with the code?&lt;/p&gt;
&lt;h2&gt;The fix: three codes, three questions&lt;/h2&gt;
&lt;p&gt;A status code earns its place only if the client reacts differently to it. For a refused write, there are three different reactions, so there are three codes. Ask the questions in order and stop at the first yes:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Could someone holding only the API documentation see that this request is wrong?&lt;/strong&gt; Then it&#39;s a &lt;strong&gt;400&lt;/strong&gt;. Broken JSON, a missing field, an email without &lt;code&gt;@&lt;/code&gt;, a name over the maximum length.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is the request fine, but the resource is already in a state that rules it out?&lt;/strong&gt; Then it&#39;s a &lt;strong&gt;409&lt;/strong&gt;. The email is already registered, the order has already shipped, the record changed since the client read it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is the request fine, and a business rule refuses it?&lt;/strong&gt; Then it&#39;s a &lt;strong&gt;422&lt;/strong&gt;. Signups are closed for this domain, the transfer is above the daily limit.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/status-code-three-questions.svg&quot; alt=&quot;Three questions asked in order: wrong by the API documentation alone gives 400, ruled out by the current state gives 409, refused by a business rule gives 422.&quot;&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Code&lt;/th&gt;
&lt;th&gt;Who is &amp;quot;wrong&amp;quot;&lt;/th&gt;
&lt;th&gt;What the client does&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;400&lt;/td&gt;
&lt;td&gt;The request, by the contract&lt;/td&gt;
&lt;td&gt;Fix the request. Show the field errors next to the fields.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;409&lt;/td&gt;
&lt;td&gt;Nobody; the state got there first&lt;/td&gt;
&lt;td&gt;Reload the current state and show it.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;422&lt;/td&gt;
&lt;td&gt;Nobody; the business says no&lt;/td&gt;
&lt;td&gt;Show the rule&#39;s message.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;For both 409 and 422, retrying the request unchanged won&#39;t help while the relevant state stays the same. Whether it helps later depends on the specific problem: an email stays taken, a daily limit resets at midnight. That level of detail belongs to the &lt;code&gt;type&lt;/code&gt; described below, not to the status code.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://droitromain.univ-grenoble-alpes.fr/Anglica/D1_Scott.htm&quot;&gt;Ulpian&lt;/a&gt; summed up Roman law in three precepts, and the third is the one that applies here: &lt;em&gt;suum cuique tribuere&lt;/em&gt;, give each his own. Each kind of failure gets its own code, and no failure gets two.&lt;/p&gt;
&lt;h3&gt;Why 400 for validation, on .NET&lt;/h3&gt;
&lt;p&gt;Choosing 422 for validation errors is a legitimate policy, and several widely used frameworks choose it. On ASP.NET Core it means overriding the default in every place the framework validates, and the one you miss brings the mix back. Staying with 400 costs nothing and matches what .NET clients and tools already expect.&lt;/p&gt;
&lt;p&gt;If your API already answers validation errors with 422 everywhere, keep it. Consistency is the goal; the number is secondary.&lt;/p&gt;
&lt;h3&gt;The border between 409 and 422&lt;/h3&gt;
&lt;p&gt;This border is not sharp. A seat limit on a plan is a business rule, but it&#39;s also state: delete a user and the same request succeeds. The Greeks had a paradox for this, &lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.01.0258:book=2:chapter=10&quot;&gt;attributed to Eubulides of Miletus&lt;/a&gt;: one grain of sand is not a heap, adding one grain never turns a non-heap into a heap, and yet heaps exist. You won&#39;t find the exact grain where a conflict becomes a refusal.&lt;/p&gt;
&lt;p&gt;A rule of thumb gets most cases right. If the honest message starts with &amp;quot;it already…&amp;quot; (exists, shipped, changed), use 409. If it starts with &amp;quot;you may not…&amp;quot;, use 422. For the rest, decide once per error, write the decision down, and move on. The next two sections keep the cost of a borderline decision small.&lt;/p&gt;
&lt;h3&gt;One catalogue applies the policy&lt;/h3&gt;
&lt;p&gt;The policy lives in one file. Endpoints pick an error; they never pick a number:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;// The whole status code policy: three kinds of failure, three codes.&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;enum&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;ErrorKind&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    Invalid &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;400&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;token comment&quot;&gt;// wrong according to the API contract: fix the request&lt;/span&gt;
    Conflict &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;409&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// fine on its own, but the resource&#39;s current state says no&lt;/span&gt;
    Refused &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;422&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;token comment&quot;&gt;// fine on its own, but a business rule says no&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// One entry in the error catalogue. Code is the stable part clients may branch on.&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;sealed&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;record&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Error&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;/span&gt; Code&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;ErrorKind&lt;/span&gt; Kind&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;/span&gt; Title&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;/span&gt; BaseUri &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;https://errors.acme.example/&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;/span&gt; Type &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; BaseUri &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; Code&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;IResult&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;ToProblem&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;?&lt;/span&gt;&lt;/span&gt; detail &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
        Results&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Problem&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token named-parameter punctuation&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; Type&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token named-parameter punctuation&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; Title&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token named-parameter punctuation&quot;&gt;detail&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; detail&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token named-parameter punctuation&quot;&gt;statusCode&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;Kind&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Errors&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Error&lt;/span&gt; ValidationFailed &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;validation-failed&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ErrorKind&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Invalid&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;One or more fields are invalid&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Error&lt;/span&gt; EmailTaken &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;email-taken&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ErrorKind&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Conflict&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;Email already registered&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Error&lt;/span&gt; SignupDomainClosed &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;signup-domain-closed&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ErrorKind&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Refused&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;Signups are closed for this domain&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token comment&quot;&gt;// Field errors keep the &quot;errors&quot; member that ASP.NET Core clients already know.&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;IResult&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;Validation&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;IDictionary&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; errors&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
        Results&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ValidationProblem&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
            errors&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;token named-parameter punctuation&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; ValidationFailed&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Type&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;token named-parameter punctuation&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; ValidationFailed&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Title&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;token named-parameter punctuation&quot;&gt;statusCode&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;ValidationFailed&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Kind&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The signup endpoint now asks the three questions, the third before the second:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; result &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; validator&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ValidateAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;signup&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;!&lt;/span&gt;result&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;IsValid&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; Errors&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Validation&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;result&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToDictionary&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// 400: the contract says this request is wrong&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; email &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Email&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Normalize&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;signup&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; domain &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Email&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;DomainOf&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;closedDomains&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Contains&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;domain&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// 422: a valid request that a business rule refuses&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; Errors&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;SignupDomainClosed&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToProblem&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;token interpolation-string&quot;&gt;&lt;span class=&quot;token string&quot;&gt;$&quot;Accounts for &lt;/span&gt;&lt;span class=&quot;token interpolation&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token expression language-csharp&quot;&gt;domain&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt; are created by the organisation&#39;s administrator.&quot;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Users&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token constructor-invocation class-name&quot;&gt;User&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; Email &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; email &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;try&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;catch&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;DbUpdateException&lt;/span&gt; ex&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;when&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ex&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;InnerException &lt;span class=&quot;token keyword&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;PostgresException&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    SqlState&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; PostgresErrorCodes&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;UniqueViolation&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token named-parameter punctuation&quot;&gt;ConstraintName&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; AppDb&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;UsersEmailIndex
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// 409: a valid request that the current state of the table refuses&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; Errors&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;EmailTaken&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToProblem&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;An account with this email already exists.&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The questions classify a failure; they don&#39;t fix the order of the checks. A signup for a closed domain, with an address that is already registered, fails both ways, and the API has to decide which answer it gives. This one checks the domain rule first: it needs no database round trip, and the refusal holds whether or not the address exists. Whatever precedence you choose, write it down next to the catalogue.&lt;/p&gt;
&lt;p&gt;The domain rule is also only as good as the validation before it. FluentValidation&#39;s &lt;code&gt;EmailAddress()&lt;/code&gt; deliberately checks little more than the presence of an &lt;code&gt;@&lt;/code&gt;, so &lt;code&gt;dana@ corp.example&lt;/code&gt; passes it, and its &amp;quot;domain&amp;quot; starts with a space and misses the closed list. The sample&#39;s validator therefore defines the syntax this API accepts (one &lt;code&gt;@&lt;/code&gt;, no whitespace, a dot in the domain) before any rule reads the domain.&lt;/p&gt;
&lt;p&gt;A reviewer who disagrees with a status code now has one line to change, in the catalogue, and the change applies everywhere that error is returned.&lt;/p&gt;
&lt;h3&gt;The &lt;code&gt;type&lt;/code&gt; is the contract&lt;/h3&gt;
&lt;p&gt;Every response is Problem Details (RFC 9457), and every error has its own &lt;code&gt;type&lt;/code&gt;. These are the sample&#39;s real responses, with the trace ID removed:&lt;/p&gt;
&lt;pre class=&quot;language-http&quot;&gt;&lt;code class=&quot;language-http&quot;&gt;&lt;span class=&quot;token response-status&quot;&gt;&lt;span class=&quot;token http-version property&quot;&gt;HTTP/1.1&lt;/span&gt; &lt;span class=&quot;token status-code number&quot;&gt;400&lt;/span&gt; &lt;span class=&quot;token reason-phrase string&quot;&gt;Bad Request&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;Content-Type&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;application/problem+json&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token application-json&quot;&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;type&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;https://errors.acme.example/validation-failed&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;title&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;One or more fields are invalid&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;status&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;400&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;errors&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;Email&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;&#39;Email&#39; must look like name@example.com, with no spaces.&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-http&quot;&gt;&lt;code class=&quot;language-http&quot;&gt;&lt;span class=&quot;token response-status&quot;&gt;&lt;span class=&quot;token http-version property&quot;&gt;HTTP/1.1&lt;/span&gt; &lt;span class=&quot;token status-code number&quot;&gt;422&lt;/span&gt; &lt;span class=&quot;token reason-phrase string&quot;&gt;Unprocessable Entity&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;Content-Type&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;application/problem+json&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token application-json&quot;&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;type&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;https://errors.acme.example/signup-domain-closed&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;title&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Signups are closed for this domain&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;status&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;422&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;detail&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Accounts for corp.example are created by the organisation&#39;s administrator.&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-http&quot;&gt;&lt;code class=&quot;language-http&quot;&gt;&lt;span class=&quot;token response-status&quot;&gt;&lt;span class=&quot;token http-version property&quot;&gt;HTTP/1.1&lt;/span&gt; &lt;span class=&quot;token status-code number&quot;&gt;409&lt;/span&gt; &lt;span class=&quot;token reason-phrase string&quot;&gt;Conflict&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;Content-Type&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;application/problem+json&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token application-json&quot;&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;type&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;https://errors.acme.example/email-taken&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;title&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Email already registered&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;status&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;409&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;detail&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;An account with this email already exists.&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The two parts do different jobs:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The status code is the coarse class.&lt;/strong&gt; Generic code uses it: retry policies, monitoring, API gateways, a client&#39;s fallback handler.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The &lt;code&gt;type&lt;/code&gt; is the precise answer.&lt;/strong&gt; A client that needs to treat &amp;quot;email taken&amp;quot; specially branches on &lt;code&gt;email-taken&lt;/code&gt;, and never on 409 versus 422.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That limits the cost of a borderline 409-or-422 decision. If you later move the seat limit from one to the other, clients that dispatch only on &lt;code&gt;type&lt;/code&gt; keep their handling. Everything that reads the status code can still be affected, so the change needs a compatibility review, as the last section says.&lt;/p&gt;
&lt;p&gt;Two details from the output above:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Kestrel still labels 422 with the old reason phrase, &amp;quot;Unprocessable Entity&amp;quot;; RFC 9110 renamed it &amp;quot;Unprocessable Content&amp;quot;. Clients must ignore the phrase, and HTTP/2 doesn&#39;t send one.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;type&lt;/code&gt; URIs don&#39;t have to resolve. If you do publish a page per error, the catalogue is your table of contents.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Failures your code never sees&lt;/h3&gt;
&lt;p&gt;Broken JSON never reaches the endpoint; the framework rejects it during binding. A few lines give those failures the same media type as your own errors:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;builder&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Services&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;AddProblemDetails&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token comment&quot;&gt;// ...&lt;/span&gt;
app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;UseExceptionHandler&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token constructor-invocation class-name&quot;&gt;ExceptionHandlerOptions&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// Keep the status a bad request carries instead of reporting it as a 500.&lt;/span&gt;
    StatusCodeSelector &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; ex &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; ex &lt;span class=&quot;token keyword&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;BadHttpRequestException&lt;/span&gt; bad
        &lt;span class=&quot;token punctuation&quot;&gt;?&lt;/span&gt; bad&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;StatusCode
        &lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; StatusCodes&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Status500InternalServerError&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;UseStatusCodePages&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The selector matters in Development. There, minimal APIs throw a &lt;code&gt;BadHttpRequestException&lt;/code&gt; for a body they can&#39;t bind, and a plain &lt;code&gt;UseExceptionHandler()&lt;/code&gt; reports it as a 500. In Production the framework answers 400 without throwing. With the selector, broken JSON is a 400 in both:&lt;/p&gt;
&lt;pre class=&quot;language-http&quot;&gt;&lt;code class=&quot;language-http&quot;&gt;&lt;span class=&quot;token response-status&quot;&gt;&lt;span class=&quot;token http-version property&quot;&gt;HTTP/1.1&lt;/span&gt; &lt;span class=&quot;token status-code number&quot;&gt;400&lt;/span&gt; &lt;span class=&quot;token reason-phrase string&quot;&gt;Bad Request&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;Content-Type&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;application/problem+json&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token application-json&quot;&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;type&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;https://tools.ietf.org/html/rfc9110#section-15.5.1&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;title&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Bad Request&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;status&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;400&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The same middleware covers unknown routes (404) and unhandled exceptions (500). It gives otherwise empty error responses a Problem Details body when the client accepts JSON. A client that asks only for &lt;code&gt;text/html&lt;/code&gt; gets a plain-text line, and failures that happen outside the application, in a proxy or a load balancer, aren&#39;t covered at all.&lt;/p&gt;
&lt;h2&gt;What stays out of the policy&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;200 with an error in the body.&lt;/strong&gt; Every proxy, monitor and retry policy between you and the client reads the status code first.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A fourth and fifth code for refused writes.&lt;/strong&gt; Other 4xx codes have their own clear jobs (401, 403, 404, 412 for a failed &lt;code&gt;If-Match&lt;/code&gt;, 429). For &amp;quot;the write was refused&amp;quot;, three are enough.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Status codes typed into endpoints.&lt;/strong&gt; A number in an endpoint is a policy decision made by whoever wrote that endpoint.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Changing a code on a published API as a clean-up.&lt;/strong&gt; A client that branches on status will break. Fix the catalogue for new errors, and treat a change to an existing one as a contract change.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;The rule&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;400 when the contract says the request is wrong.&lt;/strong&gt; It&#39;s the ASP.NET Core default; don&#39;t fight it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;409 when the state says no, 422 when a business rule says no.&lt;/strong&gt; Decide once per error, in a catalogue, never per endpoint.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Give every error a stable &lt;code&gt;type&lt;/code&gt;.&lt;/strong&gt; Clients branch on the type; the status code is for everything in between.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Tradition has it that Rome&#39;s first written law, the Twelve Tables, was &lt;a href=&quot;https://penelope.uchicago.edu/Thayer/E/Roman/Texts/Diodorus_Siculus/12B%2A.html&quot;&gt;set up on the Rostra&lt;/a&gt; so that nobody had to guess what the rules were. A status code policy needs the same treatment: short, written down, and in one place where every endpoint can see it. Which number you wrote matters less than the fact that you wrote one.&lt;/p&gt;
&lt;h2&gt;Run it yourself&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/status-code-policy&quot;&gt;companion sample&lt;/a&gt; is a minimal ASP.NET Core API with one endpoint, &lt;code&gt;POST /users&lt;/code&gt;, and the catalogue above. The 409 comes from a unique index, as described in &lt;a href=&quot;https://nstanev.com/blog/database-constraint-beats-async-validator/&quot;&gt;A database constraint beats an async validator&lt;/a&gt;. It runs entirely in Docker, next to PostgreSQL:&lt;/p&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose up &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;--build&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then send one request per question:&lt;/p&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;curl&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;-i&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;-X&lt;/span&gt; POST http://localhost:5081/users &lt;span class=&quot;token parameter variable&quot;&gt;-H&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;Content-Type: application/json&quot;&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&#39;{&quot;email&quot;:&quot;not-an-email&quot;}&#39;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;curl&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;-i&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;-X&lt;/span&gt; POST http://localhost:5081/users &lt;span class=&quot;token parameter variable&quot;&gt;-H&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;Content-Type: application/json&quot;&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&#39;{&quot;email&quot;:&quot;dana@corp.example&quot;}&#39;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;curl&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;-i&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;-X&lt;/span&gt; POST http://localhost:5081/users &lt;span class=&quot;token parameter variable&quot;&gt;-H&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;Content-Type: application/json&quot;&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&#39;{&quot;email&quot;:&quot;dana@acme.example&quot;}&#39;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Run the last one twice: the first call returns 201, the second 409. The closed domains are a setting, &lt;code&gt;Signup:ClosedDomains&lt;/code&gt; in &lt;code&gt;appsettings.json&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Further reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9110#name-400-bad-request&quot;&gt;RFC 9110: 400 Bad Request&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9110#name-409-conflict&quot;&gt;RFC 9110: 409 Conflict&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9110#name-422-unprocessable-content&quot;&gt;RFC 9110: 422 Unprocessable Content&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9457&quot;&gt;RFC 9457: Problem Details for HTTP APIs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/aspnet/core/fundamentals/error-handling-api&quot;&gt;ASP.NET Core: handle errors in APIs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.github.com/rest/using-the-rest-api/troubleshooting-the-rest-api&quot;&gt;GitHub REST API: troubleshooting, including 422 validation errors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://fastapi.tiangolo.com/tutorial/handling-errors/&quot;&gt;FastAPI: handling errors&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;p&gt;This article is part of &lt;em&gt;Justified Complexity: Building Backends One Decision at a Time&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Updated 2026-11-11: malformed JSON returned 500 when the sample ran in Development, and the exception handler now keeps the 400; the sample validates email syntax more strictly before the domain rule; the article now states that the 422 check runs before the 409 one, qualifies the retry guidance and the claim about changing a status code, and dates the broad definition of 400 to RFC 7231. The classical references now link to their sources; the Twelve Tables are said to have been set up on the Rostra, as Diodorus reports, where the article used to say &amp;quot;posted in the Forum&amp;quot;.&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>The duplicate charge</title>
    <link href="https://nstanev.com/blog/the-duplicate-charge/" />
    <updated>2026-09-07T00:00:00Z</updated>
    <id>https://nstanev.com/blog/the-duplicate-charge/</id>
    <content type="html">&lt;p&gt;A customer pays 49.90 for an order from a train. The request leaves the phone, the train enters a tunnel, and the app waits. After ten seconds it gives up and tries again, as it was built to do. The second attempt succeeds and the app shows a receipt.&lt;/p&gt;
&lt;p&gt;The bank statement shows two charges.&lt;/p&gt;
&lt;p&gt;Neither request handler reported a failure. The API received two valid requests and handled both correctly, so both charged the card. The first one succeeded too; only its answer never arrived.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.02.0006:poem=5&quot;&gt;Catullus&lt;/a&gt; asked for a thousand kisses, then a hundred, then another thousand, and proposed to muddle the total so that nobody could know it. A client that retries is in the same position, except it never wanted to lose count. Your API has to keep count for it.&lt;/p&gt;
&lt;p&gt;This article shows why retries lead to duplicate charges unless the operation deduplicates them, how an idempotency key does that, and why the key has to travel all the way to the payment provider. Examples use ASP.NET Core, EF Core and PostgreSQL, but the reasoning holds for any stack.&lt;/p&gt;
&lt;video controls=&quot;&quot; preload=&quot;none&quot; playsinline=&quot;&quot; width=&quot;1280&quot; height=&quot;720&quot; poster=&quot;https://nstanev.com/blog/images/the-duplicate-charge-poster.jpg&quot;&gt;
  &lt;source src=&quot;https://nstanev.com/blog/videos/the-duplicate-charge-v2.mp4&quot; type=&quot;video/mp4&quot;&gt;
  &lt;a href=&quot;https://nstanev.com/blog/videos/the-duplicate-charge-v2.mp4&quot;&gt;Watch the 40-second video (MP4)&lt;/a&gt;
&lt;/video&gt;
&lt;p&gt;&lt;em&gt;The whole argument in 40 seconds.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;The version everyone writes first&lt;/h2&gt;
&lt;p&gt;Charge the card, save the payment, return 201:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;MapPost&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/payments&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;PaymentRequest&lt;/span&gt; request&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;PaymentProvider&lt;/span&gt; provider&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AppDb&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; chargeId &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; provider&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ChargeAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;request&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;OrderId&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; request&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Amount&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; payment &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token constructor-invocation class-name&quot;&gt;Payment&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; OrderId &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; request&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;OrderId&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Amount &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; request&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Amount&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ProviderChargeId &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; chargeId &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Payments&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;payment&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; Results&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Created&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token interpolation-string&quot;&gt;&lt;span class=&quot;token string&quot;&gt;$&quot;/payments/&lt;/span&gt;&lt;span class=&quot;token interpolation&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token expression language-csharp&quot;&gt;payment&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Id&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; payment&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is correct for every request it receives. The problem is that it can&#39;t tell a second payment from a second attempt at the first one.&lt;/p&gt;
&lt;h2&gt;Why it fails&lt;/h2&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/lost-response-two-charges.svg&quot; alt=&quot;Sequence of a payment whose 201 response is lost: the client times out and retries, and the payment provider charges the card a second time.&quot;&gt;&lt;/p&gt;
&lt;p&gt;A timeout tells the client nothing about what happened. Three different stories look identical from its side:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;What happened&lt;/th&gt;
&lt;th&gt;Charged?&lt;/th&gt;
&lt;th&gt;What the client sees&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;The request never reached the API&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Timeout&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The API failed before charging&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Timeout or 500&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The charge succeeded and the response was lost&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Timeout&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The client can&#39;t tell these apart, so it has two choices: give up and maybe lose a sale, or retry and maybe charge twice. Almost everything in a modern system chooses to retry:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;People.&lt;/strong&gt; A spinner that lasts too long gets a second tap.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;HTTP clients.&lt;/strong&gt; The standard resilience handler for &lt;code&gt;HttpClient&lt;/code&gt; in .NET retries failed requests, POST included, unless you turn that off with &lt;code&gt;DisableForUnsafeHttpMethods()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Infrastructure.&lt;/strong&gt; Gateways and load balancers can replay a request to another instance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Message consumers.&lt;/strong&gt; Brokers deliver at least once, so a handler that calls your API will sometimes call it twice.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Retrying is the right reaction to a timeout only when repeating the request is safe. HTTP says which methods are meant to be repeatable: GET, PUT and DELETE are defined as idempotent. POST is not, and &amp;quot;create a payment&amp;quot; is a POST. RFC 9110 tells clients not to retry such a request automatically unless they know it is safe, and many of the retriers above do it anyway.&lt;/p&gt;
&lt;p&gt;Three common fixes don&#39;t close the gap:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Disable the Pay button after the first click.&lt;/strong&gt; That stops one of the four retriers above.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Check for an existing payment for this order before charging.&lt;/strong&gt; This is the check-then-act race from &lt;a href=&quot;https://nstanev.com/blog/database-constraint-beats-async-validator/&quot;&gt;A database constraint beats an async validator&lt;/a&gt;: two attempts can both find nothing. It also blocks orders that are legitimately paid in two parts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Treat the same amount within a minute as a duplicate.&lt;/strong&gt; A guess blocks real payments and misses slow retries.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The server can&#39;t work out whether two identical requests are one intention or two. Only the client knows that, so the client has to say it.&lt;/p&gt;
&lt;h2&gt;The fix: let the client name the payment&lt;/h2&gt;
&lt;p&gt;Roman law &lt;a href=&quot;https://penelope.uchicago.edu/Thayer/E/Roman/Texts/Quintilian/Institutio_Oratoria/7D%2A.html&quot;&gt;barred a second action on the same matter&lt;/a&gt;, a principle later compressed into the maxim &lt;em&gt;ne bis in idem&lt;/em&gt;, not twice for the same thing. A court can only apply it if it can recognise the same matter when it comes back. An idempotency key gives a payment that identity.&lt;/p&gt;
&lt;p&gt;The client generates a unique value for each payment it intends to make, usually a UUID, and sends it in an &lt;code&gt;Idempotency-Key&lt;/code&gt; header. Every retry of that payment carries the same key. A new payment gets a new key.&lt;/p&gt;
&lt;pre class=&quot;language-http&quot;&gt;&lt;code class=&quot;language-http&quot;&gt;POST /payments
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;Content-Type&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;application/json&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;Idempotency-Key&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;0f2b6c1e-8d4a-4f0b-9a57-3c1d2e4f5a6b&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token application-json&quot;&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;orderId&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;order-2001&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;amount&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;49.90&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The header is not a standard yet. The IETF draft that defines it writes the value as a quoted string, &lt;code&gt;Idempotency-Key: &amp;quot;0f2b6c1e-...&amp;quot;&lt;/code&gt;; Stripe and many other APIs take it bare, as above. Pick one convention and document it. The sample accepts both forms as the same key and rejects a request that carries more than one.&lt;/p&gt;
&lt;p&gt;The Greeks had an object for this, the &lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.01.0174:text=Sym.:section=191d&quot;&gt;&lt;em&gt;symbolon&lt;/em&gt;&lt;/a&gt;: a token broken in two when an agreement was made, each party keeping a half. Whoever arrived later with the matching half was speaking about the same agreement. The key is the client&#39;s half, and the server keeps the other.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/idempotency-key-one-charge.svg&quot; alt=&quot;Sequence of a payment sent with an idempotency key: the response is lost, the client retries with the same key, and the API replays the saved 201 without contacting the payment provider.&quot;&gt;&lt;/p&gt;
&lt;p&gt;The server side has three steps.&lt;/p&gt;
&lt;h3&gt;1. Claim the key&lt;/h3&gt;
&lt;p&gt;The API keeps one row per key: the key, a fingerprint of the request, a status and, once the work is done, the response.&lt;/p&gt;
&lt;p&gt;The fingerprint defines what &amp;quot;the same request&amp;quot; means, so choose it deliberately. A hash of the raw body treats &lt;code&gt;49.9&lt;/code&gt; and &lt;code&gt;49.90&lt;/code&gt; as two different payments and turns a harmless retry into an error. The sample validates the request first and then hashes the order id and the amount in cents.&lt;/p&gt;
&lt;p&gt;A lookup followed by an insert would be the same race again. One statement does both, and the primary key decides which request owns the key:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; claimed &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Database&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ExecuteSqlInterpolatedAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token interpolation-string&quot;&gt;&lt;span class=&quot;token string&quot;&gt;$&quot;&quot;&lt;/span&gt;&lt;/span&gt;&quot;
    INSERT &lt;span class=&quot;token return-type class-name&quot;&gt;INTO&lt;/span&gt; idempotency_keys &lt;span class=&quot;token return-type class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;key&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; request_hash&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; status&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; locked_at&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/span&gt;
    VALUES &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;key&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;hash&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &#39;in_progress&#39;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;now&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token return-type class-name&quot;&gt;ON&lt;/span&gt; CONFLICT &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;key&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; DO UPDATE &lt;span class=&quot;token class-name&quot;&gt;SET&lt;/span&gt; locked_at &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;now&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    WHERE idempotency_keys&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;status &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &#39;in_progress&#39;
      AND idempotency_keys&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;request_hash &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;hash&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
      AND idempotency_keys&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;locked_at &lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;staleBefore&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;token string&quot;&gt;&quot;&quot;&lt;/span&gt;&quot;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If the statement changes one row, this request owns the key and does the work. If it changes none, the key belongs to someone else, and the stored row says what to answer:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;The key is&lt;/th&gt;
&lt;th&gt;Answer&lt;/th&gt;
&lt;th&gt;Why&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Missing from the request&lt;/td&gt;
&lt;td&gt;400&lt;/td&gt;
&lt;td&gt;The contract requires it&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;New&lt;/td&gt;
&lt;td&gt;Do the work&lt;/td&gt;
&lt;td&gt;This is the first attempt&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Completed, same request&lt;/td&gt;
&lt;td&gt;The stored response&lt;/td&gt;
&lt;td&gt;This is a retry; the work is done&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;In progress&lt;/td&gt;
&lt;td&gt;409&lt;/td&gt;
&lt;td&gt;The first attempt is still running; try again shortly&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Known, different request&lt;/td&gt;
&lt;td&gt;422&lt;/td&gt;
&lt;td&gt;A key names one payment; this is a client bug&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The three status codes are the ones the IETF draft for the &lt;code&gt;Idempotency-Key&lt;/code&gt; header recommends. Treat them as that draft&#39;s conventions. They don&#39;t all follow from the three questions in &lt;a href=&quot;https://nstanev.com/blog/400-or-422/&quot;&gt;400 or 422?&lt;/a&gt;: a key reused with a different request breaks the documented contract and conflicts with stored state at the same time, and the draft still answers it with 422.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;ON CONFLICT ... WHERE&lt;/code&gt; part handles one more case: a request that claimed the key and then died. Its row stays &lt;code&gt;in_progress&lt;/code&gt; forever unless someone may take it over, so a retry of the same request can do that once the lock is older than a timeout.&lt;/p&gt;
&lt;h3&gt;2. Pass the key to the payment provider&lt;/h3&gt;
&lt;p&gt;This is the step that is easiest to skip and the one the article&#39;s title depends on.&lt;/p&gt;
&lt;p&gt;The API can crash after the provider charged the card and before the payment is saved. The key row is still &lt;code&gt;in_progress&lt;/code&gt;, the retry takes it over after the timeout, and the work runs again. If the second run calls the provider without the key, the card is charged twice, and all the bookkeeping above only made the bug rarer.&lt;/p&gt;
&lt;p&gt;So the key goes downstream:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; providerKey &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token interpolation-string&quot;&gt;&lt;span class=&quot;token string&quot;&gt;$&quot;payments/&lt;/span&gt;&lt;span class=&quot;token interpolation&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token expression language-csharp&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; chargeId &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; provider&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ChargeAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;request&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;OrderId&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; request&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Amount&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; providerKey&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The provider applies the same rule you do: it has seen this key, so it returns the result of the first attempt and doesn&#39;t charge again. Stripe accepts an &lt;code&gt;Idempotency-Key&lt;/code&gt; header for exactly this purpose, and most payment providers have an equivalent.&lt;/p&gt;
&lt;p&gt;The result of the first attempt is not always a successful charge. Three outcomes need different handling:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The charge succeeded and the response was lost.&lt;/strong&gt; The retry gets the original charge back. This is the case the sample shows.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The card was declined.&lt;/strong&gt; That answer is final. Store it and replay it, as you would a success.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The outcome is unknown&lt;/strong&gt;, because the provider timed out or answered with an error. Stripe, for example, replays a stored 500 for the same key. Retry with the same key, and if that doesn&#39;t settle it, ask the provider what happened before you do anything else.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Derive the downstream key from the caller&#39;s scope, the operation and the client&#39;s key, for example &lt;code&gt;{tenant}/payments/{key}&lt;/code&gt;. If two tenants both send the key &lt;code&gt;abc&lt;/code&gt; and you pass it on unchanged to one shared provider account, the provider sees a single operation.&lt;/p&gt;
&lt;p&gt;The general rule: every call with a side effect that sits behind your endpoint needs the key, or a value derived from it, and has to deduplicate on it. A system that ignores the key gains nothing from receiving it. Idempotency doesn&#39;t pass through a call chain by itself.&lt;/p&gt;
&lt;h3&gt;3. Save the payment and the response together&lt;/h3&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Payments&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;payment&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;record&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;IdempotencyKeys&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SingleAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;r &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; r&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Key &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; key&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;record&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Status &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; IdempotencyRecord&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Completed&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;record&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;ResponseStatus &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; StatusCodes&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Status201Created&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;record&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;ResponseBody &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; body&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// one transaction&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The payment row and the completed key row are written in one transaction, so the API can never hold a payment without a stored response or a stored response without a payment.&lt;/p&gt;
&lt;p&gt;A unique index on &lt;code&gt;payments.idempotency_key&lt;/code&gt; is the final guard. If a slow request and a retry that took over its key both reach this point, the index lets one of them save and the other replays the winner&#39;s response.&lt;/p&gt;
&lt;p&gt;A retry now gets the first answer back, marked as a replay:&lt;/p&gt;
&lt;pre class=&quot;language-http&quot;&gt;&lt;code class=&quot;language-http&quot;&gt;&lt;span class=&quot;token response-status&quot;&gt;&lt;span class=&quot;token http-version property&quot;&gt;HTTP/1.1&lt;/span&gt; &lt;span class=&quot;token status-code number&quot;&gt;201&lt;/span&gt; &lt;span class=&quot;token reason-phrase string&quot;&gt;Created&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;Content-Type&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;application/json&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;Idempotent-Replayed&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;true&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token application-json&quot;&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;paymentId&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;01a1c9df-a519-7943-a6ba-243902b58d7d&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;orderId&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;order-2001&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;amount&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;49.90&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token string-property property&quot;&gt;&quot;providerChargeId&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;ch_9&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;What the key table asks of you&lt;/h2&gt;
&lt;p&gt;The table is small, but it comes with decisions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The lock timeout.&lt;/strong&gt; Make it longer than the processing time you expect. There may be no true worst case, so one day a retry will take over a request that is still running. That is still safe here, because the provider deduplicates on the key and the unique index allows one payment, but you pay for the work twice.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Retention.&lt;/strong&gt; Keys can&#39;t be kept forever. Pick a period, delete older rows, and tell clients not to retry after it. Stripe, for example, may remove keys once they are at least 24 hours old.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The provider&#39;s window.&lt;/strong&gt; The provider forgets keys too, and afterwards it treats the same key as a new request. Suppose the API failed after a charge, and a retry takes the key over after the provider has pruned it: the card is charged again. No local index can stop that, because no payment was ever saved. So end automatic recovery well inside the provider&#39;s retention period. After it, reconcile: look the payment up at the provider by a reference you saved with the key before calling it, such as the order id, and only then decide whether to charge.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Scope.&lt;/strong&gt; A key is unique per caller. In a multi-tenant API the primary key is the tenant and the key together, so one customer&#39;s key can never collide with another&#39;s.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Validation comes first.&lt;/strong&gt; Reject a malformed request before claiming the key, so a 400 never uses one up.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No database transaction across the provider call.&lt;/strong&gt; Claim the key in its own statement, call the provider, then save. Holding a transaction open while a remote system thinks ties up a connection for as long as that system takes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;When you don&#39;t need a key table&lt;/h2&gt;
&lt;p&gt;The table is the general answer. Often a smaller one is enough:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Situation&lt;/th&gt;
&lt;th&gt;Smaller answer&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;The resource has a natural unique identity, such as one payment per order&lt;/td&gt;
&lt;td&gt;That identity can name the operation: claim it as you would a key and derive the provider&#39;s key from it. A unique index alone is not enough, because the second request charges the card before its insert fails&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The client can choose the identifier&lt;/td&gt;
&lt;td&gt;&lt;code&gt;PUT /payments/{id}&lt;/code&gt; with a client-generated id, which then plays the role of the key. PUT only promises idempotency; the implementation still has to claim the id and pass it to the provider&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The work only touches your own database&lt;/td&gt;
&lt;td&gt;Insert the key and do the work in one transaction; no &lt;code&gt;in_progress&lt;/code&gt; state is needed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The operation is naturally repeatable, such as &amp;quot;set status to shipped&amp;quot;&lt;/td&gt;
&lt;td&gt;Nothing; write it as an upsert&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Reach for the key table when a POST has a side effect outside your database that must not happen twice. Payments are the clearest case; sending an email or creating a shipment are others.&lt;/p&gt;
&lt;h2&gt;The rule&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;A timeout is not a &amp;quot;no&amp;quot;.&lt;/strong&gt; Clients will retry, whether or not it is safe. Every write that must not happen twice needs a name the client chooses.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Let one unique key decide who does the work.&lt;/strong&gt; Claim it in one statement, store the response, and replay it to every retry.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pass the key to everything behind the endpoint that can deduplicate on it.&lt;/strong&gt; Your API is only as idempotent as the last system it calls.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Roman law did have a remedy for the payment made twice. Gaius records in his &lt;a href=&quot;https://droitromain.univ-grenoble-alpes.fr/Anglica/gai3_Poste.htm&quot;&gt;&lt;em&gt;Institutes&lt;/em&gt;&lt;/a&gt; that whoever receives what was not owed, from someone who paid by mistake, is bound to return it. A refund process is still worth having. It is a poor substitute for charging once.&lt;/p&gt;
&lt;h2&gt;Run it yourself&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/duplicate-charge&quot;&gt;companion sample&lt;/a&gt; is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. It takes the same payment in two ways: &lt;code&gt;POST /naive/payments&lt;/code&gt;, with no key, and &lt;code&gt;POST /payments&lt;/code&gt;, with the key table. The payment provider is faked inside the sample and keeps its own record of charges. A small client plays the customer on the train.&lt;/p&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose up &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;--build&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose run &lt;span class=&quot;token parameter variable&quot;&gt;--rm&lt;/span&gt; demo&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output on my machine:&lt;/p&gt;
&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;1. No key: the client retries a payment of 49.90 five times at once
   POST /naive/payments  5 x 201

2. Same retries, with one Idempotency-Key
   POST /payments        1 x 201, 4 x 409
   retry after it finished: 201 (replayed)
   same amount sent as 49.9: 201 (replayed)

3. The same key with a different amount
   POST /payments        422

4. The request fails after the card is charged, before the payment is saved
   first attempt:        500
   immediate retry:      409
   retry after 2.5 s:    201

What the API saved and what the provider charged (GET /stats):
   order-1001: 5 payment row(s), 5 charge(s), 249.50 charged
   order-1002: 1 payment row(s), 1 charge(s), 49.90 charged
   order-1003: 1 payment row(s), 1 charge(s), 49.90 charged&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Five charges and 249.50 taken for one 49.90 order without the key; one charge with it. Step 4 is the one to study: the request fails after the card is charged, the retry is refused while the first attempt still holds the key, and the next retry finishes the payment without a second charge, because the provider recognised the key.&lt;/p&gt;
&lt;p&gt;The demo has limits. Step 4 fails one request; it doesn&#39;t kill the process. The fake provider always charges successfully and never forgets a key, so declines, unknown outcomes and the provider&#39;s retention window are described above but not simulated.&lt;/p&gt;
&lt;p&gt;The sample&#39;s lock timeout is 2 seconds so that step 4 is quick to watch. The README explains the other switches.&lt;/p&gt;
&lt;h2&gt;Further reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/&quot;&gt;IETF draft: The Idempotency-Key HTTP Header Field&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.stripe.com/api/idempotent_requests&quot;&gt;Stripe API: idempotent requests&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9110#name-idempotent-methods&quot;&gt;RFC 9110: idempotent methods&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/sql-insert.html&quot;&gt;PostgreSQL: INSERT ... ON CONFLICT&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/dotnet/core/resilience/http-resilience&quot;&gt;.NET: build resilient HTTP apps&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;p&gt;This article is part of &lt;em&gt;Justified Complexity: Building Backends One Decision at a Time&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Updated 2026-11-11: the classical references now link to their sources, and the Roman rule behind&lt;/em&gt; ne bis in idem &lt;em&gt;is described more exactly as barring a second action on the same matter.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Updated 2026-11-11, after a review: two shortcuts in &amp;quot;When you don&#39;t need a key table&amp;quot; were wrong, since a unique index or a PUT alone doesn&#39;t stop the second charge, and are corrected. Added the provider&#39;s key retention window, the provider&#39;s other outcomes (declines and unknown results), the definition of the request fingerprint, the header&#39;s syntax, and the scope of the downstream key. The status codes are presented as the IETF draft&#39;s conventions, and &amp;quot;the API crashes&amp;quot; in the demo is now &amp;quot;the request fails&amp;quot;.&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>You don&#39;t need MediatR, but you do need decorators</title>
    <link href="https://nstanev.com/blog/you-dont-need-mediatr/" />
    <updated>2026-09-10T00:00:00Z</updated>
    <id>https://nstanev.com/blog/you-dont-need-mediatr/</id>
    <content type="html">&lt;p&gt;A team decides to stop using MediatR. The pull request is a pleasure to review: the package is gone, every endpoint asks for its handler and calls it, and the diff is mostly red. Sixty handlers, all tests green, three approvals.&lt;/p&gt;
&lt;p&gt;Three weeks later there is an order for -5 widgets in the database, and the warehouse system shows five more widgets than anyone ever delivered.&lt;/p&gt;
&lt;p&gt;Nobody deleted the validation. It was never in the handler. It ran around the handler, and the thing that ran it was removed.&lt;/p&gt;
&lt;p&gt;This article shows what MediatR actually does for you, which half you can drop without loss, and how to keep the other half in about sixty lines with nothing but the built-in container. Examples use ASP.NET Core, EF Core and PostgreSQL, but the reasoning holds for any stack with a mediator library and a dependency injection container.&lt;/p&gt;
&lt;video controls=&quot;&quot; preload=&quot;none&quot; playsinline=&quot;&quot; width=&quot;1280&quot; height=&quot;720&quot; poster=&quot;https://nstanev.com/blog/images/you-dont-need-mediatr-poster.jpg&quot;&gt;
  &lt;source src=&quot;https://nstanev.com/blog/videos/you-dont-need-mediatr-v2.mp4&quot; type=&quot;video/mp4&quot;&gt;
  &lt;a href=&quot;https://nstanev.com/blog/videos/you-dont-need-mediatr-v2.mp4&quot;&gt;Watch the 40-second video (MP4)&lt;/a&gt;
&lt;/video&gt;
&lt;p&gt;&lt;em&gt;The whole argument in 40 seconds.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;The version everyone writes first&lt;/h2&gt;
&lt;p&gt;With MediatR, an endpoint sends a request and something, somewhere, handles it:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;MapPost&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/orders&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;PlaceOrderBody&lt;/span&gt; body&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;ISender&lt;/span&gt; sender&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;Created&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; sender&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Send&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToCommand&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;body&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Without it, the endpoint asks for the handler and calls it:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;MapPost&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/orders&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;PlaceOrderBody&lt;/span&gt; body&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;PlaceOrderHandler&lt;/span&gt; handler&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;Created&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; handler&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;HandleAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToCommand&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;body&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The second version is better in ways you notice on the first day. &amp;quot;Go to definition&amp;quot; on &lt;code&gt;HandleAsync&lt;/code&gt; lands in the handler. With &lt;code&gt;Send&lt;/code&gt;, it lands on an interface inside a library, and you search for the request type to find out who handles it. In the myth as &lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.01.0022:text=Epitome:book=E:chapter=1:section=9&quot;&gt;Apollodorus&lt;/a&gt; tells it, Ariadne gave Theseus a thread to fasten at the door of the labyrinth, so that he could find his way out again. A direct call is that thread. You can always follow it.&lt;/p&gt;
&lt;p&gt;So the change is reasonable, the code is shorter, and the business logic didn&#39;t change by a line.&lt;/p&gt;
&lt;h2&gt;Why it fails&lt;/h2&gt;
&lt;p&gt;MediatR does two separate jobs, and the pull request replaced only one of them.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Job&lt;/th&gt;
&lt;th&gt;What it does&lt;/th&gt;
&lt;th&gt;What the pull request did&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Dispatch&lt;/td&gt;
&lt;td&gt;Finds the handler for a request type at run time&lt;/td&gt;
&lt;td&gt;Replaced it with a direct call&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pipeline&lt;/td&gt;
&lt;td&gt;Runs behaviors around every handler&lt;/td&gt;
&lt;td&gt;Deleted it&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The pipeline was three lines of registration, far from any handler:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;builder&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Services&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;AddMediatR&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;cfg &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    cfg&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;RegisterServicesFromAssemblyContaining&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;PlaceOrder&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    cfg&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;AddOpenBehavior&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;typeof&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token type-expression class-name&quot;&gt;LoggingBehavior&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    cfg&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;AddOpenBehavior&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;typeof&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token type-expression class-name&quot;&gt;ValidationBehavior&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    cfg&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;AddOpenBehavior&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;typeof&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token type-expression class-name&quot;&gt;TransactionBehavior&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When &lt;code&gt;AddMediatR&lt;/code&gt; went, these went with it. The behavior classes may even still be in the repository, compiling happily, called by nothing.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/pipeline-lost-and-restored.svg&quot; alt=&quot;Three columns show the same PlaceOrder handler: under MediatR it is wrapped in logging, validation and a transaction; called directly it runs alone and the three layers are missing; with decorators the three layers wrap it again.&quot;&gt;&lt;/p&gt;
&lt;p&gt;The handler in the companion sample saves an order and then reserves stock, in two writes. Here is what the same two bad requests do before and after the &amp;quot;clean-up&amp;quot;:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Request&lt;/th&gt;
&lt;th&gt;With MediatR&lt;/th&gt;
&lt;th&gt;Handler called directly&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;An order for -5 widgets&lt;/td&gt;
&lt;td&gt;400, nothing saved&lt;/td&gt;
&lt;td&gt;201, order saved, five widgets added to stock&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;An order for an item that is out of stock&lt;/td&gt;
&lt;td&gt;409, nothing saved&lt;/td&gt;
&lt;td&gt;409, but the order row and the widget it had already reserved stay in the database&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The second row is the quieter one. The client gets the right answer, and the database keeps half an order.&lt;/p&gt;
&lt;p&gt;Nothing warned anyone, for two reasons:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The compiler can&#39;t see it.&lt;/strong&gt; Behaviors are open generics, resolved from the container at run time. Removing their registration is not a compile error.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The tests never went through the pipeline.&lt;/strong&gt; A handler&#39;s unit tests call the handler. They passed before and they pass now, because they never covered what the pipeline did.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;a href=&quot;https://penelope.uchicago.edu/Thayer/E/Roman/Texts/Dionysius_of_Halicarnassus/6D%2A.html&quot;&gt;Dionysius of Halicarnassus&lt;/a&gt; records the fable Menenius Agrippa told the Roman plebs when they walked out of the city. The parts of the body turn on the belly: the feet say the whole body rests on them, the hands that they do the work, the shoulders that they bear the burdens, and the belly, as far as they can see, does nothing. They stop serving it, and the whole body starves. MediatR looked like the belly. It sat in the middle and seemed only to pass requests along.&lt;/p&gt;
&lt;h2&gt;The fix: keep the pipeline, drop the dispatcher&lt;/h2&gt;
&lt;p&gt;You need three things: an interface, one small class per cross-cutting job, and one place that puts them together.&lt;/p&gt;
&lt;h3&gt;1. One interface&lt;/h3&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;interface&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;IHandler&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token return-type class-name&quot;&gt;Task&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;HandleAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;TRequest&lt;/span&gt; request&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A handler implements it. An endpoint asks for &lt;code&gt;IHandler&amp;lt;PlaceOrder, OrderPlaced&amp;gt;&lt;/code&gt; and gets whatever the container decides that means.&lt;/p&gt;
&lt;h3&gt;2. One decorator per job&lt;/h3&gt;
&lt;p&gt;A decorator is a handler that wraps another handler. It does one thing and calls the next:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;sealed&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;ValidationDecorator&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;token class-name&quot;&gt;IHandler&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; inner&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token class-name&quot;&gt;IEnumerable&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;IValidator&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; validators&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; IHandler&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;Task&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;HandleAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;TRequest&lt;/span&gt; request&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;foreach&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; validator &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; validators&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; validator&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ValidateAndThrowAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;request&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; inner&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;HandleAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;request&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;sealed&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;TransactionDecorator&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;token class-name&quot;&gt;IHandler&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; inner&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token class-name&quot;&gt;AppDb&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; IHandler&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;Task&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;HandleAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;TRequest&lt;/span&gt; request&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; transaction &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Database&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;BeginTransactionAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; response &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; inner&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;HandleAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;request&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; transaction&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;CommitAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// if the handler throws, disposing rolls back&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; response&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;EF Core already makes a single &lt;code&gt;SaveChangesAsync&lt;/code&gt; atomic. This handler needs an explicit transaction because it does two separate writes, the order and then the stock, and they have to commit or roll back together.&lt;/p&gt;
&lt;p&gt;The logging decorator has the same shape. If you compare each one with the MediatR behavior it replaces, the body is identical. Only the signature differs: &lt;code&gt;inner.HandleAsync(request, ct)&lt;/code&gt; where the behavior had &lt;code&gt;next()&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;3. One place that composes them&lt;/h3&gt;
&lt;p&gt;The built-in container has no method for decorating a registration, so the sample writes the wrapping out in a factory:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;IServiceCollection&lt;/span&gt; &lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;AddHandler&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; THandler&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;IServiceCollection&lt;/span&gt; services&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;where&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;THandler&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token type-list&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;IHandler&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    services&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;AddScoped&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;THandler&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    services&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;AddScoped&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;IHandler&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;sp &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token constructor-invocation class-name&quot;&gt;LoggingDecorator&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token constructor-invocation class-name&quot;&gt;ValidationDecorator&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
                &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token constructor-invocation class-name&quot;&gt;TransactionDecorator&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
                    sp&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;GetRequiredService&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;THandler&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
                    sp&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;GetRequiredService&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;AppDb&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
                sp&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;GetServices&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;IValidator&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
            sp&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;GetRequiredService&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;ILogger&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;LoggingDecorator&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;TRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; TResponse&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; services&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each use case is then one line, and the endpoint asks for the interface:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;builder&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Services&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;AddHandler&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;PlaceOrder&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; OrderPlaced&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; PlaceOrderHandler&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;MapPost&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/orders&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;PlaceOrderBody&lt;/span&gt; body&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;IHandler&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;PlaceOrder&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; OrderPlaced&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; handler&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;Created&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; handler&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;HandleAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToCommand&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;body&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The order of the three is now something you can read: logging on the outside so it sees every outcome, validation next so an invalid request never opens a transaction, the transaction closest to the handler. With MediatR the same order was implied by the sequence of three registration calls.&lt;/p&gt;
&lt;p&gt;With many handlers, the &lt;a href=&quot;https://github.com/khellang/Scrutor&quot;&gt;Scrutor&lt;/a&gt; package does the wrapping for every handler at once, with &lt;code&gt;services.Decorate(typeof(IHandler&amp;lt;,&amp;gt;), typeof(LoggingDecorator&amp;lt;,&amp;gt;))&lt;/code&gt;. Mind the direction: in Scrutor the last &lt;code&gt;Decorate&lt;/code&gt; call is the outermost, while in MediatR the first registered behavior is the outermost.&lt;/p&gt;
&lt;p&gt;&amp;quot;Go to definition&amp;quot; still works. It lands on the interface, and &amp;quot;go to implementation&amp;quot; lists the handler and its three decorators, which is the whole truth about what runs.&lt;/p&gt;
&lt;h2&gt;What decorators ask of you&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A handler reached by its concrete type skips them.&lt;/strong&gt; The broken endpoint above injects &lt;code&gt;PlaceOrderHandler&lt;/code&gt;; the fixed one injects &lt;code&gt;IHandler&amp;lt;PlaceOrder, OrderPlaced&amp;gt;&lt;/code&gt;. That is one type in a parameter list. Add a test that fails when an endpoint depends on a concrete handler, or it will happen again.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not every handler wants every decorator.&lt;/strong&gt; Most queries don&#39;t need a transaction. Split the interface into &lt;code&gt;ICommandHandler&lt;/code&gt; and &lt;code&gt;IQueryHandler&lt;/code&gt;, or let the decorator check for a marker interface on the request.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Failures need one translator.&lt;/strong&gt; These decorators throw. One &lt;code&gt;IExceptionHandler&lt;/code&gt; turns a validation failure into a 400 and an out-of-stock failure into a 409, following the policy in &lt;a href=&quot;https://nstanev.com/blog/400-or-422/&quot;&gt;400 or 422?&lt;/a&gt;. If you prefer result types over exceptions, the validation decorator returns a failed result without calling the next handler, and the transaction decorator has to roll back when it gets a failed result back. As written, it commits whenever the handler returns. The composition stays the same.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Order is your decision now.&lt;/strong&gt; Write it in one place and comment why. Two registrations that wrap in different orders by accident are a bug that only shows under failure.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;This transaction decorator has limits.&lt;/strong&gt; It assumes a top-level command and one database context. A decorated handler that calls another decorated handler would begin a second transaction on the same context. A retrying execution strategy needs the whole transaction &lt;a href=&quot;https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency#execution-strategies-and-transactions&quot;&gt;inside the strategy&lt;/a&gt;. And a rollback cannot undo an HTTP call or a published message.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;When to keep MediatR&lt;/h2&gt;
&lt;p&gt;Removing it is not always the right call.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Your situation&lt;/th&gt;
&lt;th&gt;Reasonable decision&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;A new service with a handful of use cases&lt;/td&gt;
&lt;td&gt;Start without it&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;You rely on notifications, with several handlers per event, or on streaming requests&lt;/td&gt;
&lt;td&gt;Keep it, or replace those separately; decorators only cover request and response&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Hundreds of handlers and a pipeline that works&lt;/td&gt;
&lt;td&gt;Stay. The migration costs weeks and changes no behaviour&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;You are on version 12&lt;/td&gt;
&lt;td&gt;It stays under its original Apache-2.0 licence; new releases are version 13 and later&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The licence is what started most of these conversations. Since version 13.0.0, released on 2 July 2025, MediatR is dual-licensed: under the Reciprocal Public License 1.5, or under a commercial licence. There is a free Community tier, for companies and individuals with less than 5 million US dollars in annual gross revenue, with further conditions. A missing licence key produces a log warning, not a failure. Read the &lt;a href=&quot;https://mediatr.io/&quot;&gt;current terms&lt;/a&gt; before you decide. Paying for a library your system depends on is a fair outcome. Removing it without knowing what it did is not a saving.&lt;/p&gt;
&lt;p&gt;If you want a library and not sixty lines of your own, the source-generated &lt;a href=&quot;https://github.com/martinothamar/Mediator&quot;&gt;Mediator&lt;/a&gt; and &lt;a href=&quot;https://github.com/JasperFx/wolverine&quot;&gt;Wolverine&lt;/a&gt; are both MIT-licensed and both have their own way of wrapping handlers.&lt;/p&gt;
&lt;h2&gt;The rule&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Know what a library does before you remove it.&lt;/strong&gt; MediatR dispatches requests and it wraps handlers. The second job has no line of code in any handler.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Drop the dispatch, keep the wrapping.&lt;/strong&gt; Inject the handler&#39;s interface, and give each cross-cutting job one decorator.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Compose in one place, and test the composition.&lt;/strong&gt; Send a request that should be refused and check that it was, through the real endpoint.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;a href=&quot;https://penelope.uchicago.edu/Thayer/E/Roman/Texts/Frontinus/De_Aquis/Bennett/1%2A.html#1.16&quot;&gt;Frontinus&lt;/a&gt;, who ran Rome&#39;s water supply, described the city&#39;s aqueducts and then invited the reader to compare such indispensable structures with &amp;quot;the idle Pyramids&amp;quot;. Validation, logging and transactions are that kind of structure: nobody admires them, and everything depends on them.&lt;/p&gt;
&lt;h2&gt;Run it yourself&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/handlers-with-decorators&quot;&gt;companion sample&lt;/a&gt; is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. It places the same order through three endpoints that share one handler: &lt;code&gt;POST /mediatr/orders&lt;/code&gt;, &lt;code&gt;POST /plain/orders&lt;/code&gt; and &lt;code&gt;POST /orders&lt;/code&gt;. A small client sends two bad orders to each.&lt;/p&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose up &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;--build&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose run &lt;span class=&quot;token parameter variable&quot;&gt;--rm&lt;/span&gt; demo&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output on my machine:&lt;/p&gt;
&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;1. An order for -5 widgets (the request is invalid)
   MediatR with behaviors   POST /mediatr/orders 400
   Handler called directly  POST /plain/orders   201
   Handler with decorators  POST /orders         400

2. An order for 1 widget and 1 gadget (gadgets are out of stock)
   MediatR with behaviors   POST /mediatr/orders 409
   Handler called directly  POST /plain/orders   409
   Handler with decorators  POST /orders         409

What each endpoint left behind (GET /stats). Each started with 10 widgets and no orders:
   mediatr    0 order(s) saved, 10 widgets in stock
   plain      2 order(s) saved, 14 widgets in stock
   decorated  0 order(s) saved, 10 widgets in stock&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The plain endpoint kept both bad orders. The first added five widgets to the shelf; the second took one before it failed. That is where 14 comes from. The other two endpoints behave identically, and one of them has no mediator.&lt;/p&gt;
&lt;p&gt;The sample pins MediatR 12.5.0, the last release under the Apache-2.0 licence, so it runs without a licence key.&lt;/p&gt;
&lt;h2&gt;Further reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://mediatr.io/&quot;&gt;MediatR: licensing and editions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.jimmybogard.com/automapper-and-mediatr-commercial-editions-launch-today/&quot;&gt;Jimmy Bogard: AutoMapper and MediatR commercial editions launch today&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/LuckyPennySoftware/MediatR/wiki/Behaviors&quot;&gt;MediatR wiki: behaviors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/khellang/Scrutor&quot;&gt;Scrutor: assembly scanning and decoration for Microsoft.Extensions.DependencyInjection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/dotnet/runtime/issues/36021&quot;&gt;dotnet/runtime issue 36021: decorator extension methods for IServiceCollection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/dotnet/core/extensions/dependency-injection/guidelines&quot;&gt;.NET: dependency injection guidelines&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;p&gt;This article is part of &lt;em&gt;Justified Complexity: Building Backends One Decision at a Time&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Updated 2026-11-11, after a review: the note on result types now says that the transaction decorator must roll back on a failed result; added why this handler needs an explicit transaction and what the transaction decorator assumes; three sentences are worded more exactly. In the sample, a null order line is now refused with a 400, the demo client checks its own output, and the &lt;code&gt;Location&lt;/code&gt; of a created order resolves.&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>The invoice that was never sent</title>
    <link href="https://nstanev.com/blog/the-invoice-that-was-never-sent/" />
    <updated>2026-09-13T00:00:00Z</updated>
    <id>https://nstanev.com/blog/the-invoice-that-was-never-sent/</id>
    <content type="html">&lt;p&gt;On Monday a customer asks where their invoice is. Finance looks it up: INV-1001, issued on Friday at 16:42, 49.90, due in thirty days. It is in the database and on the dashboard, and it is counted in Friday&#39;s revenue. The customer never received it.&lt;/p&gt;
&lt;p&gt;On Friday at 16:42 the message broker was restarting. It was down for under a minute. The API saved the invoice, tried to announce it, got an error and returned 503. Nobody retried. The service that emails invoices was never told that this one exists.&lt;/p&gt;
&lt;p&gt;The logs show one failed request among thousands. Nothing crashed and no data was corrupted. The system simply holds a fact that it never passed on.&lt;/p&gt;
&lt;p&gt;This article shows why saving a row and publishing a message can&#39;t be made to succeed or fail together, what goes wrong in each order you try, and how an outbox table closes the gap in about sixty lines without a messaging library. Examples use ASP.NET Core, EF Core and PostgreSQL, but the reasoning holds for any database with transactions and any broker.&lt;/p&gt;
&lt;video controls=&quot;&quot; preload=&quot;none&quot; playsinline=&quot;&quot; width=&quot;1280&quot; height=&quot;720&quot; poster=&quot;https://nstanev.com/blog/images/the-invoice-that-was-never-sent-poster.jpg&quot;&gt;
  &lt;source src=&quot;https://nstanev.com/blog/videos/the-invoice-that-was-never-sent.mp4&quot; type=&quot;video/mp4&quot;&gt;
  &lt;a href=&quot;https://nstanev.com/blog/videos/the-invoice-that-was-never-sent.mp4&quot;&gt;Watch the 40-second video (MP4)&lt;/a&gt;
&lt;/video&gt;
&lt;p&gt;&lt;em&gt;The whole argument in 40 seconds.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;The version everyone writes first&lt;/h2&gt;
&lt;p&gt;Save the invoice, then tell everyone else:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;MapPost&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/invoices&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;IssueInvoiceRequest&lt;/span&gt; request&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;IBroker&lt;/span&gt; broker&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AppDb&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; invoice &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;From&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;request&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Invoices&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;invoice&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// committed&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; broker&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;PublishAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToEvent&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; Results&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Created&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token interpolation-string&quot;&gt;&lt;span class=&quot;token string&quot;&gt;$&quot;/invoices/&lt;/span&gt;&lt;span class=&quot;token interpolation&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token expression language-csharp&quot;&gt;invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Id&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToResponse&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It reads the way the business describes it: issue the invoice, then announce it. It passes every test, because in a test the broker is always there.&lt;/p&gt;
&lt;h2&gt;Why it fails&lt;/h2&gt;
&lt;p&gt;The handler writes to two systems, the database and the broker, and there is no transaction that covers both. Between the two lines the process can be stopped by a deployment, the broker can be restarting, or the network can drop the call. The first write then stands alone.&lt;/p&gt;
&lt;p&gt;The usual reaction is to swap the order: open a transaction, save, publish, and commit last, so that a failed publish rolls the invoice back.&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; transaction &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Database&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;BeginTransactionAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Invoices&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;invoice&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;            &lt;span class=&quot;token comment&quot;&gt;// not committed yet&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; broker&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;PublishAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToEvent&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; transaction&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;CommitAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;        &lt;span class=&quot;token comment&quot;&gt;// and if this line never runs?&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This fixes the Friday incident and creates its mirror image. If the request dies after the publish and before the commit, the invoice is rolled back and the event is already out. The mailing service emails the customer an invoice that does not exist.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://topostext.org/work/632&quot;&gt;Theophrastus&lt;/a&gt; has a character for this in his &lt;em&gt;Characters&lt;/em&gt;, the newsmaker: a man who reports a victory that never happened, on the word of a soldier fresh from the battlefield whom nobody can find. Publishing before the commit makes your API that man. It announces something that has not happened yet and may never happen.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/save-and-publish-two-ways.svg&quot; alt=&quot;Two sequences of the same request. In the first the invoice is committed and the publish fails: the invoice is saved and no event exists. In the second the event is published and the commit never happens: the event exists and the invoice does not.&quot;&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Order&lt;/th&gt;
&lt;th&gt;Fails between the two steps&lt;/th&gt;
&lt;th&gt;What is left&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Commit, then publish&lt;/td&gt;
&lt;td&gt;The publish fails or never runs&lt;/td&gt;
&lt;td&gt;An invoice nobody was told about&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Publish, then commit&lt;/td&gt;
&lt;td&gt;The commit fails or never runs&lt;/td&gt;
&lt;td&gt;An event for an invoice that does not exist&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Four other fixes come up in every review of this problem, and none of them closes the gap:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Catch the error and retry the publish.&lt;/strong&gt; The retry lives in the memory of a process that can be stopped at any moment. It also keeps the customer&#39;s request open while the broker is away.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Return an error and let the client retry.&lt;/strong&gt; The invoice is already committed, so the retry creates a second one unless the endpoint is idempotent. The first event is still missing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use a distributed transaction.&lt;/strong&gt; Two-phase commit needs both sides to take part. Most brokers a team is likely to use can&#39;t join a transaction with your database.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Trust the broker&#39;s uptime.&lt;/strong&gt; The broker is one of three things that can fail here. The other two are the network and your own process, and you restart that one on every deployment.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Whichever order you choose, there is a point where one write has happened and the other has not. The only way out is to stop doing two writes.&lt;/p&gt;
&lt;h2&gt;The fix: write the message down next to the invoice&lt;/h2&gt;
&lt;p&gt;After its laws were revised, Athens added a rule that &lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus%3Atext%3A1999.01.0018%3Aspeech%3D1%3Asection%3D85&quot;&gt;Andocides&lt;/a&gt; quotes in court: in no circumstances may the magistrates enforce a law that has not been inscribed. The outbox applies the same rule to events. An event that is not written in your database does not exist yet, and only written events are published.&lt;/p&gt;
&lt;p&gt;It has three parts.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/outbox-flow.svg&quot; alt=&quot;The outbox flow: the API writes the invoice and an outbox row in one transaction; a dispatcher reads unsent rows, publishes them to the broker and marks them as sent; the consumer records the message id in its inbox and sends the email in one transaction.&quot;&gt;&lt;/p&gt;
&lt;h3&gt;1. Save the message in the same transaction as the invoice&lt;/h3&gt;
&lt;p&gt;The message goes into a table in the same database, with the same &lt;code&gt;SaveChangesAsync&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;MapPost&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/invoices&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;IssueInvoiceRequest&lt;/span&gt; request&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AppDb&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; invoice &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;From&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;request&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Invoices&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;invoice&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;OutboxMessages&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;OutboxMessage&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;From&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToEvent&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// one transaction: both rows or neither&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; Results&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Created&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token interpolation-string&quot;&gt;&lt;span class=&quot;token string&quot;&gt;$&quot;/invoices/&lt;/span&gt;&lt;span class=&quot;token interpolation&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token expression language-csharp&quot;&gt;invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Id&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToResponse&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The row holds what the broker will need later:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;sealed&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;OutboxMessage&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;Guid&lt;/span&gt; Id &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;              &lt;span class=&quot;token comment&quot;&gt;// also the message id the consumer deduplicates on&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; required &lt;span class=&quot;token return-type class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;/span&gt; Type &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; required &lt;span class=&quot;token return-type class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;/span&gt; Payload &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;DateTime&lt;/span&gt; OccurredAt &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;DateTime&lt;span class=&quot;token punctuation&quot;&gt;?&lt;/span&gt;&lt;/span&gt; ProcessedAt &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// null until the broker has it&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt;&lt;/span&gt; Attempts &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;?&lt;/span&gt;&lt;/span&gt; LastError &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The request no longer talks to the broker at all. It can&#39;t lose an event, because the event is a row that commits with the invoice. It can&#39;t announce an invoice that does not exist, because a rollback removes the row too. And it answers 201 while the broker is down, which the first version could not do.&lt;/p&gt;
&lt;h3&gt;2. A dispatcher moves the rows to the broker&lt;/h3&gt;
&lt;p&gt;A background service polls the table, publishes what it finds and marks it as sent:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;Task&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;DispatchBatchAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; db &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;CreateDbContextAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; transaction &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Database&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;BeginTransactionAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; batch &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;OutboxMessages&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;FromSql&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token interpolation-string&quot;&gt;&lt;span class=&quot;token string&quot;&gt;$&quot;&quot;&lt;/span&gt;&lt;/span&gt;&quot;
        SELECT &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; FROM outbox_messages
        WHERE processed_at IS NULL
        ORDER BY &lt;span class=&quot;token return-type class-name&quot;&gt;id&lt;/span&gt;
        LIMIT &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;BatchSize&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
        FOR UPDATE SKIP LOCKED
        &lt;span class=&quot;token string&quot;&gt;&quot;&quot;&lt;/span&gt;&quot;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToListAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; sent &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;foreach&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; message &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; batch&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;try&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; broker&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;PublishAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;message&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Id&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; message&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Type&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; message&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Payload&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;catch&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;BrokerUnavailableException&lt;/span&gt; ex&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
            message&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Attempts&lt;span class=&quot;token operator&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
            message&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;LastError &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; ex&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Message&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
            &lt;span class=&quot;token keyword&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// the rows after it would fail too; the next tick tries again&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

        message&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;ProcessedAt &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; DateTime&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;UtcNow&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        sent&lt;span class=&quot;token operator&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; transaction&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;CommitAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; sent&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;FOR UPDATE&lt;/code&gt; locks the rows the query returns until the transaction ends. &lt;code&gt;SKIP LOCKED&lt;/code&gt; tells a second dispatcher to pass over rows that are already locked, without waiting for them. That is what lets you run the dispatcher in every instance of the API: each one takes different rows.&lt;/p&gt;
&lt;p&gt;A partial index keeps the query cheap however many sent rows the table holds:&lt;/p&gt;
&lt;pre class=&quot;language-sql&quot;&gt;&lt;code class=&quot;language-sql&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;CREATE&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;INDEX&lt;/span&gt; ix_outbox_messages_unsent &lt;span class=&quot;token keyword&quot;&gt;ON&lt;/span&gt; outbox_messages &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;id&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;WHERE&lt;/span&gt; processed_at &lt;span class=&quot;token operator&quot;&gt;IS&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;NULL&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The dispatcher has the same two writes the endpoint had: publish to the broker, then mark the row. It can fail between them too. The difference is in what the failure costs. The row is still unsent, so the next pass publishes it again. A lost event has become a repeated one.&lt;/p&gt;
&lt;p&gt;In &lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus%3Atext%3A1999.01.0112%3Acard%3D753&quot;&gt;Euripides&lt;/a&gt;&#39; &lt;em&gt;Iphigenia among the Taurians&lt;/em&gt;, Iphigenia hands Pylades a letter, and he asks what becomes of his oath if the ship goes down and the letter with it. She answers by telling him the contents as well: if the tablet survives, it will speak for itself, and if it is lost, he carries the message. The outbox row plays that part. Whatever happens to one attempt at delivery, the message is still there to be sent again.&lt;/p&gt;
&lt;h3&gt;3. The consumer expects every message twice&lt;/h3&gt;
&lt;p&gt;Delivery is now at least once, so the consumer has to recognise a message it has already handled. It records the message id in an inbox table, in the same transaction as its own work:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;InboxMessages&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token constructor-invocation class-name&quot;&gt;InboxMessage&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; MessageId &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; messageId&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ProcessedAt &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; DateTime&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;UtcNow &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Emails&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token constructor-invocation class-name&quot;&gt;SentEmail&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; Id &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Guid&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;CreateVersion7&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; InvoiceId &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; issued&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;InvoiceId&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Number &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; issued&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Number &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;try&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// one transaction: the inbox row and the work&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;catch&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;DbUpdateException&lt;/span&gt; ex&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;when&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ex&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;InnerException &lt;span class=&quot;token keyword&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;PostgresException&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    SqlState&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; PostgresErrorCodes&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;UniqueViolation&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token named-parameter punctuation&quot;&gt;ConstraintName&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; AppDb&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;InboxKey
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// Already handled. The second delivery is a no-op.&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The primary key on the message id does the deduplication, for the reason given in &lt;a href=&quot;https://nstanev.com/blog/database-constraint-beats-async-validator/&quot;&gt;A database constraint beats an async validator&lt;/a&gt;: a lookup before the insert would let two deliveries through at the same moment.&lt;/p&gt;
&lt;p&gt;This is the server side of &lt;a href=&quot;https://nstanev.com/blog/the-duplicate-charge/&quot;&gt;The duplicate charge&lt;/a&gt; seen from a consumer. There the client named the payment with an idempotency key. Here the outbox names the message with its row id, and the id travels with the message so that every delivery of it carries the same name. If the consumer&#39;s work is a call to another system, such as a real email provider, that call needs the id as well.&lt;/p&gt;
&lt;h2&gt;What the outbox asks of you&lt;/h2&gt;
&lt;p&gt;The table is small, but it comes with decisions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Duplicates are part of the contract.&lt;/strong&gt; Every consumer of an outbox has to be idempotent. Say so in the event&#39;s documentation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Order is not guaranteed with more than one dispatcher.&lt;/strong&gt; One dispatcher holds rows 1 to 20 while another publishes rows 21 to 40. In the sample, 19 of 60 events reached the broker after an event that was written later. If consumers need order, run one dispatcher, or split the rows by a key and keep one dispatcher per key.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Latency.&lt;/strong&gt; An event waits up to one polling interval, 500 ms in the sample. When that is too slow, PostgreSQL&#39;s &lt;code&gt;LISTEN&lt;/code&gt; and &lt;code&gt;NOTIFY&lt;/code&gt; can wake the dispatcher early, and change data capture can read the rows from the write-ahead log. Both add moving parts; start with polling.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The dispatcher holds a transaction open while it publishes.&lt;/strong&gt; The transaction is what keeps the rows locked. It costs one connection per dispatcher, not one per request, but the publish needs a timeout so a stuck broker can&#39;t hold the rows indefinitely.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A message that can never be published blocks the ones behind it.&lt;/strong&gt; Count the attempts, move the row aside after a limit, and alert.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sent rows pile up.&lt;/strong&gt; Delete or archive them on a schedule. The partial index hides the cost for a while, but the cost is still there.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The payload is a contract.&lt;/strong&gt; It is serialised when the invoice is saved and read by another system later, possibly after a deployment. Version it as you would an API.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One number to watch.&lt;/strong&gt; The age of the oldest unsent row tells you whether events are flowing. Alert on it.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;When you don&#39;t need an outbox&lt;/h2&gt;
&lt;p&gt;The outbox is the general answer. Often a smaller one is enough:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Situation&lt;/th&gt;
&lt;th&gt;Smaller answer&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;The consumer lives in the same database, as in a modular monolith&lt;/td&gt;
&lt;td&gt;Write its row in the same transaction, or give it a job table. No broker is involved&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Losing a message now and then is acceptable, such as a cache invalidation or a metric&lt;/td&gt;
&lt;td&gt;Publish after the commit&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The second write is one call to a system that deduplicates on a key&lt;/td&gt;
&lt;td&gt;Pass an idempotency key and retry, as in &lt;a href=&quot;https://nstanev.com/blog/the-duplicate-charge/&quot;&gt;The duplicate charge&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;A scheduled reconciliation already finds invoices without emails&lt;/td&gt;
&lt;td&gt;Let it do the work, if its delay is acceptable&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;You already use a messaging library that ships an outbox, such as MassTransit, Wolverine or NServiceBus&lt;/td&gt;
&lt;td&gt;Use theirs, and read what it guarantees&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Reach for the outbox when a state change in your database must reach another system, and a missing or invented message costs real money or trust.&lt;/p&gt;
&lt;h2&gt;The rule&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;A save and a publish are two writes.&lt;/strong&gt; No ordering of them is safe, because one of them can always succeed alone.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Write the message in the same transaction as the data, and publish from the table.&lt;/strong&gt; A lost message becomes a late one.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Expect every message twice and out of order.&lt;/strong&gt; At-least-once delivery only works when the consumer deduplicates.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Run it yourself&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/outbox&quot;&gt;companion sample&lt;/a&gt; is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. It issues the same invoice in three ways: publish after the commit, publish before the commit, and the outbox. The broker is faked inside the sample and keeps its own record of every message it accepted. The consumer writes a row for every email it would send. A small client makes each option fail and counts what is left.&lt;/p&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose up &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;--build&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose run &lt;span class=&quot;token parameter variable&quot;&gt;--rm&lt;/span&gt; demo&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output on my machine:&lt;/p&gt;
&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;1. Publish after commit. The broker is down.
   POST /publish-after-commit/invoices   503
   INV-1001: invoices 1, outbox 0, events 0, emails 0   &lt;- saved, and the customer never gets it

2. Publish before commit. The request fails between the publish and the commit.
   POST /publish-before-commit/invoices  500
   INV-1002: invoices 0, outbox 0, events 1, emails 1   &lt;- emailed, and the invoice does not exist

3. Outbox. The broker is down.
   POST /invoices                        201
   INV-1003: invoices 1, outbox 1, events 0, emails 0   &lt;- the invoice is issued; the event waits
   the broker comes back
   INV-1003: invoices 1, outbox 0, events 1, emails 1   &lt;- delivered

4. Outbox. The dispatcher fails after publishing, before it marks the row as sent.
   POST /invoices                        201
   INV-1004: invoices 1, outbox 0, events 2, emails 1   &lt;- published twice, emailed once

5. Outbox. 60 invoices pile up while the broker is down, then two dispatchers drain them.
   POST /invoices                        60 x 201
   invoices 60, outbox 0, events 60, emails 60, published twice 0
   events that reached the broker after a later one: 19 of 60&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Steps 1 and 2 are the two failures from the table. Step 3 is the Friday incident with the outbox in place: the customer&#39;s request succeeds while the broker is down, and the event leaves when the broker returns. Step 4 is the one to study: the event is published twice and the customer gets one email, because the inbox refused the second delivery. Step 5 shows two dispatchers sharing a backlog without publishing anything twice, and what that costs in ordering. The last number changes from run to run.&lt;/p&gt;
&lt;p&gt;The demo has limits. Steps 2 and 4 fail one request or one dispatcher pass; they don&#39;t kill the process. The fake broker hands each message to the consumer immediately and never redelivers by itself, and the consumer shares the API&#39;s database. A real consumer has its own database, with the inbox in it.&lt;/p&gt;
&lt;p&gt;The client checks its own output and exits with code 1 if anything differs. The README explains the switches.&lt;/p&gt;
&lt;h2&gt;Further reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://microservices.io/patterns/data/transactional-outbox.html&quot;&gt;Pattern: Transactional outbox&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE&quot;&gt;PostgreSQL: the locking clause, FOR UPDATE and SKIP LOCKED&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/indexes-partial.html&quot;&gt;PostgreSQL: partial indexes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/sql-notify.html&quot;&gt;PostgreSQL: NOTIFY&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html&quot;&gt;Debezium: outbox event router&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/ef/core/saving/transactions&quot;&gt;EF Core: using transactions&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;p&gt;This article is part of &lt;em&gt;Justified Complexity: Building Backends One Decision at a Time&lt;/em&gt;.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>The deploy that locked the table</title>
    <link href="https://nstanev.com/blog/the-deploy-that-locked-the-table/" />
    <updated>2026-09-16T00:00:00Z</updated>
    <id>https://nstanev.com/blog/the-deploy-that-locked-the-table/</id>
    <content type="html">&lt;p&gt;The deployment on Tuesday afternoon contains one schema change: a new nullable column, &lt;code&gt;notes&lt;/code&gt;, on the &lt;code&gt;invoices&lt;/code&gt; table. In staging the migration took four milliseconds.&lt;/p&gt;
&lt;p&gt;In production the API stops answering. For almost five seconds every request that touches an invoice hangs, reads included. Nineteen of twenty-seven reads time out, and the same number of writes. Then everything recovers, and the migration log reports success: one statement, 4.7 seconds.&lt;/p&gt;
&lt;p&gt;Nothing was wrong with the statement. Somewhere else, finance was running a report on the same table, and the migration stood in line behind it. Every request that arrived afterwards stood in line behind the migration.&lt;/p&gt;
&lt;p&gt;This article shows why a schema change that takes milliseconds can stop a table for seconds or minutes, which changes are dangerous and why, and three habits that make them safe. Examples use ASP.NET Core, EF Core and PostgreSQL. The locking rules are PostgreSQL&#39;s; other databases have the same problem with different names.&lt;/p&gt;
&lt;video controls=&quot;&quot; preload=&quot;none&quot; playsinline=&quot;&quot; width=&quot;1280&quot; height=&quot;720&quot; poster=&quot;https://nstanev.com/blog/images/the-deploy-that-locked-the-table-poster.jpg&quot;&gt;
  &lt;source src=&quot;https://nstanev.com/blog/videos/the-deploy-that-locked-the-table.mp4&quot; type=&quot;video/mp4&quot;&gt;
  &lt;a href=&quot;https://nstanev.com/blog/videos/the-deploy-that-locked-the-table.mp4&quot;&gt;Watch the 40-second video (MP4)&lt;/a&gt;
&lt;/video&gt;
&lt;p&gt;&lt;em&gt;The whole argument in 40 seconds.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;The version everyone writes first&lt;/h2&gt;
&lt;p&gt;An EF Core migration that adds a column:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;protected&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;override&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;Up&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;MigrationBuilder&lt;/span&gt; migrationBuilder&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    migrationBuilder&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;AddColumn&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token named-parameter punctuation&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;notes&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token named-parameter punctuation&quot;&gt;table&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;invoices&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token named-parameter punctuation&quot;&gt;nullable&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which becomes:&lt;/p&gt;
&lt;pre class=&quot;language-sql&quot;&gt;&lt;code class=&quot;language-sql&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;ALTER&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;TABLE&lt;/span&gt; invoices &lt;span class=&quot;token keyword&quot;&gt;ADD&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;COLUMN&lt;/span&gt; notes &lt;span class=&quot;token keyword&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Adding a nullable column without a default changes only the table&#39;s definition. No row is rewritten, so the size of the table does not matter. That is why it took four milliseconds in staging, and why nobody thought about it again.&lt;/p&gt;
&lt;p&gt;At Gordium, &lt;a href=&quot;https://en.wikisource.org/wiki/The_Anabasis_of_Alexander/Book_II/Chapter_III&quot;&gt;Arrian&lt;/a&gt; reports, Alexander could find no way to untie the knot on the wagon and, by one account, cut it with his sword. A migration written like this takes the same approach to a table in use: one stroke, at whatever moment the deployment happens to run.&lt;/p&gt;
&lt;h2&gt;Why it fails&lt;/h2&gt;
&lt;p&gt;To change a table&#39;s definition PostgreSQL needs the strongest lock on it, &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;. That lock conflicts with every other lock, including the weakest one, &lt;code&gt;ACCESS SHARE&lt;/code&gt;, which every &lt;code&gt;SELECT&lt;/code&gt; takes and holds until its transaction ends.&lt;/p&gt;
&lt;p&gt;So the &lt;code&gt;ALTER TABLE&lt;/code&gt; has to wait for every transaction that has touched the table to finish. The wait is not the dangerous part. The queue is. PostgreSQL grants locks in order, so every statement that arrives after the waiting &lt;code&gt;ALTER TABLE&lt;/code&gt; waits behind it, even a plain &lt;code&gt;SELECT&lt;/code&gt; that would have no conflict with the report.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/lock-queue.svg&quot; alt=&quot;A timeline of three sessions on the invoices table. A report holds a read lock for five seconds. ALTER TABLE arrives, needs an exclusive lock and waits. Every request that arrives after it queues behind it until the report ends.&quot;&gt;&lt;/p&gt;
&lt;p&gt;The report could run next to the application all day. It becomes a problem only because the migration is standing between them.&lt;/p&gt;
&lt;p&gt;The blocker does not have to be a report. Anything that has touched the table and has not finished its transaction will do: a slow query, a backup, a session left open in a database console with a &lt;code&gt;BEGIN&lt;/code&gt; and no &lt;code&gt;COMMIT&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The lock queue is one of three ways a schema change stops a table. They differ in what is blocked and for how long:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Change&lt;/th&gt;
&lt;th&gt;Lock it takes&lt;/th&gt;
&lt;th&gt;What waits&lt;/th&gt;
&lt;th&gt;For how long&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;ADD COLUMN&lt;/code&gt; (nullable)&lt;/td&gt;
&lt;td&gt;&lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Reads and writes&lt;/td&gt;
&lt;td&gt;Milliseconds, plus the time it waits for its own lock&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;CREATE INDEX&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;SHARE&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Writes&lt;/td&gt;
&lt;td&gt;The whole index build&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;ADD CONSTRAINT ... CHECK&lt;/code&gt;, &lt;code&gt;SET NOT NULL&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Reads and writes&lt;/td&gt;
&lt;td&gt;A scan of every row&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The sample at the end of this article runs all three against a table of two million rows while a client sends five reads and five writes per second, each with a one-second timeout:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Change&lt;/th&gt;
&lt;th&gt;Reads timed out&lt;/th&gt;
&lt;th&gt;Writes timed out&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;ADD COLUMN&lt;/code&gt; behind a 5-second report&lt;/td&gt;
&lt;td&gt;19 of 27&lt;/td&gt;
&lt;td&gt;19 of 27&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;CREATE INDEX&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;0 of 21&lt;/td&gt;
&lt;td&gt;14 of 21&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;ADD CONSTRAINT ... CHECK&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;3 of 11&lt;/td&gt;
&lt;td&gt;3 of 11&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;The fix: three habits&lt;/h2&gt;
&lt;h3&gt;1. Never wait for a lock without a limit&lt;/h3&gt;
&lt;p&gt;Tell the migration how long it may stand in the queue:&lt;/p&gt;
&lt;pre class=&quot;language-sql&quot;&gt;&lt;code class=&quot;language-sql&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;BEGIN&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;SET&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;LOCAL&lt;/span&gt; lock_timeout &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&#39;300ms&#39;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;ALTER&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;TABLE&lt;/span&gt; invoices &lt;span class=&quot;token keyword&quot;&gt;ADD&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;COLUMN&lt;/span&gt; notes &lt;span class=&quot;token keyword&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;COMMIT&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If the lock is not free within 300 ms, the statement fails with error &lt;code&gt;55P03&lt;/code&gt; and leaves the queue. The requests behind it go ahead. The migration then tries again a moment later:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; attempt &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; attempt&lt;span class=&quot;token operator&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; connection &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; dataSource&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;OpenConnectionAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; transaction &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; connection&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;BeginTransactionAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;try&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;ExecuteAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;connection&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; transaction&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;SET LOCAL lock_timeout = &#39;300ms&#39;&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;ExecuteAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;connection&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; transaction&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; sql&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; transaction&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;CommitAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; attempt&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;catch&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;PostgresException&lt;/span&gt; ex&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;when&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ex&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;SqlState &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; PostgresErrorCodes&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;LockNotAvailable &lt;span class=&quot;token operator&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; attempt &lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;40&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; transaction&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;RollbackAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; Task&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Delay&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;TimeSpan&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;FromMilliseconds&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;700&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;SET LOCAL&lt;/code&gt; lasts until the end of the transaction, so the setting never leaks to a pooled connection. In an EF Core migration, put &lt;code&gt;migrationBuilder.Sql(&amp;quot;SET LOCAL lock_timeout = &#39;300ms&#39;;&amp;quot;)&lt;/code&gt; first in &lt;code&gt;Up&lt;/code&gt;, and let the deployment step that applies migrations retry on failure.&lt;/p&gt;
&lt;p&gt;In the sample the same &lt;code&gt;ALTER TABLE&lt;/code&gt; behind the same report needed six attempts and 5.1 seconds, and no request timed out.&lt;/p&gt;
&lt;p&gt;Demosthenes tells of a custom among the Locrians: whoever proposed a new law did so &lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus%3Atext%3A1999.01.0074%3Aspeech%3D24%3Asection%3D139&quot;&gt;with a halter round his neck&lt;/a&gt;, and if the proposal was rejected, the halter was drawn tight. &lt;code&gt;lock_timeout&lt;/code&gt; is that arrangement for schema changes. When the change can&#39;t be made now, it is the migration that dies, and not the traffic behind it.&lt;/p&gt;
&lt;h3&gt;2. Build indexes concurrently&lt;/h3&gt;
&lt;p&gt;A plain &lt;code&gt;CREATE INDEX&lt;/code&gt; lets reads through and blocks every write until the index is built. &lt;code&gt;CREATE INDEX CONCURRENTLY&lt;/code&gt; builds the same index while writes continue:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;migrationBuilder&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Sql&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;token string&quot;&gt;&quot;CREATE INDEX CONCURRENTLY ix_invoices_customer ON invoices (customer);&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token named-parameter punctuation&quot;&gt;suppressTransaction&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;suppressTransaction: true&lt;/code&gt; is required, because a concurrent build can&#39;t run inside a transaction and EF Core wraps each migration in one.&lt;/p&gt;
&lt;p&gt;It has two costs. It takes somewhat longer, because it scans the table twice. And if it fails or is cancelled, it leaves the index behind, marked invalid: every write maintains it and no query uses it. A build that ends without an error is valid, so the times to look are after a failed build and before you run one again:&lt;/p&gt;
&lt;pre class=&quot;language-sql&quot;&gt;&lt;code class=&quot;language-sql&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;SELECT&lt;/span&gt; indisvalid &lt;span class=&quot;token keyword&quot;&gt;FROM&lt;/span&gt; pg_index &lt;span class=&quot;token keyword&quot;&gt;WHERE&lt;/span&gt; indexrelid &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&#39;ix_invoices_customer&#39;&lt;/span&gt;::regclass&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If the answer is false, remove the index with &lt;code&gt;DROP INDEX CONCURRENTLY&lt;/code&gt; and build it again.&lt;/p&gt;
&lt;p&gt;Don&#39;t put a short &lt;code&gt;lock_timeout&lt;/code&gt; on a concurrent build, since a timeout is one of the ways it ends up invalid. And don&#39;t write &lt;code&gt;CREATE INDEX CONCURRENTLY IF NOT EXISTS&lt;/code&gt; in a script that is retried: the second run finds the invalid index, sees that it exists and reports success.&lt;/p&gt;
&lt;h3&gt;3. Split every change that reads or rewrites all rows&lt;/h3&gt;
&lt;p&gt;A &lt;code&gt;CHECK&lt;/code&gt; constraint is verified against every existing row while the table is locked for reads and writes. Do it in two statements, in two transactions:&lt;/p&gt;
&lt;pre class=&quot;language-sql&quot;&gt;&lt;code class=&quot;language-sql&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;ALTER&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;TABLE&lt;/span&gt; invoices
    &lt;span class=&quot;token keyword&quot;&gt;ADD&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;CONSTRAINT&lt;/span&gt; ck_invoices_number &lt;span class=&quot;token keyword&quot;&gt;CHECK&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;number &lt;span class=&quot;token operator&quot;&gt;~&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&#39;^INV-[0-9]+$&#39;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;NOT&lt;/span&gt; VALID&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;-- Commit here. The lock taken above must be released before the scan starts.&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;ALTER&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;TABLE&lt;/span&gt; invoices VALIDATE &lt;span class=&quot;token keyword&quot;&gt;CONSTRAINT&lt;/span&gt; ck_invoices_number&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first enforces the rule for new and changed rows and returns at once. The second checks the old rows under a lock that lets reads and writes through.&lt;/p&gt;
&lt;p&gt;The commit between them matters. The first statement takes &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;, and PostgreSQL holds a lock until the transaction ends. In one transaction the scan would run under that lock, and nothing would be gained. EF Core wraps each migration in a transaction, and EF Core 9 wraps all pending migrations in one, so two &lt;code&gt;migrationBuilder.Sql&lt;/code&gt; calls are not enough. Give the &lt;code&gt;VALIDATE&lt;/code&gt; statement &lt;code&gt;suppressTransaction: true&lt;/code&gt;, as for the concurrent index, and check that the generated script commits between the two.&lt;/p&gt;
&lt;p&gt;The same route leads to &lt;code&gt;NOT NULL&lt;/code&gt; without a blocking scan: add &lt;code&gt;CHECK (column IS NOT NULL) NOT VALID&lt;/code&gt;, validate it, then &lt;code&gt;SET NOT NULL&lt;/code&gt;, which PostgreSQL can now do without scanning because the constraint already proves it.&lt;/p&gt;
&lt;p&gt;Changes that no single safe statement can make, such as renaming a column or changing its type, are spread over several deployments:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/expand-backfill-contract.svg&quot; alt=&quot;Four deployments in a row. Expand: add the new column. Migrate: the application writes both columns while a job copies old rows in batches. Switch: the application reads the new column. Contract: the old column is dropped.&quot;&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Step&lt;/th&gt;
&lt;th&gt;Database&lt;/th&gt;
&lt;th&gt;Application&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Expand&lt;/td&gt;
&lt;td&gt;Add the new column, nullable&lt;/td&gt;
&lt;td&gt;Unchanged&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Migrate&lt;/td&gt;
&lt;td&gt;Copy old rows in batches of a few thousand, each in its own transaction&lt;/td&gt;
&lt;td&gt;Writes both columns&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Switch&lt;/td&gt;
&lt;td&gt;Nothing&lt;/td&gt;
&lt;td&gt;Reads the new column&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Contract&lt;/td&gt;
&lt;td&gt;Drop the old column&lt;/td&gt;
&lt;td&gt;No longer mentions it&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The old and the new exist side by side until the new one carries the load. Dropping the old column comes last for that reason.&lt;/p&gt;
&lt;h2&gt;What safe migrations ask of you&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;More deployments per change.&lt;/strong&gt; A rename is four small deployments. Each is boring, which is the goal.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A retry in the pipeline.&lt;/strong&gt; A migration with &lt;code&gt;lock_timeout&lt;/code&gt; fails on purpose when the table is busy. The step that runs it has to try again, and to give up loudly after a limit.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A limit on the other side as well.&lt;/strong&gt; &lt;code&gt;idle_in_transaction_session_timeout&lt;/code&gt; ends sessions that hold locks and do nothing, so a forgotten console can&#39;t block deployments for hours.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Migrations as a deployment step.&lt;/strong&gt; Calling &lt;code&gt;Migrate()&lt;/code&gt; when the application starts means every instance tries, during the very rollout that is replacing instances.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Backfills in batches.&lt;/strong&gt; One &lt;code&gt;UPDATE&lt;/code&gt; over two million rows holds its row locks until it commits and produces one very large transaction for replicas to replay.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A rehearsal with real sizes and real traffic.&lt;/strong&gt; A migration that takes four milliseconds on an empty staging table says nothing about production. The sample is a small version of that rehearsal.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;When you don&#39;t need any of this&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Situation&lt;/th&gt;
&lt;th&gt;Smaller answer&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;The table has a few thousand rows and no long transactions&lt;/td&gt;
&lt;td&gt;A plain migration; the scan and the build take milliseconds&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The table is new and nothing reads it yet&lt;/td&gt;
&lt;td&gt;Create it with its indexes and constraints in one go&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The system has a maintenance window that users accept&lt;/td&gt;
&lt;td&gt;Run the plain migration inside it&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The product has not launched&lt;/td&gt;
&lt;td&gt;Keep migrations simple until there is traffic to protect&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;code&gt;lock_timeout&lt;/code&gt; is the exception: it costs one line and belongs in every migration that touches an existing table, whatever the table&#39;s size.&lt;/p&gt;
&lt;h2&gt;The rule&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;A schema change is a lock request first.&lt;/strong&gt; Ask what it locks, what waits behind it and for how long, before asking how long the statement runs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Never wait for a lock without a limit.&lt;/strong&gt; Set &lt;code&gt;lock_timeout&lt;/code&gt;, fail fast and retry.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Split every change that reads or rewrites all rows.&lt;/strong&gt; Build indexes concurrently, validate constraints separately, and expand before you contract.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Run it yourself&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/migration-lock&quot;&gt;companion sample&lt;/a&gt; is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. On start it loads two million invoices. A small client sends steady traffic while six schema changes run, three written the obvious way and three the safe way.&lt;/p&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose up &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;--build&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose run &lt;span class=&quot;token parameter variable&quot;&gt;--rm&lt;/span&gt; demo&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output on my machine:&lt;/p&gt;
&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;Table invoices: 2,000,000 rows. Traffic: 5 reads and 5 writes per second, each with a 1 s timeout.

1. ALTER TABLE ... ADD COLUMN while a 5-second report is reading the table
   migration: 1 attempt(s), 4.7 s
   reads:     27 sent, 19 timed out, 3 slower than 500 ms
   writes:    27 sent, 19 timed out, 2 slower than 500 ms

2. The same, with lock_timeout = 300 ms and a retry
   migration: 6 attempt(s), 5.1 s
   reads:     27 sent, 0 timed out, 0 slower than 500 ms
   writes:    27 sent, 0 timed out, 0 slower than 500 ms

3. CREATE INDEX
   migration: 1 attempt(s), 3.7 s
   reads:     21 sent, 0 timed out, 0 slower than 500 ms
   writes:    21 sent, 14 timed out, 2 slower than 500 ms

4. CREATE INDEX CONCURRENTLY
   migration: 1 attempt(s), 3.9 s
   reads:     22 sent, 0 timed out, 0 slower than 500 ms
   writes:    22 sent, 0 timed out, 0 slower than 500 ms

5. ADD CONSTRAINT ... CHECK
   migration: 1 attempt(s), 1.5 s
   reads:     11 sent, 3 timed out, 3 slower than 500 ms
   writes:    11 sent, 3 timed out, 3 slower than 500 ms

6. ADD CONSTRAINT ... CHECK NOT VALID, then VALIDATE CONSTRAINT
   migration: 1 attempt(s), 1.5 s
   reads:     10 sent, 0 timed out, 0 slower than 500 ms
   writes:    10 sent, 0 timed out, 0 slower than 500 ms&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each safe version takes about as long as the unsafe one. The time was never the problem. What changes is who waits.&lt;/p&gt;
&lt;p&gt;The demo has limits. Its traffic is ten requests per second; with real traffic the requests that pile up behind the lock also use up the connection pool. The exact counts depend on the machine, so the client checks the pattern, failures in steps 1, 3 and 5 and none in steps 2, 4 and 6, and exits with code 1 if it differs. The schema changes are plain SQL; the README shows how each maps to an EF Core migration.&lt;/p&gt;
&lt;h2&gt;Further reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/explicit-locking.html&quot;&gt;PostgreSQL: explicit locking and lock modes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/sql-altertable.html&quot;&gt;PostgreSQL: ALTER TABLE, notes on locks, NOT VALID and VALIDATE CONSTRAINT&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY&quot;&gt;PostgreSQL: building indexes concurrently&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/runtime-config-client.html&quot;&gt;PostgreSQL: lock_timeout and idle_in_transaction_session_timeout&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/ef/core/managing-schemas/migrations/managing&quot;&gt;EF Core: custom SQL in migrations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;p&gt;This article is part of &lt;em&gt;Justified Complexity: Building Backends One Decision at a Time&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Updated 2026-11-12, after a review: the &lt;code&gt;NOT VALID&lt;/code&gt; and &lt;code&gt;VALIDATE&lt;/code&gt; statements must run in separate transactions, and the article now says so and explains what that means in an EF Core migration; the check for an invalid index belongs after a failed build and before a rerun, since a build that succeeds is always valid, and the &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/migration-lock&quot;&gt;sample&lt;/a&gt; now does that.&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>The query that returned another company&#39;s payslips</title>
    <link href="https://nstanev.com/blog/another-companys-payslips/" />
    <updated>2026-09-19T00:00:00Z</updated>
    <id>https://nstanev.com/blog/another-companys-payslips/</id>
    <content type="html">&lt;p&gt;An HR manager at Acme types &amp;quot;an&amp;quot; into the employee search of the payroll service her company rents. She is looking for Hanna. The list shows Hanna, Dana and Ivan, and below them Stefan, Joanna and Nathan, with their net pay for August. She has never heard of them. They work for Globex, another customer of the same service.&lt;/p&gt;
&lt;p&gt;She takes a screenshot and calls her account manager.&lt;/p&gt;
&lt;p&gt;The search endpoint was added eight months after the others, by a developer who had joined the month before. It was reviewed and tested, and it worked: the test environment has one tenant. The query looked for employees by name. It did not say whose employees.&lt;/p&gt;
&lt;p&gt;For a payroll service this is a personal data breach. Under the GDPR the service, as Globex&#39;s processor, must tell Globex without undue delay. Globex then has 72 hours, where feasible, to notify the regulator, unless the breach is unlikely to put its employees at risk. And the service has two customers to explain itself to.&lt;/p&gt;
&lt;p&gt;This article shows why &amp;quot;remember the tenant in every query&amp;quot; fails, what an EF Core global query filter fixes and where it stops, and how PostgreSQL row-level security keeps tenants apart when the application code gets it wrong. Examples use ASP.NET Core, EF Core and PostgreSQL.&lt;/p&gt;
&lt;video controls=&quot;&quot; preload=&quot;none&quot; playsinline=&quot;&quot; width=&quot;1280&quot; height=&quot;720&quot; poster=&quot;https://nstanev.com/blog/images/another-companys-payslips-poster.jpg&quot;&gt;
  &lt;source src=&quot;https://nstanev.com/blog/videos/another-companys-payslips.mp4&quot; type=&quot;video/mp4&quot;&gt;
  &lt;a href=&quot;https://nstanev.com/blog/videos/another-companys-payslips.mp4&quot;&gt;Watch the 40-second video (MP4)&lt;/a&gt;
&lt;/video&gt;
&lt;p&gt;&lt;em&gt;The whole argument in 40 seconds.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;The version everyone writes first&lt;/h2&gt;
&lt;p&gt;All tenants share one table, and every row says whose it is:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;MapGet&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/payslips&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;TenantContext&lt;/span&gt; tenant&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AppDb&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Payslips
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Where&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;p &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; p&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;TenantId &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; tenant&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;TenantId&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;OrderBy&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;p &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; p&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Employee&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToListAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is the cheapest way to run a multi-tenant product: one database, one schema, one deployment. The cost is that every query, in every endpoint, has to carry that &lt;code&gt;Where&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;In Aristophanes&#39; &lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus%3Atext%3A1999.01.0030%3Acard%3D667&quot;&gt;&lt;em&gt;Assemblywomen&lt;/em&gt;&lt;/a&gt;, Praxagora promises to turn Athens into a single dwelling, so that anyone can walk from one house into any other. A shared table is that city. The walls between households exist only where somebody remembered to write one.&lt;/p&gt;
&lt;h2&gt;Why it fails&lt;/h2&gt;
&lt;p&gt;The search that leaked:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;MapGet&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/payslips/search&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;string&lt;/span&gt;&lt;/span&gt; employee&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AppDb&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Payslips
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Where&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;p &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; EF&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Functions&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ILike&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;p&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Employee&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token interpolation-string&quot;&gt;&lt;span class=&quot;token string&quot;&gt;$&quot;%&lt;/span&gt;&lt;span class=&quot;token interpolation&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;token expression language-csharp&quot;&gt;employee&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;%&quot;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;OrderBy&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;p &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; p&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Employee&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToListAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nothing about this code is unusual, which is the problem. The rule &amp;quot;filter by tenant&amp;quot; lives in the developers&#39; memory and is checked by nothing:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The compiler&lt;/strong&gt; sees a valid query.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The tests&lt;/strong&gt; pass, because test data rarely has a second tenant, and a test that does has to be written for every endpoint.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The reviewer&lt;/strong&gt; sees a search by name and approves a search by name.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Production&lt;/strong&gt; returns 200.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A rule that has to be applied in a hundred places will be missed in one of them. The first improvement is to apply it in one place.&lt;/p&gt;
&lt;h2&gt;The first layer: a global query filter&lt;/h2&gt;
&lt;p&gt;EF Core can add the condition to every query on an entity:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;sealed&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AppDb&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;DbContextOptions&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;AppDb&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; options&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;TenantContext&lt;/span&gt; tenant&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;DbContext&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;options&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;Guid&lt;span class=&quot;token punctuation&quot;&gt;?&lt;/span&gt;&lt;/span&gt; CurrentTenant &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; tenant&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;TenantId&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;protected&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;override&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;OnModelCreating&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;ModelBuilder&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        b&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;Entity&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;Payslip&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;HasQueryFilter&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;p &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; p&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;TenantId &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; CurrentTenant&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now the search needs no tenant in it. EF Core adds &lt;code&gt;WHERE tenant_id = @tenant&lt;/code&gt; to every LINQ query on &lt;code&gt;Payslips&lt;/code&gt;, including the ones nobody has written yet. This is a real improvement, and for many teams it is where the work stops.&lt;/p&gt;
&lt;p&gt;It should not stop there, because the filter is a feature of EF Core&#39;s query pipeline, and data is reached in other ways:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Path&lt;/th&gt;
&lt;th&gt;Does the filter apply?&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;A LINQ query on the &lt;code&gt;DbSet&lt;/code&gt;, or &lt;code&gt;FromSql&lt;/code&gt; on it&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Database.SqlQuery&amp;lt;T&amp;gt;&lt;/code&gt; with hand-written SQL&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;IgnoreQueryFilters()&lt;/code&gt;, added for an admin screen and copied later&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;An insert or update with another tenant&#39;s id&lt;/td&gt;
&lt;td&gt;No, the filter only reads&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Dapper, a reporting tool or a script on the same database&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;A background job, where there is no request and no tenant&lt;/td&gt;
&lt;td&gt;The filter compares with &lt;code&gt;NULL&lt;/code&gt;; raw SQL returns everything&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;At the door of Trimalchio&#39;s house, in &lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus%3Atext%3A2007.01.0027%3Atext%3DSatyricon%3Asection%3D29&quot;&gt;Petronius&lt;/a&gt;, a huge chained dog is painted on the wall above the words &lt;em&gt;CAVE CANEM&lt;/em&gt;, beware of the dog, and the narrator is so startled that he nearly falls over. A query filter is that painting. It stops everyone who comes in through the front door and looks at the wall.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/tenant-leaks-by-layer.svg&quot; alt=&quot;A table of three ways to keep tenants apart and four ways to reach the data. A WHERE in every query leaks through the query that forgot it. A global query filter stops that and leaks through raw SQL, writes and code with no tenant. Row-level security leaks through none of them.&quot;&gt;&lt;/p&gt;
&lt;h2&gt;The second layer: let the database refuse&lt;/h2&gt;
&lt;p&gt;PostgreSQL can attach the condition to the table itself. It then applies to every statement from every client, whatever wrote the SQL. This is row-level security, and it has four parts.&lt;/p&gt;
&lt;h3&gt;1. A login that owns nothing&lt;/h3&gt;
&lt;pre class=&quot;language-sql&quot;&gt;&lt;code class=&quot;language-sql&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;CREATE&lt;/span&gt; ROLE payroll_api LOGIN PASSWORD &lt;span class=&quot;token string&quot;&gt;&#39;...&#39;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;GRANT&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;SELECT&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;INSERT&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;UPDATE&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;DELETE&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;ON&lt;/span&gt; payslips &lt;span class=&quot;token keyword&quot;&gt;TO&lt;/span&gt; payroll_api&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Policies do not apply to superusers, and by default they do not apply to the table&#39;s owner either. An application that connects as the user that created the tables is exempt from every policy on them. So migrations run as the owner, and the API connects as a second role that owns nothing.&lt;/p&gt;
&lt;h3&gt;2. A policy on the table&lt;/h3&gt;
&lt;pre class=&quot;language-sql&quot;&gt;&lt;code class=&quot;language-sql&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;ALTER&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;TABLE&lt;/span&gt; payslips &lt;span class=&quot;token keyword&quot;&gt;ENABLE&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;ROW&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;LEVEL&lt;/span&gt; SECURITY&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;CREATE&lt;/span&gt; POLICY payslips_same_tenant &lt;span class=&quot;token keyword&quot;&gt;ON&lt;/span&gt; payslips &lt;span class=&quot;token keyword&quot;&gt;TO&lt;/span&gt; payroll_api
    &lt;span class=&quot;token keyword&quot;&gt;USING&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;tenant_id &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;NULLIF&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;current_setting&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&#39;app.current_tenant&#39;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&#39;&#39;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;::uuid&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;WITH&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;CHECK&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;tenant_id &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;NULLIF&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;current_setting&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&#39;app.current_tenant&#39;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&#39;&#39;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;::uuid&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;USING&lt;/code&gt; decides which rows a statement can see. &lt;code&gt;WITH CHECK&lt;/code&gt; decides which rows it may write. Both compare the row&#39;s tenant with a setting on the connection.&lt;/p&gt;
&lt;h3&gt;3. The tenant, set on every connection&lt;/h3&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;sealed&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;TenantConnectionInterceptor&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;TenantContext&lt;/span&gt; tenant&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; DbConnectionInterceptor
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;override&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;Task&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;ConnectionOpenedAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;token class-name&quot;&gt;DbConnection&lt;/span&gt; connection&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;ConnectionEndEventData&lt;/span&gt; eventData&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; cancellationToken &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; command &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; connection&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;CreateCommand&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        command&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;CommandText &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;SELECT set_config(&#39;app.current_tenant&#39;, @tenant, false)&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; parameter &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; command&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;CreateParameter&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        parameter&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;ParameterName &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;tenant&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        parameter&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Value &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; tenant&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;TenantId&lt;span class=&quot;token punctuation&quot;&gt;?.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ToString&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;??&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        command&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Parameters&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Add&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;parameter&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; command&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ExecuteNonQueryAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;cancellationToken&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;EF Core calls the interceptor each time it opens a connection. The value is set every time, including to &amp;quot;no tenant&amp;quot;, so a pooled connection never carries the previous request&#39;s tenant.&lt;/p&gt;
&lt;p&gt;The policy trusts this value. It protects against a query that forgets the tenant. It does not protect against code that sets the wrong tenant, or against SQL injected through the API&#39;s own login, which can call &lt;code&gt;set_config&lt;/code&gt; like any other statement. So the tenant has to come from the authenticated user, never from something the client is free to choose.&lt;/p&gt;
&lt;h3&gt;4. No tenant means no rows&lt;/h3&gt;
&lt;p&gt;With no tenant, the setting is an empty string, &lt;code&gt;NULLIF&lt;/code&gt; turns it into &lt;code&gt;NULL&lt;/code&gt;, and &lt;code&gt;tenant_id = NULL&lt;/code&gt; is true for no row. A job that forgets to say whom it works for reads nothing and can write nothing. The failure is an empty report, which somebody notices. It is not a report with every customer&#39;s data in it.&lt;/p&gt;
&lt;p&gt;Keep the query filter as well. &lt;a href=&quot;https://en.wikisource.org/wiki/The_War_of_the_Jews/Book_V&quot;&gt;Josephus&lt;/a&gt; describes the inner court of the Temple in Jerusalem as surrounded by a stone partition, with pillars on it at equal distances that announced, some in Greek and some in Roman letters, that no foreigner might go further. There was a notice and there was a wall. The filter is the notice: it keeps honest queries correct and readable. The policy is the wall.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/tenant-two-layers.svg&quot; alt=&quot;A request passes two layers on its way to the payslips table. The EF Core query filter adds the tenant to LINQ queries; raw SQL goes around it. The row-level security policy in PostgreSQL applies to every statement from the API&#39;s login and returns only the tenant&#39;s rows.&quot;&gt;&lt;/p&gt;
&lt;h2&gt;What the sample counts&lt;/h2&gt;
&lt;p&gt;The companion sample has all three variants over the same table: two tenants, three payslips each. Every request is made as Acme.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Request&lt;/th&gt;
&lt;th&gt;&lt;code&gt;WHERE&lt;/code&gt; in every query&lt;/th&gt;
&lt;th&gt;Query filter&lt;/th&gt;
&lt;th&gt;Filter and row-level security&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;List payslips&lt;/td&gt;
&lt;td&gt;3 rows, 0 leaked&lt;/td&gt;
&lt;td&gt;3 rows, 0 leaked&lt;/td&gt;
&lt;td&gt;3 rows, 0 leaked&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Search by name&lt;/td&gt;
&lt;td&gt;6 rows, 3 leaked&lt;/td&gt;
&lt;td&gt;3 rows, 0 leaked&lt;/td&gt;
&lt;td&gt;3 rows, 0 leaked&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;A report in raw SQL&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;6 rows, 3 leaked&lt;/td&gt;
&lt;td&gt;3 rows, 0 leaked&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Insert a row for Globex&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;201, row planted&lt;/td&gt;
&lt;td&gt;403, refused&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The raw SQL with no tenant&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;7 rows, 2 tenants&lt;/td&gt;
&lt;td&gt;0 rows&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The code in the last two columns is the same. Only the database login differs.&lt;/p&gt;
&lt;h2&gt;What row-level security asks of you&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Two database roles.&lt;/strong&gt; One owns the schema and runs migrations. The other serves requests. If the application connects as the owner, the policies do nothing and nothing warns you.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A policy on every tenant-owned table.&lt;/strong&gt; A new table without one is unprotected. The sample has a query that lists every table with a &lt;code&gt;tenant_id&lt;/code&gt; column and no row-level security; run it as a test, so the build fails when someone adds such a table.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Care with connection pooling.&lt;/strong&gt; Setting the tenant when a connection is opened is safe with the driver&#39;s own pool. Behind a pooler in transaction mode, such as PgBouncer, consecutive transactions of one session may run on different server connections, so set the tenant inside each transaction with &lt;code&gt;set_config(..., true)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The tenant has to come from something the caller can&#39;t choose.&lt;/strong&gt; The sample reads a header to stay small. A real API reads a claim from a validated token.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;An index that starts with &lt;code&gt;tenant_id&lt;/code&gt;.&lt;/strong&gt; The policy is a filter on every statement, and the planner needs an index to serve it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Views and functions.&lt;/strong&gt; A view runs with its owner&#39;s rights unless it is created with &lt;code&gt;security_invoker&lt;/code&gt;, so a view owned by the schema owner goes around the policy.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A way for support to look across tenants.&lt;/strong&gt; That is a separate role with &lt;code&gt;BYPASSRLS&lt;/code&gt;, used by a separate tool, and every use of it is logged.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;When you don&#39;t need it&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Situation&lt;/th&gt;
&lt;th&gt;Smaller answer&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Each tenant has its own database or schema&lt;/td&gt;
&lt;td&gt;Isolation comes from the connection; there is no shared table to filter&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The product is installed once per customer&lt;/td&gt;
&lt;td&gt;There is one tenant&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The shared tables hold nothing confidential, such as a public catalogue&lt;/td&gt;
&lt;td&gt;A query filter, for correctness&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;A few large customers, each with contract terms about isolation&lt;/td&gt;
&lt;td&gt;A database per tenant is often easier to explain to their auditors&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Reach for row-level security when tenants share tables and a row shown to the wrong one is an incident, which is the case for personal, financial and health data.&lt;/p&gt;
&lt;h2&gt;The rule&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;A rule that every query must remember will be forgotten by one.&lt;/strong&gt; Put tenant isolation where a query can&#39;t forget it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use two layers.&lt;/strong&gt; A query filter keeps the application&#39;s queries correct; a database policy holds when a query doesn&#39;t go through the filter.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fail closed.&lt;/strong&gt; With no tenant set, the answer is no rows, never all rows.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Run it yourself&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/tenant-isolation&quot;&gt;companion sample&lt;/a&gt; is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. A small client sends Acme&#39;s tenant header, calls every endpoint and counts the rows that belong to Globex.&lt;/p&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose up &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;--build&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose run &lt;span class=&quot;token parameter variable&quot;&gt;--rm&lt;/span&gt; demo&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output on my machine:&lt;/p&gt;
&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;Two tenants, Acme and Globex, with 3 payslips each. Every request below is made as Acme.

1. A WHERE clause in every query
   GET  /manual/payslips             3 row(s), 0 from another tenant
   GET  /manual/payslips/search      6 row(s), 3 from another tenant   &lt;- this query forgot the WHERE

2. An EF Core global query filter
   GET  /filtered/payslips           3 row(s), 0 from another tenant
   GET  /filtered/payslips/search    3 row(s), 0 from another tenant
   GET  /filtered/payslips/highest   6 row(s), 3 from another tenant   &lt;- raw SQL does not go through the filter

3. The same code on a database login with row-level security
   GET  /rls/payslips                3 row(s), 0 from another tenant
   GET  /rls/payslips/search         3 row(s), 0 from another tenant
   GET  /rls/payslips/highest        3 row(s), 0 from another tenant   &lt;- the same raw SQL

4. A write that names another tenant (the body says Globex)
   POST /rls/payslips                403   &lt;- the database refused the row
   POST /filtered/payslips           201   &lt;- a payslip planted in Globex

5. No tenant at all, as in a background job
   GET  /filtered/payslips/highest   7 row(s) from 2 tenant(s)   &lt;- every tenant&#39;s rows
   GET  /rls/payslips/highest        0 row(s) from 0 tenant(s)   &lt;- nothing: no tenant, no rows

6. Tables with a tenant_id column and no row-level security: leave_requests&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Step 6 is the check that should run in your build. The sample contains a table without a policy, &lt;code&gt;leave_requests&lt;/code&gt;, so that the check has something to find.&lt;/p&gt;
&lt;p&gt;The demo has limits. The tenant comes from an &lt;code&gt;X-Tenant&lt;/code&gt; header, not from a token. The &lt;code&gt;POST&lt;/code&gt; endpoints accept a tenant id in the body on purpose, to show what each layer does with it. Views, a &lt;code&gt;BYPASSRLS&lt;/code&gt; role for support and the cost of policies on large tables are described above but not shown.&lt;/p&gt;
&lt;h2&gt;Further reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/ddl-rowsecurity.html&quot;&gt;PostgreSQL: row security policies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/sql-createpolicy.html&quot;&gt;PostgreSQL: CREATE POLICY&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/ef/core/querying/filters&quot;&gt;EF Core: global query filters&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/ef/core/logging-events-diagnostics/interceptors&quot;&gt;EF Core: interceptors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://gdpr-info.eu/art-33-gdpr/&quot;&gt;GDPR, Article 33: notification of a personal data breach&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;p&gt;This article is part of &lt;em&gt;Justified Complexity: Building Backends One Decision at a Time&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Updated 2026-11-12, after a review: the GDPR sentence now says who notifies whom (the service tells its customer without undue delay; the customer has 72 hours, where feasible, to notify the regulator); added that the policy trusts the tenant value the application sets, so it guards against a forgotten filter and not against a wrong tenant or injected SQL. The &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/tenant-isolation&quot;&gt;sample&#39;s&lt;/a&gt; demo client now reports a failed request instead of counting it as no rows.&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Two people edited the same invoice</title>
    <link href="https://nstanev.com/blog/two-people-edited-the-same-invoice/" />
    <updated>2026-09-22T00:00:00Z</updated>
    <id>https://nstanev.com/blog/two-people-edited-the-same-invoice/</id>
    <content type="html">&lt;p&gt;A customer calls on Monday and asks for two more weeks to pay. Alice in accounts opens invoice INV-3001, moves the due date from 30 September to 15 October and saves. The screen says &amp;quot;Saved&amp;quot;.&lt;/p&gt;
&lt;p&gt;Bob has had the same invoice open in another tab since the morning. The customer&#39;s purchase order number has just arrived by email. He types it in and saves. The screen says &amp;quot;Saved&amp;quot;.&lt;/p&gt;
&lt;p&gt;On 1 October the system sends a payment reminder to a customer who was promised until the 15th.&lt;/p&gt;
&lt;p&gt;Bob did not touch the due date. His form sent the whole invoice back, with the due date as it was when he opened it, and the API saved what it received. Alice&#39;s change was on the record for about a minute. No error was logged, because none occurred.&lt;/p&gt;
&lt;p&gt;This article shows why an update endpoint loses changes without ever failing, why the usual fixes miss, and how a version number carried by two standard HTTP headers makes the second save fail loudly, not silently. Examples use ASP.NET Core, EF Core and PostgreSQL, but the HTTP part holds for any stack.&lt;/p&gt;
&lt;video controls=&quot;&quot; preload=&quot;none&quot; playsinline=&quot;&quot; width=&quot;1280&quot; height=&quot;720&quot; poster=&quot;https://nstanev.com/blog/images/two-people-edited-the-same-invoice-poster.jpg&quot;&gt;
  &lt;source src=&quot;https://nstanev.com/blog/videos/two-people-edited-the-same-invoice.mp4&quot; type=&quot;video/mp4&quot;&gt;
  &lt;a href=&quot;https://nstanev.com/blog/videos/two-people-edited-the-same-invoice.mp4&quot;&gt;Watch the 40-second video (MP4)&lt;/a&gt;
&lt;/video&gt;
&lt;p&gt;&lt;em&gt;The whole argument in 40 seconds.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;The version everyone writes first&lt;/h2&gt;
&lt;p&gt;Load nothing, check nothing, save what arrived:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;MapPut&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/invoices/{id:int}&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt;&lt;/span&gt; id&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;InvoiceUpdate&lt;/span&gt; update&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AppDb&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;CancellationToken&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;var&lt;/span&gt;&lt;/span&gt; changed &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Invoices&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Where&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;i &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; i&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Id &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; id&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;ExecuteUpdateAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;s &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; s
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SetProperty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;i &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; i&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Customer&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; update&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Customer&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SetProperty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;i &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; i&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;PoNumber&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; update&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;PoNumber&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SetProperty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;i &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; i&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;DueDate&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; update&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;DueDate&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SetProperty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;i &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; i&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Total&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; update&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Total&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; changed &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;?&lt;/span&gt; Results&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;NoContent&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; Results&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;NotFound&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is what &lt;code&gt;PUT&lt;/code&gt; means: replace the resource with the representation in the request. It is correct for every request it receives. It can&#39;t know that the representation was read an hour ago.&lt;/p&gt;
&lt;p&gt;Martial wrote a couplet to go with a gift of parchment writing tablets: think of them as wax, he says, for &lt;a href=&quot;https://www.thelatinlibrary.com/martial/mart14.shtml&quot;&gt;you will rub out as often as you wish to write afresh&lt;/a&gt; (&lt;em&gt;delebis, quotiens scripta novare voles&lt;/em&gt;). That is this endpoint. Whatever was written before is wiped by whoever writes next, and the tablet keeps no memory of it.&lt;/p&gt;
&lt;h2&gt;Why it fails&lt;/h2&gt;
&lt;p&gt;Editing is three steps: read, change, write. The read and the write are two separate requests, and between them is a person: a phone call, a coffee, a tab left open since the morning.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/lost-update-two-editors.svg&quot; alt=&quot;Two sequences. Without a version check, Alice and Bob both read the invoice, Alice saves a new due date, Bob saves a PO number with the old due date, and Alice&#39;s change is overwritten. With If-Match, Bob&#39;s save carries the version he read and is refused with 412.&quot;&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Time&lt;/th&gt;
&lt;th&gt;Alice&lt;/th&gt;
&lt;th&gt;Bob&lt;/th&gt;
&lt;th&gt;Saved due date&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;09:10&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;Opens the invoice&lt;/td&gt;
&lt;td&gt;30 September&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;14:02&lt;/td&gt;
&lt;td&gt;Opens the invoice&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;30 September&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;14:03&lt;/td&gt;
&lt;td&gt;Saves: due 15 October&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;15 October&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;14:04&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;Saves: PO-7781, due 30 September&lt;/td&gt;
&lt;td&gt;30 September&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;This is called a lost update. It has nothing to do with database isolation: each &lt;code&gt;UPDATE&lt;/code&gt; ran alone, in its own transaction, and committed correctly. No transaction can span the minutes a person spends looking at a form.&lt;/p&gt;
&lt;p&gt;Two common fixes don&#39;t close the gap:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Send only the changed fields.&lt;/strong&gt; A &lt;code&gt;PATCH&lt;/code&gt; with just the PO number would have saved Alice here. It does nothing when both people change the same field, or when a value is computed from what was read, such as a total.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Lock the invoice while someone has it open.&lt;/strong&gt; Now Bob&#39;s tab blocks Alice all day. Locks held by people need timeouts, a way to break them and a screen that explains them.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The server can&#39;t see what a client read. So the client has to tell it.&lt;/p&gt;
&lt;h2&gt;The fix: say which version you edited&lt;/h2&gt;
&lt;h3&gt;1. Hand out a version with every read&lt;/h3&gt;
&lt;pre class=&quot;language-http&quot;&gt;&lt;code class=&quot;language-http&quot;&gt;GET /invoices/3001

&lt;span class=&quot;token response-status&quot;&gt;&lt;span class=&quot;token http-version property&quot;&gt;HTTP/1.1&lt;/span&gt; &lt;span class=&quot;token status-code number&quot;&gt;200&lt;/span&gt; &lt;span class=&quot;token reason-phrase string&quot;&gt;OK&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;ETag&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;&quot;838&quot;&lt;/span&gt;&lt;/span&gt;

{&quot;id&quot;:3001,&quot;number&quot;:&quot;INV-3001&quot;,&quot;customer&quot;:&quot;Acme Ltd&quot;,&quot;poNumber&quot;:null,&quot;dueDate&quot;:&quot;2026-09-30&quot;,&quot;total&quot;:100.00}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;An &lt;code&gt;ETag&lt;/code&gt; is HTTP&#39;s name for &amp;quot;this exact version of the resource&amp;quot;. The value is opaque to the client. Here it comes from PostgreSQL&#39;s &lt;code&gt;xmin&lt;/code&gt;, a system column that changes every time a row is written, mapped in EF Core as a row version:&lt;/p&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token return-type class-name&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;uint&lt;/span&gt;&lt;/span&gt; Version &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// in OnModelCreating&lt;/span&gt;
b&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-method&quot;&gt;&lt;span class=&quot;token function&quot;&gt;Entity&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;Invoice&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;Property&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;i &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; i&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Version&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;IsRowVersion&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;2. Require it on every write&lt;/h3&gt;
&lt;pre class=&quot;language-http&quot;&gt;&lt;code class=&quot;language-http&quot;&gt;PUT /invoices/3001
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;If-Match&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;&quot;838&quot;&lt;/span&gt;&lt;/span&gt;

{&quot;customer&quot;:&quot;Acme Ltd&quot;,&quot;poNumber&quot;:&quot;PO-7781&quot;,&quot;dueDate&quot;:&quot;2026-09-30&quot;,&quot;total&quot;:100.00}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;If-Match&lt;/code&gt; makes the request conditional: do this only if the resource is still at this version. A request without the header gets 428 Precondition Required, the status code defined for exactly this refusal. If the header were optional, the clients most likely to lose updates would be the ones that leave it out.&lt;/p&gt;
&lt;h3&gt;3. Compare in the statement that writes&lt;/h3&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code class=&quot;language-csharp&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Version &lt;span class=&quot;token operator&quot;&gt;!=&lt;/span&gt; version&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;Stale&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;   &lt;span class=&quot;token comment&quot;&gt;// 412 Precondition Failed&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Customer &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; update&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Customer&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;PoNumber &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; update&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;PoNumber&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;DueDate &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; update&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;DueDate&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
invoice&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Total &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; update&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Total&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;try&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; db&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;SaveChangesAsync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;ct&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;catch&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;DbUpdateConcurrencyException&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;Stale&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There are two checks, and both are needed.&lt;/p&gt;
&lt;p&gt;The second one is the guarantee, and it has no line of its own in this code. Because &lt;code&gt;Version&lt;/code&gt; is mapped as a row version, EF Core sends &lt;code&gt;UPDATE ... WHERE id = @id AND xmin = @version&lt;/code&gt;, with the version it read, which the first check has just shown to be the one the client edited. The database compares and writes in one statement, so two requests that arrive together can&#39;t both pass. This is the lesson of &lt;a href=&quot;https://nstanev.com/blog/database-constraint-beats-async-validator/&quot;&gt;A database constraint beats an async validator&lt;/a&gt; again: a check in application code followed by a write is a race, and only the database can do both at once.&lt;/p&gt;
&lt;p&gt;The first one covers a case I found by getting it wrong. If the row already holds exactly the values in the request, EF Core sees nothing to change and sends no &lt;code&gt;UPDATE&lt;/code&gt;, so the database is never asked. In the sample&#39;s first version, twenty people added 10.00 to the same total from the same stale copy, and seven of them got 200: one real save, and six requests whose target value was already there. Each of those six had asked for an increase that never happened. The explicit comparison answers them 412.&lt;/p&gt;
&lt;h3&gt;4. Answer the stale save with 412&lt;/h3&gt;
&lt;pre class=&quot;language-http&quot;&gt;&lt;code class=&quot;language-http&quot;&gt;&lt;span class=&quot;token response-status&quot;&gt;&lt;span class=&quot;token http-version property&quot;&gt;HTTP/1.1&lt;/span&gt; &lt;span class=&quot;token status-code number&quot;&gt;412&lt;/span&gt; &lt;span class=&quot;token reason-phrase string&quot;&gt;Precondition Failed&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token header&quot;&gt;&lt;span class=&quot;token header-name keyword&quot;&gt;Content-Type&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token header-value&quot;&gt;application/problem+json&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;token application-json&quot;&gt;
&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token string-property property&quot;&gt;&quot;type&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;https://errors.acme.example/invoice-changed&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token string-property property&quot;&gt;&quot;title&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;The invoice was changed by someone else&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token string-property property&quot;&gt;&quot;status&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;412&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token string-property property&quot;&gt;&quot;detail&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;Read it again, apply your change to the current version and retry.&quot;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;412 is the status for a precondition in the request headers that turned out to be false. If the version travels in the body, 409 is the usual answer, since there is no header precondition to fail; that fits the reasoning in &lt;a href=&quot;https://nstanev.com/blog/400-or-422/&quot;&gt;400 or 422?&lt;/a&gt;, where 409 means the resource&#39;s current state says no. Pick one of the two designs and document it. The headers have one advantage: every HTTP client, proxy and API tool already knows what they mean.&lt;/p&gt;
&lt;p&gt;What the client does with a 412 depends on who is behind it. A program reads again, applies its change to the current version and retries. A screen shows the person what changed and lets them decide.&lt;/p&gt;
&lt;p&gt;In Athens, &lt;a href=&quot;https://www.perseus.tufts.edu/hopper/text?doc=Perseus%3Atext%3A1999.01.0002%3Aspeech%3D3%3Asection%3D38&quot;&gt;Aeschines&lt;/a&gt; says, the law required the magistrates to review the laws every year, and where two contradicted each other, to bring both before the people, who voted to keep one, so that for each matter there would be one law and no more. A 412 does the same with two edits. It can&#39;t know which one is right, so it refuses to choose in silence and sends the question back to someone who can.&lt;/p&gt;
&lt;h2&gt;What the sample counts&lt;/h2&gt;
&lt;p&gt;Twenty people each add 10.00 to an invoice of 100.00 at the same moment. The total should end at 300.00.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://nstanev.com/blog/images/lost-update-twenty-edits.svg&quot; alt=&quot;Four bars for the final total after twenty simultaneous edits of 10.00 each. No version check: 110.00, nineteen updates lost silently. If-Match: 110.00, nineteen refused with 412. If-Match with retry: 300.00. One UPDATE statement: 300.00.&quot;&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Approach&lt;/th&gt;
&lt;th&gt;Answers&lt;/th&gt;
&lt;th&gt;Final total&lt;/th&gt;
&lt;th&gt;Changes not applied&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;No version check&lt;/td&gt;
&lt;td&gt;20 × 204&lt;/td&gt;
&lt;td&gt;110.00&lt;/td&gt;
&lt;td&gt;19, and nobody knows&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;If-Match&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;1 × 200, 19 × 412&lt;/td&gt;
&lt;td&gt;110.00&lt;/td&gt;
&lt;td&gt;19, and each client knows&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;If-Match&lt;/code&gt;, client retries on 412&lt;/td&gt;
&lt;td&gt;20 × 200 after 86 attempts&lt;/td&gt;
&lt;td&gt;300.00&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;One &lt;code&gt;UPDATE&lt;/code&gt; that adds 10.00&lt;/td&gt;
&lt;td&gt;20 × 204&lt;/td&gt;
&lt;td&gt;300.00&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The first two rows end at the same total, and they are completely different outcomes. In the first, nineteen people were told their change was saved. Propertius once lost his writing tablets and mourned what went with them: &lt;a href=&quot;https://www.thelatinlibrary.com/prop3.html&quot;&gt;&lt;em&gt;scripta quibus pariter tot periere bona&lt;/em&gt;&lt;/a&gt;, so many good things written on them, lost together. He at least knew they were gone, and offered a reward.&lt;/p&gt;
&lt;h2&gt;What the version asks of you&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Every client has to handle 412.&lt;/strong&gt; A client that treats it as a generic failure and shows &amp;quot;something went wrong&amp;quot; has gained little. Decide what the screen does: reload, show a comparison, or merge when the changes don&#39;t overlap.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;xmin&lt;/code&gt; has edges.&lt;/strong&gt; It changes on every write to the row, including writes to columns the API doesn&#39;t expose and writes by triggers. It is a 32-bit transaction id and can change after a dump and restore. Where that matters, use a version column that the application increments.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Every write needs it, not only &lt;code&gt;PUT&lt;/code&gt;.&lt;/strong&gt; A &lt;code&gt;PATCH&lt;/code&gt; or a &lt;code&gt;DELETE&lt;/code&gt; on a stale version loses information in the same way.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Lists need the version too.&lt;/strong&gt; An &lt;code&gt;ETag&lt;/code&gt; header describes one resource. In a collection, put each item&#39;s version in its body, or make the client read an item before it edits it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Retries multiply under contention.&lt;/strong&gt; The third row above needed 86 attempts, each a read and a write, for 20 changes. Optimistic concurrency assumes conflicts are rare. For a row that many writers change at once, use the fourth row&#39;s approach or a queue.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Strong comparison.&lt;/strong&gt; &lt;code&gt;If-Match&lt;/code&gt; never matches a weak &lt;code&gt;ETag&lt;/code&gt; (&lt;code&gt;W/&amp;quot;...&amp;quot;&lt;/code&gt;). &lt;code&gt;If-Match: *&lt;/code&gt; means &amp;quot;any version, as long as it exists&amp;quot;; decide whether to allow it.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;When you don&#39;t need a version&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Situation&lt;/th&gt;
&lt;th&gt;Smaller answer&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;The change is relative: add an amount, increment a counter&lt;/td&gt;
&lt;td&gt;One &lt;code&gt;UPDATE ... SET total = total + @amount&lt;/code&gt;. The database serialises the writers&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The change adds something: a line, a comment, a payment&lt;/td&gt;
&lt;td&gt;Insert a row. Two inserts don&#39;t overwrite each other&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;One writer per resource, such as a user&#39;s own profile&lt;/td&gt;
&lt;td&gt;Nothing, as long as the same user in two tabs is acceptable&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;The last value is all that matters, such as a &amp;quot;last seen&amp;quot; time&lt;/td&gt;
&lt;td&gt;Last write wins is the correct behaviour&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Reach for the version when people edit shared records through forms, which is most business software.&lt;/p&gt;
&lt;h2&gt;The rule&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;A save without a version is a guess about what the client saw.&lt;/strong&gt; The read and the write are minutes apart, and no transaction covers them.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hand out a version on every read and require it on every write.&lt;/strong&gt; &lt;code&gt;ETag&lt;/code&gt; out, &lt;code&gt;If-Match&lt;/code&gt; in, 428 when it is missing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Refuse the stale save where the write happens, and say so.&lt;/strong&gt; Compare in the &lt;code&gt;UPDATE&lt;/code&gt; itself and answer 412, so that losing a change is a decision somebody makes.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Run it yourself&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/lost-update&quot;&gt;companion sample&lt;/a&gt; is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. A small client plays Alice and Bob, then twenty simultaneous editors.&lt;/p&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose up &lt;span class=&quot;token parameter variable&quot;&gt;-d&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;--build&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;token function&quot;&gt;docker&lt;/span&gt; compose run &lt;span class=&quot;token parameter variable&quot;&gt;--rm&lt;/span&gt; demo&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output on my machine:&lt;/p&gt;
&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;1. Alice and Bob open the same invoice. Alice changes the due date, then Bob adds a PO number.
   no version check:  Alice 204, Bob 204. Saved: due 2026-09-30, PO PO-7781   &lt;- Alice&#39;s change is gone
   If-Match:          Alice 200, Bob 412. Saved: due 2026-10-15, PO none   &lt;- Bob is told to reload

2. 20 people each add 10.00 to an invoice of 100.00 at the same moment. The total should be 300.00.
   no version check:      20 x 204. Total: 110.00, 19 update(s) not applied
   If-Match:              1 x 200, 19 x 412. Total: 110.00, 19 update(s) not applied
   If-Match + retry:      20 x 200 after 86 attempts in total
                          Total: 300.00, 0 update(s) not applied
   one UPDATE statement:  20 x 204. Total: 300.00, 0 update(s) not applied

3. A save that does not say which version it edited
   PUT /invoices/2 without If-Match: 428&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The number of attempts in the retry line changes from run to run; the client checks everything else and exits with code 1 if anything differs.&lt;/p&gt;
&lt;p&gt;The demo has limits. Its editors are programs that all read first and then all write, which is the worst case arranged on purpose. The retrying client simply reapplies its change; a real screen would show the person what changed. The README explains the two checks and the &lt;code&gt;xmin&lt;/code&gt; caveats.&lt;/p&gt;
&lt;h2&gt;Further reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9110#name-if-match&quot;&gt;RFC 9110: If-Match&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9110#name-412-precondition-failed&quot;&gt;RFC 9110: 412 Precondition Failed&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc6585#section-3&quot;&gt;RFC 6585: 428 Precondition Required&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/ef/core/saving/concurrency&quot;&gt;EF Core: handling concurrency conflicts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.npgsql.org/efcore/modeling/concurrency.html&quot;&gt;Npgsql EF Core provider: concurrency tokens&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.postgresql.org/docs/current/ddl-system-columns.html&quot;&gt;PostgreSQL: system columns&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;p&gt;This article is part of &lt;em&gt;Justified Complexity: Building Backends One Decision at a Time&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Updated 2026-11-12, after a review: the code set the row version&#39;s original value before saving, and the text credited that line with the &lt;code&gt;AND xmin = ...&lt;/code&gt; in the &lt;code&gt;UPDATE&lt;/code&gt;. The row-version mapping does that; after the explicit comparison the line changed nothing, so it is removed here and in the &lt;a href=&quot;https://github.com/nsstanev/justified-complexity/tree/main/samples/lost-update&quot;&gt;sample&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
</feed>