
When RAG Pipelines Fail: Engineering Reliable Document Ingestion with AWS
Handling duplicate events, failed ingestion jobs, stale knowledge, and recovery in an AI-powered university assistant.

1. Introduction: The Hidden Reliability Problem in RAG
UniAssist lets students ask questions grounded in university documents: handbooks, examination regulations, fee schedules, accommodation rules. The retrieval layer, Amazon Bedrock Knowledge Bases, gets most of the design attention. But a retrieval system answers from whatever its index currently contains. If the index is wrong, a flawless retriever and a strong model will produce a confident, well-cited, wrong answer.
"Upload a PDF to S3 and sync" hides several failure modes that only appear under real operational conditions:
- Duplicate uploads and duplicate events. An administrator double-clicks "Publish", or the browser retries a multipart upload. Separately, S3 delivers events to EventBridge at least once, so even a single upload can produce more than one notification. Hypothetically, the Examinations Office uploads Â
exam-regulations-2026.pdfÂonce and the pipeline starts two ingestion attempts for it.
- Failed processing. A scanned handbook that is actually an encrypted or truncated PDF passes the upload but never becomes searchable.
- Incomplete ingestion. A sync job can finish while some documents in the batch failed. "Job complete" does not mean "every document is searchable."
- Outdated policies. The 2025 late-submission policy is replaced by the 2026 one. Until the old chunks leave the index, students can be told the wrong deadline.
- Volume spikes. At semester start, departments upload dozens of documents within minutes. Ingestion jobs are quota-limited, so naive "one job per upload" fails.
- Temporary service failures. Throttling, transient 5xx errors, and Lambda cold failures are routine at scale.
- Synchronization delay. Data sources are synced by an explicit ingestion job. Between upload and job completion, the index is stale by definition.
The central argument of this article: a RAG application is only as trustworthy as the knowledge pipeline behind it. The engineering goal is not just "documents eventually get indexed" but a system that can say, at any moment, which version of which document is authoritative, whether it is searchable yet, and what to do when it isn't.

2. Proposed AWS Architecture
2.1 Flow
- An administrator, authenticated through Cognito and authorized server-side, uploads a document and its metadata sidecar to a private S3 bucket.
- S3 sends object events to Amazon EventBridge (bucket-level EventBridge notifications must be enabled).
- An EventBridge rule filters on Â
source: aws.s3Âand the relevant Âdetail-typeÂvalues (ÂObject CreatedÂ, ÂObject DeletedÂ) and targets an SQS queue.
- A Lambda function consumes the queue, validates the object, and registers the request.
- DynamoDB records document versions and processing state.
- A Step Functions workflow orchestrates the synchronization.
- The workflow starts a Bedrock Knowledge Base ingestion job and polls its status until it reaches a terminal state.
- CloudWatch collects logs, metrics, and alarms.
- Messages that exhaust their retries land in a dead-letter queue (DLQ).

2.2 Responsibilities and why each service is here
Service | Responsibility | Why it belongs |
|---|---|---|
S3 | Durable document store; versioning enabled | Source of truth for bytes. Versioning gives each overwrite a distinct identifier. |
EventBridge | Routing and filtering of S3 events | Pattern matching by prefix/suffix/type, and multiple targets without changing S3 config. |
SQS (+DLQ) | Buffer between events and compute | Absorbs spikes, enables retries with visibility timeouts, isolates poison messages. |
Lambda (registrar) | Validate, register, decide whether to trigger sync | Short, stateless logic. |
DynamoDB | Version registry, processing state, idempotency records, sync lock | Conditional writes give atomic claim semantics. |
Step Functions | Long-running sync orchestration | Retries, backoff, waits, and failure branches are declarative and visible. A Lambda should not sleep-poll for minutes. |
Bedrock Knowledge Base | Chunking, embedding, indexing, retrieval | Managed ingestion; UniAssist does not build its own indexer. |
CloudWatch | Logs, metrics, alarms | Operational visibility. |
2.3 Who talks directly to whom
- S3 → EventBridge is direct (native integration). S3 does not talk to SQS in this design; EventBridge sits in between so routing can evolve.
- EventBridge → SQS is a direct rule target. Delivery failures to the target can be sent to a separate DLQ configured on the target. That DLQ is distinct from the consumer-side DLQ.
- SQS → Lambda is mediated by a Lambda event source mapping, which polls the queue; SQS does not "push".
- Lambda → Step Functions is an explicit Â
StartExecutionÂcall, not an event.
- Step Functions → Bedrock needs a decision. Step Functions has AWS SDK integrations for a large and growing list of services, but I have not verified that the Â
bedrock-agentÂÂStartIngestionJobÂ/ ÂGetIngestionJobÂactions are available as direct integrations in the target Region. Dependency: check the "AWS SDK service integrations" list. The conservative design used here wraps those calls in a small Lambda, which also gives a place to normalize errors. If the direct integration exists, it can replace the wrapper.

3. Handling Duplicate Events with Idempotency
3.1 Why duplicates are normal
S3 delivers events to EventBridge at least once and does not guarantee ordering. A standard SQS queue is also at-least-once. A Lambda function can time out after doing its work but before the message is deleted, so the message reappears after the visibility timeout. Duplicates are therefore a property of the platform, not a bug to be eliminated. The consumer must make processing the same event twice equivalent to processing it once.
3.2 Identity: what makes two events "the same"
UniAssist needs two identifiers:
- Â
documentIdÂ: stable across versions (for example, Âexam-regulationsÂ), derived from the S3 key layout Âdocuments/{documentId}/{filename}Â.
- Version identity: the S3 object version ID (Â
version-idÂin the event detail for versioned buckets). Two events for the same Â(bucket, key, versionId)Âdescribe the same bytes.
The idempotency key is therefore Â
(documentId, versionId) . Do not use the EventBridge event  id : a re-upload of identical content is a new event but the same logical work only if the version is the same, and a duplicate delivery may be a distinct delivery of the same S3 event. Keying on the S3 version is semantically stable. This requires bucket versioning, which is a stated requirement of this design.3.3 Claiming with a conditional write
A single DynamoDB Â
UpdateItem with a condition expression acts as an atomic claim. It succeeds if the item does not exist, or if a previous worker's lease expired (it crashed), or if a previous attempt ended in a retryable failure. Under concurrent delivery, exactly one writer wins.import { DynamoDBClient } from "@aws-sdk/client-dynamodb";import { DynamoDBDocumentClient, UpdateCommand } from "@aws-sdk/lib-dynamodb";import { S3Client, HeadObjectCommand, GetObjectCommand } from "@aws-sdk/client-s3";import type { SQSEvent, SQSBatchResponse } from "aws-lambda";
const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));const s3 = new S3Client({});const TABLE = process.env.TABLE_NAME!;const LEASE_SECONDS = 120; // must be well below the SQS visibility timeout
class PermanentError extends Error {} // retrying will not help
export const handler = async (event: SQSEvent): Promise<SQSBatchResponse> => { const batchItemFailures: { itemIdentifier: string }[] = []; for (const record of event.Records) { try { await processRecord(JSON.parse(record.body), record.messageId); } catch (err) { if (err instanceof PermanentError) { // Already recorded as REJECTED inside processRecord; acknowledge, don't retry. console.log(JSON.stringify({ level: "WARN", msg: "permanent_failure", reason: err.message })); } else { batchItemFailures.push({ itemIdentifier: record.messageId }); // retry via SQS } } } return { batchItemFailures }; // requires ReportBatchItemFailures on the event source mapping};
async function processRecord(evt: any, messageId: string) { const bucket = evt.detail.bucket.name as string; const key = decodeURIComponent(evt.detail.object.key as string); const versionId = evt.detail.object["version-id"] as string | undefined; if (!versionId) throw new PermanentError("bucket versioning disabled or event lacks version-id");
const m = /^documents\/([a-z0-9-]+)\/[^/]+\.pdf$/.exec(key); if (!m) throw new PermanentError(`unexpected key layout: ${key}`); const documentId = m[1];
const now = Math.floor(Date.now() / 1000); const pk = `DOC#${documentId}`; const sk = `VER#${versionId}`;
// 1. Atomic claim. Fails if another worker holds a live lease or the version is already past REGISTERING. try { await ddb.send(new UpdateCommand({ TableName: TABLE, Key: { pk, sk }, UpdateExpression: "SET #s = :registering, leaseExpiresAt = :lease, s3Key = :key, bucket = :bucket, " + "firstSeenAt = if_not_exists(firstSeenAt, :now), attempts = if_not_exists(attempts, :zero) + :one", ConditionExpression: "attribute_not_exists(pk) OR (#s = :registering AND leaseExpiresAt < :now) OR #s = :retryable", ExpressionAttributeNames: { "#s": "processingState" }, ExpressionAttributeValues: { ":registering": "REGISTERING", ":retryable": "RETRYABLE_FAILURE", ":lease": now + LEASE_SECONDS, ":now": now, ":key": key, ":bucket": bucket, ":zero": 0, ":one": 1, }, })); } catch (e: any) { if (e.name === "ConditionalCheckFailedException") { return; // duplicate or in-flight: safe no-op, message is acknowledged } throw e; // throttling etc.: let SQS retry }
// 2. Validate (permanent failures are recorded, not retried). try { await validatePdf(bucket, key, versionId); } catch (e) { if (e instanceof PermanentError) { /* UpdateCommand: SET processingState = REJECTED, rejectionReason */ } throw e; }
// 3. Register. The condition prevents a late duplicate from regressing state. await ddb.send(new UpdateCommand({ TableName: TABLE, Key: { pk, sk }, UpdateExpression: "SET #s = :registered, registeredAt = :now REMOVE leaseExpiresAt", ConditionExpression: "#s = :registering", ExpressionAttributeNames: { "#s": "processingState" }, ExpressionAttributeValues: { ":registered": "REGISTERED", ":registering": "REGISTERING", ":now": now }, })); // 4. Then try to acquire the per-data-source sync lock and start the workflow (Section 4).}
async function validatePdf(bucket: string, key: string, versionId: string) { // HeadObject: reject size 0 or > 50 MB; ranged GetObject bytes 0-4 must equal "%PDF-" // otherwise throw new PermanentError(...)}
3.4 What this does and doesn't protect
- Race between two concurrent deliveries: only one Â
UpdateItemÂsatisfies the condition; the loser returns without side effects.
- Worker crash mid-flight: the lease expires, so the redelivered message can reclaim the item. The lease must be shorter than the SQS visibility timeout, or the redelivered message will be treated as "in flight" and no one retries until another redelivery.
- Safe retries downstream: Â
StartIngestionJobÂaccepts a ÂclientTokenÂ; if a later request reuses a token, Bedrock ignores it without error. Derive the token from a sync batch ID so a retried workflow step does not start a second job. The documented token length is 33 to 256 characters.

4. Designing a Reliable Ingestion Workflow
4.1 A constraint that shapes everything
An ingestion job is scoped to a data source, not a single document. It scans the source and incrementally processes added, modified, and deleted content. AWS's reference solution for automatic sync reports quota constraints: five concurrent ingestion jobs per account, one per knowledge base, one per data source, and a Â
StartIngestionJob rate limit of 0.1 requests per second (one every 10 seconds) per Region. Treat those as figures to re-verify in Service Quotas, since quotas change.Consequences for UniAssist:
- Do not start one job per uploaded file. Many registered documents should be coalesced into one job.
- Only one sync workflow should run per data source at a time. UniAssist enforces this with a lock item in DynamoDB (Â
pk = LOCK#<kbId>#<dataSourceId>Â), acquired with a conditional write like the one above. The registrar attempts to acquire it after registering a document; the winner calls ÂStartExecutionÂ. Losers do nothing, because the running workflow's final step re-checks for documents registered after the job started.
- A document registered during a running job may or may not be covered by that job. The workflow therefore compares Â
registeredAtÂagainst the job's ÂstartedAtÂand loops if anything newer exists. This is the "dirty watermark" check below.
4.2 Conceptual workflow

4.3 Behaviour of each concern
Retries and backoff. Step Functions Â
Retry supports  ErrorEquals ,  IntervalSeconds ,  MaxAttempts ,  BackoffRate ,  MaxDelaySeconds , and  JitterStrategy ( FULL or  NONE ). Use full jitter so that several retrying executions don't synchronize. Retries count as state transitions for billing.Catch and failure states. A Â
Catch routes to a state after retries are exhausted. Distinguish error classes. Errors named by the Bedrock SDK ( ThrottlingException ,  ConflictException ,  ServiceQuotaExceededException ,  InternalServerException ) surface from a Lambda wrapper if it rethrows them by name. Treat  ThrottlingException and  InternalServerException as retryable;  ConflictException and quota errors mean "capacity not available right now" (wait and retry with a longer interval);  ValidationException and  AccessDeniedException are configuration defects and must not be retried.Timeouts. Set Â
TimeoutSeconds on each task and an overall execution timeout. Without a polling deadline, a stuck job holds the lock forever. On timeout, the workflow should call  GetIngestionJob once more and, only if it is still running well past any plausible duration, record the batch as  RETRYABLE_FAILURE and surface an alarm. Whether to call  StopIngestionJob is an operational decision, not an automatic one.Polling. Ingestion is asynchronous. Â
StartIngestionJob returns immediately (HTTP 202) with a job in a starting state;  GetIngestionJob returns  status ( STARTING ,  IN_PROGRESS ,  COMPLETE ,  FAILED , plus stopping states),  statistics , and  failureReasons . A  Wait +  Task +  Choice loop is the standard pattern, with a wait interval chosen against cost (each loop iteration is state transitions).Interpreting "COMPLETE". Â
COMPLETE with  numberOfDocumentsFailed > 0 is partial success. Dependency: statistics are aggregate counts, and  failureReasons is job-level; verify how much per-document attribution your data source type gives. If it's coarse, the safe response is to quarantine the whole batch for human review rather than mark individual documents  INDEXED on a guess.4.4 Conceptual versus deployable
The diagram and the notes above are a conceptual workflow. A deployable state machine additionally needs: concrete ARNs and IAM roles, payload size and Â
ResultPath handling, error names verified against actual SDK responses, execution naming/lock-release guarantees (the lock needs a TTL so a dead workflow can't hold it forever), and tests against a non-production knowledge base. Per task, use  Retry blocks (short intervals for  ThrottlingException / InternalServerException , longer for  ConflictException /quota errors, all with  JitterStrategy: FULL ) and  Catch blocks routing  ValidationException / AccessDeniedException to  FailBatchPermanent and everything else to  FailBatchRetryable . Whether the wrapper Lambda surfaces SDK errors under those names depends on how it is written.
5. Preventing Stale University Knowledge
This is where reliability becomes trust. A student asking "what is the penalty for late coursework?" should never receive last year's rule, and should never receive both years' rules blended into one answer.
5.1 Version model
Store each version as an immutable S3 object under a version-aware layout, for example Â
documents/{documentId}/v{n}/{filename}.pdf with a sibling  {filename}.pdf.metadata.json . UniAssist's DynamoDB registry holds the authoritative lifecycle state; the S3 sidecar carries the attributes the retriever can filter on.Version states (proposed): Â
REGISTERED → INDEXED → ACTIVE → SUPERSEDED | EXPIRED | DELETED , plus  REJECTED and  QUARANTINED .Each registry item (Â
pk = DOC#<documentId>Â , Â sk = VER#<versionId>Â ) stores title, department, owner, versionNumber, publishedAt, effectiveFrom, expiresAt, lifecycleStatus, processingState, supersedes, s3Key, lastIngestionJobId, correlationId and attempts.Metadata sidecar example. For S3 data sources, metadata lives in a file named like the document with Â
.metadata.json appended; AWS documents a 10 KB limit per metadata file. Attributes can be strings, numbers, or booleans:{ "metadataAttributes": { "documentId": "exam-regulations", "department": "Examinations Office", "versionNumber": 4, "status": "ACTIVE", "publishedAtEpoch": 1788220800, "expiresAtEpoch": 0 }}Dates are stored as epoch numbers because numeric comparison filters are the reliable way to filter on time. (Dependency: verify the metadata format your Knowledge Base version expects. AWS documents both a simple key/value form and a typed form with Â
includeForEmbedding .)5.2 Two layers of defense
A single metadata filter is not enough, because the index lags reality (a sync takes time, and a job isn't atomic across documents). UniAssist uses two layers:
Layer 1: retrieval-time metadata filtering. The backend calls Â
Retrieve with a filter such as:{ "andAll": [ { "equals": { "key": "status", "value": "ACTIVE" } }, { "greaterThan": { "key": "expiresAtEpoch", "value": <now> } }] }(Use a sentinel far-future value for documents without expiry so one numeric comparison suffices.) This keeps superseded chunks from crowding out good results in the top-k.
Layer 2: post-retrieval verification against DynamoDB. Each retrieved chunk carries its source location and metadata. The backend checks every result's Â
(documentId, version) against the registry and drops any chunk whose version is not currently  ACTIVE , before the text reaches the model. This layer is what makes deletion and supersession immediate from the student's perspective: marking a version  DELETED or  SUPERSEDED in DynamoDB hides it instantly, without waiting for an ingestion job. If filtering removes everything, UniAssist should answer "I couldn't find a current source" rather than fall back to old material.The registry is thus the authority; the vector index is a cache of searchable content that must be reconciled to it.
5.3 Lifecycle scenarios
- Updated handbook. Upload v5 with its sidecar. After the sync batch containing it completes successfully, promote v5 to Â
ACTIVEÂand v4 to ÂSUPERSEDEDÂin one DynamoDB transaction (ÂTransactWriteItemsÂ). Then update v4's sidecar to Âstatus: SUPERSEDEDÂso the next sync fixes the index. Fail-safe ordering: the old version stays active until the new one is confirmed indexed. A failed ingestion leaves students on the previous valid policy rather than on nothing.
- Revised exam policy with an effective date. Keep Â
effectiveFromÂ. A future-dated policy can be ÂINDEXEDÂbut not ÂACTIVEÂuntil its date; a scheduled task flips it. Beware the window where both are "valid-looking": the registry should hold exactly one ÂACTIVEÂversion per ÂdocumentIdÂ, enforced by the transaction.
- Expired announcements. Set Â
expiresAtÂ. Retrieval filtering and post-verification both honor it, so expiry works even if no re-sync ever runs.
- Deleted documents. S3 emits an Â
Object DeletedÂevent; with versioning, a plain delete creates a delete marker, and the event's Âdeletion-typeÂdistinguishes ÂDelete Marker CreatedÂfrom ÂPermanently DeletedÂ. The registrar sets ÂDELETEDÂimmediately (Layer 2 hides it). The next ingestion job removes it from the index because incremental syncs process deleted content. Dependency: confirm in a test environment how the S3 connector treats delete markers in a versioned bucket.
- Conflicting versions. Two administrators upload competing versions of the same Â
documentIdÂwithin minutes. Reject ambiguity: the registry transaction promotes only the highest ÂversionNumberÂallocated by a conditional counter on the document item, and a lower-numbered late arrival is registered as ÂSUPERSEDEDÂon arrival or sent to ÂQUARANTINEDÂfor human decision.

6. Failure Recovery and Dead-Letter Queues
6.1 The SQS mechanics
- Visibility timeout. While a worker processes a message, it is hidden. AWS guidance for Lambda is to set the queue's visibility timeout to at least six times the function timeout (plus the batching window if one is configured), so throttled retries don't reappear prematurely. Lambda validates that the function timeout doesn't exceed the visibility timeout.
- Retry limit. Â
maxReceiveCountÂon the redrive policy moves a message to the DLQ after that many receives. AWS recommends at least 5 for Lambda sources.
- Partial batch responses. With Â
ReportBatchItemFailuresÂ, only failed messages return to the queue.
- DLQ is for unexpected failures. Known-permanent failures (an invalid PDF) are recorded in DynamoDB and acknowledged, not retried five times and then parked. The DLQ should mean "a human needs to look at a case the code didn't anticipate."
6.2 Scenario table (Proposed)
Scenario | Detection | Automatic behavior | Investigation | Recovery |
|---|---|---|---|---|
Invalid PDF uploaded | Registrar validation (magic bytes, size) fails | Version →  REJECTED with reason; message acknowledged; no retry | Query registry for  REJECTED ; notify owner | Admin uploads a corrected file as a new version. Never redrive. |
Lambda invocation fails (throttling, timeout, bug) |  Errors / Throttles metrics; message  ApproximateReceiveCount rising | Message returns after visibility timeout; idempotent claim makes retry safe | Logs by correlation ID | Fix cause, let SQS retry; if DLQ'd, redrive after the fix |
Bedrock ingestion job fails |  GetIngestionJob status  FAILED with  failureReasons | Workflow marks batch failed; classifies error | Read  failureReasons ; check data source access and file issues | Permanent cause (bad file, permissions): fix, then new sync. Transient: workflow retry |
Event delivered more than once | Conditional write fails; duplicate-skipped log/metric | No-op; message acknowledged | A high duplicate ratio is informational | None needed |
Queue accumulates messages | Rising  ApproximateNumberOfMessagesVisible ,  ApproximateAgeOfOldestMessage | Messages wait; Lambda scales per event source mapping settings | Is the consumer erroring, throttled, or just slow? Is a sync lock stuck? | Fix consumer; cap concurrency if downstream is the bottleneck |
Ingestion takes too long | Workflow polling deadline or execution timeout | Batch →  RETRYABLE_FAILURE ; alarm; lock released with TTL as backstop |  GetIngestionJob statistics: is it still progressing? Unusually large batch? | Decide manually whether to stop the job; re-run |
6.3 Controlled redrive
Redriving a DLQ is a deliberate act:
- Triage first. Sample DLQ messages and group by failure cause using correlation IDs. Do not redrive a message whose cause is permanent. It will fail again, consume retries, and pollute metrics.
- Fix the cause (deploy a code fix, restore a permission, correct metadata).
- Redrive gradually. SQS supports moving messages from a DLQ back to a source queue (console DLQ redrive, and the Â
StartMessageMoveTaskÂAPI), with a rate cap on message movement. Start with a small sample, watch the failure metrics, then continue.

7. Monitoring and Observability
7.1 Metrics
Some metrics exist natively; others are custom metrics UniAssist would emit (for example via CloudWatch embedded metric format). Names of the custom ones below are proposals.
Signal | Source | Why it matters |
|---|---|---|
Documents uploaded | Custom ( DocumentsUploaded ) | Baseline volume |
Documents successfully processed | Custom ( DocumentsIndexed ) | Throughput |
Failed ingestion jobs | Custom, from workflow | Pipeline health |
Queue depth | SQS  ApproximateNumberOfMessagesVisible | Backlog |
Age of oldest queued message | SQS  ApproximateAgeOfOldestMessage | Best indicator of "stuck" |
Processing duration | Custom, upload→ ACTIVE | Freshness of knowledge |
Retry count | Custom ( attempts ) or  ApproximateReceiveCount | Hidden instability |
DLQ message count | SQS on the DLQ | Alarm at > 0 |
Ingestion completion rate | Computed: indexed / uploaded over a window | Overall reliability |
Alarm on age of oldest message and DLQ > 0 first. They catch most silent failures.
7.2 Structured logs and correlation IDs
Generate a Â
correlationId at registration (or propagate one from the upload API) and carry it in the DynamoDB item, the Step Functions input, and every log line. One query then reconstructs a document's path across Lambda, the workflow, and the sync client.Log records should be structured JSON containing Â
timestamp ,  level ,  service ,  event ,  correlationId ,  documentId ,  versionId ,  processingState ,  attempt and  durationMs . They should omit document text, student identifiers, and presigned URLs.
8. Security and Data Integrity
Why frontend-only restrictions fail. Hiding the "Upload" button for non-admins in React is a usability feature. Any user can call the backend or storage APIs directly with their own valid token. Authorization must be enforced where the action happens: at the API/Lambda layer (validating Cognito tokens and group claims) and in IAM.
- Separate roles. Administrators (Cognito group, verified server-side) may upload; students may only call the question-answering API. Students never receive credentials that can read the bucket or call Â
bedrock-agentÂ.
- Least-privilege IAM per function. The registrar gets DynamoDB access on one table, Â
s3:GetObjectÂ/ÂHeadObjectÂon the documents prefix, and Âstates:StartExecutionÂon one state machine. The sync client gets only Âbedrock:StartIngestionJobÂ, ÂGetIngestionJobÂ, and optionally ÂStopIngestionJobÂ, scoped to the knowledge base ARN. The student-facing backend gets Âbedrock:RetrieveÂ(and generation permissions as needed) but no ingestion rights.
- Private bucket. Block Public Access on; no public ACLs; access through IAM roles and, for uploads, short-lived presigned URLs issued by the backend after authorization.
- Encryption. Server-side encryption at rest (SSE-KMS gives key-level audit and access control); a bucket policy denying requests without TLS (Â
aws:SecureTransportÂ). DynamoDB and SQS encrypt at rest as well. If SQS uses a customer managed KMS key, grant EventBridge and the Lambda role the necessary key permissions.
- Validation and upload limits. Enforce type, size, and key-prefix rules server-side (and in the presigned URL conditions), then validate content (magic bytes) again in the registrar. Extension checks alone are not validation.
- Audience control. AWS documents that data synced into a knowledge base becomes retrievable by anyone with Â
bedrock:RetrieveÂpermission on it. Staff-only or confidential documents therefore should not share a knowledge base with student-facing ones unless the backend enforces an audience metadata filter server-side. A separate knowledge base is the stronger boundary.

9. Testing the Pipeline
All entries below are Proposed. No test has been performed and no results exist. Run them against a non-production knowledge base and record evidence in the right-hand column.
# | Test scenario | Expected behavior | Metric / evidence to collect | Status |
|---|---|---|---|---|
1 | Normal upload of PDF + sidecar | Version registered → sync →  INDEXED →  ACTIVE ; document retrievable with correct metadata | DynamoDB state history;  GetIngestionJob output; a  Retrieve call result; upload→ ACTIVE duration | Not run |
2 | Duplicate event delivery (replay same event twice, concurrently) | One claim wins; the other is a no-op; one ingestion batch | Conditional-check-failure count; single job ID; no duplicate rows | Not run |
3 | Invalid file (renamed  .txt , truncated PDF) |  REJECTED , message acknowledged, not in DLQ | Registry reason; DLQ count unchanged; retry count = 0 | Not run |
4 | Temporary failure (inject throttling in the sync client) | Retries with backoff, then succeeds; one job | Retry attempts in execution history; final  ACTIVE | Not run |
5 | Permanent failure (revoke Bedrock permission in test) | No futile retries; batch marked permanent failure; alarm fires | Execution path through  FailBatchPermanent ; alarm state | Not run |
6 | Updated document version | New version  ACTIVE , old  SUPERSEDED ; students never see old chunks after promotion | Registry transaction;  Retrieve results with and without Layer 2 | Not run |
7 | Deleted document | Immediately hidden by Layer 2; removed from index after next sync | Registry  DELETED timestamp; retrieval result before/after sync | Not run |
8 | DLQ recovery | Redrive after fix processes messages idempotently; permanent cases are not redriven | Message-move task output; DLQ drained; final states | Not run |

10. Cost and Architecture Trade-offs
Serverless is not cost-free. Chatty designs (tight polling, aggressive retries, verbose logging) scale cost with activity. No cost figures are given because none have been measured.
Decision | Option A | Option B | Trade-off |
|---|---|---|---|
Lambda invocation | Direct from events | SQS buffering | SQS adds a component and latency, but provides buffering, retry control, DLQ, and backpressure. For bursty uploads against a rate-limited API, buffering is justified. |
Ingestion | Managed Knowledge Base sync | Custom chunk/embed/index pipeline | Managed ingestion removes substantial engineering and gives metadata filtering out of the box, but you accept its quotas, rate limits, and limited per-document visibility. A custom pipeline gives fine-grained control (per-document status, custom chunking) with much more to build and operate. |

11. Conclusion
Reliable ingestion for a RAG system comes down to a few engineering commitments:
- Assume duplicates and reordering. Key idempotency on Â
(documentId, S3 versionId)Âand claim with conditional writes.
- Respect the shape of the ingestion API. Jobs are per data source, asynchronous, quota-limited, and not a per-document guarantee, so coalesce, serialize with a lock, and poll to a terminal state.
- Separate permanent from transient failure. Retry the second with backoff and jitter; record and surface the first.
- Make the registry the authority. The vector index is a lagging cache. Filter at retrieval and verify against DynamoDB before generation, so supersession, expiry, and deletion take effect immediately.
- Instrument for staleness, not just errors. Age of the oldest message and time from upload to Â
ACTIVEÂmeasure what students actually experience.
The takeaway: in a RAG system, correctness is a property of the index lifecycle, not just of retrieval. Treat every document version as a state machine with an explicit authority record, and a stale or failed ingestion degrades into "no current source found" rather than into a confidently wrong answer.

References
AWS documentation for Bedrock Knowledge Bases ingestion, S3 EventBridge events, Lambda SQS event source mappings, and Step Functions error handling.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article