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

推荐订阅源

J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
B
Blog RSS Feed
C
Check Point Blog
D
Docker
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
MongoDB | Blog
MongoDB | Blog
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
量子位
有赞技术团队
有赞技术团队
IT之家
IT之家
大猫的无限游戏
大猫的无限游戏
D
DataBreaches.Net
M
MIT News - Artificial intelligence
B
Blog
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
腾讯CDC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
V2EX
月光博客
月光博客

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
Building a Payment Processor: Moving Payments to the Back...
Oreoluwa Bim · 2026-05-08 · via DEV Community

My first attempt at a payment processor was synchronous and dangerous. If anything timed out or failed mid-way, I ended up with inconsistent data or double charges.

To fix it, I had to stop trying to do everything inside the HTTP request. I moved to a model where the API just records the intent to pay, and a separate worker handles the actual execution.

Step 1: Idempotency (The "Don't Double Charge" Fix)

The first thing I needed was an Idempotency-Key. It’s just a unique string from the client. If I see the same key twice, I return the existing result instead of starting a new process.

I added a unique index to my payments table and updated the handler to check for it first:

idemKey := r.Header.Get("Idempotency-Key")
existing, err := s.store.GetPaymentByIdempotency(ctx, idemKey)
if err == nil {
    // We've seen this before, just return the result
    writeJSON(w, http.StatusOK, existing)
    return
}

Enter fullscreen mode Exit fullscreen mode

Now, retries from the client are safe.

Step 2: The Outbox Pattern and RabbitMQ

I decided to use a background worker to handle the actual provider call. But this introduced a new problem: what if I save the payment to the database, but my server crashes before it can send the message to RabbitMQ? The payment would stay "pending" forever.

This is where the Outbox Pattern comes in. Instead of publishing to RabbitMQ directly, I save the payment and a "message to be sent" into an outbox table in the same database transaction.

tx, _ := s.db.Begin()

// 1. Save payment as pending
payment, _ := qtx.CreatePayment(ctx, params)

// 2. Save the intent to the outbox table
qtx.CreateOutboxEvent(ctx, outboxParams)

tx.Commit()

Enter fullscreen mode Exit fullscreen mode

Since they are in the same transaction, either both are saved or neither is. A separate background process then reads from the outbox and publishes to RabbitMQ. If the publish succeeds, it marks the outbox row as sent.

The client gets a 202 Accepted immediately. They can poll a GET endpoint later to see if it’s finished. This frees up my API and prevents holding connections open while waiting for slow providers.

Step 3: Handling Provider Failures

Payment providers fail. A lot. My mock provider is actually set to fail 50% of the time just to make sure my retry logic actually works.

When the worker picks up a message and the provider fails, I don't want to just give up. I implemented a simple retry poller with backoff. If a charge fails, I update the DB with a next_retry_at timestamp. A background process sweeps the DB every few seconds and re-queues anything that's ready for another shot.

The New State Machine

The flow looks more like this now:
pendingprocessingcompleted OR failed (which triggers a retry).

By moving to this async model, I’ve solved the timeout issues. Even if the client disconnects, the worker keeps going. If the worker crashes, the outbox or the retry poller eventually catches it.

But there's still a catch. What happens if the worker crashes exactly after charging the user but before updating the database? That's the final 1% of failures I'll tackle in the last post.

The code for this version is at github.com/oreoluwa-bs/dinero/tree/resilient-approach.