AWS Builder Center
How to Build a Zero-Server RAG Pipeline with Amazon Bedrock, Lambda, and pgvector

How to Build a Zero-Server RAG Pipeline with Amazon Bedrock, Lambda, and pgvector

A hands-on, production-tested architecture guide to deploying a scalable, cost-effective Retrieval-Augmented Generation (RAG) system entirely on serverless AWS infrastructure.

Deploying Retrieval-Augmented Generation (RAG) applications often begins with dedicated cluster management, idle compute bills, and operational overhead.
By combining Amazon Bedrock, AWS Lambda, and Amazon Aurora Serverless v2 (PostgreSQL with  pgvector ), you can run an enterprise-grade semantic search pipeline that automatically scales down to zero when unused.
Here is the exact architecture, setup steps, and implementation code.

1. High-Level Architecture

The flow separates the indexing process from the real-time query interface:
User Request ──► API Gateway / Function URL ──► Query Lambda
│
┌─────────────────── Bedrock ───────────────┤
│ (Titan Embeddings / Claude Sonnet) │
▼ ▼
Vector Embeddings Vector Similarity Search
│
▼
Aurora Serverless v2
(pgvector store)
  1. Ingestion Flow: Documents uploaded to Amazon S3 trigger an event-driven processing Lambda that chunks text, calls Bedrock's embedding model, and persists vector embeddings into PostgreSQL.
  1. Retrieval Flow: The user query is embedded into a dense vector via Amazon Bedrock, queried against Aurora via Cosine Similarity ( <=> ), and passed with retrieved chunks into an LLM for context-grounded completion.

2. Database Setup: Enabling  pgvector 

Connect to your Aurora Serverless v2 PostgreSQL instance and initialize the vector extension:
-- Enable the vector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- Create documents table
CREATE TABLE document_embeddings (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
content TEXT NOT NULL,
metadata JSONB,
embedding vector(1536) -- Matches Titan Text Embeddings V2 dimension
);
-- Build an HNSW index for ultra-fast approximate nearest neighbor lookup
CREATE INDEX ON document_embeddings
USING hnsw (embedding vector_cosine_ops);

3. Query Handler Lambda (Python 3.12)

The following Lambda function generates the query embedding, queries nearest chunks, and synthesizes the final response.
import json
import os
import boto3
import psycopg2
from psycopg2.extras import RealDictCursor
bedrock = boto3.client("bedrock-runtime", region_name=os.environ.get("AWS_REGION", "us-east-1"))
DB_HOST = os.environ["DB_HOST"]
DB_NAME = os.environ["DB_NAME"]
DB_USER = os.environ["DB_USER"]
DB_PASS = os.environ["DB_PASS"]
def get_db_connection():
return psycopg2.connect(
host=DB_HOST,
database=DB_NAME,
user=DB_USER,
password=DB_PASS,
cursor_factory=RealDictCursor
)
def generate_embedding(text: str) -> list:
payload = json.dumps({"inputText": text})
response = bedrock.invoke_model(
modelId="amazon.titan-embed-text-v2:0",
contentType="application/json",
accept="application/json",
body=payload
)
result = json.loads(response["body"].read())
return result["embedding"]
def query_similar_chunks(embedding: list, top_k: int = 3):
conn = get_db_connection()
try:
with conn.cursor() as cur:
cur.execute("""
SELECT content, 1 - (embedding <=> %s::vector) AS similarity
FROM document_embeddings
ORDER BY embedding <=> %s::vector
LIMIT %s;
""", (embedding, embedding, top_k))
return cur.fetchall()
finally:
conn.close()
def invoke_llm(prompt: str, context_chunks: list) -> str:
context_text = "\n\n---\n\n".join([c["content"] for c in context_chunks])
system_prompt = "You are an assistant answering based strictly on the provided context."
user_message = f"Context:\n{context_text}\n\nQuestion: {prompt}"
payload = json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 1000,
"messages": [{"role": "user", "content": user_message}],
"system": system_prompt
})
response = bedrock.invoke_model(
modelId="anthropic.claude-3-5-sonnet-20241022-v2:0",
contentType="application/json",
accept="application/json",
body=payload
)
result = json.loads(response["body"].read())
return result["content"][0]["text"]
def lambda_handler(event, context):
body = json.loads(event.get("body", "{}"))
query = body.get("query")
if not query:
return {"statusCode": 400, "body": json.dumps({"error": "Missing query parameter"})}
# 1. Convert user query to vector
query_vector = generate_embedding(query)
# 2. Vector search in PostgreSQL
relevant_chunks = query_similar_chunks(query_vector, top_k=3)
# 3. Pass context + prompt to Claude
answer = invoke_llm(query, relevant_chunks)
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"answer": answer,
"sources": [r["content"] for r in relevant_chunks]
})
}

4. Key Production Lessons & Cost Optimization

  1. Connection Pooling is Mandatory: Use RDS Proxy between your Lambda and Aurora instance to avoid exhausting database connections during traffic spikes.
  1. Dimension Truncation in Titan V2: Titan Text Embeddings V2 allows reducing output dimensions (e.g., from 1024/1536 down to 512 or 256) with negligible retrieval accuracy degradation, slashing memory and index size by over 50%.
  1. IAM Least Privilege: Restrict Bedrock model invocation permissions solely to the specific ARNs of the models your service consumes:
{
"Effect": "Allow",
"Action": "bedrock:InvokeModel",
"Resource": [
"arn:aws:bedrock:*::foundation-model/amazon.titan-embed-text-v2:0",
"arn:aws:bedrock:*::foundation-model/anthropic.claude-3-5-sonnet*"
]
}
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article