Handling migrations
Get real-world experience of maintaining a stateful object stored in memory, which will be persisted through migrations and even graceful aborts.
Let's first head into our academy-amazon-scraper and create a new file named asinTracker.js in the src folder. Within this file, we are going to build a utility class which will allow us to store, modify, persist, and log our tracked ASIN data.
Here's the skeleton of our class:
import { log } from 'apify';
class ASINTracker {
constructor() {
this.state = {};
// Log the state to the console every ten
// seconds
setInterval(() => log.info('ASIN tracker', this.state), 10000);
}
// Add an offer to the ASIN's offer count
// If ASIN doesn't exist yet, set it to 0
incrementASIN(asin) {
if (this.state[asin] === undefined) {
this.state[asin] = 0;
return;
}
this.state[asin] += 1;
}
}
// It is only a utility class, so we will immediately
// create an instance of it and export that. We only
// need one instance for our use case.
export const tracker = new ASINTracker();
Multiple techniques exist for storing data in memory; however, this is the most modular way, as all state-persistence and modification logic will be held in this file.
Here is our updated routes.js file which is now utilizing this utility class to track the number of offers for each product ASIN:
import { createCheerioRouter } from '@crawlee/cheerio';
import { tracker } from './asinTracker.js';
import { BASE_URL, labels, OFFERS_URL } from './constants.js';
export const router = createCheerioRouter();
router.addHandler(labels.START, async ({ $, addRequests, request }) => {
const { keyword } = request.userData;
const products = $('div[data-component-type="s-search-result"]:not(.AdHolder)');
if (!products.length) {
throw new Error('No products found, retrying');
}
const requests = [];
for (const product of products) {
const element = $(product);
const asin = element.attr('data-asin');
if (!asin) continue;
// For each product, add it to the ASIN tracker
// and initialize its collected offers count to 0
tracker.incrementASIN(asin);
const url = `${BASE_URL}/dp/${asin}`;
requests.push({
url,
label: labels.PRODUCT,
userData: {
data: {
title: element.find('h2[aria-label]').text().trim(),
asin,
itemUrl: url,
keyword,
},
},
});
}
await addRequests(requests);
});
// The PRODUCT handler stays the same
router.addHandler(labels.OFFERS, async ({ $, request, pushData }) => {
const { data } = request.userData;
if (!$('#aod-container').length) {
throw new Error('Offers did not load, retrying');
}
for (const offer of $('#aod-pinned-offer, #aod-offer')) {
const element = $(offer);
const price = element.find('.apex-pricetopay-value').first().text().trim();
if (!price) continue;
// For each offer, add 1 to the ASIN's
// offer count
tracker.incrementASIN(data.asin);
await pushData({
...data,
sellerName: element.find('#aod-offer-soldBy [aria-label]').text().trim(),
offer: price,
});
}
});
Persisting state
By default, the persistState event is automatically fired every 60 seconds by the Apify SDK while the Actor is running. It's also fired when the migrating event occurs.
In order to persist our ASIN tracker object, let's use the Actor.on function to listen for the persistState event and store it in the key-value store each time it is emitted. First, we'll add the name of the key-value store key to constants.js:
// ...
export const ASIN_TRACKER = 'ASIN-TRACKER';
Then we can use it in the tracker:
import { Actor, log } from 'apify';
import { ASIN_TRACKER } from './constants.js';
class ASINTracker {
constructor() {
this.state = {};
}
initialize() {
Actor.on('persistState', async () => {
await Actor.setValue(ASIN_TRACKER, this.state);
});
setInterval(() => log.info('ASIN tracker', this.state), 10000);
}
incrementASIN(asin) {
if (this.state[asin] === undefined) {
this.state[asin] = 0;
return;
}
this.state[asin] += 1;
}
}
export const tracker = new ASINTracker();
The listener is registered in the initialize() method and not in the constructor, because the tracker object is created as soon as asinTracker.js is imported, which is before Actor.init() runs. On the Apify platform, Actor.init() replaces the event manager, so a listener registered before it never receives the persistState event. Locally the event manager isn't replaced, so the mistake goes unnoticed with apify run. That's why we'll call initialize() from main.js right after Actor.init().
Handling resurrections
Once initialize() is called, our state will be persisted every 60 seconds in the key-value store. However, we're not done. Let's say that the Actor migrates and is resurrected. We never actually update the state variable of our ASINTracker class with the state stored in the key-value store, so as our code currently stands, we still don't support state-persistence on migrations.
In order to fix this, let's extend the initialize method, so that before it starts persisting the state, it checks the key-value store for a previous state under the key ASIN-TRACKER. If a previous state does live there, then it will update the class' state variable with the value read from the key-value store:
import { Actor, log } from 'apify';
import { ASIN_TRACKER } from './constants.js';
class ASINTracker {
constructor() {
this.state = {};
}
async initialize() {
// Read the data from the key-value store. If it
// doesn't exist, it will be undefined
const data = await Actor.getValue(ASIN_TRACKER);
// If the data does exist, replace the current state
// (initialized as an empty object) with the data
if (data) this.state = data;
Actor.on('persistState', async () => {
await Actor.setValue(ASIN_TRACKER, this.state);
});
setInterval(() => log.info('ASIN tracker', this.state), 10000);
}
incrementASIN(asin) {
if (this.state[asin] === undefined) {
this.state[asin] = 0;
return;
}
this.state[asin] += 1;
}
}
export const tracker = new ASINTracker();
We'll now call this method at the top level of the main.js file to ensure it is the first thing that gets called when the Actor starts up:
// ...
import { tracker } from './asinTracker.js';
// The Actor.init() function should be executed before
// the tracker's initialization
await Actor.init();
await tracker.initialize();
// ...
The tracker saves its state each time the persistState event fires, so after a migration, or a graceful abort and resurrection, it picks up from the last save. Offers counted after that save are lost, but the tracker no longer has to start counting from scratch.
That's everything! Run the Actor on the platform, abort it gracefully halfway through, resurrect it, and watch the log as the tracker picks up where it left off.
Quiz answers 📝
Q: Actors have an option in the Settings tab to Restart on error. Would you use this feature for regular Actors? When would you use this feature?
A: It's not best to use this option by default. If it fails, there must be a reason, which would need to be thought through first - meaning that the edge case of failing should be handled when resurrecting the Actor. The state should be persisted beforehand.
Q: Migrations happen randomly, but by aborting gracefully, you can simulate a similar situation. Try this out on the platform and observe what happens. What changes occur, and what remains the same for the restarted Actor's run?
A: After aborting or throwing an error mid-process, it manages to start back from where it was upon resurrection.
Q: Why don't you (usually) need to add any special migration handling code for a standard crawling/scraping Actor? Are there any features in Crawlee or Apify SDK that handle this under the hood?
A: Because Apify SDK handles all of the migration handling code for us. To add custom migration-handling code, use the Actor.on() function to listen for the migrating or persistState events to save the current state in key-value store or elsewhere.
Q: How can you intercept the migration event? How much time do you have after this event happens and before the Actor migrates?
A: By using the Actor.on function. You have a maximum of a few seconds before shutdown after the migrating event has been fired.
Q: When would you persist data to the default key-value store instead of to a named key-value store?
A: Persisting data to the default key-value store would help when handling an Actor's run state or with storing metadata about the run (such as results, miscellaneous files, or logs). Using a named key-value store allows you to persist data at the account level to handle data across multiple Actor runs.
Wrap up
In this activity, we learned how to persist custom values on an interval as well as after Actor migrations by using the persistState event and the key-value store. With this knowledge, you can safely increase your Actor's performance by storing data in variables and then pushing them to the dataset periodically/at the end of the Actor's run as opposed to pushing data immediately after it's been collected.
One important thing to note is that this workflow can be used to replace the usage of userData to pass data between requests, as it allows for the creation of a "global store" which all requests have access to at any time.