Your daily import is green. An older listing now advertises a different salary, but your database still has the original band. Naturally, the dashboard looks reassuring.
A new-job alert and a changed-job alert need different fetch plans. postedWithinDays filters publication dates, so it cannot serve as a revision feed.
Changing a salary or application deadline doesn't make an older posting eligible for your recent-posting window. Sorting by latest doesn't change that relationship.
Why does the salary edit disappear?
The discovery query answers “which postings belong in this publication window?” Your database needs another answer: “what do the listings already tracked look like now?”
The Actor supports exact listing lookups through byUrls. That gives you separate discovery and refresh lanes without repeatedly searching the entire board.
Example discovery input, followed by the imports shared throughout this workflow:
import { createHash, randomUUID } from 'node:crypto'; import { ApifyClient } from 'apify-client'; import { z } from 'zod'; import pg from 'pg'; const client = new ApifyClient({ token: process.env.APIFY_TOKEN }); const pool = new pg.Pool(); const actorName = 'nimbryxo-studio/jobberman-nigeria-job-listings-scraper'; const discoveryInput = { mode: 'search', searchQuery: 'sales', sortBy: 'latest', postedWithinDays: 7, includeFullDescription: true, maxItems: 100, maxPages: 5, }; type Db = Awaited<ReturnType<typeof pool.connect>>; Full descriptions stay enabled in both lanes. Otherwise, you're comparing detailed observations with card-only observations, and your change detector may mostly detect your own configuration.
Give discovery and refresh separate worklists
Discovery adds canonical URLs to your database. Refresh reads those URLs back without applying the publication window.
Recent-posting search ─┐ ├─ validate ─ fingerprint ─ transaction Tracked URL refresh ──┘ ├─ current job ├─ content version └─ change event Use sourceUrl as the upsert key because it identifies the canonical listing. Keep it unchanged.
That key identifies a listing, not an underlying vacancy across reposts. If a posting moves or returns under another URL, you need an explicit identity policy before merging it. Similar titles aren't sufficient evidence.
The database keeps searchable salary columns alongside raw JSONB. It also separates reusable content versions from change events.
async function initialize(db: Db) { await db.query(` CREATE TABLE IF NOT EXISTS ingestion_attempts ( attempt_id uuid PRIMARY KEY, lane text NOT NULL, run_id text, status text NOT NULL, started_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz, details jsonb ); CREATE TABLE IF NOT EXISTS jobs ( source_url text PRIMARY KEY, fingerprint text NOT NULL, salary_min double precision, salary_max double precision, raw jsonb NOT NULL, last_observed_at timestamptz NOT NULL, refresh_enabled boolean NOT NULL DEFAULT true ); CREATE TABLE IF NOT EXISTS job_versions ( source_url text NOT NULL, fingerprint text NOT NULL, raw jsonb NOT NULL, first_detected_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (source_url, fingerprint) ); CREATE TABLE IF NOT EXISTS job_changes ( attempt_id uuid NOT NULL REFERENCES ingestion_attempts(attempt_id), source_url text NOT NULL, fingerprint text NOT NULL, detected_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (attempt_id, source_url) ); `); } JSONB preserves fields your application doesn't understand yet. Typed columns make routine salary queries straightforward.
The cost is duplication: changing a projection requires changing its writer. This schema promotes only the salary endpoints; other fields remain in JSONB until a real query justifies another column.
Validate the contract your application actually needs
Missing salary or deadline fields aren't automatically extraction failures. The source can omit them, and the Actor omits unpublished values.
Use optional fields for that legitimate absence. Reject incompatible values instead of coercing them into something plausible.
This validator checks the fields used by the fingerprint. Passthrough preserves everything else.
const Job = z.object({ sourceUrl: z.string().url(), recordType: z.literal('job').optional(), salaryMin: z.number().finite().optional(), salaryMax: z.number().finite().optional(), salaryCurrency: z.string().optional(), salaryPeriod: z.union([z.string(), z.number().finite()]).optional(), validThrough: z.string().optional(), descriptionText: z.string().optional(), datePosted: z.string().optional(), scrapedAt: z.string().optional(), }).passthrough(); function prepare(items: unknown[]) { const rows = new Map<string, { source_url: string; fingerprint: string; salary_min: number | null; salary_max: number | null; raw: unknown; }>(); const blocked = new Set<string>(); const rejected: unknown[] = []; for (const item of items) { const parsed = Job.safeParse(item); if (!parsed.success) { rejected.push({ raw: item, issues: parsed.error.issues }); continue; } const job = parsed.data; const fingerprint = createHash('sha256').update(JSON.stringify([ job.salaryMin ?? null, job.salaryMax ?? null, job.salaryCurrency ?? null, job.salaryPeriod ?? null, job.validThrough ?? null, job.descriptionText ?? null, ])).digest('hex'); if (blocked.has(job.sourceUrl)) { rejected.push({ raw: item, reason: 'Conflicting duplicate URL' }); continue; } const previous = rows.get(job.sourceUrl); if (previous && previous.fingerprint !== fingerprint) { rejected.push({ raw: [previous.raw, item], reason: 'Conflicting duplicate URL', }); rows.delete(job.sourceUrl); blocked.add(job.sourceUrl); continue; } rows.set(job.sourceUrl, { source_url: job.sourceUrl, fingerprint, salary_min: job.salaryMin ?? null, salary_max: job.salaryMax ?? null, raw: item, }); } return { rows: [...rows.values()], rejected }; } Strict validation of the entire object would reject legitimate fields outside this small contract. Passthrough accepts additions; incompatible selected fields enter quarantine with their original record and validation issues.
The fingerprint deliberately excludes scrapedAt. Otherwise, observing an unchanged listing would manufacture a revision.
It also excludes datePosted: publication time isn't the change signal being tracked. This detector covers salary terms, deadline text and description text. Title changes alone won't trigger it.
Keep those boundaries explicit. A fingerprint is a policy with a hash attached.
Make retries boring in Postgres
A unique URL-and-fingerprint constraint prevents duplicate content versions. It doesn't, by itself, preserve every transition.
A listing can move from content A to B and later return to A. The separate change table records that return while reusing the existing content version.
This statement writes the batch together and adds change events only when the current fingerprint differs.
const writeBatchSql = ` WITH incoming AS ( SELECT * FROM jsonb_to_recordset($1::jsonb) AS x( source_url text, fingerprint text, salary_min double precision, salary_max double precision, raw jsonb ) ), changed AS MATERIALIZED ( SELECT i.* FROM incoming i LEFT JOIN jobs j USING (source_url) WHERE j.fingerprint IS DISTINCT FROM i.fingerprint ), versions AS ( INSERT INTO job_versions (source_url, fingerprint, raw) SELECT source_url, fingerprint, raw FROM changed ON CONFLICT (source_url, fingerprint) DO NOTHING RETURNING source_url ), events AS ( INSERT INTO job_changes (attempt_id, source_url, fingerprint) SELECT $2::uuid, source_url, fingerprint FROM changed ON CONFLICT (attempt_id, source_url) DO NOTHING RETURNING source_url ) INSERT INTO jobs ( source_url, fingerprint, salary_min, salary_max, raw, last_observed_at ) SELECT source_url, fingerprint, salary_min, salary_max, raw, statement_timestamp() FROM incoming ON CONFLICT (source_url) DO UPDATE SET fingerprint = EXCLUDED.fingerprint, salary_min = EXCLUDED.salary_min, salary_max = EXCLUDED.salary_max, raw = EXCLUDED.raw, last_observed_at = EXCLUDED.last_observed_at `; An unchanged observation updates the current raw record and observation time without adding history.
Publication time remains in datePosted, source observation time in scrapedAt, and local change detection time in detected_at. Don't substitute one for another when explaining an alert.
Wait for completion before accepting observations
A successful transport call isn't your ingestion transaction.
The runner waits for the Actor, checks its status, reads the dataset and validates every item. It commits usable records while retaining rejected records in the attempt ledger.
async function runLane( db: Db, lane: string, input: Record<string, unknown>, ) { const attemptId = randomUUID(); await db.query( `INSERT INTO ingestion_attempts (attempt_id, lane, status) VALUES ($1, $2, 'STARTED')`, [attemptId, lane], ); let transactionOpen = false; try { const run = await client.actor(actorName).call(input); await db.query( 'UPDATE ingestion_attempts SET run_id = $2 WHERE attempt_id = $1', [attemptId, run.id], ); if (run.status !== 'SUCCEEDED') { throw new Error(`Actor finished with status ${run.status}`); } const { items } = await client.dataset(run.defaultDatasetId).listItems(); const { rows, rejected } = prepare(items); const observed = new Set(rows.map(row => row.source_url)); const requested = Array.isArray(input.listingUrls) ? input.listingUrls as string[] : []; const missing = requested.filter(url => !observed.has(url)); const capped = lane === 'discovery' && items.length >= Number(input.maxItems); const attention = rejected.length > 0 || missing.length > 0 || capped; await db.query('BEGIN'); transactionOpen = true; await db.query(writeBatchSql, [JSON.stringify(rows), attemptId]); await db.query( `UPDATE ingestion_attempts SET status = $2, finished_at = now(), details = $3::jsonb WHERE attempt_id = $1`, [ attemptId, attention ? 'ATTENTION' : 'COMPLETE', JSON.stringify({ accepted: rows.length, rejected, missing, discoveryCapReached: capped, }), ], ); await db.query('COMMIT'); transactionOpen = false; return !attention; } catch (error) { if (transactionOpen) await db.query('ROLLBACK'); await db.query( `UPDATE ingestion_attempts SET status = 'FAILED', finished_at = now(), details = $2::jsonb WHERE attempt_id = $1 AND status = 'STARTED'`, [attemptId, JSON.stringify({ error: error instanceof Error ? error.message : String(error), })], ); return false; } } A failed Actor run contributes no records under this policy. A successful run with rejected items commits the valid subset and requests attention.
That distinction matters during recovery. You can repair the validator and replay a stored dataset, rather than purchasing another observation merely to fix local parsing.
A fresh run remains safe for current-state ingestion: unchanged fingerprints don't add revisions. However, rerunning can't reconstruct an intermediate edit nobody observed.
Refresh the URLs you already own
The refresh worklist comes from stored canonical URLs. Its input uses postedWithinDays: 0, allowing any posting date.
The program snapshots that worklist before discovery, so newly discovered listings don't immediately incur a redundant refresh. It exports an attention flag while keeping each lane's outcome in the ledger.
export const ingestionReport = { needsAttention: false }; let db: Db | undefined; let locked = false; try { db = await pool.connect(); await initialize(db); await db.query( "SELECT pg_advisory_lock(hashtext('job-listing-ingestion'))", ); locked = true; const tracked = await db.query<{ source_url: string }>( 'SELECT source_url FROM jobs WHERE refresh_enabled ORDER BY source_url', ); let needsAttention = !(await runLane(db, 'discovery', discoveryInput)); for (let offset = 0; offset < tracked.rows.length; offset += 100) { const listingUrls = tracked.rows .slice(offset, offset + 100) .map(row => row.source_url); const refreshInput = { mode: 'byUrls', listingUrls, postedWithinDays: 0, includeFullDescription: true, maxItems: listingUrls.length, }; if (!(await runLane(db, 'refresh', refreshInput))) { needsAttention = true; } } ingestionReport.needsAttention = needsAttention; } finally { try { if (db && locked) { await db.query( "SELECT pg_advisory_unlock(hashtext('job-listing-ingestion'))", ); } } finally { db?.release(); await pool.end(); } } The session lock serializes cooperating writers across both lanes. That protects the read-before-change comparison from overlapping schedules.
The trade-off is a database connection held during remote work. At larger scale, partition ownership and per-listing ordering deserve their own design.
An attention flag is a handled outcome, so the program finishes after committing its findings. An importing scheduler can inspect ingestionReport.needsAttention; an external monitor can query the durable ledger.
Route FAILED and ATTENTION attempts to your existing alerting system. Also alert on attempts left in STARTED beyond your expected runtime, because an interrupted process can't record its own ending.
Process completion and ingestion health are separate signals. Your monitor needs both.
What a successful run can't promise
The worked example uses Jobberman Nigeria Job Listings Scraper. The reusable pattern is separating discovery eligibility from repeated observation.
There are several boundaries worth keeping visible:
| Signal | What it supports | What it doesn't establish |
|---|---|---|
| Recent-posting match | Discovery within the selected window | An edit to an older posting |
| No published posting date | The record passes the date filter | A known publication time |
| Search ends on an empty page or 404 | Search pagination stops and found records are emitted | Closure of previously tracked listings |
| Tracked URL has no usable observation | Refresh needs investigation | Permission to mark the job closed |
A missing refresh leaves the previous row intact. The code records the missing URL separately because absence deserves investigation, not an invented closure event.
Likewise, a changed deadline is a content revision. This workflow doesn't interpret its date format or use it to infer whether applications remain open.
The discovery cap deserves an alert because reaching it makes coverage uncertain. Before increasing batch sizes, add dataset pagination and reconcile retrieval counts.
Costs also follow the fetch plan. Each refresh batch creates another run, with start charges, emitted-result charges and platform usage. maxItems bounds emitted records; it isn't a complete spending ceiling.
Keep the refresh watchlist intentional. Disable refresh explicitly through refresh_enabled when your retention policy says observation can stop.
Before handing this to on-call
- Confirm that discovery and refresh attempts are recorded separately.
- Alert on failed runs, rejected records, missing tracked URLs and discovery saturation.
- Monitor unfinished attempts independently of the importing process.
- Quarantine incompatible records without erasing prior job state.
- Keep every writer inside the same locking convention.
- Route downstream alerts from committed change events, with durable delivery tracking.
- Define when a tracked URL leaves the refresh watchlist.
A green discovery job proves that discovery ran. It says nothing about the salary you stopped looking at.
Drafted with AI assistance and reviewed for accuracy.

