Stack AI Vector DB
A FastAPI service for efficient vector database operations with multiple indexing algorithms and persistent storage.
Table of Contents
Overview
Stack AI Vector DB is a specialized service for managing vector databases that efficiently store, index, and search text embeddings. It provides a scalable solution for semantic similarity search, featuring multiple indexing algorithms and persistent disk storage.
Features
- In-memory vector storage with JSON persistence
- Multiple vector indexing algorithms (BruteForce, BallTree)
- RESTful API with FastAPI
- Thread-safe operations for concurrent access
- Hierarchical document organization (libraries → documents → chunks)
- Automatic vector embedding generation (via Cohere API)
- Comprehensive test suite
- Docker and Docker Compose support
- Wikipedia data importer for demo purposes
Installation
Local Installation
-
Clone the repository:
git clone https://github.com/yourusername/stack-ai-vector-db.git
cd stack-ai-vector-db
-
Create and activate a virtual environment:
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt
-
Set up environment variables:
echo "COHERE_API_KEY=your_api_key_here" > .env
-
Run the application:
python -m uvicorn app.main:app --host 0.0.0.0 --port 8000
-
Access the API documentation:
-
Verify the service is running:
curl http://localhost:8000/health
# Expected response: {"status": "ok"}
Docker Installation
-
Build the Docker image:
docker build -t stack-ai-vector-db .
-
Run the container:
docker run -p 8000:8000 -e COHERE_API_KEY=your_api_key_here stack-ai-vector-db
Docker Compose
-
Create a .env file with your Cohere API key:
echo "COHERE_API_KEY=your_api_key_here" > .env
-
Run with Docker Compose:
-
To use the test dataset:
TESTING_DATA=true docker-compose up
Kubernetes Deployment
For deploying to a Kubernetes cluster like Minikube, this project includes a Helm chart in the helmchart/ directory.
-
Build and push the Docker image:
docker build -t your-username/vector-db:latest .
docker push your-username/vector-db:latest
-
Update the image repository in values.yaml:
image:
repository: your-username/vector-db
tag: latest
-
Install the Helm chart:
# Create base64 encoded API key
COHERE_API_KEY_B64=$(echo -n "your-actual-api-key" | base64)
# Install the chart
helm install vector-db ./helmchart/vector-db --set cohereApiKey=$COHERE_API_KEY_B64
-
Access the service in Minikube:
minikube service vector-db --url
Health and Readiness Probes
The Kubernetes deployment includes health monitoring via probes that connect to the application's /health endpoint:
-
Liveness Probe: Verifies the application is running and responsive. If this probe fails, Kubernetes automatically restarts the container.
- Initial delay: 30 seconds after container starts
- Check frequency: Every 10 seconds
- Timeout: 5 seconds per check
- Failure threshold: 3 consecutive failures trigger a restart
-
Readiness Probe: Determines if the application is ready to receive traffic. Until this probe succeeds, the pod won't receive requests.
- Initial delay: 5 seconds after container starts
- Check frequency: Every 10 seconds
- Timeout: 2 seconds per check
- Success threshold: 1 successful check to mark as ready
- Failure threshold: 3 failures to mark as not ready
These probes ensure high availability by:
- Automatically restarting unhealthy containers
- Routing traffic only to healthy instances
- Enabling smoother rolling updates during deployments
All probe settings can be customized in the Helm chart's values.yaml file.
Database Model
The database is structured using a hierarchical model:
-
Library: The top-level container that holds documents and configuration
- Properties: id, name, metadata, index_status
- Relationships: one-to-many with Documents
-
Document: Contains metadata and a collection of text chunks
- Properties: id, library_id, name, metadata
- Relationships: belongs-to Library, one-to-many with Chunks
-
Chunk: The smallest unit of text with vector embeddings
- Properties: id, document_id, text, embedding, metadata
- Relationships: belongs-to Document
This hierarchical approach enables:
- Logical organization of related content
- Efficient retrieval by context
- Independent indexing for different content collections
- Flexible metadata at multiple levels
Indexing Algorithms
The system implements two vector indexing algorithms:
BruteForce Indexer
- Simple implementation that compares query vectors with all indexed vectors
- Time complexity: O(n) where n is the number of vectors
- Space complexity: O(n×d) where d is the embedding dimension
- Pros: Exact results, simple implementation
- Cons: Slow for large datasets
- Best for: Small libraries (<1000 vectors) or when precision is critical
BallTree Indexer
- Tree-based structure that organizes vectors in nested hyperspheres
- Time complexity: O(log n) average case for queries
- Space complexity: O(n×d) plus tree overhead
- Pros: Faster queries on large datasets, scales better
- Cons: Slightly more complex, approximate results
- Best for: Larger libraries, speed-critical applications
- Configuration: Tunable via
leaf_size parameter (default: 40)
Choosing the Right Indexer
- Brute Force: Best for small datasets (< 1000 vectors) or when exact results are critical
- Ball Tree: Better for larger datasets, higher-dimensional embeddings, or when search speed is important
The leaf_size parameter in Ball Tree allows tuning the trade-off between search speed and memory usage:
- Smaller leaf sizes (10-20) create deeper trees that can search faster but use more memory
- Larger leaf sizes (40-100) create shallower trees that use less memory but may search slightly slower
Concurrency and Thread Safety
The application handles concurrent operations through:
-
Fine-grained Locks: Separate locks for libraries, documents, and chunks
self.library_lock = threading.RLock()
self.document_lock = threading.RLock()
self.chunk_lock = threading.RLock()
-
Reentrant Locks: Using RLock to allow the same thread to acquire a lock multiple times
-
Atomic Operations: Critical operations are wrapped in a single lock context:
with db.document_lock:
# Atomic operations here
-
Relationship Consistency: Locks ensure map relationships remain consistent:
with db.document_lock:
db.documents[document_id] = document_data
db.document_library_map[document_id] = library_id
-
Hierarchical Locking: Careful lock ordering prevents deadlocks
CRUD Operations & Data Flow
The service implements a layered architecture:
-
Database Layer (app/database/):
- Direct data access with thread-safe operations
- Maintains relationships between entities
- Handles persistence to disk
-
Service Layer (app/services/):
- Business logic implementation
- Coordinates database operations
- Manages side effects and dependencies
-
API Layer (app/routers/):
- HTTP endpoint routing
- Input validation
- Response formatting
Data flow follows a clean, cascading pattern:
- Creating a document automatically creates its chunks
- Deleting a library automatically deletes its documents and their chunks
- Updating a document or chunk marks the library as not indexed
- Library operations like search automatically use the appropriate indexer
Automatic Data Loading on Startup
Thanks to the persistence system, every time the application starts, it automatically loads all vector libraries stored as JSON files in the /data directory. This gives you immediate access to your previously created libraries without having to recreate them.
The project includes a pre-built vector database about Andorra with the following structure:
- 1 library named "Andorra"
- 5 documents covering different aspects (Overview, History, Tourism, Geography, Culture)
- 23 text chunks with factual information
This test database is automatically loaded on startup if the TESTING_DATA environment variable is set to true in your .env file:
TESTING_DATA=true
TESTING_DATA_FILE=app/data/library_a1b2c3d4-e5f6-7890-9101-1a2b3c4d5e6f.json
If you want to disable loading this test database, simply set TESTING_DATA=false in your .env file or remove these environment variables.
This automatic loading feature makes the application ready-to-use immediately after startup and allows you to experiment with search functionality without having to create your own data first.
API Workflow
The typical workflow for using the API:
-
Create a Library:
curl -X POST "http://localhost:8000/api/libraries" \
-H "Content-Type: application/json" \
-d '{"name": "Research Papers", "metadata": {"field": "Computer Science"}}'
-
Create Documents with Chunks:
curl -X POST "http://localhost:8000/api/documents" \
-H "Content-Type: application/json" \
-d '{
"library_id": "your-library-id",
"name": "Transformer Architecture",
"metadata": {"author": "Smith et al."},
"chunks": [
{"text": "Transformers use self-attention...", "metadata": {"position": "0"}},
{"text": "The encoder-decoder architecture...", "metadata": {"position": "1"}}
]
}'
-
Index the Library:
curl -X POST "http://localhost:8000/api/libraries/your-library-id/index" \
-H "Content-Type: application/json" \
-d '{"indexer_type": "BALL_TREE", "leaf_size": 40}'
-
Search the Library:
curl -X POST "http://localhost:8000/api/libraries/your-library-id/search" \
-H "Content-Type: application/json" \
-d '{"query_text": "attention mechanism in transformers", "top_k": 5}'
This workflow separates content creation from indexing, allowing for batch operations and optimized embedding generation.
Library Indexing Lifecycle
- A new library starts with
indexed: false and indexing_in_progress: false
- When you start indexing, the library transitions to
indexed: false and indexing_in_progress: true
- After successful indexing, the library becomes
indexed: true and indexing_in_progress: false
- Any modifications to the library's documents or chunks automatically mark it as
indexed: false