#16997·medusa

Missing Row Locks in `revertUsage` and Un-Accumulated Limits in Promotion Module

Author: codeCraft-RitikCreated Sep 25, 2026Updated Sep 29, 2026
Labelstype: bugstatus: needs triaginghelp-wanted

Issue : Missing Row Locks in revertUsage and Un-Accumulated Limits in Promotion Module

1. Metadata

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):

  1. Zero Row Locks are Acquired: revertUsage() performs an un-isolated read-modify-write:
    typescript
    const newUsedValue = MathBN.sub(campaignBudgetData.used ?? 0, computedAction.amount)
    campaignBudgetData.used = MathBN.lt(newUsedValue, 0) ? 0 : newUsedValue
    await this.campaignBudgetService_.update(campaignBudgetsData, sharedContext)
    If a cart failure or cancellation occurs concurrently with another customer placing an order with the same promo code, revertUsage reads a stale used count and overwrites the database with an outdated total. This clobbers concurrent registrations and corrupts campaign spend ledgers.
  2. Missing Accumulator on Multi-Item Promotion Limits: In registerUsage(), when a promotion code applies across multiple items in a single cart, computedActions contains multiple actions for the same code. While CampaignBudgetType.USAGE guards against repeated increments using promotionCodeUsageMap, the promotion.limit check (lines 405–419) does not track code usage across iterations, re-reading the unmutated promotion.used entity 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):

typescript
// 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):

typescript
@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)

mermaid
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:

diff
--- 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) {