Raw
1 export const metadata = {
2 title: `${pageNumber} Best Practices for Third-Party Syncing`,
3 }
4
5 # {metadata.title}
6
7 In this chapter, you'll learn about best practices for syncing data between Medusa and third-party systems.
8
9 ## Common Issues with Third-Party Syncing Implementation
10
11 Syncing data between Medusa and external systems is a common use case for commerce applications. For example, if your commerce ecosystem includes an external CMS or inventory management system, you may need to sync product data between Medusa and these systems.
12
13 However, how you implement third-party syncing can significantly impact performance and memory usage. Syncing large amounts of data without proper handling can lead to issues like:
14
15 - Out-of-memory (OOM) errors.
16 - Slow syncs that block the event loop and degrade application performance.
17 - Application crashes in production.
18
19 This chapter covers best practices to avoid these issues when syncing data between Medusa and third-party systems. These best practices are general programming patterns that aren't Medusa-specific, but they're essential for building robust third-party syncs.
20
21 ---
22
23 ## How to Sync Data Between Systems
24
25 Before diving into best practices, it's important to understand the general approach for syncing data between Medusa and third-party systems. Third-party syncing typically involves two main steps:
26
27 1. Define the syncing logic in a [workflow](../../fundamentals/workflows/page.mdx).
28 2. Execute the workflow from either a [scheduled job](../../fundamentals/scheduled-jobs/page.mdx) or a [subscriber](../../fundamentals/events-and-subscribers/page.mdx).
29
30 ### Define Syncing Logic in a Workflow
31
32 [Workflows](../../fundamentals/workflows/page.mdx) are special functions designed for long-running, asynchronous tasks. They provide features like [compensation](../../fundamentals/workflows/compensation-function/page.mdx), [retries](../../fundamentals/workflows/retry-failed-steps/page.mdx), and [async execution](../../fundamentals/workflows/long-running-workflow/page.mdx) that are essential for reliable data syncing.
33
34 When defining your syncing logic, such as pushing product data to a third-party service or pulling inventory data into Medusa, you should define a workflow that encapsulates this logic.
35
36 Medusa also exposes [built-in workflows](!resources!/medusa-workflows-reference) for common commerce operations, like creating or updating products, that you can leverage in your syncing logic.
37
38 For example, you can use Medusa's built-in [batchProductsWorkflow](!resources!/references/medusa-workflows/batchProductsWorkflow) to create or update products in batches:
39
40 ```ts title="src/jobs/sync-products.ts"
41 import { MedusaContainer } from "@medusajs/framework/types"
42 import { batchProductsWorkflow } from "@medusajs/medusa/core-flows"
43
44 export default async function syncProductsJob(container: MedusaContainer) {
45 // ...
46 await batchProductsWorkflow(container).run({
47 input: {
48 create: productsToCreate,
49 update: productsToUpdate,
50 },
51 })
52 }
53 ```
54
55 ### Execute Workflows from Scheduled Jobs or Subscribers
56
57 After defining your syncing logic in a workflow, or choosing a Medusa workflow to use, you need to execute it based on your syncing requirements:
58
59 - [Scheduled Jobs](../../fundamentals/scheduled-jobs/page.mdx): Use scheduled jobs for periodic syncs, such as syncing products daily or inventory hourly. Scheduled jobs run at specified intervals and can trigger your workflow to perform the sync.
60 - [Subscribers](../../fundamentals/events-and-subscribers/page.mdx): Use subscribers for event-driven syncs, such as syncing data when a product is updated in Medusa or when an order is placed. Subscribers listen for specific events and can trigger your workflow in response.
61
62 If you've set up [server and worker instances](../../production/worker-mode/page.mdx), the worker will handle the execution. So, the syncing execution won't block the main server process.
63
64 <Note title="Tip">
65
66 [Cloud](!cloud!) creates server and worker instances for your project automatically, so you don't need to set this up manually.
67
68 </Note>
69
70 In the scheduled job or subscriber, you retrieve the data to be synced from the third-party service or from Medusa itself. Then, you execute the workflow, passing it the data to be synced.
71
72 For example, the following scheduled job fetches products from a third-party service and syncs them to Medusa using a workflow:
73
74 ```ts title="src/jobs/sync-products.ts"
75 import { MedusaContainer } from "@medusajs/framework/types"
76 import { batchProductsWorkflow } from "@medusajs/medusa/core-flows"
77
78 export default async function syncProductsJob(container: MedusaContainer) {
79 const productStream = streamProductsFromApi()
80 const batchedProducts = batchProducts(productStream, 50)
81
82 for await (const batch of batchedProducts) {
83 const {
84 productsToCreate,
85 productsToUpdate,
86 } = await prepareProducts(batch)
87
88 await batchProductsWorkflow(container).run({
89 input: {
90 create: productsToCreate,
91 update: productsToUpdate,
92 },
93 })
94 }
95 }
96 ```
97
98 You'll learn about best practices for implementing the data fetching, batching, and preparation logic in the next sections.
99
100 ---
101
102 ## Syncing Best Practices
103
104 The following sections cover best practices for implementing third-party syncing in a way that minimizes memory usage, maximizes performance, and ensures reliability.
105
106 <Details summaryContent="Full Scheduled Job Code">
107
108 The following sections take snippets from this complete example of a high-performance, memory-efficient product synchronization job that incorporates all the best practices discussed:
109
110 ```ts title="src/jobs/sync-products.ts"
111 import { MedusaContainer } from "@medusajs/framework/types"
112 import { ContainerRegistrationKeys, MedusaError, Modules } from "@medusajs/framework/utils"
113 import { batchProductsWorkflow } from "@medusajs/medusa/core-flows"
114 import { Readable } from "stream"
115 import { parser } from "stream-json"
116 import { pick } from "stream-json/filters/Pick"
117 import { streamArray } from "stream-json/streamers/StreamArray"
118 import { chain } from "stream-chain"
119
120 const API_FETCH_SIZE = 200
121 const PROCESS_BATCH_SIZE = 50
122 const MAX_RETRIES = 3
123 const RETRY_DELAY_MS = 1000
124 const FETCH_TIMEOUT_MS = 30000
125
126 async function fetchWithRetry(
127 url: string,
128 retries = MAX_RETRIES
129 ): Promise<Response> {
130 let lastError: Error | null = null
131
132 for (let attempt = 1; attempt <= retries; attempt++) {
133 try {
134 const controller = new AbortController()
135 const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
136
137 const response = await fetch(url, {
138 signal: controller.signal,
139 // Keep connection alive for efficiency with multiple requests
140 headers: {
141 "Connection": "keep-alive",
142 },
143 })
144
145 clearTimeout(timeoutId)
146
147 if (!response.ok) {
148 throw new MedusaError(
149 MedusaError.Types.UNEXPECTED_STATE,
150 `HTTP ${response.status}: ${response.statusText}`
151 )
152 }
153
154 return response
155 } catch (error: any) {
156 lastError = error
157 const isRetryable =
158 error.code === "UND_ERR_SOCKET" ||
159 error.code === "ECONNREFUSED" ||
160 error.code === "ECONNRESET" ||
161 error.code === "ETIMEDOUT" ||
162 error.name === "AbortError"
163
164 if (isRetryable && attempt < retries) {
165 // Exponential backoff: 1s → 2s → 4s
166 const delay = RETRY_DELAY_MS * Math.pow(2, attempt - 1)
167 await new Promise((resolve) => setTimeout(resolve, delay))
168 } else {
169 break
170 }
171 }
172 }
173
174 throw lastError
175 }
176
177 /**
178 * Streams products from the external API using incremental JSON parsing
179 * Products are yielded one by one as they're parsed from the response stream
180 */
181 async function* streamProductsFromApi() {
182 let offset = 0
183 let hasMore = true
184
185 while (hasMore) {
186 const url = `https://third-party-api.com/products?limit=${API_FETCH_SIZE}&offset=${offset}`
187
188 const response = await fetchWithRetry(url)
189
190 // Convert web ReadableStream to Node.js Readable
191 const nodeStream = Readable.fromWeb(response.body as any)
192
193 // Create a streaming JSON parser pipeline that:
194 // 1. Parses JSON incrementally
195 // 2. Picks only the "products" array
196 // 3. Streams each array item individually
197 const pipeline = chain([
198 nodeStream,
199 parser(),
200 pick({ filter: "products" }),
201 streamArray(),
202 ])
203
204 let productCount = 0
205
206 // Yield each product as it's parsed - memory stays constant
207 try {
208 for await (const { value } of pipeline) {
209 yield value
210 productCount++
211
212 // Yield to event loop periodically to prevent blocking
213 if (productCount % 100 === 0) {
214 await new Promise((resolve) => setImmediate(resolve))
215 }
216 }
217 } catch (streamError: any) {
218 // Handle stream errors (socket closed mid-stream)
219 if (streamError.code === "UND_ERR_SOCKET" || streamError.code === "ECONNRESET") {
220 throw new MedusaError(
221 MedusaError.Types.UNEXPECTED_STATE,
222 `Stream interrupted after ${productCount} products: ${streamError.message}`
223 )
224 }
225 throw streamError
226 }
227
228 // If the products are less than expected, there are no more products
229 if (productCount < API_FETCH_SIZE) {
230 hasMore = false
231 } else {
232 offset += productCount
233 }
234 }
235 }
236
237 /**
238 * Collects products into batches of the specified size
239 */
240 async function* batchProducts(
241 products: AsyncGenerator,
242 batchSize: number
243 ): AsyncGenerator<any[]> {
244 let batch: any[] = []
245
246 for await (const product of products) {
247 batch.push(product)
248
249 if (batch.length >= batchSize) {
250 yield batch
251 // Release reference for GC
252 batch = []
253 }
254 }
255
256 // Yield remaining products
257 if (batch.length > 0) {
258 yield batch
259 }
260 }
261
262 export default async function syncProductsJob(container: MedusaContainer) {
263 const query = container.resolve(ContainerRegistrationKeys.QUERY)
264 const workflowEngine = container.resolve(Modules.WORKFLOW_ENGINE)
265
266 let totalCreated = 0
267 let totalUpdated = 0
268 let batchNumber = 0
269
270 // Stream products from API and process in batches
271 // Memory stays constant - we only hold PROCESS_BATCH_SIZE products at a time
272 const productStream = streamProductsFromApi()
273 const batchedProducts = batchProducts(productStream, PROCESS_BATCH_SIZE)
274
275 for await (const batch of batchedProducts) {
276 batchNumber++
277
278 // Extract external IDs from this batch to look up in Medusa
279 const externalIds = batch.map((p) => p.id)
280
281 // Query Medusa for products matching these external IDs
282 const { data: existingProducts } = await query.graph(
283 {
284 entity: "product",
285 fields: ["id", "updated_at", "external_id"],
286 filters: {
287 external_id: externalIds,
288 },
289 }
290 )
291
292 // Build a map for quick lookup
293 const existingByExternalId = new Map(
294 existingProducts.map((p) => [p.external_id, {
295 id: p.id,
296 updatedAt: p.updated_at,
297 }])
298 )
299
300 const productsToCreate: any[] = []
301 const productsToUpdate: any[] = []
302
303 for (const externalProduct of batch) {
304 const existing = existingByExternalId.get(externalProduct.id)
305
306 if (existing) {
307 // Product exists - prepare update
308 productsToUpdate.push({
309 id: existing.id,
310 title: externalProduct.title,
311 description: externalProduct.description ?? undefined,
312 metadata: {
313 external_id: externalProduct.id,
314 last_synced: new Date().toISOString(),
315 },
316 })
317 } else {
318 // New product - prepare create
319 productsToCreate.push({
320 title: externalProduct.title,
321 description: externalProduct.description ?? undefined,
322 handle: externalProduct.handle,
323 status: "draft",
324 metadata: {
325 external_id: externalProduct.id,
326 last_synced: new Date().toISOString(),
327 },
328 options: [
329 {
330 title: "Default",
331 values: ["Default"],
332 },
333 ],
334 variants: externalProduct.variants.map((v) => ({
335 title: v.title ?? "Default Variant",
336 sku: v.sku ?? undefined,
337 options: {
338 Default: "Default",
339 },
340 prices: [
341 {
342 amount: v.price,
343 currency_code: "usd",
344 },
345 ],
346 })),
347 })
348 }
349 }
350
351 // Execute batch workflow for this batch
352 if (productsToCreate.length > 0 || productsToUpdate.length > 0) {
353 await batchProductsWorkflow(container).run({
354 input: {
355 create: productsToCreate,
356 update: productsToUpdate,
357 },
358 })
359
360 totalCreated += productsToCreate.length
361 totalUpdated += productsToUpdate.length
362 }
363 // Yield to event loop between batches
364 await new Promise((resolve) => setImmediate(resolve))
365 }
366 }
367
368 export const config = {
369 name: "sync-products",
370 schedule: "0 0 * * *", // Run at midnight every day
371 }
372 ```
373
374 </Details>
375
376 ### Stream Data from External APIs
377
378 When retrieving data from external APIs using `fetch`, the common approach is to fetch the data and load it entirely into memory using `response.json()`. For example:
379
380 ```ts
381 const response = await fetch("https://third-party-api.com/products")
382 // Load entire response into memory
383 const data = await response.json()
384 ```
385
386 However, this can lead to high memory usage and performance issues, especially with large datasets.
387
388 Instead, process data in streams or batches. This approach allows you to handle large datasets without loading everything into memory at once. You can use libraries like [stream-json](https://www.npmjs.com/package/stream-json) to parse JSON data incrementally as it's received.
389
390 ![Diagram showcasing object in memory when loading entire JSON response vs streaming JSON parsing](https://res.cloudinary.com/dza7lstvk/image/upload/v1764761087/Medusa%20Book/stream-vs-full_iz2fyv.jpg)
391
392 First, install the `stream-json` library in your Medusa project:
393
394 ```bash npm2yarn
395 npm install stream-json @types/stream-json
396 ```
397
398 Then, use it in your scheduled job or subscriber to stream and parse JSON data from the third-party service:
399
400 export const streamDataHighlights = [
401 ["19", "nodeStream", "Create a Node.js Readable stream from the response body"],
402 ["25", "pipeline", "Set up a streaming JSON parser pipeline"],
403 ["36", "for await", "Yield each product one at a time as it's parsed"],
404 ]
405
406 ```ts title="src/jobs/sync-products.ts" highlights={streamDataHighlights}
407 import { Readable } from "stream"
408 import { parser } from "stream-json"
409 import { pick } from "stream-json/filters/Pick"
410 import { streamArray } from "stream-json/streamers/StreamArray"
411 import { chain } from "stream-chain"
412
413 const API_FETCH_SIZE = 200
414
415 async function* streamProductsFromApi() {
416 let offset = 0
417 let hasMore = true
418
419 while (hasMore) {
420 const url = `https://third-party-api.com/products?limit=${API_FETCH_SIZE}&offset=${offset}`
421 // TODO: Add retry with exponential backoff
422 const response = await fetch(url)
423
424 // Convert web ReadableStream to Node.js Readable
425 const nodeStream = Readable.fromWeb(response.body as any)
426
427 // Create a streaming JSON parser pipeline that:
428 // 1. Parses JSON incrementally
429 // 2. Picks only the "products" array
430 // 3. Streams each array item individually
431 const pipeline = chain([
432 nodeStream,
433 parser(),
434 pick({ filter: "products" }),
435 streamArray(),
436 ])
437
438 let productCount = 0
439
440 try {
441 // Yield each product one at a time
442 for await (const { value } of pipeline) {
443 yield value
444 productCount++
445
446 // TODO: Yield to event loop periodically to prevent blocking
447 }
448 } catch (streamError: any) {
449 // TODO: Handle stream errors
450 }
451
452 // If the products are less than expected, there are no more products
453 if (productCount < API_FETCH_SIZE) {
454 hasMore = false
455 } else {
456 offset += productCount
457 }
458 }
459 }
460
461 export default async function syncProductsJob(container: MedusaContainer) {
462 const productStream = streamProductsFromApi()
463 // ...
464 }
465 ```
466
467 In the above snippet, you set up a streaming JSON parser that processes the API response incrementally. Instead of loading the entire response into memory, the parser yields each product one at a time.
468
469 This approach significantly reduces memory usage, as you only hold JSON tokens and the current product being parsed, rather than the entire dataset.
470
471 #### Handle Stream Errors
472
473 When working with streams, it's important to handle potential errors that may occur during streaming, such as network interruptions. Catch these errors and implement retry logic or error reporting as needed.
474
475 For example:
476
477 ```ts title="src/jobs/sync-products.ts"
478 async function* streamProductsFromApi() {
479 // Initial setup...
480 while (hasMore) {
481 // Setup pipeline...
482 try {
483 for await (const { value } of pipeline) {
484 yield value
485 // ...
486 }
487 } catch (streamError: any) {
488 // Handle stream errors (socket closed mid-stream)
489 if (
490 streamError.code === "UND_ERR_SOCKET" ||
491 streamError.code === "ECONNRESET"
492 ) {
493 throw new MedusaError(
494 MedusaError.Types.UNEXPECTED_STATE,
495 `Stream interrupted after ${productCount} products: ${streamError.message}`
496 )
497 }
498 throw streamError
499 }
500 // Update pagination...
501 }
502 }
503
504 export default async function syncProductsJob(container: MedusaContainer) {
505 // Initial setup...
506
507 const productStream = streamProductsFromApi()
508 // sync products...
509 }
510 ```
511
512 In the above snippet, you catch stream errors and check for specific error codes that indicate transient network issues. You can then decide how to handle these errors, such as retrying the fetch or logging the error.
513
514 ### Retrieve Only Necessary Fields
515
516 A common performance pitfall when syncing data is retrieving more fields than necessary from third-party services or Medusa's [Query](../../fundamentals/query/page.mdx). This leads to increased data size, slower performance, and higher memory usage.
517
518 When retrieving data from third-party services or with Medusa's Query, only request the necessary fields. Then, to efficiently group existing data for updates, use a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) for quick lookups.
519
520 For example, don't retrieve all product fields like this:
521
522 ```ts
523 // DON'T
524 const { data: existingProducts } = await query.graph(
525 {
526 entity: "product",
527 fields: ["*"],
528 filters: {
529 external_id: externalIds,
530 },
531 }
532 )
533 ```
534
535 Instead, only request the fields you need:
536
537 export const fieldsHighlights = [
538 ["19", "fields", "Request only necessary fields from Medusa"],
539 ["27", "Map", "Build a map for quick lookups by external ID"],
540 ]
541
542 ```ts title="src/jobs/sync-products.ts" highlights={fieldsHighlights}
543 export default async function syncProductsJob(container: MedusaContainer) {
544 const query = container.resolve(ContainerRegistrationKeys.QUERY)
545
546 // Initial setup...
547
548 const productStream = streamProductsFromApi()
549 const batchedProducts = batchProducts(productStream, PROCESS_BATCH_SIZE)
550
551 for await (const batch of batchedProducts) {
552 // Increment data...
553
554 // Extract external IDs from this batch to look up in Medusa
555 const externalIds = batch.map((p) => p.id)
556
557 // Query Medusa for products matching these external IDs
558 const { data: existingProducts } = await query.graph(
559 {
560 entity: "product",
561 fields: ["id", "updated_at", "external_id"],
562 filters: {
563 external_id: externalIds,
564 },
565 }
566 )
567
568 // Build a map for quick lookup
569 const existingByExternalId = new Map(
570 existingProducts.map((p) => [p.external_id, {
571 id: p.id,
572 updatedAt: p.updated_at,
573 }])
574 )
575
576 // Process batch and sync to Medusa...
577 }
578 }
579 ```
580
581 In the above snippet, after retrieving a batch of products from the external API, you query Medusa's products to find existing products that match the external IDs. You only request the necessary fields for this operation.
582
583 Then, you build a map `existingByExternalId` that enables efficient lookups when determining whether to create or update products.
584
585 This approach minimizes the amount of data transferred and processed, leading to better performance and lower memory usage.
586
587 ### Use Async Generators
588
589 [Async generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator) are a powerful feature in JavaScript that allow you to define asynchronous iterators. They're particularly useful for processing large datasets incrementally, as they enable you to yield data items one at a time without loading everything into memory.
590
591 When retrieving large datasets from third-party services, use async generators to yield data items one at a time. This allows you to process data incrementally without loading everything into memory.
592
593 ![Diagram showcasing how batches are loaded into memories one at a time with async generators](https://res.cloudinary.com/dza7lstvk/image/upload/v1764761706/Medusa%20Book/async-gen-batches_ne09bs.jpg)
594
595 For example:
596
597 export const asyncGeneratorHighlights = [
598 ["1", "streamProductsFromApi", "Async generator to stream products from API"],
599 ["9", "yield", "Yield one product at a time from the API"],
600 ["21", "batchProducts", "Async generator to batch products"],
601 ["31", "yield batch", "Yield batches of products for processing"],
602 ]
603
604 ```ts title="src/jobs/sync-products.ts" highlights={asyncGeneratorHighlights}
605 async function* streamProductsFromApi() {
606 // Initial setup...
607
608 while (hasMore) {
609 // Setup pipeline...
610
611 try {
612 for await (const { value } of pipeline) {
613 yield value // Yield one product at a time
614
615 // TODO: Yield to event loop periodically to prevent blocking...
616 }
617 } catch (streamError: any) {
618 // Handle stream errors...
619 }
620
621 // Update pagination...
622 }
623 }
624
625 async function* batchProducts(
626 products: AsyncGenerator,
627 batchSize: number
628 ): AsyncGenerator<any[]> {
629 let batch: any[] = []
630
631 for await (const product of products) {
632 batch.push(product)
633
634 if (batch.length >= batchSize) {
635 yield batch
636 // Release reference for GC
637 batch = []
638 }
639 }
640
641 // Yield remaining products
642 if (batch.length > 0) {
643 yield batch
644 }
645 }
646
647 export default async function syncProductsJob(container: MedusaContainer) {
648 // Initial setup...
649
650 const productStream = streamProductsFromApi()
651 const batchedProducts = batchProducts(productStream, PROCESS_BATCH_SIZE)
652
653 for await (const batch of batchedProducts) {
654 // Process batch and sync to Medusa...
655 }
656 }
657 ```
658
659 In the above snippet, you define two async generators:
660
661 1. `streamProductsFromApi`: Yields individual products from the third-party service one at a time.
662 2. `batchProducts`: Takes an async generator of products and yields them in batches of a specified size.
663
664 Then, in your scheduled job, you consume these generators using [for await...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) loops to process product batches incrementally.
665
666 This approach keeps memory usage low, as you only hold the current product or batch in memory at any given time.
667
668 #### Release References for Garbage Collection
669
670 When using async generators, it's important to release references to processed data to allow for [garbage collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Memory_management#garbage_collection). This keeps memory usage low, especially when processing large datasets.
671
672 For example, the `batchProducts` generator demonstrates this:
673
674 ```ts title="src/jobs/sync-products.ts" highlights={[["13"]]}
675 async function* batchProducts(
676 products: AsyncGenerator,
677 batchSize: number
678 ): AsyncGenerator<any[]> {
679 let batch: any[] = []
680
681 for await (const product of products) {
682 batch.push(product)
683
684 if (batch.length >= batchSize) {
685 yield batch
686 // Release reference for GC
687 batch = []
688 }
689 }
690
691 // Yield remaining products
692 if (batch.length > 0) {
693 yield batch
694 }
695 }
696 ```
697
698 ### Handle Backpressure
699
700 Backpressure is a mechanism that manages the flow of data between producers (API fetches) and consumers (data processing workflows). Without proper backpressure handling, fast API fetches can overwhelm the processing workflow, leading to high memory usage and potential crashes.
701
702 Handle backpressure by controlling the pace at which data is processed. One effective way to do this in JavaScript is using `for await...of` loops, which naturally provide backpressure by waiting for each iteration to complete before fetching the next item.
703
704 ![Diagram showcasing timeline from start to end of scheduled job execution where batches are fetched and synced one at a time](https://res.cloudinary.com/dza7lstvk/image/upload/v1764762095/Medusa%20Book/timeline-backpressure_rtwwzt.jpg)
705
706 For example, you can implement backpressure handling in your scheduled job:
707
708 ```ts title="src/jobs/sync-products.ts" highlights={[["7"]]}
709 export default async function syncProductsJob(container: MedusaContainer) {
710 // Initial setup...
711
712 const productStream = streamProductsFromApi()
713 const batchedProducts = batchProducts(productStream, PROCESS_BATCH_SIZE)
714
715 for await (const batch of batchedProducts) {
716 // Process batch and sync to Medusa...
717 // The next batch won't be fetched until processing of the current batch is complete
718 }
719 }
720 ```
721
722 In the above snippet, the `for await...of` loop processes each batch of products. This ensures that the next batch isn't fetched until the current batch has been fully processed, effectively implementing backpressure.
723
724 This approach keeps memory usage controlled and prevents the system from being overwhelmed by incoming data, ensuring stability during large data syncs.
725
726 ### Retry Errors with Exponential Backoff
727
728 Errors can occur during data syncing due to transient network issues, rate limiting, or temporary unavailability of third-party services. To improve reliability, implement retry logic with exponential backoff for transient errors.
729
730 For example, implement a custom function that fetches data with retry logic, then use it to fetch data from the third-party service:
731
732 export const retryHighlights = [
733 ["3", "MAX_RETRIES", "Maximum number of retry attempts"],
734 ["4", "RETRY_DELAY_MS", "Base delay for retries"],
735 ["6", "fetchWithRetry", "Function to fetch with retry logic"],
736 ["15", "fetch", "Fetch data from API"],
737 ["27", "isRetryable", "Check if error is retryable"],
738 ["36", "delay", "Calculate exponential backoff delay"],
739 ]
740
741 ```ts title="src/jobs/sync-products.ts" highlights={retryHighlights}
742 import { MedusaError } from "@medusajs/framework/utils"
743
744 const MAX_RETRIES = 3
745 const RETRY_DELAY_MS = 1000
746
747 async function fetchWithRetry(
748 url: string,
749 retries = MAX_RETRIES
750 ): Promise<Response> {
751 let lastError: Error | null = null
752
753 for (let attempt = 1; attempt <= retries; attempt++) {
754 try {
755 // TODO: Add request timeout...
756 const response = await fetch(url)
757
758 if (!response.ok) {
759 throw new MedusaError(
760 MedusaError.Types.UNEXPECTED_STATE,
761 `HTTP ${response.status}: ${response.statusText}`
762 )
763 }
764
765 return response
766 } catch (error: any) {
767 lastError = error
768 const isRetryable =
769 error.code === "UND_ERR_SOCKET" ||
770 error.code === "ECONNREFUSED" ||
771 error.code === "ECONNRESET" ||
772 error.code === "ETIMEDOUT" ||
773 error.name === "AbortError"
774
775 if (isRetryable && attempt < retries) {
776 // Exponential backoff: 1s → 2s → 4s
777 const delay = RETRY_DELAY_MS * Math.pow(2, attempt - 1)
778 await new Promise((resolve) => setTimeout(resolve, delay))
779 } else {
780 break
781 }
782 }
783 }
784
785 throw lastError
786 }
787
788 async function* streamProductsFromApi() {
789 // Initial setup...
790
791 while (hasMore) {
792 const url = `https://third-party-api.com/products?limit=${API_FETCH_SIZE}&offset=${offset}`
793
794 const response = await fetchWithRetry(url)
795 // TODO Setup pipeline...
796 }
797 }
798
799 export default async function syncProductsJob(container: MedusaContainer) {
800 // Initial setup...
801
802 const productStream = streamProductsFromApi()
803 // Process and sync products...
804 }
805 ```
806
807 In the above snippet, the `fetchWithRetry` function attempts to fetch a URL multiple times if a retryable error occurs. It uses exponential backoff to increase the delay between retries, reducing the load on the third-party service.
808
809 This approach improves the reliability of your data syncing process by handling transient errors gracefully.
810
811 ### Set Request Timeouts
812
813 When making API calls to third-party services, always set request timeouts. This prevents the event loop from being blocked indefinitely if the third-party service is unresponsive.
814
815 For example, set a request timeout on a `fetch` call using the `AbortController`:
816
817 export const timeoutHighlights = [
818 ["3", "FETCH_TIMEOUT_MS", "Timeout duration for fetch requests"],
819 ["13", "AbortController", "Create an `AbortController` for request timeout"],
820 ["14", "setTimeout", "Set a timeout to abort the request"],
821 ["24", "clearTimeout", "Clear the timeout on successful response"],
822 ]
823
824 ```ts title="src/jobs/sync-products.ts" highlights={timeoutHighlights}
825 import { MedusaError } from "@medusajs/framework/utils"
826
827 const FETCH_TIMEOUT_MS = 30000
828
829 async function fetchWithRetry(
830 url: string,
831 retries = MAX_RETRIES
832 ): Promise<Response> {
833 const lastError: Error | null = null
834
835 for (let attempt = 1; attempt <= retries; attempt++) {
836 try {
837 const controller = new AbortController()
838 const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
839
840 const response = await fetch(url, {
841 signal: controller.signal,
842 // Keep connection alive for efficiency with multiple requests
843 headers: {
844 "Connection": "keep-alive",
845 },
846 })
847
848 clearTimeout(timeoutId)
849
850 if (!response.ok) {
851 throw new MedusaError(
852 MedusaError.Types.UNEXPECTED_STATE,
853 `HTTP ${response.status}: ${response.statusText}`
854 )
855 }
856
857 return response
858 } catch (error: any) {
859 // Retry logic with exponential backoff...
860 }
861 }
862
863 throw lastError
864 }
865
866 async function* streamProductsFromApi() {
867 // initial setup...
868
869 while (hasMore) {
870 const url = `https://third-party-api.com/products?limit=${API_FETCH_SIZE}&offset=${offset}`
871
872 const response = await fetchWithRetry(url)
873 // Setup streaming pipeline...
874 }
875 }
876
877 export default async function syncProductsJob(container: MedusaContainer) {
878 // Initial setup...
879
880 const productStream = streamProductsFromApi()
881 // Process and sync products...
882 }
883 ```
884
885 In the above snippet, an `AbortController` sets a timeout for the `fetch` request. If the request takes longer than the specified timeout, it's aborted, preventing indefinite blocking of the event loop.
886
887 This approach ensures that your application remains responsive even when third-party services are slow or unresponsive.
888
889 ### Yield to the Event Loop
890
891 When processing large amounts of data in loops, periodically yield control back to the event loop. This prevents blocking the event loop for extended periods, which can lead to unresponsiveness in your application. For example, it may prevent other scheduled jobs or subscribers from executing.
892
893 Yield to the event loop using [setImmediate](https://nodejs.org/api/timers.html#timers_setimmediate_callback_args). For example:
894
895 export const yieldHighlights = [
896 ["11", "productCount", "Count of processed products"],
897 ["15", "setImmediate", "Yield to event loop every 100 products"],
898 ]
899
900 ```ts title="src/jobs/sync-products.ts" highlights={yieldHighlights}
901 async function* streamProductsFromApi() {
902 // Initial setup...
903
904 while (hasMore) {
905 // Setup pipeline...
906
907 try {
908 // Yield each product one at a time
909 for await (const { value } of pipeline) {
910 yield value
911 productCount++
912
913 // Yield to event loop periodically to prevent blocking
914 if (productCount % 100 === 0) {
915 await new Promise((resolve) => setImmediate(resolve))
916 }
917 }
918 } catch (streamError: any) {
919 // Handle stream errors...
920 }
921
922 // If the products are less than expected, there are no more products
923 if (productCount < API_FETCH_SIZE) {
924 hasMore = false
925 } else {
926 offset += productCount
927 }
928 }
929 }
930
931 export default async function syncProductsJob(container: MedusaContainer) {
932 const productStream = streamProductsFromApi()
933 // Process and sync products...
934 }
935 ```
936
937 In the above snippet, the code yields to the event loop every 100 products processed. This allows other tasks in the event loop to execute, improving overall responsiveness.