<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Irina Scurtu</title>
    <description>The latest articles on DEV Community by Irina Scurtu (@irina_scurtu).</description>
    <link>https://dev.to/irina_scurtu</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F140520%2Ff26e8061-d6dd-457b-8530-e7ae5de8194c.jpg</url>
      <title>DEV Community: Irina Scurtu</title>
      <link>https://dev.to/irina_scurtu</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/irina_scurtu"/>
    <language>en</language>
    <item>
      <title>Publish Events, Send Commands</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 17 Nov 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/publish-events-send-commands-4kg7</link>
      <guid>https://dev.to/irina_scurtu/publish-events-send-commands-4kg7</guid>
      <description>&lt;p&gt;&lt;em&gt;A command with no owner is a &lt;code&gt;request&lt;/code&gt; nobody has to answer.&lt;/em&gt;&lt;/p&gt;

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

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

&lt;h2&gt;
  
  
  Commands vs events: two kinds of ownership
&lt;/h2&gt;

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

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

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

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

&lt;h2&gt;
  
  
  What publishing a command actually does
&lt;/h2&gt;

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

&lt;p&gt;Here's how it goes wrong. Your checkout service publishes &lt;code&gt;ChargeCustomer&lt;/code&gt;. The payments service subscribes. Everything works for a year.&lt;/p&gt;

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

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

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

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7c9n65uv7lrf3jt5mc4u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7c9n65uv7lrf3jt5mc4u.png" alt="Left panel, Send: Checkout sends ChargeCustomer to a payments queue with a single Payments owner. Right panel, Publish: Checkout publishes ChargeCustomer to a topic that fans out to a Card service and a Wallet service, both of which charge, while a second topic with no subscribers receives it and nothing happens." width="799" height="353"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The code should say which one you mean
&lt;/h2&gt;

&lt;p&gt;In NServiceBus, the verb is the decision:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="c1"&gt;// A request with one owner&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ChargeCustomer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;orderId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// A fact, for whoever cares&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Publish&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;OrderPlaced&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;orderId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;NServiceBus goes further and enforces it. The &lt;a href="https://docs.particular.net/nservicebus/messaging/messages-events-commands" rel="noopener noreferrer"&gt;docs on messages, events, and commands&lt;/a&gt; say a command "should be sent to the logical owner" and "cannot be subscribed to", while an event "should be published by the logical owner". Get it wrong and it throws. Publish a command and you get:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"Pub/Sub is not supported for Commands. They should be sent directly to their logical owner."&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Send an event and you get:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"Events can have multiple recipients so they should be published."&lt;/p&gt;
&lt;/blockquote&gt;

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

&lt;p&gt;MassTransit is more relaxed. Its &lt;a href="https://masstransit.massient.com/documentation/concepts/messages" rel="noopener noreferrer"&gt;message docs&lt;/a&gt; use the same vocabulary: a command "tells a service to do something, and typically a command should only be consumed by a single consumer", while events "are published (using &lt;code&gt;Publish&lt;/code&gt;)". But the docs also say commands may be published and will be routed to the consumer. Nothing stops you. So I treat it as a convention you enforce in code review: &lt;code&gt;Send&lt;/code&gt; to an endpoint for commands, &lt;code&gt;Publish&lt;/code&gt; for events.&lt;/p&gt;

&lt;h2&gt;
  
  
  When a command wants to be an event
&lt;/h2&gt;

&lt;p&gt;Sometimes a published command is a sign the message is named wrong.&lt;/p&gt;

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

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

&lt;p&gt;A useful test: &lt;strong&gt;if nobody handles this message, is that a bug?&lt;/strong&gt; If yes, it's a command. If no, it's an event.&lt;/p&gt;

&lt;h2&gt;
  
  
  When pub/sub is the wrong tool
&lt;/h2&gt;

&lt;p&gt;There are a few cases where I'd skip pub/sub altogether:&lt;/p&gt;

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

&lt;p&gt;Notice how many of these describe commands in disguise. "I need an answer now" and "it must happen exactly once as part of my transaction" are things a sender says about work it depends on. I wrote about the saga side of this in &lt;a href="https://irina.codes/when-business-processes-outlive-your-request/" rel="noopener noreferrer"&gt;When Business Processes Outlive Your Request&lt;/a&gt;: the orchestrator sends commands and reacts to events, and it never mixes the two up.&lt;/p&gt;

&lt;h2&gt;
  
  
  Who owns the schema
&lt;/h2&gt;

&lt;p&gt;Ownership shows up again when messages change.&lt;/p&gt;

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

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

&lt;h2&gt;
  
  
  What this means in practice
&lt;/h2&gt;

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

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

&lt;p&gt;The broker will carry your commands. It just won't tell you who picked them up, or that nobody did.&lt;/p&gt;

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

</description>
      <category>architecture</category>
      <category>microservices</category>
      <category>softwareengineering</category>
      <category>systemdesign</category>
    </item>
    <item>
      <title>Scaling Out Your Consumers Can Take Down Your Database</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 10 Nov 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/scaling-out-your-consumers-can-take-down-your-database-11lp</link>
      <guid>https://dev.to/irina_scurtu/scaling-out-your-consumers-can-take-down-your-database-11lp</guid>
      <description>&lt;p&gt;&lt;em&gt;The queue was never the thing that needed protecting.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Imagine this scenario. A bulk of 40,000 messages lands at 9:00, you scale out and add competing consumers, and by 9:12 queue depth is back to zero. Green everywhere. Success! But there is a different side to this story.&lt;/p&gt;

&lt;p&gt;The database has been returning errors for ten minutes. Orders that sat safely in the queue at 9:00 are now in the dead-letter queue, the retry policy limit is exhausted now, and the on-call engineer is staring at Azure SQL error 10928: &lt;code&gt;The request limit for the database is 120 and has been reached&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Nothing broke in the messaging layer. It did exactly what we asked, and we asked for the wrong thing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two patterns that pull in opposite directions
&lt;/h2&gt;

&lt;p&gt;Competing consumers and a queue for load leveling almost always ship together. The first is about throughput: you add consumers, and with autoscaling the instance count follows message volume. The second is about protection: the queue absorbs the spike so the database behind it doesn't have to.&lt;/p&gt;

&lt;p&gt;When you put them together sometimes the second promise quietly breaks. Let's disect this a little bit. A queue levels load because consumers work at their own pace. When you autoscale based on queue depth, the pace becomes "as fast as the backlog demands." At that point the queue stops being a buffer. It becomes a very efficient way to move the spike to your database.&lt;/p&gt;

&lt;p&gt;The standard Azure setup shows it well: Azure Functions between a Service Bus queue and a data store. Unless you tune scale limits and trigger concurrency, the worker layer brings the contention right back to the database. &lt;strong&gt;Neither default knows anything about your database.&lt;/strong&gt; Again, autoscaling that doesn't bound the combined rate of all consumers only moves the overload to whatever sits downstream.&lt;/p&gt;

&lt;h2&gt;
  
  
  Do the multiplication
&lt;/h2&gt;

&lt;p&gt;Every consumer platform gives you two numbers: how many instances run, and how many messages each instance handles at once. Your database sees the product.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Instances x concurrency per instance = concurrent database work.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Take an Azure Functions app with a Service Bus trigger and default settings. &lt;code&gt;maxConcurrentCalls&lt;/code&gt; in &lt;code&gt;host.json&lt;/code&gt; defaults to 16 per instance. The docs add a detail that's easy to miss: on hardware with more than one core, that number is multiplied by the core count. Scale out to 20 instances and you have 320 handlers, or 640 on two cores, each able to open a transaction at the same moment.&lt;/p&gt;

&lt;p&gt;Now the other side. A Standard S2 Azure SQL database allows 120 concurrent workers. An S3 allows 200. Past that limit, Azure SQL rejects new requests with error 10928. The message still says "request limit" for backward compatibility, but what ran out is workers. A parallel query plan uses more than one worker, so you can hit the ceiling with fewer requests than you'd expect. Cosmos DB tells the same story in different words: exceed your provisioned RU/s and you get 429s.&lt;/p&gt;

&lt;p&gt;Your connection pool won't save you either. SqlClient's &lt;code&gt;Max Pool Size&lt;/code&gt; defaults to 100, but that's per process. Twenty instances means twenty pools and up to 2,000 connections. The pool limits each instance. Nothing limits the fleet.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsg36xwysig7rdrt2h6xg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsg36xwysig7rdrt2h6xg.png" alt="A queue at depth zero feeds 20 consumer instances, each running 16 messages at once, for 320 in flight against an Azure SQL S2 database with 120 workers, which answers with error 10928. The fix is labelled underneath: cap instances and cap concurrency." width="799" height="197"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Lowering concurrency can add instances
&lt;/h2&gt;

&lt;p&gt;No page in the docs says this outright. It falls out of the math.&lt;/p&gt;

&lt;p&gt;Azure Functions scales Service Bus triggers with target-based scaling, and the documented formula is simple: desired instances = queue length / target executions per instance. For a single-dispatch Service Bus trigger, target executions per instance &lt;em&gt;is&lt;/em&gt; &lt;code&gt;maxConcurrentCalls&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now follow the formula through. You see the database struggling and drop &lt;code&gt;maxConcurrentCalls&lt;/code&gt; from 16 to 4 to ease the pressure. With 320 messages waiting, the formula asked for 20 instances before the change. After it, the formula asks for 80. Each instance does less, so the platform wants four times as many: 20 x 16 and 80 x 4 are both 320 messages in flight. Unless an instance cap stops it, the load on your database doesn't change.&lt;/p&gt;

&lt;p&gt;Container Apps behaves the same way. KEDA computes &lt;code&gt;desiredReplicas = ceil(queueLength / messageCount)&lt;/code&gt;, bounded only by &lt;code&gt;maxReplicas&lt;/code&gt;. A smaller &lt;code&gt;messageCount&lt;/code&gt; means more replicas.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The per-instance limit and the instance cap only protect the database together.&lt;/strong&gt; Either one alone is a suggestion.&lt;/p&gt;

&lt;p&gt;NServiceBus and MassTransit have the same trap without the scaler. &lt;code&gt;LimitMessageProcessingConcurrencyTo&lt;/code&gt; applies per endpoint instance, and the Particular docs spell it out: three instances with a limit of 4 means 12. MassTransit's docs say &lt;code&gt;ConcurrentMessageLimit&lt;/code&gt; at bus level "provides a default for each endpoint, not a shared limit across the bus." Every limit you set is local. T &lt;strong&gt;he database on the other hand only cares about the global one.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Retries turn a slow database into a full dead-letter queue
&lt;/h2&gt;

&lt;p&gt;An overloaded database rarely fails cleanly. Queries slow down, lock waits grow, and handlers start timing out.&lt;/p&gt;

&lt;p&gt;Then the retries start, and there are more layers of them than most teams count. The Cosmos DB .NET SDK retries a 429 up to 9 times by default before your code sees an exception. If the handler still fails, the Functions runtime abandons the message and Service Bus redelivers it, up to &lt;code&gt;MaxDeliveryCount&lt;/code&gt;, which defaults to 10. In the worst case, a message that makes one Cosmos DB call becomes &lt;strong&gt;100 requests&lt;/strong&gt; against a database that was already saying no.&lt;/p&gt;

&lt;p&gt;After the tenth failed delivery, a perfectly valid message moves to the dead-letter queue with reason &lt;code&gt;MaxDeliveryCountExceeded&lt;/code&gt;. Nothing was wrong with it. It just arrived during the wrong five minutes. Your DLQ alert, the one I told you to set up, now fires for thousands of healthy orders, and someone has to replay them after the database recovers.&lt;/p&gt;

&lt;p&gt;That's what makes incidents like these expensive. Queue depth at zero looked like success. In reality the backlog moved from the one place built to hold it, the broker, into two places that weren't: the database and the DLQ.&lt;/p&gt;

&lt;h2&gt;
  
  
  What else competing consumers cost you
&lt;/h2&gt;

&lt;p&gt;Competing consumers cost you a few more things.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Ordering is gone.&lt;/strong&gt; With more than one consumer, processing order is not guaranteed. Service Bus sessions give you FIFO per session, with one consumer holding a session at a time.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Results have nowhere to go.&lt;/strong&gt; The consumer is decoupled from the caller. If a result must come back, you need a reply queue or shared storage, a way to signal "done", and correlation back to the original request.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The queue itself can become the bottleneck.&lt;/strong&gt; At high enough volume one queue saturates. The usual fix is partitioning across queues, which brings the ordering question right back.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can live with all three, as long as you choose them on purpose.&lt;/p&gt;

&lt;h2&gt;
  
  
  What this means in practice
&lt;/h2&gt;

&lt;p&gt;Start from the database and work backwards. Decide how much concurrent work the downstream resource can take, and leave headroom for everything else that uses it: the API, reports, the nightly job. That number is your budget. Instances x concurrency has to fit inside it.&lt;/p&gt;

&lt;p&gt;Then set both knobs:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Platform&lt;/th&gt;
&lt;th&gt;Per-instance concurrency&lt;/th&gt;
&lt;th&gt;Instance cap&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Azure Functions, Service Bus trigger&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;maxConcurrentCalls&lt;/code&gt; in &lt;code&gt;host.json&lt;/code&gt; (default 16, multiplied by cores)&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;functionAppScaleLimit&lt;/code&gt; (Consumption, Premium) or maximum instance count (Flex Consumption)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Azure Container Apps&lt;/td&gt;
&lt;td&gt;your consumer's own setting&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;maxReplicas&lt;/code&gt; (default 10)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NServiceBus&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;LimitMessageProcessingConcurrencyTo&lt;/code&gt; (default: logical processors, minimum 2)&lt;/td&gt;
&lt;td&gt;whatever hosts the endpoint&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;MassTransit&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;ConcurrentMessageLimit&lt;/code&gt;, &lt;code&gt;PrefetchCount&lt;/code&gt; (default max(CPU count x 2, 16))&lt;/td&gt;
&lt;td&gt;whatever hosts the endpoint&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;A few rules I follow:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Cap instances explicitly.&lt;/strong&gt; The Functions docs say restricting scale-out is "most common for cases where a downstream component like a database has limited throughput." That's you.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Treat the budget as a bulkhead.&lt;/strong&gt; Consumers on different queues that hit the same database share one budget. Split it, so a flood on the reporting queue can't take the capacity the checkout handler needs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Count every retry layer.&lt;/strong&gt; SDK retries, handler retries, redeliveries. Multiply them and make sure the product is survivable.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Alert on the database as well as the queue.&lt;/strong&gt; Worker percentage, 429 rate, lock waits, DLQ depth. A falling queue is good news only while the database is healthy.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Let the queue grow.&lt;/strong&gt; A backlog that drains in 40 minutes at a safe rate is the pattern working. If the average arrival rate stays above what the database can take, you need a bigger database or load shedding at the producer. More consumers won't help.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Closing
&lt;/h2&gt;

&lt;p&gt;How many consumers you run is a database decision that we keep making in the messaging layer, because that's where the slider lives. The queue will hold 40,000 messages for as long as you need. Your database won't hold an infinite number of concurrent transactions.&lt;/p&gt;

&lt;p&gt;Go and multiply your instance cap by your per-instance concurrency. If you don't have an instance cap, that's your answer.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>backend</category>
      <category>database</category>
      <category>scalability</category>
    </item>
    <item>
      <title>A Queue Is a Shock Absorber, Not a Pump</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 03 Nov 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/a-queue-is-a-shock-absorber-not-a-pump-1p1h</link>
      <guid>https://dev.to/irina_scurtu/a-queue-is-a-shock-absorber-not-a-pump-1p1h</guid>
      <description>&lt;p&gt;&lt;em&gt;A queue will buy you time, but it doesn't buy you throughput.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Putting a queue in front of a struggling service feels like a fix. The API stops timing out, the database stops falling, the error graph goes flatter. The pattern even has a reassuring name: &lt;strong&gt;Queue-Based Load Leveling&lt;/strong&gt;. And it does what the name says. It levels load, but it doesn't reduce it.&lt;/p&gt;

&lt;p&gt;That difference is invisible on the day you add the queue. It shows up weeks later, when the queue is deeper every morning than the morning before and nobody can say when it started.&lt;/p&gt;

&lt;h2&gt;
  
  
  A shock absorber, not a pump
&lt;/h2&gt;

&lt;p&gt;Picture a kitchen that cooks 60 dishes an hour. On Friday at 8pm, 100 orders come in within the hour. The order tickets pile up, the cooks keep their pace, and people wait a bit longer for their food. After 9pm, orders drop to 30 an hour. By half past ten the pile is gone, and the kitchen closes on time.&lt;/p&gt;

&lt;p&gt;Now make it 70 orders an hour, all evening. The pile never goes away. By 11pm there are 40 orders waiting, each new order waits 40 minutes, and every hour adds ten more.&lt;/p&gt;

&lt;p&gt;In both cases the pile did the same job: it held the orders until the cooks got to them. That's all a queue does. &lt;strong&gt;It stores extra work and hands it out later&lt;/strong&gt; , like a shock absorber. The bump is still there, just spread out over time. If the consumers can't keep up on average, the queue turns extra work into waiting, and the wait keeps growing.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fum684xqtihr6qc76pn90.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fum684xqtihr6qc76pn90.png" alt="A kitchen that plates 60 dishes an hour, shown twice. On the Friday spike, 100 orders in one hour leave a few tickets waiting, and everything is served by 10:30pm. When 70 orders arrive every hour, the tickets keep piling up, ten more each hour, and the pile never empties." width="800" height="395"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The arithmetic of a spike
&lt;/h2&gt;

&lt;p&gt;Let's put numbers on it, in messaging terms. Your consumers process 600 messages per second. A spike sends 1,000 messages per second for ten minutes, then traffic drops back to its normal 300.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;During the spike: 1,000 in, 600 out, for 600 s
Backlog: (1,000 - 600) x 600 = 240,000 messages
Last one in waits: 240,000 / 600 = 400 s (6 min 40 s)

After the spike: 300 in, 600 out -&amp;gt; drains at 300 msg/s
Drain time: 240,000 / 300 = 800 s (13 min 20 s)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A ten-minute spike costs you 23 minutes and 20 seconds of elevated latency. The drain is longer than the spike itself.&lt;/p&gt;

&lt;p&gt;Look at what sets the drain speed: your &lt;strong&gt;headroom&lt;/strong&gt; , meaning capacity minus normal traffic. With 300 messages per second of headroom, 240,000 messages take 13 minutes. If normal traffic were 550 instead of 300, the headroom drops to 50, and the same backlog takes 80 minutes to clear. If another spike lands before that, you start the next one with a head start in the wrong direction.&lt;/p&gt;

&lt;p&gt;The usual argument for a queue is that you can size consumers for average load instead of peak load. That holds, and the catch is in the word &lt;em&gt;average&lt;/em&gt;. For that hour, the average is (600,000 + 900,000) / 3,600, about 417 messages per second. That's comfortably under 600, so the queue does its job. But the average includes the spike, and your capacity still needs room above it to drain before the next one arrives.&lt;/p&gt;

&lt;h2&gt;
  
  
  When the average itself is the problem
&lt;/h2&gt;

&lt;p&gt;Change one number. Traffic sits at 700 messages per second, steady, against the same 600.&lt;/p&gt;

&lt;p&gt;That's 100 extra messages every second, 360,000 every hour. Each hour of traffic adds ten minutes to the wait. After a day you have 8.64 million messages and the newest one waits four hours. Nothing drains, because there is no quiet period to drain into.&lt;/p&gt;

&lt;p&gt;A queue can't fix this. Neither can a bigger queue. I said it in the backpressure carousel and I stand by it: unbounded queues are delayed failures. Let's take Azure Service Bus for example. It will eventually say no for you, since a queue at its size limit rejects sends with a &lt;code&gt;QuotaExceeded&lt;/code&gt; error. That's the worst moment and the worst place to find out.&lt;/p&gt;

&lt;p&gt;So watch the direction, not a fixed threshold. A depth of 50,000 during a sale can be fine. A depth that is higher at the end of every day than at the start is not. Depending on what you are using you can also measure age directly: &lt;code&gt;ServiceBusReceivedMessage.EnqueuedTime&lt;/code&gt; tells the consumer how long each message waited, and that number maps to what your users feel.&lt;/p&gt;

&lt;p&gt;When the average is too high, you have two honest options. Add real capacity, or shed work at the producer before it enters the queue. I wrote about how to do the second one in &lt;a href="https://irina.codes/load-shedding-dropping-requests-to-save-your-system/" rel="noopener noreferrer"&gt;Load Shedding: Dropping Requests to Save Your System&lt;/a&gt;. A &lt;code&gt;503&lt;/code&gt; with &lt;code&gt;Retry-After&lt;/code&gt; at the front door is kinder than a four-hour wait nobody told the caller about.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5mz5l76d4l5o0tj5a70g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5mz5l76d4l5o0tj5a70g.png" alt="Queue depth over ten minutes of 1,000 messages per second against 600 per second of capacity. The backlog peaks at 240,000 messages at minute 10 and drains to zero around minute 23 once traffic drops to 300 per second. A dashed line for 700 in and 600 out keeps climbing and never drains." width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Scaling the consumers can move the overload
&lt;/h2&gt;

&lt;p&gt;The obvious fix is to scale the consumers on queue depth: more instances reading from the same queue, each taking the next message, which is the &lt;a href="https://irina.codes/competing-consumers-pattern-the-underrated-key-to-handling-more-load/" rel="noopener noreferrer"&gt;Competing Consumers pattern&lt;/a&gt;. Azure Functions does this out of the box. With target-based scaling on a Service Bus trigger, the desired instance count is the queue length divided by &lt;code&gt;maxConcurrentCalls&lt;/code&gt;, which defaults to 16.&lt;/p&gt;

&lt;p&gt;Run our 240,000-message backlog through that. The formula asks for 15,000 instances. On the Flex Consumption plan, the default cap is 100 instances, so you get 100. That is 1,600 concurrent handlers - more on multi-core plans, where &lt;code&gt;maxConcurrentCalls&lt;/code&gt; is multiplied by the number of cores. All of them are now hitting the database you put the queue in front of to protect.&lt;/p&gt;

&lt;p&gt;The queue is empty again, and the overload moved one hop down. The number that matters is instances times per-instance concurrency, and it should come from what the downstream can take.&lt;/p&gt;

&lt;p&gt;In Azure Functions that means capping both numbers. &lt;code&gt;maxConcurrentCalls&lt;/code&gt; in &lt;code&gt;host.json&lt;/code&gt; sets the handlers per instance, and &lt;code&gt;--maximum-instance-count&lt;/code&gt; on Flex Consumption or &lt;code&gt;functionAppScaleLimit&lt;/code&gt; on Consumption and Premium sets how many instances you get. Multiply the two before you trust either one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Aging messages
&lt;/h2&gt;

&lt;p&gt;Some messages age well. An invoice email sent 20 minutes late is fine. A "your driver is two minutes away" push notification sent 20 minutes late is noise.&lt;/p&gt;

&lt;p&gt;Remember the 6 minutes 40 seconds from the spike example. If the data inside a message has a shelf life shorter than your worst drain, processing it late is wasted work. Worse, it slows down the drain for messages that still matter.&lt;/p&gt;

&lt;p&gt;Many frameworks let you say specify the &lt;code&gt;TimeToLive&lt;/code&gt;, same for Azure Service Bus.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ServiceBusMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;TimeToLive&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;TimeSpan&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;FromMinutes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;SendMessageAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;TTL on Standard and Premium is effectively forever, so nothing expires unless you ask. And expired messages are dropped unless the queue has &lt;code&gt;DeadLetteringOnMessageExpiration&lt;/code&gt; enabled. Turn it on, then do something with what lands there: tell the user it's taking longer than usual, or send the work down a slower path, like an email instead of a push.&lt;/p&gt;

&lt;p&gt;Expiry is also lazy. The broker might remove expired messages later, and a message already locked by a consumer still gets processed. Treat TTL as a cleanup rule. If you need a hard deadline, check it in the handler as well.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where a queue is the wrong answer
&lt;/h2&gt;

&lt;p&gt;If the caller needs a synchronous answer, a queue doesn't help. The caller waits for the same backlog as everyone else. Six minutes and 40 seconds behind a spike is fine for an email. It's an eternity for an HTTP request someone is watching.&lt;/p&gt;

&lt;p&gt;A queue also only levels load if the buffer survives. If the broker doesn't persist messages, a crash takes the backlog with it, and in our example that's 240,000 messages. And if your traffic is low and flat, a queue levels nothing. You get a broker to run and one more hop to debug.&lt;/p&gt;

&lt;h2&gt;
  
  
  What this means in practice
&lt;/h2&gt;

&lt;p&gt;Before adding a queue for load leveling, work out a few numbers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Average arrival rate&lt;/strong&gt; , over a period that includes your spikes. If it's at or above sustained consumer throughput, stop. A queue won't help.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Headroom&lt;/strong&gt; , meaning capacity minus normal traffic. Divide your worst expected backlog by it and you have your drain time.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Downstream limit&lt;/strong&gt;. Cap instances times per-instance concurrency below it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Shelf life&lt;/strong&gt;. Set &lt;code&gt;TimeToLive&lt;/code&gt; on anything that goes stale, with dead-lettering on expiration.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then alert on the trend of depth and message age over hours, and decide ahead of time what the producer does when the queue is too deep. That decision is much easier to make on a Tuesday afternoon than during the incident.&lt;/p&gt;

&lt;h2&gt;
  
  
  Closing
&lt;/h2&gt;

&lt;p&gt;A queue is a promise to do the work later. The pattern holds as long as "later" eventually arrives, which means the spike ends and your consumers have room to catch up. When the average is too high, the queue keeps collecting promises you can't keep.&lt;/p&gt;

&lt;p&gt;PS: have you had a queue that never drained? Tell me what gave it away.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>performance</category>
      <category>scalability</category>
      <category>systemdesign</category>
    </item>
    <item>
      <title>Load Shedding: Dropping Requests to Save Your System</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 27 Oct 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/load-shedding-dropping-requests-to-save-your-system-45nb</link>
      <guid>https://dev.to/irina_scurtu/load-shedding-dropping-requests-to-save-your-system-45nb</guid>
      <description>&lt;p&gt;&lt;em&gt;Your system under pressure will either shed load deliberately or collapse accidentally.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Traffic spikes. Response times climb. Clients start retrying. The retries add more load. Response times climb further. At some point, the whole thing tips over, and every user gets nothing instead of something.&lt;/p&gt;

&lt;p&gt;Most teams I talk to reach for circuit breakers or rate limiters when this happens. Both are good tools. Neither solves this problem. The missing piece, the one that keeps your system alive when everything else is failing, is &lt;strong&gt;load shedding&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;And the reason most teams don't have it is that they think they already do.&lt;/p&gt;

&lt;h2&gt;
  
  
  What load shedding actually is (and what it isn't)
&lt;/h2&gt;

&lt;p&gt;Let me be precise about terms, because this is where most confusion starts.&lt;/p&gt;

&lt;p&gt;Rate limiting is about &lt;em&gt;identity and quota&lt;/em&gt;. You allow 100 requests per second per client. It doesn't matter how healthy your system is: if a client is over quota, they're rejected. Rate limiting protects you from individual bad actors or runaway clients.&lt;/p&gt;

&lt;p&gt;Circuit breakers are about &lt;em&gt;outbound calls&lt;/em&gt;. When a downstream service is failing, you stop calling it. The circuit breaker sits between you and your dependencies.&lt;/p&gt;

&lt;p&gt;Load shedding is different. It responds to your system's health right now. When CPU is saturating, memory is tight, or your request queue is backing up, you drop requests. It doesn't matter who sent them. Not because of policy. Because you physically cannot serve them well.&lt;/p&gt;

&lt;p&gt;The correct HTTP response for a shed request is &lt;code&gt;503 Service Unavailable&lt;/code&gt; with a &lt;code&gt;Retry-After&lt;/code&gt; header. Not &lt;code&gt;429 Too Many Requests&lt;/code&gt;: that implies the caller is the problem. &lt;code&gt;503&lt;/code&gt; says: it's us, not you, try again in a moment.&lt;/p&gt;

&lt;p&gt;A minimal implementation in ASP.NET Core 7+ looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;memoryInfo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;GC&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetGCMemoryInfo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;load&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;double&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="n"&gt;memoryInfo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;MemoryLoadBytes&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;memoryInfo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;HighMemoryLoadThresholdBytes&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;load&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mf"&gt;0.85&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="n"&gt;_activeRequests&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;_maxConcurrent&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;StatusCode&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;503&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Headers&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"Retry-After"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"5"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nc"&gt;Interlocked&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Increment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;ref&lt;/span&gt; &lt;span class="n"&gt;_activeRequests&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;Interlocked&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Decrement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;ref&lt;/span&gt; &lt;span class="n"&gt;_activeRequests&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Simple. But where you put this matters more than you might think.&lt;/p&gt;

&lt;h2&gt;
  
  
  The cost of where you shed
&lt;/h2&gt;

&lt;p&gt;Think about it: by the time your middleware runs, your system has already done a lot of work.&lt;/p&gt;

&lt;p&gt;The TCP connection was accepted. TLS was negotiated. HTTP/2 frames were parsed. Request headers were read. The ASP.NET Core pipeline started. Middleware before yours executed. Dependency injection resolved your services. Authentication ran.&lt;/p&gt;

&lt;p&gt;All of that happened before you decided to return a 503.&lt;/p&gt;

&lt;p&gt;Imagine a restaurant that seats guests, hands them menus, and takes their drink order before sending it to the kitchen. Only &lt;em&gt;then&lt;/em&gt; does it tell them the kitchen is closed. You've wasted everyone's time, including your own. &lt;strong&gt;The earlier you shed, the cheaper each rejection is.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Kestrel exposes &lt;code&gt;MaxConcurrentConnections&lt;/code&gt; and &lt;code&gt;MaxConcurrentUpgradedConnections&lt;/code&gt; for connection-level limiting, before any HTTP parsing happens. That's the cheapest possible rejection. Your custom middleware is next. Your controller is the most expensive place to shed, because by then you've done almost everything.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;WebHost&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ConfigureKestrel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;options&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;options&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Limits&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;MaxConcurrentConnections&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In practice, you often need both: Kestrel limits as a hard ceiling, middleware for health-signal-based shedding. The point is to push the decision as far left in the stack as you can.&lt;/p&gt;

&lt;h2&gt;
  
  
  Not all requests deserve equal treatment
&lt;/h2&gt;

&lt;p&gt;Here's where most load shedding implementations leave a lot on the table.&lt;/p&gt;

&lt;p&gt;Standard shedding is binary: you're over threshold, so you reject the next request in the queue. But think about what's in that queue. Health check probes from your orchestrator. Background telemetry events. An analytics batch job. And a user trying to complete a payment.&lt;/p&gt;

&lt;p&gt;These are not the same. Dropping a telemetry flush is free. Dropping a payment request has a real cost.&lt;/p&gt;

&lt;p&gt;Google's SRE team calls these &lt;em&gt;criticality labels&lt;/em&gt;: not all RPCs are equal, so you shouldn't shed them equally. In .NET 7+, you can implement the same idea with endpoint metadata and a priority-aware middleware.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SheddingPriorityAttribute&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Attribute&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;IEndpointMetadata&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;SheddingPriority&lt;/span&gt; &lt;span class="nc"&gt;Priority&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;SheddingPriorityAttribute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SheddingPriority&lt;/span&gt; &lt;span class="n"&gt;priority&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;Priority&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;priority&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;enum&lt;/span&gt; &lt;span class="nc"&gt;SheddingPriority&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;ShedFirst&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Normal&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Protected&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then in your middleware, read the priority before deciding whether to shed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;IsOverloaded&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;priority&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetEndpoint&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Metadata&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GetMetadata&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;SheddingPriorityAttribute&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Priority&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="nc"&gt;SheddingPriority&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Normal&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;priority&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="nc"&gt;SheddingPriority&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Protected&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;StatusCode&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;503&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Headers&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"Retry-After"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"5"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Apply it on your endpoints:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;MapGet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/metrics"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;WithMetadata&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;SheddingPriorityAttribute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SheddingPriority&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ShedFirst&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;MapPost&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/checkout"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;WithMetadata&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;SheddingPriorityAttribute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SheddingPriority&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Protected&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Uber described something similar in 2019. They shed roughly 10% of requests during peak events, with no measurable customer impact. The reason? They shed the &lt;em&gt;right&lt;/em&gt; 10%.&lt;/p&gt;

&lt;h2&gt;
  
  
  Static thresholds will betray you
&lt;/h2&gt;

&lt;p&gt;Most implementations I see use a static threshold: if CPU &amp;gt; 80%, start shedding. In my opinion, this is better than nothing, but it's a guess, and often a late one.&lt;/p&gt;

&lt;p&gt;Queueing theory (the M/M/1 model, if you want to look it up) tells us why. Latency doesn't degrade linearly as utilisation climbs. It degrades super-linearly. At 70% utilisation things feel fine. At 85% they start to slip. By 95% you're already in trouble, and that's when the threshold fires.&lt;/p&gt;

&lt;p&gt;The smarter signal isn't the absolute CPU value. It's the &lt;em&gt;gradient&lt;/em&gt;: is latency getting worse? By how much, and how fast?&lt;/p&gt;

&lt;p&gt;Netflix's Concurrency Limits library, which powers parts of their resilience infrastructure, uses TCP Vegas for exactly this. TCP Vegas was designed for network congestion control. Instead of detecting packet loss (the cliff), it detects the &lt;em&gt;onset&lt;/em&gt; of congestion by tracking latency increase. Load shedding can work the same way.&lt;/p&gt;

&lt;p&gt;There's no standard .NET library that does adaptive shedding like this. It's a genuine gap in the ecosystem. But you can get close with &lt;code&gt;System.Diagnostics.Metrics&lt;/code&gt; in .NET 8. Track a rolling P99 latency histogram and engage shedding when the gradient turns positive:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;histogram&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;meter&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;CreateHistogram&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;double&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"request.duration.ms"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Record on every request: histogram.Record(elapsedMs);&lt;/span&gt;
&lt;span class="c1"&gt;// In your shedding middleware: compare rolling P99 against baseline&lt;/span&gt;
&lt;span class="c1"&gt;// When P99 rises &amp;gt;20% over baseline, start shedding&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Start shedding when things are &lt;em&gt;getting worse&lt;/em&gt;, not when they're already broken. That's the difference between a controlled degradation and a collapse.&lt;/p&gt;

&lt;h2&gt;
  
  
  What this means in practice
&lt;/h2&gt;

&lt;p&gt;Load shedding isn't one decision: it's a stack of decisions. Here's how I'd approach it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Shed at the lowest layer you can&lt;/strong&gt; : Kestrel limits before middleware, middleware before controllers&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Assign criticality to endpoint groups&lt;/strong&gt; : protect payments, shed telemetry and batch jobs first&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Use health signals, not static thresholds&lt;/strong&gt; : track latency gradient, not just CPU percentage&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Return &lt;code&gt;503 + Retry-After&lt;/code&gt;, never &lt;code&gt;429&lt;/code&gt;, for load shedding.&lt;/strong&gt; The semantics matter&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Test it under load&lt;/strong&gt; by simulating overload in staging and verifying that P99 for accepted requests improves; if it doesn't, your threshold is wrong&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Layer it with your other resilience tools.&lt;/strong&gt; Load shedding doesn't replace rate limiting, circuit breakers, or backpressure; it completes them&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Remember: properly implemented load shedding &lt;em&gt;improves&lt;/em&gt; the experience for the requests you do accept. By refusing to queue work you can't process quickly, you keep latency tight for everything you take on. AWS and Google both document this. It's counterintuitive until you see the numbers.&lt;/p&gt;

&lt;p&gt;Load shedding feels like giving up. It feels like admitting your system can't handle the load, that you're turning users away.&lt;/p&gt;

&lt;p&gt;In reality, it's the opposite. It's your system making a deliberate, informed choice about who it can serve &lt;em&gt;well&lt;/em&gt; right now. That's better than trying to serve everyone badly and tipping into total failure. Systems that shed deliberately stay alive. Systems that don't shed eventually serve no one.&lt;/p&gt;

&lt;p&gt;The question worth asking: has a retry storm ever taken down one of your services? Because load shedding is precisely the thing that would have stopped it.&lt;/p&gt;

&lt;p&gt;If you find this useful, ping me on &lt;a href="https://twitter.com/irina_scurtu" rel="noopener noreferrer"&gt;Twitter/X&lt;/a&gt; or &lt;a href="https://linkedin.com/in/irinascurtu" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;. A follow there is always appreciated if you'd like more of this. I'm always curious what resilience patterns teams use in production.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>performance</category>
      <category>sre</category>
      <category>systemdesign</category>
    </item>
    <item>
      <title>REST APIs in Production: Pagination, HATEOAS, and the Patterns That Actually Matter (Part 3 of 3)</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 20 Oct 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/rest-apis-in-production-pagination-hateoas-and-the-patterns-that-actually-matter-part-3-of-3-4b4h</link>
      <guid>https://dev.to/irina_scurtu/rest-apis-in-production-pagination-hateoas-and-the-patterns-that-actually-matter-part-3-of-3-4b4h</guid>
      <description>&lt;p&gt;This is the last post in a three-part series on REST API design. &lt;a href="https://irina.codes/rest-api-constraints-and-http-semantics/" rel="noopener noreferrer"&gt;The first post&lt;/a&gt; covered REST's constraints and HTTP semantics. &lt;a href="https://irina.codes/rest-api-resource-design-versioning-auth/" rel="noopener noreferrer"&gt;The second&lt;/a&gt; covered resource design, versioning, and authentication. This one covers what separates a demo API from a production one.&lt;/p&gt;




&lt;h2&gt;
  
  
  Pagination
&lt;/h2&gt;

&lt;p&gt;Always paginate collections that can grow without bound. Returning 50,000 records in one response is a denial-of-service problem waiting to happen.&lt;/p&gt;

&lt;h3&gt;
  
  
  Offset-Based Pagination
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /orders?offset&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;
&lt;span class="na"&gt;GET /orders?offset&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;
&lt;span class="na"&gt;GET /orders?page&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;per_page&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Simple to implement and query. Allows jumping to arbitrary pages.&lt;/p&gt;

&lt;p&gt;Weakness: inconsistent results under concurrent writes. A record inserted between page 1 and page 2 requests can show up as a duplicate. If one is deleted, you may skip a record. Performance also degrades at high offsets in most databases.&lt;/p&gt;

&lt;h3&gt;
  
  
  Cursor-Based Pagination
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /orders?limit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;
&lt;span class="c1"&gt;# Returns: { "data": [...], "cursor": "eyJpZCI6MjB9" }
&lt;/span&gt;
&lt;span class="na"&gt;GET /orders?after&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;eyJpZCI6MjB9&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The cursor encodes a position in the result set. It's typically the ID or sort key of the last item returned. Each page request is a stable query from a known position.&lt;/p&gt;

&lt;p&gt;Strengths: consistent under concurrent writes, efficient at any depth, suits real-time feeds.&lt;/p&gt;

&lt;p&gt;Weaknesses: cannot jump to arbitrary pages (only forward/backward), and clients must treat the cursor as opaque.&lt;/p&gt;

&lt;h3&gt;
  
  
  Keyset Pagination
&lt;/h3&gt;

&lt;p&gt;A variant of cursor pagination that expresses the position as an explicit field value:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /orders?after_id&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;789&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Less opaque than encoded cursors, but ties pagination semantics to visible fields.&lt;/p&gt;

&lt;h3&gt;
  
  
  Response Envelope for Pagination
&lt;/h3&gt;

&lt;p&gt;Always include pagination metadata:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;"data"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="err"&gt;...&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"pagination"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;"total"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1540&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"limit"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"offset"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"has_next"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"has_previous"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"links"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;"self"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/orders?offset=40&amp;amp;limit=20"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"next"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/orders?offset=60&amp;amp;limit=20"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"prev"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/orders?offset=20&amp;amp;limit=20"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"first"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/orders?offset=0&amp;amp;limit=20"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"last"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/orders?offset=1520&amp;amp;limit=20"&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;links&lt;/code&gt; object connects this to HATEOAS, more on that next.&lt;/p&gt;




&lt;h2&gt;
  
  
  HATEOAS
&lt;/h2&gt;

&lt;p&gt;HATEOAS (Hypermedia as the Engine of Application State) is REST's most misunderstood, most often omitted constraint. According to Fielding himself, it's also the part that makes an API truly RESTful.&lt;/p&gt;

&lt;p&gt;The idea: a client moves through an API using links in responses. It needs little upfront knowledge of URI structure. A human clicks through a website by following links. A REST client should do the same instead of hardcoding URI structure it was never given.&lt;/p&gt;

&lt;h3&gt;
  
  
  What It Looks Like
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="no"&gt;GET&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mi"&gt;789&lt;/span&gt;

&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"789"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"pending"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"total"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;142.50&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"customer"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"42"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Alice"&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"_links"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s2"&gt;"self"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"href"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/orders/789"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"cancel"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"href"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/orders/789/cancel"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"method"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"POST"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"customer"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"href"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/users/42"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"payment"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"href"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/payments?orderId=789"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The server controls what actions are available. If the order is already cancelled, the &lt;code&gt;cancel&lt;/code&gt; link disappears. The client doesn't need to know the cancellation rules. It just checks whether the link is present.&lt;/p&gt;

&lt;h3&gt;
  
  
  Media Types and HATEOAS
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;_links&lt;/code&gt; pattern above is informal. There are standardized hypermedia formats:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;HAL (Hypertext Application Language)&lt;/strong&gt;: uses &lt;code&gt;_links&lt;/code&gt; and &lt;code&gt;_embedded&lt;/code&gt;, widely adopted&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;JSON:API&lt;/strong&gt; : a more opinionated full specification for request/response format&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Siren&lt;/strong&gt; : includes actions with typed fields, more expressive for write operations&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Collection+JSON&lt;/strong&gt; : designed specifically for collection resources&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  The Reality of HATEOAS Adoption
&lt;/h3&gt;

&lt;p&gt;HATEOAS is theoretically correct and has genuine benefits for client decoupling. In practice, most production APIs don't implement it. Most clients don't use it even when offered. The reasons are pragmatic. Statically typed clients often prefer a well-documented contract over dynamic link discovery. Tooling for hypermedia clients also isn't as mature as tooling for OpenAPI-described APIs.&lt;/p&gt;

&lt;p&gt;Know this so you decide deliberately, not by default. For public APIs with diverse clients and long lifespans, HATEOAS is worth the investment. For internal APIs between services you control, a well-maintained OpenAPI spec may be more practical.&lt;/p&gt;




&lt;h2&gt;
  
  
  Filtering, Sorting, and Searching
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Filtering
&lt;/h3&gt;

&lt;p&gt;Use query parameters to filter collections:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /orders?status&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;pending&lt;/span&gt;
&lt;span class="na"&gt;GET /orders?status&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;pending&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;
&lt;span class="na"&gt;GET /products?minPrice&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;maxPrice&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;category&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;electronics&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For complex filters, some APIs use a structured query language:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /products?filter&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;lt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;category&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;eq&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;electronics&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or a JSON-encoded filter (though this can be awkward in URLs):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /products?filter&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"price"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"lt"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s2"&gt;"category"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="s2"&gt;"electronics"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Be consistent and document your filter syntax explicitly.&lt;/p&gt;

&lt;h3&gt;
  
  
  Sorting
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /orders?sort&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;createdAt&lt;/span&gt;
&lt;span class="na"&gt;GET /orders?sort&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;createdAt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;desc&lt;/span&gt;
&lt;span class="na"&gt;GET /orders?sort&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="n"&gt;createdAt&lt;/span&gt; &lt;span class="c1"&gt;# minus prefix for descending&lt;/span&gt;
&lt;span class="na"&gt;GET /orders?sort&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;createdAt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;desc&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Always document the default sort order, and make it stable. Include a unique field as a tiebreaker.&lt;/p&gt;

&lt;h3&gt;
  
  
  Searching
&lt;/h3&gt;

&lt;p&gt;Full-text search usually warrants a dedicated endpoint or query parameter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /products?q&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;wireless&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="n"&gt;headphones&lt;/span&gt;
&lt;span class="na"&gt;GET /search?q&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;wireless&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="n"&gt;headphones&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;products&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For sophisticated search requirements, dedicated search endpoints with POST bodies can be appropriate:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="no"&gt;POST&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;products&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;search&lt;/span&gt;

&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="s2"&gt;"query"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"wireless headphones"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"filters"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"inStock"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"priceMax"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"sort"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"field"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"relevance"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"order"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"desc"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"pagination"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"limit"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"offset"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;POST works for search when the query is too complex for a URL. It's pragmatic, but it sacrifices cacheability.&lt;/p&gt;




&lt;h2&gt;
  
  
  Sparse Fieldsets and Field Selection
&lt;/h2&gt;

&lt;p&gt;Large resources with many fields are expensive to transfer. They often contain fields a given client doesn't need. Field selection lets clients request only what they need:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /users/42?fields&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;
&lt;span class="na"&gt;GET /orders?fields&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;include&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is particularly important for mobile clients on limited bandwidth.&lt;/p&gt;




&lt;h2&gt;
  
  
  Content Negotiation
&lt;/h2&gt;

&lt;p&gt;REST embraces HTTP's content negotiation mechanism. Clients can request specific response formats:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Request JSON&lt;/span&gt;
curl -H &lt;span class="s2"&gt;"Accept: application/json"&lt;/span&gt; https://api.example.com/users/42

&lt;span class="c"&gt;# Request XML&lt;/span&gt;
curl -H &lt;span class="s2"&gt;"Accept: application/xml"&lt;/span&gt; https://api.example.com/users/42
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The server indicates what it returned:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="n"&gt;Content&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="n"&gt;Type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;application&lt;/span&gt;&lt;span class="err"&gt;/&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt; &lt;span class="n"&gt;charset&lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="n"&gt;utf&lt;/span&gt;&lt;span class="mi"&gt;-8&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the server cannot produce the requested format, it returns &lt;code&gt;406 Not Acceptable&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For versioning via content type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl -H &lt;span class="s2"&gt;"Accept: application/vnd.myapi.v2+json"&lt;/span&gt; https://api.example.com/users/42
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Rate Limiting
&lt;/h2&gt;

&lt;p&gt;Every public API needs rate limiting. Return standard headers so clients can manage their behavior:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="no"&gt;X&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nc"&gt;RateLimit&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nc"&gt;Limit&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;
&lt;span class="no"&gt;X&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nc"&gt;RateLimit&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nc"&gt;Remaining&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;742&lt;/span&gt;
&lt;span class="no"&gt;X&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nc"&gt;RateLimit&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nc"&gt;Reset&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1735689600&lt;/span&gt;
&lt;span class="nc"&gt;Retry&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nc"&gt;After&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3600&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When a client exceeds the limit, return &lt;code&gt;429 Too Many Requests&lt;/code&gt; with a &lt;code&gt;Retry-After&lt;/code&gt; header.&lt;/p&gt;

&lt;p&gt;Common rate limiting strategies:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Fixed window&lt;/strong&gt; : count requests in a fixed time window (simple, but allows burst at window boundary)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sliding window&lt;/strong&gt; : rolling time window (smoother, more expensive)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Token bucket&lt;/strong&gt; : tokens replenish at a fixed rate, bursts allowed up to bucket size&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Leaky bucket&lt;/strong&gt; : requests processed at a fixed rate, excess queued or dropped&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Provide different rate limit tiers for different clients (authenticated vs. anonymous, free vs. paid).&lt;/p&gt;




&lt;h2&gt;
  
  
  Idempotency Keys
&lt;/h2&gt;

&lt;p&gt;For non-idempotent operations like POST, idempotency keys let clients retry safely. There's no risk of duplicate side effects:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl -X POST https://api.example.com/payments \
  -H &lt;span class="s2"&gt;"Idempotency-Key: 7f3a2b1c-4d5e-6f7g-8h9i-0j1k2l3m4n5o"&lt;/span&gt; \
  -H &lt;span class="s2"&gt;"Content-Type: application/json"&lt;/span&gt; \
  -d &lt;span class="s1"&gt;'{"amount": 9900, "currency": "USD"}'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The server caches the response for the idempotency key for a defined window. A retry with the same key returns the cached response without reprocessing the payment.&lt;/p&gt;

&lt;p&gt;This pattern is essential for payment APIs and order creation. It matters for any operation with financial or irreversible consequences.&lt;/p&gt;




&lt;h2&gt;
  
  
  Conditional Requests and Optimistic Concurrency
&lt;/h2&gt;

&lt;p&gt;HTTP provides mechanisms for conditional operations via ETags and timestamps.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ETags&lt;/strong&gt; are version identifiers for a resource:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="no"&gt;GET&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mi"&gt;789&lt;/span&gt;

&lt;span class="no"&gt;HTTP&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mf"&gt;1.1&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt; &lt;span class="no"&gt;OK&lt;/span&gt;
&lt;span class="nc"&gt;ETag&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"abc123"&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A client can make conditional requests using &lt;code&gt;If-Match&lt;/code&gt; to prevent lost updates:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Only update if the resource still has this ETag (optimistic locking)&lt;/span&gt;
curl -X PUT https://api.example.com/orders/789 \
  -H &lt;span class="s2"&gt;"If-Match: \"abc123\""&lt;/span&gt; \
  -d &lt;span class="s1"&gt;'{ "status": "processing" }'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Someone else may have modified the resource since the client retrieved it. If so, the server returns &lt;code&gt;412 Precondition Failed&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For cache revalidation, clients use &lt;code&gt;If-None-Match&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Only send the body if the resource has changed&lt;/span&gt;
curl -H &lt;span class="s2"&gt;"If-None-Match: \"abc123\""&lt;/span&gt; https://api.example.com/orders/789
&lt;span class="c"&gt;# Returns 304 Not Modified if unchanged&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;If-Modified-Since&lt;/code&gt; / &lt;code&gt;Last-Modified&lt;/code&gt; work similarly but with timestamps.&lt;/p&gt;




&lt;h2&gt;
  
  
  Long-Running Operations
&lt;/h2&gt;

&lt;p&gt;Some operations take seconds or minutes. Don't block. Return &lt;code&gt;202 Accepted&lt;/code&gt; and provide a way to track progress:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="no"&gt;POST&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;reports&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;generate&lt;/span&gt;

&lt;span class="no"&gt;HTTP&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mf"&gt;1.1&lt;/span&gt; &lt;span class="mi"&gt;202&lt;/span&gt; &lt;span class="nc"&gt;Accepted&lt;/span&gt;
&lt;span class="nc"&gt;Location&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;jobs&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;report&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;abc123&lt;/span&gt;

&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="s2"&gt;"jobId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"report-abc123"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"pending"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"statusUrl"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/jobs/report-abc123"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="no"&gt;GET&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;jobs&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;report&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;abc123&lt;/span&gt;

&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="s2"&gt;"jobId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"report-abc123"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"running"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"progress"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"startedAt"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"2026-03-27T09:00:00Z"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="no"&gt;GET&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;jobs&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;report&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;abc123&lt;/span&gt;

&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="s2"&gt;"jobId"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"report-abc123"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"completed"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"result"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"url"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/reports/2026-q1.pdf"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively, use webhooks to push completion notifications rather than requiring polling.&lt;/p&gt;




&lt;h2&gt;
  
  
  API Design Best Practices
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Be Consistent
&lt;/h3&gt;

&lt;p&gt;Inconsistency is the number one user-experience failure in APIs. Pick conventions for naming, casing, error format, date format, pagination, and versioning, then apply them everywhere.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Field names: &lt;code&gt;camelCase&lt;/code&gt; or &lt;code&gt;snake_case&lt;/code&gt;, pick one&lt;/li&gt;
&lt;li&gt;Dates: ISO 8601 (&lt;code&gt;2026-03-27T09:00:00Z&lt;/code&gt;) always, never Unix timestamps in mixed APIs&lt;/li&gt;
&lt;li&gt;Booleans: &lt;code&gt;isActive&lt;/code&gt;, not &lt;code&gt;active&lt;/code&gt;, &lt;code&gt;enabled&lt;/code&gt;, or &lt;code&gt;status: "true"&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Document Everything
&lt;/h3&gt;

&lt;p&gt;An API without documentation is incomplete. Use OpenAPI 3.x to describe your API. It enables generated documentation, client SDK generation, request validation, and contract testing.&lt;/p&gt;

&lt;p&gt;Document:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Every endpoint, method, and path parameter&lt;/li&gt;
&lt;li&gt;Every request body field (required vs. optional, constraints)&lt;/li&gt;
&lt;li&gt;Every response status code and body&lt;/li&gt;
&lt;li&gt;Authentication requirements&lt;/li&gt;
&lt;li&gt;Rate limits&lt;/li&gt;
&lt;li&gt;Deprecation timelines&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Use HTTPS Exclusively
&lt;/h3&gt;

&lt;p&gt;Never offer plain HTTP. Redirect all HTTP traffic to HTTPS. Use HSTS (&lt;code&gt;Strict-Transport-Security&lt;/code&gt;) to prevent downgrade attacks.&lt;/p&gt;

&lt;h3&gt;
  
  
  Design for Your Consumer
&lt;/h3&gt;

&lt;p&gt;APIs are products. Talk to the developers who will use your API. Understand their workflows. APIs that are technically correct but operationally awkward get abandoned. I always advise treating your API contract like a public function signature in a library.&lt;/p&gt;

&lt;h3&gt;
  
  
  Backward Compatibility is a Promise
&lt;/h3&gt;

&lt;p&gt;Once you publish an endpoint, clients depend on it. Make breaking changes rare, communicate them well, and support them with a migration path and a generous deprecation window.&lt;/p&gt;

&lt;h3&gt;
  
  
  Keep Actions Atomic
&lt;/h3&gt;

&lt;p&gt;An endpoint should either succeed completely or fail completely. Partial success is a consistency nightmare. If a batch operation partially fails, return a clear, structured response. It should identify which items succeeded and which failed, with specific error details.&lt;/p&gt;

&lt;h3&gt;
  
  
  Don't Return 200 with an Error Body
&lt;/h3&gt;

&lt;p&gt;This bears repeating. Use the HTTP status code correctly. Your monitoring, your clients, and your own sanity will thank you.&lt;/p&gt;




&lt;h2&gt;
  
  
  Closing
&lt;/h2&gt;

&lt;p&gt;Most "REST APIs" in production implement a subset of the constraints. They ignore the rest, particularly HATEOAS. That's a pragmatic reality of software engineering. It's fine, as long as it's a deliberate choice.&lt;/p&gt;

&lt;p&gt;Think about it. The difference between a good API and a frustrating one usually isn't the technology. It's the care taken with every small decision. The status code, the error message, the version strategy, the pagination contract. Those decisions compound. Clients you don't know yet will inherit them.&lt;/p&gt;

&lt;p&gt;Build APIs you'd want to consume yourself.&lt;/p&gt;

&lt;p&gt;PS: Let me know if I missed anything. Ping me on &lt;a href="https://twitter.com/irina_scurtu" rel="noopener noreferrer"&gt;Twitter/X&lt;/a&gt; or &lt;a href="https://linkedin.com/in/irinascurtu" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;, and follow along there if you'd like more of this. Let's chat.&lt;/p&gt;

</description>
      <category>api</category>
      <category>architecture</category>
      <category>backend</category>
    </item>
    <item>
      <title>REST API Design: Resources, Versioning, and Auth That Hold Up (Part 2 of 3)</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 13 Oct 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/rest-api-design-resources-versioning-and-auth-that-hold-up-part-2-of-3-32bc</link>
      <guid>https://dev.to/irina_scurtu/rest-api-design-resources-versioning-and-auth-that-hold-up-part-2-of-3-32bc</guid>
      <description>&lt;p&gt;In &lt;a href="https://irina.codes/rest-api-constraints-and-http-semantics/" rel="noopener noreferrer"&gt;the first post in this series&lt;/a&gt;, I covered REST's architectural constraints and the HTTP semantics (methods, status codes) that most APIs get subtly wrong. Constraints and semantics get you a technically correct API. They don't get you a good one.&lt;/p&gt;

&lt;p&gt;A good API needs resources named sensibly and a versioning strategy that won't break your clients every quarter. It also needs an authentication pattern matching your threat model, and errors that tell the caller something useful. That's what this post covers.&lt;/p&gt;




&lt;h2&gt;
  
  
  REST API Resource Design
&lt;/h2&gt;

&lt;p&gt;Resources are the nouns of your API. Good resource design is the single biggest factor in how usable and evolvable your API will be.&lt;/p&gt;

&lt;h3&gt;
  
  
  URIs Should Identify Resources, Not Actions
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Good - noun-based, resource-centric
GET /orders
GET /orders/789
POST /orders
PUT /orders/789
DELETE /orders/789

# Bad - verb-based, RPC-style
POST /getOrder
POST /createOrder
POST /deleteOrder

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The HTTP method carries the action. The URI carries the identity of the resource the action applies to.&lt;/p&gt;

&lt;h3&gt;
  
  
  Singular vs. Plural
&lt;/h3&gt;

&lt;p&gt;Use plurals for collections consistently:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/users # collection
/users/42 # single resource
/users/42/posts # sub-collection

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mixing singular and plural is a maintenance and documentation headache.&lt;/p&gt;

&lt;h3&gt;
  
  
  Hierarchical Relationships
&lt;/h3&gt;

&lt;p&gt;Nest resources to express ownership or containment, but limit nesting depth:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/users/42/orders # orders belonging to user 42
/users/42/orders/789 # order 789 belonging to user 42

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Deep nesting (more than two levels) is a sign that you may need to reconsider your resource model. &lt;code&gt;/users/42/orders/789/items/1/reviews/5&lt;/code&gt; is hard to work with. In my opinion, it's better to use query parameters to filter at the top-level collection:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /orders?userId&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Resource Identifiers
&lt;/h3&gt;

&lt;p&gt;Prefer opaque, stable identifiers. UUIDs or ULIDs are better than auto-increment integers for several reasons:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;They don't expose record counts (a security and competitive concern)&lt;/li&gt;
&lt;li&gt;They can be generated client-side without a round-trip&lt;/li&gt;
&lt;li&gt;They're safe to use across environments without collision&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Once you publish a URI, it is a contract. Change it only with proper versioning and redirect support.&lt;/p&gt;

&lt;h3&gt;
  
  
  Controller Resources
&lt;/h3&gt;

&lt;p&gt;Some operations don't map cleanly onto CRUD. Use controller resources for these, named with a verb and invoked with POST:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="no"&gt;POST&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mi"&gt;789&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;cancel&lt;/span&gt;
&lt;span class="no"&gt;POST&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;verify&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;
&lt;span class="no"&gt;POST&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;payments&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;refund&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is better than bending PUT or PATCH into something unnatural.&lt;/p&gt;




&lt;h2&gt;
  
  
  Versioning Strategies
&lt;/h2&gt;

&lt;p&gt;APIs change. Resources get new fields, old fields get removed, behavior changes. Versioning is how you manage change without breaking existing clients.&lt;/p&gt;

&lt;h3&gt;
  
  
  URI Versioning
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/v1/users
/v2/users

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pros: explicit, easy to route at the infrastructure level, easy to document and test separately, shows up clearly in logs.&lt;/p&gt;

&lt;p&gt;Cons: technically violates REST's uniform interface (the same resource should have one canonical URI), pollutes the URI space, encourages "big bang" version increments rather than incremental evolution.&lt;/p&gt;

&lt;p&gt;This is the most pragmatic approach and the most widely used.&lt;/p&gt;

&lt;h3&gt;
  
  
  Header Versioning
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="no"&gt;GET&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;
&lt;span class="nc"&gt;Accept&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;application&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;vnd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;myapi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;v2&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pros: URIs remain stable, aligns with HTTP content negotiation, cleaner theoretically.&lt;/p&gt;

&lt;p&gt;Cons: harder to test in a browser, not visible in logs without extra work, requires clients to set headers correctly, harder to cache with some intermediaries.&lt;/p&gt;

&lt;h3&gt;
  
  
  Query Parameter Versioning
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;GET /users?version&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pros: easy to test, explicit, no header management.&lt;/p&gt;

&lt;p&gt;Cons: version in the query string is semantically awkward (it's not a filter parameter), can interfere with caching.&lt;/p&gt;

&lt;h3&gt;
  
  
  Additive Changes vs. Breaking Changes
&lt;/h3&gt;

&lt;p&gt;The best versioning strategy is to not break clients in the first place. Additive changes are generally safe:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Adding new fields to a response&lt;/li&gt;
&lt;li&gt;Adding new optional request parameters&lt;/li&gt;
&lt;li&gt;Adding new endpoints&lt;/li&gt;
&lt;li&gt;Adding new values to an enum (this can break strict deserializers, so communicate it)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Breaking changes require a new version:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Removing or renaming fields&lt;/li&gt;
&lt;li&gt;Changing field types&lt;/li&gt;
&lt;li&gt;Changing URI structure&lt;/li&gt;
&lt;li&gt;Changing status codes for existing operations&lt;/li&gt;
&lt;li&gt;Removing endpoints&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Be pragmatic about it, and don't take it to the extreme. An API version number is not a build number. Don't do that.&lt;/p&gt;

&lt;h3&gt;
  
  
  Versioning in Practice
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Requesting a specific version via header&lt;/span&gt;
curl -H &lt;span class="s2"&gt;"Accept: application/vnd.myapi.v2+json"&lt;/span&gt; https://api.example.com/users

&lt;span class="c"&gt;# URI versioning&lt;/span&gt;
curl https://api.example.com/v2/users
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Maintain multiple versions simultaneously during a deprecation window. Communicate deprecation timelines clearly via &lt;code&gt;Deprecation&lt;/code&gt; and &lt;code&gt;Sunset&lt;/code&gt; response headers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="nc"&gt;Deprecation&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
&lt;span class="nc"&gt;Sunset&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Sat&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;31&lt;/span&gt; &lt;span class="nc"&gt;Dec&lt;/span&gt; &lt;span class="mi"&gt;2026&lt;/span&gt; &lt;span class="mi"&gt;23&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;59&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;59&lt;/span&gt; &lt;span class="no"&gt;GMT&lt;/span&gt;
&lt;span class="na"&gt;Link: &amp;lt;https://api.example.com/v2/users&amp;gt;; rel&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"successor-version"&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Authentication Patterns
&lt;/h2&gt;

&lt;p&gt;REST is stateless, which means credentials travel with every request. There are several established patterns.&lt;/p&gt;

&lt;h3&gt;
  
  
  API Keys
&lt;/h3&gt;

&lt;p&gt;The simplest approach. You issue a key to a client, who sends it with every request, typically in a header:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl -H &lt;span class="s2"&gt;"X-API-Key: abc123xyz"&lt;/span&gt; https://api.example.com/data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or as a Bearer token variant:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl -H &lt;span class="s2"&gt;"Authorization: ApiKey abc123xyz"&lt;/span&gt; https://api.example.com/data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pros: simple to implement and use, easy to rotate. Cons: no expiration built in, broad access (all-or-nothing unless scoped), key must be kept secret.&lt;/p&gt;

&lt;h3&gt;
  
  
  HTTP Basic Authentication
&lt;/h3&gt;

&lt;p&gt;Username and password encoded as Base64 in the Authorization header:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl -u username:password https://api.example.com/data
&lt;span class="c"&gt;# Which sends:&lt;/span&gt;
&lt;span class="c"&gt;# Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Never use Basic auth over plain HTTP. Base64 only obscures credentials; it doesn't encrypt them. Only acceptable over HTTPS.&lt;/p&gt;

&lt;h3&gt;
  
  
  Bearer Tokens (JWT / OAuth 2.0)
&lt;/h3&gt;

&lt;p&gt;The dominant pattern for modern APIs. You obtain a token through an authentication flow and include it as a Bearer token:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl -H &lt;span class="s2"&gt;"Authorization: Bearer eyJhbGciOiJSUzI1NiJ9..."&lt;/span&gt; https://api.example.com/data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;JWTs (JSON Web Tokens) are self-contained: they encode claims (user ID, roles, expiry) and are cryptographically signed. The server can validate them without a database lookup.&lt;/p&gt;

&lt;p&gt;Key properties to verify when processing JWTs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Signature validity (using the correct public key or shared secret)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;exp&lt;/code&gt; claim (not expired)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;iss&lt;/code&gt; claim (issued by the expected authority)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;aud&lt;/code&gt; claim (intended for your service)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;OAuth 2.0 defines flows for obtaining tokens. The authorization code flow is appropriate for delegated access on behalf of a user. Client credentials flow is appropriate for machine-to-machine APIs.&lt;/p&gt;

&lt;h3&gt;
  
  
  Mutual TLS (mTLS)
&lt;/h3&gt;

&lt;p&gt;Both client and server present certificates. Strong authentication with no bearer token to steal, but operationally complex (certificate management, rotation). Common in zero-trust internal service meshes.&lt;/p&gt;

&lt;h3&gt;
  
  
  Choosing a Pattern
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Public API, external developers&lt;/strong&gt; : OAuth 2.0 with API keys for non-delegated access&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Service-to-service&lt;/strong&gt; : mTLS or client credentials flow&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Internal tooling&lt;/strong&gt; : API keys or JWT with short expiry&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;User-facing mobile/web&lt;/strong&gt; : OAuth 2.0 authorization code flow with PKCE&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Error Handling
&lt;/h2&gt;

&lt;p&gt;Error responses deserve as much design attention as success responses. A client that receives an error needs to know what went wrong and why. It also needs to know what, if anything, it can do about it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Structure Your Error Responses
&lt;/h3&gt;

&lt;p&gt;Ad-hoc error messages are hard to handle programmatically. Define a consistent error structure and use it everywhere:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"https://api.example.com/errors/validation-failed"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Validation Failed"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;422&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"detail"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"The request payload contains invalid values."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"instance"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"/orders/create"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"errors"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nl"&gt;"field"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"email"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="nl"&gt;"code"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"INVALID_FORMAT"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="nl"&gt;"message"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Email address is not in a valid format."&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nl"&gt;"field"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"quantity"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="nl"&gt;"code"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"OUT_OF_RANGE"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="nl"&gt;"message"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Quantity must be between 1 and 100."&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This follows &lt;a href="https://datatracker.ietf.org/doc/html/rfc7807" rel="noopener noreferrer"&gt;RFC 7807 (Problem Details for HTTP APIs)&lt;/a&gt;, a standard worth adopting. The &lt;code&gt;type&lt;/code&gt; field is a URI that identifies the error type (it should resolve to documentation). The &lt;code&gt;instance&lt;/code&gt; field identifies the specific occurrence.&lt;/p&gt;

&lt;h3&gt;
  
  
  Be Specific
&lt;/h3&gt;

&lt;p&gt;A 400 with "bad request" is nearly useless. Tell the client:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Which field(s) failed validation&lt;/li&gt;
&lt;li&gt;What constraint was violated&lt;/li&gt;
&lt;li&gt;What the expected format or range is&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Don't Leak Internals
&lt;/h3&gt;

&lt;p&gt;Error responses must never expose:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Stack traces&lt;/li&gt;
&lt;li&gt;Database error messages&lt;/li&gt;
&lt;li&gt;Internal server paths&lt;/li&gt;
&lt;li&gt;Framework-level exceptions&lt;/li&gt;
&lt;li&gt;Secrets or keys&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Log those internally. Return only what the client needs to understand and act on the error.&lt;/p&gt;

&lt;h3&gt;
  
  
  Distinguish Permanent from Transient Errors
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;4xx errors are the client's fault. Retrying the same request unchanged is pointless.&lt;/li&gt;
&lt;li&gt;5xx errors are the server's fault. The client may retry, ideally with exponential backoff and jitter.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Make this distinction explicit in your API documentation and, where possible, in the response itself.&lt;/p&gt;

&lt;h3&gt;
  
  
  Correlation IDs
&lt;/h3&gt;

&lt;p&gt;Return a correlation ID in every error response (and ideally every response):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="no"&gt;X&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nc"&gt;Correlation&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nc"&gt;Id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;7f3a2b1c&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;4d&lt;/span&gt;&lt;span class="mf"&gt;5e-6f&lt;/span&gt;&lt;span class="mi"&gt;7g&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;8h9i&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;0j1k2l3m4n5o&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows support teams to trace a client-reported error back to server-side logs without guessing.&lt;/p&gt;




&lt;h2&gt;
  
  
  Closing
&lt;/h2&gt;

&lt;p&gt;Resource design, versioning, and auth get your API to a place where it's usable and safe to evolve.&lt;/p&gt;

&lt;p&gt;PS: Let me know if I missed anything. Ping me on &lt;a href="https://twitter.com/irina_scurtu" rel="noopener noreferrer"&gt;Twitter/X&lt;/a&gt; or &lt;a href="https://linkedin.com/in/irinascurtu" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;, and follow along there if you'd like more of this. Let's chat.&lt;/p&gt;

</description>
      <category>api</category>
      <category>architecture</category>
      <category>backend</category>
      <category>design</category>
    </item>
    <item>
      <title>REST API Design: The Constraints and HTTP Semantics Everyone Skips (Part 1 of 3)</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 06 Oct 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/rest-api-design-the-constraints-and-http-semantics-everyone-skips-part-1-of-3-3jkd</link>
      <guid>https://dev.to/irina_scurtu/rest-api-design-the-constraints-and-http-semantics-everyone-skips-part-1-of-3-3jkd</guid>
      <description>&lt;p&gt;REST is everywhere. Almost every web application, mobile app, and microservice you interact with today exposes or consumes a REST API. Yet most developers learn REST by cargo-culting patterns they see in tutorials. They slap HTTP verbs on endpoints and call it done.&lt;/p&gt;

&lt;p&gt;This is the first post in a series on REST API design that goes deeper than the tutorials. We'll start with the part everyone skips: what REST actually is, the constraints Roy Fielding defined it by, and the HTTP semantics that most APIs get subtly wrong. That means methods and status codes.&lt;/p&gt;




&lt;h2&gt;
  
  
  What REST Actually Is
&lt;/h2&gt;

&lt;p&gt;REST stands for &lt;strong&gt;Representational State Transfer&lt;/strong&gt;. Roy Fielding defined it in his 2000 doctoral dissertation, where he described the architectural style that underpins the web itself.&lt;/p&gt;

&lt;p&gt;The key insight in Fielding's thesis is that REST is not a protocol or a standard. It is an &lt;strong&gt;architectural style&lt;/strong&gt; : a set of constraints that, applied together, produce desirable properties in a distributed hypermedia system. If your API doesn't satisfy those constraints, it isn't REST. It may still be a perfectly useful HTTP API, but calling it REST is technically incorrect.&lt;/p&gt;

&lt;p&gt;This distinction matters more than it might seem. Fielding designed REST to be highly scalable, loosely coupled, and evolvable over time. Those properties emerge from the constraints, not from any single choice like "use JSON" or "put the ID in the URL". Understanding the constraints is understanding the &lt;em&gt;why&lt;/em&gt; behind every REST best practice.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Six Architectural Constraints
&lt;/h2&gt;

&lt;p&gt;Fielding defined six constraints. The first five are mandatory; the sixth is optional.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Client-Server
&lt;/h3&gt;

&lt;p&gt;A uniform interface separates the client and server. The client is responsible for the user interface and user experience. The server is responsible for data storage, business logic, and security.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why it matters:&lt;/strong&gt; This separation improves portability of the UI across platforms and scalability of the server components. Neither side needs to know the implementation details of the other. A web client, a mobile client, and a CLI tool can all consume the same API. The server doesn't care which one is making the request.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Stateless
&lt;/h3&gt;

&lt;p&gt;Each request from a client to a server must contain all the information necessary to process it. The client keeps all session state. The server stores no client context between requests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why it matters:&lt;/strong&gt; Statelessness enables horizontal scaling. Any server in a pool can handle any request because no server holds session state. It also improves visibility: you can understand a single request in isolation, which helps with debugging and monitoring. And it improves reliability, since partial failures don't leave dangling server-side sessions.&lt;/p&gt;

&lt;p&gt;The practical consequence: if a user is authenticated, the authentication token travels with every single request. The server never says "I remember you from last time." It re-validates the token on every call.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Cacheable
&lt;/h3&gt;

&lt;p&gt;Responses must define themselves as cacheable or non-cacheable. If a response is cacheable, the client (or an intermediate proxy) can reuse that response for equivalent future requests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why it matters:&lt;/strong&gt; Caching eliminates some client-server interactions entirely, improving efficiency, scalability, and perceived performance. HTTP already has a rich caching model (&lt;code&gt;Cache-Control&lt;/code&gt;, &lt;code&gt;ETag&lt;/code&gt;, &lt;code&gt;Last-Modified&lt;/code&gt;, &lt;code&gt;Expires&lt;/code&gt;), and REST makes full use of it.&lt;/p&gt;

&lt;p&gt;Getting caching right requires deliberate thought about:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Which resources change frequently vs. infrequently&lt;/li&gt;
&lt;li&gt;Whether two requests are truly equivalent (same query parameters, same &lt;code&gt;Accept&lt;/code&gt; header, etc.)&lt;/li&gt;
&lt;li&gt;Conditional requests (&lt;code&gt;If-None-Match&lt;/code&gt;, &lt;code&gt;If-Modified-Since&lt;/code&gt;) for cheap revalidation&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  4. Uniform Interface
&lt;/h3&gt;

&lt;p&gt;This is the central constraint that distinguishes REST from other network-based styles. It has four sub-constraints:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Identification of resources.&lt;/strong&gt; Stable identifiers (URIs) identify each resource. The resource and its representation are distinct. The server might store user data in a relational database. It can represent that data as JSON, XML, or HTML, depending on what the client requests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Manipulation of resources through representations.&lt;/strong&gt; When a client holds a representation of a resource, including any metadata, it has enough information to modify or delete the resource. It just needs permission.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Self-descriptive messages.&lt;/strong&gt; Each message includes enough information to describe how to process it. A &lt;code&gt;Content-Type: application/json&lt;/code&gt; header tells the recipient exactly how to interpret the body. This decouples message processing from the application logic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hypermedia as the engine of application state (HATEOAS).&lt;/strong&gt; Clients interact with the application entirely through hypermedia that the server provides dynamically. I cover this one in detail in the last post of this series.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why it matters:&lt;/strong&gt; A uniform interface simplifies the architecture and makes it easier to evolve parts of the system independently. The cost is efficiency: the interface generalizes rather than optimizing for any specific use case. That is an explicit and intentional trade-off in REST.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Layered System
&lt;/h3&gt;

&lt;p&gt;The architecture must be composable from hierarchical layers. A client cannot tell whether it's talking directly to the server or to an intermediary. You can insert intermediaries, such as load balancers, API gateways, caches, and security proxies, transparently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why it matters:&lt;/strong&gt; Layers let you enforce security policies at the boundary, cache aggressively at edge nodes, and load-balance without clients knowing. They also let you evolve infrastructure independently from application logic. HTTPS termination at a load balancer is a layered system in action.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Code on Demand (Optional)
&lt;/h3&gt;

&lt;p&gt;Servers can extend client functionality by transferring executable code, like JavaScript running in a browser. This constraint is optional because it reduces visibility. You can't easily audit what code a client will execute, and it creates coupling.&lt;/p&gt;

&lt;p&gt;Most API design work ignores code on demand. It shows up primarily in browser-based applications, not in service-to-service APIs.&lt;/p&gt;




&lt;h2&gt;
  
  
  HTTP Methods
&lt;/h2&gt;

&lt;p&gt;HTTP provides a small vocabulary of methods (also called verbs). REST maps operations on resources to this vocabulary. Each method carries a defined semantic and a set of properties.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Core Methods
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Semantics&lt;/th&gt;
&lt;th&gt;Safe&lt;/th&gt;
&lt;th&gt;Idempotent&lt;/th&gt;
&lt;th&gt;Request Body&lt;/th&gt;
&lt;th&gt;Response Body&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;GET&lt;/td&gt;
&lt;td&gt;Retrieve a resource or collection&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;POST&lt;/td&gt;
&lt;td&gt;Create a subordinate resource, or trigger a process&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;PUT&lt;/td&gt;
&lt;td&gt;Replace a resource entirely&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;PATCH&lt;/td&gt;
&lt;td&gt;Partially update a resource&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;No (usually)&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;DELETE&lt;/td&gt;
&lt;td&gt;Remove a resource&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Optional&lt;/td&gt;
&lt;td&gt;Optional&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;HEAD&lt;/td&gt;
&lt;td&gt;Same as GET but body omitted&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;OPTIONS&lt;/td&gt;
&lt;td&gt;Retrieve supported methods and CORS preflight&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Safe&lt;/strong&gt; means the method should not have any observable side effects on the server. Clients (and proxies) can prefetch or retry safe methods freely.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Idempotent&lt;/strong&gt; means that multiple identical requests produce the same server state as a single request. A &lt;code&gt;DELETE /users/42&lt;/code&gt; should have the same effect whether called once or ten times. This property is what makes retries safe.&lt;/p&gt;

&lt;h3&gt;
  
  
  Common Misuses
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;POST for everything.&lt;/strong&gt; Using POST for reads, updates, and deletes is a common anti-pattern. It throws away idempotency and prevents HTTP-layer caching.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PUT when you mean PATCH.&lt;/strong&gt; PUT replaces the entire resource. If a client sends a PUT with a partial payload and the server accepts it, the result behaves like PATCH. On paper, though, it's still PUT. This creates subtle bugs when clients omit fields they didn't intend to clear.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DELETE with a body.&lt;/strong&gt; While technically possible, HTTP clients and intermediaries poorly support bodies on DELETE requests. If you need to delete multiple resources, prefer a separate endpoint or use PATCH on a collection.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;POST vs. PUT for creation.&lt;/strong&gt; Use POST when the server assigns the identifier: you POST to &lt;code&gt;/orders&lt;/code&gt; and the server returns &lt;code&gt;/orders/789&lt;/code&gt;. Use PUT when the client specifies the identifier: you PUT to &lt;code&gt;/users/alice&lt;/code&gt; to create or replace that resource.&lt;/p&gt;




&lt;h2&gt;
  
  
  HTTP Status Codes
&lt;/h2&gt;

&lt;p&gt;Status codes are not decoration. They carry semantic meaning and drive client behavior. Using the wrong status code is like raising the wrong exception type. Technically it works, but everyone downstream makes the wrong decisions because of it.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Five Classes
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1xx, Informational&lt;/strong&gt; : Rarely used in REST APIs. &lt;code&gt;100 Continue&lt;/code&gt; tells the client it can proceed with a large request body.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2xx, Success&lt;/strong&gt; : The request was received, understood, and accepted.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3xx, Redirection&lt;/strong&gt; : Further action needs to be taken to complete the request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4xx, Client Error&lt;/strong&gt; : The client sent an invalid request. Retrying the same request unchanged will not succeed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5xx, Server Error&lt;/strong&gt; : The server failed to process a valid request. The client may retry.&lt;/p&gt;

&lt;h3&gt;
  
  
  Key Codes in Detail
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;200 OK&lt;/strong&gt; : General success. The response body contains the result. Appropriate for GET, PUT, PATCH.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;201 Created&lt;/strong&gt; : A new resource was created. The &lt;code&gt;Location&lt;/code&gt; header should point to the new resource URI. Appropriate for POST and PUT when creating.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;202 Accepted&lt;/strong&gt; : The server accepted the request for processing, but processing isn't complete. Used for async operations. The response should explain how the client can check status.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;204 No Content&lt;/strong&gt; : Success, but there is nothing to return. Common for DELETE and some PUTs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;301 Moved Permanently&lt;/strong&gt; : The resource has a new permanent URI. Clients should update their bookmarks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;304 Not Modified&lt;/strong&gt; : The client's cached copy is still fresh. No body is returned. Used with conditional requests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;400 Bad Request&lt;/strong&gt; : The server cannot process the request because of a client error (malformed JSON, invalid field values, missing required parameters). Return a body that explains what is wrong.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;401 Unauthorized&lt;/strong&gt; : The request lacks valid authentication credentials. Despite the name, this code means "unauthenticated": the client needs to provide credentials.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;403 Forbidden&lt;/strong&gt; : The client is authenticated but does not have permission to access the resource. Don't return 404 as a security measure unless you want to hide the existence of the resource.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;404 Not Found&lt;/strong&gt; : The resource does not exist. Also used intentionally when a 403 would reveal information you want to protect.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;405 Method Not Allowed&lt;/strong&gt; : The HTTP method is not supported for this resource. The response must include an &lt;code&gt;Allow&lt;/code&gt; header listing valid methods.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;409 Conflict&lt;/strong&gt; : The request conflicts with the current state of the resource. Common for optimistic concurrency failures or duplicate creation attempts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;410 Gone&lt;/strong&gt; : The resource existed but has been permanently deleted. Distinct from 404; useful for caches and clients to know not to ask again.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;422 Unprocessable Entity&lt;/strong&gt; : The request is syntactically valid but semantically wrong (valid JSON, but the business rules reject it). Preferred over 400 for domain validation failures.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;429 Too Many Requests&lt;/strong&gt; : Rate limit exceeded. Include a &lt;code&gt;Retry-After&lt;/code&gt; header.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;500 Internal Server Error&lt;/strong&gt; : Generic server failure. Never expose stack traces or internal details.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;503 Service Unavailable&lt;/strong&gt; : The server is temporarily unable to handle requests (overloaded, maintenance). Include &lt;code&gt;Retry-After&lt;/code&gt; if known.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Mistake of Returning 200 for Everything
&lt;/h3&gt;

&lt;p&gt;A common anti-pattern is returning &lt;code&gt;200 OK&lt;/code&gt; with a body that contains an error flag:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="no"&gt;HTTP&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mf"&gt;1.1&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt; &lt;span class="no"&gt;OK&lt;/span&gt;

&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"success"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"error"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"User not found"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This forces every client to parse the body to know whether the request succeeded. It breaks HTTP-aware intermediaries (caches will cache failure responses), APM tools, and alerting systems. Use the status code as it was designed to be used.&lt;/p&gt;




&lt;h2&gt;
  
  
  Closing
&lt;/h2&gt;

&lt;p&gt;Get the constraints and the HTTP semantics right, and you've built the foundation. Neither one is optional trivia. The rest of REST design only works if two things hold: a client that trusts your status codes, and an architecture that respects statelessness.&lt;/p&gt;

&lt;p&gt;PS: Let me know if I missed anything, ping me on &lt;a href="https://twitter.com/irina_scurtu" rel="noopener noreferrer"&gt;Twitter/X&lt;/a&gt; or &lt;a href="https://linkedin.com/in/irinascurtu" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;, and follow along there if you'd like more of this. Let's chat.&lt;/p&gt;

</description>
      <category>api</category>
      <category>architecture</category>
      <category>backend</category>
      <category>webdev</category>
    </item>
    <item>
      <title>What Happens to Outbox When the Database Goes Down?</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 29 Sep 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/what-happens-to-outbox-when-the-database-goes-down-3dcl</link>
      <guid>https://dev.to/irina_scurtu/what-happens-to-outbox-when-the-database-goes-down-3dcl</guid>
      <description>&lt;p&gt;&lt;em&gt;Every outbox talk speaks about the broker failing.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I've given this talk enough times to know the slides by heart. The broker goes down. The outbox row is already committed, the worker publishes it later, and nothing is lost. It lands well, because it's true.&lt;/p&gt;

&lt;p&gt;Then someone asks the follow-up, and I don't have a slide for it. What happens when the &lt;strong&gt;database&lt;/strong&gt; is the thing that's unavailable? Not RabbitMQ or the broker. The database the outbox table lives in.&lt;/p&gt;

&lt;p&gt;This is more than a fair question.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the outbox is actually for
&lt;/h2&gt;

&lt;p&gt;The outbox pattern exists because of one specific problem. You need to save data and publish an event. Those are two different systems, talking over a network, and they can't share a transaction.&lt;/p&gt;

&lt;p&gt;Do the save first and the publish second. A crash in between leaves an order in your database that nobody downstream heard about. Do the publish first, and a failure leaves an event announcing work that never happened. Both are wrong, and no ordering of the two calls fixes it.&lt;/p&gt;

&lt;p&gt;The outbox removes the second system from the critical path. The event becomes a row in &lt;strong&gt;the same database, in the same transaction&lt;/strong&gt; as your domain data. Either both commit or neither does. A separate worker reads that table afterwards and publishes. If the broker is down right then, the row waits.&lt;/p&gt;

&lt;p&gt;The inbox pattern points the same idea the other way. Record that you received the message, in your own database, before you act on it. Then you can recognise a redelivery.&lt;/p&gt;

&lt;p&gt;Notice what both of those depend on. They assume &lt;strong&gt;your database is the reliable thing&lt;/strong&gt; in the picture. But it can't be. It's a system like any other.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why a missing database is a different kind of failure
&lt;/h2&gt;

&lt;p&gt;The problem the outbox solves is a partial write. Half the work committed and half didn't, and the two halves sit in systems that can't agree with each other.&lt;/p&gt;

&lt;p&gt;An unavailable database doesn't produce a partial write. It produces no write.&lt;/p&gt;

&lt;p&gt;The transaction never begins. There's no order row and no outbox row, and nothing sits half-finished anywhere. There's no inconsistency to repair, because nothing got recorded to be inconsistent with. Your service tried to do some work and the work didn't happen. That's an ordinary failure, and your application already knows how to talk about it.&lt;/p&gt;

&lt;p&gt;That's the shape of the whole answer. A down broker threatens correctness. A down database threatens availability. They feel the same when you're the one being paged. They need different responses.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fw3mu19goersdmjvv8z1i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fw3mu19goersdmjvv8z1i.png" alt="The outbox path from producer to consumer. A down broker only delays publishing, because the row is already committed. A down database stops the transaction from starting at all." width="800" height="458"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  On the producer side, the save just fails
&lt;/h2&gt;

&lt;p&gt;Your handler opens a transaction and the connection throws. The request fails. The caller gets an error.&lt;/p&gt;

&lt;p&gt;You retry at the application layer, with backoff and a limit. It's the same retry you'd write for any database that's temporarily unreachable. If it's an HTTP request, the client sees a 503 and decides whether to try again. If it's a message, nothing acknowledges it, so it comes back later. We'll get to that case.&lt;/p&gt;

&lt;p&gt;The important part is what didn't happen. Nothing was published, because publishing was never the first step. No downstream service acted on an order that doesn't exist. Your API returned an honest error instead of an acceptance it couldn't back up.&lt;/p&gt;

&lt;p&gt;Failing to write is a clean failure. Writing half of it costs you more.&lt;/p&gt;

&lt;h2&gt;
  
  
  The outbox worker stops and waits
&lt;/h2&gt;

&lt;p&gt;The worker's whole job is to poll a table. That table lives in the database that just went away. So the worker gets a connection error, logs it, and tries again next cycle. It does this for as long as the outage lasts.&lt;/p&gt;

&lt;p&gt;Meanwhile the rows committed before the outage sit there untouched, because that's what committed means. They're not in flight. They're not in a queue that might expire them. They're durable rows in a table, which is the safest place a pending message can be.&lt;/p&gt;

&lt;p&gt;When the database comes back, the next poll succeeds and the worker picks up where it stopped. Messages go out late. None go out twice because of the outage, and none go missing.&lt;/p&gt;

&lt;p&gt;Check one thing in your own setup. Make sure the worker's failure to reach the database is loud. A component that polls quietly can stay broken for an hour after everything else recovers. Nobody notices, because no user ever sees an error.&lt;/p&gt;

&lt;h2&gt;
  
  
  On the consumer side, the broker holds the line
&lt;/h2&gt;

&lt;p&gt;The consumer pulls a message off the queue and tries to write it to the inbox table. That write fails.&lt;/p&gt;

&lt;p&gt;So the consumer never acknowledges the message.&lt;/p&gt;

&lt;p&gt;That single fact does all the work. Every broker worth using treats an unacknowledged message the same way. After a visibility timeout or a channel close, it goes back on the queue and gets delivered again. The broker never had a reason to believe anyone handled it.&lt;/p&gt;

&lt;p&gt;The rule generalises well beyond this scenario. &lt;strong&gt;Never acknowledge work you couldn't persist.&lt;/strong&gt; Acknowledge after the write, never before, and most of your redelivery behaviour becomes correct by construction.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where it still bites
&lt;/h2&gt;

&lt;p&gt;The self-healing story is real, and it has an expiry date. This is the part I'd put on a slide.&lt;/p&gt;

&lt;p&gt;Queues grow while consumers are stuck. Every message you'd normally process piles up, along with the redeliveries of the ones already being retried. Queue depth tells you how much trouble is waiting when things come back. It's often the first place a database outage becomes visible.&lt;/p&gt;

&lt;p&gt;Retries don't run forever. Each redelivery burns an attempt. Once a message exhausts its retry policy it lands in the dead letter queue. An outage longer than your retry budget quietly turns good messages into dead-lettered ones, and a human has to replay them.&lt;/p&gt;

&lt;p&gt;Message TTL (time to live) and queue retention keep running during the outage. If your broker discards messages older than an hour, an hour-long outage starts deleting work. That's the failure mode that turns a delay into real data loss. It happens without a single error in your logs.&lt;/p&gt;

&lt;p&gt;None of these are outbox problems. They're what happens when a system stays unavailable longer than its timeouts expected. They're also why "it recovers on its own" needs a duration attached to it.&lt;/p&gt;

&lt;p&gt;Three zones, and two numbers decide where the boundaries fall. Up to your retry budget, the backlog is just a backlog. Past it, messages dead-letter and a human has to replay them. Past TTL and retention, the broker starts deleting, and there's nothing left to replay.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnyb83pc42ylaei170mn6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnyb83pc42ylaei170mn6.png" alt="A timeline of outage duration split into three zones. Queues grow, until the retry budget runs out; then messages land in the dead letter queue, until TTL and retention expire; after that they are deleted." width="799" height="279"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What this means in practice
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Treat a database outage as an availability incident&lt;/strong&gt; , not a data integrity one. Nothing partial was written, so nothing partial needs undoing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Retry the producer's save at the application layer.&lt;/strong&gt; Backoff, a limit, and an honest error to the caller.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Alert on your outbox worker's failures.&lt;/strong&gt; Silent polling is how a recovered system stays broken.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Acknowledge only after the inbox write succeeds.&lt;/strong&gt; That one rule covers most redelivery correctness.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Know your numbers&lt;/strong&gt; : retry budget, message TTL, and queue retention. They decide how long an outage stays survivable.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Closing
&lt;/h2&gt;

&lt;p&gt;This question is a good one because it makes you say out loud which system you're trusting. The outbox pattern trusts your database completely. That's reasonable, right up until someone asks what happens when that trust is unavailable for twenty minutes.&lt;/p&gt;

&lt;p&gt;Nothing partial gets written, so nothing partial needs undoing. Everything pauses instead of corrupting. Then a retention policy you configured two years ago decides how long that stays true.&lt;/p&gt;

&lt;p&gt;Go and find out how long your broker will hold everything before it starts deleting. Most teams have never measured it, and it's a five-minute answer. Tell me what you find on &lt;a href="https://twitter.com/irina_scurtu" rel="noopener noreferrer"&gt;Twitter/X&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>backend</category>
      <category>database</category>
      <category>systemdesign</category>
    </item>
    <item>
      <title>Compensation Is Not Rollback</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 22 Sep 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/compensation-is-not-rollback-90m</link>
      <guid>https://dev.to/irina_scurtu/compensation-is-not-rollback-90m</guid>
      <description>&lt;p&gt;&lt;em&gt;Distributed systems don't get an undo button.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Something fails halfway through a workflow, and somebody in the room says "we'll just roll it back."&lt;/p&gt;

&lt;p&gt;Everyone nods, because rollback is one of the few things in software that's genuinely simple. You've used it a thousand times. It works.&lt;/p&gt;

&lt;p&gt;Then you remember the order went through five services and three external APIs. The card was charged eleven seconds ago, by a payment provider that has never heard of your transaction.&lt;/p&gt;

&lt;h2&gt;
  
  
  What rollback actually is
&lt;/h2&gt;

&lt;p&gt;Rollback is a database primitive. That's not a technicality, it's the whole point.&lt;/p&gt;

&lt;p&gt;When a transaction fails, the database reverses every change inside it, atomically. There's no partial state to inspect and no half-committed row to clean up. The system returns to exactly where it was, and no observer ever sees the intermediate steps.&lt;/p&gt;

&lt;p&gt;This works because &lt;strong&gt;one system controls all of the state&lt;/strong&gt;. The database holds the data, the log, the locks, and the clock. It can promise atomicity because it never has to ask anyone else for permission. Rollback is instant, safe, and complete. It's complete only inside that boundary.&lt;/p&gt;

&lt;p&gt;Everything people believe about rollback is true. It's just true about one database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5gam5cpslb9kltg4mgty.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5gam5cpslb9kltg4mgty.png" alt="On the left, three writes inside one transaction boundary in a single database, all reversed atomically when the third fails. On the right, four services that each committed independently, with nothing left to reverse when the last one fails." width="800" height="203"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Why distributed systems break the promise
&lt;/h2&gt;

&lt;p&gt;Now spread the same workflow across services.&lt;/p&gt;

&lt;p&gt;Service A charged the card. Service B reserved the inventory. Service C sent the confirmation email. Service D fails.&lt;/p&gt;

&lt;p&gt;Each of those services committed its own change, independently, to its own store. Each was right to. There was no shared transaction, because there's no practical way to have one. Two-phase commit exists, it doesn't scale, and it turns every participant into a hostage of the slowest one.&lt;/p&gt;

&lt;p&gt;So there's nothing to reverse. You can't un-send an email. You can't un-charge a card atomically, because the charge lives in a payment provider's ledger and that ledger isn't yours. The inventory reservation is already visible to other customers.&lt;/p&gt;

&lt;p&gt;The only direction available is forward. Not back to the previous state, but on to a new one that resembles it.&lt;/p&gt;

&lt;h2&gt;
  
  
  What compensation actually is
&lt;/h2&gt;

&lt;p&gt;A compensating action is a &lt;strong&gt;new business action that semantically reverses a previous one&lt;/strong&gt;. That word semantically carries real weight.&lt;/p&gt;

&lt;p&gt;You issue a refund. That isn't an un-charge. It's a second transaction, leaving two entries on the customer's statement and two rows in the provider's ledger. You cancel the reservation, which is a new state rather than the absence of the old one. You send a cancellation email, which sits in the inbox underneath the confirmation you wish you hadn't sent.&lt;/p&gt;

&lt;p&gt;The end state is close to where you started. It isn't identical, and the difference isn't cosmetic. Anyone reading your data later will see that something happened and then something else undid it. An auditor, a support agent, a customer. That history is real, and it's often exactly what the business wants.&lt;/p&gt;

&lt;p&gt;Compensation is an operation like any other in your system. It runs business logic. It calls services. It writes to databases. And because it does all that, it can fail.&lt;/p&gt;

&lt;h2&gt;
  
  
  The four differences that matter
&lt;/h2&gt;

&lt;p&gt;Rollback is atomic. Compensation is &lt;strong&gt;eventual&lt;/strong&gt;. There's a window, sometimes a long one, where the charge has happened and the refund hasn't. Your system is visibly inconsistent during that window, and you have to decide what it shows users.&lt;/p&gt;

&lt;p&gt;Rollback is invisible to the business. Compensation is a &lt;strong&gt;business event&lt;/strong&gt;. Nobody outside the database learns about a rolled-back transaction. Everybody learns about a refund, including your finance team.&lt;/p&gt;

&lt;p&gt;Rollback cannot fail. Compensation &lt;strong&gt;absolutely can&lt;/strong&gt;. The refund API can be down. The cancellation can time out. The inventory service can reject the release, because someone else already bought the item.&lt;/p&gt;

&lt;p&gt;Rollback is symmetric. Compensation is often &lt;strong&gt;asymmetric&lt;/strong&gt;. Charging takes one call. Refunding takes a call, a settlement delay, and sometimes a manual review. The undo is rarely a mirror image of the do.&lt;/p&gt;

&lt;p&gt;Treating compensation as if it had rollback's properties is the most common distributed systems mistake I see. It stays invisible until the day it gets expensive.&lt;/p&gt;

&lt;h2&gt;
  
  
  Design compensation on purpose
&lt;/h2&gt;

&lt;p&gt;The practical work is unglamorous, and it pays for itself.&lt;/p&gt;

&lt;p&gt;Go through your workflow step by step. For each one, write down what undoing it means as a new action. Not "reverse the payment step" but "call the refund endpoint with the original payment reference and record the refund id". If you can't write that sentence, you don't have a compensating action. You have a hope.&lt;/p&gt;

&lt;p&gt;Model those actions as &lt;strong&gt;first-class workflow steps&lt;/strong&gt;. They deserve the same retries, logging, idempotency keys, and monitoring as the forward path. Compensation tucked into a catch block gets none of that, and it's the code that runs on your worst day.&lt;/p&gt;

&lt;p&gt;Then mark the steps you can't compensate at all. Sending an SMS is the honest example. It's gone, it's on someone's phone, and no API retrieves it. Once you know which steps are one-way doors, you can move them as late in the workflow as possible. That costs nothing and saves a great deal.&lt;/p&gt;

&lt;p&gt;Finally, the question almost nobody asks. What happens when the compensation itself fails? You need an answer, and it's usually retries, an alert, and a human. A failed compensation is its own error case, and it's the one that leaves money in the wrong place.&lt;/p&gt;

&lt;h2&gt;
  
  
  The saga pattern is this, written down
&lt;/h2&gt;

&lt;p&gt;Sagas are compensation made explicit. A saga is a sequence of local transactions. Each step has a defined compensating transaction, and if step N fails, the compensations for the preceding steps run in reverse.&lt;/p&gt;

&lt;p&gt;That's the whole idea. The value isn't the mechanism. It's the discipline of naming the undo for every step at design time, instead of at three in the morning.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Feeif557sluz59vx6tari.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Feeif557sluz59vx6tari.png" alt="The forward path runs from order placed through payment, reservation and confirmation email to a failed shipping step. Underneath, three compensating actions run in reverse: cancellation email, reservation released, refund issued." width="800" height="320"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You get two flavours. Choreography, where services react to each other's events and the workflow exists only as an emergent property of who listens to what. Orchestration, where a coordinator holds the state and tells each participant what to do next. Choreography couples less and is harder to see. Orchestration is easier to reason about and puts the logic in one place.&lt;/p&gt;

&lt;p&gt;Both need the same thing underneath: reliable messaging. A saga running on delivery you don't trust is a state machine that silently skips states, which is worse than no saga at all.&lt;/p&gt;

&lt;h2&gt;
  
  
  What this means in practice
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Stop saying rollback&lt;/strong&gt; about anything that crosses a service boundary. The word imports guarantees you don't have.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Write the compensating action for every step&lt;/strong&gt; , as a concrete call with concrete arguments.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Give compensations the same engineering as the forward path&lt;/strong&gt; , including idempotency, because they'll be retried.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Identify the steps you can't undo&lt;/strong&gt; and push them as late in the workflow as the business allows.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Plan for a failed compensation.&lt;/strong&gt; Retries, alerting, and a human path for the ones that stay broken.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Closing
&lt;/h2&gt;

&lt;p&gt;The mental model that causes the damage is the one where distributed workflows are just longer database transactions. They aren't. They're a series of small commitments to the outside world, each becoming real the moment it happens.&lt;/p&gt;

&lt;p&gt;Compensation is a business action. Rollback is a database primitive. Model them differently, because they're different, and the gap between them is where the money goes missing.&lt;/p&gt;

&lt;p&gt;Which step in your workflow has no real compensating action? That's usually the interesting one. Come tell me about it on &lt;a href="https://twitter.com/irina_scurtu" rel="noopener noreferrer"&gt;Twitter/X&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>database</category>
      <category>microservices</category>
      <category>systemdesign</category>
    </item>
    <item>
      <title>Your Idempotency Check Has a Race in It</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 15 Sep 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/your-idempotency-check-has-a-race-in-it-hf9</link>
      <guid>https://dev.to/irina_scurtu/your-idempotency-check-has-a-race-in-it-hf9</guid>
      <description>&lt;p&gt;&lt;em&gt;Safe to retry means nothing if two retries run at the same time.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Almost every team I talk to has an idempotency story, and it's almost always the same one. Give each operation a key. Look the key up. If you've seen it, return what you returned last time. If you haven't, do the work and save the result.&lt;/p&gt;

&lt;p&gt;It's a good design. It also passes every test you'll write for it, because your tests run one request at a time.&lt;/p&gt;

&lt;p&gt;Then production sends you two copies of the same message, half a millisecond apart. Both look up the key before either has written anything.&lt;/p&gt;

&lt;h2&gt;
  
  
  The check and the write are two different moments
&lt;/h2&gt;

&lt;p&gt;Here is the sequence, with two threads instead of one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Thread 1: SELECT ... WHERE key = 'abc' -&amp;gt; not found
Thread 2: SELECT ... WHERE key = 'abc' -&amp;gt; not found
Thread 1: process, then INSERT
Thread 2: process, then INSERT &amp;lt;- charged the card twice
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Neither thread did anything wrong. Both followed the design exactly. The design has a gap in the middle of it. It sits between the moment you check and the moment you act.&lt;/p&gt;

&lt;p&gt;This has a name that predates messaging by decades. Time-of-check to time-of-use, TOCTOU. It shows up anywhere you read state, decide, then write on that decision without holding anything in between. A distributed cache has it. A database read followed by a write has it. Any read-modify-write that isn't a single atomic operation has it.&lt;/p&gt;

&lt;p&gt;The window is small. It's also wide open, thousands of times a day, in a system doing real traffic.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsvijs28fms9ewgjf7ghs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsvijs28fms9ewgjf7ghs.png" alt="Two deliveries each ask the idempotency store whether key abc has been seen. Both are told no, because neither has written yet, so both process the message and the card is charged twice." width="800" height="505"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  This happens more often than the odds suggest
&lt;/h2&gt;

&lt;p&gt;The usual reaction is that two retries landing in the same millisecond sounds unlikely. It would be, if retries were spread evenly. They aren't.&lt;/p&gt;

&lt;p&gt;Duplicates arrive in bursts, because the things that cause them are bursty. A consumer's visibility timeout expires while it's still working. The broker hands that same message to a second consumer, mid-flight. A Kafka consumer group rebalances and reassigns partitions that were already being processed. A deployment rolls, and new instances pick up work the old ones hadn't acknowledged.&lt;/p&gt;

&lt;p&gt;Every one of those produces duplicates that are &lt;strong&gt;concurrent by construction&lt;/strong&gt;. They don't spread out politely over the next few minutes. Retry storms have the same shape. When a downstream service recovers, every client that was backing off comes back at once.&lt;/p&gt;

&lt;p&gt;Scale the consumer out to ten instances and the effect multiplies. You didn't make duplicates more likely. You made them more likely to overlap, and overlap is the thing your idempotency check can't survive.&lt;/p&gt;

&lt;h2&gt;
  
  
  Make the check and the write one operation
&lt;/h2&gt;

&lt;p&gt;The fix isn't a bigger lock or a longer transaction. Stop treating the check and the write as two steps that happen to sit near each other.&lt;/p&gt;

&lt;p&gt;The simplest version is a unique constraint. Put one on the idempotency key and let the database referee the race.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;INSERT&lt;/span&gt; &lt;span class="k"&gt;INTO&lt;/span&gt; &lt;span class="n"&gt;processed_messages&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;processed_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;VALUES&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@messageId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nd"&gt;@now&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="k"&gt;CONFLICT&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;DO&lt;/span&gt; &lt;span class="k"&gt;NOTHING&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then look at how many rows changed. One means you won and should do the work. Zero means someone else got there first, and the right thing to do is nothing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;inserted&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;connection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ExecuteAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InsertProcessedMessage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;messageId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inserted&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Another delivery of this message is already being handled.&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;DoTheActualWork&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's the whole trick. The database does the check and the write in one indivisible step. No second thread can slip through the gap. Write it as &lt;code&gt;ON CONFLICT DO NOTHING&lt;/code&gt; in Postgres. Or a unique index that throws in SQL Server, or &lt;code&gt;SET NX&lt;/code&gt; in Redis. The property is the same: &lt;strong&gt;one operation, not two&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi5dzbgeose4whxmo5in6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi5dzbgeose4whxmo5in6.png" alt="Two deliveries both hit a single insert with on conflict do nothing. One gets a row back and does the work, the other gets zero rows and returns without acting." width="799" height="186"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Optimistic concurrency reaches the same place from another direction. Include a version number or an ETag in the write, and require it to match what you read. If someone moved the row underneath you, your update affects zero rows and you know you lost. This fits better when you're updating existing state rather than recording that a message was seen.&lt;/p&gt;

&lt;p&gt;One version of this looks right and isn't. Wrapping the SELECT and the INSERT in a transaction doesn't close the gap on its own. At read-committed isolation, two transactions can both read "not found" happily. You need the constraint, a stricter isolation level, or an explicit lock. The transaction alone isn't the atomicity you're looking for.&lt;/p&gt;

&lt;h2&gt;
  
  
  Losing the race is a normal outcome
&lt;/h2&gt;

&lt;p&gt;Once the write is atomic, roughly half your concurrent duplicates will lose. You have to decide what losing looks like to the caller.&lt;/p&gt;

&lt;p&gt;Returning the stored result of the first execution is the friendliest option, and the most expensive. You keep the response body around, keyed by the idempotency key, for as long as anyone might retry. Stripe does this, which is why their idempotency layer is a small state machine rather than a unique index.&lt;/p&gt;

&lt;p&gt;Returning a 409 Conflict is honest and cheap. It hands the decision back to the caller. That's reasonable for a synchronous API, and unhelpful for a message handler with nobody to hand anything to.&lt;/p&gt;

&lt;p&gt;Doing nothing at all is correct more often than people expect. Say your handler's only job is moving an order from pending to paid. The second delivery has no work left. Silence is the right response.&lt;/p&gt;

&lt;p&gt;The rule underneath all three: &lt;strong&gt;the caller must not be able to tell whether it won or lost&lt;/strong&gt;. Same status, same shape, same effect on the world. The moment a duplicate returns something visibly different, you've leaked your implementation into your contract.&lt;/p&gt;

&lt;h2&gt;
  
  
  Keys can't live forever
&lt;/h2&gt;

&lt;p&gt;An idempotency table with no expiry policy grows until someone notices it in a disk alert.&lt;/p&gt;

&lt;p&gt;Pick a retention window covering your realistic retry horizon, then delete beyond it. A day handles transport-level redelivery comfortably. A week covers manual replays and a long weekend of nobody watching the dead letter queue. Longer than that, and you're storing rows against a retry nobody will send.&lt;/p&gt;

&lt;p&gt;The forgotten part is that expiry is a guarantee with an end date. After the TTL passes, the same key is a brand new request and the operation runs again. That's a business decision as much as a storage one. It belongs in your API documentation, next to everything else you promise.&lt;/p&gt;

&lt;h2&gt;
  
  
  What this means in practice
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Never SELECT then INSERT.&lt;/strong&gt; Use a unique constraint, an atomic upsert, or a compare-and-set. One operation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Assume your duplicates are concurrent.&lt;/strong&gt; Timeout expiry, rebalances, and deploys all produce overlapping deliveries.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Decide what losing returns&lt;/strong&gt; , and make it indistinguishable from winning.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Give keys a TTL&lt;/strong&gt; , then document when the guarantee expires.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reach for the stored-response state machine&lt;/strong&gt; only when one logical operation spans several side effects. A unique constraint covers the rest.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you're on MassTransit or NServiceBus, most of this exists already. Both frame their outbox support as a replacement for hand-rolled idempotency checks, not something you bolt on beside one. That's one less race condition to write yourself.&lt;/p&gt;

&lt;h2&gt;
  
  
  Closing
&lt;/h2&gt;

&lt;p&gt;Idempotency is usually taught as a property of an operation. It's more useful as a property of an operation under contention. That's the only condition where it does any work.&lt;/p&gt;

&lt;p&gt;A handler that's safe to retry sequentially is a handler that has never been tested. Run two copies at once and see what your database says.&lt;/p&gt;

&lt;p&gt;How are you handling this in your stack?&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>backend</category>
      <category>database</category>
      <category>systemdesign</category>
    </item>
    <item>
      <title>Eventual Consistency Explained</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Thu, 20 Aug 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/eventual-consistency-explained-1pkc</link>
      <guid>https://dev.to/irina_scurtu/eventual-consistency-explained-1pkc</guid>
      <description>&lt;p&gt;&lt;em&gt;Not a bug. A trade-off you need to understand.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Update your profile picture, refresh the page on your phone, and for a second the old one is still there. Is that a bug? Most people's instinct is yes: I just saved this, why doesn't everything show it immediately?&lt;/p&gt;

&lt;p&gt;It isn't a bug. It's eventual consistency, and if you build distributed systems, you're relying on it constantly, whether you've designed for it or not.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Promise We Want, and What It Costs
&lt;/h2&gt;

&lt;p&gt;The promise everyone wants is simple: you update something, and every service, every region, every cache sees it instantly. One version of the truth, always. That's &lt;strong&gt;strong consistency&lt;/strong&gt; , and it's a completely reasonable thing to want.&lt;/p&gt;

&lt;p&gt;It's also expensive. Guaranteeing that every node agrees before you consider a write done means coordination. And coordination across a network, especially across regions, means waiting on round trips you don't control. Do that on every write, at scale, and your system's latency is now bounded by your slowest node and your worst network hop.&lt;/p&gt;

&lt;p&gt;So most distributed systems don't do that. They accept a weaker guarantee in exchange for speed and availability, and call it eventual consistency.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Eventual Consistency Actually Means
&lt;/h2&gt;

&lt;p&gt;Here's the mechanism: a write lands on one node (or a small subset of nodes). The other nodes find out later, through replication, gossip, or some other propagation mechanism, not as part of the original write. If no new updates come in, every node &lt;strong&gt;eventually&lt;/strong&gt; converges on the same value.&lt;/p&gt;

&lt;p&gt;That word "eventually" is doing a lot of work, and it's worth being precise about it. It's a promise about outcome, not about timing. Given enough time and no further writes, all replicas agree. In practice, "eventually" is usually milliseconds, sometimes seconds, and only occasionally something you'd notice. But the guarantee itself says nothing about &lt;em&gt;how fast&lt;/em&gt;. It only says &lt;em&gt;eventually&lt;/em&gt;, which is a liveness guarantee, not a timing one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sequenceDiagram
    participant Client
    participant A as Node A
    participant B as Node B
    participant C as Node C

    Client-&amp;gt;&amp;gt;A: Write(value = X)
    A--&amp;gt;&amp;gt;Client: Ack (write accepted)
    Note over A,C: Client already sees success.&amp;lt;br/&amp;gt;Replication starts now, not before.
    A-&amp;gt;&amp;gt;B: Replicate X
    A-&amp;gt;&amp;gt;C: Replicate X
    Note over B: Still serving the old value&amp;lt;br/&amp;gt;until replication lands
    B--&amp;gt;&amp;gt;B: Converges on X
    C--&amp;gt;&amp;gt;C: Converges on X
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The CAP Trade-Off
&lt;/h2&gt;

&lt;p&gt;This is where the CAP theorem shows up. It's less abstract than it sounds once you connect it to a decision you're already making. CAP says a distributed system can only guarantee two of these three properties at once, and in practice, partition tolerance isn't optional for any system that spans more than one node:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight dot"&gt;&lt;code&gt;&lt;span class="n"&gt;graph&lt;/span&gt; &lt;span class="no"&gt;LR&lt;/span&gt;
    &lt;span class="no"&gt;C&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Consistency&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="no"&gt;A&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Availability&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="no"&gt;P&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Partition&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;br&lt;/span&gt;&lt;span class="o"&gt;/&amp;gt;&lt;/span&gt;&lt;span class="nc"&gt;Tolerance&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="no"&gt;C&lt;/span&gt; &lt;span class="o"&gt;---|&lt;/span&gt;&lt;span class="s2"&gt;"CA: no partition tolerance"&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="no"&gt;A&lt;/span&gt;
    &lt;span class="no"&gt;C&lt;/span&gt; &lt;span class="o"&gt;---|&lt;/span&gt;&lt;span class="s2"&gt;"CP: consistent, may be unavailable"&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="no"&gt;P&lt;/span&gt;
    &lt;span class="no"&gt;A&lt;/span&gt; &lt;span class="o"&gt;---|&lt;/span&gt;&lt;span class="s2"&gt;"AP: available, eventually consistent"&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="no"&gt;P&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That leaves a real choice only once a partition actually happens: stay &lt;strong&gt;consistent&lt;/strong&gt; , where every node sees the same data, or stay &lt;strong&gt;available&lt;/strong&gt; , where every request gets a response, even if it's not the latest data. You can't fully have both during that partition.&lt;/p&gt;

&lt;p&gt;Eric Brewer, who proposed CAP back in 2000, revised his own framing in 2012 for exactly this reason. Partition tolerance was never really a dial you could turn off for a system with more than one node, so treating it as an equal third option was misleading. The only decision that matters is what happens to consistency and availability once a partition actually hits.&lt;/p&gt;

&lt;p&gt;Real systems announce which side of that decision they land on. &lt;strong&gt;CP&lt;/strong&gt; (consistency + partition tolerance) systems, like MongoDB in its default configuration or HBase, choose consistency: rather than serve you something wrong, they'd rather reject the request. &lt;strong&gt;AP&lt;/strong&gt; (availability + partition tolerance) systems, like Cassandra or DynamoDB, choose availability: they'll serve you data that might be a few writes behind rather than nothing at all, and lean on eventual consistency to close the gap afterward. &lt;strong&gt;CA&lt;/strong&gt; (consistency + availability) systems, like a traditional PostgreSQL or MySQL install running in one place, get to keep both, but only because they were never asked to survive a partition between nodes. Spread that same database across two data centers, and CA quietly stops being on the table.&lt;/p&gt;

&lt;p&gt;Eventual consistency is the deliberate choice of availability over strong consistency. You're saying: I'd rather my system keep responding, even with slightly stale data somewhere, than refuse to answer. It shouldn't have to wait until everyone agrees. For a lot of systems, that's exactly the right call. It's worth naming it as a call, not something that just happens to you.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where You're Already Using It
&lt;/h2&gt;

&lt;p&gt;This isn't exotic. You might assume eventual consistency is something only distributed-systems specialists deal with. Consider how much of your daily infrastructure already works this way.&lt;/p&gt;

&lt;p&gt;DNS is the oldest example: update a record and it can take minutes to propagate everywhere, not milliseconds. CDNs cache content at edge nodes and take time to invalidate it after a change. Social media feeds (likes, comments, view counts) propagate asynchronously. Nobody expects a like count to update everywhere in the same instant. And if you run a primary/replica database setup, your read replicas are, by construction, eventually consistent with the primary. There's always some lag, even if it's usually small enough that nobody notices.&lt;/p&gt;

&lt;p&gt;You've been relying on eventual consistency for years. The only question is whether you've been designing for it on purpose.&lt;/p&gt;

&lt;h2&gt;
  
  
  What This Means in Practice
&lt;/h2&gt;

&lt;p&gt;Designing for eventual consistency on purpose looks different from tolerating it by accident. A few things that help:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Show what the user submitted, not what's confirmed.&lt;/strong&gt; This is optimistic UI. Update the screen right after the action. Don't wait on a round trip to every replica before showing the change.&lt;/li&gt;
&lt;li&gt;Retries should be idempotent. If an operation might have partially succeeded, retrying it again needs to be safe, not additive.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Version your data.&lt;/strong&gt; ETags, sequence numbers, or vector clocks let you detect conflicts instead of silently losing one write to another.&lt;/li&gt;
&lt;li&gt;Conflicts need to be resolvable, not just detectable. "Last write wins" is the easy default, but it isn't always the right one. Know when it's acceptable and when it isn't.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;None of this has to be all-or-nothing at the system level, either. Most distributed databases let you dial consistency per operation instead of per deployment. Cassandra lets you ask for a &lt;code&gt;QUORUM&lt;/code&gt; read on an account balance and an &lt;code&gt;ONE&lt;/code&gt; read on an activity feed, in the same application. DynamoDB defaults to eventually consistent reads but gives you a strongly consistent read on request, at roughly double the read cost. MongoDB's &lt;code&gt;writeConcern&lt;/code&gt; and &lt;code&gt;readPreference&lt;/code&gt; settings do the same job. Pick the guarantee per query, not per database.&lt;/p&gt;

&lt;p&gt;Know the specific failure patterns to watch for too. They're the same handful every time:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reading your own write and getting the stale value back (you just saved this, why doesn't it show?).&lt;/li&gt;
&lt;li&gt;Stale aggregates, where a count or total lags behind the records it's summarizing.&lt;/li&gt;
&lt;li&gt;Two users updating the same record concurrently, with one silently overwriting the other.&lt;/li&gt;
&lt;li&gt;Downstream actions (an email, a notification) firing off the back of data that's already out of date by the time they run.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;None of these are exotic bugs. They're the predictable consequences of eventual consistency meeting code that was written as if it were strongly consistent.&lt;/p&gt;

&lt;p&gt;Not every part of your system should take the eventually-consistent trade, either. Financial transactions (debits and credits) need to be atomic. Inventory reservation needs strong consistency, or two customers can both "successfully" claim the last item in stock. A revoked authentication token needs to be invalid immediately, not eventually. Eventual consistency is a sensible default for a lot of your system. It isn't a universal rule. Treat it as one, and you'll end up debugging a double-sold item at 2am.&lt;/p&gt;

&lt;h2&gt;
  
  
  Closing
&lt;/h2&gt;

&lt;p&gt;Eventual consistency trades "always correct" for "always available." For most of what you build, that's the right trade. The mistake isn't choosing it. The mistake is not knowing you've chosen it.&lt;/p&gt;

&lt;p&gt;The worst eventual consistency bugs I've seen didn't come from the trade-off itself. They came from nobody realizing they'd made a trade-off, until a user noticed their own change had disappeared.&lt;/p&gt;

&lt;p&gt;PS: Let me know if I missed anything, ping me on &lt;a href="https://twitter.com/irina_scurtu" rel="noopener noreferrer"&gt;Twitter/X&lt;/a&gt; or &lt;a href="https://linkedin.com/in/irinascurtu" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;, and follow along there if you'd like more of this. Let's chat.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>database</category>
      <category>scalability</category>
      <category>systemdesign</category>
    </item>
    <item>
      <title>When Business Processes Outlive Your Request</title>
      <dc:creator>Irina Scurtu</dc:creator>
      <pubDate>Tue, 14 Apr 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/irina_scurtu/when-business-processes-outlive-your-request-1npi</link>
      <guid>https://dev.to/irina_scurtu/when-business-processes-outlive-your-request-1npi</guid>
      <description>&lt;p&gt;&lt;em&gt;A request has a lifecycle measured in milliseconds. A business process has one measured in minutes, hours, or days - and the gap between those two timelines is where most distributed systems go wrong.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The Millisecond and the Multi-Day Process
&lt;/h2&gt;

&lt;p&gt;Think about what happens when a customer places an order on an e-commerce platform. From the user's perspective, they click "Buy" and wait a few seconds for a confirmation. But behind the scenes, that single click might kick off a workflow that takes days to fully complete: payment authorisation, inventory reservation, warehouse picking, carrier handoff, customs clearance if it's international, and eventually delivery confirmation.&lt;/p&gt;

&lt;p&gt;That workflow doesn't live inside a single HTTP request. It can't - not because of any technical limitation on our end, but because the world it's coordinating with operates on a different clock. The payment provider has its own settlement windows. The warehouse runs on shifts. The carrier updates its tracking on its own schedule. And if any of those steps fail mid-flight, the system needs to know what to do, even though the original HTTP connection closed three days ago.&lt;/p&gt;

&lt;p&gt;This isn't unique to e-commerce. Loan approval workflows sit in review queues for hours before an underwriter picks them up. User onboarding flows wait for email verification and background checks before granting access. Subscription billing retries over days when a card declines. &lt;strong&gt;The moment a business process outlives its triggering request, you have a different class of problem&lt;/strong&gt; - and request-response thinking is the wrong tool for it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Request-Response Thinking Breaks Down
&lt;/h2&gt;

&lt;p&gt;The request-response model is beautiful in its simplicity. A client sends a request, the server does work, the server responds. The connection is open the whole time; if something fails, you get an exception; if everything succeeds, you get data back. It's easy to reason about because one thing happens at a time, in one place, under one transaction.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sequenceDiagram
    participant Client
    participant Server

    Client-&amp;gt;&amp;gt;Server: Request
    Server--&amp;gt;&amp;gt;Client: Response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Distribute that workflow across multiple services, though, and the guarantees evaporate fast. Consider an order fulfillment flow that calls three services: one charges the card, one reserves inventory, and one sends a confirmation email. If the inventory service fails after the card charge goes through, what state are you in? The database transaction that might have protected you in a monolith doesn't span service boundaries. Each service has already committed its own local transaction. You can't "rollback" a charge that's already been authorised. You can't "un-send" an email.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sequenceDiagram
    participant Client
    participant OrderService as Order Service
    participant PaymentService as Payment Service
    participant InventoryService as Inventory Service
    participant EmailService as Email Service

    Client-&amp;gt;&amp;gt;OrderService: POST /orders
    activate OrderService
    OrderService-&amp;gt;&amp;gt;PaymentService: Charge card
    PaymentService--&amp;gt;&amp;gt;OrderService: ✓ Authorised
    OrderService-&amp;gt;&amp;gt;InventoryService: Reserve stock
    InventoryService--&amp;gt;&amp;gt;OrderService: ✗ Out of stock
    Note over PaymentService: Card already charged
    Note over EmailService: Never reached
    OrderService--&amp;gt;&amp;gt;Client: 500 Error
    deactivate OrderService
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What you get instead is &lt;strong&gt;partial completion&lt;/strong&gt; - a system where some steps succeeded, some failed, and the overall state is inconsistent in ways that are not immediately obvious. And this isn't a corner case you can architect away. Services fail mid-flight. Networks drop connections. Deployments happen. The question isn't whether partial completion will occur; it's whether your system knows how to recover when it does.&lt;/p&gt;

&lt;p&gt;There's also the &lt;strong&gt;state drift problem&lt;/strong&gt;. In a long-running workflow, every service involved maintains its own view of the process state. If those views diverge - because a message was lost, a retry was missed, or a timeout fired at the wrong moment - you end up with services that disagree about where the workflow is. The payment service thinks the order is complete. The inventory service thinks it was cancelled. Nobody is wrong according to their own data. The system is just inconsistent.&lt;/p&gt;

&lt;p&gt;Want the next one in your inbox? &lt;a href="https://irinacodes.kit.com/" rel="noopener noreferrer"&gt;One email a week.&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Sagas: A Fast Recap
&lt;/h2&gt;

&lt;p&gt;The Saga pattern was formalised by Hector Garcia-Molina and Kenneth Salem back in 1987, originally in the context of long-lived database transactions. The core idea is simple: instead of one large distributed transaction that would require coordination across all participants (which doesn't scale and is largely impractical in practice), you break the workflow into a &lt;strong&gt;sequence of smaller local transactions&lt;/strong&gt; , each of which commits independently. And for each of those steps, you define a &lt;strong&gt;compensating transaction&lt;/strong&gt; - a business action that semantically reverses what that step did, should something go wrong later.&lt;/p&gt;

&lt;p&gt;If step 4 fails in a five-step workflow, you run the compensating transactions for steps 3, 2, and 1 in reverse order. You end up in a state that's consistent again - not identical to where you started (the compensation itself is a new business event), but coherent.&lt;/p&gt;

&lt;p&gt;That's the pattern in one paragraph. Two things to hold onto: the sequence of local commits, and the compensations that undo them. Everything else - orchestration vs choreography, timeout handling, observability - is about how you implement that idea well in production.&lt;/p&gt;

&lt;h2&gt;
  
  
  Designing the Saga: Orchestration vs Choreography
&lt;/h2&gt;

&lt;p&gt;There are two ways to coordinate a saga, and choosing the wrong one for your context creates pain that's hard to unwind.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Orchestration&lt;/strong&gt; means there's a central coordinator - a saga state machine or process manager - that drives each step. It sends commands to services, waits for responses, tracks the overall state, and decides what happens next. The workflow logic lives in one place. If you need to know where a given order is in the fulfillment process, you ask the coordinator. This is intuitive. It maps well onto how humans think about workflows, and it makes complex compensations straightforward to implement because the coordinator has the full context.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Orchestration&lt;/strong&gt; - workflow logic lives in the coordinator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight dot"&gt;&lt;code&gt;&lt;span class="n"&gt;flowchart&lt;/span&gt; &lt;span class="no"&gt;TD&lt;/span&gt;
    &lt;span class="no"&gt;C&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Coordinator&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="no"&gt;C&lt;/span&gt; &lt;span class="o"&gt;--&amp;gt;|&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt; &lt;span class="nc"&gt;ChargeCard&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="no"&gt;P&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Payment&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="no"&gt;C&lt;/span&gt; &lt;span class="o"&gt;--&amp;gt;|&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt; &lt;span class="nc"&gt;ReserveStock&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="no"&gt;I&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Inventory&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="no"&gt;C&lt;/span&gt; &lt;span class="o"&gt;--&amp;gt;|&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt; &lt;span class="nc"&gt;CreateShipment&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="no"&gt;S&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Shipping&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Choreography&lt;/strong&gt; means there's no central coordinator. Each service reacts to events published by previous steps. Service A completes its work and publishes &lt;code&gt;OrderValidated&lt;/code&gt;. Service B subscribes to that event, does its part, and publishes &lt;code&gt;StockReserved&lt;/code&gt;. Service C picks that up and publishes &lt;code&gt;PaymentProcessed&lt;/code&gt;. The workflow emerges from the interactions - no single service orchestrates it. This scales better, removes a central point of coupling, and lets each team own their domain completely.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Choreography&lt;/strong&gt; - workflow emerges from events, no coordinator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sequenceDiagram
    participant P as Payment
    participant I as Inventory
    participant S as Shipping

    Note over P,S: No coordinator — services react to events
    P-)I: OrderPaid
    I-)S: StockReserved
    S-)P: ShipmentCreated
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So how do you choose? I look at a few things. If the workflow has &lt;strong&gt;complex branching logic&lt;/strong&gt; - "if the payment fails, route to retry; if the retry budget is exhausted, escalate to manual review; if manual review times out, cancel and notify" - that logic has to live somewhere. In choreography, it ends up scattered across services that need to know about each other's states, which tends to create hidden coupling. Orchestration keeps it in one place. On the other hand, if the steps are genuinely &lt;strong&gt;independent domain reactions&lt;/strong&gt; - each service truly just needs to know "this thing happened, now I do my part" - choreography gives you better isolation and resilience.&lt;/p&gt;

&lt;p&gt;Where I see teams go wrong is mixing both styles within a single workflow. An orchestrator that also listens to events from services it's supposed to be coordinating creates a tangle. Pick one model per workflow, and be deliberate about it. Choreography is not "orchestration without writing a coordinator" - it's a different design choice with different trade-offs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Compensating Transactions Done Right
&lt;/h2&gt;

&lt;p&gt;Here's the thing that trips up almost every team the first time they design a saga: &lt;strong&gt;compensation is not rollback&lt;/strong&gt;. They look similar on the surface - something went wrong, we go back to where we were - but they're fundamentally different operations.&lt;/p&gt;

&lt;p&gt;Rollback is a database primitive. When a transaction fails, the database engine atomically reverses every change as if the transaction never happened. It's invisible to the business. It cannot fail. It's symmetric - the before and after states are identical.&lt;/p&gt;

&lt;p&gt;Compensation is a business action. Issuing a refund is not "un-charging" a card - it's a new transaction that creates a new fact in the payment ledger. Cancelling a reservation is not "un-reserving" inventory - it's releasing stock back to the available pool, which may then be picked up by another order. Sending a cancellation email is not "un-sending" the confirmation - it's a new message with a new meaning. Compensation can fail. It can be partial. It's visible to the business and to the customer.&lt;/p&gt;

&lt;p&gt;This matters because if you design compensations as if they were rollbacks, you'll miss important cases. The most important question to ask when designing a compensating transaction is: &lt;strong&gt;"What if this compensation fails?"&lt;/strong&gt; Most teams never ask it. A failed compensation is its own error case that needs its own handling - possibly a manual intervention workflow, an alert to an operations team, or a retry with a longer delay.&lt;/p&gt;

&lt;p&gt;Design compensations upfront, not as afterthoughts. For every step in your saga, before you write the forward path, write the compensating action. Name it explicitly: &lt;code&gt;RefundPayment&lt;/code&gt;, &lt;code&gt;ReleaseReservation&lt;/code&gt;, &lt;code&gt;SendCancellationNotification&lt;/code&gt;. Some steps won't have a neat compensation - sending an SMS is very hard to undo. Model those as non-compensatable steps and think carefully about where in the saga sequence they appear.&lt;/p&gt;

&lt;p&gt;Every compensating transaction must also be &lt;strong&gt;idempotent&lt;/strong&gt;. When your saga state machine executes a compensation, it might execute it more than once - due to a retry after a timeout, or a network blip that prevented the acknowledgment from reaching the coordinator. Executing the same compensation twice must produce the same result as executing it once. The refund must not be issued twice. The reservation must not be released twice and then fail on a third attempt. Design for this from the start, not after you find the bug in production.&lt;/p&gt;

&lt;h2&gt;
  
  
  Timeouts, Retries, and the Messy Middle
&lt;/h2&gt;

&lt;p&gt;Long-running workflows spend a lot of time in a state I call the messy middle: you've sent a command to a service, and you don't know what happened to it.&lt;/p&gt;

&lt;p&gt;The message might have been delivered and processed successfully but the acknowledgment was lost in transit. The message might never have arrived at all. The service might have received it, started processing, crashed halfway through, and is now recovering. The service might have processed it and responded, but your network blipped and you missed the response. From the saga coordinator's perspective, all of these look identical: silence.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sequenceDiagram
    participant C as Coordinator
    participant S as Service

    Note over C,S: Scenario A — message never arrived
    C--xS: Command
    C-&amp;gt;&amp;gt;C: ⏱ Timeout

    Note over C,S: Scenario B — service crashed mid-processing
    C-&amp;gt;&amp;gt;S: Command
    Note over S: Crash
    C-&amp;gt;&amp;gt;C: ⏱ Timeout

    Note over C,S: Scenario C — acknowledgment lost
    C-&amp;gt;&amp;gt;S: Command
    Note over S: ✓ Processed
    S--xC: Ack
    C-&amp;gt;&amp;gt;C: ⏱ Timeout

    Note over C: All three look identical to the coordinator
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the fundamental challenge that makes distributed systems hard. The timeout fires, and you need to make a decision: did that step complete or not?&lt;/p&gt;

&lt;p&gt;The answer is almost always: &lt;strong&gt;assume it might have completed, and design your retry as if it did&lt;/strong&gt;. Send the same command again with the same idempotency key. A well-designed service will recognise the duplicate and return the result of the first execution without re-processing. A poorly designed service will execute the operation twice. This is why idempotency isn't optional in saga steps - it's the mechanism that makes the messy middle safe to navigate.&lt;/p&gt;

&lt;p&gt;For retry policies within sagas, I think in terms of three categories. &lt;strong&gt;Transient failures&lt;/strong&gt; - network blips, brief overloads - should be retried quickly, with exponential backoff and jitter to avoid thundering-herd effects. &lt;strong&gt;Uncertain states&lt;/strong&gt; - where you timed out and don't know the outcome - should be retried with idempotency keys. &lt;strong&gt;Permanent failures&lt;/strong&gt; - a 400 Bad Request, a business rule violation, an external service that's permanently shut down - should not be retried at all. Retrying a permanent failure is just executing the same bug repeatedly.&lt;/p&gt;

&lt;p&gt;Timeout policies should be defined per step, based on that step's expected latency SLA. Don't use a single global timeout for everything - a warehouse reservation might legitimately take 30 seconds while a payment authorisation should complete in under 3. When a timeout fires in a saga, you have three options: retry the step, escalate to manual review, or start the compensation sequence. Which one you choose depends on the business rules - and those rules should be explicit in your saga design, not emergent from whatever happens to work in tests.&lt;/p&gt;

&lt;h2&gt;
  
  
  Observability: Seeing Inside the Black Box
&lt;/h2&gt;

&lt;p&gt;A long-running workflow that spans multiple services and days of calendar time is, without the right observability, a black box. You know when it started, and you know when it ends. Everything in between is inference.&lt;/p&gt;

&lt;p&gt;The most important thing you can do is establish a &lt;strong&gt;correlation ID&lt;/strong&gt; from the very first event, and propagate it through every message, every log line, every trace span for the entire lifetime of the workflow. The correlation ID ties together every bit of activity - the payment charge, the inventory update, the shipping label generation - into a single coherent narrative. Without it, debugging a workflow failure means manually correlating timestamps across five services' logs, which is miserable and error-prone.&lt;/p&gt;

&lt;p&gt;Beyond correlation, you need &lt;strong&gt;saga state snapshots&lt;/strong&gt; - a persistent record of what state the saga is in at each point in time. Every time the saga transitions - a step completes, a timeout fires, a compensation begins - record that transition with a timestamp. This gives you a queryable audit log: "where is order 12345 in the workflow right now?" and "what was the sequence of events that led to this saga being stuck in the compensation phase?" A good saga state machine will handle this automatically; if you're rolling your own, it's the first thing to build.&lt;/p&gt;

&lt;p&gt;Think about what you need to monitor operationally:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How many saga instances are currently in-flight, by workflow type and by state?&lt;/li&gt;
&lt;li&gt;What's the p99 completion time for each workflow type, and how has it changed over time?&lt;/li&gt;
&lt;li&gt;How many sagas are currently stuck - in a state they haven't left for longer than expected?&lt;/li&gt;
&lt;li&gt;What's the rate of compensations being triggered, and which saga steps are causing them most often?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That last metric is particularly valuable. If you start seeing a spike in compensations triggered from a specific step, that step is degrading. You can catch this before it turns into a customer-visible incident.&lt;/p&gt;

&lt;h2&gt;
  
  
  Five Things Worth Remembering
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Model the unhappy paths first.&lt;/strong&gt; The happy path is easy - services cooperate, everything succeeds. The value of saga design is in making failure explicit: defining what "undo step 3" means as a named business operation before you write step 3.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Compensation is not rollback.&lt;/strong&gt; It's a new forward action with its own failure modes. Ask "what if this compensation fails?" for every step, and have an answer.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Choose orchestration or choreography deliberately.&lt;/strong&gt; Both are valid. Orchestration wins for complex branching and human-in-loop steps. Choreography wins for genuinely independent domain reactions. Mixing both within a single workflow is a sign you haven't committed to a model.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Every saga step must be idempotent.&lt;/strong&gt; The messy middle is unavoidable in distributed systems. The mechanism that makes retries safe is idempotency, and it needs to be designed in from the start, not retrofitted.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Observability is not optional.&lt;/strong&gt; A workflow you can't see is a workflow you can't operate. Correlation IDs, state snapshots, and operational metrics are the minimum.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Whatever your stack - MassTransit, NServiceBus, Temporal, AWS Step Functions, or something you've built yourself - these patterns apply. The frameworks help with the plumbing, but the design thinking is on you.&lt;/p&gt;




&lt;p&gt;If any of this resonates with problems you're currently dealing with, or if you disagree with any of my choices here, reach out. I'd genuinely like to hear how your team has approached it.&lt;/p&gt;

&lt;p&gt;PS: Let me know if I forgot anything.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>backend</category>
      <category>systemdesign</category>
    </item>
  </channel>
</rss>
