[{"data":1,"prerenderedAt":1221},["ShallowReactive",2],{"\u002Fblog\u002Fdatabase-race-conditions-coupon-system-rails":3},{"path":4,"data":5,"meta":17,"nodes":51},"\u002Fblog\u002Fdatabase-race-conditions-coupon-system-rails",{"title":6,"description":7,"date":8,"tags":9,"authors":11,"image":13,"seo":14},"How to Prevent Database Race Conditions in a Rails Coupon System","Learn how to avoid 5 common database traps when building a coupon system","2026-02-17",[10],"engineering",[12],"Ali Fadel","\u002Fimages\u002Fblog\u002Fdatabase-race-conditions-coupon-system-rails.webp",{"title":15,"description":16},"Solving Database Race Conditions in a Coupon System | Rails Guide","Learn how to avoid 5 common database traps when building a coupon system, including race conditions, write skew, and atomicity issues in Ruby on Rails.",{"toc":18,"key":43,"source":44,"stem":45,"extension":46,"kind":47,"type":48,"partial":49,"hash":50},{"title":19,"searchDepth":20,"depth":20,"links":21},"",2,[22,25,28,31,34,37,40],{"id":23,"depth":20,"text":24},"the-setup","The Setup",{"id":26,"depth":20,"text":27},"_1-the-double-redemption-race-toctou","1. The Double Redemption Race (TOCTOU)",{"id":29,"depth":20,"text":30},"_2-the-coupon-stacking-problem-and-write-skew","2. The Coupon Stacking Problem and Write Skew",{"id":32,"depth":20,"text":33},"_3-the-cascading-delete-trap","3. The Cascading Delete Trap",{"id":35,"depth":20,"text":36},"_4-the-case-sensitivity-trap","4. The Case Sensitivity Trap",{"id":38,"depth":20,"text":39},"_5-the-half-created-bill","5. The Half-Created Bill",{"id":41,"depth":20,"text":42},"the-pattern","The Pattern","blog\u002Fdatabase-race-conditions-coupon-system-rails.md","blog","database-race-conditions-coupon-system-rails",".md","document","text\u002Fmarkdown",false,"bfa649e681d373a2",[52,62,65,68,71,83,91,94,138,144,147,149,157,160,209,212,219,222,225,231,234,237,284,287,334,337,339,342,345,390,393,401,409,450,457,460,463,549,552,554,557,564,602,614,622,625,628,691,698,701,703,713,716,765,777,786,789,821,839,855,857,860,863,947,953,961,1058,1061,1073,1076,1188,1191,1193,1196,1207,1210,1218],[53,54,55,56,61],"p",{},"We shipped a coupon system last week. Took one day. Most of the time was spent fixing bugs that only appear when things happen at the same time—",[57,58,60],"a",{"href":59},"https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FRace_condition","race conditions",".",[53,63,64],{},"Coupon systems look trivial. Store a code, check if it's valid, apply a discount. But underneath that simplicity is a minefield of race conditions and edge cases. The kind that pass every test, work fine in staging, then blow up when two customers click \"Apply\" at the same moment.",[53,66,67],{},"Here's what we learned.",[69,70,24],"h2",{"id":23},[53,72,73,77,78,82],{},[57,74,76],{"href":75},"https:\u002F\u002Fmilkstraw.ai\u002F","MilkStraw AI"," helps companies reduce their ",[57,79,81],{"href":80},"https:\u002F\u002Faws.amazon.com\u002F","AWS"," bills. We analyze their cloud usage, find savings opportunities, and take a percentage of what we save them. Think of it as a success-fee model: if we save you $10,000\u002Fmonth, we take 20% ($2,000) and you keep the rest.",[53,84,85,86,90],{},"We wanted promotional pricing. Give early adopters a discount. Let partners offer special rates. The usual ",[57,87,89],{"href":88},"https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FSoftware_as_a_service","SaaS"," promo code stuff.",[53,92,93],{},"The domain model looks like this:",[95,96,97,110,116,122,132],"ul",{},[98,99,100,104,105,109],"li",{},[101,102,103],"strong",{},"Coupon",": The promo code itself. Has a code (",[106,107,108],"code",{},"SUMMER25","), a validity window (start\u002Fend dates), a duration (how many months the discount lasts), and a discounted fee percentage (e.g., 10% instead of our standard 20%).",[98,111,112,115],{},[101,113,114],{},"Organization",": A company using MilkStraw. Has AWS accounts, gets monthly bills.",[98,117,118,121],{},[101,119,120],{},"User",": A person who belongs to one or more organizations.",[98,123,124,127,128,131],{},[101,125,126],{},"Redemption",": The record that ties it together. When a user enters a promo code for their organization, we create a redemption with a ",[106,129,130],{},"months_remaining"," counter.",[98,133,134,137],{},[101,135,136],{},"Bill",": Monthly invoice for an organization. References the active redemption (if any) to apply the discounted rate.",[53,139,140,141,143],{},"Each billing cycle, we create a bill for each organization. If they have an active redemption, we use the coupon's discounted fee instead of the standard rate. Then we decrement ",[106,142,130],{},". When it hits zero, the discount stops.",[53,145,146],{},"Simple enough. Here's where it breaks.",[69,148,27],{"id":26},[53,150,151,152,156],{},"A Time-of-Check to Time-of-Use (",[57,153,155],{"href":154},"https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FTime-of-check_to_time-of-use","TOCTOU",") bug occurs when two users from the same organization click \"Apply\" simultaneously. Both requests see no existing redemption and create one, resulting in duplicate discounts.",[53,158,159],{},"Each organization should only redeem a given coupon once. We added a validation:",[161,162,165],"pre",{"language":163,"class":164},"ruby","shiki shiki-themes github-light-default github-dark-default dark:github-dark-default",[106,166,168,185,186,185,204],{"class":167},"language-ruby",[169,170,173,177,181],"span",{"class":171,"style":172},"line","display: inline",[169,174,176],{"style":175},"color:#CF222E;--shiki-dark:#FF7B72","def",[169,178,180],{"style":179},"color:#8250DF;--shiki-dark:#D2A8FF"," already_redeemed_for_organization?",[169,182,184],{"style":183},"color:#1F2328;--shiki-dark:#E6EDF3","(organization)","\n",[169,187,188,191,194,197,201],{"class":171,"style":172},[169,189,190],{"style":183},"  redemptions.",[169,192,193],{"style":179},"exists?",[169,195,196],{"style":183},"(",[169,198,200],{"style":199},"color:#0550AE;--shiki-dark:#79C0FF","organization:",[169,202,203],{"style":183},")",[169,205,206],{"class":171,"style":172},[169,207,208],{"style":175},"end",[53,210,211],{},"Simple check. If a redemption exists for this org, reject. Except two users from the same organization can hit \"Apply\" at the same moment.",[53,213,214,215,218],{},"Both requests check ",[106,216,217],{},"already_redeemed_for_organization?",". Both see no existing redemption. Both create one. Now the organization has two redemptions for the same coupon.",[53,220,221],{},"The state changes between when you check it and when you act on it. It's a classic \"check-then-act\" race condition.",[53,223,224],{},"Here's how it plays out:",[53,226,227],{},[228,229],"img",{"src":230},"\u002Fimages\u002Fblog\u002Fdatabase-race-conditions-coupon-system-rails-1.webp",[53,232,233],{},"This isn't theoretical. It happens when companies have multiple admins. Two people see a promo code in Slack, both rush to apply it. Milliseconds apart.",[53,235,236],{},"The fix is a database-level unique constraint:",[161,238,239],{"language":163,"class":164},[106,240,241,185,264,185,275],{"class":167},[169,242,243,246,249,252,255,258,261],{"class":171,"style":172},[169,244,245],{"style":183},"add_index ",[169,247,248],{"style":199},":coupon_redemptions",[169,250,251],{"style":183},", [",[169,253,254],{"style":199},":coupon_id",[169,256,257],{"style":183},", ",[169,259,260],{"style":199},":organization_id",[169,262,263],{"style":183},"],",[169,265,266,269,272],{"class":171,"style":172},[169,267,268],{"style":199},"          unique:",[169,270,271],{"style":199}," true",[169,273,274],{"style":183},",",[169,276,277,280],{"class":171,"style":172},[169,278,279],{"style":199},"          name:",[169,281,283],{"style":282},"color:#0A3069;--shiki-dark:#A5D6FF"," 'idx_coupon_redemptions_coupon_org_unique'",[53,285,286],{},"Then catch the constraint violation:",[161,288,289],{"language":163,"class":164},[106,290,291,185,298,185,304,185,318,185,330],{"class":167},[169,292,293,295],{"class":171,"style":172},[169,294,176],{"style":175},[169,296,297],{"style":179}," call",[169,299,300],{"class":171,"style":172},[169,301,303],{"style":302},"color:#6E7781;--shiki-dark:#8B949E","  # ... validation and redemption creation",[169,305,306,309,312,315],{"class":171,"style":172},[169,307,308],{"style":175},"rescue",[169,310,311],{"style":199}," ActiveRecord",[169,313,314],{"style":183},"::",[169,316,317],{"style":199},"RecordNotUnique",[169,319,320,323,325,328],{"class":171,"style":172},[169,321,322],{"style":179},"  error_result",[169,324,196],{"style":183},[169,326,327],{"style":199},":already_redeemed",[169,329,203],{"style":183},[169,331,332],{"class":171,"style":172},[169,333,208],{"style":175},[53,335,336],{},"Application code validates first (fast feedback for users). Database constraints catch the race condition (correctness guarantee). Both layers matter.",[69,338,30],{"id":29},[53,340,341],{},"An organization should only have one active coupon at a time. If you're getting 50% off for 3 months, you shouldn't be able to stack another 25% off on top.",[53,343,344],{},"We added a check:",[161,346,347],{"language":163,"class":164},[106,348,349,185,359,185,381,185,386],{"class":167},[169,350,351,353,356],{"class":171,"style":172},[169,352,176],{"style":175},[169,354,355],{"style":179}," validate_redemption_limits",[169,357,358],{"style":183},"(coupon)",[169,360,361,364,367,370,373,376,378],{"class":171,"style":172},[169,362,363],{"style":175},"  return",[169,365,366],{"style":199}," :organization_has_active_redemption",[169,368,369],{"style":175}," if",[169,371,372],{"style":183}," @organization.",[169,374,375],{"style":179},"active_coupon_redemption",[169,377,61],{"style":183},[169,379,380],{"style":179},"present?",[169,382,383],{"class":171,"style":172},[169,384,385],{"style":302},"  # ...",[169,387,388],{"class":171,"style":172},[169,389,208],{"style":175},[53,391,392],{},"Same race condition. Two different promo codes, submitted simultaneously. Both pass validation. Both create redemptions. Organization now has two active discounts.",[53,394,395,396,400],{},"In database terms, this is called ",[57,397,399],{"href":398},"https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FSnapshot_isolation","write skew",". Two transactions read overlapping data, make decisions based on what they read, and write back results that violate an invariant. Neither transaction saw the other's write.",[53,402,403,404,408],{},"The solution is a ",[57,405,407],{"href":406},"https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Findexes-partial.html","partial unique index"," (also called a filtered index):",[161,410,411],{"language":163,"class":164},[106,412,413,185,425,185,433,185,443],{"class":167},[169,414,415,417,419,421,423],{"class":171,"style":172},[169,416,245],{"style":183},[169,418,248],{"style":199},[169,420,257],{"style":183},[169,422,260],{"style":199},[169,424,274],{"style":183},[169,426,427,429,431],{"class":171,"style":172},[169,428,268],{"style":199},[169,430,271],{"style":199},[169,432,274],{"style":183},[169,434,435,438,441],{"class":171,"style":172},[169,436,437],{"style":199},"          where:",[169,439,440],{"style":282}," 'months_remaining > 0'",[169,442,274],{"style":183},[169,444,445,447],{"class":171,"style":172},[169,446,279],{"style":199},[169,448,449],{"style":282}," 'idx_coupon_redemptions_one_active_per_org'",[53,451,452,453,456],{},"This says: among all redemptions where ",[106,454,455],{},"months_remaining > 0",", each organization can appear only once. When the redemption expires (months hit zero), it falls out of the index, and the organization can redeem a new coupon.",[53,458,459],{},"Partial indexes are underused. They let you enforce constraints that only apply to a subset of rows. \"Unique among active records\" is a pattern that shows up constantly: one active subscription per user, one pending order per cart, one draft post per author.",[53,461,462],{},"We also need to distinguish between the two race condition errors:",[161,464,465],{"language":163,"class":164},[106,466,467,185,473,185,477,185,490,185,513,185,525,185,530,185,540,185,545],{"class":167},[169,468,469,471],{"class":171,"style":172},[169,470,176],{"style":175},[169,472,297],{"style":179},[169,474,475],{"class":171,"style":172},[169,476,303],{"style":302},[169,478,479,481,483,485,487],{"class":171,"style":172},[169,480,308],{"style":175},[169,482,311],{"style":199},[169,484,314],{"style":183},[169,486,317],{"style":199},[169,488,489],{"style":183}," => e",[169,491,492,495,498,501,503,506,508,511],{"class":171,"style":172},[169,493,494],{"style":175},"  if",[169,496,497],{"style":183}," e.",[169,499,500],{"style":179},"message",[169,502,61],{"style":183},[169,504,505],{"style":179},"include?",[169,507,196],{"style":183},[169,509,510],{"style":282},"'idx_coupon_redemptions_one_active_per_org'",[169,512,203],{"style":183},[169,514,515,518,520,523],{"class":171,"style":172},[169,516,517],{"style":179},"    error_result",[169,519,196],{"style":183},[169,521,522],{"style":199},":organization_has_active_redemption",[169,524,203],{"style":183},[169,526,527],{"class":171,"style":172},[169,528,529],{"style":175},"  else",[169,531,532,534,536,538],{"class":171,"style":172},[169,533,517],{"style":179},[169,535,196],{"style":183},[169,537,327],{"style":199},[169,539,203],{"style":183},[169,541,542],{"class":171,"style":172},[169,543,544],{"style":175},"  end",[169,546,547],{"class":171,"style":172},[169,548,208],{"style":175},[53,550,551],{},"Different constraints, different user messages. Parsing the error message feels hacky, but it works and it's explicit about what went wrong.",[69,553,33],{"id":32},[53,555,556],{},"A user redeems a coupon for their company. A month later, that user leaves the company and gets deleted from the system. What happens to the discount?",[53,558,559,560,563],{},"With ",[106,561,562],{},"dependent: :destroy"," on the association:",[161,565,566],{"language":163,"class":164},[106,567,568,185,583,185,598],{"class":167},[169,569,570,573,577,580],{"class":171,"style":172},[169,571,572],{"style":175},"class",[169,574,576],{"style":575},"color:#953800;--shiki-dark:#FFA657"," User",[169,578,579],{"style":183}," \u003C ",[169,581,582],{"style":199},"ApplicationRecord",[169,584,585,588,590,592,595],{"class":171,"style":172},[169,586,587],{"style":183},"  has_many ",[169,589,248],{"style":199},[169,591,257],{"style":183},[169,593,594],{"style":199},"dependent:",[169,596,597],{"style":199}," :destroy",[169,599,600],{"class":171,"style":172},[169,601,208],{"style":175},[53,603,604,605,608,609,613],{},"The redemption gets deleted. The company loses its promotional pricing mid-way through. Worse: the coupon's ",[106,606,607],{},"redemptions_count"," decrements via ",[57,610,612],{"href":611},"https:\u002F\u002Fguides.rubyonrails.org\u002Fassociation_basics.html#options-for-belongs-to-counter-cache","counter cache",", potentially reopening a sold-out promotion.",[53,615,616,617,621],{},"This is a cascading delete gone wrong. The database faithfully maintains ",[57,618,620],{"href":619},"https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FReferential_integrity","referential integrity"," by removing child records when the parent disappears. But referential integrity isn't the same as business logic integrity.",[53,623,624],{},"The discount doesn't belong to the user. It belongs to the organization. The user just happened to type in the code.",[53,626,627],{},"Fix:",[161,629,630],{"language":163,"class":164},[106,631,632,185,642,185,655,185,659,185,661,185,672,185,687],{"class":167},[169,633,634,636,638,640],{"class":171,"style":172},[169,635,572],{"style":175},[169,637,576],{"style":575},[169,639,579],{"style":183},[169,641,582],{"style":199},[169,643,644,646,648,650,652],{"class":171,"style":172},[169,645,587],{"style":183},[169,647,248],{"style":199},[169,649,257],{"style":183},[169,651,594],{"style":199},[169,653,654],{"style":199}," :nullify",[169,656,657],{"class":171,"style":172},[169,658,208],{"style":175},[169,660],{"class":171,"style":172},[169,662,663,665,668,670],{"class":171,"style":172},[169,664,572],{"style":175},[169,666,667],{"style":575}," Coupon::Redemption",[169,669,579],{"style":183},[169,671,582],{"style":199},[169,673,674,677,680,682,685],{"class":171,"style":172},[169,675,676],{"style":183},"  belongs_to ",[169,678,679],{"style":199},":user",[169,681,257],{"style":183},[169,683,684],{"style":199},"optional:",[169,686,271],{"style":199},[169,688,689],{"class":171,"style":172},[169,690,208],{"style":175},[53,692,693,694,697],{},"Now when a user is deleted, their redemptions survive with ",[106,695,696],{},"user_id"," set to null. The organization keeps its discount. The counter cache stays accurate. We lose the audit trail of who entered the code, but that's a reasonable tradeoff.",[53,699,700],{},"This pattern applies anywhere you have \"who did it\" vs \"who benefits from it\" ownership. The click-to-buy user vs the account that owns the purchase. The admin who invited a teammate vs the team that gains the member.",[69,702,36],{"id":35},[53,704,705,706,709,710,712],{},"Users type coupon codes wrong. ",[106,707,708],{},"summer25"," instead of ",[106,711,108],{},". If your code lookup is case-sensitive, they get \"invalid code\" errors and file support tickets.",[53,714,715],{},"So you add a normalizer:",[161,717,718],{"language":163,"class":164},[106,719,720,185,731,185,761],{"class":167},[169,721,722,724,727,729],{"class":171,"style":172},[169,723,572],{"style":175},[169,725,726],{"style":575}," Coupon",[169,728,579],{"style":183},[169,730,582],{"style":199},[169,732,733,736,739,741,744,747,750,753,755,758],{"class":171,"style":172},[169,734,735],{"style":183},"  normalizes ",[169,737,738],{"style":199},":code",[169,740,257],{"style":183},[169,742,743],{"style":199},"with:",[169,745,746],{"style":199}," ->",[169,748,749],{"style":183}," { it.",[169,751,752],{"style":179},"strip",[169,754,61],{"style":183},[169,756,757],{"style":179},"upcase",[169,759,760],{"style":183}," }",[169,762,763],{"class":171,"style":172},[169,764,208],{"style":175},[53,766,767,768,771,772,776],{},"The ",[106,769,770],{},"normalizes"," callback (",[57,773,775],{"href":774},"https:\u002F\u002Frubyonrails.org\u002F","Rails"," 7.1+) handles the application layer. All codes entered through your app get uppercased before storage.",[53,778,779,780,782,783,785],{},"But there's a gap. What if someone creates ",[106,781,108],{}," and ",[106,784,708],{}," as separate coupons through a direct database insert, a Rails console session, or a bug in an admin API?",[53,787,788],{},"The unique index needs to match:",[161,790,791],{"language":163,"class":164},[106,792,793,185,814],{"class":167},[169,794,795,797,800,802,805,807,810,812],{"class":171,"style":172},[169,796,245],{"style":183},[169,798,799],{"style":199},":coupons",[169,801,257],{"style":183},[169,803,804],{"style":282},"'lower(code)'",[169,806,257],{"style":183},[169,808,809],{"style":199},"unique:",[169,811,271],{"style":199},[169,813,274],{"style":183},[169,815,816,818],{"class":171,"style":172},[169,817,279],{"style":199},[169,819,820],{"style":282}," 'index_coupons_on_lower_code'",[53,822,823,824,828,829,832,833,782,835,838],{},"This is called an ",[57,825,827],{"href":826},"https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Findexes-expressional.html","expression index"," (or functional index). Instead of indexing the column value directly, you index a function of it. ",[106,830,831],{},"lower(code)"," ensures ",[106,834,108],{},[106,836,837],{},"Summer25"," collide at the database level.",[53,840,841,257,845,849,850,854],{},[57,842,844],{"href":843},"https:\u002F\u002Fwww.postgresql.org\u002F","PostgreSQL",[57,846,848],{"href":847},"https:\u002F\u002Fwww.mysql.com\u002F","MySQL"," 8+, and ",[57,851,853],{"href":852},"https:\u002F\u002Fsqlite.org\u002F","SQLite"," all support this. If you have case-insensitive uniqueness requirements, expression indexes are the reliable way to enforce them.",[69,856,39],{"id":38},[53,858,859],{},"Creating a bill and decrementing the coupon's remaining months are two operations. What if one fails?",[53,861,862],{},"Original code:",[161,864,865],{"language":163,"class":164},[106,866,867,185,876,185,889,185,891,185,910,185,921,185,926,185,931,185,933,185,943],{"class":167},[169,868,869,871,874],{"class":171,"style":172},[169,870,176],{"style":175},[169,872,873],{"style":179}," create_organization_bill",[169,875,184],{"style":183},[169,877,878,881,884,887],{"class":171,"style":172},[169,879,880],{"style":575},"  coupon_redemption",[169,882,883],{"style":175}," =",[169,885,886],{"style":183}," organization.",[169,888,375],{"style":179},[169,890],{"class":171,"style":172},[169,892,893,896,898,900,903,905,908],{"class":171,"style":172},[169,894,895],{"style":575},"  bill",[169,897,883],{"style":175},[169,899,886],{"style":183},[169,901,902],{"style":179},"bills",[169,904,61],{"style":183},[169,906,907],{"style":179},"create!",[169,909,196],{"style":183},[169,911,912,915,918],{"class":171,"style":172},[169,913,914],{"style":199},"    fee_percentage:",[169,916,917],{"style":179}," fee_percentage",[169,919,920],{"style":183},"(organization, coupon_redemption),",[169,922,923],{"class":171,"style":172},[169,924,925],{"style":199},"    coupon_redemption:",[169,927,928],{"class":171,"style":172},[169,929,930],{"style":183},"  )",[169,932],{"class":171,"style":172},[169,934,935,937,940],{"class":171,"style":172},[169,936,880],{"style":183},[169,938,939],{"style":175},"&.",[169,941,942],{"style":179},"decrement_month!",[169,944,945],{"class":171,"style":172},[169,946,208],{"style":175},[53,948,949,950,952],{},"If ",[106,951,942],{}," raises an exception, the bill exists but the month wasn't decremented. Next billing cycle, they get the discount again. Free month.",[53,954,955,956,960],{},"This is a partial failure leading to inconsistent state. The fix is atomicity (the A in ",[57,957,959],{"href":958},"https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FACID","ACID","). Wrap both operations in a transaction:",[161,962,963],{"language":163,"class":164},[106,964,965,185,973,185,983,185,985,185,1003,185,1020,185,1029,185,1034,185,1039,185,1041,185,1050,185,1054],{"class":167},[169,966,967,969,971],{"class":171,"style":172},[169,968,176],{"style":175},[169,970,873],{"style":179},[169,972,184],{"style":183},[169,974,975,977,979,981],{"class":171,"style":172},[169,976,880],{"style":575},[169,978,883],{"style":175},[169,980,886],{"style":183},[169,982,375],{"style":179},[169,984],{"class":171,"style":172},[169,986,987,990,992,995,997,1000],{"class":171,"style":172},[169,988,989],{"style":199},"  ActiveRecord",[169,991,314],{"style":183},[169,993,994],{"style":199},"Base",[169,996,61],{"style":183},[169,998,999],{"style":179},"transaction",[169,1001,1002],{"style":175}," do",[169,1004,1005,1008,1010,1012,1014,1016,1018],{"class":171,"style":172},[169,1006,1007],{"style":575},"    bill",[169,1009,883],{"style":175},[169,1011,886],{"style":183},[169,1013,902],{"style":179},[169,1015,61],{"style":183},[169,1017,907],{"style":179},[169,1019,196],{"style":183},[169,1021,1022,1025,1027],{"class":171,"style":172},[169,1023,1024],{"style":199},"      fee_percentage:",[169,1026,917],{"style":179},[169,1028,920],{"style":183},[169,1030,1031],{"class":171,"style":172},[169,1032,1033],{"style":199},"      coupon_redemption:",[169,1035,1036],{"class":171,"style":172},[169,1037,1038],{"style":183},"    )",[169,1040],{"class":171,"style":172},[169,1042,1043,1046,1048],{"class":171,"style":172},[169,1044,1045],{"style":183},"    coupon_redemption",[169,1047,939],{"style":175},[169,1049,942],{"style":179},[169,1051,1052],{"class":171,"style":172},[169,1053,544],{"style":175},[169,1055,1056],{"class":171,"style":172},[169,1057,208],{"style":175},[53,1059,1060],{},"If either operation fails, both roll back. Atomicity.",[53,1062,1063,1064,1068,1069,1072],{},"One thing transactions don't solve: ",[57,1065,1067],{"href":1066},"https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FIdempotence","idempotency",". If your job succeeds, commits the transaction, then crashes before marking itself complete, it might retry and create a duplicate bill. We handle this by checking if a bill already exists for the organization in the current billing period before creating a new one. To truly close the loop, we back this check with a unique database index on ",[106,1070,1071],{},"[organization_id, billing_period]",", ensuring that even if two billing jobs trigger at once, the database only ever allows one source of truth. Transactions guarantee consistency within a single attempt. Idempotency guards against repeated attempts.",[53,1074,1075],{},"The test for rollback behavior is important too:",[161,1077,1078],{"language":163,"class":164},[106,1079,1080,185,1090,185,1132,185,1134,185,1144,185,1163,185,1175,185,1180,185,1184],{"class":167},[169,1081,1082,1085,1088],{"class":171,"style":172},[169,1083,1084],{"style":199},"test",[169,1086,1087],{"style":282}," 'rolls back bill creation when decrement_month! fails'",[169,1089,1002],{"style":175},[169,1091,1092,1095,1097,1099,1101,1104,1106,1109,1111,1114,1117,1120,1122,1125,1127,1130],{"class":171,"style":172},[169,1093,1094],{"style":199},"  Coupon",[169,1096,314],{"style":183},[169,1098,126],{"style":199},[169,1100,61],{"style":183},[169,1102,1103],{"style":179},"any_instance",[169,1105,61],{"style":183},[169,1107,1108],{"style":179},"stubs",[169,1110,196],{"style":183},[169,1112,1113],{"style":199},":decrement_month!",[169,1115,1116],{"style":183},").",[169,1118,1119],{"style":179},"raises",[169,1121,196],{"style":183},[169,1123,1124],{"style":199},"ActiveRecord",[169,1126,314],{"style":183},[169,1128,1129],{"style":199},"RecordInvalid",[169,1131,203],{"style":183},[169,1133],{"class":171,"style":172},[169,1135,1136,1139,1142],{"class":171,"style":172},[169,1137,1138],{"style":183},"  assert_no_difference ",[169,1140,1141],{"style":282},"'Organization::Bill.count'",[169,1143,1002],{"style":175},[169,1145,1146,1149,1151,1153,1155,1157,1160],{"class":171,"style":172},[169,1147,1148],{"style":179},"    assert_raises",[169,1150,196],{"style":183},[169,1152,1124],{"style":199},[169,1154,314],{"style":183},[169,1156,1129],{"style":199},[169,1158,1159],{"style":183},") ",[169,1161,1162],{"style":175},"do",[169,1164,1165,1168,1170,1173],{"class":171,"style":172},[169,1166,1167],{"style":199},"      CreateOrganizationBillJob",[169,1169,61],{"style":183},[169,1171,1172],{"style":179},"perform_now",[169,1174,184],{"style":183},[169,1176,1177],{"class":171,"style":172},[169,1178,1179],{"style":175},"    end",[169,1181,1182],{"class":171,"style":172},[169,1183,544],{"style":175},[169,1185,1186],{"class":171,"style":172},[169,1187,208],{"style":175},[53,1189,1190],{},"If you don't test the rollback behavior explicitly, you'll only discover it's broken when customers complain about missing charges or duplicate discounts.",[69,1192,42],{"id":41},[53,1194,1195],{},"Every one of these bugs shares a root cause: assuming atomicity where none exists.",[95,1197,1198,1201,1204],{},[98,1199,1200],{},"Two requests can run the same check simultaneously",[98,1202,1203],{},"A user can be deleted while their data is being processed",[98,1205,1206],{},"Two operations that \"always happen together\" can fail independently",[53,1208,1209],{},"In a single-user, single-threaded world, none of this happens. Everything works in sequence. But production has concurrent requests, background jobs, admin panels, and cascading deletions all happening simultaneously.",[53,1211,1212,1213,1217],{},"The database is your friend here. Unique indexes, partial indexes, expression indexes, ",[57,1214,1216],{"href":1215},"https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FForeign_key","foreign keys",", and transactions all exist to enforce invariants that application code can't reliably maintain.",[53,1219,1220],{},"Application validations are for user feedback. Database constraints are for correctness. Use both.",1794817943326]