Raw
1 import { Table, CardList, Tabs, TabsList, TabsTrigger, TabsContent, TabsContentWrapper } from "docs-ui"
2
3 export const metadata = {
4 title: `Locking Module`,
5 }
6
7 # {metadata.title}
8
9 In this document, you'll learn about the Locking Module and its providers.
10
11 ## What is the Locking Module?
12
13 The Locking Module manages access to shared resources by multiple processes or threads. It prevents conflicts between processes that are trying to access the same resource at the same time, and ensures data consistency.
14
15 Medusa uses the Locking Module to control concurrency, avoid race conditions, and protect parts of code that should not be executed by more than one process at a time. This is especially essential in distributed or multi-threaded environments.
16
17 For example, Medusa uses the Locking Module in inventory management to ensure that only one transaction can update the stock levels at a time. By using the Locking Module in this scenario, Medusa prevents overselling an inventory item and keeps its quantity amounts accurate, even during high traffic periods or when receiving concurrent requests.
18
19 ---
20
21 ## How to Use the Locking Module?
22
23 You can use the Locking Module as part of the [workflows](!docs!/learn/fundamentals/workflows) you build for your custom features. A workflow is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.
24
25 In a workflow, you can either use:
26
27 - Medusa's [acquireLockStep](/references/medusa-workflows/steps/acquireLockStep) and [releaseLockStep](/references/medusa-workflows/steps/releaseLockStep) to create locks around critical steps in your workflow.
28 - The Locking Module's service directly in your steps to have more control over the locking mechanism
29
30 For example:
31
32 <Tabs defaultValue="workflow">
33 <TabsList>
34 <TabsTrigger value="workflow">Workflow</TabsTrigger>
35 <TabsTrigger value="step">Step</TabsTrigger>
36 </TabsList>
37 <TabsContentWrapper>
38 <TabsContent value="workflow">
39
40 ```ts title="src/workflows/charge-customer.ts"
41 import { createWorkflow } from "@medusajs/framework/workflows-sdk"
42 import { acquireLockStep, releaseLockStep } from "@medusajs/medusa/core-flows"
43 import { chargeCustomerStep } from "./steps/charge-customer-step"
44
45 type WorkflowInput = {
46 customer_id: string;
47 order_id: string;
48 }
49
50 export const chargeCustomerWorkflow = createWorkflow(
51 "charge-customer",
52 (input: WorkflowInput) => {
53 acquireLockStep({
54 key: input.order_id,
55 // Attempt to acquire the lock for two seconds before timing out
56 timeout: 2,
57 // Lock is only held for a maximum of ten seconds
58 ttl: 10,
59 })
60
61 chargeCustomerStep(input)
62
63 releaseLockStep({
64 key: input.order_id,
65 })
66 }
67 )
68 ```
69
70 In the example above, you create a workflow that acquires a lock on an order using the `acquireLockStep` before charging a customer. The lock is then released using the `releaseLockStep` after the operation is complete.
71
72 This ensures that only one instance of the workflow can modify the order at a time, preventing issues like double charging the customer.
73
74 </TabsContent>
75 <TabsContent value="step">
76
77 ```ts
78 import { Modules } from "@medusajs/framework/utils"
79 import {
80 createStep,
81 createWorkflow,
82 } from "@medusajs/framework/workflows-sdk"
83
84 const step1 = createStep(
85 "step-1",
86 async ({}, { container }) => {
87 const lockingModuleService = container.resolve(
88 Modules.LOCKING
89 )
90 const productModuleService = container.resolve(
91 Modules.PRODUCT
92 )
93
94 await lockingModuleService.execute("prod_123", async () => {
95 await productModuleService.deleteProduct("prod_123")
96 })
97 }
98 )
99
100 export const workflow = createWorkflow(
101 "workflow-1",
102 () => {
103 step1()
104 }
105 )
106 ```
107
108 In the example above, you create a workflow that has a step. In the step, you resolve the services of the Locking and Product modules from the [Medusa container](!docs!/learn/fundamentals/medusa-container).
109
110 Then, you use the `execute` method of the Locking Module to acquire a lock for the product with the ID `prod_123` and execute an asynchronous function, which deletes the product.
111
112 </TabsContent>
113 </TabsContentWrapper>
114 </Tabs>
115
116 ---
117
118 ## When to Use the Locking Module?
119
120 You should use the Locking Module when you need to ensure that only one process can access a shared resource at a time. As mentioned in the inventory example previously, you don't want customers to order quantities of inventory that are not available, or to update the stock levels of an item concurrently.
121
122 In those scenarios, you can use the Locking Module to acquire a lock for a resource and execute a critical section of code that should not be accessed by multiple processes simultaneously.
123
124 ---
125
126 ## What is a Locking Module Provider?
127
128 A Locking Module Provider implements the underlying logic of the Locking Module. It manages the locking mechanisms and ensures that only one process can access a shared resource at a time.
129
130 Medusa provides [multiple Locking Module Providers](#list-of-locking-module-providers) that are suitable for development and production. You can also create a [custom Locking Module Provider](/references/locking-module-provider) to implement custom locking mechanisms or integrate with third-party services.
131
132 ### Default Locking Module Provider
133
134 By default, Medusa uses the In-Memory Locking Module Provider. This provider uses a plain JavaScript map to store the locks. While this is useful for development, it is not recommended for production environments as it is only intended for use in a single-instance environment.
135
136 To add more providers, you can register them in the `medusa-config.ts` file. For example:
137
138 ```ts
139 module.exports = defineConfig({
140 // ...
141 modules: [
142 {
143 resolve: "@medusajs/medusa/locking",
144 options: {
145 providers: [
146 // add providers here...
147 ],
148 },
149 },
150 ],
151 })
152 ```
153
154 When you register other providers in `medusa-config.ts`, Medusa will set the default provider based on the following scenarios:
155
156 <Table>
157 <Table.Header>
158 <Table.Row>
159 <Table.HeaderCell>
160 Scenario
161 </Table.HeaderCell>
162 <Table.HeaderCell>
163 Default Provider
164 </Table.HeaderCell>
165 </Table.Row>
166 </Table.Header>
167 <Table.Body>
168 <Table.Row>
169 <Table.Cell>
170 One provider is registered.
171 </Table.Cell>
172 <Table.Cell>
173 The registered provider.
174 </Table.Cell>
175 </Table.Row>
176 <Table.Row>
177 <Table.Cell>
178 Multiple providers are registered and none of them has an `is_default` flag.
179 </Table.Cell>
180 <Table.Cell>
181 In-Memory Locking Module Provider.
182 </Table.Cell>
183 </Table.Row>
184 <Table.Row>
185 <Table.Cell>
186 Multiple providers and one of them has an `is_default` flag.
187 </Table.Cell>
188 <Table.Cell>
189 The provider with the `is_default` flag.
190 </Table.Cell>
191 </Table.Row>
192 </Table.Body>
193 </Table>
194
195 ---
196
197 ## List of Locking Module Providers
198
199 Medusa provides the following Locking Module Providers. You can use one of them, or [Create a Locking Module Provider](/references/locking-module-provider).
200
201 <CardList
202 items={[
203 {
204 title: "Redis",
205 href: "/infrastructure-modules/locking/redis",
206 badge: {
207 variant: "green",
208 children: "Recommended"
209 }
210 },
211 {
212 title: "PostgreSQL",
213 href: "/infrastructure-modules/locking/postgres",
214 }
215 ]}
216 />