Storage Internals

Vela's storage rules aim for one property above all: a file that the database says exists always has its bytes. This page explains the mechanisms behind that, for operators who want to understand the guarantees and contributors who change the code.

Data directory layout

/data
├── vela.db              # SQLite (WAL), 0600
├── vela.db-wal          # write-ahead log
├── vela.db-shm
├── blobs/               # 0755 — readable by nginx for accel
│   └── r7/c4/01m4tscd50ry5wfktp4mx4r7c4   # 0644, immutable
└── tmp/                 # 0700 — uploads in progress
  • Blobs are named by lower-case ULIDs and sharded by the last four characters — the random part. Sharding by the first characters would put every blob from the same few days into one directory, because ULIDs start with a timestamp.
  • tmp/ and blobs/ must be on the same filesystem; publication uses links within it.
  • Permissions are set explicitly, never inherited from the umask.
  • In R2 mode only the database is local; blobs live at <bucket>/<prefix><shard>/<id>.

Atomic publication (filesystem)

  1. Stream to tmp

    The body is written to a temporary file in tmp/ while its size is limited and its SHA-256 computed. Exceeding the limit aborts immediately with 413.

  2. Verify

    If the client sent X-Vela-SHA256, it is compared in constant time; a mismatch aborts with checksum_mismatch.

  3. Make durable

    The file is chmodded 0644 and fsynced.

  4. Publish exclusively

    It is hard-linked to blobs/<shard>/<id> — an exclusive operation that refuses to replace an existing ID — then the temporary name is removed and every new directory, including the shard, is fsynced.

  5. Commit metadata

    Only now is the database row written, with conflict and precondition checks inside the transaction. If the transaction fails, the new blob is removed.

A crash at any point leaves either nothing visible or a complete file. Leftovers in tmp/ and unreferenced blobs are cleaned by the janitor after an hour.

SQLite configuration

  • journal_mode=WAL, synchronous=NORMAL, busy_timeout and foreign keys on.
  • One writer connection serialized with BEGIN IMMEDIATE — no lock-upgrade SQLITE_BUSY surprises — and four query_only reader connections.
  • Migrations are embedded and applied in order at startup.

With synchronous=NORMAL, a committed transaction can roll back after a power loss until the next checkpoint. That is why content is never deleted immediately.

Deferred collection

When an overwrite, purge or orphan scan removes the last reference to a blob, the same transaction inserts it into the blob_gc queue. The collector — every five minutes and during janitor passes — deletes a queued blob only after:

  • a 15-minute grace period, so requests authorized before the change can finish (including nginx accel reads);
  • a PRAGMA wal_checkpoint(FULL), the durability barrier that makes the reference removal permanent;
  • a re-check that no live object or trash entry references it.

Entries leave the queue only after the physical deletion succeeded (or the blob turned out to be referenced again). Failures stay queued and stop the current pass; the next pass retries without a full orphan walk.

Leases

Long-running operations hold renewable leases in the database so that separate processes coordinate:

LeaseHeld byEffect
janitorA janitor passPasses never overlap across processes; a pass that loses its lease stops.
backupvelad backup, velad storage migrateThe collector deletes nothing; backups and migrations exclude each other.

Leases renew every third of their duration (default one hour). Losing one cancels the operation rather than letting two processes proceed concurrently.

Directory policy cache

All directory policies are loaded into an immutable in-memory map. A persistent counter, advanced by insert/update/delete triggers in the same transaction, invalidates it — including changes made by other processes. Public listings read their objects in batches, then re-check the generation and retry if a concurrent move changed policies mid-read, so a hidden directory can never appear by combining old rules with new paths.

The R2/S3 backend

  • Uploads stream through the SDK's multipart uploader with a fixed part size (5–64 MiB) and per-upload concurrency (1–16). A semaphore (VELA_MAX_CONCURRENT_UPLOADS) bounds simultaneous uploads.
  • The stream is size-limited and hashed on the way. Exceeding the limit cancels and aborts the multipart upload; a checksum mismatch, detectable only after completion, deletes the object.
  • Requests use connection and header deadlines and at most three attempts; there is no total deadline on bodies.
  • Errors are sanitized: no raw SDK messages or presigned URLs reach logs.
  • Health uses HeadBucket, cached for 45 seconds.
  • Stale multipart uploads are aborted by the janitor after 24 hours; a bucket lifecycle rule is the safety net.

Memory: buffers are about part size × (concurrency + 2) × active uploads; plan for part size × (concurrency + 4) × active uploads. Size ceiling: part size × 10,000. See R2 memory planning.

Delivery contracts

  • HEAD and matching conditional requests are answered from metadata without opening content.
  • The SHA-256 ETag is the sole validator; Last-Modified is never sent.
  • Public/unlisted downloads: public, max-age=300. Signed and API downloads: private, no-store. Invalid ranges: 416, no-store, no ETag.
  • Accel passes cache, ETag, robots and referrer policies through X-Vela-* headers that nginx re-emits exactly once — verified by the end-to-end test.
  • R2 redirects encode response headers in the presigned URL, cap grants at object/link expiry, and fall back to proxy near expiry and for conditional requests.

Backup and migration guarantees

  • Backup (fs): VACUUM INTO snapshot plus every referenced live/trash blob, hard-linked or copied, size-checked (and SHA-256 with --verify), under the backup lease. Missing or damaged blobs fail the backup; partial output is removed.
  • Backup (R2): SQLite only. A consistent pair requires the server stopped while the snapshot and a bucket copy are taken.
  • Restore: with Vela stopped, restore vela.db, remove stale -wal/-shm files, restore matching blobs or bucket prefix, start with the same backend settings.
  • Symlinks have no blob, so backups, migrations, the orphan scan and the collector skip them; they travel in the database snapshot and keep pointing at the same object IDs.
  • Migration: preserves IDs and metadata; verifies destinations before using sources (so reruns resume even after partial source deletion); --delete-source starts only after every destination is verified. It pins blobs but does not block writes — operators must quiesce them.