Database / ChromaDB Interview Questions
How do you back up and restore a ChromaDB persistent database?
A PersistentClient database is simply a directory on disk. Backing it up is as straightforward as copying that directory — but you must ensure no writes are occurring during the copy to avoid a corrupted SQLite file.
import chromadb import shutil import os from datetime import datetime DB_PATH = "./my_chroma_db" BACKUP_DIR = "./backups" # --- Backup strategy 1: Simple directory copy --- # SAFE when: no active PersistentClient writes during the copy os.makedirs(BACKUP_DIR, exist_ok=True) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") backup_path = os.path.join(BACKUP_DIR, f"chroma_backup_{timestamp}") shutil.copytree(DB_PATH, backup_path) print(f"Backup saved to {backup_path}") # --- Backup strategy 2: SQLite online backup (safe during reads) --- import sqlite3 def backup_sqlite(db_path: str, backup_path: str): """SQLite online backup â safe even with active readers.""" src = sqlite3.connect(os.path.join(db_path, "chroma.sqlite3")) dst = sqlite3.connect(os.path.join(backup_path, "chroma.sqlite3")) os.makedirs(backup_path, exist_ok=True) with dst: src.backup(dst, pages=100, progress=lambda s,p,r: print(f"Backed up {p} pages")) dst.close() src.close() # Also copy the HNSW index binary files for root, dirs, files in os.walk(db_path): for f in files: if f != "chroma.sqlite3": rel = os.path.relpath(root, db_path) dest_dir = os.path.join(backup_path, rel) os.makedirs(dest_dir, exist_ok=True) shutil.copy2(os.path.join(root, f), os.path.join(dest_dir, f)) # --- Restore --- def restore_backup(backup_path: str, restore_path: str): if os.path.exists(restore_path): shutil.rmtree(restore_path) # remove current shutil.copytree(backup_path, restore_path) print(f"Restored from {backup_path} to {restore_path}") # Verify restored database client = chromadb.PersistentClient(path=restore_path) for col in client.list_collections(): print(f" {col}: {client.get_collection(col).count()} documents")
For the HttpClient / server mode: stop the ChromaDB server before copying the data directory, or use SQLite's online backup API. Never copy a SQLite file while it has active writers — this can produce a corrupted backup.
More Related questions...