blog.rust.gay

Blobasaur puts a sharded blob store on SQLite

Zerodha's Kite trading platform has about 20 million customers. Its users save multi-chart layouts, indicator templates, vector drawings, and workspace preferences. Under the hood, those are opaque JSON blobs ranging from a few kilobytes to several megabytes, written and read thousands to tens of thousands of times per second. The company's old store, SSDB, was unmaintained, single-node, and had forced a 1 MB cap on blob size. Zerodha replaced it with Blobasaur, a Rust binary that speaks the Redis protocol and uses SQLite as its storage engine.

The interesting part is not that SQLite can store blobs. It is that a sharded SQLite design with per-shard writers, group commit, and compression is a better fit for this workload than the usual distributed databases. Blobasaur is a useful counterexample to the idea that every high-throughput service needs a complex distributed system. It also has clear limits, and the team is unusually candid about them.

The workload is the design

The first thing to understand about Blobasaur is that it was not built as a general-purpose database. It was built for a specific access pattern: overwrite-heavy key-value blobs, mostly JSON, with TTLs, where losing a recent UI preference is annoying but not catastrophic. Writes make up roughly 50% of production traffic. The payloads are large enough that per-request overhead matters, but small enough that a compressed value usually fits in a few SQLite pages.

That profile rules out several obvious candidates. ScyllaDB was already in use for high-throughput workloads, but it performed poorly on large blobs and required careful tombstone tuning for frequent overwrites and TTL expiries. PostgreSQL with BYTEA columns was not efficient for this shape. RocksDB had the right primitives but was not architected for multi-megabyte writes. Ceph was too operationally heavy. SeaweedFS was close, but its append-before-compaction behavior and lack of per-blob TTL made it a poor fit for an overwrite-heavy workload. S3 and MinIO had high per-request latency for small blobs, high request costs under write-heavy load, and coarse lifecycle TTLs instead of exact key expiry.

The raw filesystem was the other option: one file per blob. That would have required implementing atomic writes, batching, TTL cleanup, file-descriptor management, and a separate metadata index. SQLite already provides those primitives. SQLite's own benchmark claims up to 35% faster operation than raw filesystem I/O for small blobs. Above roughly 100 KiB, raw files start to win, but Blobasaur compresses before writing, and 99% of compressed values sit below 100 KiB. That is the key economic detail: compression changes the crossover point.

SQLite as a storage engine, not a database server

Blobasaur uses SQLite in WAL mode. In WAL mode, a single SQLite database allows concurrent readers but only one writer at a time. Since writes are half of production traffic, a single database file per node would bottleneck quickly. The solution is to split the keyspace across multiple SQLite database files, called shards, on the same machine.

Each shard has a dedicated writer task fed by a bounded queue. The writer drains a batch of pending writes and executes them inside a single BEGIN IMMEDIATE ... COMMIT transaction. That group commit amortizes transaction and WAL overhead across concurrent clients. Reads go directly to a per-shard pool of read-only SQLite connections and can run concurrently with the writer. Consistent hashing maps each key to a shard, so adding or removing a shard moves a limited set of keys rather than reshuffling the whole node.

The schema is intentionally simple. Plain keys live in a blobs table with a primary key, a data blob, timestamps, an optional expires_at, and a version. Hashes use a per-namespace table such as blobs_prefs with the same columns. A partial index on expires_at keeps rows without a TTL out of the expiry index. Reads filter expired rows, and a background worker reaps them asynchronously. That is enough for the access pattern, and it avoids the complexity of a query planner, secondary indexes, and server-side scripting.

The Rust choice is also pragmatic. Most of Zerodha's backend is Go, but Go's standard SQLite driver requires CGo, which complicates static builds, pins OS threads during C calls under high concurrency, and adds garbage-collection pressure when allocating and compressing multi-megabyte buffers. Blobasaur uses Rust with sqlx, rusqlite, and tokio, calls SQLite's C API directly, and ships a single static binary. That is not a language argument. It is an operational argument about predictable memory use and deployment.

The schema also illustrates the API boundary. Existing services already spoke Redis, so the migration did not require rewriting application code. A service can run HSET prefs user42 '<json>' and later HGET prefs user42 without knowing whether the value lives in a plain key table or a per-namespace hash table. That compatibility was a risk-reduction decision: the fewer application changes, the fewer places to introduce a regression during the migration from SSDB.

SQLite also gives the operators a useful escape hatch. Any shard can be inspected with the sqlite3 CLI or queried with plain SQL for analytics. That is not a substitute for a proper observability stack, but it is valuable during an incident. When a user reports a missing workspace, an operator can look at the row directly instead of decoding a proprietary storage format. The tooling is boring, which is the point.

The numbers

Zerodha benchmarked one shard against sixteen shards with 64 concurrent connections, 100,000 keys, 64 KiB JSON payloads, synchronous writes, and a batch size of 50. The data directory was on tmpfs to isolate SQLite locking and CPU overhead from disk variance. Both setups received the same total resources: 1,600 MB of SQLite page cache and 64 read connections.

Workload 1 shard 16 shards
HSET only 7,740 ops/s, p99 10.7 ms 25,324 ops/s, p99 8.3 ms
50% HSET, 50% HGET 14,227 ops/s, p99 10.5 ms 29,538 ops/s, p99 8.5 ms
HGET only 67,128 ops/s, p99 2.1 ms 70,884 ops/s, p99 2.3 ms

The write throughput improves by about 3.3x, and median write latency drops from 8.2 ms to 2.1 ms. Read throughput barely changes, because SQLite WAL mode already serves concurrent readers without contention. That is the expected result, and it is a useful one: sharding buys write concurrency, not read concurrency, for this design.

At 25,324 HSET operations per second with a 64 KiB payload, Blobasaur processes roughly 1.66 GB/s of uncompressed JSON through zstd. The caveat is important: the server and the load generator ran on the same 16-core laptop, sharing CPU resources. That is a respectable proof of concept, not a data-center capacity plan. A production benchmark should separate the client and server, use real disks, and include the cost of replication and failover.

Compression is where the design pays off. Over one hour of production HSET traffic, the average payload went from 63.6 KiB to 5.5 KiB, about an 11x reduction. The p99 payload went from 935 KiB to 59.3 KiB, about 16x. With SQLite's default 4 KiB pages, shrinking a 63.6 KiB payload to 5.5 KiB reduces its storage footprint from roughly 16 pages to roughly 2 before row and index overhead. That means less page-cache pressure and less data written through the WAL. The compression ratio is not a vanity metric; it is the reason SQLite remains competitive above its usual small-blob sweet spot.

Durability is a deliberate trade-off

Blobasaur runs shards in WAL mode with PRAGMA synchronous = NORMAL. SQLite does not fsync on every transaction commit. An OS crash or power loss can lose recent committed transactions that have not yet been synced to durable storage, while preserving database consistency. That is acceptable for UI preferences. It would not be acceptable for financial data.

The team also supports an optional async_write mode that acknowledges writes as soon as they enter the shard's memory queue, before the SQLite batch commits. To preserve read-your-writes consistency, queued writes are placed in an in-memory pending map that reads check before querying SQLite. The team hit edge cases where read and existence-check paths bypassed the pending map or failed to account for deletes. A DEL followed immediately by a GET could return the old value from SQLite because the queued delete had not committed. They fixed it by storing explicit tombstones in the pending map and routing every read through it.

That is the kind of bug that makes relaxed durability dangerous if you copy the design without understanding it. The performance benefit is real, but the consistency model is not "eventually consistent" in the usual distributed-systems sense. It is "read-your-writes within a node, with explicit tombstones, and possible loss of recent writes on power loss." If your application cannot tolerate that, do not enable it.

Disk reclamation is another operational detail that SQLite does not handle automatically in the way people expect. Deleting rows does not shrink the database file. By default, SQLite keeps freed pages on an internal freelist for future writes. Blobasaur enables PRAGMA auto_vacuum = INCREMENTAL on every shard and adds a blobasaur shard vacuum command to reclaim unused freelist pages within a set allocation, 128 MB by default. Shrinking the actual file in WAL mode also requires a checkpoint, so the command runs PRAGMA wal_checkpoint(TRUNCATE) after the incremental vacuum.

That is the kind of work that a managed database hides from you and a SQLite-based system exposes. It is not difficult, but it has to be scheduled and monitored. A shard that grows without bound because expired rows are never vacuumed is a capacity incident waiting to happen. The team's transparency about this is more useful than another throughput chart.

Where the design stops

Blobasaur implements the Redis Cluster protocol, using 16,384 CRC16 hash slots, MOVED redirects, and gossip for node discovery. That gives it two levels of routing: the cluster level selects a machine, and the node level selects a SQLite shard. But slot assignment is static in configuration. Live slot rebalancing between running nodes and automatic failover are not implemented yet. Resharding is an offline operation through a CLI, with a --verify step to check that keys landed in the expected shards.

Those are significant limitations for a system that calls itself distributed. A production deployment needs a plan for node failure, slot movement, and capacity changes. Blobasaur gives you the storage engine and the protocol, but not a full control plane. You can run it with external orchestration, or you can accept that a node failure requires manual intervention. The team is explicit about this, which is better than pretending the problem does not exist.

The other limit is workload shape. Blobasaur is a poor fit for small, latency-sensitive counters, complex queries, secondary indexes, or strict durability. It is a good fit for large, compressible, overwrite-heavy blobs where a lost recent write is tolerable and the access pattern is simple key-value or hash operations. That is a narrow niche, but it is a real one, and Zerodha's production use shows it can be a large niche.

What to take away

The interesting lesson is not "use SQLite for everything." It is that the storage engine should match the access pattern, and that a simple engine with good operational properties can beat a complex distributed database on a narrow workload. Blobasaur's sharding, group commit, and compression are not novel ideas. The contribution is the combination, packaged as a single Rust binary with Redis compatibility, and validated in production at a company with a demanding latency profile.

If you are considering a similar design, start with the durability question. Can you lose the last few seconds of writes? If not, stop. Then measure the compression ratio and the payload distribution. If most values compress well and fit in a few pages, SQLite may be a better engine than a distributed object store. If the values are small and the request rate is enormous, the per-request overhead will dominate and a different design will win. The benchmark table is useful, but the fit criteria are more useful.

Sources


← back to posts