DEV Community

Sanjay Patoliya
Sanjay Patoliya

Posted on Originally published at sanjaypatoliya.com

RAG Silent Failure: When Your Embedding Pipeline Reports Success But Isn't Searchable

The Bug

A document gets uploaded. Textract extracts the text, Claude classifies it and writes a summary, the card in the UI flips to "Completed" with a green checkmark. Everything looks fine.

Then you ask the chat "what's in this document?" and get nothing back. The document is indexed, completed, searchable by every signal the UI shows you — except it isn't actually in the vector index at all.

The key problem: a failure three layers deep was being swallowed at the first layer, so by the time it reached the status the user sees, it had already turned into a success.

I hit this while running a buyer-style test of my own AI Document Processor template — uploading a handful of PDFs back-to-back through a fresh Voyage AI key with no payment method attached. Voyage's free tier caps you at 3 requests/minute and 10K tokens/minute. Upload three documents in a row and the fourth embedding call gets rate-limited.

The Bug

A document gets uploaded. Textract extracts the text, Claude classifies it and writes a summary, the card in the UI flips to "Completed" with a green checkmark. Everything looks fine.

Then you ask the chat "what's in this document?" and get nothing back. The document is indexed, completed, searchable by every signal the UI shows you — except it isn't actually in the vector index at all.

The key problem: a failure three layers deep was being swallowed at the first layer, so by the time it reached the status the user sees, it had already turned into a success.

I hit this while running a buyer-style test of my own AI Document Processor template — uploading a handful of PDFs back-to-back through a fresh Voyage AI key with no payment method attached. Voyage's free tier caps you at 3 requests/minute and 10K tokens/minute. Upload three documents in a row and the fourth embedding call gets rate-limited.


Root Cause

The old embedding function in the Lambda processor looked like this:

# backend/lambdas/processor/handler.py (before)
def _embed_texts(texts: list[str]) -> list[list[float]] | None:
    try:
        import voyageai
        client = voyageai.Client(api_key=os.environ.get("VOYAGE_API_KEY", ""))
        result = client.embed([t[:8000] for t in texts], model="voyage-3", input_type="document")
        return result.embeddings
    except Exception as e:
        logger.warning("embed_failed: %s", str(e))
        return None
Enter fullscreen mode Exit fullscreen mode

Three separate problems stacked on top of each other here:

  1. Any exception — including RateLimitError — was caught, logged at warning level, and swallowed. Nothing upstream ever learned the embeddings didn't exist.
  2. The caller stored chunks with embedding_vec = None when embeddings came back empty, instead of refusing to write incomplete rows.
  3. The document status was set to completed before any of this ran, because chunking/embedding was fire-and-forget, wrapped in its own try/except purely to stop one bad batch from crashing the whole Lambda:
# Step 4: update DB → COMPLETED
_update_document(doc_id, {"status": "completed", ...})

# Step 5: chunk text + generate embeddings + store in pgvector
try:
    _store_chunks(doc_id, result["pages"])
except Exception as e:
    logger.warning("chunk_store_failed: %s", str(e), extra={"doc_id": doc_id})
Enter fullscreen mode Exit fullscreen mode

The document ends up with a summary, a doc type, a "Completed" badge — and zero rows in the vector index. Nothing in the API response, the WebSocket push, or the UI ever surfaces that. The only way to notice is to search for something you know is in the document and get nothing back.

This is the failure mode that worries me most in RAG systems: not a wrong answer, but a correctly shaped success response for a search that silently never happened.


Root Cause

The old embedding function in the Lambda processor looked like this:

# backend/lambdas/processor/handler.py (before)
def _embed_texts(texts: list[str]) -> list[list[float]] | None:
    try:
        import voyageai
        client = voyageai.Client(api_key=os.environ.get("VOYAGE_API_KEY", ""))
        result = client.embed([t[:8000] for t in texts], model="voyage-3", input_type="document")
        return result.embeddings
    except Exception as e:
        logger.warning("embed_failed: %s", str(e))
        return None
Enter fullscreen mode Exit fullscreen mode

Three separate problems stacked on top of each other here:

  1. Any exception — including RateLimitError — was caught, logged at warning level, and swallowed. Nothing upstream ever learned the embeddings didn't exist.
  2. The caller stored chunks with embedding_vec = None when embeddings came back empty, instead of refusing to write incomplete rows.
  3. The document status was set to completed before any of this ran, because chunking/embedding was fire-and-forget, wrapped in its own try/except purely to stop one bad batch from crashing the whole Lambda:
# Step 4: update DB → COMPLETED
_update_document(doc_id, {"status": "completed", ...})

# Step 5: chunk text + generate embeddings + store in pgvector
try:
    _store_chunks(doc_id, result["pages"])
except Exception as e:
    logger.warning("chunk_store_failed: %s", str(e), extra={"doc_id": doc_id})
Enter fullscreen mode Exit fullscreen mode

The document ends up with a summary, a doc type, a "Completed" badge — and zero rows in the vector index. Nothing in the API response, the WebSocket push, or the UI ever surfaces that. The only way to notice is to search for something you know is in the document and get nothing back.

This is the failure mode that worries me most in RAG systems: not a wrong answer, but a correctly shaped success response for a search that silently never happened.


The Fix

Three changes, in order of how much they mattered:

1. Treat embedding failure as a real error, not a warning.

# backend/lambdas/processor/handler.py (after)
class EmbeddingError(Exception):
    """Embeddings could not be generated; the document can't be searched."""

def _embed_texts(texts: list[str], context) -> list[list[float]]:
    client = voyageai.Client(api_key=os.environ.get("VOYAGE_API_KEY", ""))
    embeddings: list[list[float]] = []

    for start in range(0, len(texts), _EMBED_BATCH_SIZE):  # 128 — Voyage's per-request cap
        batch = [t[:8000] for t in texts[start:start + _EMBED_BATCH_SIZE]]
        for attempt in range(_EMBED_MAX_ATTEMPTS):
            try:
                result = client.embed(batch, model="voyage-3", input_type="document")
                embeddings.extend(result.embeddings)
                break
            except RateLimitError as e:
                if attempt == _EMBED_MAX_ATTEMPTS - 1:
                    raise EmbeddingError("Voyage AI rate limit exceeded...") from e
                delay = _EMBED_BACKOFF_SECONDS[attempt] + random.uniform(0, 5)
                if context.get_remaining_time_in_millis() < delay * 1000 + _DEADLINE_MARGIN_MS:
                    raise EmbeddingError("...ran out of time...") from e
                time.sleep(delay)
    return embeddings
Enter fullscreen mode Exit fullscreen mode

No more None return. Either you get back exactly as many embeddings as you sent texts, or you get an exception with a message a user can act on ("add a payment method and re-upload"). The backoff schedule (20s / 40s / 60s + jitter) matches Voyage's free-tier window — just long enough to clear a 3 RPM cap without blowing the Lambda's timeout, which is why the retry loop also checks context.get_remaining_time_in_millis() before sleeping again. A Lambda that times out mid-retry would leave the document stuck on "processing" forever, which is its own silent failure.

2. Embed before you touch existing data, and never store a chunk without its embedding.

The old code deleted a document's existing chunks before generating new ones — so a failed re-index didn't just fail to add new chunks, it deleted the old working ones too. The fix flips the order: generate embeddings first, and only delete + insert once they're confirmed with zip(all_chunks, embeddings, strict=True), which throws if the counts ever mismatch instead of silently zipping short.

3. Make "completed" depend on indexing actually succeeding.

try:
    _store_chunks(doc_id, result["pages"], context)
except EmbeddingError as e:
    _update_document(doc_id, {
        "status": "failed",
        "error_message": f"Search indexing failed: {e}",
        ...
    })
    continue

_update_document(doc_id, {"status": "completed", ...})
Enter fullscreen mode Exit fullscreen mode

error_message is now a real column, exposed through the API schema and rendered on the document card in the frontend, so a failed upload says why it failed instead of a generic "please retry." A failed WebSocket push doesn't carry the message, so the frontend hook refetches the document on a failed event specifically to pick it up.


Lessons Learned

A caught exception that gets logged and ignored is a design decision, not a safety net. except Exception: return None felt defensive when I wrote it — "don't let one broken document crash the whole batch" — but it also meant the one signal that would've told the user something was wrong never left the Lambda.

Status fields need to mean what they say. "Completed" meant "the LLM steps ran" when it should have meant "this document is fully usable." Any state your UI shows the user should be downstream of everything that has to succeed for that state to be true — not set early for convenience and patched around later.

Free tiers change your error distribution, not just your error rate. On a paid Voyage key this bug might never surface — 3 RPM only bites when you're testing with a brand-new, unfunded account, which is exactly the account a first-time buyer of a template product would have. The failure mode that matters most in a product is often the one your own dev environment doesn't hit.

"It looks done" is not the same test as "it works." The card said Completed, the summary was there, Textract and Claude both did their job — every surface signal was green. The only way I caught this was deliberately testing the thing the UI doesn't show: searching for content I knew was in the document.


GitHub

Key code samples (RAG service, Lambda processor, CDK stacks) are available on GitHub:

👉 github.com/sanjaypatoliya/ai-document-processor-sample


About the Author

I'm Sanjay Patoliya — AWS Certified Generative AI Developer Pro, Solutions Architect & DevOps Engineer building production-ready AI systems on AWS. If you're looking to build something similar or need a remote AWS + AI engineer, feel free to reach out.

Top comments (19)

Collapse
 
kamalmosadegh profile image
Kamal Mosadegh •

Great write-up — the shape you describe (a correctly-shaped success for a search that never happened) shows up one layer earlier too, at extraction, and it's even harder to notice there because there's no rate-limit error to catch at all.

I benchmarked MarkItDown 0.1.9 against a two-path extractor on 20 mixed PDFs: pooled recall 0.61, and 15 of 20 files silently lost their rotated pages — a single 90° page went from recall 0.00 to 1.00 just by setting pdfminer detect_vertical=True. No exception anywhere; the markdown just looked complete. Same story as your Voyage 429, minus the log line.

Two checks that close it at that layer:

  1. A per-page character-count assertion right after extraction: a page that yields 0 characters is a failed page, not an empty page — route it to OCR or mark the document failed. The check costs one integer per page.
  2. Watch the t[:8000] truncation in your embed call — that's a second silent cut in the same function. Assert chunk length against input length, or a long document quietly loses its tail the same way it lost its embeddings.

Abdullah's per-document read-back is the right delivery gate for the index side; the per-page assertion is the matching gate for the extraction side. Status should be derived from the verification read, never set before the pipeline runs.

Collapse
 
sanjaypatoliya profile image
Sanjay Patoliya •

Thanks Kamal, good points. I don't check for empty pages after extraction yet, so I'll add that. The 8000 cut can't trigger today, since my chunks are only 800 characters, but a check would protect me if that changes. I use Textract, so I'd test rotated pages first. Setting the status only after checking the result is a great rule.

Collapse
 
kamalmosadegh profile image
Kamal Mosadegh •

Thanks — the empty-page check is the one that matters most, since that's the layer with no error to catch at all.

On the 8000 cut: you're right it can't trigger with 800-character chunks, and the assert is still worth the one line — it protects the day chunk size changes or a full-text embed path gets added. Assert chunk length against input length at the embed call, or log when a truncation happens, so the cut can never go silent again.

On Textract and rotated pages: Textract does orientation detection, so a rotated page may come back fine — but run one fixture anyway, a 90° page through Textract, and check the returned block order against the visual order. The per-page char-count assertion catches a page that returns nothing; it can't catch a page that returns everything in the wrong order. If Textract scrambles order on a rotated page, that's the layer where a geometry signal is needed, same as the OCR path in the STFG thread.

And the status rule is the one that ties both layers together: derive it from the verification read, never set it before the pipeline runs.

Collapse
 
userxnom profile image
Abdullah Naseer •

This is the failure mode that scares me most in RAG too — not a wrong answer, but a correctly shaped success. Your line "a caught exception that gets logged and ignored is a design decision, not a safety net" is the one I'd put on a wall. The except Exception: return None pattern feels defensive when you write it, and it is exactly what turns a rate limit into a document that looks indexed and isn't.

One thing I'd add to the fix list, and it's cheap: a read-back check before you flip the status. After indexing, run a canary query that should only match that document, and only mark it completed if the document actually comes back. It turns "it looks done" into "it works" without trusting any single layer's status.

The operational question I'm curious about: what happened to the documents that were already stuck in that state before the fix — the ones marked completed with zero rows in the vector index? Did you have a way to find them and re-index, or did they only surface when someone asked about a specific document?

Collapse
 
sanjaypatoliya profile image
Sanjay Patoliya •

Thanks Abdullah, a canary query is a cheap check and I like it. It's on my backlog as a post-ingest probe, and your framing is better than how I'd written it down.

To answer your question honestly: the documents that were already stuck were found by hand. I noticed the problem when I searched for something I knew was in a document and got nothing back. There was no automated sweep. Because it was a small set of test documents, I re-uploaded them after the fix.

At any real scale that wouldn't be enough. The sweep is simple: find every "completed" document with zero rows in the vector table, then re-queue those. I haven't built it yet. Running it as a one-off before turning on the canary check would catch the old backlog, and the canary would stop new ones appearing.

Collapse
 
alexshev profile image
Alex Shev •

A completed status should mean every promised retrieval invariant holds, not merely that extraction finished. I would expose indexed-chunk count, embedding model/version, and a post-index probe in the document state so rate-limit failures cannot turn into a believable but empty success.

Collapse
 
sanjaypatoliya profile image
Sanjay Patoliya •

Good list. The chunk count and the probe are already on my to-do list, and I agree the status should depend on them. The model and version one I hadn't thought of. It would matter if I ever change the embedding model, because old and new vectors can't be searched together. I'll add it.

Collapse
 
ascendra_ventures_92c21f2 profile image
Ascendra Ventures •

The green checkmark telling the truth about the upload and nothing about the search is a clean way to describe it. The fix you landed on in the comments, that green should mean searchable rather than uploaded, is really a rule about who owns the final status: the step that can prove the outcome, not the first step that finished without an exception.

Ascendra Ventures applied the same rule to a candidate pipeline for a seed-stage talent platform. Each profile went through enrichment, OpenAI batch parsing, embeddings and database writes, and any slow step could leave a person in an unclear state. The problem was stated as every candidate should finish or visibly fail, never sit in the middle. The processor moved into a durable workflow that waits for the batch jobs, falls back to polling when the webhooks go quiet, and finalizes every person's status at the end so failed work shows up. The write-up states 99.99% system reliability at $0.004 per candidate imported.

Your canary query and the per-document read-back catch different failures. Once the read-back is in, would you still keep a status between processing and completed, something like indexed but unverified, so a stuck document is visible without anyone having to search for it?

Collapse
 
sanjaypatoliya profile image
Sanjay Patoliya •

Yes, I would. Three states: processing, indexed (embeddings saved, not yet checked), and completed (checked). A document that sits in "indexed" too long shows up on its own, so nobody has to search for it. I'd also add a timer that marks it failed after a set time. Right now I only have processing, completed and failed, so this is the next step, not built yet.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

the green completed checkmark is the part that stings. the document looked indexed by every signal the ui showed while the fourth embedding call was rate-limited three layers down.

Collapse
 
sanjaypatoliya profile image
Sanjay Patoliya •

Exactly. The checkmark was telling the truth about the upload, not about the search. Now it only turns green once the document can be found.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

that is the fix. green should mean searchable, not just uploaded.

Collapse
 
the_daily_flare profile image
The daily flare •

Would your 3 requests per minute Voyage cap leave my own completed document with zero rows in its vector index too?

Collapse
 
sanjaypatoliya profile image
Sanjay Patoliya •

It depends on two things. First, whether you're on Voyage's free tier (no payment method), which is what has the 3 per minute cap. Second, whether your code swallows the error and still marks the document completed, like mine did. If either one isn't true, you probably won't see it. The quickest check is to count the document's rows in the vector table. Zero rows on a "completed" document means it hit this.

Collapse
 
dafili profile image
Renhua Wei •

Generating embeddings before the delete closes most of the window, but the delete and the insert are still two separate steps: the DELETE commits, the first insert batch dies on a 429 or a pgvector write, and the doc is emptier than before the fix. Writing chunks under a per-document version and flipping one pointer after a SELECT count(*) on that version leaves the old rows answering queries until the swap, so a failed re-index degrades to stale instead of unsearchable. Are the delete and insert in one transaction, or does the Lambda just retry the document from scratch?

Collapse
 
paragonaimag profile image
Paragon •

Your 'Completed' badge with zero rows in the index is the same shape as our podcast dashboard saying 'Avg episode downloads 84' when 191 downloads across 30 episodes works out to 6.4.

Collapse
 
sanjaypatoliya profile image
Sanjay Patoliya •

That's a good example. In both cases the aggregate looks fine and nobody checks it against the raw rows. The fix is the same too: verify the number against the source before you show it.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.