1 export const metadata = {
2 title: `${pageNumber} Locking Operations in Workflows`,
3 }
4
5 # {metadata.title}
6
7 In this chapter, you’ll learn how to lock operations in your workflows to avoid race conditions and ensure data consistency.
8
9 ## What is a Lock?
10
11 A lock is a mechanism that restricts multiple accesses to a resource or a piece of code, preventing multiple processes from modifying it simultaneously.
12
13 Locks are particularly useful in workflows where concurrent executions may lead to commerce risks. For example, Medusa uses locks in its cart workflows to prevent issues like overselling products or double charging customers.
14
15 The [Locking Module](!resources!/infrastructure-modules/locking) handles the locking mechanism using the underlying provider. You can use the Locking Module's service in your workflows to create locks around critical sections of your code.
16
17 ---
18
19 ## How to Use Locks in Workflows
20
21 Medusa provides two steps that you can use to create locks in your workflows:
22
23 - [acquireLockStep](!resources!/references/medusa-workflows/steps/acquireLockStep): Attempt to acquire a lock. If the lock is already held by another process, this step will wait until the lock is released. It will fail if a timeout occurs before acquiring the lock.
24 - [releaseLockStep](!resources!/references/medusa-workflows/steps/releaseLockStep): Release a previously acquired lock.
25
26 You can use these steps in your workflows to ensure that only one instance of a workflow can modify a resource at a time.
27
28 For example:
29
30 export const workflowLockHighlights = [
31 ["13", "acquireLockStep", "Acquire a lock on the order."],
32 ["21", "chargeCustomerStep", "Perform an operation once the lock is acquired."],
33 ["23", "releaseLockStep", "Release the lock after the operation is complete."]
34 ]
35
36 ```ts title="src/workflows/charge-customer.ts" highlights={workflowLockHighlights}
37 import { createWorkflow } from "@medusajs/framework/workflows-sdk"
38 import { acquireLockStep, releaseLockStep } from "@medusajs/medusa/core-flows"
39 import { chargeCustomerStep } from "./steps/charge-customer-step"
40
41 type WorkflowInput = {
42 customer_id: string;
43 order_id: string;
44 }
45
46 export const chargeCustomerWorkflow = createWorkflow(
47 "charge-customer",
48 (input: WorkflowInput) => {
49 acquireLockStep({
50 key: input.order_id,
51 // Attempt to acquire the lock for two seconds before timing out
52 timeout: 2,
53 // Lock is only held for a maximum of ten seconds
54 ttl: 10,
55 })
56
57 chargeCustomerStep(input)
58
59 releaseLockStep({
60 key: input.order_id,
61 })
62 }
63 )
64 ```
65
66 In this example, the workflow attempts to acquire a lock on an order using its ID as the lock key.
67
68 Once the lock is acquired, it executes the `chargeCustomerStep`. After the step is complete, it releases the lock using the `releaseLockStep`.
69
70 If the lock cannot be acquired within the specified timeout period, the `acquireLockStep` will throw an error, and the workflow will fail.
71
72 <Note title="Tip">
73
74 If an error occurs in the workflow after a lock is acquired with `acquireLockStep`, the step's compensation function will release the lock automatically.
75
76 </Note>
77
78 ### Locking Steps API
79
80 Refer to the [acquireLockStep](!resources!/references/medusa-workflows/steps/acquireLockStep) and [releaseLockStep](!resources!/references/medusa-workflows/steps/releaseLockStep) for more information on the inputs of these steps.
81
82 ---
83
84 ## How to Use Locks in Workflow Steps
85
86 You can alternatively acquire and release locks within steps by resolving the Locking Module's service and using its `acquire` and `release` methods.
87
88 <Note type="warning">
89
90 Do not acquire locks within a workflow and a step in the same workflow execution, as this can lead to deadlocks.
91
92 </Note>
93
94 For example:
95
96 ```ts title="src/workflows/steps/charge-customer.ts"
97 import { createStep } from "@medusajs/framework/workflows-sdk"
98 import { Modules } from "@medusajs/framework/utils"
99
100 type StepInput = {
101 order_id: string
102 customer_id: string
103 }
104
105 export const chargeCustomerStep = createStep(
106 "charge-customer",
107 async (input: StepInput, { container }) => {
108 const lockingModuleService = container.resolve(
109 Modules.LOCKING
110 )
111
112 await lockingModuleService.acquire(input.order_id, {
113 // Lock will auto-expire after 10 seconds
114 expire: 10,
115 })
116
117 // TODO: charge customer
118
119 await lockingModuleService.release(input.order_id)
120 }
121 )
122 ```
123
124 In this example, the `chargeCustomerStep` step acquires a lock on the order using the `order_id` as the lock key. After performing the operation, it releases the lock.
125
126 <Note title="Tip">
127
128 The step will wait until the lock is acquired based on the configured Locking Module Provider's options. For example, the [Redis Locking Module Provider](!resources!/infrastructure-modules/locking/redis) will wait five seconds before timing out by default, with exponential backoff retry intervals.
129
130 </Note>
131
132 ### Locking Module Service API
133
134 Refer to the [Locking Module reference](!resources!/references/locking-service) for more information on the Locking Module's service methods.
135
136 ---
137
138 ## Locks in Nested Workflows
139
140 When a [Nested workflows](../execute-another-workflow/page.mdx) acquires a lock with `acquireLockStep`, the lock is not acquired. So, if you're using a workflow that acquires locks with `acquireLockStep` within another workflow, the parent workflow must handle the locking mechanism.
141
142 <Note>
143
144 If the nested workflow acquires a lock in a step using the Locking Module's service, the lock will be acquired as expected.
145
146 </Note>
147
148 For example, consider a custom workflow that executes Medusa's [completeCartWorkflow](!resources!/references/medusa-workflows/completeCartWorkflow). The `completeCartWorkflow` acquires locks on the cart with `acquireLockStep` to prevent race conditions.
149
150 Therefore, the custom workflow must acquire and release the locks around the `completeCartWorkflow` execution. For example:
151
152 export const nestedWorkflowLockHighlights = [
153 ["16", "acquireLockStep", "Acquire a lock on the cart before executing the nested workflow."],
154 ["23", "completeCartWorkflow", "Execute the nested workflow that requires the lock."],
155 ["30", "releaseLockStep", "Release the lock after the nested workflow is complete."]
156 ]
157
158 ```ts title="src/workflows/custom-complete-cart.ts" highlights={nestedWorkflowLockHighlights}
159 import { createWorkflow } from "@medusajs/framework/workflows-sdk"
160 import {
161 acquireLockStep,
162 releaseLockStep,
163 completeCartWorkflow,
164 } from "@medusajs/medusa/core-flows"
165
166 type WorkflowInput = {
167 cart_id: string;
168 }
169
170 export const customCompleteCartWorkflow = createWorkflow(
171 "custom-complete-cart",
172 (input: WorkflowInput) => {
173 // acquire the same lock as the nested workflow
174 acquireLockStep({
175 key: input.cart_id,
176 timeout: 30,
177 ttl: 60 * 2,
178 })
179
180 // Execute the nested workflow
181 completeCartWorkflow.runAsStep({
182 input: {
183 id: input.cart_id,
184 },
185 })
186
187 // release the lock after the nested workflow is complete
188 releaseLockStep({
189 key: input.cart_id,
190 })
191 }
192 )
193 ```
194
195 In the example above, the `customCompleteCartWorkflow` acquires a lock on the cart before executing the `completeCartWorkflow` and releases it afterward.
196
197 Make sure you're acquiring the same lock key as the nested workflow.