October 22, 2026โ€ข5 min read

So Your RAG Stops Hitting 504: Split the Query Path From Ingestion

One RAG service that both parses uploads and answers queries will fall over the moment someone uploads a 200-page PDF. The cure is two paths and one queue.

Read in Indonesian

Building RAG during a hackathon feels instant. One FastAPI container, take a PDF, extract the text, build embeddings, store them in a vector database, all inside the same HTTP request. Show it to a friend, it looks cool.

Once the app meets real users, trouble arrives from a direction the demo never showed. Someone uploads a 200-page financial report full of tables. Parsing, chunking, and the embedding API calls take tens of seconds. The load balancer gives up first with 504 Gateway Timeout. What is more annoying: the CPU-hungry parsing pins the server thread. Other users' chat queries stall too.

So how do you build RAG that holds up, without renting a fiddly, expensive Kubernetes cluster? The answer is not a bigger machine, but separating two loads that are different by nature.

Key takeaways

  • The query path and the ingestion path have opposite load profiles, so ingestion has to move to an async worker backed by a queue.
  • Uploading through a GCS signed URL keeps the backend light, because files tens of megabytes big never pass through the API server's memory.
  • Cloud Tasks delivers tasks at-least-once and its deduplication only applies to explicitly named tasks, so the ingestion worker must be idempotent.
  • min-instances: 1 on the query service and 0 on the worker settles the cold start problem without paying for an idle instance.

Two paths with opposite natures

Inside a RAG system there are two workloads with opposite characters:

  • Query path: a user asks, the query is embedded (under 100 ms), vector search (under 50 ms), the LLM streams an answer. It is I/O-bound and wants latency as low as possible.
  • Ingestion path: a user uploads a document, layout parsing, chunking, hundreds of embeddings built, written to the index. It is CPU-bound and takes seconds to minutes.

If these two paths share CPU in the same service, your uptime is handed over to whichever user uploads big files the most. The golden rule is one: the ingestion path must be split into an async worker backed by a queue.

Why Cloud Run and Cloud Tasks

Many teams reach straight for Kafka or RabbitMQ on their own VM to manage background workers. That is fair, but for a small team the operational burden goes overboard. The serverless duo on GCP solves the same problem with no server to maintain:

  • Cloud Run: run any container, scale-to-zero when there is no traffic (when it is quiet, the bill is zero ๐Ÿ’ธ), and scale out to hundreds of instances automatically when the queue floods ๐Ÿš€
  • Cloud Tasks: a fully managed queue, with built-in rate limiting (say a maximum of 10 parallel tasks so the embedding provider's TPM/RPM quota does not blow), retry with exponential backoff (max_attempts defaults to 100, backoff up to 3600 seconds), and task deduplication. That last one has a condition, we get to it later.

The journey of one document, from upload to ready

Here is the life cycle of a document if you trace it in a mature RAG:

First, upload straight to storage. A 50 MB file never passes through the backend. The backend only creates a GCS signed URL, then the browser uploads the binary straight to the bucket. The API server's bandwidth and memory stay safe.

Second, enqueue and answer fast. Once the file lands in GCS, the backend creates a task in Cloud Tasks with a metadata payload (document_id, gcs_uri). Then it immediately returns HTTP 202 Accepted to the user. Other users' chat queries take no hit at all.

Third, the worker runs in a separate container. Cloud Tasks sends an HTTP POST to the worker endpoint on a different Cloud Run service. The steps form one chain: download the file, parse, chunk, batch embed. Then write to the vector store (Qdrant, Vertex AI Vector Search, or pgvector), update the document status to READY, and notify the user through a webhook or websocket.

The code, the part I could confirm runs

Now let's look at the code. This is the enqueue part, using google-cloud-tasks 2.26.0:

PYTHON
from google.cloud import tasks_v2
import json
import time
from fastapi import FastAPI, status

app = FastAPI()
tasks_client = tasks_v2.CloudTasksClient()

PROJECT_ID = "my-gcp-ai-project"
LOCATION_ID = "asia-southeast2"  # Jakarta region
QUEUE_ID = "document-ingestion-queue"

queue_path = tasks_client.queue_path(PROJECT_ID, LOCATION_ID, QUEUE_ID)

@app.post("/api/v1/documents/process", status_code=status.HTTP_202_ACCEPTED)
async def enqueue_document_processing(doc_id: str, gcs_uri: str):
    # 1. Build the task payload
    payload = {
        "document_id": doc_id,
        "gcs_uri": gcs_uri
    }

    # 2. Create the HTTP target task for the Cloud Run worker
    task = {
        # An explicit name means deduplication: the same name is rejected with ALREADY_EXISTS
        "name": f"{queue_path}/tasks/{doc_id}-{int(time.time() // 60)}",
        "http_request": {
            "http_method": tasks_v2.HttpMethod.POST,
            "url": "https://rag-worker-xyz-as.a.run.app/internal/tasks/ingest",
            "headers": {"Content-Type": "application/json"},
            "body": json.dumps(payload).encode(),
            # OIDC token for safe service-to-service auth inside GCP!
            "oidc_token": {
                "service_account_email": "tasks-invoker@my-gcp-ai-project.iam.gserviceaccount.com"
            }
        }
    }

    # 3. Put the task into the Cloud Tasks queue
    response = tasks_client.create_task(request={"parent": queue_path, "task": task})

    return {
        "status": "queued",
        "message": "Dokumen berhasil dimasukkan ke antrean pemrosesan asinkron.",
        "task_id": response.name
    }

What I could confirm without GCP credentials: the request shape is valid. queue_path builds out to projects/my-gcp-ai-project/locations/asia-southeast2/queues/document-ingestion-queue, and the task object serializes correctly into httpMethod: POST, an oidcToken with the right service account, and a whole JSON body. The real create_task that sends to the queue needs credentials, so I deliberately did not run that part here.

Two extra notes for this code. First, the oidc_token in that task is what lets the Cloud Run worker stay protected, as long as its service account holds the run.invoker role. But internal ingress has a condition: Cloud Tasks only counts as internal when the project is the same (or inside one VPC-SC perimeter) and you use the default run.app URL. If you turn the default URL off, or you use a custom domain, the calls stop working. So for a private worker, what you lean on is authentication, not just internal ingress. Second, Cloud Tasks treats a task as successful when the worker replies 2xx before the default 10-minute timeout (30 at most, if you raise it). If your 200-page PDF parsing takes longer than that, the task counts as failed. It gets retried, even though the work may not be wrong. You must tune that timeout number to your parsing load.

Two details you cannot see in the diagram

Architecture diagrams always look tidy. These two usually only show up after something falls over:

Cloud Tasks is at-least-once, not exactly-once. The official docs say it plainly: in rare cases a task runs more than once, and you have to make that repeat safe. That means you must make the worker idempotent: the same task arrives twice, the result must stay the same. It is the same principle as idempotent checkpoints in agent orchestration systems, just in another context.

Deduplication only applies to explicitly named tasks. Without a name, the same task can be sent twice if the caller retries create_task. With a name, Cloud Tasks rejects the duplicate with an ALREADY_EXISTS error. But there is a trap. A task name is remembered for 24 hours after the task finishes. Nine days, even, if the queue was created from queue.yaml. So if the name is only document_id, a user who re-uploads the same document within 24 hours gets rejected, not de-duped. From the outside it looks like the queue is broken. That is why the code above names it {document_id}-{epoch_menit}: the same upload is still de-duped within the same minute, but a re-upload the next day still goes through.

Cold start: one number per service

The classic serverless challenge is cold start, especially when the container loads heavy parsing libraries. The cure differs per service:

  • Query service: set min-instances: 1. There is always one warm instance, so the first user never eats a pause of several seconds. The cost is that the idle instance is still billed at the cheaper idle rate (in request-based billing mode, which is the default; in instance-based mode you pay the full rate while the instance lives).
  • Ingestion worker: leave it at min-instances: 0. Nobody is waiting at a screen, so scale-to-zero is safe, and the bill is zero when it is quiet.
  • Slim the image down: multi-stage build, no pip cache, a slim base image (say python:3.13-slim), so pulling the image stays quick.

What makes RAG strong is not the model

A RAG system that survives in production is not the one with the biggest LLM, but the one disciplined about who may use CPU when. Split the fast path from the heavy path, trust the queue to a service built for exactly that, and you only pay for compute while a document is actually being processed.

If your chat queries start crawling whenever someone uploads a document, the thing to blame is not the embedding model, it is the architecture. Split the paths first, the rest is a matter of numbers. May your 504s say goodbye ๐Ÿ˜„

Get better at shipping code.

Join the other developers getting tech updates, tips, and relaxed tutorials in their inbox every week.

Stay in the loop

Tech updates, coding tips, and relaxed insights straight to your inbox every week.

No spam. Unsubscribe anytime.

Read next

See all
LlmWhat a Prompt Cache Actually Remembers

Four providers cache the same bytes under four different rulebooks. The question that decides your bill: when the second request is longer than the first, does it reuse the whole prefix or only the part that was already written?

For developers who learn by struggling

ยฉ 2026 Inva.dev.