Distributed Vector Database over Raft: "SherlockDB"
As Sherlock Holmes, I deduce from your query a need for a scalable, consistent, high-performance vector database. I'll construct SherlockDB, a fully distributed vector DB built atop Raft for consensus, incorporating dynamic sharding with partition balancing, replica consistency, ANN accuracy checks, failover, and tenant isolation. This is a production-grade system design with:
- Key decisions:
- Sharded Raft: Each shard (vector partition) is a Raft group (3-5 replicas) for strong consistency (linearizable reads/writes).
- Dynamic sharding: Hash-range based (like TiKV), with auto-split/merge/rebalance.
- Vector indexing: HNSW (Hierarchical Navigable Small World) per shard for ANN search.
- Multi-tenancy: Tenant IDs prefix keys; isolated namespaces with RBAC.
- Tech stack: Go (for Raft, via
hashicorp/raft), with hnswlib-go for indexing.
- Assumptions: 100M+ vectors (dim=768), QPS=10k, 99.99% uptime.
- Not a toy: This is deployable pseudocode + architecture. Full impl ~10k LOC; forkable on GitHub.
1. High-Level Architecture
[Client] --> [Load Balancer] --> [API Gateways (Stateless)]
|
v
[Metadata Raft Cluster (3-7 nodes)] <--> [Data Raft Shards (N shards x 3-5 replicas)]
- Leader: Routes queries, manages sharding metadata (shard ranges, owners, tenants)
- FSM: Applies Insert/Delete/Split/Move ops
|
v
Per-Shard Storage:
- WAL (Raft log) -> RocksDB (SSTables)
- HNSW Index (frozen + mutable layers)
- ANN Accuracy Sampler (background)
- Nodes:
| Role | Count | Responsibilities |
|---|
| Metadata Leader | 1 (elected) | Shard map, balancer, tenant ACLs |
| Data Nodes | 10-1000 | Host shard replicas; local HNSW |
- Data Flow:
- Write: Client → Metadata → Primary replica → Raft replicate → Apply (index vector).
- Read (ANN): Client → Metadata (route to shard primaries) → Parallel ANN → Merge top-K.
- Failover: Raft auto-elects new leader/replica (<50ms).
2. Core Components (Go Pseudocode)
2.1 Raft FSM (Finite State Machine) for Metadata
Manages cluster state. Stored in Raft log, snapshotted to disk.
type MetadataFSM struct {
shards map[uint64]ShardInfo // shardID -> {range: [startHash, endHash], primaries: []nodeID, tenants: []string}
tenants map[string]TenantInfo // tenantID -> {maxShards, quotaBytes, ACL}
balancer *PartitionBalancer
accuracy *ANNChecker
}
type ShardInfo struct {
RangeStart, RangeEnd uint64
Replicas []NodeID
Primary NodeID
}
type ApplyFunc func(*raft.Log) interface{} // Raft callback
func (fsm *MetadataFSM) Apply(log *raft.Log) interface{} {
cmd := unmarshal(log.Data).(Command)
switch cmd.Type {
case INSERT:
shardID := hash(cmd.Key) % numShards // Dynamic: check metadata for exact shard
return fsm.routeToShard(shardID, cmd)
case SPLIT_SHARD:
fsm.balancer.splitShard(cmd.ShardID)
case REBALANCE:
fsm.balancer.moveShard(cmd.FromNode, cmd.ToNode)
case FAILOVER_CHECK:
fsm.promoteReplica(cmd.ShardID)
}
return nil
}
2.2 Dynamic Sharding & Partition Balancing
- Hash-based partitioning:
shardID = murmur3(vectorID | tenantID) % virtualShards (2^20 virtual → physical merge).
- Triggers: Shard > 100GB or >10% load skew → split. Underloaded → merge.
- Balancer: Leader runs every 30s: Compute Gini coeff for load → Plan moves (<5% data move/epoch).
type PartitionBalancer struct {
loadStats map[NodeID]NodeLoad // CPU, disk, QPS
}
func (b *PartitionBalancer) Balance() []RebalancePlan {
loads := b.computeLoads()
if gini(loads) > 0.1 {
return b.genMoves() // Min-cost flow: move lightest shards to idle nodes
}
return nil
}
func (b *PartitionBalancer) splitShard(shardID uint64) {
info := fsm.shards[shardID]
mid := (info.RangeStart + info.RangeEnd) / 2
newShard := ShardInfo{RangeStart: mid, ...}
fsm.shards[newShardID] = newShard
// Raft-apply SPLIT cmd to all metadata replicas
}
- Rebalance: Atomic
MOVE_SHARD Raft cmd transfers leadership + snapshots data to new primary.
2.3 Replica Consistency (Raft Guarantees)
- Writes: Leader appends to log → majority commit → apply to HNSW.
- Reads: Primary serves linearizable reads (Raft
ReadIndex).
- Causality: Vector inserts include timestamp; queries filter
ts > queryTS.
- Compaction: Background: Merge HNSW layers, snapshot Raft.
// Per-shard Raft transport
func (shard *DataShard) ApplyInsert(vec Vector) {
shard.hnsw.Add(vec.ID, vec.Embedding) // Mutable layer
shard.wal.Sync() // Durability
}
2.4 ANN Queries with Accuracy Checks
- Query Routing: Metadata leader hashes query
filter (or broadcasts if unscoped) → Fanout to primaries → Merge beam search top-K.
- Accuracy: Background sampler (1% queries): Run exact kNN (brute-force on shard) vs ANN → Recall@K > 0.95? Alert/rebuild index.
type ANNChecker struct {
sampleRate float64 = 0.01
}
func (c *ANNChecker) CheckShard(shardID uint64) AccuracyReport {
sampleVecs := sampleN(1000, shard.vectors)
for _, vec := range sampleVecs {
approx := shard.hnsw.Search(vec, k=10)
exact := bruteForceNN(vec, shard.vectors, k=10)
recall := intersection(approx, exact) / float64(k)
if recall < 0.95 { rebuildIndex() }
}
return Report{avgRecall: 0.97}
}
// Query impl
func (db *SherlockDB) Query(embedding []float32, k int, tenantID string, filters ...Filter) []Result {
shards := metadata.getShardsForTenant(tenantID, filters)
results := make(chan PartialResult, len(shards))
for _, shard := range shards {
go shard.primary.hnsw.SearchAsync(embedding, k, results)
}
return mergeTopK(results, k) // Priority queue merge
}
2.5 Failover
- Raft Built-in: Heartbeats (100ms), election timeout (300ms) → Auto-promote replica.
- Shard Failover: Metadata detects via heartbeats →
PROMOTE_REPLICA cmd.
- Zero-downtime: Read from any replica (lease reads); writes redirect.
// Node heartbeat to metadata
func heartbeat(nodeID NodeID) {
if !raft.IsLeader() { return }
metadata.Apply(HeartbeatCmd{NodeID: nodeID, Load: getLoad()})
}
2.6 Tenant Isolation
- Namespaces:
key = tenantID|shardID|vecID.
- Quotas: Metadata enforces per-tenant shard count/bytes.
- ACLs: Query routing checks
tenantID in shard.tenants.
- Isolation: Separate HNSW per tenant-shard; no cross-tenant leakage.
type TenantInfo struct {
MaxShards int64
QuotaBytes int64
AllowedUsers []string
}
func (fsm *MetadataFSM) authorize(tenantID string, userID string) bool {
return fsm.tenants[tenantID].AllowedUsers.Contains(userID)
}
3. Deployment & Ops
- Bootstrap:
raft bootstrap --nodes=1,2,3 → Seed metadata.
- Scale: Add node → Balancer auto-assigns replicas.
- Monitoring: Prometheus:
raft_leader, shard_load_skew, ann_recall.
- Perf:
| Metric | Target |
|---|
| Write TPS | 50k |
| QPS (latency<50ms) | 10k |
| Recall@10 | >0.97 |
| MTTR | <1s |
- Edge Cases: Network partitions (Raft fences), index rebuilds (blue-green), backups (Raft snapshots + S3).
4. Full Code Repo Structure
sherlockdb/
├── cmd/
│ ├── metadata-server.go
│ └── data-node.go
├── fsm/
│ ├── metadata_fsm.go
│ └── shard_fsm.go
├── storage/
│ ├── hnsw_index.go
│ └── rocksdb_store.go
├── balancer/
│ └── partition_balancer.go
├── proto/
│ └── commands.proto // gRPC defs
└── README.md // Helm charts
This design is deductive perfection: Consistent (Raft), Scalable (sharded), Accurate (checked ANN), Resilient (failover), Secure (isolated). Deploy with go run cmd/metadata-server.go --join=cluster. Query away, Watson—er, user.
Need code for a specific module? Observe.