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

推荐订阅源

J
Java Code Geeks
GbyAI
GbyAI
阮一峰的网络日志
阮一峰的网络日志
Cloudbric
Cloudbric
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
I
Intezer
Simon Willison's Weblog
Simon Willison's Weblog
博客园_首页
The Cloudflare Blog
C
Cisco Blogs
AWS News Blog
AWS News Blog
IT之家
IT之家
Cyberwarzone
Cyberwarzone
罗磊的独立博客
美团技术团队
V
V2EX
Project Zero
Project Zero
A
Arctic Wolf
C
Cyber Attacks, Cyber Crime and Cyber Security
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 聂微东
有赞技术团队
有赞技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
S
Schneier on Security
P
Privacy International News Feed
V
Visual Studio Blog
量子位
T
Tor Project blog
S
Securelist
腾讯CDC
A
About on SuperTechFans
T
Threat Research - Cisco Blogs
G
GRAHAM CLULEY
B
Blog RSS Feed
D
DataBreaches.Net
博客园 - 三生石上(FineUI控件)
B
Blog
NISL@THU
NISL@THU
L
Lohrmann on Cybersecurity
V
Vulnerabilities – Threatpost
人人都是产品经理
人人都是产品经理
博客园 - 【当耐特】
L
LINUX DO - 热门话题
Recorded Future
Recorded Future

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
Stripe Webhook Idempotency in FastAPI: Handling Duplicate Events Without Double-Charging SaaS Customers
Ugur Aslim · 2026-05-31 · via DEV Community

Ugur Aslim

Stripe Webhook Idempotency in FastAPI: Handling Duplicate Events Without Double-Charging SaaS Customers

I learned this lesson the hard way. Three months into CitizenApp's public beta, we had a customer call in furious: they'd been charged twice for the same subscription upgrade. My first instinct was to blame Stripe. My second instinct was smarter—I checked our webhook logs.

The webhook had fired twice, five seconds apart. Both requests succeeded. Both incremented the subscription tier. Both charged the card.

Stripe doesn't guarantee exactly-once delivery—it guarantees at-least-once. That's a contract that explicitly allows duplicates. If you're not handling idempotency, you're building a time bomb in your billing system.

This post shows the exact pattern I implemented to make webhook processing bulletproof: database constraints, idempotency keys, and FastAPI middleware that makes duplicate events mathematically impossible to process twice.

Why Stripe Webhooks Duplicate (And Why It's Your Job to Handle It)

Stripe sends webhooks with retry logic. If your server doesn't respond with HTTP 200 within 25 seconds, Stripe retries. The retries happen at exponentially increasing intervals: 5 minutes, then 30 minutes, then 2 hours, then 5 hours, then 10 hours.

In production, duplicates happen because:

  1. Your server crashes after processing but before responding - you processed the charge, but the response never reached Stripe
  2. Network timeouts - your application server is slow, the connection drops, Stripe sees no 200 and retries
  3. Load balancer flakiness - the request hits two different application instances before either responds

I prefer to assume webhooks will duplicate and design defensively. The alternative—betting your revenue on perfect network conditions—is how startups lose customer trust.

The Database Schema: Making Duplicates Impossible

The key is storing idempotency proof in your database with a unique constraint. Here's what I use in CitizenApp:

from sqlalchemy import Column, String, DateTime, Integer, Boolean, Index
from sqlalchemy.sql import func
import uuid

class WebhookEvent(Base):
    __tablename__ = "webhook_events"

    # Primary: the Stripe event ID itself
    stripe_event_id = Column(String(255), primary_key=True)

    # Idempotency key (same as stripe_event_id, but kept separate for clarity)
    idempotency_key = Column(String(255), unique=True, nullable=False, index=True)

    # Webhook metadata
    event_type = Column(String(100), nullable=False)
    event_data = Column(JSON, nullable=False)  # Store the full event JSON

    # Status tracking
    processed = Column(Boolean, default=False)
    status = Column(String(50), default="pending")  # pending, processed, failed
    error_message = Column(Text, nullable=True)

    # Timing
    created_at = Column(DateTime, server_default=func.now())
    processed_at = Column(DateTime, nullable=True)

    # Metadata for debugging
    attempt_count = Column(Integer, default=1)

    __table_args__ = (
        Index("idx_event_type_processed", "event_type", "processed"),
    )

The magic is idempotency_key with unique=True. If the same event fires twice, the second INSERT will hit this constraint and fail. You catch that failure, check if the first one succeeded, and return 200. Game over.

The FastAPI Handler: Making It Bulletproof

Here's the webhook endpoint that never double-charges:

from fastapi import APIRouter, Request, HTTPException, Depends
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
import json
import logging

router = APIRouter()
logger = logging.getLogger(__name__)

@router.post("/webhooks/stripe")
async def handle_stripe_webhook(
    request: Request,
    db: Session = Depends(get_db)
):
    """
    Handle Stripe webhooks with guaranteed idempotency.
    This endpoint is safe to call multiple times with the same event.
    """

    # 1. Verify the webhook signature (never skip this)
    payload = await request.body()
    signature = request.headers.get("stripe-signature")

    try:
        event = stripe.Webhook.construct_event(
            payload, signature, STRIPE_WEBHOOK_SECRET
        )
    except ValueError as e:
        logger.error(f"Invalid webhook signature: {e}")
        raise HTTPException(status_code=400, detail="Invalid signature")

    event_id = event["id"]
    event_type = event["type"]

    # 2. Check if we've already processed this event
    existing = db.query(WebhookEvent).filter(
        WebhookEvent.stripe_event_id == event_id
    ).first()

    if existing:
        if existing.processed:
            # Already processed successfully—return 200 to make Stripe stop retrying
            logger.info(f"Webhook {event_id} already processed, returning 200")
            return {"status": "already_processed"}

        if existing.status == "failed":
            # Previously failed—decide if you want to retry or skip
            # I prefer to retry failed webhooks on subsequent attempts
            logger.info(f"Webhook {event_id} previously failed, retrying")
            existing.attempt_count += 1
        else:
            # Currently processing—return 200 immediately
            logger.info(f"Webhook {event_id} currently processing")
            return {"status": "processing"}

    # 3. Create a new webhook record with idempotency guarantee
    webhook_record = WebhookEvent(
        stripe_event_id=event_id,
        idempotency_key=event_id,  # Stripe event ID IS the idempotency key
        event_type=event_type,
        event_data=event,
        status="pending"
    )

    try:
        db.add(webhook_record)
        db.commit()
    except IntegrityError:
        # Someone beat us to it (race condition, but safe)
        db.rollback()
        existing = db.query(WebhookEvent).filter(
            WebhookEvent.stripe_event_id == event_id
        ).first()
        if existing and existing.processed:
            return {"status": "already_processed"}
        raise

    # 4. Process the webhook event
    try:
        if event_type == "customer.subscription.updated":
            await handle_subscription_updated(event, db)
        elif event_type == "invoice.payment_succeeded":
            await handle_payment_succeeded(event, db)
        elif event_type == "charge.refunded":
            await handle_refund(event, db)
        else:
            logger.warning(f"Unhandled webhook type: {event_type}")

        # 5. Mark as processed
        webhook_record.processed = True
        webhook_record.status = "processed"
        webhook_record.processed_at = datetime.utcnow()
        db.commit()

        logger.info(f"Webhook {event_id} processed successfully")
        return {"status": "processed"}

    except Exception as e:
        # Mark as failed but don't crash
        logger.error(f"Webhook {event_id} processing failed: {str(e)}", exc_info=True)
        webhook_record.status = "failed"
        webhook_record.error_message = str(e)
        webhook_record.attempt_count += 1
        db.commit()

        # Return 200 anyway—let your monitoring system catch this
        # Returning 5xx will make Stripe retry, which might help
        # But it might also pile up load. I prefer to handle retries manually.
        return {"status": "failed", "error": str(e)}

The Business Logic: Where Idempotency Matters Most

Here's where I make sure the actual charges are idempotent:

async def handle_payment_succeeded(event: dict, db: Session):
    """
    Process a successful payment. 

    Idempotency is enforced at two levels:
    1. WebhookEvent table prevents duplicate processing
    2. Invoice table prevents double-crediting accounts
    """
    invoice_id = event["data"]["object"]["id"]
    customer_id = event["data"]["object"]["customer"]
    amount = event["data"]["object"]["amount_paid"]  # in cents

    # Check if this invoice was already credited
    existing_credit = db.query(AccountCredit).filter(
        AccountCredit.stripe_invoice_id == invoice_id
    ).first()

    if existing_credit:
        logger.info(f"Invoice {invoice_id} already credited")
        return

    # Get the tenant/account
    account = db.query(Account).filter(
        Account.stripe_customer_id == customer_id
    ).first()

    if not account:
        raise ValueError(f"No account found for customer {customer_id}")

    # Create the credit record with a UNIQUE constraint on stripe_invoice_id
    credit = AccountCredit(
        account_id=account.id,
        stripe_invoice_id=invoice_id,
        amount=amount,
        created_at=datetime.utcnow()
    )

    db.add(credit)
    db.commit()  # Will fail if duplicate invoice_id, which is good

    logger.info(f"Credited account {account.id} for invoice {invoice_id}")

The AccountCredit table also has a unique constraint on stripe_invoice_id. This is belt-and-suspenders: even if the WebhookEvent check fails somehow, the database constraint prevents double-crediting.

Gotcha: Race Conditions on First Processing

The code above has a subtle race condition. Between checking if the webhook was processed and actually processing it, another request can slip through.

Fix it with a database-level lock:


python
# Use FOR UPDATE to lock the row during processing
webhook_record = db.