gotchapythonfastapiCritical
HF Spaces: DB wiped on rebuild — seed users at startup
Viewed 0 times
hf spaces db wipedpersistent storageseed usersrebuild loses datasqlite ephemeral402 payment required storage
docker
Error Messages
Problem
Hugging Face Spaces without persistent storage (requires Pro plan) lose their SQLite database on every rebuild. Any file upload to the Space repo triggers a rebuild, wiping all runtime data including user accounts. Users get locked out after every code deployment.
Solution
Add seed accounts directly in the
init_db() function so they're recreated on every startup. Use INSERT with an existence check (SELECT before INSERT) to avoid duplicates if the DB survives. Passwords are hashed with bcrypt before insertion. This guarantees users can always log in regardless of rebuilds. Persistent storage on HF Spaces requires a Pro subscription ($9/mo) — api.request_space_storage() returns 402 without it.Why
HF Spaces free tier uses ephemeral filesystem. The Dockerfile COPY bakes in the initial DB, but any runtime changes (new users, notes, audit logs) are lost when the container rebuilds. Every
upload_file() via the HF API triggers a rebuild.Gotchas
- HF Spaces persistent storage requires Pro plan — no free workaround
- Every upload_file() call triggers a full rebuild
- Runtime SQLite changes are lost on rebuild including user sessions, notes, audit logs — not just user accounts
Code Snippets
Seed users in init_db to survive rebuilds (no real credentials)
_SEED_USERS = [
{"email": "user@example.com", "name": "User", "password": "CHANGE_ME", "is_admin": 1},
]
def _hash_pw(password: str) -> str:
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
def init_db():
conn = sqlite3.connect(str(DB_PATH))
conn.executescript("""CREATE TABLE IF NOT EXISTS users (...)""")
for user in _SEED_USERS:
existing = conn.execute("SELECT id FROM users WHERE email = ?", (user["email"],)).fetchone()
if not existing:
conn.execute(
"INSERT INTO users (email, name, password_hash, is_admin) VALUES (?, ?, ?, ?)",
(user["email"], user["name"], _hash_pw(user["password"]), user["is_admin"]),
)
conn.commit()
conn.close()Context
Deploying a FastAPI backend with SQLite auth to HF Spaces (free tier, cpu-basic, no persistent storage)
Revisions (0)
No revisions yet.