Vector Databases for LLM Long-Term Memory: Architecture, Indexing, and Retrieval Practices

    This article explains how vector databases provide an external memory layer for large language models, covering embedding and similarity concepts, reference architecture, indexing trade-offs, chunking and metadata design, retrieval and write paths, quality evaluation, and production practices. Readers will learn how to build a semantic retrieval system that supplies accurate, fresh, permission-aware context to a model without relying on extremely long prompts.

    1. Why LLMs Need External Memory

    The knowledge of a large language model comes mainly from its training phase. Once the parameters are fixed, the model cannot directly perceive new information created after the training cutoff, nor can it read an organization’s private documents. In addition, the context length available for a single inference is limited. Even as context windows continue to expand, packing all reference material into a prompt remains expensive and slow, and it can easily bury key information.

    The external memory approach stores knowledge in a system outside the model. When needed, it retrieves only the fragments relevant to the current question and places those fragments into the prompt. This allows the model to use the latest and most specific data without paying the cost of an extremely long context. Vector databases are a common infrastructure component for supporting this approach.

    2. Core Concepts

    2.1 Embedding Vectors

    An embedding vector is a fixed-length floating-point array generated by an encoding model. Texts with similar semantics are closer to each other in vector space. For example, “How do I reset my login password?” and “What should I do if I forget my password?” differ greatly in wording, but their vectors are relatively close, so they can be retrieved by the same search.

    2.2 Similarity Metrics

    Three metrics are commonly used:

    • Cosine similarity: measures the difference in direction between two vectors and is independent of vector length. It is the most widely used metric in text retrieval.
    • Inner product: computationally efficient. If vectors are normalized, its result is equivalent to cosine similarity.
    • Euclidean distance: measures straight-line distance in space and is suitable for some image and numerical feature scenarios.

    When choosing a metric, it should match the objective used when the encoding model was trained. Otherwise, the similarity ranking may become distorted.

    2.3 Differences from Traditional Databases

    Traditional relational databases excel at exact matching, range queries, and transaction processing. Vector databases are designed for approximate semantic queries, and their core operation is “given a vector, return the top K most similar records.” The two are not replacements for each other. In practice, a common design keeps structured information in a relational database and stores vectors and metadata in a vector database, linking them through a shared business primary key.

    3. Typical System Architecture

    A complete semantic retrieval pipeline usually includes the following layers:

    1. Source materials (documents, tickets, conversation logs)
    2. │
    3. ▼
    4. Cleaning and chunking ──► Metadata extraction (source, time, permissions, version)
    5. │
    6. ▼
    7. Embedding model generates vectors
    8. │
    9. ▼
    10. Vector storage and indexing (filterable approximate nearest neighbor search)
    11. │
    12. ▼
    13. Query rewriting → vector search → result filtering → reranking
    14. │
    15. ▼
    16. Prompt assembly → LLM generation → answer with citations

    The responsibilities of each layer should be clearly separated. Cleaning and chunking determine the granularity of knowledge, the encoding model determines the quality of semantic representation, the indexing layer determines retrieval speed and recall, and reranking makes a more precise judgment within the candidate set. Most quality issues can be traced to one of these layers.

    4. Indexing Mechanisms and Performance Trade-offs

    Exact search computes the similarity between the query vector and every vector in the database one by one. The results are completely accurate, but the time required grows linearly with data volume. When the data reaches millions or even billions of records, this approach struggles to meet the latency requirements of online services.

    Approximate nearest neighbor search trades a small amount of recall for orders-of-magnitude speed improvements. It is a core capability of vector databases, and common implementation approaches include:

    • Graph-based indexing: organizes vectors into an adjacency graph and gradually approaches the target along the graph during a query. It is suitable for scenarios that require high recall and low latency.
    • Quantization compression: compresses high-dimensional floating-point vectors into low-bit encodings, significantly reducing memory usage. It is suitable for very large-scale data.
    • Partitioned indexing: first divides the space into several clusters and searches only the closest clusters during a query. It is suitable for batch offline retrieval.

    4.2 Trade-offs Among the Three Approaches

    Aspect Exact Search Graph-Based Index Quantization
    Recall 100% Usually high Depends on compression ratio
    Query latency Grows with data volume Low Low
    Memory usage High Medium to high Low
    Build cost None Relatively high Moderate
    Suitable scale Up to ~100K Medium to large scale Large scale

    When selecting an approach, first measure the recall and latency curves with real data, and then decide on parameters. Applying rule-of-thumb values directly often leads to performance or quality problems after launch.

    5. Data Chunking and Metadata Design

    5.1 Chunking Strategies

    Chunking is one of the most critical factors affecting retrieval quality. If chunks are too large, a single fragment may contain multiple topics, the vector becomes averaged, and precise matching becomes difficult. If chunks are too small, the context is incomplete and the model cannot understand the meaning of the fragment.

    Common practices include:

    1. Split by natural structure, such as headings, paragraphs, list items, and code blocks, while preserving semantic completeness as much as possible.
    2. Set a target length and an upper limit, and retain a small overlap between adjacent chunks to prevent key sentences from being cut off.
    3. Attach the section path of each chunk so that retrieval results remain understandable when separated from the original document.

    5.2 Metadata Design

    Metadata upgrades retrieval from “semantically similar” to “semantically similar and satisfying business constraints.” At a minimum, record the following fields:

    • Source identifier: document ID, dataset name, or system source.
    • Time information: creation time and update time, used to prioritize the latest content.
    • Access permissions: department, role, or tenant, used to complete permission filtering during retrieval.
    • Version number: facilitates rollback and incremental updates.

    Permission filtering must be completed during retrieval, not after the answer is generated. Otherwise, sensitive content may still leak through intermediate results.

    5.3 Example Ingestion Flow

    The following pseudocode shows a simplified ingestion flow. Specific interfaces should be adjusted according to the chosen storage and encoding components:

    1. function ingest_document(doc):
    2. chunks = split_by_structure(doc.content, max_tokens=512, overlap=64)
    3. for chunk in chunks:
    4. vector = embedding_model.encode(chunk.text)
    5. metadata = {
    6. "source_id": doc.id,
    7. "section": chunk.section_path,
    8. "updated_at": doc.updated_at,
    9. "tenant": doc.tenant,
    10. "version": doc.version
    11. }
    12. vector_store.upsert(id=chunk.id, vector=vector, metadata=metadata)

    Here, upsert means overwrite by primary key, which prevents redundant fragments when a document is imported repeatedly.

    6. Retrieval and Memory Read/Write

    6.1 Read Path

    A complete retrieval typically goes through the following steps:

    1. Query rewriting: resolve references and complete the context of the user’s question so that the query is more complete.
    2. Vector search: use the same encoding model to generate the query vector and apply tenant and permission filters during retrieval.
    3. Reranking: perform a more precise relevance judgment on the top N candidates and select the final K results.
    4. Context assembly: concatenate fragments in relevance order and attach source information so the model can generate a traceable answer.
    1. function retrieve(question, user):
    2. query = rewrite_with_context(question, session_history)
    3. q_vec = embedding_model.encode(query)
    4. candidates = vector_store.search(
    5. vector=q_vec,
    6. top_k=50,
    7. filter={"tenant": user.tenant, "roles": user.roles}
    8. )
    9. best = rerank(query, candidates)[:5]
    10. return build_prompt(question, best)

    6.2 Write Path

    Long-term memory requires not only reading but also continuous writing. Stable facts from a conversation, such as user preferences, confirmed requirements, or completed tasks, can be extracted into summaries after the session ends and written to the vector store. Three points require attention during writing:

    • Deduplication: when the same fact appears multiple times, merge or update the existing record so that retrieval results are not filled with duplicate content.
    • Conflict updates: after a user changes a preference, the new version should overwrite the old record and retain a timestamp.
    • Expiration cleanup: for time-sensitive information, set a validity period and automatically reduce its weight or delete it after expiration.

    7. Quality Evaluation

    Retrieval quality directly determines generation quality, so it should be evaluated independently of the large language model.

    7.1 Offline Metrics

    • Recall@K: the proportion of relevant fragments in the annotated data that appear in the top K results.
    • Mean reciprocal rank: measures the average quality of the position at which the first relevant result appears.
    • Normalized discounted cumulative gain: when multi-level relevance annotations are available, considers both ranking position and relevance level.

    The evaluation set should cover the question distribution of real users, including short questions, long questions, colloquial expressions, and ambiguous references. Using only manually written ideal questions can easily overestimate system performance.

    7.2 Online Metrics

    After launch, the following signals can be observed: the user’s adoption rate of answers, the number of follow-up questions, the proportion of empty retrieval results, and whether cited fragments are clicked or confirmed. Declines in offline metrics often appear in these online signals in advance, so both should be monitored together.

    8. Engineering Implementation Considerations

    8.1 Versioning and Rebuilding

    After an encoding model is upgraded, historical vectors and new vectors are no longer in the same space, so all data must be re-encoded and a new index must be built. A recommended approach is dual writing and gradual switching: first validate on the new index, then gradually shift traffic, and finally take the old index offline.

    8.2 Security and Isolation

    • Multi-tenant data should be logically isolated, and the tenant identifier must be forcibly injected into retrieval conditions rather than relying on front-end parameters.
    • Original documents, chunk texts, and vectors should all be stored encrypted, and access credentials should be centrally managed by a key management service.
    • Logs should not record complete user questions or sensitive fragments; retain only desensitized query features.

    8.3 Infrastructure Combinations

    Vector databases are usually used together with the following general infrastructure:

    • Object storage: stores original documents and historical versions.
    • Message queue: receives incremental data changes and drives asynchronous encoding and ingestion.
    • Container platform: deploys encoding services and retrieval services and scales elastically according to load.
    • Logging and monitoring/alerting: collects metrics such as retrieval latency, recall hit rate, and error rate, and notifies on-call staff when thresholds are triggered.

    8.4 Monitoring Metrics

    Pay particular attention to P99 retrieval latency, the number of candidates per request, the proportion of empty results, reranking time, and cost per query. Cost metrics cannot be ignored, because embedding computation and high-dimensional storage expenses grow rapidly as data volume increases.

    9. Common Pitfalls

    1. Treating a vector database as a universal store. It is good at approximate semantic queries but is not suitable for replacing a transactional business database.
    2. Ingesting entire documents without chunking. When fragments are too large, retrieval results contain a large amount of irrelevant content.
    3. Ignoring metadata filtering. Without permission and version constraints, retrieval results may be unauthorized or outdated.
    4. Looking at only a single metric. High recall does not mean the answer is correct; reranking effectiveness and end-to-end generation quality must be considered together.
    5. Changing the encoding model without rebuilding the index. Mixing old and new vectors will completely distort similarity ranking.

    10. Summary

    Vector databases provide large language models with an external memory layer that is searchable, updatable, and permission-controlled. In implementation, the key is to chunk knowledge appropriately, design metadata that can constrain retrieval, choose an indexing method based on scale and latency requirements, and continuously calibrate results through offline evaluation and online monitoring. When these elements are connected, a semantic retrieval system can reliably provide the model with accurate, timely, and permission-compliant context.