Missing Row Locks in `revertUsage` and Un-Accumulated Limits in Promotion Module
Issue : Missing Row Locks in revertUsage and Un-Accumulated Limits in Promotion Module
1. Metadata
- Affected File:
packages/modules/promotion/src/services/promotion-module.ts&lines 545–640 - Component:
PromotionModuleService(@medusajs/promotion) - Severity: High
- Category: Data Integrity / Concurrency / Race Conditions
2. Problem Statement
Medusa's promotion module allows store operators to configure promotional campaigns with strict budgets (e.g., maximum budget spend limit of $10,000, or a total usage cap of 500 uses).
To prevent race conditions where concurrent checkouts over-spend a budget, registerUsage() strictly acquires row-level pessimistic locks using PostgreSQL SELECT ... FOR UPDATE with a 3-second timeout (SET LOCAL lock_timeout = '3s') on promotion and promotion_campaign_budget rows.
However, in revertUsage() (which is invoked whenever a cart completion fails, an authorization is declined, or compensation workflows execute):
- Zero Row Locks are Acquired:
revertUsage()performs an un-isolated read-modify-write:If a cart failure or cancellation occurs concurrently with another customer placing an order with the same promo code,const newUsedValue = MathBN.sub(campaignBudgetData.used ?? 0, computedAction.amount) campaignBudgetData.used = MathBN.lt(newUsedValue, 0) ? 0 : newUsedValue await this.campaignBudgetService_.update(campaignBudgetsData, sharedContext)revertUsagereads a staleusedcount and overwrites the database with an outdated total. This clobbers concurrent registrations and corrupts campaign spend ledgers. - Missing Accumulator on Multi-Item Promotion Limits: In
registerUsage(), when a promotion code applies across multiple items in a single cart,computedActionscontains multiple actions for the same code. WhileCampaignBudgetType.USAGEguards against repeated increments usingpromotionCodeUsageMap, thepromotion.limitcheck (lines 405–419) does not track code usage across iterations, re-reading the unmutatedpromotion.usedentity on each line item.
3. Deep-Dive Code Analysis
Look at the difference between registerUsage and revertUsage in packages/modules/promotion/src/services/promotion-module.ts:
In registerUsage (lines 359–373):
// Properly locks rows to serialize concurrent updates:
await knex.raw("SET LOCAL lock_timeout = '3s'")
if (lockPromotionIds.length) {
await knex("promotion")
.whereIn("id", lockPromotionIds)
.orderBy("id")
.forUpdate()
.select("id")
}
if (lockBudgetIds.length) {
await knex("promotion_campaign_budget")
.whereIn("id", lockBudgetIds)
.orderBy("id")
.forUpdate()
.select("id")
}Now examine revertUsage (lines 543–615):
@InjectTransactionManager()
@EmitEvents()
async revertUsage(
computedActions: PromotionTypes.UsageComputedActions[],
registrationContext: PromotionTypes.CampaignBudgetUsageContext,
@MedusaContext() sharedContext: Context = {}
): Promise<void> {
// NO lock_timeout!
// NO knex("promotion").forUpdate()!
// NO knex("promotion_campaign_budget").forUpdate()!
const existingPromotions = await this.listActivePromotions_(...)
// Reads stale budget.used, mutates in JS memory, writes back with update()
const newUsedValue = MathBN.sub(campaignBudgetData.used ?? 0, computedAction.amount)
campaignBudgetData.used = MathBN.lt(newUsedValue, 0) ? 0 : newUsedValue
// ...
await this.campaignBudgetService_.update(campaignBudgetsData, sharedContext)
}4. Failure Timeline (Lost Update Anomaly)
sequenceDiagram
autonumber
participant T1 as Order A (Checkout Failed / Revert)
participant DB as Postgres (campaign_budget: used=$100)
participant T2 as Order B (Checking Out: +$50)
T1->>DB: listActivePromotions_ (Reads used = $100)
T2->>DB: registerUsage (Locks row FOR UPDATE, Reads used = $100)
T2->>DB: Writes used = $150 and commits
Note over DB: Committed budget is now $150
Note over T1: T1 calculates: $100 - $30 = $70 (stale!)
T1->>DB: campaignBudgetService_.update (Writes used = $70)
Note over DB: CRITICAL CORRUPTION: Order B's +$50 registration is completely LOST!5. Production & Business Impact
- Financial Over-spending: Marketing budgets have hard financial caps (e.g. $5,000 max promotion subsidy). Lost budget updates cause Medusa to think budget is still available when it has already been depleted, leading to thousands of dollars in over-discounting.
- Audit Inconsistency: The sum of orders using a promo code no longer matches
campaign_budget.used.
6. Recommended Solution & Code Patch
Add the identical deterministic FOR UPDATE lock scoping into revertUsage before reading budget records:
--- a/packages/modules/promotion/src/services/promotion-module.ts
+++ b/packages/modules/promotion/src/services/promotion-module.ts
@@ -562,6 +562,35 @@ export class PromotionModuleService extends MedusaService({
sharedContext
)
+ const lockPromotionIds = existingPromotions
+ .filter((promotion) => typeof promotion.limit === "number")
+ .map((promotion) => promotion.id)
+ const lockBudgetIds = Array.from(
+ new Set(
+ existingPromotions
+ .map((promotion) => promotion.campaign?.budget?.id)
+ .filter(Boolean) as string[]
+ )
+ )
+
+ const manager = sharedContext.transactionManager as SqlEntityManager
+ const knex = manager?.getTransactionContext()
+ if (knex) {
+ await knex.raw("SET LOCAL lock_timeout = '3s'")
+ if (lockPromotionIds.length) {
+ await knex("promotion")
+ .whereIn("id", lockPromotionIds)
+ .orderBy("id")
+ .forUpdate()
+ .select("id")
+ }
+ if (lockBudgetIds.length) {
+ await knex("promotion_campaign_budget")
+ .whereIn("id", lockBudgetIds)
+ .orderBy("id")
+ .forUpdate()
+ .select("id")
+ }
+ }
+
for (const promotion of existingPromotions) {Source: medusajs/medusa