Playground Sign in Start free

How to Keep a RAG Knowledge Base in Sync with a Website

Download runnable code Sign in to prefill your key
Webhook receiver (Flask / Express) Download
Start the daily crawl Download
1

Sync by comparing page hashes

To keep a RAG knowledge base in sync with a website, re-crawl the site on a schedule and compare each page's sha256 with the previous run: re-embed only the new and changed pages, and delete the chunks of pages that are gone. The Crawl API does not re-crawl only the changed pages by itself: every run reads, and bills, every page in scope, and your code compares the hashes. What you save is the work after the crawl, chunking, embedding and indexing, on every page that did not change.

Every page record of a crawl, and the job archive's manifest.json, carries the sha256 of the stored content, so a refresh can tell exactly which pages are new or different:

  1. A daily cron starts the crawl with a webhook URL and an Idempotency-Key.
  2. When the job ends, Ujeebu sends one signed POST to your receiver.
  3. The receiver checks the signature, answers at once, then downloads the job's archive and checks its checksum.
  4. It compares each page's sha256 with the previous run and processes only new and changed pages; pages that now answer 404 or 410 are removed.

This builds on Convert a website to Markdown for LLMs: same crawl, same chunks. Each run reads the same 20 Markdown pages, for 200 credits. In our two runs on the ujeebu.com docs, the first found 20 new pages and the second found all 20 unchanged. The use case Website to RAG knowledge base shows the whole pipeline.

A crawl bill you can trust

A free quote gives the most a crawl can cost before it starts, and max_credits is a hard cap: the job stops before a page that would pass it. Failed and blocked pages are not billed.

2

Start a daily crawl with a webhook

The script asks for the free quote, then starts the job with max_credits set to the quote's credits_ceiling and a webhook.url. The Idempotency-Key header carries the date: if cron runs it again the same day, the API returns the job already started instead of starting a second one.

#!/usr/bin/env python3
"""Start the docs crawl with a webhook, once a day (Ujeebu Crawl API).

The free quote gives the most the crawl can cost; the job is capped there with max_credits.
Run it from cron, for example every morning at 6:00:

    0 6 * * *  cd /srv/kb && UJEEBU_API_KEY=your-key WEBHOOK_URL=https://kb.example.com/hooks/crawl python3 start_crawl.py

The Idempotency-Key makes a retry on the same day return the same job instead of starting another.
"""
import datetime
import os

import requests

API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY")
API = "https://api.ujeebu.com"
WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "https://kb.example.com/hooks/crawl")   # your receiver

crawl = {
    "urls": ["https://ujeebu.com/docs"],
    "scope": {"include": ["/docs/**"], "max_pages": 20},
    "use_sitemap": True,
    "format": "markdown",
    "markdown": {"filter": "fit"},
    "webhook": {"url": WEBHOOK_URL},
}
headers = {"ApiKey": API_KEY}


def post(path, body, extra_headers=None):
    response = requests.post(API + path, json=body, headers={**headers, **(extra_headers or {})}, timeout=60)
    if response.status_code >= 400:
        raise SystemExit(f"{path}: {response.status_code} {response.text}")
    return response.json()


quote = post("/crawl/quote", crawl)
job = post("/crawl", {**crawl, "max_credits": quote["credits_ceiling"]},
           {"Idempotency-Key": f"docs-refresh-{datetime.date.today()}"})
print(f"at most {quote['credits_ceiling']} credits:", job)
Output
$ python3 start_crawl.py          # a second run on the same day
at most 200 credits: {'idempotent_replay': True, 'job_id': 'c_21815e27-063b-4e81-966b-c8310165d8b7', 'status': 'completed'}

The webhook host must resolve when you start the job: the API refuses an unknown host with a 400. You can also pass your own headers with webhook.headers, for example a routing header your gateway expects; they are never echoed back.

3

What the webhook sends

One POST when the job ends, with three headers and a JSON body. The event is crawl.job.completed, crawl.job.failed or crawl.job.cancelled.

Request (trimmed)
POST /hooks/crawl
X-Ujeebu-Signature: sha256=ec7cb671555e2...
X-Ujeebu-Timestamp: 1794914787
X-Ujeebu-Webhook-Id: 987567ee-f17f-47af-be0f-ebec011197d4

{
  "event": "crawl.job.completed",
  "job_id": "c_ae53274f-f2b4-4f40-9256-c2157591b301",
  "status": "completed",
  "stop_reason": "max_pages",
  "counts": {"discovered": 20, "pending": 0, "in_progress": 0, "done": 20, "failed": 0, "skipped": 0},
  "errors": {},
  "credits_used": 200,
  "archive": {
    "url": "https://storage.ujeebu.com/...signed link...",
    "size_bytes": 90943,
    "checksum_sha256": "737a9472d88b8363d8e885577291e2383a295a0144dd0592bdb3178f3f80cb28",
    "file_count": 21,
    "expires_at": "2026-11-20T11:26:21Z"
  },
  "timestamp": "2026-11-17T11:26:27Z"
}

The archive is a .tar.gz file: manifest.json (the job and every page record, each with its file and sha256) plus one file per page read, page-000001.md and so on. Its link is signed and valid for 48 hours from the time it is handed out.

4

Verify the signature

The signature is an HMAC-SHA256, keyed with your own API key, of the timestamp, a dot, and the raw request body. Check it before you trust anything in the body:

  • use the raw bytes as received: a parsed and re-encoded body will not match;
  • compare in constant time;
  • refuse a timestamp more than a few minutes old, so a captured call cannot be replayed later;
  • remember X-Ujeebu-Webhook-Id, so a repeated delivery is answered without running the refresh twice.
def signature_ok(raw_body, timestamp, signature):
    """HMAC-SHA256 of "<timestamp>.<raw body>" keyed with your API key, compared in constant time."""
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > MAX_AGE:
        return False
    digest = hmac.new(API_KEY.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest("sha256=" + digest, signature)


@app.post("/hooks/crawl")
def crawl_webhook():
    raw = request.get_data()   # the raw bytes: the signature covers them exactly
    if not signature_ok(raw, request.headers.get("X-Ujeebu-Timestamp", ""),
                        request.headers.get("X-Ujeebu-Signature", "")):
        abort(401)
    ...

We sent both receivers real deliveries and altered copies of them. What they answered:

CallFlaskExpress
A delivery from the API202202
The same X-Ujeebu-Webhook-Id again200, no second refresh200, no second refresh
A wrong signature401401
A timestamp 15 minutes old401401
A body changed after signing401401
5

Download the archive and compare hashes

Answer the webhook first (202), then do the work in the background: download the archive, check that its sha256 equals checksum_sha256, read manifest.json, and compare each page's hash with the one you stored last time.

for page in manifest["pages"]:
    url = page["url"]
    if page["state"] == "done":
        if hashes.get(url) == page["sha256"]:
            unchanged += 1
            continue
        reprocess(url, files[page["file"]].decode("utf-8"))   # chunk, embed, upsert
        hashes[url] = page["sha256"]
        changed += 1
    elif page.get("error_class") == "not_found" and url in hashes:
        remove(url)                 # the page is gone (404 or 410)
        del hashes[url]
        removed += 1

The first run on the ujeebu.com docs had no stored hashes, so every page was new:

Output (Flask receiver, trimmed)
  process  https://ujeebu.com/docs (762 chars)
  process  https://ujeebu.com/docs/apis (1662 chars)
  process  https://ujeebu.com/docs/apis/scrape (41520 chars)
  ...
  process  https://ujeebu.com/docs/sdks (794 chars)
c_ae53274f-f2b4-4f40-9256-c2157591b301: 20 new or changed, 0 unchanged, 0 removed (200 credits)

The same 20 pages delivered again, with the hashes from that first run:

Output (Express receiver)
c_ae53274f-f2b4-4f40-9256-c2157591b301: 0 new or changed, 20 unchanged, 0 removed (200 credits)
The crawl is billed, the rework is not

Every page the job reads is billed, changed or not. What the comparison saves is everything after the crawl: chunking, embedding and writing to your index. A second crawl of the same docs found all 20 hashes unchanged.

No archive at hand? The same sha256 is on every record of GET /crawl/{id}/pages, so the comparison also works from the page cursor. Page contents are kept for 72 hours after the job completes.

6

The complete receiver

Both receivers do the same thing and keep the hashes in page-hashes.json. Replace reprocess() and remove() with calls into your pipeline.

#!/usr/bin/env python3
"""Keep a knowledge base fresh with the Ujeebu Crawl API: the webhook receiver (Flask).

When a crawl job ends, Ujeebu sends one signed POST to /hooks/crawl. This receiver checks the
signature, answers at once, then downloads the job's archive, checks its checksum and compares
each page's sha256 with the previous run, so only new and changed pages are processed again.

    pip install flask requests
    UJEEBU_API_KEY=your-key python3 receiver.py
"""
import hashlib
import hmac
import io
import json
import os
import tarfile
import threading
import time

import requests
from flask import Flask, abort, request

API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY")   # webhooks are signed with your API key
HASHES_FILE = "page-hashes.json"   # url -> sha256 of the content last processed
MAX_AGE = 300                      # refuse a call signed more than 5 minutes ago

app = Flask(__name__)
seen_ids = set()                   # X-Ujeebu-Webhook-Id of the calls already accepted
lock = threading.Lock()            # one refresh at a time


def signature_ok(raw_body, timestamp, signature):
    """HMAC-SHA256 of "<timestamp>.<raw body>" keyed with your API key, compared in constant time."""
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > MAX_AGE:
        return False
    digest = hmac.new(API_KEY.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest("sha256=" + digest, signature)


def download_archive(archive):
    """The job's tar.gz archive as {file name: bytes}, once its sha256 matches."""
    raw = requests.get(archive["url"], timeout=300).content
    if hashlib.sha256(raw).hexdigest() != archive["checksum_sha256"]:
        raise ValueError("archive checksum mismatch")
    with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tar:
        return {m.name: tar.extractfile(m).read() for m in tar.getmembers() if m.isfile()}


def reprocess(url, markdown):
    """Your pipeline: chunk, embed and upsert this page (see the previous tutorial)."""
    print(f"  process  {url} ({len(markdown)} chars)")


def remove(url):
    """Your pipeline: delete this page's chunks from the knowledge base."""
    print(f"  remove   {url}")


def refresh(event):
    files = download_archive(event["archive"])
    manifest = json.loads(files["manifest.json"])
    with lock:
        hashes = {}
        if os.path.exists(HASHES_FILE):
            with open(HASHES_FILE) as f:
                hashes = json.load(f)
        changed = unchanged = removed = 0
        for page in manifest["pages"]:
            url = page["url"]
            if page["state"] == "done":
                if hashes.get(url) == page["sha256"]:
                    unchanged += 1
                    continue
                reprocess(url, files[page["file"]].decode("utf-8"))
                hashes[url] = page["sha256"]
                changed += 1
            elif page.get("error_class") == "not_found" and url in hashes:
                remove(url)                 # the page is gone (404 or 410)
                del hashes[url]
                removed += 1
        with open(HASHES_FILE, "w") as f:
            json.dump(hashes, f, indent=1)
    print(f"{event['job_id']}: {changed} new or changed, {unchanged} unchanged, "
          f"{removed} removed ({event['credits_used']} credits)")


@app.post("/hooks/crawl")
def crawl_webhook():
    raw = request.get_data()   # the raw bytes: the signature covers them exactly
    if not signature_ok(raw, request.headers.get("X-Ujeebu-Timestamp", ""),
                        request.headers.get("X-Ujeebu-Signature", "")):
        abort(401)
    webhook_id = request.headers.get("X-Ujeebu-Webhook-Id", "")
    if webhook_id in seen_ids:
        return "", 200         # a retry of a call already accepted
    seen_ids.add(webhook_id)
    event = json.loads(raw)
    if event["event"] != "crawl.job.completed":   # crawl.job.failed or crawl.job.cancelled
        print(f"{event['job_id']}: {event['event']} ({event['stop_reason']}), nothing to refresh")
        return "", 200
    threading.Thread(target=refresh, args=(event,), daemon=True).start()
    return "", 202             # answer at once; the refresh runs in the background


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8000)))
Run it
# Flask, the receiver saved as receiver.py
pip install flask requests
UJEEBU_API_KEY=your-key python3 receiver.py

# Express (Node.js 18 or later), the receiver saved as receiver.js
npm install express
UJEEBU_API_KEY=your-key node receiver.js
7

In production

Use HTTPS

Put the receiver behind HTTPS on a public URL. The Flask development server in the example is for trying it out; run a WSGI server in production.

Answer fast

Return a 2xx as soon as the signature checks out and do the refresh in the background, as both receivers do.

Store hashes with vectors

Keep the page hashes in your database next to the chunks, not in a file, when several workers run the receiver.

Watch delivery

GET /crawl/{id} shows webhook.delivered, attempts and last_status, plus the archive link to run a refresh by hand.

Size the site you want to keep in sync

The free sizer lists a site's sitemap URLs, quotes the crawl before you spend a credit and tests your webhook endpoint.

?

Frequently Asked Questions

How do I keep a RAG knowledge base in sync with a website?

Re-crawl the site on a schedule, and when the job ends compare each page's sha256 with the one you stored last time. Re-embed only the new and changed pages, and delete the chunks of pages that now answer 404 or 410. A signed webhook tells your server when the job is done.

Does the Crawl API re-crawl only the pages that changed?

No. Each job reads, and bills, every page in its scope. Your code compares the sha256 of each page with the previous run, which saves the work after the crawl: chunking, embedding and writing to your index.

How do I know which pages changed between two crawls?

Every page record, and the manifest.json of the job archive, carries the sha256 of the stored content. Keep a map of URL to sha256: a page is new when its URL is not in the map and changed when its hash differs. In our two runs of the same 20 documentation pages, all 20 hashes matched.

How do I verify the Ujeebu webhook signature?

Take X-Ujeebu-Timestamp and the raw request body, compute the HMAC-SHA256 of "<timestamp>.<body>" with your API key, and compare "sha256=<hex>" with X-Ujeebu-Signature in constant time. Refuse old timestamps, and parse the JSON only after the check.

What if the webhook does not reach my server?

GET /crawl/{id} shows webhook.delivered, attempts and last_status, plus the archive link. Run the same refresh from the job status: the archive link in it is valid for 48 hours from that call.

Which events does the crawl webhook send?

One POST when the job ends: crawl.job.completed, crawl.job.failed or crawl.job.cancelled. The body carries the job id, status, stop_reason, counts, errors, credits_used and the archive.