Raw
1 import { Prerequisites, Card } from "docs-ui"
2 import { Github } from "@medusajs/icons"
3
4 export const metadata = {
5 title: `Create Memcached Caching Module Provider`,
6 }
7
8 # {metadata.title}
9
10 In this tutorial, you'll learn how to create a Memcached [Caching Module Provider](../../providers/page.mdx) for your Medusa application.
11
12 [Memcached](https://memcached.org/) is a high-performance, distributed memory caching system that speeds up dynamic web applications by reducing database load.
13
14 By the end of this tutorial, you'll be able to cache data in your Medusa application using Memcached.
15
16 <Note>
17
18 Refer to the [Caching Module](../../page.mdx) documentation to learn more about caching in Medusa.
19
20 </Note>
21
22 ![Diagram illustrating the Memcached caching module provider in a Medusa application](https://res.cloudinary.com/dza7lstvk/image/upload/v1759925175/Medusa%20Resources/memcached-summary_ztlanl.jpg)
23
24 <Card
25 title="Full Code"
26 href="https://github.com/medusajs/examples/tree/main/memcached-caching"
27 text="Find the complete code on GitHub"
28 icon={Github}
29 />
30
31 ---
32
33 <Prerequisites
34 items={[
35 {
36 text: "Medusa Application",
37 href: "!docs!/learn/installation"
38 },
39 {
40 text: "Memcached server",
41 href: "https://memcached.org/",
42 }
43 ]}
44 />
45
46 ## 1. Install Memcached Client
47
48 To interact with Memcached, you'll need to install the `memjs` client. You can install it in your Medusa project by running the following command:
49
50 ```bash npm2yarn
51 npm install memjs
52 ```
53
54 ---
55
56 ## 2. Create Module Directory
57
58 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/memcached` in your Medusa project.
59
60 ---
61
62 ## 3. Create Memcached Connection Loader
63
64 Next, establish a connection to Memcached in your module using a [Loader](!docs!/learn/fundamentals/modules/loaders). A loader is an asynchronous function that runs when the module is initialized. It's useful for setting up connections to external services, such as databases or caching systems.
65
66 Create the file `src/modules/memcached/loaders/connection.ts` with the following content:
67
68 export const loaderHighlights = [
69 ["8", "serverUrls", "Memcached server URLs"],
70 ["9", "username", "Username for authentication"],
71 ["10", "password", "Password for authentication"],
72 ["11", "options", "Additional Memcached client options"],
73 ["12", "cachePrefix", "Prefix for cache keys"],
74 ["13", "defaultTtl", "Default time-to-live for cached items"],
75 ["14", "compression", "Compression settings"],
76 ["15", "enable", "Enable compression"],
77 ["16", "threshold", "Minimum size to compress"],
78 ["17", "level", "Compression level"],
79 ["39", "client", "Create Memcached client"],
80 ["47", "stats", "Test the connection to Memcached"],
81 ["59", "register", "Register the client in the container"],
82 ]
83
84 ```ts title="src/modules/memcached/loaders/connection.ts" highlights={loaderHighlights}
85 import { LoaderOptions } from "@medusajs/framework/types"
86 import * as memjs from "memjs"
87 import {
88 ContainerRegistrationKeys,
89 } from "@medusajs/framework/utils"
90
91 export type ModuleOptions = {
92 serverUrls?: string[]
93 username?: string
94 password?: string
95 options?: memjs.ClientOptions
96 cachePrefix?: string
97 defaultTtl?: number // Default TTL in seconds
98 compression?: {
99 enabled?: boolean
100 threshold?: number // Minimum size in bytes to compress
101 level?: number // Compression level (1-9)
102 }
103 }
104
105 export default async function connection({
106 container,
107 options,
108 }: LoaderOptions<ModuleOptions>) {
109 const logger = container.resolve(
110 ContainerRegistrationKeys.LOGGER
111 )
112 const {
113 serverUrls = ["127.0.0.1:11211"],
114 username,
115 password,
116 options: clientOptions,
117 } = options || {}
118
119 try {
120 logger.info("Connecting to Memcached...")
121
122 // Create Memcached client
123 const client = memjs.Client.create(serverUrls.join(","), {
124 username,
125 password,
126 ...clientOptions,
127 })
128
129 // Test the connection
130 await new Promise<void>((resolve, reject) => {
131 client.stats((err, stats) => {
132 if (err) {
133 logger.error("Failed to connect to Memcached:", err)
134 reject(err)
135 } else {
136 logger.info("Successfully connected to Memcached")
137 resolve()
138 }
139 })
140 })
141
142 // Register the client in the container
143 container.register({
144 memcachedClient: {
145 resolve: () => client,
146 },
147 })
148
149 } catch (error) {
150 logger.error("Failed to initialize Memcached connection:", error)
151 throw error
152 }
153 }
154 ```
155
156 You first define module options that are passed to the Memcached Module Provider. You'll set those up later when you [register the module in your Medusa application](#register-memcached-module-provider). The module accepts the following options:
157
158 - `serverUrls`: An array of Memcached server URLs. Defaults to `["127.0.0.1:11211"]`.
159 - `username`: The username for authenticating with the Memcached server (if required).
160 - `password`: The password for authenticating with the Memcached server (if required).
161 - `options`: Additional options to pass to the Memcached client.
162 - `cachePrefix`: A prefix to use for all cache keys to avoid collisions. Defaults to `"medusa"`.
163 - `defaultTtl`: The default time-to-live (TTL) for cached items, in seconds. Defaults to `3600` (1 hour).
164 - `compression`: Configuration for data compression:
165 - `enabled`: Whether to enable compression. Defaults to `true`.
166 - `threshold`: The minimum size in bytes for data to be compressed. Defaults to `2048` (2KB).
167 - `level`: The compression level (1-9). Defaults to `6`.
168
169 Then, export a loader function. This function receives an object with the following properties:
170
171 - `container`: The [Module container](!docs!/learn/fundamentals/modules/container) that holds Framework and module-specific resources.
172 - `options`: The options passed to the module when it's registered in the Medusa application.
173
174 In the loader, you create a Memcached client and test the connection. If the connection is successful, you register the client in the container, allowing you later to access it in the module's service.
175
176 ---
177
178 ## 4. Create Memcached Module Provider Service
179
180 You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can interact with third-party services to perform operations.
181
182 In this step, you'll create the service of the Memcached Module Provider. This service must implement the `ICachingProviderService` and implement its methods.
183
184 To create the service, create the file `src/modules/memcached/service.ts` with the following content:
185
186 export const serviceHighlights1 = [
187 ["25", "memcachedClient", "Resolve Memcached client from the module container."],
188 ["26", "options", "Options passed to the module provider."]
189 ]
190
191 ```ts title="src/modules/memcached/service.ts" highlights={serviceHighlights1}
192 import { ICachingProviderService } from "@medusajs/framework/types"
193 import * as memjs from "memjs"
194 import { ModuleOptions } from "./loaders/connection"
195
196 type InjectedDependencies = {
197 memcachedClient: memjs.Client
198 }
199
200 class MemcachedCachingProviderService implements ICachingProviderService {
201 static identifier = "memcached-cache"
202
203 protected client: memjs.Client
204 protected options_: ModuleOptions
205 protected readonly CACHE_PREFIX: string
206 protected readonly TAG_PREFIX: string
207 protected readonly OPTIONS_PREFIX: string
208 protected readonly KEY_TAGS_PREFIX: string
209 protected readonly TAG_KEYS_PREFIX: string
210 protected readonly compressionEnabled: boolean
211 protected readonly compressionThreshold: number
212 protected readonly compressionLevel: number
213 protected readonly defaultTtl: number
214
215 constructor(
216 { memcachedClient }: InjectedDependencies,
217 options: ModuleOptions
218 ) {
219 this.client = memcachedClient
220 this.options_ = options
221
222 // Set all prefixes with the main prefix
223 const mainPrefix = options.cachePrefix || "medusa"
224 this.CACHE_PREFIX = `${mainPrefix}:`
225 this.TAG_PREFIX = `${mainPrefix}:tag:`
226 this.OPTIONS_PREFIX = `${mainPrefix}:opt:`
227 this.KEY_TAGS_PREFIX = `${mainPrefix}:key_tags:`
228 this.TAG_KEYS_PREFIX = `${mainPrefix}:tag_keys:`
229
230 // Set compression options
231 this.compressionEnabled = options.compression?.enabled ?? true
232 this.compressionThreshold = options.compression?.threshold ?? 2048 // 2KB default
233 this.compressionLevel = options.compression?.level ?? 6 // Balanced compression
234
235 // Set default TTL
236 this.defaultTtl = options.defaultTtl ?? 3600 // 1 hour default
237 }
238 }
239 ```
240
241 You create the service that implements the `ICachingProviderService` interface. You define in the class some protected properties to hold dependencies, the Memcached client, and configuration options.
242
243 You also define a constructor in the service. Service constructors accept two parameters:
244
245 1. The Module container, from which you can resolve dependencies. In this case, you resolve the `memcachedClient` that you registered in the loader.
246 2. The options passed to the module when it's registered in the Medusa application.
247
248 You'll get a type error at this point because you haven't implemented the methods of the `ICachingProviderService` interface yet. You'll implement them next, along with utility methods.
249
250 ### Compression Utility Methods
251
252 Before implementing the caching methods, you'll implement two utility methods to handle data compression and decompression.
253
254 These methods use the `zlib` library to compress data before storing it in Memcached and decompress it when retrieving it. This optimizes storage and network usage, especially for large data.
255
256 First, add the following imports at the top of the file:
257
258 ```ts title="src/modules/memcached/service.ts"
259 import { deflate, inflate } from "zlib"
260 import { promisify } from "util"
261
262 const deflateAsync = promisify(deflate)
263 const inflateAsync = promisify(inflate)
264 ```
265
266 Then, add the following methods to the `MemcachedCachingProviderService` class:
267
268 ```ts title="src/modules/memcached/service.ts"
269 class MemcachedCachingProviderService implements ICachingProviderService {
270 // ...
271 private async compressData(data: string): Promise<{
272 data: string;
273 compressed: boolean
274 }> {
275 if (!this.compressionEnabled || data.length < this.compressionThreshold) {
276 return { data, compressed: false }
277 }
278
279 const buffer = Buffer.from(data, "utf8")
280 const compressed = await deflateAsync(buffer)
281 const compressedData = compressed.toString("base64")
282
283 // Only use compression if it actually reduces size
284 if (compressedData.length < data.length) {
285 return { data: compressedData, compressed: true }
286 }
287
288 return { data, compressed: false }
289 }
290
291 private async decompressData(
292 data: string,
293 compressed: boolean
294 ): Promise<string> {
295 if (!compressed) {
296 return data
297 }
298
299 const buffer = Buffer.from(data, "base64")
300 const decompressed = await inflateAsync(buffer)
301 return decompressed.toString("utf8")
302 }
303 }
304 ```
305
306 You define two private methods:
307
308 - `compressData`: Takes a string `data` as input and compresses it using `zlib.deflate` if compression is enabled and the data size exceeds the defined threshold. It returns an object containing the (possibly compressed) data and a boolean indicating whether compression was applied.
309 - `decompressData`: Takes a string `data` and a boolean `compressed` as input. If `compressed` is `true`, it decompresses the data using `zlib.inflate`. Otherwise, it returns the data as is.
310
311 ### Set Methods
312
313 Next, you'll implement the [set method](/references/caching-module-provider#set) of the `ICachingProviderService` interface. This method stores a value in the cache with an optional time-to-live (TTL) and associated tags.
314
315 #### setKeyTags Helper Method
316
317 Before implementing the method, you'll implement the helper method `setKeyTags`. Since Memcached doesn't support tagging natively, you'll need to manage tags manually by storing mappings between keys and tags.
318
319 Add the following method to the `MemcachedCachingProviderService` class:
320
321 ```ts title="src/modules/memcached/service.ts"
322 class MemcachedCachingProviderService implements ICachingProviderService {
323 // ...
324 private async setKeyTags(
325 key: string,
326 tags: string[],
327 setOptions: memjs.InsertOptions
328 ): Promise<void> {
329 const timestamp = Math.floor(Date.now() / 1000)
330 const tagNamespaces: Record<string, string> = {}
331 const operations: Promise<any>[] = []
332
333 // Batch all namespace operations
334 for (const tag of tags) {
335 const tagKey = this.TAG_PREFIX + tag
336 const tagKeysKey = `${this.TAG_KEYS_PREFIX}${tag}`
337
338 // Get namespace version
339 operations.push(
340 (async () => {
341 const result = await this.client.get(tagKey)
342 if (!result.value) {
343 tagNamespaces[tag] = timestamp.toString()
344 await this.client.add(tagKey, timestamp.toString())
345 } else {
346 tagNamespaces[tag] = result.value.toString()
347 }
348 })()
349 )
350
351 // Add key to tag's key list
352 operations.push(
353 (async () => {
354 const result = await this.client.get(tagKeysKey)
355 let keys: string[] = []
356 if (result.value) {
357 keys = JSON.parse(result.value.toString()) as string[]
358 }
359 if (!keys.includes(key)) {
360 keys.push(key)
361 await this.client.set(tagKeysKey, JSON.stringify(keys), setOptions)
362 }
363 })()
364 )
365 }
366
367 await Promise.all(operations)
368
369 // Store the tag namespaces for this key
370 const keyTagsKey = `${this.KEY_TAGS_PREFIX}${key}`
371 const serializedTags = JSON.stringify(tagNamespaces)
372 await this.client.set(keyTagsKey, serializedTags, setOptions)
373 }
374 }
375 ```
376
377 The `setKeyTags` method takes a cache `key`, an array of `tags`, and Memcached `setOptions`.
378
379 In the method, you:
380
381 1. Get the current timestamp to use as a namespace version for tags.
382 2. Iterate over the provided tags and for each tag:
383 - Retrieve the current namespace version from Memcached. If it doesn't exist, set it to the current timestamp.
384 - Retrieve the list of keys associated with the tag. If the current key is not in the list, add it and update the list in Memcached.
385 3. Store the mapping of tags and their namespace versions for the given key.
386
387 You'll use this method in the `set` method to manage tags when storing a value.
388
389 #### set Method
390
391 Add the following `set` method to the `MemcachedCachingProviderService` class:
392
393 ```ts title="src/modules/memcached/service.ts"
394 class MemcachedCachingProviderService implements ICachingProviderService {
395 // ...
396 async set({
397 key,
398 data,
399 ttl,
400 tags,
401 options,
402 }: {
403 key: string
404 data: any
405 ttl?: number
406 tags?: string[]
407 options?: { autoInvalidate?: boolean }
408 }): Promise<void> {
409 const prefixedKey = this.CACHE_PREFIX + key
410 const serializedData = JSON.stringify(data)
411 const setOptions: memjs.InsertOptions = {}
412
413 // Use provided TTL or default TTL
414 setOptions.expires = ttl ?? this.defaultTtl
415
416 // Compress data if enabled
417 const {
418 data: finalData,
419 compressed,
420 } = await this.compressData(serializedData)
421
422 // Batch operations for better performance
423 const operations: Promise<any>[] = [
424 this.client.set(prefixedKey, finalData, setOptions),
425 ]
426
427 // Always store options (including compression flag) to allow checking them later
428 const optionsKey = this.OPTIONS_PREFIX + key
429 const optionsData = { ...options, compressed }
430 operations.push(
431 this.client.set(optionsKey, JSON.stringify(optionsData), setOptions)
432 )
433
434 // Handle tags using namespace simulation with batching
435 if (tags && tags.length > 0) {
436 operations.push(this.setKeyTags(key, tags, setOptions))
437 }
438
439 await Promise.all(operations)
440 }
441 }
442 ```
443
444 The `set` method takes an object with the following properties:
445
446 - `key`: The cache key.
447 - `data`: The value to cache.
448 - `ttl`: Optional time-to-live for the cached value, in seconds.
449 - `tags`: Optional array of tags to associate with the cached value.
450 - `options`: Optional additional options, such as `autoInvalidate`, which indicates whether to automatically invalidate the cache based on tags.
451
452 In the method, you:
453
454 1. Store the value in Memcached with the specified TTL. You store the compressed data if compression is enabled and necessary.
455 2. Store the options (including whether the data was compressed) in a separate key to allow checking them later.
456 - This is necessary to determine whether the data can be automatically invalidated based on tags.
457 3. If tags are provided, call the `setKeyTags` method to set up the tag mappings.
458
459 You batch all operations using `Promise.all` for better performance.
460
461 ### Get Methods
462
463 Next, you'll implement the [get method](/references/caching-module-provider#get) of the `ICachingProviderService` interface. This method retrieves a value from the cache either by its key or by associated tags.
464
465 Before implementing the method, you need two helper methods.
466
467 #### validateKeyByTags Helper Method
468
469 The first helper method validates that a key is still valid based on its tags. You'll use this method when retrieving a value by its key to ensure that the value hasn't been invalidated by tag updates.
470
471 Add the following method to the `MemcachedCachingProviderService` class:
472
473 ```ts title="src/modules/memcached/service.ts"
474 class MemcachedCachingProviderService implements ICachingProviderService {
475 // ...
476 private async validateKeyByTags(key: string, tags: string[]): Promise<boolean> {
477 if (!tags || tags.length === 0) {
478 return true // No tags to validate
479 }
480
481 // Get the stored tag namespaces for this key
482 const keyTagsKey = `${this.KEY_TAGS_PREFIX}${key}`
483 const keyTagsResult = await this.client.get(keyTagsKey)
484
485 if (!keyTagsResult.value) {
486 return true // No stored tags, assume valid
487 }
488
489 const storedTags = JSON.parse(keyTagsResult.value.toString())
490
491 // Batch all namespace checks for better performance
492 const tagKeys = Object.keys(storedTags).map((tag) => this.TAG_PREFIX + tag)
493 const tagResults = await Promise.all(
494 tagKeys.map((tagKey) => this.client.get(tagKey))
495 )
496
497 // Check if any tag namespace is missing or changed
498 for (let i = 0; i < tagResults.length; i++) {
499 const tag = Object.keys(storedTags)[i]
500 const tagResult = tagResults[i]
501
502 if (tagResult.value) {
503 const currentTag = tagResult.value.toString()
504 // If the namespace has changed since the key was stored, it's invalid
505 if (currentTag !== storedTags[tag]) {
506 return false
507 }
508 } else {
509 // Namespace doesn't exist - this means it was reclaimed after being incremented
510 // This indicates the tag was cleared, so the key should be considered invalid
511 return false
512 }
513 }
514
515 return true
516 }
517 }
518 ```
519
520 The `validateKeyByTags` method accepts a cache `key` and an array of `tags`.
521
522 In the method, you:
523
524 - Retrieve from Memcached the tag namespaces for the given key.
525 - If no tags are stored, you assume the key is valid and return `true`.
526 - For each stored tag, retrieve its current namespace version from Memcached.
527 - Compare the current namespace version with the stored version. If any tag's namespace has changed or is missing, return `false`, indicating that the key is invalid. Otherwise, return `true`.
528
529 #### getByTags Helper Method
530
531 The second helper method retrieves the cached data associated with specified tags. You'll use this method when retrieving a value by tags.
532
533 Add the following method to the `MemcachedCachingProviderService` class:
534
535 ```ts title="src/modules/memcached/service.ts"
536 class MemcachedCachingProviderService implements ICachingProviderService {
537 // ...
538 private async getByTags(tags: string[]): Promise<any[] | null> {
539 if (!tags || tags.length === 0) {
540 return null
541 }
542
543 // Get all keys associated with each tag
544 const tagKeysOperations = tags.map((tag) => {
545 const tagKeysKey = `${this.TAG_KEYS_PREFIX}${tag}`
546 return this.client.get(tagKeysKey)
547 })
548
549 const tagKeysResults = await Promise.all(tagKeysOperations)
550
551 // Collect all unique keys from all tags
552 const allKeys = new Set<string>()
553 for (const result of tagKeysResults) {
554 if (result.value) {
555 const keys = JSON.parse(result.value.toString()) as string[]
556 keys.forEach((key) => allKeys.add(key))
557 }
558 }
559
560 if (allKeys.size === 0) {
561 return null
562 }
563
564 // Get all cached data for the collected keys
565 const dataOperations = Array.from(allKeys).map(async (key) => {
566 const prefixedKey = this.CACHE_PREFIX + key
567 const result = await this.client.get(prefixedKey)
568
569 if (!result.value) {
570 return { key, data: null }
571 }
572
573 const dataString = result.value.toString()
574
575 // Check if data is compressed
576 const optionsKey = this.OPTIONS_PREFIX + key
577 const optionsResult = await this.client.get(optionsKey)
578 let compressed = false
579
580 if (optionsResult.value) {
581 const options = JSON.parse(optionsResult.value.toString())
582 compressed = options.compressed || false
583 }
584
585 // Decompress if needed
586 const decompressedData = await this.decompressData(dataString, compressed)
587 return { key, data: JSON.parse(decompressedData) }
588 })
589
590 const dataResults = await Promise.all(dataOperations)
591
592 // Filter out null data and validate tags for each key
593 const validData: any[] = []
594 for (const { key, data } of dataResults) {
595 if (data !== null) {
596 // Validate that this key is still valid for the requested tags
597 const isValid = await this.validateKeyByTags(key, tags)
598 if (isValid) {
599 validData.push(data)
600 }
601 }
602 }
603
604 return Object.keys(validData).length > 0 ? validData : null
605 }
606 }
607 ```
608
609 The `getByTags` method takes an array of `tags`.
610
611 In the method, you:
612
613 - Retrieve from Memcached all keys associated with each tag. You collect all unique keys from the results.
614 - For each unique key, retrieve the cached data with its options.
615 - If the data is compressed, decompress it using the `decompressData` method.
616 - Validate each key using the `validateKeyByTags` method to ensure that the data is still valid based on its tags.
617 - Return an array of valid cached data or `null` if no valid data is found.
618
619 You can now implement the `get` method using these helper methods.
620
621 #### get Method
622
623 Add the `get` method to the `MemcachedCachingProviderService` class:
624
625 ```ts title="src/modules/memcached/service.ts"
626 class MemcachedCachingProviderService implements ICachingProviderService {
627 // ...
628 async get({
629 key,
630 tags,
631 }: {
632 key?: string
633 tags?: string[]
634 }): Promise<any> {
635 if (key) {
636 const prefixedKey = this.CACHE_PREFIX + key
637
638 // Get the stored tags for this key and validate them
639 const keyTagsKey = `${this.KEY_TAGS_PREFIX}${key}`
640 const keyTagsResult = await this.client.get(keyTagsKey)
641
642 if (keyTagsResult.value) {
643 const storedTags = JSON.parse(keyTagsResult.value.toString())
644 const tagNames = Object.keys(storedTags)
645
646 const isValid = await this.validateKeyByTags(key, tagNames)
647 if (!isValid) {
648 return null
649 }
650 }
651
652 const result = await this.client.get(prefixedKey)
653 if (result.value) {
654 const dataString = result.value.toString()
655
656 // Check if data is compressed (look for compression flag in options)
657 const optionsKey = this.OPTIONS_PREFIX + key
658 const optionsResult = await this.client.get(optionsKey)
659 let compressed = false
660
661 if (optionsResult.value) {
662 const options = JSON.parse(optionsResult.value.toString())
663 compressed = options.compressed || false
664 }
665
666 // Decompress if needed
667 const decompressedData = await this.decompressData(dataString, compressed)
668 return JSON.parse(decompressedData)
669 }
670 return null
671 }
672
673 if (tags && tags.length > 0) {
674 // Retrieve data by tags - get all keys associated with the tags
675 return await this.getByTags(tags)
676 }
677
678 return null
679 }
680 }
681 ```
682
683 The `get` method takes an object with optional `key` and `tags` properties.
684
685 In the method:
686
687 - If a `key` is provided, you give it a higher priority and retrieve the cached value for that key.
688 - You first check if the key has associated tags and validate them using the `validateKeyByTags` method, ensuring the cached value is still valid.
689 - You decompress the data if it was stored in a compressed format.
690 - If the key is not found or is invalid, you return `null`. Otherwise, you return the cached value.
691 - If no `key` is provided but `tags` are, you call the `getByTags` method to retrieve all cached values associated with the provided tags.
692 - If neither `key` nor `tags` are provided, you return `null`.
693
694 ### Clear Methods
695
696 Finally, you'll implement the [clear method](/references/caching-module-provider#clear) of the `ICachingProviderService` interface.
697
698 The `clear` method removes a cached value either by its key or by associated tags. It also receives an optional `options` parameter to control whether to automatically invalidate the cache based on tags:
699
700 - If `options` isn't set, you clear all cached values associated with the provided tags.
701 - If `options.autoInvalidate` is `true`, you only invalidate the keys of the provided tags whose options allow automatic invalidation.
702
703 Before implementing the `clear` method, you'll implement four helper methods to handle tag and key invalidation.
704
705 #### removeKeysFromTag Helper Method
706
707 The `removeKeysFromTag` method removes a list of keys from a tag's key list in Memcached. This is useful when invalidating by key or when clearing keys associated with a tag.
708
709 Add the following method to the `MemcachedCachingProviderService` class:
710
711 ```ts title="src/modules/memcached/service.ts"
712 class MemcachedCachingProviderService implements ICachingProviderService {
713 // ...
714 private async removeKeysFromTag(tag: string, keysToRemove: string[]): Promise<void> {
715 const tagKeysKey = `${this.TAG_KEYS_PREFIX}${tag}`
716 const tagKeysResult = await this.client.get(tagKeysKey)
717
718 if (!tagKeysResult.value) {
719 return // No keys to remove
720 }
721
722 let keys: string[] = JSON.parse(tagKeysResult.value.toString()) as string[]
723
724 // Remove the specified keys
725 keys = keys.filter((key) => !keysToRemove.includes(key))
726
727 if (keys.length === 0) {
728 // If no keys left, delete the tag keys entry
729 await this.client.delete(tagKeysKey)
730 } else {
731 // Update the tag keys list
732 await this.client.set(tagKeysKey, JSON.stringify(keys))
733 }
734 }
735 }
736 ```
737
738 The `removeKeysFromTag` method takes a `tag` and an array of `keysToRemove`.
739
740 In the method, you:
741
742 1. Retrieve the list of keys associated with the tag from Memcached.
743 2. Filter out the keys that need to be removed.
744 3. If no keys are left, delete the tag's key list entry. Otherwise, update the list in Memcached.
745
746 #### clearByKey Helper Method
747
748 Next, you'll implement the `clearByKey` method. It removes a cached value by its key and updates the associated tags to remove the key from their key lists.
749
750 Add the following method to the `MemcachedCachingProviderService` class:
751
752 ```ts title="src/modules/memcached/service.ts"
753 class MemcachedCachingProviderService implements ICachingProviderService {
754 // ...
755 private async clearByKey(key: string): Promise<void> {
756 // Get the key's tags before deleting to clean up tag key lists
757 const keyTagsKey = `${this.KEY_TAGS_PREFIX}${key}`
758 const keyTagsResult = await this.client.get(keyTagsKey)
759
760 const operations: Promise<any>[] = [
761 this.client.delete(this.CACHE_PREFIX + key),
762 this.client.delete(this.OPTIONS_PREFIX + key),
763 this.client.delete(keyTagsKey),
764 ]
765
766 // If the key has tags, remove it from tag key lists
767 if (keyTagsResult.value) {
768 const storedTags = JSON.parse(keyTagsResult.value.toString())
769 const tagNames = Object.keys(storedTags)
770
771 // Batch tag cleanup operations
772 const tagCleanupOperations = tagNames.map(async (tag) => {
773 await this.removeKeysFromTag(tag, [key])
774 })
775 operations.push(...tagCleanupOperations)
776 }
777
778 await Promise.all(operations)
779 }
780 }
781 ```
782
783 The `clearByKey` method takes a cache `key`.
784
785 In the method, you:
786
787 1. Retrieve the tags associated with the key before deleting it.
788 2. Delete the cached value, its options, and the key's tag mapping from Memcached.
789 3. If the key has associated tags, call the `removeKeysFromTag` method for each tag to remove the key from their key lists.
790 4. Batch all operations using `Promise.all` for better performance.
791
792 #### clearByTags Helper Method
793
794 Next, you'll implement the `clearByTags` method. It removes all cached values associated with the provided tags. You'll use this method when the `options` parameter isn't set in the `clear` method.
795
796 Add the following method to the `MemcachedCachingProviderService` class:
797
798 ```ts title="src/modules/memcached/service.ts"
799 class MemcachedCachingProviderService implements ICachingProviderService {
800 // ...
801 private async clearByTags(tags: string[]): Promise<void> {
802 const operations = tags.map(async (tag) => {
803 const tagKey = this.TAG_PREFIX + tag
804 const result = await this.client.increment(tagKey, 1)
805 if (result === null) {
806 // Key doesn't exist, create it with current timestamp
807 const timestamp = Math.floor(Date.now() / 1000)
808 await this.client.add(tagKey, timestamp.toString())
809 }
810 })
811
812 await Promise.all(operations)
813 }
814 }
815 ```
816
817 The `clearByTags` method takes an array of `tags`.
818
819 In the method, you loop over the tags to increment their namespace versions in Memcached. If a tag's namespace doesn't exist, you create it with the current timestamp.
820
821 By incrementing the namespace version, you effectively invalidate the tag and all associated keys, as they will no longer match the stored namespace versions. The namespace version will also be replaced in Memcached after being reclaimed.
822
823 <Note title="Tip">
824
825 Learn more about this invalidation strategy in [Memcached's documentation](https://docs.memcached.org/userguide/usecases/).
826
827 </Note>
828
829 #### clearByTagsWithAutoInvalidate Helper Method
830
831 The `clearByTagsWithAutoInvalidate` method removes cached values associated with the provided tags, but only for keys whose options allow automatic invalidation. You'll use this method when the `options.autoInvalidate` parameter is `true` in the `clear` method.
832
833 Add the following method to the `MemcachedCachingProviderService` class:
834
835 ```ts title="src/modules/memcached/service.ts"
836 class MemcachedCachingProviderService implements ICachingProviderService {
837 // ...
838 private async clearByTagsWithAutoInvalidate(tags: string[]): Promise<void> {
839 for (const tag of tags) {
840 // Get the list of keys associated with this tag
841 const tagKeysKey = `${this.TAG_KEYS_PREFIX}${tag}`
842 const tagKeysResult = await this.client.get(tagKeysKey)
843
844 if (!tagKeysResult.value) {
845 continue
846 }
847
848 const keys = JSON.parse(tagKeysResult.value.toString()) as string[]
849
850 // Check each key's options and delete if autoInvalidate is true
851 const keysToRemove: string[] = []
852 for (const key of keys) {
853 const optionsKey = `${this.OPTIONS_PREFIX}${key}`
854 const optionsResult = await this.client.get(optionsKey)
855
856 if (optionsResult.value) {
857 const options = JSON.parse(optionsResult.value.toString())
858 if (options.autoInvalidate) {
859 // Delete the key and its associated data
860 await this.client.delete(this.CACHE_PREFIX + key)
861 await this.client.delete(optionsKey)
862 await this.client.delete(`${this.KEY_TAGS_PREFIX}${key}`)
863 keysToRemove.push(key)
864 }
865 }
866 }
867
868 // Remove deleted keys from the tag's key list
869 if (keysToRemove.length > 0) {
870 await this.removeKeysFromTag(tag, keysToRemove)
871 }
872 }
873 }
874 }
875 ```
876
877 You define the `clearByTagsWithAutoInvalidate` method, which takes an array of `tags`.
878
879 In the method, you loop over the tags to:
880
881 1. Retrieve the list of keys associated with each tag from Memcached.
882 2. For each key, retrieve its options and check if `autoInvalidate` is `true`.
883 3. If `autoInvalidate` is `true`, delete the cached value, its options, and its tag mapping from Memcached. You also keep track of the keys that were deleted.
884 4. After processing all keys for a tag, call the `removeKeysFromTag` method to remove the deleted keys from the tag's key list.
885
886 #### clear Method
887
888 Finally, add the `clear` method to the `MemcachedCachingProviderService` class:
889
890 ```ts title="src/modules/memcached/service.ts"
891 class MemcachedCachingProviderService implements ICachingProviderService {
892 // ...
893 async clear({
894 key,
895 tags,
896 options,
897 }: {
898 key?: string
899 tags?: string[]
900 options?: { autoInvalidate?: boolean }
901 }): Promise<void> {
902 if (key) {
903 await this.clearByKey(key)
904 }
905
906 if (tags?.length) {
907 if (!options) {
908 // Clear all items with the specified tags
909 await this.clearByTags(tags)
910 } else if (options.autoInvalidate) {
911 // Clear only items with autoInvalidate option set to true
912 await this.clearByTagsWithAutoInvalidate(tags)
913 }
914 }
915 }
916 }
917 ```
918
919 The `clear` method takes an object with optional `key`, `tags`, and `options` properties.
920
921 In the method:
922
923 - If a `key` is provided, you call the `clearByKey` method to remove the cached value and update associated tags.
924 - If `tags` are provided:
925 - If `options` isn't set, you call the `clearByTags` method to invalidate all cached values associated with the tags.
926 - If `options.autoInvalidate` is `true`, you call the `clearByTagsWithAutoInvalidate` method to invalidate only the keys whose options allow automatic invalidation.
927
928 You've now implemented all methods of the `ICachingProviderService` interface in the `MemcachedCachingProviderService` class.
929
930 ---
931
932 ## 5. Export Memcached Module Provider Definition
933
934 The final piece of a module provider is its definition, which you export in an `index.ts` file at its root directory. This definition tells Medusa which module this provider belongs to, its loaders, and its service.
935
936 Create the file `src/modules/memcached/index.ts` with the following content:
937
938 ```ts title="src/modules/memcached/index.ts"
939 import { ModuleProvider, Modules } from "@medusajs/framework/utils"
940 import MemcachedCachingProviderService from "./service"
941 import connection from "./loaders/connection"
942
943 export default ModuleProvider(Modules.CACHING, {
944 services: [MemcachedCachingProviderService],
945 loaders: [connection],
946 })
947 ```
948
949 You use the `ModuleProvider` function from the Modules SDK to create the module provider's definition. It accepts two parameters:
950
951 1. The module this provider belongs to. In this case, the `Modules.CACHING` module.
952 2. An object with the provider's `services` and `loaders`.
953
954 ---
955
956 ## 6. Register Memcached Module Provider
957
958 The last step is to register the Memcached Module Provider in your Medusa application.
959
960 ### Enable Caching Feature Flag
961
962 First, enable the [Caching Module's feature flag](../../page.mdx#1-enable-caching-feature-flag) by setting the following environment variable:
963
964 ```bash
965 MEDUSA_FF_CACHING=true
966 ```
967
968 ### Register Memcached Module Provider
969
970 Then, in `medusa-config.ts`, add a new entry in the `modules` array to register the Memcached Module Provider:
971
972 ```ts title="medusa-config.ts"
973 module.exports = defineConfig({
974 // ...
975 modules: [
976 {
977 resolve: "@medusajs/medusa/caching",
978 options: {
979 in_memory: {
980 enable: true,
981 },
982 providers: [
983 {
984 resolve: "./src/modules/memcached",
985 id: "caching-memcached",
986 // Optional, makes this the default caching provider
987 is_default: true,
988 options: {
989 serverUrls: process.env.MEMCACHED_SERVERS?.split(",") ||
990 ["127.0.0.1:11211"],
991 // add other optional options here...
992 },
993 },
994 // other caching providers...
995 ],
996 },
997 },
998 ],
999 })
1000 ```
1001
1002 You register the `@medusajs/medusa/caching` module and add the Memcached Module Provider to its `providers` array.
1003
1004 You pass the options to configure the Memcached client and the module's behavior. These are the same [options you defined in the ModuleOptions type in the loader](#3-create-memcached-connection-loader).
1005
1006 ### Add Environment Variables
1007
1008 Make sure you set the necessary environment variables in your `.env` file. For example:
1009
1010 ```bash
1011 MEMCACHED_SERVERS=127.0.0.1:11211 # Comma-separated list of Memcached server URLs
1012 # Add other optional variables as needed
1013 ```
1014
1015 You set the `MEMCACHED_SERVERS` variable to specify the Memcached server URLs. You can also set other optional variables like `MEMCACHED_USERNAME` and `MEMCACHED_PASSWORD` based on your use case.
1016
1017 ---
1018
1019 ## Test the Memcached Caching Provider
1020
1021 To test that the Memcached Caching Provider is working, start the Medusa application with the following command:
1022
1023 ```bash npm2yarn
1024 npm run dev
1025 ```
1026
1027 You'll see in the logs that the Memcached connection is established successfully:
1028
1029 ```bash
1030 info: Connecting to Memcached...
1031 info: Successfully connected to Memcached
1032 ```
1033
1034 If you set the `is_default` option to `true` in the provider registration, the Memcached Caching Provider will be used for all caching operations in the Medusa application.
1035
1036 ### Create Test API Route
1037
1038 To verify that the caching is working, you can create a simple [API route](!docs!/learn/fundamentals/api-routes) that retrieves data with caching.
1039
1040 To create an API route, create a new file at `src/api/test-cache/route.ts` with the following content:
1041
1042 ```ts title="src/api/test-cache/route.ts"
1043 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
1044 import {
1045 ContainerRegistrationKeys,
1046 } from "@medusajs/framework/utils"
1047
1048 export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
1049 const query = req.scope.resolve(
1050 ContainerRegistrationKeys.QUERY
1051 )
1052
1053 // Test caching with a simple query
1054 const { data } = await query.graph({
1055 entity: "product",
1056 fields: ["id", "title", "handle"],
1057 }, {
1058 cache: {
1059 enable: true,
1060 // For testing purposes
1061 key: "test-cache-products",
1062 // If you didn't set is_default to true, uncomment the following line
1063 // providers: ["caching-memcached"],
1064 },
1065 })
1066
1067 res.status(200).json({
1068 message: "Products retrieved with Memcached caching",
1069 data,
1070 })
1071 }
1072 ```
1073
1074 This creates a `GET` route at `/test-cache` that retrieves products using Query with caching enabled. The `key` so that you can easily check the cached data in Memcached for testing purposes.
1075
1076 Then, send a `GET` request to the `/test-cache` endpoint:
1077
1078 ```bash
1079 curl http://localhost:9000/test-cache
1080 ```
1081
1082 You'll receive the list of products in the response.
1083
1084 You can then check that the data is cached in Memcached using the [memcached-cli](https://github.com/pd4d10/memcached-cli) tool.
1085
1086 First, establish a connection to your Memcached server:
1087
1088 ```bash npx2yarn
1089 npx memcached-cli localhost:11211 # Replace with your Memcached server URL
1090 ```
1091
1092 Then, retrieve the cached data using the key you specified in the API route:
1093
1094 ```bash
1095 get medusa:test-cache-products
1096 ```
1097
1098 Notice that you prefix the key with `medusa:`, which is the default prefix unless you set the `keyPrefix` option in the provider registration.
1099
1100 ---
1101
1102 ## Next Steps
1103
1104 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth understanding of all the concepts you've used in this guide and more.
1105
1106 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../../commerce-modules/page.mdx).
1107
1108 ### Troubleshooting
1109
1110 If you encounter issues during your development, check out the [troubleshooting guides](../../../../troubleshooting/page.mdx).
1111
1112 ### Getting Help
1113
1114 If you encounter issues not covered in the troubleshooting guides:
1115
1116 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
1117 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.