Feature Stores, Embeddings, and Retrieval: A Practical Guide
The term "feature store" predates the LLM era by nearly a decade—Uber's Michelangelo platform introduced the concept around 2017. But as retrieval-augmented generation has become a dominant AI pattern, the responsibilities of feature stores have expanded significantly.
Today's AI engineers must navigate two parallel infrastructure tracks: traditional ML feature stores that serve numerical and categorical features, and embedding-based retrieval systems that serve semantic search. Understanding how these systems interact—and when to unify versus separate them—is essential for building maintainable AI infrastructure.
What Feature Stores Were Built For
Traditional feature stores solved a specific problem: the impossibility of re-creating exact feature values at the time of an inference request. If you trained a model using "purchases_last_30_days" computed on January 1st, how do you ensure that the same "purchases_last_30_days" feature is computed identically when serving inference requests on January 15th?
Feature stores solve this through:
- Offline stores: Historical feature snapshots used for training
- Online stores: Current feature values served at low latency
- Point-in-time correct joins: Training data that only uses features that existed at each historical timestamp
# Feast: Classic feature store usage
from feast import FeatureStore
import pandas as pd
store = FeatureStore(repo_path=".")
# Training: historical features with time-travel
entity_df = pd.DataFrame({
"user_id": ["user_1", "user_2", "user_3"],
"event_timestamp": ["2024-01-15", "2024-01-16", "2024-01-17"]
})
training_df = store.get_historical_features(
entity_df=entity_df,
features=[
"user_stats:purchases_30d",
"user_stats:avg_order_value",
"user_stats:days_since_last_purchase"
]
).to_df()
# Serving: online features at inference time
online_features = store.get_online_features(
features=["user_stats:purchases_30d", "user_stats:avg_order_value"],
entity_rows=[{"user_id": "user_1"}]
).to_dict()
Where Embeddings Fit In
Embeddings present a fundamentally different challenge. Unlike numerical features (a count, a ratio, a duration), embeddings are dense vectors representing semantic content—a user's recent product interactions encoded as a 768-dimensional vector, or a document chunk encoded for semantic search.
Embedding Features vs. Retrieval Indexes
It's important to distinguish two different uses of embeddings:
1. Embedding features for ML models: User/item embeddings used as input features to downstream models. These belong naturally in a feature store.
2. Retrieval indexes: Embeddings indexed for similarity search (HNSW, IVF). These are better served by a dedicated vector store.
# Embedding as a feature store value
@feature_view(
entities=[Entity(name="user_id")],
ttl=timedelta(hours=24),
)
def user_preference_embeddings(inputs: RequestSource) -> pd.DataFrame:
"""
Pre-computed user preference embedding for recommendation models.
Stored as a 256-dim float array in the feature store.
"""
return compute_user_preference_embedding(inputs)
# vs. Retrieval index (vector DB)
# Documents are chunked, embedded, and indexed for semantic search
# This is NOT a feature store concern
def index_documents_for_rag(documents: List[Document]):
for doc in documents:
chunks = chunk_document(doc)
embeddings = embed_chunks(chunks)
vector_store.upsert(
ids=[c.id for c in chunks],
embeddings=embeddings.tolist(),
metadata=[c.metadata for c in chunks]
)
The Embedding Consistency Problem
The most critical challenge at the intersection of feature stores and embeddings is embedding consistency: ensuring that the same content produces the same embedding across training, serving, and retrieval.
This sounds obvious, but it's routinely violated through:
- Model version drift: The embedding model is updated, but only some stores are re-indexed
- Preprocessing drift: Text cleaning applied at indexing time differs from cleanup at query time
- Batch vs. online discrepancy: Batch embedding jobs use different code paths than online embedding requests
# Anti-pattern: Different preprocessing for indexing vs. querying
def preprocess_for_indexing(text: str) -> str:
return text.strip().lower() # lowercase for indexing
def embed_query(text: str) -> np.ndarray:
# Missing the lowercase! Training-serving skew.
return embedding_model.encode(text.strip())
# Correct pattern: Single preprocessing function everywhere
def preprocess_text(text: str) -> str:
text = text.strip()
text = re.sub(r'\s+', ' ', text) # normalize whitespace
return text
def embed_any(text: str) -> np.ndarray:
return embedding_model.encode(preprocess_text(text))
# Use embed_any() everywhere: indexing, query, training
Versioning Your Embedding Model
When you change your embedding model, you must:
- Re-embed all documents in your retrieval index
- Re-embed all stored embedding features
- Potentially retrain downstream models that used the old embeddings as features
This makes embedding model selection a high-stakes decision. Consider:
- Stability over state-of-the-art: A slightly older, stable embedding model beats a cutting-edge one that changes frequently
- Model registry integration: Track which embedding model version was used for every indexed document
- Rollback capability: Maintain the previous embedding model and index for at least 30 days post-migration
@dataclass
class IndexedDocument:
doc_id: str
content: str
embedding: np.ndarray
embedding_model_version: str # e.g. "text-embedding-3-small-v1"
indexed_at: datetime
content_hash: str # to detect when content changes
Building a Unified Retrieval Architecture
For AI systems that use both traditional ML models and LLM-based retrieval, consider a unified retrieval service that abstracts over both patterns:
from abc import ABC, abstractmethod
from typing import List, Dict, Any
class Retriever(ABC):
@abstractmethod
def retrieve(
self,
query: str,
entity_context: Dict[str, Any],
top_k: int = 5
) -> List[dict]:
pass
class VectorRetriever(Retriever):
"""Retrieves documents by semantic similarity."""
def __init__(self, vector_store, embedding_model):
self.vector_store = vector_store
self.embedding_model = embedding_model
def retrieve(self, query, entity_context, top_k=5):
embedding = self.embedding_model.encode(query)
return self.vector_store.search(embedding, top_k=top_k)
class FeatureRetriever(Retriever):
"""Retrieves ML features for entity context."""
def __init__(self, feature_store):
self.feature_store = feature_store
def retrieve(self, query, entity_context, top_k=5):
return self.feature_store.get_online_features(
features=["user_stats:*"],
entity_rows=[entity_context]
).to_dict()
class HybridRetriever(Retriever):
"""Combines vector search with feature store context."""
def __init__(self, vector_retriever, feature_retriever):
self.vector_retriever = vector_retriever
self.feature_retriever = feature_retriever
def retrieve(self, query, entity_context, top_k=5):
# Parallel retrieval
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor() as executor:
semantic_future = executor.submit(
self.vector_retriever.retrieve, query, entity_context, top_k
)
feature_future = executor.submit(
self.feature_retriever.retrieve, query, entity_context
)
return {
"semantic_context": semantic_future.result(),
"user_context": feature_future.result()
}
Evaluating Retrieval Quality
A retrieval system is only as good as its ability to surface the right information. Standard evaluation metrics:
Recall@K: Of all relevant documents, what fraction appear in the top-K results? Precision@K: Of the top-K results, what fraction are relevant? MRR (Mean Reciprocal Rank): On average, how high does the first relevant document rank? NDCG (Normalized Discounted Cumulative Gain): Weighted precision that penalizes relevant documents ranked lower.
def evaluate_retrieval(
retriever: Retriever,
test_cases: List[dict], # [{"query": str, "relevant_ids": List[str]}]
k: int = 5
) -> dict:
recall_scores = []
precision_scores = []
mrr_scores = []
for case in test_cases:
results = retriever.retrieve(case["query"], {}, top_k=k)
retrieved_ids = [r["id"] for r in results]
relevant = set(case["relevant_ids"])
# Recall@K
hits = sum(1 for id in retrieved_ids if id in relevant)
recall_scores.append(hits / len(relevant) if relevant else 0)
# Precision@K
precision_scores.append(hits / k)
# MRR
for rank, id in enumerate(retrieved_ids, 1):
if id in relevant:
mrr_scores.append(1/rank)
break
else:
mrr_scores.append(0)
return {
f"recall@{k}": sum(recall_scores) / len(recall_scores),
f"precision@{k}": sum(precision_scores) / len(precision_scores),
"mrr": sum(mrr_scores) / len(mrr_scores)
}
Key Takeaways
- Feature stores and retrieval indexes solve different problems: Use feature stores for ML model inputs; use vector stores for semantic search.
- Embedding consistency is non-negotiable: A single preprocessing function used everywhere is the most important engineering discipline.
- Version your embedding models: Know exactly which model version embedded every document in your index.
- Build a golden evaluation set before optimizing: You can't improve what you can't measure.
- Hybrid retrieval outperforms pure vector search: Combining semantic search with structured feature context produces better results in most real-world AI applications.
FAQ
Q: Should I store embeddings in my feature store? A: Yes, if those embeddings are used as inputs to downstream ML models. No, if they're only used for retrieval. Avoid using a feature store as your primary vector search index.
Q: How do I handle embedding model updates without downtime? A: Use blue-green indexing: build the new index in parallel with the existing one, validate quality on your evaluation set, then atomically swap traffic to the new index.
Q: What's the typical embedding model for production RAG? A: OpenAI's text-embedding-3-small (1536-dim) offers the best cost/performance tradeoff for most use cases. For privacy-sensitive applications or cost at massive scale, consider self-hosted models like E5-large-v2 or BGE-M3.