DEV Community

YatesHolloway6872
YatesHolloway6872

Posted on

Scrape Plus Embed Pipeline — What Fresh Market Evidence Looks Like

For a market research tool, a scrape plus embed pipeline looks like a scheduled fetcher feeding a versioned document store, followed by chunking, embedding, retrieval, and cited answers. Embed only changed content. The least complex credible design is a full initial crawl plus conditional refreshes, content-hash deduplication, and citation-aware retrieval.

Short answer: treat freshness and provenance as data, not metadata you can bolt on later. The pipeline is discover -> fetch -> normalize -> version -> chunk -> embed -> index -> retrieve -> answer -> cite. A page becoming stale or disappearing must change what the bot is allowed to say.

Choice Freshness Operational load Best fit
Full recrawl on every run Bounded by the run schedule High and repetitive Small, stable source sets
Conditional refresh plus content hashes Bounded by the run schedule Moderate Most market research corpora
Event-driven ingestion Potentially fastest Highest integration burden Sources you control

My default is the middle row. It outsources change detection to standard HTTP validators where publishers provide them, then uses a content hash as the backstop. A solo SaaS has to protect revenue-producing hours; building per-site event integrations rarely wins that trade unless the source is part of the product's own system.

What actually makes a scraped answer trustworthy?

Grounding has two separate requirements. Retrieval must find evidence relevant to the question, and the answer must expose evidence a reader can inspect. Retrieval-augmented generation was introduced as a way to combine a model's parametric memory with retrieved non-parametric memory. For market research, the practical consequence is blunt: a fluent answer without a resolvable source is unfinished.

Store each fetched representation with a canonical URL, retrieval time, observed publication time when the page supplies one, HTTP validator values, content hash, and a status. Keep the raw response or a lossless snapshot long enough to investigate extraction mistakes. The normalized text is a derived artifact. It should point back to both its source record and its extractor version.

Freshness is the first decision criterion. A retrieved chunk should inherit the source version's timestamps and status. Query policy can then distinguish a current page from an older snapshot rather than leaving the language model to infer freshness from prose. Do not silently replace history: append a new version when the meaningful normalized content changes, and mark older chunks inactive in the serving index.

The second criterion is citation integrity. A citation should identify the exact source version used to construct the answer, not merely the site's home page. Chunk IDs therefore need stable parent links. If normalization strips a navigation bar or repeated footer, store character offsets against the normalized document and a short quoted span with the retrieval result. That gives the application enough information to render a useful citation and enough evidence to reject a mismatched one.

This is where a lot of diagrams stop too early. An arrow from vector search to a model says nothing about whether source 17 was fetched yesterday, whether its text changed this morning, or whether the quoted sentence survived extraction. Those fields are part of the answer contract.

What does a scrape plus embed pipeline look like end to end?

The complete flow is explained here as a data path, not as a shopping list. Start discovery from an explicit source registry. It might contain competitor release pages, public pricing pages, documentation, and regulatory publications relevant to the market being studied. Each entry needs a scope rule. Following every link turns a focused corpus into an accidental web crawler and can pull account pages, calendars, and duplicate locale paths into the index.

Fetching should respect the Web's control signals. Check robots.txt before scheduling a URL. Use If-None-Match with a stored ETag or If-Modified-Since with a stored modification date when available; a 304 Not Modified response means the selected representation has not changed and avoids downloading its body again. Redirects must update the observed URL without discarding the identity of the source you requested.

Normalize after fetch. Remove navigation, cookie banners, repeated chrome, and scripts while preserving headings, lists, tables, and link text that carry meaning. Then hash the normalized content. Hashing raw HTML is noisy because analytics markup can change while the market evidence does not.

Chunking comes next, but chunk size is not a universal constant. Split first on document structure and only then apply a token ceiling. A pricing table and its heading should stay together; a 4,000-word legal page should not. Add a small overlap only when a boundary would otherwise sever a sentence or definition. More overlap creates more near-duplicates in retrieval.

Embedding is a deterministic transformation from chunk text plus an embedding-model identifier. Record that identifier and the vector dimension beside every index generation. When either the model or chunking logic changes, build a new generation and switch reads after it is complete. Mixing vector spaces from different embedding models in one similarity calculation is not a migration strategy.

At query time, filter out inactive source versions, retrieve candidates, and rerank if the corpus and latency budget justify it. Pass the selected text and citation metadata to the answer stage. The answer stage should be allowed to abstain when evidence is missing or conflicting. That behavior is more valuable than confident copy in a B2B research workflow.

A small TypeScript contract that keeps provenance intact

The implementation does not need a large framework. It needs boundaries that prevent a text string from losing its origin while moving between jobs. This stripped-down contract keeps those boundaries visible:

type SourceVersion = {
  sourceId: string;
  versionId: string;
  canonicalUrl: string;
  fetchedAt: string;
  publishedAt?: string;
  etag?: string;
  lastModified?: string;
  normalizedHash: string;
  status: "active" | "superseded" | "removed";
};

type Chunk = {
  chunkId: string;
  versionId: string;
  headingPath: string[];
  text: string;
  startOffset: number;
  endOffset: number;
  embeddingGeneration: string;
};

type Evidence = {
  chunk: Chunk;
  source: SourceVersion;
  score: number;
  quotedText: string;
};

interface PipelineStores {
  saveVersion(version: SourceVersion, normalizedText: string): Promise<void>;
  replaceActiveChunks(sourceId: string, chunks: Chunk[]): Promise<void>;
  search(query: string, limit: number): Promise<Evidence[]>;
}
Enter fullscreen mode Exit fullscreen mode

The crucial choice is boring: Evidence contains the chunk and its source version. If search returns only text and a score, every later layer has to reconstruct provenance, and eventually one will guess. I prefer spending a little more storage here because the trade-off buys faster debugging and fewer ambiguous citations; storage is undifferentiated infrastructure, while credible evidence is product behavior.

A refresh worker can avoid unnecessary embedding work by comparing normalized hashes. The numbers below are policy examples, not universal performance claims: four fetches in flight is a cautious starting point, and 12 retrieved candidates is a manageable set for a later ranking step.

async function refreshSource(
  sourceId: string,
  url: string,
  previous: SourceVersion | undefined,
  stores: PipelineStores,
): Promise<"unchanged" | "indexed"> {
  const response = await fetch(url, {
    headers: {
      ...(previous?.etag ? { "If-None-Match": previous.etag } : {}),
      ...(previous?.lastModified
        ? { "If-Modified-Since": previous.lastModified }
        : {}),
    },
  });

  if (response.status === 304) return "unchanged";
  if (!response.ok) throw new Error(`Fetch failed with status ${response.status}`);

  const html = await response.text();
  const normalized = normalizeReadableContent(html);
  const normalizedHash = await sha256(normalized);
  if (normalizedHash === previous?.normalizedHash) return "unchanged";

  const version = buildVersion(sourceId, url, response.headers, normalizedHash);
  const chunks = await chunkAndEmbed(normalized, version);

  await stores.saveVersion(version, normalized);
  await stores.replaceActiveChunks(sourceId, chunks);
  return "indexed";
}
Enter fullscreen mode Exit fullscreen mode

normalizeReadableContent, sha256, buildVersion, and chunkAndEmbed are deliberately local abstractions. Extraction rules, cryptographic hashing, version identity, and embedding configuration should be testable without running the whole crawl. The index replacement also needs an atomic visibility boundary: readers should see the old generation or the complete new one, never half of each.

Ship this vertically before broadening it. One source class, one extraction path, one index, one answer format.

Keep it narrow.

Weekly shipping favors a small loop whose failures can be inspected over a crawler platform with twenty knobs and no trustworthy citations. The HTTP behavior in this design follows RFC 9110, while crawler access rules follow RFC 9309; pinning those versions in the engineering note makes the operational assumptions checkable.

Operate the evidence, not just the jobs

Pipeline health is not equivalent to answer quality. A green fetch job can produce empty article text. A successful embedding request can index a cookie notice. Monitor the transitions that matter: discovered URLs versus fetched URLs, changed versus unchanged normalized hashes, extracted text length, chunks per source version, inactive chunks still returned by search, citation resolution failures, and answer abstentions. Consider the first refresh after a publisher redesign. The request succeeds, the validator changes, and the worker stores a new version, yet a selector aimed at the old article container extracts only the consent banner. Transport metrics call that run healthy. A normalized-text check catches the abrupt length drop; a shared-hash check may reveal the same banner across many URLs; a retrieval fixture fails because its expected heading has vanished. The right response is to quarantine the new versions, continue serving the last known good generation, and repair the extractor. This isn't a workaround for a specific service. It's the expected state transition for uncertain input: fetched, extracted, validated, then eligible for indexing. Making eligibility explicit prevents a routine page redesign from becoming unsupported research claims.

Fetches lie.

Alert on changes in distributions rather than pretending one threshold fits every site. A source that usually produces 30 chunks and suddenly produces zero deserves investigation. So does a template change that makes hundreds of pages share the same hash. These checks are cheap compared with having a customer open a citation that does not support the claim.

Testing needs three layers. Unit tests should pin normalization against saved HTML fixtures and verify stable hashes. Integration tests should run a small deterministic corpus through chunking, indexing, filtering, and citation resolution. Retrieval evaluation should use representative market-research questions with judged supporting sources, then track whether relevant evidence appears in the candidate set. The final answer can only be as grounded as that set.

Error handling should preserve state. A timeout must not deactivate the last known good version. A confirmed removal can mark a source unavailable according to retention policy, while a transient fetch failure schedules another attempt with backoff. Keep the distinction explicit.

Cost is a constraint, not the thesis. Fetch only on the cadence the decision needs, embed only meaningful changes, and cap query candidates before the answer stage. Measure worker time, bytes fetched, chunks embedded, index size, and answer latency per source class. Those counters tell a solo operator where maintenance is consuming feature time without turning the architecture into a pricing spreadsheet.

When is the runner-up design better?

A full recrawl is better when the allowlist is tiny, pages are small, and predictability matters more than bandwidth or embedding churn. Its state machine is easier to reason about. It is also a useful recovery path when stored validators or hashes cannot be trusted after an extractor migration.

Event-driven ingestion wins when you control the publishing system and it can emit a durable event after content commits. The event should carry a source identity, not the final chunk text; the ingestion worker still fetches or reads the canonical representation, versions it, and applies the same normalization and citation rules. Keep a periodic reconciliation job because event delivery and source state can diverge.

There is also a point where scraping is the wrong boundary. If a source offers an authorized, stable export containing the fields and timestamps the research tool needs, ingesting that structured representation removes extraction ambiguity. Preserve its record identity and provenance exactly as you would for a page.

Choose the simplest acquisition method that can prove what was known, from which representation, and when. For most public-web market research, conditional refresh plus versioned evidence provides that proof without turning the product into a crawler company. The retrieval layer then has one clear job: return current, inspectable support or admit that it cannot.

Further reading

Top comments (0)