Keeping a Bedrock Knowledge Base in Sync: S3 Landing Zone, Change Detection, Ingestion Jobs, Failures and Alarms

When you first build a knowledge base, one click on "Sync" in the console is enough. Once it is in production, other questions show up. Why does a policy withdrawn last week still appear in answers? Why is yesterday's announcement missing? Did a sync half fail without anyone noticing? Why are the old and new versions of the same document both retrieved? These are what happens when people keep the source systems and the knowledge base aligned by hand. This post builds a sync pipeline: S3 as the landing zone, finding changed documents, running ingestion jobs, catching failures and raising alarms.

Field notes · Amazon Bedrock · Knowledge Bases · Ingestion pipeline

The security setup of the knowledge base itself is in Building RAG on a closed network, and syncing document permissions as metadata is in Document access control. This post assumes both and covers only following content as it changes.

Keeping a Bedrock Knowledge Base in Sync: S3 Landing Zone, Change Detection, Ingestion Jobs, Failures and Alarms

Know this first: what sync does and does not do

Syncing an S3 data source (an ingestion job) does more than you might expect, but its boundaries are clear.

  • What it does: Sync is incremental. It processes only documents added, modified or deleted in S3 since the last sync. Unchanged documents are skipped, documents whose content or metadata changed are parsed, chunked, embedded and indexed again, and documents deleted from S3 are removed from the vector store.
  • What it does not do: It knows nothing about the source systems (document management, groupware, file servers). The knowledge base's reference is S3, and mirroring the sources into S3 is your job. It does not start syncs on its own either.
  • One at a time: One ingestion job can run at a time per data source and per knowledge base, and five per account. StartIngestionJob is limited to 0.1 requests per second. All of these are listed as non-adjustable default quotas, so check the current values.
  • Job status and document results are different things. The job status is one of STARTING, IN_PROGRESS, COMPLETE, FAILED, STOPPING or STOPPED, and per-document results appear separately in the statistics (statistics) and in the knowledge base logs. If you look only at the status, you miss failures of individual documents.
  • Right after it finishes, data may not be visible yet. The docs say that for stores other than Aurora, new embeddings can take a few minutes to become queryable after the job completes.

So the pipeline has four parts. Mirror the sources into S3 (mirror), flag that something changed (request), run one ingestion at a time (start), and check the result and alert (check).

The overall structure

From a source change to search results
Mirror job
Compare the source listing with the manifest · Skip when hashes match · Deletes protected by a ratio cap
S3 landing zone
Stable keys from source IDs · Metadata first · Versioning · Data source sees only current/
Sync request flag
S3 event → EventBridge → Lambda records only "something changed" in DynamoDB
Starter (scheduled)
Every few minutes · StartIngestionJob if something changed and no job is running · clientToken
Checker and alarms
GetIngestionJob statistics · Per-document failures in the KB logs · Custom metrics · Time since last good sync
Top to bottom: finding changes and running ingestion are kept apart, so a burst of events still runs only one job at a time.

Step 1: design the S3 landing zone as a mirror of the source

Sync follows the state of S3 exactly, so which keys you put in S3 and what they hold is the content of the knowledge base.

  • Let the data source see only the current/ prefix. Set the S3 data source's inclusion prefix to current/ and write files still being converted to staging/. Sync then never picks up a half-written file.
  • Derive keys from source IDs. File names easily carry versions, like "policy_v3_final.pdf". If you use the name as the key, the new version lands next to the old one and both are retrieved. If the key is fixed by the source system's document ID, a new version overwrites the same key and sync treats it as a modification.
  • Turn on bucket versioning. If a faulty mirror run deletes or overwrites documents, you can restore earlier versions. A lifecycle rule removes noncurrent versions after a set period.
  • Do not let data sources share prefixes. If two data sources in the same knowledge base see the same object, you get two copies of that document's chunks.
import hashlib
import re

def s3_key(system: str, source_id: str, ext: str) -> str:
    """Build a stable key from the source document ID. No title or version in the key."""
    safe = re.sub(r"[^A-Za-z0-9_-]", "_", source_id)
    shard = hashlib.sha256(source_id.encode()).hexdigest()[:2]   # spread prefixes
    return f"current/{system}/{shard}/{safe}.{ext}"

# s3_key("edms", "DOC-2024-00172", "pdf")
# -> current/edms/3f/DOC-2024-00172.pdf  (+ .pdf.metadata.json)

Title, version and revision date go into the metadata file (<file name>.metadata.json) instead of the key. The metadata file must have exactly the same name and extension as the source file, or it is ignored.

Step 2: find what changed, with a manifest

The mirror job takes the source listing and compares it with a DynamoDB manifest table. One item is one source document.

AttributePurpose
source_id (partition key)Document ID in the source system
s3_keyKey built with the rule from step 1
content_sha256, meta_sha256Hashes of the converted body and the metadata. If they match, nothing is written
last_seenThe run ID that last saw it in the source listing. Used to decide deletions
import hashlib, json, time
import boto3

s3 = boto3.client("s3")
table = boto3.resource("dynamodb").Table("kb-manifest-edms")
BUCKET, MAX_DELETE_RATIO = "kb-docs-edms", 0.05

def sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()

def mirror(run_id: str, docs):          # docs: (source_id, body, meta) tuples from the source
    changed, seen = 0, set()
    for source_id, body, meta in docs:
        seen.add(source_id)
        key = s3_key("edms", source_id, "pdf")
        meta_b = json.dumps({"metadataAttributes": meta}, ensure_ascii=False).encode()
        item = table.get_item(Key={"source_id": source_id}).get("Item", {})
        if item.get("content_sha256") == sha(body) and item.get("meta_sha256") == sha(meta_b):
            table.update_item(Key={"source_id": source_id},          # unchanged: do not write
                              UpdateExpression="SET last_seen = :r",
                              ExpressionAttributeValues={":r": run_id})
            continue
        s3.put_object(Bucket=BUCKET, Key=key + ".metadata.json", Body=meta_b)   # metadata first
        s3.put_object(Bucket=BUCKET, Key=key, Body=body)
        table.put_item(Item={"source_id": source_id, "s3_key": key, "last_seen": run_id,
                             "content_sha256": sha(body), "meta_sha256": sha(meta_b)})
        changed += 1

    gone = [i for i in table.scan()["Items"] if i["source_id"] not in seen]  # pagination omitted
    total = len(seen) + len(gone)
    if total and len(gone) / total > MAX_DELETE_RATIO:
        raise RuntimeError(f"delete guard: {len(gone)}/{total} documents vanished")  # alarm on this
    for i in gone:
        s3.delete_objects(Bucket=BUCKET, Delete={"Objects": [
            {"Key": i["s3_key"]}, {"Key": i["s3_key"] + ".metadata.json"}]})
        table.delete_item(Key={"source_id": i["source_id"]})
    return changed + len(gone)

Three things to notice in the code:

  • If the hashes match, nothing is written to S3. The docs do not state what comparison sync uses, so whether rewriting identical content counts as "no change" is not documented. The safe option is not to write at all. Not writing also means no re-embedding cost.
  • Deletions happen only on a full listing. Because the job deletes "documents not seen in this run", an erroring source API that returns an empty list would delete everything. Above a ratio cap (5% here) the job stops and a person checks. Bucket versioning is the way back in that case.
  • When only permissions change, only metadata is written. If the body hash matches and only the metadata hash differs, the knowledge base can, under certain conditions, update metadata without re-embedding. The conditions are in step 3 of the document access control post.
Going deeper: why keep both change events and a full reconciliation

If the source system offers a change feed (webhooks, a change log table), it is tempting to drive the mirror from that alone. It is fast and cheap. But an event-driven approach cannot notice events it missed. Ten minutes while the webhook receiver was being deployed, or a bulk migration on the source side that emitted no events, leave data out of step for good. So you usually keep both. During business hours, mirror only the documents that change events point to, and once a night take the full listing and reconcile it with the manifest. If deletions happen only in the full reconciliation, the event handler deals only with additions and modifications and stays simple, and the risk of wrong deletions sits in one place.

Step 3: start ingestion jobs, on a schedule and from events

Do not call StartIngestionJob directly for every S3 event. With one concurrent job per data source, the second call fails with a conflict error, and the call limit is 0.1 per second. A hundred documents uploaded at once produce a hundred events. So separate flagging "something changed" from starting the job.

  • Turn on EventBridge notifications on the bucket, have a rule receive Object Created and Object Deleted events for the current/ prefix only, and let a Lambda write the current time to last_change in a DynamoDB state table. That is all it does.
  • EventBridge Scheduler calls the starter Lambda every few minutes. If there is a change flag and no job running, it starts a job.
  • Even with no events at all, let the starter run a job once a day. If the event path breaks, things never drift by more than a day.
import time
import boto3
from botocore.exceptions import ClientError

agent = boto3.client("bedrock-agent")
state = boto3.resource("dynamodb").Table("kb-sync-state")
KB_ID, DS_ID = "KB12345678", "DS12345678"
RUNNING = {"STARTING", "IN_PROGRESS", "STOPPING"}

def handler(event, context):
    s = state.get_item(Key={"ds": DS_ID}).get("Item", {})
    changed_at, started_at = float(s.get("last_change", 0)), float(s.get("last_started", 0))
    daily = time.time() - started_at > 24 * 3600          # once a day even with no events
    if changed_at <= started_at and not daily:
        return "nothing to do"
    jobs = agent.list_ingestion_jobs(knowledgeBaseId=KB_ID, dataSourceId=DS_ID,
                                     sortBy={"attribute": "STARTED_AT", "order": "DESCENDING"},
                                     maxResults=1)["ingestionJobSummaries"]
    if jobs and jobs[0]["status"] in RUNNING:
        return "job running, retry next tick"
    token = f"kbsync-{DS_ID}-{int(changed_at)}-{int(started_at)}".ljust(33, "0")  # 33+ chars
    t0 = time.time()                                       # changes after this go to the next job
    try:
        job = agent.start_ingestion_job(knowledgeBaseId=KB_ID, dataSourceId=DS_ID,
                                        clientToken=token,
                                        description=f"changes up to {int(t0)}")["ingestionJob"]
    except ClientError as e:
        if e.response["Error"]["Code"] in ("ConflictException", "ThrottlingException"):
            return "busy, retry next tick"
        raise
    state.update_item(Key={"ds": DS_ID},
                      UpdateExpression="SET last_job = :j, last_started = :t",
                      ExpressionAttributeValues={":j": job["ingestionJobId"], ":t": str(t0)})
    return job["ingestionJobId"]

Field tip: If a new file arrives while a job is running, you cannot tell whether this job picked it up. So the starter records the time just before starting the job as last_started, and any later last_change always goes to the next job. If this job already picked up the file, the next job simply runs once more. Running once more costs little, because sync is incremental and skips what did not change. Missing a change costs a lot. clientToken must be at least 33 characters, and calling again with the same token is ignored without an error. The code above builds the token from the state it read, so even if the Lambda is retried after the job started but before the state was written, you do not get two jobs.

The job state change events in Bedrock's EventBridge documentation are mainly for model customization and batch inference jobs; an ingestion job state change event is not in the list at the time of writing. So to learn when a job ends, the checker in the next step calls GetIngestionJob periodically. The list of supported events can change, so check the current docs. If you need a flow with more steps, you can move this into a Step Functions wait-and-poll loop as in the batch inference pipeline.

Step 4: check results and handle partial failures

Every few minutes the checker reads the last job (last_job) and publishes the numbers as metrics. The time of the last good sync is recorded as the time the job finished (updatedAt).

cw = boto3.client("cloudwatch")

def check(job_id):
    job = agent.get_ingestion_job(knowledgeBaseId=KB_ID, dataSourceId=DS_ID,
                                  ingestionJobId=job_id)["ingestionJob"]
    st, stats = job["status"], job.get("statistics", {})
    if st == "COMPLETE" and stats.get("numberOfDocumentsFailed", 0) == 0:
        state.update_item(Key={"ds": DS_ID}, UpdateExpression="SET last_good = :t",
                          ExpressionAttributeValues={":t": str(job["updatedAt"].timestamp())})
    last_good = float(state.get_item(Key={"ds": DS_ID})["Item"].get("last_good", 0))
    put("SecondsSinceLastGoodSync", time.time() - last_good)   # on every checker run
    if st in RUNNING:
        put("JobRunningSeconds", time.time() - job["startedAt"].timestamp())  # alarm if too long
        return st
    put("DocumentsFailed", stats.get("numberOfDocumentsFailed", 0))
    put("DocumentsIndexed", stats.get("numberOfNewDocumentsIndexed", 0)
        + stats.get("numberOfModifiedDocumentsIndexed", 0))
    put("DocumentsDeleted", stats.get("numberOfDocumentsDeleted", 0))
    put("JobFailed", 1 if st == "FAILED" else 0)
    for reason in job.get("failureReasons", [])[:20]:
        print("failure:", reason)                       # reasons the whole job failed
    return st

def put(name, value):
    cw.put_metric_data(Namespace="KbSync", MetricData=[{
        "MetricName": name, "Value": float(value),
        "Dimensions": [{"Name": "DataSource", "Value": DS_ID}]}])

The statistics hold only document counts, not "which document and why". That is in the knowledge base logs. Turn on log delivery for the knowledge base (log type APPLICATION_LOGS, destination CloudWatch Logs, S3 or Data Firehose) and each document's status is recorded. Pull out only the failed documents with CloudWatch Logs Insights.

fields @timestamp, event.document_location.s3_location.uri as uri,
       event.status as status, event.status_reasons.0 as reason
| filter event.ingestion_job_id = "JOB1234567"
| filter status in ["EMBEDDING_FAILED", "INDEXING_FAILED", "DELETION_FAILED",
                    "METADATA_UPDATE_FAILED", "FAILED", "PARTIALLY_INDEXED", "RESOURCE_IGNORED"]
| sort @timestamp desc
| limit 200

Common failure causes and where to look:

SymptomLook here first
RESOURCE_IGNOREDUnsupported format, size over the limit (the ingestion job file size quota for files with text content), metadata file name mismatch. The reason is in status_reasons
EMBEDDING_FAILEDEmbedding model permissions, throttling on the model side, KMS permissions of the service role
INDEXING_FAILEDStore-side limits (for example S3 Vectors metadata size), store capacity, field mappings
The job itself is FAILEDfailureReasons. Settings that affect every document, such as the bucket policy, KMS or the store's network policy

The docs do not state clearly whether a failed document is retried automatically on the next incremental sync. After fixing the cause, make it a procedure to write the object again (for example, have the mirror job clear the hash in the manifest so it uploads again), sync, and confirm in the logs that the document ended as INDEXED. If you stopped a job with StopIngestionJob, the docs say starting again ingests the rest.

Step 5: prevent duplicate and stale chunks

"An old policy shows up in answers" is almost always one of these.

CauseHow to prevent it
A versioned file name creates a new objectStep 1: stable keys from source IDs
An archive copy sits inside the data source prefixLimit the inclusion prefix to current/, keep archives in another bucket
Two data sources see the same objectCheck before deployment that data source prefixes do not overlap
Deleted at the source but still in S3Step 2: delete in the nightly full reconciliation
Deleted from S3 but no sync ranStep 3: delete events also set the flag, plus a forced sync once a day
A document added through the direct ingestion API is not in S3With an S3 data source, keep S3 as the reference. Use the direct ingestion API together with S3

Verify with retrieval. A search filtered to the S3 address of a deleted document must return zero results. The knowledge base attaches each chunk's source location as x-amz-bedrock-kb-source-uri metadata, so use that as the filter key. Behaviour can differ by store, so confirm it once yourself.

rt = boto3.client("bedrock-agent-runtime")

def chunks_left(uri: str, probe: str) -> int:
    r = rt.retrieve(knowledgeBaseId=KB_ID, retrievalQuery={"text": probe},
                    retrievalConfiguration={"vectorSearchConfiguration": {
                        "numberOfResults": 10,
                        "filter": {"equals": {"key": "x-amz-bedrock-kb-source-uri", "value": uri}}}})
    return len(r["retrievalResults"])

# for each deleted document: use its title or first sentence as the probe
assert chunks_left("s3://kb-docs-edms/current/edms/3f/DOC-2024-00172.pdf", "travel expense claim deadline") == 0

Field tip: Sometimes the same content arrives twice under different source IDs, like an announcement posted on two boards. Add a second index on the body hash in the manifest, and log a warning when a new document's body hash already exists under another source_id. Do not remove it automatically: if the two boards have different permissions, both may be needed.

Step 6: alarms

Set alarms on the custom metrics published in step 4. The numbers are starting points; adjust them to your business needs.

AlarmCondition (example)Meaning
Stale26 hours since the last good syncEven the daily forced sync failed. The most important alarm
Document failuresDocumentsFailed > 0Partial failure. Find the documents with the step 4 query
Job failureJobFailed = 1A configuration problem. Check failureReasons
Stuck jobJobRunningSeconds several times the usualA large change set or a slow store
Delete guardThe mirror job's delete guard error in the logsSomething is wrong with the source listing. No deletions until a person checks
Mass deletionDocumentsDeleted above the usualA large deletion that passed the guard. Confirm it was intended

The stale alarm must also catch the case where no data arrives at all, so treat missing data as breaching. If the checker itself dies, the metric stops.

aws cloudwatch put-metric-alarm \
  --alarm-name kb-edms-stale \
  --namespace KbSync --metric-name SecondsSinceLastGoodSync \
  --dimensions Name=DataSource,Value=DS12345678 \
  --statistic Maximum --period 3600 --evaluation-periods 2 --datapoints-to-alarm 2 \
  --threshold 93600 --comparison-operator GreaterThanThreshold \
  --treat-missing-data breaching \
  --alarm-actions arn:aws:sns:ap-northeast-2:111122223333:kb-ops

The threshold of 93,600 seconds is 26 hours. The checker runs every few minutes and publishes the time since the last good sync whatever the state of the last job, so the alarm fires when the value is over the threshold for two hours in a row or when the metric stops.

Step 7: test it

Run the items below against a test knowledge base and record the results. Judge by retrieval results and logs.

  • Add a new document → appears in search within the agreed time (for example 15 minutes), log status INDEXED
  • Modify the body → searching with the old sentence no longer returns the old chunk
  • Change only the metadata (permissions) → the metadata-modified count in the statistics goes up, results change under the new filter
  • Delete at the source → after the nightly reconciliation chunks_left is 0
  • Upload a new version of the same document → only one copy in results
  • Slip in one broken file → the job finishes, the DocumentsFailed alarm fires, the document is in the logs
  • Make the source API return an empty list → stopped by the delete guard, no change in S3
  • Upload 50 files within a minute → only one (or two) ingestion jobs start
  • Upload a new file while a job is running → the change flag stays and the next job handles it
  • Disable the starter Lambda → stale alarm after 26 hours

Checklist

  • Data source inclusion prefix current/, files in conversion under staging/
  • Stable keys from source IDs, title and version in metadata
  • Bucket versioning and a lifecycle rule for noncurrent versions
  • No overlapping prefixes between data sources
  • Manifest: body and metadata hashes, nothing written when unchanged
  • Deletions only in the full reconciliation, with a ratio cap and an alarm
  • S3 events only set a flag, the scheduled starter runs one job at a time
  • clientToken (33+ characters) and retry on the next tick after conflicts or throttling
  • Knowledge base logs (APPLICATION_LOGS) on, the failed-document query saved
  • Custom metrics and alarms: stale, document failures, job failures, stuck jobs, mass deletion
  • A procedure to confirm by retrieval that deleted documents have zero chunks left
  • Step 7 test results recorded

Quotas, ingestion job behaviour, supported file formats and the list of events change. Before you apply any of this, check the data source sync and knowledge base logging (CloudWatch Logs) sections of the Amazon Bedrock User Guide, StartIngestionJob and GetIngestionJob in the API reference, the Bedrock quotas in the AWS General Reference, and the Amazon S3 documentation on EventBridge notifications. If you are studying for an exam, the same topics show up on AWS AIP-C01 and DEA-C01 (data ingestion and pipelines): you can practice related questions on cert-bank.

Comments