Raw
1 import { CardList, Card, Table, CodeTabs, CodeTab, Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `Caching Module`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn about the Caching Module and its providers.
10
11 <Note title="Cloud user?">
12
13 Refer to the [Medusa Cache Cloud](!cloud!/cache) guide for setting up the Caching Module in Cloud.
14
15 </Note>
16
17 <Note>
18
19 The Caching Module is available starting [Medusa v2.11.0](https://github.com/medusajs/medusa/releases/tag/v2.11.0). It replaces the deprecated [Cache Module](../cache/page.mdx).
20
21 </Note>
22
23 ## What is the Caching Module?
24
25 The Caching Module provides functionality to cache data in your Medusa application, improving performance and reducing latency for frequently accessed data.
26
27 For example, Medusa uses the Caching Module to cache product information, and you can cache custom data such as brand information.
28
29 The Caching Module stores and retrieves cached data using the caching service you integrate, such as [Redis](./providers/redis/page.mdx) or [Memcached](./guides/memcached/page.mdx). This provides flexibility in customizing your Medusa application's infrastructure to meet your performance and scalability requirements.
30
31 ![Diagram illustrating the Caching Module architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1759846791/Medusa%20Resources/caching-overview_tz91tw.jpg)
32
33 ### Caching Module vs Cache Module
34
35 Before Medusa v2.11.0, you used the [Cache Module](../cache/page.mdx) to cache data. The Cache Module is now deprecated and has been replaced by the Caching Module.
36
37 If you're using the Cache Module in your application, refer to the [migrate to the Caching Module](./migrate-cache/page.mdx).
38
39 ---
40
41 ## Install the Caching Module
42
43 <Prerequisites
44 items={[
45 {
46 text: "Redis installed and Redis server running",
47 link: "https://redis.io/docs/getting-started/installation/"
48 }
49 ]}
50 />
51
52 The Caching Module is installed by default in your application. To use it, enable the caching feature flag and register the module in your `medusa-config.ts` file.
53
54 ### 1. Enable Caching Feature Flag
55
56 The caching feature is currently behind a feature flag. To enable it, set the `MEDUSA_FF_CACHING` environment variable to `true` in your `.env` file:
57
58 ```bash
59 MEDUSA_FF_CACHING=true
60 ```
61
62 This enables you to use the Caching Module and activates caching features in Medusa's core.
63
64 ### 2. Register the Caching Module
65
66 Next, add the Caching Module to the `modules` property of the exported object in `medusa-config.ts`:
67
68 ```ts title="medusa-config.ts"
69 module.exports = defineConfig({
70 // ...
71 modules: [
72 {
73 resolve: "@medusajs/medusa/caching",
74 options: {
75 providers: [
76 {
77 resolve: "@medusajs/caching-redis",
78 id: "caching-redis",
79 // Optional, makes this the default caching provider
80 is_default: true,
81 options: {
82 redisUrl: process.env.CACHE_REDIS_URL,
83 // more options...
84 },
85 },
86 ],
87 },
88 },
89 ],
90 })
91 ```
92
93 This registers the Caching Module in your application with the [Redis Caching Module Provider](./providers/redis/page.mdx).
94
95 <Note>
96
97 The Caching Module requires at least one Caching Module Provider to be registered. If you do not register any providers, the Caching Module throws an error when your application starts.
98
99 </Note>
100
101 ### What is a Caching Module Provider?
102
103 A Caching Module Provider implements the underlying logic for caching data, such as integrating third-party caching services. The Caching Module then uses the registered Caching Module Provider to handle caching operations.
104
105 Refer to the [Caching Module Providers guide](./providers/page.mdx) to learn more about Caching Module Providers in Medusa, and how to configure the default provider.
106
107 <CardList
108 items={[
109 {
110 title: "Redis",
111 href: "/infrastructure-modules/caching/providers/redis",
112 badge: {
113 variant: "green",
114 children: "For Production"
115 }
116 },
117 {
118 title: "Memcached",
119 href: "/infrastructure-modules/caching/guides/memcached",
120 badge: {
121 variant: "blue",
122 children: "Tutorial"
123 }
124 }
125 ]}
126 />
127
128 ### What Data is Cached by Default?
129
130 After you enable the Caching Module, Medusa automatically caches data for several business-critical APIs to boost performance and throughput. This includes all cart-related operations, where the following data is cached:
131
132 - Regions
133 - Promotion codes
134 - Variant price sets
135 - Variants
136 - Shipping options
137 - Sales channels
138 - Customers
139
140 ---
141
142 ## How to Use the Caching Module
143
144 You can cache data with the Caching Module in two ways: by caching data retrieved with [Query](!docs!/learn/fundamentals/query) or the [Index Module](!docs!/learn/fundamentals/query/index-module), or by directly using the [Caching Module's service](/references/caching-service).
145
146 ### 1. Caching with Query or Index Module
147
148 You can cache results from Query and the Index Module by passing the `cache` option to the `query.graph` and `query.index` methods, or to the `useQueryGraphStep` in workflows.
149
150 For example:
151
152 ```ts highlights={[["14"], ["15"], ["16"]]}
153 import {
154 createWorkflow,
155 WorkflowResponse,
156 } from "@medusajs/framework/workflows-sdk"
157 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
158
159 export const workflow = createWorkflow(
160 "workflow-1",
161 () => {
162 const { data: products } = useQueryGraphStep({
163 entity: "product",
164 fields: ["id", "title"],
165 options: {
166 cache: {
167 enable: true,
168 },
169 },
170 })
171
172 return new WorkflowResponse(products)
173 }
174 )
175 ```
176
177 The `useQueryGraphStep` accepts an `options.cache` property that enables and configures caching of the results.
178
179 When caching is enabled, the Caching Module stores the results in the underlying caching service (for example, Redis). Subsequent calls to the same query retrieve the results from the cache, improving performance.
180
181 Query and the Index Module accept other caching options. Learn more in the [Query](!docs!/learn/fundamentals/query#cache-query-results) and [Index Module](!docs!/learn/fundamentals/query/index-module#cache-index-module-results) guides.
182
183 ### 2. Caching with the Caching Module's Service
184
185 You can also use the Caching Module's service directly to cache custom data in your Medusa application.
186
187 For example, resolve the Caching Module's service in a workflow step and use its methods to cache brand information:
188
189 export const cachingHighlights = [
190 ["14", "computeKey", "Compute the cache key."],
191 ["15", "get", "Retrieve the cached value for the `brand` tag."],
192 ["19", "cachedValue", "If a cached value exists, return it."],
193 ["23", "getBrand", "Fetch the brand data if not cached."],
194 ["25", "set", "Cache the fetched brand data with the `brand` tag."]
195 ]
196
197 ```ts highlights={cachingHighlights}
198 import { Modules } from "@medusajs/framework/utils"
199 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
200
201 type StepInput = {
202 filters: Record<string, unknown>
203 }
204
205 export const getBrandStep = createStep(
206 "get-brand-step",
207 async (input: StepInput, { container }) => {
208 const cachingModuleService = container.resolve(Modules.CACHING)
209 const brandModuleService = container.resolve("brand")
210
211 const cacheKey = await cachingModuleService.computeKey(input.filters)
212 const cachedValue = await cachingModuleService.get({
213 tags: ["brand"],
214 })
215
216 if (cachedValue) {
217 return new StepResponse(cachedValue)
218 }
219
220 const brand = await brandModuleService.getBrand(input.filters)
221
222 await cachingModuleService.set({
223 key: cacheKey,
224 tags: [`Brand:${brand.id}`],
225 data: brand,
226 })
227
228 return new StepResponse(brand)
229 }
230 )
231 ```
232
233 In the example above, you create a step that resolves the Caching Module's service from the [Medusa container](!docs!/learn/fundamentals/medusa-container).
234
235 Then, you use the `get` method of the service to retrieve a cached value with the tag `"brand"`. You can also use other methods such as `set` to cache a value and `clear` to remove a cached value.
236
237 Learn about other methods and options of the Caching Module in the [Use Caching Module](/references/caching-service) guide.
238
239 ### Which Caching Method Should You Use?
240
241 <Table>
242 <Table.Header>
243 <Table.Row>
244 <Table.HeaderCell>
245 Caching Method
246 </Table.HeaderCell>
247 <Table.HeaderCell>
248 When to Use
249 </Table.HeaderCell>
250 </Table.Row>
251 </Table.Header>
252 <Table.Body>
253 <Table.Row>
254 <Table.Cell>
255 Query or Index Module
256 </Table.Cell>
257 <Table.Cell>
258 Ideal for standard data retrieval scenarios, such as fetching products or custom data.
259 </Table.Cell>
260 </Table.Row>
261 <Table.Row>
262 <Table.Cell>
263 Caching Module's Service
264 </Table.Cell>
265 <Table.Cell>
266 Suitable for caching computed values, external API responses, or to control caching behavior.
267 </Table.Cell>
268 </Table.Row>
269 </Table.Body>
270 </Table>
271
272 Caching data with Query or the Index Module is ideal when retrieving standard data, such as products or custom entities. The Caching Module automatically handles cache keys and invalidation for you.
273
274 If you need to cache custom data like computed values or external API responses, or you want finer control over caching behavior, use the Caching Module's service directly. In this case, you must manage cache keys yourself, though you can still enable automatic invalidation using the service's `set` method.
275
276 ---
277
278 ## Caching Module Options
279
280 You can pass the following options to the Caching Module when registering it in your `medusa-config.ts` file:
281
282 <Table>
283 <Table.Header>
284 <Table.Row>
285 <Table.HeaderCell>
286 Option
287 </Table.HeaderCell>
288 <Table.HeaderCell>
289 Description
290 </Table.HeaderCell>
291 <Table.HeaderCell>
292 Default
293 </Table.HeaderCell>
294 </Table.Row>
295 </Table.Header>
296 <Table.Body>
297 <Table.Row>
298 <Table.Cell>
299 `ttl`
300 </Table.Cell>
301 <Table.Cell>
302 A number indicating the default time-to-live (TTL) in seconds for cached items. After this period, cached items will be removed from the cache.
303 This number is passed to the underlying caching provider if no TTL is specified when caching data.
304 </Table.Cell>
305 <Table.Cell>
306 `3600` (1 hour)
307 </Table.Cell>
308 </Table.Row>
309 <Table.Row>
310 <Table.Cell>
311 `providers`
312 </Table.Cell>
313 <Table.Cell>
314 An array of caching providers to use. This allows you to configure multiple caching providers for different use cases.
315 </Table.Cell>
316 <Table.Cell>
317 No providers by default
318 </Table.Cell>
319 </Table.Row>
320 </Table.Body>
321 </Table>
322
323 ---
324
325 ## Caching Concepts
326
327 To learn more about caching concepts such as cache keys, cache tags, and automatic cache invalidation, refer to the [Caching Module Concepts guide](./concepts/page.mdx).