1 export const metadata = {
2 title: `Caching Module Concepts`,
3 }
4
5 # {metadata.title}
6
7 In this guide, you'll learn about the main concepts of the [Caching Module](../page.mdx), including cache keys, cache tags, and automatic cache invalidation.
8
9 ## Cache Keys
10
11 Cache keys uniquely identify cached data in the caching service. The Caching Module automatically generates cache keys when you cache data with Query or the Index Module.
12
13 ### Custom Cache Keys
14
15 When you cache custom data with the Caching Module's service, you can generate a cache key using the [computeKey](/references/caching-service#computeKey) method. This method generates a unique key based on the data you want to cache.
16
17 For example:
18
19 ```ts
20 const data = { id: "prod_123", title: "Product 123" }
21 const key = await cachingModuleService.computeKey(data)
22 await cachingModuleService.set({
23 key,
24 tags: ["Product:prod_123", "Product:list:*"],
25 data,
26 })
27 ```
28
29 The `computeKey` method takes an object as input and generates a unique key based on its properties.
30
31 The generated key is a hash string that uniquely identifies the data. The has doesn't change based on the order of properties in the object.
32
33 For example, the following two objects generate the same cache key:
34
35 ```ts
36 const key1 = await cachingModuleService.computeKey({ id: "prod_123", title: "Product 123" })
37 const key2 = await cachingModuleService.computeKey({ title: "Product 123", id: "prod_123" })
38
39 console.log(key1 === key2) // true
40 ```
41
42 ### When to Use Custom Cache Keys?
43
44 Use custom cache keys when you're caching custom data with the Caching Module's service. This ensures that the cached data is uniquely identified and can be retrieved or invalidated correctly.
45
46 You can also pass a custom key to Query or the Index Module when caching data. This is useful when you want to use the key for custom invalidation or retrieval.
47
48 Learn more about passing custom keys in the [Query guide](!docs!/learn/fundamentals/query#set-cache-key).
49
50 ---
51
52 ## Cache Tags
53
54 Cache tags are useful for grouping cached data, making it easier to invalidate or retrieve related cached entries.
55
56 When you cache data with the Query or Index Module, the Caching Module automatically generates cache tags based on the entity being queried and its retrieved relations.
57
58 When you cache custom data with the Caching Module's service, you can pass custom tags to the `set` and `get` methods.
59
60 ### Caching Tags Convention
61
62 The Caching Module generates cache tags in the following format:
63
64 - `Entity:id`: Cache tag for a single record of an entity. For example, `Product:prod_123` for caching a single product with the ID `prod_123`.
65 - `Entity:list:*`: Cache tag for a list of records of an entity. For example, `Product:list:*` for caching a list of products.
66
67 <Note>
68
69 `Entity` is the pascal-cased name of the data model, which you pass as the first parameter to `model.define` when defining the model.
70
71 </Note>
72
73 When you use custom tags, ensure they adhere to the above convention. Otherwise, the Caching Module cannot automatically invalidate your cached data. You'll have to [invalidate](/references/caching-service#clear) the cached data manually.
74
75 For example:
76
77 ```ts
78 const key = await cachingModuleService.computeKey(data)
79 await cachingModuleService.set({
80 key,
81 tags: ["Product:list:*", "Product:prod_123"],
82 data,
83 })
84 ```
85
86 ### When to Use Custom Tags?
87
88 Use custom tags when you want to group cached data for custom invalidation or retrieval.
89
90 Note that if your custom tags do not follow the [Caching Tags Convention](#caching-tags-convention), the Caching Module cannot automatically invalidate your cached data. You must manually [invalidate](/references/caching-service#clear) the cached data when it changes.
91
92 ### Combine Custom Tags With Automatic Tags
93
94 <Note>
95
96 This feature is available since [Medusa v2.19.0](https://github.com/medusajs/medusa/releases/tag/v2.19.0).
97
98 </Note>
99
100 When you set custom `tags`, they replace the automatically computed ones. If you want the automatic tags to still apply alongside your custom tags, set `computeAutomaticTags` to `true`.
101
102 This is useful when your query retrieves data that the automatic tag computation cannot see, such as:
103
104 - Link table rows (their own IDs are never selected, so no entity tag fires for them).
105 - Relations selected without their `id` field.
106 - Entities that affect the cached data without appearing in it, for example `ReservationItem` which changes `reserved_quantity` without being part of the query response.
107
108 For example:
109
110 ```ts
111 const key = await cachingModuleService.computeKey(data)
112 await cachingModuleService.set({
113 key,
114 tags: ["LinkProductVariantInventoryItem:list:*", "ReservationItem:list:*"],
115 computeAutomaticTags: true,
116 data,
117 })
118 ```
119
120 In the example above, the Caching Module applies the two explicit tags you provided plus all tags it computes automatically from `data`. This way you only specify what automatic computation cannot see, without restating every entity the response already exposes.
121
122 When using [Query](!docs!/learn/fundamentals/query), pass `computeAutomaticTags` in the `cache` option:
123
124 ```ts
125 const { data: products } = await query.graph({
126 entity: "product",
127 fields: ["id", "title", "variants.*"],
128 }, {
129 cache: {
130 tags: ["LinkProductVariantInventoryItem:list:*"],
131 computeAutomaticTags: true,
132 },
133 })
134 ```
135
136 <Note>
137
138 `computeAutomaticTags` has no effect when `tags` is omitted, since automatic tags are computed by default in that case.
139
140 </Note>
141
142 ---
143
144 ## Automatic Cache Invalidation
145
146 ### When is Cache Automatically Invalidated?
147
148 The Caching Module automatically invalidates cached data when the underlying data changes through database operations such as create, update, or delete.
149
150 For example, if you cache a list of products with the tag `Product:list:*` and a new product is created, the Caching Module automatically invalidates the cached list of products.
151
152 This ensures that your application always serves fresh data and avoids serving stale or outdated information.
153
154 The following table shows when the Caching Module invalidates cached data based on different database operations:
155
156 <Table>
157 <Table.Header>
158 <Table.Row>
159 <Table.HeaderCell>
160 Database Operation
161 </Table.HeaderCell>
162 <Table.HeaderCell>
163 Invalidated Cache Tags
164 </Table.HeaderCell>
165 </Table.Row>
166 </Table.Header>
167 <Table.Body>
168 <Table.Row>
169 <Table.Cell>
170 Create
171 </Table.Cell>
172 <Table.Cell>
173 `Entity:list:*` (`Product:list:*`)
174 </Table.Cell>
175 </Table.Row>
176 <Table.Row>
177 <Table.Cell>
178 Update
179 </Table.Cell>
180 <Table.Cell>
181 `Entity:{id}`, `Entity:list:*` (`Product:prod_123`, `Product:list:*`)
182 </Table.Cell>
183 </Table.Row>
184 <Table.Row>
185 <Table.Cell>
186 Delete
187 </Table.Cell>
188 <Table.Cell>
189 `Entity:list:*` (`Product:list:*`)
190 </Table.Cell>
191 </Table.Row>
192 <Table.Row>
193 <Table.Cell>
194 Restore (soft-delete reversal)
195 </Table.Cell>
196 <Table.Cell>
197 `Entity:{id}`, `Entity:list:*` (`Product:prod_123`, `Product:list:*`)
198 </Table.Cell>
199 </Table.Row>
200 <Table.Row>
201 <Table.Cell>
202 Attach (link created)
203 </Table.Cell>
204 <Table.Cell>
205 `Entity:list:*` (`LinkProductVariantInventoryItem:list:*`)
206 </Table.Cell>
207 </Table.Row>
208 <Table.Row>
209 <Table.Cell>
210 Detach (link removed)
211 </Table.Cell>
212 <Table.Cell>
213 `Entity:list:*` (`LinkProductVariantInventoryItem:list:*`)
214 </Table.Cell>
215 </Table.Row>
216 </Table.Body>
217 </Table>
218
219 <Note>
220
221 The `Entity:list:*` tag is invalidated on every mutating operation because the mutation can change whether an entity matches a cached list's filters. For example, a product going from draft to published status would appear in a list filtered by published products. Since the cache layer has no way of knowing which fields are filter-relevant, it invalidates all list caches on every mutation.
222
223 Attach and detach operations (creating or removing a module link) only invalidate the `Entity:list:*` tag because a link row doesn't carry a usable entity `id` at attach time.
224
225 Restore is included because the entity re-enters every list it was soft-deleted out of.
226
227 </Note>
228
229 ### Which Data is Automatically Invalidated?
230
231 The Caching Module automatically invalidates your cached data when:
232
233 1. The data includes an `id` field. This is used internally to map the data to the corresponding cache tags.
234 - When retrieving data with Query or the Index Module, ensure the `id` field is included in the `fields` option.
235
236 ```ts
237 const { data: products } = useQueryGraphStep({
238 entity: "product",
239 fields: ["id", "title"], // Ensure 'id' is included, or pass '*'
240 options: {
241 cache: {
242 enable: true,
243 },
244 },
245 })
246 ```
247
248 - When caching custom data with the Caching Module's service, ensure the data object includes an `id` property.
249 2. Custom tags follow the [Caching Tags Convention](#caching-tags-convention).
250
251 ```ts
252 const data = { id: "prod_123", title: "Product 123" }
253 const key = await cachingModuleService.computeKey(data)
254 await cachingModuleService.set({
255 key,
256 tags: ["Product:prod_123", "Product:list:*"],
257 data,
258 })
259 ```
260
261 3. The `autoInvalidate` option is not set or is set to `true`. This option is enabled by default.
262
263 ```ts
264 const { data: products } = useQueryGraphStep({
265 entity: "product",
266 fields: ["id", "title"],
267 options: {
268 cache: {
269 enable: true,
270 // This is enabled by default
271 // autoInvalidate: true,
272 },
273 },
274 })
275 ```
276
277 ### Invalidation of Related Entities
278
279 If the cached data includes relations, and the relation is updated, the Caching Module also invalidates the cache tags for the related entity.
280
281 For example, consider the following Query usage:
282
283 ```ts
284 const { data: products } = useQueryGraphStep({
285 entity: "product",
286 fields: ["id", "title", "variants.*"],
287 options: {
288 cache: {
289 enable: true,
290 },
291 },
292 })
293 ```
294
295 If the product's variant is updated, the Caching Module invalidates the cache tags for both the `Product` and `ProductVariant` entities.
296
297 ### When to Disable Automatic Invalidation?
298
299 Disabling automatic invalidation means the data remains in the cache until it expires (based on the TTL) or is manually invalidated.
300
301 Consider disabling automatic invalidation in the following cases:
302
303 1. You're caching data that rarely changes, such as a list of countries.
304 2. You want to manage cache invalidation manually, such as when caching data as part of a custom workflow where you want to control when the cache is invalidated.
305 3. You're caching data that does not belong to a Medusa data model, such as data from an external API or computed values. This data is not automatically invalidated by default.
306
307 Disable automatic invalidation by setting the `autoInvalidate` option to `false` when caching data with Query, the Index Module, or the Caching Module's service.
308
309 When you disable automatic invalidation, manually [invalidate](/references/caching-service#clear) the cached data when it changes.
310
311 ---
312
313 ## Caching Best Practices
314
315 ### Cache Rarely-Changing Data
316
317 Cache data that is read frequently but changes infrequently, such as product information, categories, or static content.
318
319 Caching such data can significantly improve performance and reduce database load.
320
321 ### Do Not Cache Dynamic Data
322
323 Avoid caching data that changes frequently or is user-specific, such as shopping cart contents, user sessions, or product pricing.
324
325 Caching such data can lead to inconsistencies and stale information being served to users. It also increases bandwidth and memory usage, as the cache is updated frequently.
326
327 ### Do Not Cache Frequently Updated Data
328
329 Avoid caching data that is updated frequently, such as inventory levels or order statuses.
330
331 Caching such data increases the overhead of cache invalidation and may lead to performance degradation.