DEV Community

Cover image for The API Bug That Starts With a Double-Click
Jaideep Parashar
Jaideep Parashar

Posted on

The API Bug That Starts With a Double-Click

Imagine you're ordering something online.

You select the product.

Enter your details.

Click Place Order.

Nothing happens.

You wait two seconds.

Still nothing.

So you click again.

Suddenly, two orders appear.

Congratulations. You've just discovered a bug that can exist even when every individual function works perfectly.

And here's the interesting part.

The problem might not be the button, the API, or the database.

It might be the assumption that a request will only happen once.

I think this is one of those software engineering problems that looks incredibly simple until you start building real systems.

We Assume Users Will Behave Perfectly

Consider a basic order API.

@app.post("/orders")
def create_order(order: Order):
save_order(order)
send_confirmation_email(order)
return {"status": "success"}

At first glance, nothing looks particularly unusual.

Receive an order.

Save it.

Send a confirmation.

Return success.

But what happens if the same request arrives twice?

The application might create two orders.

Send two confirmation emails.

And return two perfectly valid success responses.

From the API's perspective, both requests were processed successfully.

From the customer's perspective, something has gone terribly wrong.

The API did exactly what the code instructed it to do.

Unfortunately, that wasn't what the user intended.

The Problem Isn't Always a Double-Click

We can easily blame the user.

"Why did they click twice?"

But that's not a useful engineering explanation.

Duplicate requests can happen for several reasons.

A browser retries an operation.

A mobile application loses connectivity.

A client times out while the server continues processing.

A webhook provider delivers the same event again.

A background worker retries a job after crashing.

An automated workflow repeats an action because it never received confirmation.

The last few examples are particularly interesting.

Imagine an API successfully creates an order, but the network connection drops before the client receives the response.

The client sees a timeout.

But the server already completed the operation.

What should the client do?

Retry?

If it retries blindly, it might create another order.

If it doesn't retry, the user may never receive confirmation.

This is where a simple application starts becoming a distributed-systems problem.

A Timeout Does Not Necessarily Mean Failure

This is an important distinction.

Developers sometimes interpret a timeout as:

"The operation failed."

But a timeout usually tells us something narrower:

"We didn't receive a response within the expected time."

The operation may have failed.

It may still be running.

Or it may have completed successfully.

The client doesn't necessarily know.

For operations that only retrieve information, repeating a request is often relatively straightforward.

But for operations that change something, the consequences can be serious.

Create an order twice.

Charge a customer twice.

Send a notification twice.

Provision a resource twice.

Suddenly, retries aren't merely a reliability feature.

They're a potential source of new failures.

The API Bug That Starts With a Double-Click

This Is Why Idempotency Matters

One of the most useful concepts developers should understand is idempotency.

In simple terms, an operation is idempotent when repeating it has the same intended effect on system state as performing it once.

For example, setting a user's preference to dark_mode = true repeatedly can be idempotent.

But creating a new order every time a request arrives is not.

One common solution is an idempotency key.

Instead of treating every API request as a completely new action, the client gives each logical operation a unique identifier.

For example:

POST /orders
Idempotency-Key: order-abc-123
Content-Type: application/json
{
"product_id": "P101",
"quantity": 1
}
When the server receives the request for the first time, it processes the operation and records the key and outcome.

If the same logical request arrives again with that key, the server can recognize it and return the previous result rather than create another order.

But simply adding a header does nothing unless the server actually implements and enforces this behavior.

The key identifies the operation. The server is responsible for making retries safe.

Here's a Small Python Example

Suppose you're using Python to call an order API.

You could generate a unique identifier for the intended operation:

import uuid
import requests
order_key = str(uuid.uuid4())
payload = {
"product_id": "P101",
"quantity": 1
}
def submit_order():
return requests.post(
"https:// api.example.com/orders",
json=payload,
headers={
"Idempotency-Key": order_key
},
timeout=10
)

Notice one important detail.

The key is generated outside the function.

Calling submit_order() again reuses the same key for that particular order attempt.

If we generated a new key inside the function each time, the server could interpret each retry as a different operation.

Of course, this example assumes the API supports idempotency keys.

For a real application, you'd also need to persist the identifier across relevant client restarts, handle errors, and follow the provider's documented retry rules.

The important idea is to distinguish:

One intended operation from multiple attempts to complete that operation.

Why Disabling the Button Isn't Enough

A common frontend solution is to disable the button after the first click.

That's useful.

It prevents many accidental duplicate submissions.

But it's not a complete reliability strategy.

What if the user refreshes the page?

What if the network client retries?

What if two requests arrive at almost exactly the same time?

What if a background job repeats the operation?

Frontend controls improve the user experience.

They cannot guarantee backend correctness.

For important operations, the server needs a way to recognize and safely handle repeated requests.

And that means thinking beyond the interface.

The Database Has a Role Too

Here's another detail developers sometimes overlook.

Suppose your API checks whether a request has already been processed.

Request A: Does this key exist? No.
Request B: Does this key exist? No.

Request A: Create order.
Request B: Create order.

Both requests arrive almost simultaneously.

Both pass the initial check.

And both create an order.

This is a race condition.

A simple "check before insert" isn't sufficient if concurrent requests can pass the check together.

We need database-backed safeguards, such as a unique constraint on the idempotency key within the relevant customer or account scope, combined with correctly designed transaction handling.

The server also needs to consider what happens when an operation is still in progress or fails halfway through.

For external side effects, such as payment processing, additional coordination with the provider's idempotency mechanism and recovery procedures may be necessary.

Idempotency is not just about remembering a key. It's about coordinating the effect of an operation.

Retrying Faster Can Make an Outage Worse

There's another problem.

Imagine an API becomes temporarily unavailable.

Thousands of clients receive errors.

All of them immediately retry.

The struggling service now receives even more traffic.

More failures occur.

More retries follow.

A temporary problem can become a much larger one.

This is why reliable clients often use techniques such as exponential backoff, jitter, and retry limits.

Instead of retrying immediately and repeatedly, clients wait between attempts, introduce some randomness, and eventually stop.

For HTTP 429 or 503 responses, a server may also provide a Retry-After header indicating when another attempt is appropriate.

But not every error should be retried.

And not every operation is safe to repeat.

The right retry strategy depends on the operation, the provider's contract, and the consequences of duplication.

Sometimes the safest response is to check the existing operation's status before doing anything else.

Five Tests I Would Add Before Shipping

Here's a practical checklist worth considering for APIs that perform important actions.

1. Duplicate submission

Send the same operation twice using the same key.

Verify that only one intended effect occurs.

2. Concurrent requests

Send two matching requests almost simultaneously.

Verify that a race condition doesn't create duplicate results.

3. Lost response

Simulate a completed server operation whose response never reaches the client.

Verify that retrying can recover the outcome safely.

4. Changed request

Reuse an idempotency key with a different payload.

Verify that the API rejects the conflicting operation rather than silently returning an unrelated result.

5. Partial failure

Simulate a crash after one stage of the workflow completes.

Verify that recovery doesn't repeat irreversible actions or lose track of the result.

These tests matter because the most dangerous failures often happen between components.

Not inside the individual functions.

AI Agents Make This Problem Even More Important

Now consider what happens when AI agents begin interacting with APIs.

An agent might:

Create support tickets.

Send emails.

Update customer records.

Submit orders.

Schedule appointments.

Trigger automated workflows.

What happens when an agent doesn't receive confirmation that an action succeeded?

It might try again.

But the original action may already have completed.

This is where traditional software engineering principles become essential to agentic systems.

An intelligent model doesn't eliminate duplicate submissions, race conditions, or transaction failures.

In fact, greater automation can make such problems harder to notice if we don't design the surrounding workflow carefully.

At ReThynk AI, one principle I keep returning to is that we should improve and understand the process before automating it.

I explored that broader idea in Why You Should Fix Your Process Before Implementing AI.

The same philosophy applies here.

Before allowing any automated system to perform an action repeatedly, we need to understand what happens when that action succeeds, fails, or produces an uncertain result.

The Bigger Engineering Lesson

I think we sometimes focus too much on the happy path.

The user clicks once.

The network works.

The server responds.

The database saves the record.

Everything succeeds.

But real software operates in a much less predictable environment.

Users click twice.

Networks fail.

Servers restart.

Messages arrive late.

Requests overlap.

Responses disappear.

And automation repeats actions.

The difference between a demonstration and a reliable system is often how it handles these situations.

Good software isn't just software that works when everything goes right.

It's software that behaves predictably when things go wrong.

One Click Should Mean One Intended Action

The next time you're building an API that creates, updates, sends, charges, or triggers something, I would encourage you to ask a simple question:

"What happens if this exact request arrives twice?"

And then ask an even harder one:

"What happens if the first request succeeds, but nobody receives the response?"

Those questions may reveal more about your application's reliability than another hundred successful happy-path tests.

Because sometimes the most expensive production bug doesn't begin with complicated logic.

It begins with a user clicking the same button twice.

And the system doing exactly what they accidentally asked it to do.

Have you ever encountered duplicate API requests, repeated payments, or webhook retries that caused unexpected behavior? How did you solve it?

Top comments (2)

Collapse
 
jaideepparashar profile image
Jaideep Parashar •

The problem might not be the button, the API, or the database.

Collapse
 
jaideepparashar profile image
Jaideep Parashar •

Its not about building a software, its about building the entire ecosystem.