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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
