One large batch can save a start fee and still make your retry more expensive.

You're budgeting tonight's property refresh after a timeout. Replaying the original input feels reasonable, especially when your upsert already prevents duplicate rows.

But maxItems accepts 1 to 500 properties, while lookup pages are fetched separately, paced 3–6 seconds apart. A retry can charge again for records your database already has.

This Example input is your refresh manifest, before you split it into runs.

import assert from 'node:assert/strict'; import { ApifyClient } from 'apify-client'; import { z } from 'zod'; const run_input = { mode: 'byPropertyIds' as const, propertyIds: ['4889910', '2430840'], maxItems: 100, }; 

The useful budget unit is a checkpointed batch: requested properties, committed results, and a bounded allowance for unresolved work.

Your database can prevent duplicate storage. It can't refund repeated upstream work.

What actually gets charged?

The published pricing separates starting work from emitting results. Smaller batches create more starts; replaying finished properties creates more result events.

Charged event What drives it Your budgeting control
apify-actor-start Allocated memory, with an event per GB and a minimum charge per run A conservative start-event allowance covering deployment memory
apify-default-dataset-item Each result emitted into the default dataset Deduplicated inputs and an explicit property limit

Platform usage is additional, at your plan's rates. Keep it outside the event-fee calculation.

Don't invent a request price for optional detail, review, or calendar fetching. The Store charges the events above. Extra work can still affect platform usage and exposure to timeouts.

An event estimate can approve a job before launch. It doesn't predict all the resources that job will consume.

Cut batches where retries can resume

For lookup lists over roughly 100 IDs, split the work into separate runs. Treat that guidance as a starting boundary, then choose a smaller batch when your timeout policy needs more room.

The goal isn't maximum input density. It's limiting how much unfinished work shares a failure.

This code removes exact duplicate identifiers and gives every submitted batch its own explicit maxItems.

const lookupSchema = z.object({ mode: z.literal('byPropertyIds'), propertyIds: z.array(z.string().min(1)).min(1), maxItems: z.number().int().min(1).max(500), }).strict(); type LookupInput = z.infer<typeof lookupSchema>; const request = lookupSchema.parse(run_input); const uniqueIds = [...new Set(request.propertyIds)]; const configuredBatchSize = 100; const batchSize = Math.min(configuredBatchSize, request.maxItems); const batches: LookupInput[] = []; for (let offset = 0; offset < uniqueIds.length; offset += batchSize) { const propertyIds = uniqueIds.slice(offset, offset + batchSize); batches.push({ mode: 'byPropertyIds', propertyIds, maxItems: propertyIds.length, }); } 

Keep identifiers exact. Legacy IDs ending in ha are preserved by the Actor; converting everything to numeric IDs would destroy that distinction.

For URL refreshes, deduplicate exact startUrls entries first. Maintain a verified mapping between requested URLs and returned identities before using those identities as checkpoints.

Guessing identity from a convenient URL fragment makes an expensive retry policy surprisingly easy to implement.

Batching changes failure scope. It doesn't guarantee that a run will finish.

Compute an event-fee ceiling before launch

Use integer money units internally. Your ceiling should come from the input you're about to submit, rather than a remembered average dataset size.

The function below budgets every possible property result within that input, plus a configured start-event allowance. Its guarantee depends on that allowance covering the deployment's memory charge.

The assertions reproduce the FREE and GOLD examples for 100 and 1,000 dataset-item events. The larger examples check pricing arithmetic across event counts, not a valid single-run lookup input.

const prices = { FREE: { item: 0.00099, start: 0.10 }, BRONZE: { item: 0.00082, start: 0.077 }, SILVER: { item: 0.00066, start: 0.053 }, GOLD: { item: 0.00049, start: 0.03 }, PLATINUM: { item: 0.00049, start: 0.03 }, DIAMOND: { item: 0.00049, start: 0.03 }, } as const; type Tier = keyof typeof prices; const microsPerUsd = 1_000_000; function eventFeeMicros( tier: Tier, itemEvents: number, startEvents: number, ): number { z.number().int().nonnegative().parse(itemEvents); z.number().int().positive().parse(startEvents); const price = prices[tier]; const total = itemEvents * Math.round(price.item * microsPerUsd) + startEvents * Math.round(price.start * microsPerUsd); assert(Number.isSafeInteger(total)); return total; } function eventCeilingMicros( input: LookupInput, tier: Tier, startEventAllowance: number, ): number { const parsed = lookupSchema.parse(input); const propertyBound = Math.min( new Set(parsed.propertyIds).size, parsed.maxItems, ); return eventFeeMicros(tier, propertyBound, startEventAllowance); } assert.equal(eventFeeMicros('FREE', 100, 1), 199_000); assert.equal(eventFeeMicros('GOLD', 100, 1), 79_000); assert.equal(eventFeeMicros('FREE', 1_000, 1), 1_090_000); assert.equal(eventFeeMicros('GOLD', 1_000, 1), 520_000); 

This is an event-fee ceiling under stated assumptions. Platform usage remains outside it.

The start-event allowance is deployment configuration, separate from the Actor input. Check it against the memory actually allocated to your runs.

A memory change should trigger a budget review alongside the deployment review. That's less exciting than discovering the change from an invoice.

Reserve retries before scheduling

A recurring refresh budget needs an attempt policy. “Retry until it works” is a scheduler with access to your wallet.

Reserve enough event fees for every permitted attempt before accepting the schedule. Budgeting each retry as a full batch is conservative; reconciliation can reduce the actual retry input later.

These Example policy values are operator choices. Set the memory bound from your deployment, and keep platform usage in a separate allowance.

const policy = { tier: 'FREE' as Tier, memoryGiBUpperBound: 4, startEventAllowance: 4, attemptsPerBatch: 2, refreshesInWindow: 30, eventBudgetUsd: 30, }; for (const value of [ policy.memoryGiBUpperBound, policy.startEventAllowance, policy.attemptsPerBatch, policy.refreshesInWindow, ]) { z.number().int().positive().parse(value); } z.number().finite().nonnegative().parse(policy.eventBudgetUsd); assert( policy.startEventAllowance >= Math.max(1, Math.ceil(policy.memoryGiBUpperBound)), ); const batchCeilings = batches.map((input) => eventCeilingMicros(input, policy.tier, policy.startEventAllowance), ); const scheduleAllowanceMicros = batchCeilings.reduce((total, fee) => total + fee, 0) * policy.attemptsPerBatch * policy.refreshesInWindow; assert(Number.isSafeInteger(scheduleAllowanceMicros)); assert( scheduleAllowanceMicros <= Math.floor(policy.eventBudgetUsd * microsPerUsd), 'Schedule exceeds its event-fee allowance', ); 

An attempt includes the initial launch. Persist the attempt reservation before dispatch, so a worker restart doesn't quietly reset its allowance.

Overlapping scheduler invocations also need coordination. Reserve against the same budget ledger, and prevent concurrent workers from claiming the same refresh batch.

The pre-flight calculation wins here: it can reject an unaffordable schedule before any start event happens.

A per-run cap can't enforce a recurring budget across independent launches.

Attach the cap to the launch

Keep the platform-side guard as well. A pre-flight calculation lives in your code; the run's charge limit travels with the launch request.

The supported REST parameter is maxTotalChargeUsd. It limits pay-per-event charges for that run, while platform usage remains separately billable.

This launches the first prepared batch with its calculated limit, then uses the client to wait for a terminal status.

const client = new ApifyClient({ token: process.env.APIFY_TOKEN, }); const currentBatch = batches[0]; assert(currentBatch); const launchUrl = new URL( 'https://api.apify.com/v2/acts/' + 'nimbryxo-studio~vrbo-destination-rental-listings-extractor/runs', ); launchUrl.searchParams.set( 'maxTotalChargeUsd', String(batchCeilings[0] / microsPerUsd), ); const launchResponse = await fetch(launchUrl, { method: 'POST', headers: { Authorization: `Bearer ${process.env.APIFY_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify(currentBatch), }); if (!launchResponse.ok) { throw new Error(`Launch response needs review: ${launchResponse.status}`); } const started = z.object({ data: z.object({ id: z.string().min(1) }), }).parse(await launchResponse.json()); const finished = await client.run(started.data.id).waitForFinish(); const terminalStatuses = new Set([ 'SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED', ]); if (!finished || !terminalStatuses.has(finished.status)) { throw new Error(`Keep tracking existing run ${started.data.id}`); } 

Record the returned run ID against the reserved attempt immediately. If waiting fails, resume tracking that run.

A launch failure can also be ambiguous when the request reached the service but its response didn't reach your worker. Hold that attempt for reconciliation rather than automatically issuing another POST.

The cap contains event charges even when your estimate is wrong. It can't tell your scheduler which properties are safe to skip next time.

A stopped run still needs reconciliation

The worked example is Vrbo Destination Rental Listings Extractor. Its lookup behavior makes the retry boundary visible, but the pattern applies wherever emitted results are individually billable.

A capped or interrupted run may leave a partial dataset. Treat terminal status and batch completeness as separate facts.

The recovery path should look like this:

requested IDs -> capped run -> validate dataset -> commit rows + checkpoints | | quarantine unresolved IDs | bounded retry attempt 

Fetch the dataset after terminal status, including unsuccessful statuses. Don't turn an unreadable response into a completed batch.

This code prepares checkpoint candidates and unresolved IDs. It leaves retry dispatch until after durable persistence.

const datasetResponse = await fetch( `https://api.apify.com/v2/datasets/` + `${encodeURIComponent(finished.defaultDatasetId)}` + `/items?format=json&clean=true`, { headers: { Authorization: `Bearer ${process.env.APIFY_TOKEN}`, }, }, ); if (!datasetResponse.ok) { throw new Error('Dataset retrieval failed; preserve the existing run ID'); } const rawRows = z.array(z.unknown()).parse(await datasetResponse.json()); const rowSchema = z.object({ propertyId: z.string().min(1), source: z.string().min(1).optional(), scrapedAt: z.string().optional(), }).passthrough(); const requestedIds = new Set(currentBatch.propertyIds); const checkpointCandidates = new Map<string, z.infer<typeof rowSchema>>(); const quarantine: unknown[] = []; for (const rawRow of rawRows) { const parsed = rowSchema.safeParse(rawRow); if (!parsed.success) { quarantine.push(rawRow); continue; } const row = parsed.data; const source = row.source ?? 'vrbo.com'; if (source !== 'vrbo.com' || !requestedIds.has(row.propertyId)) { quarantine.push(rawRow); continue; } checkpointCandidates.set(row.propertyId, row); } const unresolvedIds = currentBatch.propertyIds.filter( (id) => !checkpointCandidates.has(id), ); const proposedRetry: LookupInput | null = unresolvedIds.length ? { mode: 'byPropertyIds', propertyIds: unresolvedIds, maxItems: unresolvedIds.length, } : null; 

The Actor omits source for the main storefront, so that fallback is intentional. In durable storage, scope identity by source and property ID.

Keep the refresh identifier alongside that key. Yesterday's committed property doesn't prove tonight's refresh finished.

Commit accepted property updates and their checkpoints in the same database transaction. Dispatch proposedRetry only after that commit succeeds and the attempt ledger permits it.

If persistence fails, recover the existing dataset first. Fetching the property again is the expensive substitute for recovering your own write.

The exact-match rule is conservative. If returned identifiers differ from your stored manifest, quarantine them until you establish a verified mapping.

An unresolved identifier also doesn't prove a property disappeared. It means this refresh hasn't produced an accepted record for that identifier. Keep deletion decisions out of automatic retry handling.

There's another boundary worth keeping: URL and ID lookups omit live price fields because their reliable property-page route has no stay dates. A completed profile refresh doesn't make an older stored price current.

Use scrapedAt where present to retain collection provenance. Track price freshness separately from profile freshness, so a successful lookup can't quietly renew an old rate.

Before the next nightly refresh

  • Reserve event fees for permitted attempts, with platform usage tracked separately.
  • Verify that the start-event allowance covers deployed memory.
  • Persist the attempt reservation before dispatch and the run ID immediately afterward.
  • Reconcile terminal runs against requested identities, including interrupted runs.
  • Commit property updates and source-scoped refresh checkpoints together.
  • Retry unresolved work only after the commit, within the attempt allowance.

The cheapest completed batch can still be the wrong retry boundary.

Drafted with AI assistance and reviewed for accuracy.