Skip to main content
Servers Are Up
Virtual Datacenter
PricingFree Tools
Sign inBrowse catalog
Servers Are Up
Virtual Datacenter
PricingFree Tools
Sign inBrowse catalog

Loading…

Servers Are Up

Your apps, automation and data on hardware we own. Build a private stack with predictable capacity and access through your dashboard, API or SSH.

SLA with service creditsOwned hardwareUS-based

Make room for your next idea

Explore the capacity, apps and access options that fit your workload. Check current availability and your total before you buy.

Sign up freeView Pricing

Products

  • Linux VPS
  • Windows VPS
  • Cloud & SaaS Services
  • Cloud Storage (Azure)
  • Virtual Datacenter
  • AI & Agent Hosting
  • Containers
  • Instant Apps
  • Software Platforms
  • Network builder
  • Game Servers
  • Free Game Servers
  • Pricing

Resources

  • Free Network Tools
  • 2026 Pricing Benchmark
  • Live SVG Badges
  • Latency & Speed Test
  • Guides & Tutorials
  • Documentation
  • API Reference
  • MCP Server
  • CLI & SDKs
  • OpenAPI & llms.txt
  • Use Cases
  • Free Migration
  • Uptime & Reliability
  • Datacenter
  • System Status
  • Network
  • Provider Comparisons Hub
  • Compare Providers

Company

  • About Us
  • Enterprise
  • Security Architecture
  • Trust Center
  • Blog
  • FAQ
  • Compliance
  • Startup Program
  • Open-Source Sponsorship
  • Press & Media Kit
  • Referral Program
  • Help Center
  • Contact Us
© Servers Are Up
TermsPrivacySLARefund PolicyDPAAcceptable Use
Service information
Docs
  • Documentation Hub
  • Technical Knowledge Library
    Runbooks & 187 Blueprints
  • Choose a Product
    VMs, Containers & Cloud
  • First Linux Server
    SSH, Firewall & Apps
  • Windows Server 2025
    BYOL & Remote Desktop
  • Remote Access
  • Troubleshooting
  • FAQ
  • All Product Guides
    29 Step-by-Step Guides
  • Cloud & SaaS Catalog
    112 Cloud & SaaS Offerings
  • Azure Cloud Storage
    Hot/Cool/Archive & WORM
  • Resource Manager & RBAC
    Groups, Tags & Locks
  • Multi-Model Cloud DB
    JSONB, SQL & pgvector
  • Cloud Identity & ZTNA
    OIDC, SCIM & PIM
  • Key Vault & KMS
    Secrets & Envelope Keys
  • Cloud SIEM, SOAR & DLP
    Posture & Threat Response
  • API Gateway & Cloud DNS
    Edge WAF & DNS Zones
  • Serverless, Workflows & IoT
    Functions, Queues & DAGs
  • SaaS, Governance & Vault
    Budgets & Off-Host GRS
  • Linux Systems & Kernel
    SSH, UFW, sysctl & OOM
  • Self-Hosted Apps & Stacks
    Caddy, Nextcloud & Auth
  • Build Web Apps with AI
  • Next.js and React
  • TypeScript and Node.js
  • npm and Tooling
  • Data and APIs
  • Deploy and Operate
  • Tutorials
  • Infrastructure
  • Automation & Regions
  • API Overview
  • API v1 Reference
    Endpoints & 23 Scopes
  • MCP Server
    129 AI Agent Tools
  • Swagger / OpenAPI 3.1
  • API Playground
  • Versioning & Sunset
  • API Token Security
    Authentication & Tokens
  • Instances API
    Compute Resources
  • Networking API
    Networks & Ports
  • Storage API Availability
    Volumes & Backups
  • Webhooks & Events
    Event Notifications
  • Rate Limits & Best Practices
    Throttling & Retries
  • sau CLI Reference
    34 Commands (v0.2)
  • Browser Web CLI
  • SDKs
  • Infrastructure as Code
    Terraform & Ansible
  • Code Examples
  • CLI & SDK Guides
  • Security Guides
  • Security at a Glance
  • Zero Trust Architecture
  • Live Trust Center
  • Compliance
Need help?

Loading documentation...

Documentation/ai web apps

Build RAG with PostgreSQL 17 and pgvector HNSW safely

Implement hybrid full-text and pgvector HNSW retrieval in PostgreSQL 17 with tenant isolation, halfvec memory savings, ef_search tuning, and citations.

Intermediate
35 min
Updated 2026-11-23

Deploy Ready-to-Run Infrastructure in Seconds

Linux VMs from $6/mo · Pooled Virtual Datacenters from $12/mo · Use code WELCOME20 for 20% off your first order.

Browse ServersView Pricing

Commands checked on 2026-11-23 with PostgreSQL 17, pgvector 0.8+, Node.js 24, pg 8.13+.

What you will have at the end

A multi-tenant Retrieval-Augmented Generation (RAG) knowledge database inside PostgreSQL 17 combining pgvector HNSW cosine similarity and PostgreSQL tsvector keyword ranking—strictly partitioned by tenant ID (environmentId) so customers can never retrieve another tenant's documents or research notes.

Before you start

  • A running PostgreSQL 17 instance with the vector extension; see PostgreSQL for a web app or Cloud databases with vector and SQL.
  • An OpenAI-compatible embeddings endpoint such as local nomic-embed-text / bge-large or Ollama.

Steps

1. Create the hybrid document and chunk schema with tenant boundaries

Enable vector, store document metadata separately from chunks, index both semantic vectors (hnsw) and lexical search (GIN tsvector), and partition every customer memory row by environmentId:

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE kb_documents (
  id TEXT PRIMARY KEY,
  scope TEXT NOT NULL,            -- 'public_docs' | 'tenant_memory'
  environment_id TEXT,            -- NULL only for public_docs
  title TEXT NOT NULL,
  source_url TEXT NOT NULL,
  checksum TEXT NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE kb_chunks (
  id TEXT PRIMARY KEY,
  document_id TEXT NOT NULL REFERENCES kb_documents(id) ON DELETE CASCADE,
  environment_id TEXT,
  chunk_index INTEGER NOT NULL,
  content TEXT NOT NULL,
  tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED,
  embedding halfvec(1024),
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX kb_chunks_tsv_idx ON kb_chunks USING GIN (tsv);
CREATE INDEX kb_chunks_env_idx ON kb_chunks (environment_id);

Notice halfvec(1024) halves RAM requirements compared to 32-bit vector(1024) while preserving nearly identical recall.

2. Build the HNSW index with tuned memory allocation

Temporarily raise maintenance_work_mem during index creation so Postgres builds the HNSW graph in RAM instead of spilling to disk:

SET maintenance_work_mem = '1GB';
SET max_parallel_maintenance_workers = 4;

CREATE INDEX kb_chunks_hnsw_idx
  ON kb_chunks USING hnsw (embedding halfvec_cosine_ops)
  WITH (m = 16, ef_construction = 64);

3. Execute Zero-Trust hybrid RRF queries scoped to a single tenant

Always inject the server-verified environment_id inside the WHERE predicate before taking top-K neighbors—never filter tenant ownership in application memory after fetching global top-K vectors, or rare/filtered queries will silently return zero tenant matches or leak neighboring tenants:

BEGIN;
SET LOCAL hnsw.ef_search = 100;

WITH semantic AS (
  SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> $1::halfvec) AS r
  FROM kb_chunks
  WHERE environment_id IS NULL OR environment_id = $2
  LIMIT 30
),
lexical AS (
  SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv, plainto_tsquery('english', $3)) DESC) AS r
  FROM kb_chunks
  WHERE (environment_id IS NULL OR environment_id = $2)
    AND tsv @@ plainto_tsquery('english', $3)
  LIMIT 30
)
SELECT c.id, c.content, d.title, d.source_url,
  COALESCE(1.0 / (60 + s.r), 0.0) + COALESCE(1.0 / (60 + l.r), 0.0) AS rrf_score
FROM kb_chunks c
JOIN kb_documents d ON d.id = c.document_id
LEFT JOIN semantic s ON s.id = c.id
LEFT JOIN lexical l ON l.id = c.id
WHERE s.id IS NOT NULL OR l.id IS NOT NULL
ORDER BY rrf_score DESC
LIMIT 8;
COMMIT;

Check that it works

Verify index usage with EXPLAIN (ANALYZE, BUFFERS) inside psql:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM kb_chunks
WHERE environment_id = 'ENV-DEMO'
ORDER BY embedding <=> array_fill(0.01::real, ARRAY[1024])::halfvec
LIMIT 5;

Confirm Postgres selects an Index Scan using kb_chunks_hnsw_idx (once rows accumulate) and sub-10ms lookup latency with clean tenant scoping.

What can go wrong

  • Hybrid query returns fewer than K results when filtering by environment_id. Default pgvector HNSW iteratively visits candidates, and very small tenants can exhaust hnsw.ef_search = 40 scanning other tenants' nodes first. Upgrade to pgvector 0.8+ (SET hnsw.iterative_scan = relaxed_order;), raise ef_search = 120, or pair vector search with GIN full-text fallback.
  • Query crashes with different vector dimensions. Every chunk inserted must share the exact embedding model dimension; store the model ID + dimension alongside kb_documents so re-embedding upgrades never mix dimensions.
  • Prompt injection smuggled inside retrieved RAG chunks. Wrap retrieved chunks inside untrusted XML data delimiters and strip control tokens before inserting into system prompts.

Good practice

  • Combine lexical (tsvector) search with dense vector search via Reciprocal Rank Fusion (RRF) because exact CLI flags, systemd directives (ProtectSystem=strict), and error codes (ECONNREFUSED) match poorly on embeddings alone.
  • Wrap every retrieved document snippet as inert reference data (<untrusted_external_data>) before feeding it to an LLM.
  • Enforce hnsw.iterative_scan on multi-tenant pgvector 0.8+ databases so selective tenant filters stay accurate.

Where to go next

  • Input and output guardrails for AI applications
  • Tune Valkey, Qdrant, Meilisearch, and MinIO in Docker
  • Add a first AI feature to a Next.js app

Related Articles

Choose a model for your app by measuring it

Read more

Run Dify, Flowise, and Langflow workflows cleanly in Docker

Read more

Add a first AI feature to a Next.js app

Read more

Frequently Asked Questions

What does the Build RAG with PostgreSQL 17 and pgvector HNSW safely documentation guide cover?
Implement hybrid full-text and pgvector HNSW retrieval in PostgreSQL 17 with tenant isolation, halfvec memory savings, ef_search tuning, and citations. It is rated intermediate difficulty (35 min) and applies to Servers Are Up infrastructure and workflows.
Can I manage or automate these steps through the Servers Are Up dashboard, REST API v1, or MCP server?
Yes. Every Servers Are Up server includes browser-based SSH, WebRDP, and VNC console access in the dashboard, plus programmatic control via the REST API v1 (/api/v1) and hosted Model Context Protocol server (/api/mcp/v1) using a scoped Personal Access Token.

Need hands-on help with Build RAG with PostgreSQL 17 and pgvector HNSW safely?

Every Servers Are Up virtual machine and container includes an integrated HTML5 browser-based SSH, RDP, and VNC console in your dashboard, default-off inbound firewall rules with per-IP allow-lists, and full programmatic control via REST API v1 and Model Context Protocol (MCP). Explore our Virtual Datacenter Plans or reach out to Servers Are Up Support.

Was this article helpful?

On this page

What you will have at the endBefore you startSteps1. Create the hybrid document and chunk schema with tenant boundaries2. Build the HNSW index with tuned memory allocation3. Execute Zero-Trust hybrid RRF queries scoped to a single tenantCheck that it worksWhat can go wrongGood practiceWhere to go next
Need Live Commands?

Open Aria in Wide Engineering Mode for distro-specific commands, compose tweaks, and isolated environment troubleshooting.

Knowledge Library