Distributed, high-performance blob storage on SQLite

Vikram Sengupta

Vikram Sengupta

Engineering Team

10 min read
Index(16 sections)

Executive Brief

SQLite is an effective blob engine inside one failure domain. It supplies transactions, write-ahead logging, checksums for database pages, online backup primitives, and incremental BLOB access. It does not supply membership, consensus, replica placement, network routing, or cross-node recovery.

A production design must preserve that boundary. Each SQLite database and its WAL remain on node-local durable storage. A control plane assigns every shard one fenced write owner. Stateless routers direct writes to that owner and may direct reads to healthy replicas. The data plane transfers immutable chunks between nodes instead of allowing several machines to open the same database file.

This architecture fits edge platforms, private-cloud services, appliances, artifact repositories, and content systems that value a small deployment unit. It becomes a poor fit when applications require concurrent multi-region writes, cross-shard transactions, built-in erasure coding, or a managed object-store operating model.

The relevant failure domains are explicit:

  • A process failure can leave staged or unreferenced chunks.
  • A disk or node failure removes one local SQLite replica.
  • A partition can isolate a former owner after its lease expires.
  • A control-plane outage can stop ownership changes while existing leases continue.
  • An operator error can propagate valid but unwanted deletes to every replica.

SQLite’s WAL documentation states that WAL participants must share the same host because the WAL index uses shared memory. Its locking documentation also depends on filesystem locking behavior. A live SQLite shard must therefore never become a concurrently writable network-mounted database.

Architecture Reference Topology

System Architecture Specification

The owner acknowledges only after the configured durability boundary succeeds. With local durability, an unshipped commit can be lost with the node. With replica durability, each counted replica must fsync the payload and commit its local replication record before it returns an acknowledgement.

Core Engineering Mechanics

Architectural Thesis: Treating SQLite as a Node-Local Storage Engine, Not a Distributed Database

Distribution belongs above SQLite. The shard map resolves a tenant and object key to an owner, replica set, and monotonically increasing ownership epoch. SQLite resolves local transactions within that shard.

WAL mode permits readers to retain snapshots while a writer appends changes, but SQLite still serializes writes. The service should use one writer connection, short write transactions, and a bounded admission queue. Additional writer connections do not create parallel disk commits; they add lock competition and memory consumption. Reader pool size must follow measured page-cache memory, file-descriptor limits, and tail latency.

The service must reject mutations carrying an obsolete epoch. Replicas apply the same rule. A stale owner may still write to its isolated disk, but it cannot collect current replica acknowledgements or publish a current manifest.

Blob Data Modeling: Immutable Chunks, Object Manifests, Content Identity, and Transactional Metadata

A practical schema separates five concerns:

  • chunk records identify immutable payloads by digest, length, storage type, and location.
  • object_manifest records identify tenant, key, generation, state, aggregate length, and object digest.
  • object_chunk records order chunk references within a generation.
  • idempotency records bind a request key and request digest to its committed result.
  • replication_outbox records locally committed work that replicas have not confirmed.

The service computes a content digest while streaming. SHA-256 is defined by NIST FIPS 180-4, but a digest is an integrity identifier rather than an authorization token. Cross-tenant deduplication can reveal content equality and should remain disabled where that disclosure matters.

The manifest becomes visible in one SQLite transaction after all referenced chunks reach the ready state. A crash before that transaction leaves reclaimable chunks, not a partially visible object. Deletes create tombstone generations; garbage collection removes payloads only after replica, backup, and retention watermarks permit removal.

Storage Layout Decisions: Inline BLOB Pages, External Chunk Files, and Hybrid Persistence Models

Inline BLOBs place payload and metadata under one transactional boundary. SQLite stores large record payloads through B-tree overflow pages as documented in its database file format. This approach reduces inode management but can enlarge the WAL and displace metadata from the page cache.

The incremental BLOB API avoids materializing an entire value in application memory. The application first creates a fixed-size value, commonly with zeroblob, and then writes ranges through a BLOB handle. The API cannot resize the value and does not open BLOBs from WITHOUT ROWID tables.

An external-file layout streams immutable chunks into a staged file, fsyncs it, publishes it atomically on the same filesystem, and commits its location in SQLite. This keeps large payload traffic outside the database page cache. It introduces a cross-resource commit gap: a crash can leave an orphan file or a metadata row whose file was not durably published.

A hybrid policy can inline small chunks and externalize large ones. Set the boundary from workload measurements, not from a generic object-size rule.

Distributed Data Plane: Shard Placement, Request Routing, Write Ownership, and Safe Rebalancing

The control plane stores membership and shard leases in a consensus-backed system. Routers cache versioned maps, but they include the observed epoch with every mutation. The owner persists that epoch with the manifest and outbox event.

A rebalance follows a controlled state transition:

  • The existing owner continues to accept writes.
  • The destination copies immutable chunks and a consistent SQLite snapshot.
  • It consumes the owner’s outbox until it reaches the transfer watermark.
  • Both sides verify manifest inventories and chunk digests.
  • The control plane grants a higher ownership epoch.
  • Routers move writes, and the former owner enters read-only drain mode.

Copying a live database directory is not a snapshot protocol. Use SQLite’s online backup API or an application-defined manifest export, then replay changes recorded after the snapshot boundary.

Read and Write Paths: Streaming I/O, Transaction Shaping, Cache Locality, and Backpressure

A write streams through a bounded buffer while computing its digest. The service stages and fsyncs the chunk before opening a short SQLite transaction that records chunk readiness, manifest visibility, idempotency state, and the replication outbox event. Replication occurs after local commit. A lost response is safe because a retry with the same idempotency key returns the prior result.

Reads resolve one committed manifest generation, then stream ordered chunk ranges. A replica must reject unknown generations or stale ownership state so the router can fall back to the owner. Full digest verification on every read consumes CPU and memory bandwidth; verify at ingestion and repair time, then apply sampled or risk-based read verification.

Admission control must occur before unbounded staging. Track admitted uploads, writer wait time, staged bytes, free disk, WAL growth, and replica lag. Return overload rather than allowing disk exhaustion to turn a shard-wide latency event into corruption or eviction pressure.

Production Code Implementation

The following Go primitive implements hybrid chunk ingestion. Schema migration must create chunk and a uniquely constrained replication_outbox. The write DSN must enable WAL, full synchronous commits, and foreign keys; the read DSN should use read-only mode. The stage and chunk directories reside on the same filesystem.

package blobnode
import (
	"context"
	"crypto/sha256"
	"database/sql"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"time"
	_ "modernc.org/sqlite"
)
var ErrTooLarge = errors.New("blob exceeds configured limit")
type Config struct {
	WriteDSN, ReadDSN string
	Root string
	Readers, Admission int
	MaxBody int64
	Timeout time.Duration
}
type Store struct {
	write, read *sql.DB
	root string
	maxBody int64
	timeout time.Duration
	admit chan struct{}
}
func Open(c Config) (*Store, error) {
	if c.Readers < 1 || c.Admission < 1 || c.MaxBody < 1 || c.Timeout <= 0 {
		return nil, errors.New("invalid store limits")
	}
	for _, name := range []string{".stage", "chunks"} {
		if err := os.MkdirAll(filepath.Join(c.Root, name), 0o750); err != nil {
			return nil, fmt.Errorf("create data directory: %w", err)
		}
	}
	if err := syncDir(c.Root); err != nil { return nil, err }
	w, err := sql.Open("sqlite", c.WriteDSN)
	if err != nil { return nil, fmt.Errorf("open writer: %w", err) }
	r, err := sql.Open("sqlite", c.ReadDSN)
	if err != nil { w.Close(); return nil, fmt.Errorf("open readers: %w", err) }
	w.SetMaxOpenConns(1)
	w.SetMaxIdleConns(1)
	r.SetMaxOpenConns(c.Readers)
	r.SetMaxIdleConns(c.Readers)
	ctx, cancel := context.WithTimeout(context.Background(), c.Timeout)
	defer cancel()
	var mode string
	if err = w.QueryRowContext(ctx, "PRAGMA journal_mode").Scan(&mode); err != nil {
		w.Close(); r.Close(); return nil, fmt.Errorf("read journal mode: %w", err)
	}
	if mode != "wal" {
		w.Close(); r.Close(); return nil, fmt.Errorf("journal mode is %q", mode)
	}
	if err = r.PingContext(ctx); err != nil {
		w.Close(); r.Close(); return nil, fmt.Errorf("ping readers: %w", err)
	}
	return &Store{w, r, c.Root, c.MaxBody, c.Timeout, make(chan struct{}, c.Admission)}, nil
}
func (s *Store) Close() error {
	a, b := s.read.Close(), s.write.Close()
	if a != nil { return a }
	return b
}
type contextReader struct { context.Context; io.Reader }
func (r contextReader) Read(p []byte) (int, error) {
	if err := r.Context.Err(); err != nil { return 0, err }
	return r.Reader.Read(p)
}
func (s *Store) Put(parent context.Context, src io.Reader) (string, error) {
	ctx, cancel := context.WithTimeout(parent, s.timeout)
	defer cancel()
	select {
	case s.admit <- struct{}{}:
		defer func() { <-s.admit }()
	case <-ctx.Done():
		return "", ctx.Err()
	}
	f, err := os.CreateTemp(filepath.Join(s.root, ".stage"), "put-*")
	if err != nil { return "", fmt.Errorf("create stage file: %w", err) }
	staged := f.Name()
	defer func() { f.Close(); os.Remove(staged) }()
	h := sha256.New()
	n, err := io.Copy(io.MultiWriter(f, h),
		io.LimitReader(contextReader{ctx, src}, s.maxBody+1))
	if err != nil { return "", fmt.Errorf("stream blob: %w", err) }
	if n > s.maxBody { return "", ErrTooLarge }
	if err = f.Sync(); err != nil { return "", fmt.Errorf("sync blob: %w", err) }
	if err = f.Close(); err != nil { return "", fmt.Errorf("close blob: %w", err) }
	digest := hex.EncodeToString(h.Sum(nil))
	dir := filepath.Join(s.root, "chunks", digest[:2])
	final := filepath.Join(dir, digest)
	if err = os.MkdirAll(dir, 0o750); err != nil {
		return "", fmt.Errorf("create chunk directory: %w", err)
	}
	if err = syncDir(filepath.Dir(dir)); err != nil { return "", err }
	if err = os.Link(staged, final); err != nil && !errors.Is(err, os.ErrExist) {
		return "", fmt.Errorf("publish chunk: %w", err)
	}
	if err = syncDir(dir); err != nil { return "", err }
	tx, err := s.write.BeginTx(ctx, nil)
	if err != nil { return "", fmt.Errorf("begin metadata: %w", err) }
	defer tx.Rollback()
	_, err = tx.ExecContext(ctx, `INSERT INTO chunk(hash,bytes,path,state)
		VALUES(?,?,?,'ready') ON CONFLICT(hash) DO NOTHING`, digest, n, final)
	if err != nil { return "", fmt.Errorf("insert chunk: %w", err) }
	_, err = tx.ExecContext(ctx, `INSERT INTO replication_outbox(kind,chunk_hash)
		VALUES('chunk_ready',?) ON CONFLICT DO NOTHING`, digest)
	if err != nil { return "", fmt.Errorf("insert outbox: %w", err) }
	if err = tx.Commit(); err != nil { return "", fmt.Errorf("commit metadata: %w", err) }
	return digest, nil
}
func syncDir(path string) error {
	d, err := os.Open(path)
	if err != nil { return fmt.Errorf("open directory: %w", err) }
	defer d.Close()
	if err = d.Sync(); err != nil { return fmt.Errorf("sync directory: %w", err) }
	return nil
}

The hard link prevents replacement of an existing content-addressed chunk. A crash after file publication but before metadata commit leaves an orphan that the scanner can remove. The object-manifest method should add its manifest rows and outbox record in one transaction using the same writer connection.

Consistency and Durability: Idempotency, Commit Boundaries, Replication Policies, and Failure Semantics

SQLite provides serializable writes through transaction serialization and snapshot isolation for WAL readers; see SQLite isolation. It does not make a local transaction a distributed commit.

Define acknowledgement policies as product contracts:

  • Local durable: acknowledge after payload fsync and local SQLite commit. Node loss can remove acknowledged data.
  • Replica durable: acknowledge after the required replicas persist payload and metadata.
  • Asynchronous: commit locally and ship from the transactional outbox. Recovery-point exposure equals the unreplicated suffix.

Replica-durable mode is not automatically consensus. Strong ownership requires a fenced control-plane lease, epoch checks, and refusal to acknowledge without the current replica policy. If an acknowledgement times out after commit, clients retry with the same idempotency key. They must not infer failure from a missing response.

Hardware and storage layers must honor flushes. PRAGMA synchronous=FULL cannot compensate for a controller that falsely reports durable completion.

Lifecycle and Recovery: Integrity Checking, Replica Repair, Garbage Collection, Checkpointing, Backup, and Restore

PRAGMA integrity_check validates SQLite structure, while foreign_key_check validates declared references; both are documented in the PRAGMA reference. They do not validate external payload content. Background workers must also recompute chunk digests and compare replica inventories.

Repair copies a chunk from a healthy replica into staging, verifies it, fsyncs it, and publishes it before changing local metadata. Garbage collection should mark from committed manifests and sweep only below replication, tombstone, and backup watermarks. Reference counts can accelerate discovery but should not be the sole source of truth after interrupted operations.

Long readers can prevent WAL checkpoint completion and allow the WAL to grow. Observe WAL size, oldest reader age, checkpoint duration, busy results, and writer queue time. Run checkpoints as controlled maintenance rather than placing them on every request path.

A backup couples an SQLite snapshot with an immutable chunk inventory and ownership epoch. Restore into an isolated node, run integrity checks, compare chunk digests, catch up replication, and only then register it as a replica.

Quantitative Benchmark Evaluation

SQLite’s official blob-versus-file benchmark is useful evidence for its stated local workload. It does not report distributed service percentiles, replicated-write RPS, or process memory. Those values cannot be transferred to different hardware, filesystems, object distributions, or durability policies.

Publish results only after recording the SQLite build, filesystem, storage device, cache state, object-size distribution, read/write mix, shard count, acknowledgement policy, and fault injection. Use an open-loop driver and an HDR histogram so queueing delay and coordinated omission remain visible.

Test cellp50 latencyp95 latencyp99 latencyp99.9 latencyRPSMemory footprint
Inline BLOB, local commitMeasure on targetMeasure on targetMeasure on targetMeasure on targetNot portablePage cache plus process RSS
External chunk, local commitMeasure on targetMeasure on targetMeasure on targetMeasure on targetNot portableStreaming buffers plus OS cache
External chunk, replica acknowledgementMeasure on targetMeasure on targetMeasure on targetMeasure on targetNetwork and fsync boundedAdd replication buffers
Healthy-replica readMeasure warm and coldMeasure warm and coldMeasure warm and coldMeasure warm and coldCache dependentReader pools plus caches
Write during checkpoint or repairMeasure under contentionMeasure under contentionMeasure under contentionMeasure under contentionWriter serializedInclude worker RSS

Analytical Simulation: Discrete-event queueing projection. No synthetic values are supplied because arrival and service-time distributions are deployment inputs. Source basis: SQLite WAL, SQLite status counters, and HdrHistogram.

A release gate should compare the measured percentiles, error rate, queue depth, disk reserve, and replication lag against the service SLO. Review CPU and blocking flamegraphs before increasing connection pools.

Trade-Off & Decision Matrix

PatternWrite boundaryFailure blast radiusCost envelopeDecision guidance
Inline BLOB per SQLite shardOne local writerShard unavailable until failoverLow component count; database growth costUse for bounded objects and transactional locality
External chunks with SQLite manifestsOne owner plus filesystemOrphans require repair; shard loss depends on replicasLow platform cost; inode and scanner costUse for streaming and larger payloads
Hybrid inline and externalPolicy-selected pathBoth recovery modes applyMore implementation and test costUse only after workload measurement
Shared live SQLite on network storageFilesystem lock domainStorage or locking faults can affect all writersApparently simple; high correctness riskReject for concurrent network writers
Native object store plus metadata DBService-managed distributionProvider or cluster failure domainUsage-based or dedicated-cluster costPrefer for broad lifecycle and scale features
Distributed SQL storing BLOBsConsensus transactionQuorum or regional blast radiusHigher compute and operational costUse when cross-row distributed transactions dominate

Sources: SQLite WAL restrictions, SQLite locking, and Amazon S3 consistency model. Cost entries are qualitative and require provider quotations.

Production Readiness: Security, Tenant Isolation, Observability, Validation, Capacity Guardrails, and Fit Criteria

Authenticate at the gateway and authorize every tenant, object key, and operation at the storage node. Use mTLS between routers, owners, replicas, and the control plane. Never derive filesystem paths from client keys. Encrypt the volume and backup repository through the platform key service. Treat manifests, digests, and access logs as tenant data.

Emit spans for route lookup, admission, staging, SQLite wait, commit, replication, and acknowledgement. Export writer queue depth, staged bytes, WAL growth, checkpoint state, disk errors, repair results, replica lag, lease epoch, and free-space guardrails. Logs should contain request IDs, shard IDs, generations, and epochs without payload bytes or credentials.

The following Helm-rendered Kubernetes manifest keeps each database on a single-writer PVC. Values for replicas, resources, probes, and storage must come from capacity tests and failure policy rather than copied defaults.

Production Deployment Manifest

apiVersion: v1
kind: Service
metadata:
  name: blob-node
spec:
  clusterIP: None
  selector:
    app: blob-node
  ports:
    - name: grpc
      port: {{ .Values.ports.grpc }}
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: blob-node
spec:
  minAvailable: {{ .Values.pdb.minAvailable }}
  selector:
    matchLabels:
      app: blob-node
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: blob-node
spec:
  serviceName: blob-node
  replicas: {{ .Values.replicaCount }}
  updateStrategy:
    type: OnDelete
  selector:
    matchLabels:
      app: blob-node
  template:
    metadata:
      labels:
        app: blob-node
    spec:
      automountServiceAccountToken: false
      terminationGracePeriodSeconds: {{ .Values.terminationGracePeriod }}
      affinity:
        {{- toYaml .Values.affinity | nindent 8 }}
      securityContext:
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: blob-node
          image: "{{ .Values.image.repository }}@{{ .Values.image.digest }}"
          imagePullPolicy: IfNotPresent
          args: ["serve", "--config=/etc/blob-node/config.yaml"]
          securityContext:
            runAsNonRoot: true
            readOnlyRootFilesystem: true
            allowPrivilegeEscalation: false
            capabilities:
              drop: ["ALL"]
          ports:
            - name: grpc
              containerPort: {{ .Values.ports.grpc }}
            - name: admin
              containerPort: {{ .Values.ports.admin }}
          env:
            - name: NODE_ID
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
          readinessProbe:
            httpGet:
              path: /ready
              port: admin
          livenessProbe:
            httpGet:
              path: /live
              port: admin
          lifecycle:
            preStop:
              httpGet:
                path: /admin/drain
                port: admin
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
          volumeMounts:
            - name: data
              mountPath: /data
            - name: config
              mountPath: /etc/blob-node
              readOnly: true
            - name: tls
              mountPath: /var/run/blob-tls
              readOnly: true
      volumes:
        - name: config
          configMap:
            name: blob-node
        - name: tls
          secret:
            secretName: blob-node-tls
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOncePod"]
        storageClassName: {{ .Values.storage.className }}
        resources:
          requests:
            storage: {{ .Values.storage.size }}

OnDelete allows the control plane to drain and transfer a shard before an update removes its owner. Readiness must fail when the node lacks a valid membership state, writable disk, or required recovery status. A PodDisruptionBudget limits voluntary disruption; it does not protect against node loss.

The manifest follows the Kubernetes definitions for StatefulSets, PodDisruptionBudgets, and persistent-volume access modes.

Executive Directive & Next Steps

Platform leaders should approve this design only after the following controls exist:

  • Assign one fenced writer per shard and reject stale epochs at owners and replicas.
  • Keep SQLite databases, WAL files, and temporary chunks on node-local or single-pod durable volumes.
  • Select inline, external, or hybrid storage from measured workload results.
  • Couple manifest commits, idempotency records, and replication events in local transactions.
  • Define acknowledgement semantics and recovery-point exposure in the service contract.
  • Test owner loss, partition, disk exhaustion, checkpoint contention, corrupt chunks, and interrupted rebalancing.
  • Verify backups through isolated restores rather than successful backup jobs alone.
  • Publish percentile latency, RPS, memory, and error results with the exact durability policy.
  • Maintain an export format that preserves manifests, chunk order, digests, generations, and tombstones.

SQLite should remain replaceable behind the shard interface. That constraint protects the service from local-engine limits while preserving SQLite’s strongest property: a compact, well-tested transactional core with a small operational surface.

Share This Article

More Engineering Architecture Playbooks

Deep dives and blueprints from our senior engineering team

Critical CVE Alert: CVE-2026-90817 - Vanderbilt University Research Electronic Data Capture (REDCap) Code Injection Vulnerability
Architecture•10 min read

Critical CVE Alert: CVE-2026-90817 - Vanderbilt University Research Electronic Data Capture (REDCap) Code Injection Vulnerability

The core thesis is that teams should treat the reported vulnerability as an urgent validation and exposure-management event, not as a confirmed incident based solely on an alert. The paper will separate verified facts from hypotheses and provide a production-safe decision framework for containment, detection, remediation, recovery, and stakeholder communication.

These Engineers Are Cleaning Up Connected Cars’ Security Flaws
Architecture•10 min read

These Engineers Are Cleaning Up Connected Cars’ Security Flaws

Connected-car security cannot be repaired as a sequence of isolated patches because vehicle firmware, telematics, cloud APIs, mobile applications, identity systems, and supplier components form one production environment. This case study examines how an engineering team can trace vulnerabilities across those boundaries, contain immediate risk, deliver verifiable fixes, and embed security into ongoing vehicle operations without inventing certainty where evidence is incomplete.

Microsoft 365 outage leads to chlorine gas poisoning of 15 hotel guests
Architecture•10 min read

Microsoft 365 outage leads to chlorine gas poisoning of 15 hotel guests

A cloud productivity outage should never be capable of disabling the controls needed to operate hazardous hotel systems safely. This paper will distinguish chronology from causation, examine how digital dependencies and human factors could allow an outage to propagate into physical operations, and define an architecture in which local safeguards, offline procedures, and emergency authority remain available independently of Microsoft 365.