SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Relational Databases
  • Document Databases
  • Key-Value Databases
  • Full-Text Search Engines
  • Wide Column Databases
  • Time Series Databases
  • Graph Databases
  • Vector Databases
  • NewSQL Databases
  • Columnar Databases
  • In-Memory Databases
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Types (Deep Dive)

Vector Databases

Find items that are similar in meaning, using numbers called embeddings.

⏱ 13 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A vector database stores embeddings: lists of numbers that capture the meaning of text, images or audio. It finds the items whose numbers are closest to your query, so it finds things that are similar, not just equal.

  • A model turns "cheap flights to Goa" into, say, 768 numbers. A similar sentence gets similar numbers.
  • The database answers nearest neighbour questions: "give me the 10 closest vectors to this one".
  • To stay fast on millions of vectors it uses approximate search (ANN) indexes such as HNSW and IVF.
  • Used for semantic search, recommendations, and RAG (giving an AI assistant the right documents).

02Concept: What is it?

Normal databases match exact values: id = 5, name = "Asha". Search by meaning is different. "car" and "automobile" share no letters, yet mean the same. An embedding model (a neural network) reads the text and outputs a vector, a list of numbers. Things with similar meaning end up at nearby points in this number space.

To search, you embed the query with the same model, then ask for the stored vectors nearest to it. "Nearest" is measured with a similarity metric: cosine similarity (the angle between vectors), Euclidean distance (straight line), or dot product.

From meaning to numbers to neighbours
📄Text / imageyour data
→↓embed
🔢Vector[0.12, -0.4, 0.88, ...]
→↓store + index
🗄️Vector DB
←k nearest
❓Query vectorsame model
Index time and query time must use the same embedding model.
🧠Similar meaning = nearby numbers
The database does not understand meaning. The model does. The database only stores vectors and finds the close ones fast.

03Real-Life Example

🍵The Music Shop With a Mood Map
A music shop puts every song on a big floor map. Calm piano songs sit in one corner, loud rock in another, and jazz in between. You say "I like this song", the clerk puts a finger on its spot and hands you the 5 songs nearest to it. No one searched for a title or a genre word. Distance on the map is the match.
Mood map in the shop
Vector database
Each song has a spot on the map
Each item has an embedding (a point)
The map has many directions, not just two
Hundreds or thousands of dimensions
Similar songs sit close together
Similar meaning gives close vectors
Clerk finds the 5 closest songs
k-nearest-neighbour (kNN) query
Checking every song on the floor
Exact (brute force) search
Looking only in the nearby corners
Approximate search (ANN) with an index
Sometimes the best song was in a corner skipped
Recall below 100%
Exact vs approximate, in the shop
🚶Exactwalk the whole shop
↔
🧭Approximatecheck the nearest corners

04Why Do We Need It?

🧠Search by meaning
Find results that match the idea, even with different words.
🖼️Any kind of data
Text, images, audio and code can all become vectors, so one method fits all.
🤖Feed AI assistants
RAG finds the most relevant documents and hands them to a language model.
🎯Recommendations
Show items near the ones a user liked.
⚡Fast at scale
ANN indexes search millions of vectors in milliseconds.
🌍Language-friendly
A good multilingual model places the same idea close together in any language.
When "similar" matters more than "equal", turn things into vectors and search by closeness.

05Where Do We Use It?

🔎Semantic search
Search a help centre by question, not by keywords.
💬RAG chatbots
Retrieve the right paragraphs before the model writes an answer.
🛍️Recommendations
Similar products, songs and videos.
📸Image and audio search
Find visually similar photos or matching sound clips.
👯Duplicate detection
Spot near-copies of text or images.
🛡️Anomaly and fraud checks
Flag items that are far from every normal group.

06Types / Parts / How It Works

Similarity measures

MeasureWhat it checksUse when
Cosine similarityThe angle between two vectors. Length does not matter.Text embeddings, where direction carries the meaning
Euclidean (L2) distanceStraight-line distance between two points.When length also matters, such as some image features
Dot productAngle and length together. Larger is more similar.Recommenders. Same as cosine if vectors are normalised to length 1

Exact and approximate search

Exact (brute force / flat)
Compare with every vector
  • Always the true nearest
  • Cost grows with the number of vectors
  • Fine for under about 100,000 vectors
  • No index to build
Approximate (ANN)
Search part of the space
  • Much faster on millions of vectors
  • May miss a true neighbour (recall under 100%)
  • Needs an index build and tuning
  • Memory-hungry for graph indexes
IndexIdeaGood and bad
IVF (inverted file)Cluster vectors into cells. Search only the few cells nearest the query.Small and simple. Recall depends on how many cells you probe.
HNSWA layered graph of links between close vectors. Walk it from coarse to fine.Fast and high recall. Uses lots of memory and is slower to build.
PQ (product quantisation)Compress each vector into short codes.Saves memory a lot. Loses a bit of accuracy.
LSH (hashing)Hash so that similar vectors land in the same bucket.Simple idea. Often beaten by HNSW in practice.
Disk-based graphs (for example DiskANN)Keep most of the index on SSD.Handles huge sets cheaply. More complex.
IVF in one picture
📍Query
→↓pick nearest cells
Searched
Cell 212 vectors
Cell 512 vectors
Skipped
Cell 1, 3, 4not read
Compared Skipped
Only the cells near the query are searched. The skipped cells are where recall is lost.
A similarity query (pgvector style, general idea)
-- <=> is cosine distance in pgvector
SELECT id, title
FROM documents
ORDER BY embedding <=> '[0.12, -0.40, 0.88, ...]'
LIMIT 5;
VisualizerNearest neighbours: distance vs cosine, exact vs approximateClick near the middle, then far out, and switch Straight distance to Cosine. Then choose Approximate and probe only 1 cell near a topic border.
Similarity rule
Search
Click anywhere on the plane to move the query (white diamond). Each dot is an item. Colour = topic. Ringed dots are your top 5.
CookingSportsMusicTravelNews
Compared
60/60
distance calculations
Recall@k
100%
true neighbours found
Work saved
0%
k-th distance
15.2
smaller is more similar
Exact search compared the query with all 60 points. It is always right, but the work grows with the number of vectors.

A toy with 60 items in 2 dimensions and fixed positions (no random numbers). Real embeddings have hundreds or thousands of dimensions and millions of vectors, and real indexes (IVF, HNSW) are more refined. The ideas carry over: similarity is a number, exact search is a full scan, and approximate search trades a little recall for a lot of speed.

07How to Use It / Steps / Implementation

Building semantic search

  1. 1
    Pick an embedding model
    Choose one that fits your language and data type. You must use the same model for documents and queries.
  2. 2
    Split the data into chunks
    Long documents are cut into passages (for example a few hundred words). Each chunk gets a vector.
  3. 3
    Store vector, id and metadata
    Keep the original text or a pointer, plus fields such as tenant, date and language for filtering.
  4. 4
    Choose a metric and an index
    Cosine for most text. Use flat for small data, HNSW or IVF for large data.
  5. 5
    Query: embed, search, filter
    Embed the question, ask for the top k, and apply metadata filters.
  6. 6
    Re-rank (optional)
    A slower, smarter model can re-order the top 50 into a better top 5.
  7. 7
    Measure recall and quality
    Compare ANN results with exact results on a sample. Also test with real user questions.
⚠️Changing the model means rebuilding
Vectors from different models are not comparable. If you switch the embedding model, you must re-embed all your data and rebuild the index.
Speed vs recall dialmore probes or a larger search width means better recall and slower queries

08Key Terms to Know

TermMeaning in easy words
EmbeddingA list of numbers that represents the meaning of an item
VectorAn ordered list of numbers
DimensionHow many numbers are in each vector, such as 384 or 1536
Cosine similarityHow close the directions of two vectors are
kNNFind the k nearest vectors
ANNApproximate nearest neighbour search: fast, may miss some results
RecallThe share of true nearest neighbours that the search returned
HNSWA graph index with several layers for fast approximate search
IVFAn index that clusters vectors and searches only some clusters
RAGRetrieval-augmented generation: look up documents, then let a model answer using them

09Pros, Cons and Trade-offs

✅ Pros
  • Finds meaning, not only exact words
  • Works on text, images and audio
  • Fast on huge sets with ANN
  • Key part of AI search and RAG
  • Scores let you rank results
⚠️ Cons
  • Approximate results can miss the best match
  • Depends fully on the embedding model quality
  • Indexes are memory-heavy and costly to rebuild
  • Hard to explain why a result matched
  • Filters combined with ANN need care

Trade-offs

ChoiceWe gainWe lose
Exact searchPerfect recallSlow on large data
Approximate searchSpeed and scaleSome recall, extra tuning
More dimensionsRicher meaningMore memory and slower search
Quantisation (compression)Much less memoryA little accuracy
Vector DB vs vector column in PostgresSpecialised features and scaleAnother system to run (the extension is simpler for small data)
Hybrid (keyword + vector)Catches exact terms and meaningMore moving parts

10Common Problems and Mistakes

Common mistakes

  1. Mixing models. Documents embedded with one model and queries with another give nonsense.
  2. Embedding whole big documents. One vector for a book blurs everything. Chunk it.
  3. Ignoring keywords. Part numbers and names need exact matching. Use hybrid search.
  4. No metadata filter. Users may see other tenants' or outdated documents.
  5. Never measuring recall. You do not know how much the index misses.
  6. Choosing a metric the model was not trained for. Use the metric the model's guide recommends.

Things to watch

📏Curse of dimensions
In very high dimensions, distances look more alike, so ranking gets harder.
🔧Filtered search
Filtering before or after ANN can hurt recall or speed.
♻️Updates and deletes
Some indexes need rebuilding or compaction after many changes.
💰Memory cost
1 million vectors of 1536 floats is roughly 6 GB before the index.

11Real-World Examples

🌲Pinecone, Weaviate, Milvus, Qdrant
Purpose-built vector databases with ANN indexes and metadata filtering.
🐘pgvector
A PostgreSQL extension that adds a vector column type and HNSW and IVF indexes.
🔍Elasticsearch / OpenSearch
Search engines that added vector fields and kNN search next to keyword search.
📚FAISS and ScaNN
Libraries for vector search that many systems build on.
🤖RAG assistants
Support bots and coding assistants fetch relevant chunks by similarity before answering.
🎵Recommendations
Streaming and shopping apps use embeddings of items and users to find matches.
📝Note
These are general ideas. Names, features and limits change quickly between versions.
Mini case: a RAG assistant for company docs
👤Question
→↓embed
🗄️Vector DBtop 5 chunks
→↓chunks + question
🤖Language model
→↓answer
✅Grounded answer
The vector database finds the right passages. The model writes the answer from them.

12Related Topics to Read Next

Common Database Types→

Where vector databases sit among database families.

Full-Text Search Engines→

Keyword search, often combined with vectors as hybrid search.

Indexing→

Vector indexes are a different kind of index for a different question.

Graph Databases→

HNSW is itself a graph of close vectors.

Partitioning→

IVF splits vectors into cells, an idea close to partitioning.

Sharding→

How very large vector collections are spread over machines.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: stores embeddings and finds the nearest ones.
  • ✔Embedding: numbers from a model; similar meaning means close vectors.
  • ✔Metrics: cosine (angle), Euclidean (distance), dot product.
  • ✔Exact: compare all, perfect but slow. ANN: HNSW, IVF, PQ, fast but approximate.
  • ✔Tune: recall vs latency vs memory.
  • ✔Use for: semantic search, RAG, recommendations, duplicates.
  • ✔Remember: same model for data and queries; chunk long text; add keyword and metadata filters.
  • ✔One line: “Turn meaning into numbers, then find the closest numbers fast.”
← Previous
Graph Databases
Next →
NewSQL Databases