theboreddev.com

Menu
  • Home
  • Career
  • Code Habits
  • Debugging
  • Side Projects
  • Tooling
  • About Us
  • Contact Us
  • Disclaimer
Menu

Month: September 2026

Guide on how to make a retry safe.

A Retry Without Idempotency Is a Duplicate

Posted on September 3, 2026November 7, 2026 by Tomasz Wierzbicki

I remember sitting in my kitchen at 3 AM, watching a dashboard turn a violent shade of red while my service essentially performed a self-inflicted DDoS attack on our own database. I had implemented what the documentation called “robust error handling,” but in reality, I had just built a high-speed engine for failure. I thought I was being proactive, but I hadn’t actually understood how to make a retry safe; I had just made the system faster at crashing. Most people think retries are a free lunch provided by your library, but if you don’t account for idempotency and jitter, you’re just adding fuel to the fire.

I’m not here to sell you on some complex distributed consensus algorithm or a fancy new service mesh feature. I want to talk about the actual mechanics of what prevents a transient network hiccup from turning into a total system meltdown. I’ll walk you through the specific patterns I’ve used to keep things stable—from idempotency keys to exponential backoff—based on the mistakes I’ve actually made in production. This isn’t a theoretical lecture; it’s a set of practical guardrails so you don’t have to wake up to a pager alert at three in the morning.

Table of Contents

  • Network Error Handling Patterns That Kill Your Database
  • Why a Simple Loop Isnt Enough for Distributed Systems Fault Tolerance
  • Five things I stopped doing to keep my services from eating themselves
  • The "Don't Make It Worse" Checklist
  • The Long View on Retries
  • Frequently Asked Questions

Network Error Handling Patterns That Kill Your Database

Network Error Handling Patterns That Kill Your Database

The most common way I’ve seen a system commit suicide is through the “thundering herd” problem. You have a momentary network hiccup, a few requests time out, and suddenly every single one of your microservices decides to retry at the exact same millisecond. Without an exponential backoff strategy combined with some decent jitter in retry logic, you aren’t just recovering from a glitch; you are effectively launching a self-inflicted DDoS attack against your own database. I remember a stint at a logistics firm where a minor connection blip turned into a three-hour outage because our retry loops were too synchronized, keeping the database CPU pinned at 100% as it struggled to clear the backlog.

It’s not just about the volume of requests, though; it’s about what those requests actually do. If your network error handling patterns don’t account for the state of the transaction, you end up with a mess. You might receive a timeout error, but on the server side, the write actually succeeded. If you blindly retry that operation without a robust idempotency key implementation, you’re just inviting duplicate transactions into your ledger. In a payments environment, that’s not just a bug—it’s a legal headache. You have to assume that a timeout means nothing about the finality of the operation.

Why a Simple Loop Isnt Enough for Distributed Systems Fault Tolerance

Why a Simple Loop Isnt Enough for Distributed Systems Fault Tolerance

The problem with a `for` loop or a `while` loop wrapped around an API call is that it assumes the failure happened on your end. In a distributed system, that’s rarely the case. Most of the time, the request actually reached the server, the server processed it, and then the connection dropped before you could receive the “OK.” If you just loop and try again, you aren’t just being resilient; you are actively creating duplicate data. I once spent a weekend untangling a mess where a simple retry loop in a shipping service ended up triggering three separate warehouse pick orders for a single customer.

To move beyond a naive loop, you have to accept that “failure” is an ambiguous state. You need a formal idempotency key implementation so the downstream service knows that your second, third, or tenth attempt is actually the same intent as the first. Without this, you’re just gambling with your database integrity.

Furthermore, if a service goes down, every single one of your microservices will likely start retrying at the exact same millisecond. If they all use a fixed interval, you’ve just built a self-inflicted DDoS attack. You need an exponential backoff strategy paired with jitter in retry logic to spread those requests out. It’s the difference between a controlled recovery and a thundering herd that keeps the system in a permanent state of failure.

Five things I stopped doing to keep my services from eating themselves

  • Make everything idempotent, or don’t bother retrying. If your retry logic hits a “Create Order” endpoint twice because the first response timed out, you better have a unique idempotency key in the header. Otherwise, you aren’t building a resilient system; you’re just building a way to double-charge customers.
  • Stop using fixed intervals for your retries. If a service is struggling, having a thousand clients all retrying every exactly 500ms is just a coordinated DDoS attack against your own infrastructure. You need jitter—actual randomness—to break up those synchronized waves of traffic.
  • Implement exponential backoff, but actually cap it. There is no point in waiting 40 minutes between attempts if your timeout threshold is 30 seconds. I’ve seen too many systems waste resources attempting to reach a service that has clearly been dead for an hour.
  • Distinguish between “retriable” and “fatal” errors. If you get a 400 Bad Request or a 401 Unauthorized, retrying is just a waste of CPU cycles and log space. You only retry the things that actually have a chance of succeeding on the second try, like a 503 or a network timeout.
  • Use a circuit breaker to stop the bleeding. If a downstream dependency is failing consistently, your retry logic should eventually give up and trip a breaker. It’s better to fail fast and return an error to the user than to keep hammering a dead service and tying up all your own worker threads in the process.

The "Don't Make It Worse" Checklist

Idempotency isn’t a luxury; it’s the baseline. If your retry logic can’t distinguish between “the request failed to reach the server” and “the server processed it but the ACK died on the wire,” you are essentially building a machine designed to double-charge customers.

Stop treating every error as a reason to try again. If the error is a 400-series client error or a “database connection refused,” retrying immediately is just a way to turn a minor hiccup into a self-inflicted DDoS attack against your own infrastructure.

Exponential backoff and jitter are your only defense against the “thundering herd.” Without them, when your service recovers from a momentary hiccup, every single waiting client will hit it at the exact same millisecond, knocking it right back down.

The Long View on Retries

The Long View on Retries concept.

At the end of the day, making a retry safe isn’t about picking the prettiest library or the latest middleware. It’s about realizing that every retry you trigger is a tax on your downstream systems. If you aren’t using idempotency keys, you’re essentially playing Russian roulette with your database state. If you aren’t using exponential backoff with jitter, you’re just building a distributed denial-of-service attack against your own infrastructure. I’ve spent enough nights staring at Grafana dashboards to know that a “simple fix” like adding a loop often turns a minor hiccup into a total system collapse.

Don’t aim for perfect code; aim for predictable failure. We are never going to build systems that don’t break, so our job is to make sure that when they do, they fail in a way that doesn’t require a frantic, all-hands-on-deck incident bridge. Build your retries with the assumption that the network is lying to you and your database is already tired. If you can write your logic so that a thousand repeated attempts result in the same state as a single successful one, you’ve already won half the battle. Write it for the person who has to fix it at 2 AM—and hopefully, that person is you, having had a full night’s sleep.

Frequently Asked Questions

How do I actually implement idempotency keys without adding massive overhead to my database schema?

Don’t start by adding a column to every single table in your schema. That’s how you end up with a maintenance nightmare. Instead, I usually treat idempotency as a sidecar concern. Use a dedicated, TTL-indexed table or a fast key-value store like Redis to track the `idempotency_key` and its associated response. You store the key, the status, and the result of the first successful execution. If the same key hits again, you just replay the cached response. It keeps your domain models clean and your database from bloating.

At what point does adding a jitter to my backoff strategy stop being helpful and just become more complexity I have to maintain?

If you’re still manually tuning a single microservice, jitter is probably overkill. But the moment you have two or more services talking to the same shared resource—a database, a legacy API, or a message queue—jitter becomes mandatory. It stops being “extra complexity” and becomes “insurance against a thundering herd.” I’d rather manage a few extra lines of math than spend my weekend debugging a synchronized retry storm that keeps knocking our DB offline.

If I'm using a message queue like RabbitMQ or Kafka, how do I handle retries without accidentally creating an infinite loop of poison pills?

The trick is to stop treating every failure like it’s worth a second chance. If a message fails, don’t just put it back at the head of the queue; you’ll just create a spinning loop that eats your CPU and logs. I usually implement a “retry count” in the message header. Once it hits a threshold—say, three tries—you move it to a Dead Letter Exchange. It’s better to let the message die in a separate queue where we can actually look at it, rather than letting it choke the main pipeline.

How do I distinguish between a transient network hiccup that deserves a retry and a permanent logic error that will just fail every single time?

The easiest way to tell is by looking at the error code, but don’t trust it blindly. A `503 Service Unavailable` is usually a signal to back off and try again later. A `400 Bad Request` or a `403 Forbidden` is a dead end; retrying those is just wasting CPU cycles and flooding your logs with noise. If the error is about the state of the connection, retry. If it’s about the content of the payload, stop.

Guide on how to write idempotent code.

Safe to Run Twice

Posted on September 1, 2026November 7, 2026 by Tomasz Wierzbicki

I still remember the sound of my phone buzzing on the nightstand at 3:14 AM during my time at the logistics startup. It wasn’t a high-level architectural debate that woke me up; it was a frantic Slack alert about a retry loop that had just turned a single delayed webhook into ten thousand duplicate shipping orders. Most tutorials on how to write idempotent code treat it like a theoretical math problem or a fancy pattern you add to your microservices to look smart. But in the real world, idempotency isn’t about elegance—it’s about preventing a total system meltdown when the network inevitably decides to flake out right when you’re trying to sleep.

I’m not going to waste your time with academic definitions or complex distributed locking abstractions that will only break in a different, more expensive way. Instead, I want to walk through the actual patterns I’ve used to keep databases sane and customers happy. I’ll show you the trade-offs of using idempotency keys versus state checks, and more importantly, I’ll tell you where these implementations usually fail in production. My goal is to give you a set of practical tools so that the next time a retry hits your endpoint, your system just shrugs and moves on.

Table of Contents

  • Handling Duplicate Requests in Apis Before They Escalate
  • Ensuring Request Safety in Microservices During Network Partitions
  • Five things I’ve learned from watching retries go wrong
  • Lessons from the post-mortem
  • The Bottom Line
  • Frequently Asked Questions

Handling Duplicate Requests in Apis Before They Escalate

Handling Duplicate Requests in Apis Before They Escalate.

The most common way this goes wrong is by assuming the network is reliable. It isn’t. A client sends a POST request to charge a customer, the server processes it successfully, but then the connection drops before the client gets the `200 OK`. The client, being a well-behaved piece of software, retries. Without a strategy for handling duplicate requests in APIs, you’ve just charged that customer twice. I’ve seen this happen in payment gateways where the retry logic was too aggressive and the backend was too trusting.

The standard way to stop this is through a solid idempotency key implementation. Instead of just blindly processing every incoming request, you require the client to send a unique identifier—usually a UUID—in the header. On the server side, you check if that key has been seen before within a certain window. If it has, you don’t run the business logic again; you simply return the cached response from the first successful attempt.

The trick is making sure this check is actually safe. If you check the key, then run the logic, then save the result, you’ve created a race condition. To do this right, you need to wrap the key check and the actual operation within a single unit of work to maintain database transaction atomicity. If you can’t guarantee that the “check” and the “act” happen as one inseparable event, you’re just waiting for a race condition to ruin your weekend.

Ensuring Request Safety in Microservices During Network Partitions

Ensuring Request Safety in Microservices During Network Partitions

In a microservices architecture, the network is essentially a collection of lies. A service might successfully process a request, but the acknowledgment gets swallowed by a network partition or a sudden pod restart. From the perspective of the caller, that request failed. If the caller follows standard retry logic best practices and tries again, you’re suddenly dealing with a duplicate execution. Without a way to recognize that this is the same intent as the first attempt, you risk double-billing a customer or creating duplicate shipping orders.

I’ve seen this go sideways when teams assume that a simple “check if exists” query is enough. In a distributed system, that check and the subsequent write aren’t naturally a single unit of work. To actually achieve ensuring request safety in microservices, you have to tie the idempotency key directly to your persistence layer. This usually means using a unique constraint on an idempotency key within a single database transaction atomicity block. If the second request hits the database while the first is still committing, the database itself becomes your source of truth, rejecting the duplicate before any side effects can leak out. It’s not the most elegant way to write code, but it’s the only way that keeps me sleeping through the night.

Five things I’ve learned from watching retries go wrong

  • Stop relying on the client to be well-behaved. I used to think a well-designed API would only send a request once, but networks are messy and developers get frustrated. You have to assume the client will hit that ‘Submit’ button five times in a row because the UI didn’t show a loading spinner fast enough.
  • Use a unique idempotency key, but don’t just make it a random UUID. I’ve seen cases where the key was generated on the client side, but if the client crashed and restarted, it generated a new key for the same logical action. The key needs to be tied to the actual intent of the operation, not just the lifecycle of a single HTTP request.
  • Database constraints are your last line of defense, not an afterthought. I once spent an entire afternoon debugging a race condition where two identical requests passed the application-level checks but both hit the database at the same millisecond. A unique constraint on your idempotency key column is the only thing that actually sleeps at night.
  • Your response must be consistent, even if the work is already done. If a request comes in for an operation that succeeded ten minutes ago, don’t return a 409 Conflict or an error. Return the same 200 OK (or whatever your success code is) and the same payload you sent the first time. If the client thinks it failed, it’s just going to keep hammering you.
  • Be careful with side effects that happen outside your primary transaction. If you update a row in Postgres but then try to send a Slack notification or a webhook, and that second part fails, you’re in a weird state. I’ve learned to move those side effects into an outbox pattern so the entire operation—the data change and the notification—is treated as a single, idempotent unit.

Lessons from the post-mortem

Idempotency isn’t a “nice-to-have” feature for your API; it’s the only thing standing between a transient network hiccup and a customer being charged three times for the same order.

Stop trying to build perfect distributed systems and start building systems that can fail gracefully; if a retry is going to happen, make sure the second attempt is as boring as the first.

Always design with the assumption that the client is going to retry, the network is going to drop the packet, and your database is going to be under heavy load—if your logic can’t survive that combination, it’s not production-ready.

The Bottom Line

The Bottom Line: building resilient systems.

At the end of the day, idempotency isn’t some academic concept you study to pass a system design interview; it is a practical defense mechanism. We’ve looked at how to catch duplicate API requests before they hit your business logic and how to keep your microservices from spiraling when the network inevitably decides to stop cooperating. Whether you are using unique idempotency keys in your database or implementing state checks to ensure a transition only happens once, the goal is the same: making sure a single retry doesn’t turn into a catastrophic duplicate transaction. It is about building systems that are resilient to the chaos of the real world, rather than assuming the world will always behave perfectly.

I know it feels like extra work. It’s tempting to skip the state checks and the key validation when you’re racing to hit a sprint deadline. But I’ve spent enough late nights staring at a terminal to know that the time you “save” now is usually paid back with interest during a production incident. Writing idempotent code is an investment in your own future sleep. Don’t just write code that works when things are perfect; write code that knows how to fail gracefully when things go wrong. Your future self—and whoever inherits your codebase after you—will thank you for it.

Frequently Asked Questions

How do I handle idempotency when the operation involves multiple database writes that aren't wrapped in a single transaction?

This is where things usually fall apart. If you can’t wrap everything in a single ACID transaction, you have to stop thinking about “all or nothing” and start thinking about “eventual consistency.” I usually reach for an outbox pattern or a state machine. You record your intent in a single table first, then move through the steps. If the process dies halfway through, your background worker looks at the state and knows exactly where to pick up.

At what point does storing idempotency keys become a storage bottleneck or a performance drag on the database?

It becomes a problem when your key-store grows faster than your cleanup strategy can handle. If you’re throwing every single request into a relational table without a TTL or a compaction strategy, you’ll eventually see latency spike during index lookups. I’ve seen it happen: the DB spends more time managing the index for these keys than actually serving the business logic. Use a fast, TTL-backed KV store like Redis for the keys, not your primary source of truth.

How do I deal with "partial success" scenarios where the side effect happened but the response never reached the client?

This is where the “ghost side effect” problem lives. The database updated, but the network died before the client got the `200 OK`. If the client retries without a unique idempotency key, you’re double-charging or double-shipping. I’ve learned you can’t just rely on the response; you have to make the client send a client-generated UUID with every intent. If the server sees that same UUID again, it shouldn’t re-run the logic—it should just return the cached success.

Is there a way to implement this without forcing every single developer on the team to manually check for keys in every service?

You don’t want to play that game. If you make every dev manually check for keys, someone will forget, and that’s when the double-billing happens.

  • Previous
  • 1
  • 2
  • 3

Recent Posts

  • The Signs You Will Ignore Until You Cannot
  • Crash Early Rather Than Corrupt Quietly
  • A Deadline Needs a Witness
  • Where the Evenings Actually Went
  • Teaching Yourself Without a Syllabus
  • Read Both Sides Before You Pick One

Categories

  • Career (44)
  • Code Habits (45)
  • Debugging (43)
  • Side Projects (45)
  • Tooling (43)

Archives

  • November 2026
  • October 2026
  • September 2026
  • August 2026
  • July 2026
  • June 2026
  • May 2026
  • April 2026
  • March 2026
  • February 2026
  • January 2026
© 2026 theboreddev.com | Powered by Minimalist Blog WordPress Theme