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

推荐订阅源

云风的 BLOG
云风的 BLOG
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Engineering at Meta
Engineering at Meta
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
小众软件
小众软件
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
月光博客
月光博客
Last Week in AI
Last Week in AI
博客园_首页
I
InfoQ
T
Tailwind CSS Blog
爱范儿
爱范儿
雷峰网
雷峰网
Recent Announcements
Recent Announcements
F
Fortinet All Blogs
B
Blog
WordPress大学
WordPress大学
A
About on SuperTechFans
V
Visual Studio Blog
有赞技术团队
有赞技术团队
P
Proofpoint News Feed

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
What is a database transaction, and when do you reach for...
Hassan Farooq · 2026-06-23 · via DEV Community
Cover image for What is a database transaction, and when do you reach for one in Rails?

Hassan Farooq

A transaction groups several database writes into one atomic unit. Either all of them commit, or none of them do. That is the guarantee you are buying: you never end up with half the work done and a database that contradicts itself.

People recite the full ACID list (atomicity, consistency, isolation, durability), but the property I actually reach for day to day is atomicity. All or nothing.

A real scenario: checkout

Placing an order looks like one action to the user, but under the hood it is several writes that all have to agree with each other.

Order.transaction do
  order = user.orders.create!(status: "pending")
  cart.items.each do |item|
    order.line_items.create!(product: item.product, quantity: item.quantity)
    item.product.decrement!(:stock, item.quantity)
  end
end

Say the line items save fine but the stock decrement blows up halfway through the loop. Without a transaction I now have an order that sold three units of something while only deducting one from inventory. With the transaction, the exception rolls the whole block back and I am left in a clean state, as if the order never happened.

Gotchas I watch for

Rollback only fires on a raised exception. This is the one that bites people. create returns false on a validation failure, it does not raise, so the transaction happily commits everything else around it. Use the bang versions inside the block (create!, save!, update!) so a failure actually throws and triggers the rollback.

Don't rescue the exception inside the block. If you wrap the body in a begin/rescue and swallow the error, you have also swallowed the signal that tells the transaction to roll back, so it commits anyway. If you genuinely need to abort without an exception bubbling up to your callers, raise ActiveRecord::Rollback. It rolls back quietly and does not re-raise.

Keep slow external calls out of the transaction. An open transaction holds locks on the rows you have touched. If you put a Stripe charge or any HTTP request inside the block, you are holding those locks for the length of a network round trip. Under load that is how you get lock contention and a drained connection pool.

Why the Stripe charge specifically is risky

There are two problems. The first is the lock-holding one above. The second is worse: a charge is an external side effect, and you cannot roll it back. If the transaction commits and something downstream fails, or the transaction rolls back after Stripe already charged the card, your database and Stripe now disagree, and nothing reconciles that for you.

The pattern I use is to do the local database work inside the transaction and handle the charge outside it. Confirm the payment through webhooks and reconcile against them, so a retry never double-charges the customer.