If you sell an Apify Actor with pay-per-event (PPE) pricing, the most important line of code is the one that decides when a user gets charged. Get it wrong and users pay for timeouts, 404s and empty pages, and they leave a one-star review. Get it right and the pricing sells itself: "you only pay for results you actually got".

This post shows the pattern in about 30 lines of Node.js, and, more usefully, how to test the charging locally before you publish, using two SDK environment variables that are easy to miss.

Everything below was run today with apify 3.8.0 on Node 22.

The rule

  • Success: save the row and charge one event, in the same call.
  • Failure: still save the row (so the user can see what went wrong), but don't charge.
  • Budget hit: if the user's "max cost per run" is reached, stop cleanly instead of doing work nobody pays for.

In current 3.x versions of the SDK, Actor.pushData() takes an optional event name as its second argument. That one call stores the item and charges the event, and the result tells you whether the user's budget is used up.

The code

package.json:

{ "name": "ppe-demo", "type": "module", "private": true, "scripts": { "start": "node src/main.js" }, "dependencies": { "apify": "^3.7.2" } } 

src/main.js, an Actor that fetches each URL and returns its <title>:

import { Actor, log } from 'apify'; const CHARGE_EVENT = 'result'; // must match the event name in your PPE pricing await Actor.init(); const { urls = [], timeoutSecs = 20 } = (await Actor.getInput()) ?? {}; if (!urls.length) await Actor.fail('Input "urls" must be a non-empty list.'); let charged = 0; for (const url of urls) { const base = { url, fetchedAt: new Date().toISOString() }; try { const res = await fetch(new URL(url), { signal: AbortSignal.timeout(timeoutSecs * 1000) }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const html = await res.text(); const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]?.trim() ?? null; // Success: save the row AND charge one event, in one call. const { eventChargeLimitReached } = await Actor.pushData({ ...base, status: 'ok', title }, CHARGE_EVENT); charged += 1; if (eventChargeLimitReached) { log.info('User budget reached, stopping.'); break; } } catch (err) { // Failure: save the row so the user can see why, but don't charge. await Actor.pushData({ ...base, status: 'failed', title: null, error: String(err.message ?? err) }); } } log.info(`Charged ${charged} of ${urls.length} URL(s).`); await Actor.exit(); 

A few details worth copying:

  • new URL(url) throws on garbage input ("not a url"), so invalid input falls into the free catch branch automatically.
  • AbortSignal.timeout() turns slow sites into a clean, uncharged failure instead of a hung run.
  • Actor.fail() on empty input happens before any billable work.
  • Failed rows have the same shape as good ones (title: null plus an error), so the user's table view and exports don't break.

Testing the charging locally

Create the input file at storage/key_value_stores/default/INPUT.json:

{ "urls": ["https://example.com", "https://httpbin.org/status/404", "not a url", "https://www.iana.org/help/example-domains"] } 

Then run with two environment variables:

npm install ACTOR_TEST_PAY_PER_EVENT=true ACTOR_USE_CHARGING_LOG_DATASET=true npm start 
  • ACTOR_TEST_PAY_PER_EVENT=true makes the SDK behave as if the Actor had PPE pricing (local runs only; the SDK refuses it on the platform).
  • ACTOR_USE_CHARGING_LOG_DATASET=true writes every charge to a local dataset named charging_log, so you can see exactly what would have been billed.

Output from my run:

INFO Charged 2 of 4 URL(s). 

storage/datasets/default/ holds all four rows:

{"url": "https://example.com", "status": "ok", "title": "Example Domain"} {"url": "https://httpbin.org/status/404", "status": "failed", "title": null, "error": "HTTP 404"} {"url": "not a url", "status": "failed", "title": null, "error": "Invalid URL"} {"url": "https://www.iana.org/help/example-domains", "status": "ok", "title": "Example Domains"} 

(fetchedAt removed for brevity.) And storage/datasets/charging_log/ holds exactly two entries, one per successful row:

{"eventName": "result", "eventTitle": "Unknown event 'result'", "eventPriceUsd": 1, "chargedCount": 1, "timestamp": "..."} {"eventName": "result", "eventTitle": "Unknown event 'result'", "eventPriceUsd": 1, "chargedCount": 1, "timestamp": "..."} 

The 404 and the invalid URL are in the dataset but not in the charging log. That's the whole point.

Locally the SDK doesn't know your real prices, so an unconfigured event shows up as "Unknown event" at a placeholder $1. Only the count matters here.

Testing the budget stop

Users can set a maximum cost per run. Simulate it with ACTOR_MAX_TOTAL_CHARGE_USD. With the placeholder $1 per event, a $1 cap allows exactly one charge:

rm -rf storage/datasets ACTOR_TEST_PAY_PER_EVENT=true ACTOR_USE_CHARGING_LOG_DATASET=true ACTOR_MAX_TOTAL_CHARGE_USD=1 npm start 
INFO User budget reached, stopping. INFO Charged 1 of 4 URL(s). 

The run stops right after the first paid result instead of fetching the remaining pages for free.

Before you publish

  1. In Console, open Publication > Monetization > Pay per event and create an event whose name exactly matches CHARGE_EVENT (result here). A typo means nothing gets charged.
  2. Say in your README what counts as a chargeable result and what's free. Users read it, and it's the honest thing to do.
  3. Check the price of the synthetic Actor-start event in the same screen. Keep it tiny (or zero) if your promise is "pay only for results", otherwise every empty run still costs the user something.

Want the full template?

The snippet above is all you need to get the pattern right. If you'd rather start from a complete project (input/dataset/output schemas that the Store accepts, a Dockerfile, unit tests and a README skeleton), we packaged ours as the Pay-Per-Event Actor Starter Kit (MIT, $9 one-time): details · buy.

It's the same pattern we use in our own Actors at apify.com/siftwright. If you're choosing between per-result and subscription pricing for a data API, we wrote up the break-even maths with real numbers.

Questions or corrections: support@siftwright.com.