惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy International News Feed
Simon Willison's Weblog
Simon Willison's Weblog
I
Intezer
Spread Privacy
Spread Privacy
The Hacker News
The Hacker News
P
Palo Alto Networks Blog
TaoSecurity Blog
TaoSecurity Blog
S
Secure Thoughts
Google Online Security Blog
Google Online Security Blog
H
Heimdal Security Blog
N
News | PayPal Newsroom
Attack and Defense Labs
Attack and Defense Labs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
博客园 - 【当耐特】
Webroot Blog
Webroot Blog
小众软件
小众软件
Help Net Security
Help Net Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
N
News and Events Feed by Topic
Hacker News - Newest:
Hacker News - Newest: "LLM"
PCI Perspectives
PCI Perspectives
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Cloudflare Blog
Cloudbric
Cloudbric
AI
AI
WordPress大学
WordPress大学
博客园 - 聂微东
Jina AI
Jina AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 三生石上(FineUI控件)
Hacker News: Ask HN
Hacker News: Ask HN
H
Hacker News: Front Page
博客园 - Franky
V
V2EX
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
S
SegmentFault 最新的问题
有赞技术团队
有赞技术团队
H
Help Net Security
量子位
S
Security @ Cisco Blogs
大猫的无限游戏
大猫的无限游戏
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recorded Future
Recorded Future
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
J
Java Code Geeks
C
Cisco Blogs
S
Security Affairs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Retrying HTTP Requests in Go Without Making It Worse
Krishan Kuma · 2026-05-27 · via DEV Community

When you call an external API, things go fine until they don't. A network blip, a server restart, a rate limit. So you add a retry, and most of the time it helps. The problem is that the obvious retry, the one we all write first, can quietly make things worse: it can resend a payment twice, or keep a struggling server down longer than the original failure would have.

In this post we'll build a retry client in Go from the naive version up, fix each thing that bites, and end somewhere a little uncomfortable: telling you to use a library instead. By the end you'll understand exactly what that library is doing, which is the real reason to read this.

The retry everyone writes first

Three tries, wait a second, give up. It looks reasonable, and there are three problems hiding in it.

First, the body. An HTTP client reads the request body to the end when it sends it, and it doesn't rewind. So on the second attempt there's nothing left to send, the server gets an empty POST, and it returns 400. Now you're retrying a 400 that you caused.

Second, the wait is the same for everyone. When a server starts returning 503s, every client retries on the same one-second tick, together, over and over. You haven't given it room to recover. You've lined everyone up to hit it again at the same moment. This is the thundering herd.

Third, you're retrying everything. A 400 means your request is wrong. A 404 means the thing isn't there. No amount of retrying changes either, but this loop treats every failure the same.

Three problems, and they don't get fixed in the same place. Let's take them one at a time.

Backoff: don't retry in lockstep

The wait between attempts should grow, and it shouldn't be identical for every client. Growing is exponential backoff. Not-identical is jitter. You want both.

Two details here are worth slowing down on, because they're the ones people get wrong.

I used a left shift instead of math.Pow(2, attempt). Floats are imprecise for this, and Base * 2^attempt overflows an int64 of nanoseconds sooner than you'd expect, which can wrap a careful 800ms wait into a negative number. Shifting integers and capping early avoids all of it.

And jitter is a wrapper, not a second copy of the exponential math. The tempting move is to write a separate ExponentialBackoffWithJitter type and duplicate the doubling inside it. Then your linear and constant strategies don't get jitter, and you've got the same logic in two places. Wrapping any Backoff keeps it in one place. One more thing: this is full jitter, random(0, d), not the wait give or take 25 percent, and the difference is the whole point. If every client jitters in a narrow band around the same target, they stay bunched together, just a slightly wider bunch. Picking uniformly across the entire [0, d) window is what actually scatters them. If you want the simulations behind that, AWS's Exponential Backoff and Jitter post has the graphs.

Make sleep mockable, and make it respect context

Here's a practical problem you hit the moment you write a test. If the test actually sleeps through exponential backoff, it actually takes seconds, and a suite full of them crawls.

So don't call time.Sleep directly. Put it behind an interface, and while you're there, make it cancellable.

That select on ctx.Done() is the part most hand-rolled retry loops miss. They check the context once at the top of the loop, then block on a plain time.Sleep for ten seconds. If the request is cancelled during that wait, nothing happens until the sleep ends. With the timer-and-context version, a cancelled request stops right away. On a deploy, that's the difference between a clean shutdown and a thirty-second hang.

The client, where everything comes together

Let's walk through the decisions, because they're the whole point.

We buffer the body once, up front, and only when it's a raw stream. Requests built with http.NewRequest from a bytes.Reader or a string already carry GetBody, so we reuse it instead of reading anything. We also don't mutate the request you passed in. (This does read the whole body into memory, so if you're streaming a very large upload, know that retries and streaming pull in opposite directions, and pick one on purpose.)

The default policy won't retry your POST, and this is the one I'd most want you to take away. A POST that timed out may have already succeeded on the server before the response got lost on the way back. Retry it blindly and you've charged the customer twice. So GET, HEAD, PUT and the other safe-to-repeat methods retry by default, and POST doesn't unless you opt in with an idempotency key. The policy gets the request so it can actually make that distinction.

Retry-After is respected and capped. If a server says wait two seconds, we wait two seconds. If a misconfigured server says wait 86400, we don't park the goroutine for a day. We also handle the HTTP-date form of the header, not just delta-seconds, since the spec allows both and the date form is the one that usually gets forgotten.

And when we finally give up, we hand back the last response with its body still open, plus an error. An earlier version of mine closed that body before returning it, which left the caller holding a response it couldn't read. Close it yourself and check the status if you want to know why we stopped.

Now the tests run in microseconds

Because the sleeper is mocked, we can assert the exact backoff schedule, prove Retry-After overrides the backoff, prove a cancelled context stops immediately, and prove a POST is left alone. None of it waits on a real clock. That last test, the one that pins the POST behaviour, is the one I'd be most nervous shipping without.

You probably shouldn't use any of this

Here's the uncomfortable turn. For real work, reach for a library. go-retryablehttp buffers bodies, respects Retry-After, does exponential backoff with jitter, and is wired into Terraform and Vault, so it has survived far more abuse than anything you or I will write this week. If you want a full HTTP client with a chainable API and JSON handling on top, resty has retries built in.

So why build it at all? Because now you can open that library's source and read it as a set of decisions instead of magic: why it buffers, why it clones the request, why its default policy is careful about methods. The day it does something surprising, you're debugging a thing you understand. That was the deliverable all along. Not the code, the understanding.

What actually bites people

A few things that aren't obvious until they catch you.

Idempotency is the big one. Retrying is safe right up until the operation has a side effect, and then it isn't. Make the operation idempotent, send an idempotency key, or don't retry it. There's no fourth choice that ends well.

Logging is the quiet one. The instinct is to log the full request and response on every retry, and then your logs fill with duplicated payloads, some of them carrying tokens. Log the attempt number, the status, and the endpoint. Not the body.

Timeouts catch people who think retries replace them. They don't. The HTTP client timeout is per attempt, and your overall deadline belongs in the context. Those are two different clocks, and you want both, or one slow call holds your whole retry loop hostage.

And the one worth saying out loud: retries are most dangerous in a chain. If service A retries B three times, and B retries C three times, a small hiccup in C arrives at C as nine times the load. Stack a few layers and you get a retry storm that keeps a system down well after the original cause is gone. The fix is a retry budget: cap retries to a small fraction of your request rate so a bad minute can't multiply into an outage. Single-server jitter handles the herd. A budget handles the chain. Real systems need both.

The full implementation is in the gist above. Clone it, run the tests, then break something and watch what the tests tell you. That's how it stuck for me, and how it'll stick for you. Happy coding.