The Double Tap That Charged Twice: Idempotency Keys and Azure SQL

How to prevent duplicate orders when a user double-clicks Place order: an idempotency key from the app and a unique index in Azure SQL.

Suthahar Jegatheesan By Suthahar Jegatheesan Published

Azure 24 min read —views
Article banner. On the left, the eyebrow "Azure, system design" above the title "The double tap that charged twice" and the lines "One order the customer meant. Two rows in the database.", with the MSDEVBUILD wordmark and the author name below. On the right, three stacked boxes joined by arrows: a grey box reading "POST /api/orders, twice: a double tap, or a retry after a timeout", an arrow labelled "no key" to an amber box reading "App Service, 3 instances: a fresh order id for every request", and an arrow labelled "two rows" to a red box reading "Two orders, two charges, and the kitchen cooked both".

One tap on “Place order” should create one order. When a double tap or a retry after a timeout creates two, the fix isn’t a smarter button. It’s an idempotency key from the app and a unique index in Azure SQL, and this is the Friday night that proves it.

It’s 20:10 on a Friday, the dinner rush, and you’re the engineer on call for a food delivery app. The support inbox has a new kind of ticket.

“I ordered one biryani. I was charged ₹410 three times.”

Ten minutes later a restaurant partner calls. Two identical orders from the same customer, 180 milliseconds apart. The kitchen cooked both, the rider delivered both, and the customer refused the second bag at the door.

Nothing is down. Error rates are normal. The payment gateway is slow tonight, but it’s working. Every order in the database is a valid order. There are just too many of them.

Ninety minutes, and two fixes that didn’t hold

TimeWhat happened
19:30Dinner rush. The payment gateway’s p95 climbs from 1.2 seconds to 11
19:42First ticket: “charged twice for one order”
19:58A restaurant partner calls about identical orders, both already cooked
20:05Hotfix 1 on web: a two-second debounce on the button. Duplicates keep coming
20:25Hotfix 2 in the API: reject an order if the same user placed the same total in the last 60 seconds
20:40Duplicates slow down but don’t stop. A customer ordering a second meal for a flatmate is now blocked
20:52One SQL query splits the duplicates into two groups, and the cause is obvious
21:05Hotfix 2 rolled back. Refunds start

Both hotfixes were guesses about one cause. There were two.

The debounce only helps a customer who taps twice in two seconds. That’s all it does. Hotfix 2 looks sensible and fails in two ways. Two requests 180 ms apart both run the “any recent order?” check before either one inserts. Both see nothing. Both insert. And it can’t tell a duplicate from a real second order, so it blocks paying customers.

The SQL query that split the duplicates in two

At 20:52 somebody stops guessing and asks the database how far apart the duplicate orders are. LAG puts each order next to the previous one with the same user, restaurant and total:

WITH o AS (
    SELECT Id, UserId, PlacedAt,
           LAG(PlacedAt) OVER (PARTITION BY UserId, RestaurantId, Total
                               ORDER BY PlacedAt) AS PrevPlacedAt
    FROM dbo.Orders
    WHERE PlacedAt >= '2026-09-25T14:00:00'   -- 19:30 IST, stored in UTC
)
SELECT b.gap,
       COUNT(*)                                          AS duplicates,
       MIN(DATEDIFF(millisecond, o.PrevPlacedAt, o.PlacedAt)) AS min_ms,
       MAX(DATEDIFF(millisecond, o.PrevPlacedAt, o.PlacedAt)) AS max_ms
FROM o
CROSS APPLY (SELECT CASE WHEN DATEDIFF(millisecond, o.PrevPlacedAt, o.PlacedAt) < 1000
                         THEN 'under 1 second'
                         ELSE '1 to 60 seconds' END) AS b(gap)
WHERE o.PrevPlacedAt IS NOT NULL
  AND DATEDIFF(second, o.PrevPlacedAt, o.PlacedAt) < 60
GROUP BY b.gap;

Two rows come back, and nothing in between:

gapduplicatesmin_msmax_ms
under 1 second13138610
1 to 60 seconds9210,14014,900

The first group is double taps. Under a second apart, mostly Flutter web with a mouse, some Android. The second group starts at 10.1 seconds, and 10 seconds is the app’s request timeout. Those are customers who saw “Something went wrong on our side. Please try again.” and did exactly what it said.

One more query, in Application Insights, confirms the second group. It counts orders the server finished after the app had already given up:

requests
| where timestamp between (datetime(2026-09-25 14:00) .. datetime(2026-09-25 15:30))
| where name == "POST /api/orders" and resultCode == "201"
| summarize created = count(), afterAppGaveUp = countif(duration > 10s),
            p95 = percentile(duration, 95) by bin(timestamp, 10m)

Ninety-two. The same number.

Every one of those afterAppGaveUp orders succeeded. The app told the customer it had failed, the customer tapped again, and the retry succeeded too.

Architecture diagram of the checkout before the fix. A solid frame labelled "One customer, one order they meant to place once" holds the Android and iOS app, with a double tap 180 ms apart, and Flutter web, with a retry after a 10-second timeout. One arrow, POST /api/orders, twice, goes to the web tier: App Service with 3 instances, with a red note that each request gets a fresh order id and nothing says the two are one order. From the web tier, an arrow labelled "charge, twice" goes to a red payment gateway box reading "charged twice", and an arrow labelled "INSERT, twice" goes down to the data tier, Azure SQL Database, dbo.Orders, with a red note: two rows, same user, same cart, same total, both valid. The result, in red: 223 extra orders, 214 customers charged twice, and the kitchen cooked every one of them.

Figure 1 — Friday at 20:10. Two requests for one order, and nothing anywhere that could tell them apart.

The real problem: a retry looked exactly like a new order

The server couldn’t tell “the same order again” from “another order”. Both requests carried the same cart, the same address and the same user. Neither carried anything that said I am the same attempt.

In the reference app, OrderRepositoryImpl.placeOrder asks the data source for a new order ID on every call. Two calls, two IDs, two orders, by design. And in CheckoutBloc, the submit handler is registered with no transformer:

on<CheckoutSubmitted>(_onSubmitted);

flutter_bloc runs events concurrently by default. The button does disable itself while an order is being placed, through canPlaceOrder, but only once the new state has rendered. Two clicks inside that gap both reach _onSubmitted, and both call the API.

So there were three holes lined up:

  • The app sent a second request for a double tap, and again for every retry after a timeout.
  • Nothing in the request said “same attempt”, so the API had no way to know.
  • The database accepted both, because two identical orders are, as far as a table knows, two orders.

Any one of them on its own would have been harmless. All three together, on a slow evening, put the same biryani in two bags.

The slow payment gateway didn’t cause any of this. It only made the timeouts common enough to notice.

The same problem every checkout has

Any system that moves money over a network meets this on day one. A request can fail after the server did the work, and the client can’t tell the difference.

Payment providers solved it first. Stripe, for example, accepts an Idempotency-Key header on every POST, and the IETF has a draft standard for exactly that header. Banks put a unique reference on every transfer for the same reason. When Flipkart or Amazon show “your order is being placed, don’t refresh”, the page is only being polite; the server already refuses to place it twice.

The pattern has a name, and we’ll build it end to end below. If you’d rather watch it first, there’s a one-minute short:

What’s an idempotency key?

An idempotency key is a unique value, usually a UUID, that the client creates once per operation and sends with every attempt at that operation. The server remembers the key with the result of the first attempt. A second request with the same key gets the first result back, and no new work is done.

Five steps with icons, in plain English. 1, a phone: when checkout starts, the app makes one ticket number, a random ID for this order, like a token at a bakery counter, and every retry reuses it. 2, a lightning bolt: Priya taps twice, or the app retries after a timeout, and both requests carry the same ticket number. 3, the App Service icon: your API tries to save the order with that number, maybe on two servers at almost the same moment. 4, the Azure SQL icon: Azure SQL allows only one row per ticket number, so the first save wins and the second is refused with a duplicate key error. 5, a tick: the second request gets the first order back, same order, same charge. A green box at the end reads "One tap, one order, one charge. However many times the request arrives."

In plain English — an idempotency key is a ticket number for one order, and the database only accepts each number once.

“Idempotent” means doing it twice has the same effect as doing it once. GET, PUT and DELETE are idempotent by design: reading twice, setting the same value twice, or deleting twice all leave the system in the same state. POST is not. Two POST /api/orders requests create two orders unless you give the server a way to see they’re one.

Three rules make the key work:

  1. The client creates it, before the first attempt. The server can’t make one, because the server is the side that can’t tell two requests apart.
  2. Every retry reuses it. A double tap, a timeout, a network error: same order, same key.
  3. Only a final answer retires it. A new key only after the order succeeds, or after the server clearly rejects it, like a declined card.

Is disabling the button enough?

No. The button can only stop a second tap on the same screen, and the Friday data shows that was barely more than half of the problem. Everything else reaches the server regardless:

  • a retry after a timeout, where the first request actually succeeded
  • a second browser tab, or the same account on two phones
  • an older version of the app that never had the fix
  • a proxy, a load balancer or an HTTP library that resends a request after a dropped connection (and checkout is never cached at the edge, as the CDN half of the flash sale explains, so every one of those reaches the API)
  • a user who refreshes the confirmation page, and the browser offers to resubmit

The button never sees any of those five.

The client-side fixes are still worth making. They’re the cheap first layer. The server just can’t rely on them.

The fix in the app: droppable() and one key per order

Two changes in CheckoutBloc. First, drop a submit that arrives while one is already running. bloc_concurrency is already a dependency of the app, and droppable() ignores new events until the current handler finishes:

on<CheckoutSubmitted>(_onSubmitted, transformer: droppable());

That closes the double tap, which is the 131 group. Second, give each order a key that survives retries. It’s created when checkout starts, stored in CheckoutState, and sent with every attempt:

// In _onStarted: one key for the order this checkout is about to place.
emit(state.copyWith(orderKey: const Uuid().v4()));

// In _onSubmitted:
final Result<Order> result = await _placeOrder(
  PlaceOrderParams(
    cart: event.cart,
    address: address,
    paymentMethod: state.paymentMethod,
    user: user,
    riderNote: state.riderNote.isEmpty ? null : state.riderNote,
    idempotencyKey: state.orderKey,   // the same key on every retry
  ),
);

result.fold(
  (Failure failure) => emit(
    state.copyWith(
      status: CheckoutStatus.ready,
      errorMessage: failure.message,
      // A timeout is not an answer: the order may already exist, so the next
      // tap must be the same order. Only a rejection earns a fresh key.
      orderKey: failure is ValidationFailure ? const Uuid().v4() : null,
    ),
  ),
  (Order order) => emit(
    state.copyWith(status: CheckoutStatus.placed, placedOrder: order),
  ),
);

The API client sends it as a header, Idempotency-Key: 7f3c9a2e-.... The uuid package is already in pubspec.yaml, so there’s nothing new to install.

The fix in Azure SQL: a unique index decides

The app can now say “same order”. Something on the server has to act on it. It has to hold when two requests arrive at the same moment on two different App Service instances. An if in C# can’t promise that. A unique index can.

It’s the same lesson as the plates counter in the flash sale that hit the database. Redis could say “probably”, but only UPDATE ... WHERE PlatesLeft > 0 could say “yes”. When money depends on a rule, the rule lives in the database.

The key goes on the order row itself, with a hash of what was ordered:

ALTER TABLE dbo.Orders ADD
    IdempotencyKey uniqueidentifier NULL,
    RequestHash    binary(32)       NULL;   -- SHA-256 of restaurant, lines and total

CREATE UNIQUE INDEX UX_Orders_User_IdempotencyKey
    ON dbo.Orders (UserId, IdempotencyKey)
    WHERE IdempotencyKey IS NOT NULL        -- older orders have no key
    WITH (ONLINE = ON);

Two details matter here. The index is scoped to the user, so one customer can never send another customer’s key and get their order back. And it is filtered, so the millions of orders placed before the fix, which have no key, don’t collide on NULL.

When two inserts with the same key race, SQL Server makes the second one wait for the first transaction’s lock on that key. The moment the first commits, the second fails with error 2601, “Can’t insert duplicate key row”. No timing window, no instance count and no retry policy changes that outcome. One key, one row.

The API catches that error and turns it into an answer:

app.MapPost("/api/orders", async (
    [FromHeader(Name = "Idempotency-Key")] Guid? key,
    PlaceOrderRequest request, ClaimsPrincipal user,
    OrderService orders, CancellationToken ct) =>
{
    if (key is null)
        return Results.Problem("Send an Idempotency-Key header.", statusCode: 400);

    return await orders.PlaceAsync(user.GetUserId(), key.Value, request, ct);
}).RequireAuthorization();
public async Task<IResult> PlaceAsync(string userId, Guid key,
                                      PlaceOrderRequest request, CancellationToken ct)
{
    var hash = RequestHash.Of(request);   // SHA-256 over restaurant, lines and total
    Order order;

    try
    {
        // 1. Claim the key. A short transaction: the order and its lines,
        //    status PendingPayment. The unique index is the only judge.
        order = await _orders.InsertPendingAsync(userId, key, hash, request, ct);
    }
    catch (SqlException ex) when (ex.Number is 2601 or 2627)
    {
        // 2. The key is taken, so this is a repeat. Answer it; never redo it.
        var existing = await _orders.GetByKeyAsync(userId, key, ct);

        if (!existing.RequestHash.AsSpan().SequenceEqual(hash))
            return Results.Problem("This Idempotency-Key was used for a different order.",
                                   statusCode: 422);

        if (existing.Status != OrderStatus.PendingPayment)
            return Results.Ok(existing);            // the same order, charged once

        if (existing.CreatedAt > DateTime.UtcNow.AddSeconds(-30))
            return Results.Problem("This order is still being placed.", statusCode: 409);

        order = existing;                           // stuck mid-payment: resume it
    }

    // 3. Charge with the same key, so the gateway de-duplicates on its side too.
    var charge = await _payments.ChargeAsync(order.Id, order.Total, key.ToString(), ct);
    await _orders.MarkPlacedAsync(order.Id, charge.Id, ct);
    return Results.Created($"/api/orders/{order.Id}", order with { Status = OrderStatus.Placed });
}

Error 2627 is the same violation from a UNIQUE constraint rather than a unique index. Catching both means nobody has to remember which one the table uses.

The payment call sits outside the insert transaction on purpose. Holding a database lock while waiting 11 seconds for a slow gateway would make every retry queue behind it. The row is committed as PendingPayment first, so the key is claimed in milliseconds.

UML sequence diagram with five lifelines: the Flutter app holding key 7f3c, App Service instance 1, App Service instance 2, Azure SQL dbo.Orders, and the payment gateway. Step 1, the app sends POST /api/orders with key 7f3c to instance 1. Step 2, the same POST arrives at instance 2, 180 ms later. Step 3, instance 1 inserts the order with key 7f3c as PendingPayment. Step 4, instance 2 inserts with the same key and waits on the key lock. Step 5, Azure SQL returns committed, 1 row, to instance 1. Step 6, it returns error 2601, duplicate key, to instance 2. Step 7, instance 1 charges ₹410 with Idempotency-Key 7f3c. Step 8, the gateway returns charged once. Step 9, instance 1 returns 201 Created, order 1042, to the app. Step 10, instance 2 returns 409, still being placed, for the same order. A green note says the unique index decides, not the instance and not the timing: two requests, one row, one charge.

Figure 2 — the worst case: the same order on two instances at once. The second insert waits for the first, then fails, and no second charge is ever attempted.

What should the API return for a repeated key?

The original result, with nothing done twice. The rest depends on what the first attempt is doing right now:

The key has…StatusThe app does
never been seen201 CreatedShows the order
a finished order, same request200 OK, the saved orderShows the order, exactly as if the first reply had arrived
an order still PendingPayment, under 30 seconds old409 ConflictWaits two seconds and asks again, same key
an order stuck PendingPayment for longerresumes the charge, 201Shows the order
a different cart422 Unprocessable ContentReports a bug. This is never the customer’s fault
no key at all400 Bad RequestOnly old app versions hit this; they get an update prompt

The stuck case is the reason the gateway gets the same key. If the API crashed after charging but before marking the order placed, resuming sends the charge again with the same key, and the gateway returns the first charge instead of taking the money twice.

A declined card is a final answer too. The order is marked PaymentFailed, the app shows the decline, and the next tap starts a new order with a new key.

Flowchart for POST /api/orders. It starts with the request arriving. First decision: does it have an Idempotency-Key header? No leads to a red box, 400 Bad Request, no key, no order. Yes continues to the second decision: does the INSERT with the key succeed? Yes leads to a green box: new order, charge once with the same key, 201 Created. No, error 2601, continues to the third decision: the same request hash as the order already saved? No leads to a red box: 422, the key was reused for a different cart. Yes continues to the fourth decision: still PendingPayment and under 30 seconds old? Yes leads to an amber box: 409 Conflict, still being placed, the app asks again in 2 seconds. No leads to a green box: 200 with the original order, nothing inserted, nothing charged.

Figure 3 — four checks, in order. Only the first INSERT for a key ever creates anything.

Architecture diagram after the fix. A solid frame labelled "The Flutter app: droppable() submit, one key per order" holds the Android, iOS and web app and a key icon for Idempotency-Key 7f3c, kept across retries. An arrow, POST /api/orders with the Idempotency-Key, goes to the web tier, App Service, where the key is required on POST, with a note: no key gives 400, a key already seen is answered with the saved order. An arrow labelled "same key" goes to a green payment gateway box reading "charge once, same key", and an arrow labelled "INSERT, or error 2601 on a repeat" goes down to the data tier, Azure SQL Database, with the note UNIQUE (UserId, IdempotencyKey), the one layer that can't be skipped. The result, in green: one tap, one order, one charge, and 0 duplicates in 41,200 orders the next Friday.

Figure 4 — the checkout after the fix. The app stops most repeats, and Azure SQL stops the rest.

How efficient is the new design?

Correctness stops depending on timing, instance count or client behaviour, and all it costs is one index seek per order. I’d take that trade every time.

Here is where Friday’s 223 duplicates would have ended up with the fix in place:

LayerWhat it catchesFrom Friday’s 223
droppable() in CheckoutBlocA second tap while the first is still runningthe 131 double taps
The same key on a retryA retry after a timeout or a network errorthe 92 timeout retries, answered with the saved order
Unique index in Azure SQLAnything the app misses: two tabs, a resent requestthe backstop for all of the above
Same key at the payment gatewayA charge resent after a crashthe last line, for money

Side by side, for two Friday dinner rushes:

That FridayThe next Friday
Orders38,40041,200
Duplicate orders2230
Customers charged more than once2140
Refundsabout ₹91,000none
Work per order in Azure SQLone insertone insert, with one extra index seek
Extra storagenone48 bytes per order, plus the index

Put simply, duplicates are now zero by construction, whatever the number of taps, retries or instances, because the database allows one row per key. The cost grows with orders, never with retries. A retry is cheaper than an order, in fact: one index seek and one read, no payment call.

When to use an idempotency key, and when not to

Use one on every request that creates something or moves money. Skip it where the operation is already idempotent, and prefer a natural key where the business already has one.

EndpointKey?Why
POST /api/ordersYesCreates an order and takes money
POST /api/orders/{id}/refundYesMoney again, in the other direction
POST /api/partner/menu-itemsYes, cheap insuranceA duplicate dish on a live menu
PUT /api/partner/items/{id}/priceNoSetting ₹129 twice leaves it at ₹129
DELETE /api/cart/lines/{id}NoDeleting twice leaves the same cart
POST /api/orders/{id}/reviewUse the natural keyA unique index on (OrderId, UserId) already means one review per order

Keys stored on the order live as long as the order and cost nothing to keep. If you add a generic IdempotencyKeys table for many endpoints, expire rows after 24 hours; no realistic retry arrives later than that.

Why the obvious fixes were wrong

  • “Disable the button.” It already was. It closes the double tap and nothing else.
  • “Debounce the button for two seconds.” Same as above, with a slower button.
  • “Reject the same total from the same user within 60 seconds.” A check-then-insert race lets both requests through, and it blocks a real second order. You could close the race with UPDLOCK, HOLDLOCK, and you would still be guessing at intent from the cart instead of being told.
  • “Lock in the API.” A lock or SemaphoreSlim holds on one instance. There were three.
  • “Take a Redis lock on the user.” Closer, but a lock that expires isn’t a guarantee, and it isn’t in the same transaction as the insert. The database row is the record, so the rule belongs there.
  • “Increase the timeout.” Fewer retries on a slow evening, but the next network blip brings them back. The retry was never the bug; the missing key was.

The guardrail: one query and one test

With the index in place a duplicate can’t be written, so the query to watch is the one that shows the key doing its job. From Application Insights, per hour:

requests
| where timestamp > ago(1h) and name == "POST /api/orders"
| summarize placed      = countif(resultCode == "201"),
            replayed    = countif(resultCode == "200"),
            stillPlacing = countif(resultCode == "409"),
            keyReused   = countif(resultCode == "422"),
            noKey       = countif(resultCode == "400")

replayed climbing on a slow evening is healthy: those are retries answered without a second order. keyReused above zero pages someone, because it means an app build is reusing keys across different carts. noKey should fall to zero as old app versions age out.

The test that goes into the pipeline fires two requests with one key at the same time and checks the table:

[Fact]
public async Task Two_parallel_posts_with_one_key_create_one_order()
{
    var key = Guid.NewGuid();
    HttpRequestMessage Post() => new(HttpMethod.Post, "/api/orders")
    {
        Headers = { { "Idempotency-Key", key.ToString() } },
        Content = JsonContent.Create(TestCarts.OneBiryani)
    };

    var responses = await Task.WhenAll(_client.SendAsync(Post()), _client.SendAsync(Post()));

    Assert.Single(await _db.OrdersWithKeyAsync(key));
    Assert.Contains(responses, r => r.StatusCode == HttpStatusCode.Created);
}

It runs against a real Azure SQL test database, not an in-memory fake, because the thing under test is the unique index.

System design interview questions from this incident

  1. A user double-clicks “Pay”. How do you guarantee they’re charged once? A client-created idempotency key, reused on retry, enforced by a unique constraint where the order is written, and passed to the payment provider.
  2. Why can’t the server generate the idempotency key? Because the server is the side that can’t tell two requests apart. The key has to come from the side that knows they’re the same attempt.
  3. Two requests with the same key hit two servers at the same millisecond. What happens? The database serialises them on the unique index. One inserts, the other gets a duplicate key error and returns the first result.
  4. The first request is still running when the retry arrives. What do you return? 409 with a short retry, not a second order and not a hang.
  5. How is this different from exactly-once delivery in a message queue? It’s the same idea from the receiving side: you can’t stop duplicates arriving, so you make processing one twice harmless.
  6. When would you not add an idempotency key? On reads, on PUT and DELETE that are already idempotent, and where a natural business key already makes the row unique.

What to do on day one, not after the first refund

  • Put an Idempotency-Key on every endpoint that creates something or moves money, before the first release.
  • Enforce it with a unique index in the database, not with code that checks first.
  • Create the key when the operation starts in the app, keep it across retries, and replace it only on a final answer.
  • Pass the same key to the payment provider.
  • Run a parallel-request test in the pipeline. Duplicates only show up under concurrency.

Key takeaways

  • Disabling the button stops some double taps. It can’t stop retries, tabs or resent requests.
  • An idempotency key tells the server “same attempt”. Only the client can create it.
  • A unique index on (UserId, IdempotencyKey) in Azure SQL is the one check that holds across instances and timing.
  • Return the original result for a repeated key: 200 when done, 409 while running, 422 for a different request.
  • Keep the payment call outside the insert transaction, and give the gateway the same key.

The next Friday

A week later the payment gateway has a slow evening again. Its p95 touches nine seconds at 19:50, and the app’s timeout fires for a few hundred customers.

They tap “Place order” again, as they did last week. Application Insights shows the replayed count climbing: 311 by 21:00. Each of those is a retry that got the original order back.

Duplicate orders that night: zero. The support inbox gets one ticket about a late rider, and nobody from the finance team asks about refunds.

Test yourself · 5 questions

Check what you learned

Answer the questions, then submit to see your score and the explanations. Each question is tagged with the certification exam that covers the skill: DP-300, AI-200, AZ-305.

  1. DP-300 Plan and implement data platform resources

    1. Two requests with the same idempotency key reach two different App Service instances at the same millisecond. What guarantees only one order row is created?
  2. AI-200 Connect to and consume Azure services

    2. Where in the Flutter app should the idempotency key be created?
  3. AI-200 Connect to and consume Azure services

    3. A retry arrives with a known key while the first order is still in PendingPayment, under 30 seconds old. What should the API return?
  4. DP-300 Monitor, configure, and optimize database resources

    4. Why is the unique index on IdempotencyKey created with WHERE IdempotencyKey IS NOT NULL?
  5. AZ-305 Design data storage solutions

    5. Why does the payment gateway call sit outside the insert transaction?
0 of 5 answered

Your result

These are practice questions written from this article, not questions taken from a real exam. Exam tags follow the skills listed in each exam's official study guide on Microsoft Learn.

Was this useful?

Share

Found a mistake or an outdated step? Edit this page on GitHub

Frequently asked questions

How do I prevent duplicate orders when a user double-clicks?
Give each order an idempotency key, a random ID the app creates once per order and sends with every attempt, and add a unique index on that key in the database. A double click, a retry after a timeout or a second tab all send the same key, so the second insert fails and the API returns the order it already created.
What is an idempotency key?
A unique value, usually a UUID, that the client sends in an Idempotency-Key header to say "this is the same request as before". The server stores it with the result of the first request. When the same key arrives again, it returns that stored result instead of doing the work a second time.
Is disabling the submit button enough to stop duplicate orders?
No. It stops a second tap on the same screen, and only after the next frame renders. It does nothing for a retry after a timeout, a second browser tab, an older app version, a proxy that resends the request, or a user who refreshes the page. The server has to reject duplicates itself.
How do I enforce idempotency in Azure SQL or SQL Server?
Store the key on the row you are creating and put a unique index on it, scoped to the user: CREATE UNIQUE INDEX ON dbo.Orders (UserId, IdempotencyKey). A repeated insert fails with error 2601, even when both requests run at the same moment on different servers. Catch that error and return the existing row.
What should an API return when it sees the same idempotency key twice?
The original result, with no new work done: the same order ID and the same body. If the first request is still running, return 409 Conflict so the client retries shortly. If the same key arrives with a different request body, return 422, because the client has a bug.
How long should I keep idempotency keys?
If the key is stored on the order row, keep it as long as the order, which costs nothing extra. If you use a separate idempotency table for many endpoints, 24 hours is common: long enough to cover every realistic retry, short enough to keep the table small.
Article banner. On the left, the eyebrow "Azure, system design" above the title "One hotel, three suppliers, three JSONs" and the lines "Same beach resort in Goa. Three names, prices and shapes.", with the MSDEVBUILD wordmark and the author name below. On the right, three stacked boxes joined by arrows: a grey box reading "Supplier JSON, used as-is: per night or per stay, paise or rupees", an arrow labelled "no canonical model" to an amber box reading "Mapped inside the controller: one if-else block per supplier", and an arrow labelled "launch day" to a red box reading "A ₹212 hotel, listed three times, and a 9-second search".

Next in this series · Part 5 of 7

28 min

One Hotel, Three Suppliers, Three JSON Shapes: Hotel Aggregator System Design

How a hotel aggregator integrates Expedia, Booking.com, Agoda and Trip.com when each returns different JSON: adapters, one model, hotel mapping.

Continue the series
Part 3 of 7The Flash Sale That Ran Out of Bandwidth: When to Use a CDN on Azure

Get new posts by email

New technical articles, Azure AI and GitHub Copilot updates, and upcoming events. No spam, unsubscribe anytime.

Comments

Your turn

How did Suthahar's articles help you?

If something here saved you time or unblocked a real project, I'd love to hear about it. Submissions are reviewed before they appear on the site.

0/1500 · minimum 10 characters

Never published — used only to verify your feedback.

Your name, company, and role appear publicly if published. Nothing else is collected.

↑↓ navigate ↵ open