Sub topic 15
Choosing between libraries, extensions and dedicated databases
This chapter assumes you have read the earlier chapters. You should know how embeddings, distance metrics, HNSW and IVF indexes, metadata filtering and recall measurement work. You should also be comfortable with basic Python and SQL. The goal here is to turn those pieces into a decision. You will compare three kinds of system and learn which workload facts should drive the choice.
The three categories
Every vector search product falls into one of three groups. They differ in how much they do for you beyond the index itself.
- Vector libraries are code you link into your own program. FAISS, hnswlib and ScaNN are examples. They give you fast index structures (HNSW, IVF, product quantization) in memory or on disk. They have no server, no authentication, no replication, and no notion of a record with metadata.
- Vector extensions to existing databases add a vector column type and vector indexes to a system you may already run. pgvector for PostgreSQL is the most common example. Other databases, such as Elasticsearch/OpenSearch and MongoDB, also offer vector search. Your vectors live next to your other data and inherit its transactions, backups and access control.
- Dedicated vector databases are servers built around vector search from the start. Qdrant, Milvus, Weaviate and Pinecone are examples. They provide the full data model (collections, IDs, payloads), filtering, replication, sharding and an API, and they are tuned for large vector workloads.
The categories blur at the edges. Some dedicated databases embed a library such as hnswlib or FAISS internally, and some extensions are very capable. Treat the categories as a way to ask which responsibilities you want to own.
What you take on in each case
The table summarizes who is responsible for each concern.
| Concern | Library | Extension | Dedicated database |
|---|---|---|---|
| Index algorithms | Many, you choose | Usually HNSW and IVF | Usually HNSW, often with quantization |
| Persistence | You write and load files | Handled by the host database | Built in |
| Updates and deletes | Limited, often rebuild | Normal SQL writes | Built in, with background maintenance |
| Metadata filtering | You implement it | SQL `WHERE` clauses | Native, with filter-aware search |
| Transactions with other data | None | Yes, same database | Usually none across systems |
| Horizontal scaling | You build it | Depends on the host | Built in sharding and replication |
| Extra system to operate | None | None if you already run the host | Yes |
The most important row for many teams is the last one. A new database is a new thing to deploy, monitor, secure, back up and upgrade. That cost is worth paying only when the workload needs what the system provides.
Libraries: maximum control, minimum infrastructure
A library fits when the data is static or changes in batches, the index fits on one machine, and you want full control over parameters. Typical cases are offline analysis, research experiments, a read-only search feature built from a nightly job, and a component embedded inside a larger service.
The library makes you build everything around the index. The following example shows the ID mapping you would otherwise get for free from a database. FAISS returns row positions, so you must keep your own mapping to real identifiers and metadata.
import numpy as np
import faiss
d = 64
rng = np.random.default_rng(0)
vectors = rng.normal(size=(5000, d)).astype("float32")
doc_ids = [f"doc-{i}" for i in range(len(vectors))]
categories = ["a" if i % 2 == 0 else "b" for i in range(len(vectors))]
index = faiss.IndexHNSWFlat(d, 32)
index.hnsw.efConstruction = 200
index.add(vectors)
index.hnsw.efSearch = 64
query = vectors[:1]
_, ids = index.search(query, 50)
# Post-filtering: fetch extra candidates, then filter by category in Python.
wanted = "a"
results = [doc_ids[i] for i in ids[0] if i != -1 and categories[i] == wanted][:5]
print(results)This works, but notice the cost. The filter runs after the search, so a selective filter can leave you with fewer than five results. Persistence, concurrent writes and deletes are also yours to build. A library gives you the index and little else.
Extensions: one system for everything
An extension fits best when your application already depends on a relational database, and vector search is one feature among many. The main advantage is that the vector sits in the same row as the rest of the record. You can filter, join and update it in one transaction.
The SQL below shows a typical query. It joins the vector table to another table and filters on a column, which is awkward to do across two separate systems.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE tenants (
id int PRIMARY KEY,
name text
);
CREATE TABLE documents (
id bigserial PRIMARY KEY,
tenant_id int REFERENCES tenants (id),
body text,
embedding vector(3)
);
INSERT INTO tenants VALUES (1, 'acme'), (2, 'globex');
INSERT INTO documents (tenant_id, body, embedding) VALUES
(1, 'refund policy', '[1, 0, 0]'),
(1, 'shipping times', '[0.9, 0.1, 0]'),
(2, 'refund policy', '[0.95, 0.05, 0]');
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops);
SELECT d.id, d.body, d.embedding <=> '[1, 0, 0]' AS cosine_distance
FROM documents d
JOIN tenants t ON t.id = d.tenant_id
WHERE t.name = 'acme'
ORDER BY d.embedding <=> '[1, 0, 0]'
LIMIT 2;If a document is deleted or its text changes, the row and its vector change together, and a backup covers both. You also reuse your existing tooling, such as connection pooling, role-based access and monitoring.
The limits come from the host database. Vector indexes compete for memory and CPU with your other queries. An HNSW index that does not fit in memory degrades sharply. Index builds on large tables can be slow and resource-heavy. Scaling out depends on how the host database shards, which is often harder than in a system designed for it. Filtered search also needs care. In pgvector, an approximate index scan may return fewer rows than requested when a restrictive WHERE clause applies after the index scan, so check how your version handles filters and test with your real filter selectivity.
Dedicated databases: built for scale and vector features
A dedicated vector database fits when vector search is the core of the product, or when the scale or feature needs exceed what a general database handles comfortably. Typical signs are:
- Hundreds of millions or billions of vectors, which need sharding and often quantization to control memory.
- Frequent updates to a large index while serving queries.
- Heavy filtering, where filter-aware graph traversal matters for both recall and latency.
- Multiple vectors per record, sparse and dense vectors together, or built-in hybrid search.
- A need to scale vector search separately from the rest of your data.
The price is a second source of truth. Your primary data stays in your main database, and the vector database holds a copy of the embeddings plus the metadata you need for filtering. You must keep the two in sync. A document that is deleted in the main database but not in the vector database can appear in search results, which is a correctness and sometimes a privacy bug. Plan a synchronization path, such as writing both in one service or consuming a change stream, and plan how to detect drift.
Managed offerings reduce operational work but add cost, a network hop, and a dependency on a vendor. Self-hosted options give control and need people who can run them.
A decision process
Work through these questions in order. Stop at the first one that gives a clear answer.
- How many vectors will you have in a year, and what dimension? Multiply count by dimension by 4 bytes for float32 to get raw size, then add index overhead. HNSW graphs typically add tens of percent or more. If the total fits comfortably in the memory of one machine you already run, a library or extension is realistic.
- Do you already run a relational database that holds the source data? If yes and the scale is modest, start with the extension. It removes the synchronization problem.
- How often does the data change? Batch updates suit a library. Continuous updates and deletes suit an extension or a dedicated database.
- How selective are your filters? Test them. If filters often match under about one percent of records, verify recall on filtered queries in each candidate before committing.
- What are your latency and throughput targets? Measure them against your own data. Published benchmarks use specific datasets and hardware.
- Who will operate it? A small team with no spare capacity may do better with an extension or a managed service than with a self-hosted cluster.
The same logic can be written as a small function. It is a starting heuristic, not a rule, and the thresholds are placeholders you should replace after your own testing.
def suggest_system(n_vectors, dim, has_relational_db, updates_are_batch, needs_sharding):
raw_gb = n_vectors * dim * 4 / 1e9
if needs_sharding or raw_gb > 100:
return "dedicated database"
if has_relational_db:
return "extension"
if updates_are_batch:
return "library"
return "dedicated database"
print(suggest_system(2_000_000, 768, True, False, False))
print(suggest_system(500_000_000, 768, False, False, True))Common mistakes
- Choosing on a benchmark chart alone. Vendor benchmarks vary the dataset, recall target and hardware. Always compare at the same recall, using your own vectors and your own filters.
- Adopting a dedicated database too early. A million vectors in a table with an HNSW index is often fine. The extra system may cost more than it saves.
- Staying with an extension too long. If index builds block releases, or vector queries slow down your transactional workload, it is time to separate them.
- Ignoring migration cost. Embeddings are tied to a model. Changing the model means re-embedding everything, whichever system you use. Keep the original text so you can rebuild.
- Forgetting that the choice is reversible. Keep your data access behind a small interface, so that moving from an extension to a dedicated database later is a contained change.
Exercise
A team has 3 million 768-dimension float32 embeddings of support articles. The articles live in PostgreSQL, editors update and delete articles all day, and every query filters by customer account. The team has two engineers and no spare capacity to run new infrastructure. Which category would you start with, and what two things would you test before committing?
Show answer
Start with the extension (pgvector). The raw size is 3,000,000 x 768 x 4 bytes, about 9.2 GB, which fits in memory on a normal server. The data already lives in PostgreSQL, so updates and deletes stay consistent, and no new system needs to be operated. Test first that recall and latency stay acceptable for filtered queries, using realistic account filters including the most restrictive ones, and that the HNSW index plus the existing workload fits in memory without slowing transactional queries. If either fails, move to a dedicated database.
Exercise
Why does a dedicated vector database create a synchronization problem that an extension does not, and how can it show up as a user-visible bug?
Show answer
A dedicated database keeps its own copy of the embeddings and metadata, separate from the primary database, so the two can diverge. If an article is deleted or a permission changes in the primary database and the change does not reach the vector database, the old record can still be returned by search. Users may see removed or restricted content. An extension stores the vector in the same row and transaction as the record, so a delete or update applies to both at once.