Construct a distributed vector database over Raft with dynamic sharding: partition balancing, replica consistency, ANN accuracy checks, failover, and tenant isolation.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are going to design a distributed vector database with Raft for consensus, dynamic sharding, and the mentioned features.
Steps:
We'll use Raft for each shard (as a Raft group) to manage a log of operations and ensure consistency among replicas.
Sharding: We'll have multiple shards, each shard is a Raft group (with one leader and multiple followers). We need a way to dynamically balance shards (partition balancing) and move shards between nodes.
We'll have a metadata service (which itself can be a Raft group or use one of the shard groups) that tracks which shard is on which node and the current leader for each shard.
Tenant isolation: We'll have multi-tenancy. We can isolate by having separate shards for each tenant or by having a tenant ID in every vector and filtering by tenant. However, for strict isolation and performance, we might want to have dedicated shards for tenants with high load. We'll design so that shards can be assigned to tenants and we can have multiple tenants per shard but with filtering. Alternatively, we can have a design where each tenant's data is stored in a set of shards and metadata tracks tenant-to-shard mapping.
Let's break down:
Components:
Node: Each node runs multiple Raft groups (one per shard it hosts) and a metadata service (or part of it).
Metadata Service: Keeps track of:
Shard configuration (which shards exist, their current Raft group membership, and which node is leader for each)
Tenant to shard mapping (if we use per-tenant shards) or at least which shards contain which tenant's data (if shared).
Shard rebalancing: when we add/remove nodes, we need to move shards.
Shard: Each shard is a Raft group. The state machine for the Raft group is a vector index (like HNSW, IVF, etc.) but with operations being:
Add vector (with tenant ID and possibly other metadata)
Delete vector (by ID and tenant)
Search (by vector, with tenant filter, and k)
However, note that Raft is for linearizable operations, so every write (add/delete) must go through the Raft log and be applied in order to all replicas. Search is read-only and can be served by any replica (but we must be cautious about reading stale data if we allow reading from followers). We might want to serve search from the leader for strong consistency or from followers with a lease (or use a read index) to get linearizable reads.
But ANN search is approximate and we might tolerate some staleness? We need to decide.
Since we are building a vector database, we might have two consistency models:
For writes: linearizable (via Raft)
For reads: we can choose linearizable (from leader) or staleness (from any replica). We might also have a consistency level per request.
However, the requirement says "replica consistency", so we aim for strong consistency.
Dynamic Sharding:
We start with a fixed number of shards? Or we can split/merge shards based on load?
We'll design for dynamic sharding: we can add new shards and move vectors from one shard to another (resharding). This is complex because we have to move data between Raft groups and keep the system available.
Approach for resharding:
We have a global rebalancer (could be part of metadata service) that decides when a shard is too hot or a node is overloaded.
The rebalancer creates a new shard (Raft group) and then we need to move some vectors from an existing shard to the new one.
Steps:
a. Create new shard (Raft group) with initial membership (maybe one node, then add more).
b. For the source shard, we start a "move" operation that copies vectors to the new shard. But note: vectors might be updated during copy.
c. We can do a two-phase move:
Phase 1: copy all current vectors from source to destination. During this, we still accept writes on the source.
Phase 2: We stop writes on the source (by taking a leadership transfer or by a barrier) and then copy the changes since phase1, then switch the routing for the affected vectors to the new shard.
But note: vectors are not independent by key? We are partitioning by some key (like vector ID or tenant ID?). We need a partitioning scheme.
Partitioning Scheme:
We can use consistent hashing on vector ID or tenant ID? But if we want to move a subset of a tenant's vectors, we might need to split by vector ID range or by tenant.
Alternatively, we can have a metadata mapping from vector ID to shard. But that would be a huge mapping. So we use a partitioning function.
Let's assume we partition by vector ID (or by tenant ID then by vector ID). We can have a ring of shards and assign each vector to a shard by hashing its ID.
Then, moving a shard means changing the ring so that some keys move from one shard to another.
But we have multiple tenants. We want tenant isolation: we can assign a tenant to a set of shards (or a single shard if small) and then within that tenant, partition by vector ID.
So we have two levels:
Tenant -> Shards (a set of shards for that tenant)
Shard -> Partition of vector ID space.
Then, when we rebalance, we can move shards between nodes, and also split/merge shards within a tenant.
But note: Raft groups are heavy, so we might not want too many. So we might have one shard per tenant for small tenants, and for big tenants, multiple shards.
Alternatively, we can have a fixed set of shards (say 1024) and assign tenants to these shards by hashing tenant ID. Then each tenant's data is spread across multiple shards (if we have many tenants) but that might not be isolation.
Client → Metadata Service (get shard for key)
↓
Client → Shard Leader (RPC with tenant_id + vector)
↓
Shard Leader:
1. Validate tenant isolation
2. Apply Raft log entry (ADD_VECTOR)
3. Wait for majority commit
4. Update local ANN index
5. Respond to client
↓
Followers (async replication):
1. Apply log entry
2. Update local index
2.2 Search Flow (Parallel with Staleness Bound)
code
Client → Metadata (get all shards for tenant)
↓
Client → All shard leaders/followers (parallel)
↓
Each Shard:
1. Check tenant isolation
2. Perform ANN search (k * 2 for over-fetch)
3. Return top-k with scores
↓
Client/Coordinator:
1. Merge & re-rank results
2. Apply tenant-level filtering
3. Return final top-k
2.3 Shard Splitting (Dynamic Resharding)
code
Trigger: Shard size > threshold OR imbalance detected
Steps:
1. Metadata creates new shard S2 (Raft group)
2. Metadata updates partition map:
- Old range: [A, B] → S1
- New ranges: [A, M] → S1, [M, B] → S2
3. Migration phase:
- Copy vectors from S1 to S2 (using consistent snapshot)
- During copy: dual-write to both S1 and S2 for vectors in [M, B]
4. Cutover:
- Redirect new writes for [M, B] to S2
- Wait for replication catch-up
- Delete migrated vectors from S1
5. Metadata updates: Tenant now uses both shards
2.4 Shard Merging
Reverse of splitting, with anti-entropy reconciliation.
2.5 Rebalancing
code
Trigger: Node overload/underload detected
Algorithm:
1. Identify shards to move (score = load / capacity)
2. Select target node with available capacity
3. For each shard:
a. Add new node to Raft group (joint consensus)
b. Wait for replication
c. Remove old node from Raft group
d. Update metadata
4. Verify data consistency (checksum comparison)
2.6 Failover Handling
Leader Failure: Raft election within shard (≤ 500ms)
Node Failure: Shard automatically re-replicates to other nodes
Metadata Failure: Separate Raft cluster with fast election
Client Failover:
go
func (c *Client) executeWithFailover(ctx context.Context, op Operation) error {
shards := c.metadata.GetShardsForTenant(op.TenantID)
for attempt := 0; attempt < 3; attempt++ {
shard := c.router.SelectShard(shards, op.Key)
if err := c.executeOnShard(ctx, shard, op); err != nil {
if IsRaftError(err) {
c.metadata.RefreshShard(shard.ID) // Get new leader
continue
}
return err
}
return nil
}
return ErrMaxRetriesExceeded
}
3. Tenant Isolation Mechanisms
3.1 Storage Isolation
Dedicated Shards: Each tenant gets exclusive Raft groups
Shared Shards with Tenant Tagging:
code
Vector Record:
┌─────────────┬─────────────┬─────────────┐
│ Tenant ID │ Vector ID │ Vector Data │
├─────────────┼─────────────┼─────────────┤
│ 16-byte │ 16-byte │ variable │
└─────────────┴─────────────┴─────────────┘
All queries filtered by tenant_id = ?
Storage encryption per tenant
3.2 Resource Isolation
go
type ResourceLimiter struct {
mu sync.RWMutex
tenantStats map[string]TenantStats
quotas map[string]ResourceQuota
}
func (l *ResourceLimiter) Accept(tenantID string, op Operation) bool {
l.mu.Lock()
defer l.mu.Unlock()
stats := l.tenantStats[tenantID]
quota := l.quotas[tenantID]
switch op.Type {
case SEARCH:
return stats.SearchQPS < quota.MaxSearchQPS
case WRITE:
return stats.WriteQPS < quota.MaxWriteQPS &&
stats.DiskUsage < quota.MaxDiskBytes
}
}
3.3 Network Isolation
Separate gRPC streams per tenant
Rate limiting per tenant
Priority queues for premium tenants
4. ANN Accuracy Validation
4.1 Continuous Validation System
go
type AccuracyMonitor struct {
shard *Shard
sampleRate float64 // 0.01 = 1% of queries
groundTruth *BruteForceIndex
stats *AccuracyStats
}
func (m *AccuracyMonitor) Start() {
ticker := time.NewTicker(5 * time.Minute)
for range ticker.C {
queries := m.sampleQueries()
for _, q := range queries {
annResults := m.shard.Search(q, 100)
bfResults := m.groundTruth.Search(q, 100)
recall := calculateRecall(annResults, bfResults)
m.stats.RecordRecall(recall)
if recall < m.shard.config.MinRecall {
m.triggerReindex()
}
}
}
}
System: Metadata cluster health + rebalancing status
8. Failover & Disaster Recovery
8.1 Multi-Region Deployment
code
Region A (Primary) Region B (DR)
├── Metadata Raft (3) ├── Metadata Raft (3, read-only)
├── Shard Group 1 ├── Shard Group 1 (async replica)
├── Shard Group 2 ├── Shard Group 2 (async replica)
└── ... └── ...
8.2 Recovery Procedures
Node Failure: Automatic Raft failover (≤ 500ms)
Shard Corruption: Restore from latest snapshot + WAL
Region Failure: Promote DR region (manual or automated)
Metadata Corruption: Restore from Raft snapshot + peer recovery
9. Security Considerations
9.1 Multi-Tenancy Security
Authentication: Per-tenant API keys / mTLS
Authorization: RBAC per tenant (read/write/admin)
Encryption:
At rest: AES-256-GCM per tenant
In transit: TLS 1.3 with tenant-specific certs
Isolation:
Network policies (VPC/security groups)
Process isolation (containers/VMs)
Storage isolation (separate disks/volumes)
10. Deployment & Operations
10.1 Rolling Updates
code
Phase 1: Drain connections from node
Phase 2: Wait for Raft leadership transfer
Phase 3: Stop shard processes
Phase 4: Update binary
Phase 5: Start shard processes
Phase 6: Rejoin Raft groups
Phase 7: Verify health
Phase 8: Repeat for next node
Tenant Isolation: Storage, network, resource, and data isolation
ANN Accuracy: Continuous validation with auto-tuning
High Availability: Automatic failover with sub-second downtime
Scalability: Linear scale-out via sharding
Operational Excellence: Comprehensive monitoring, backups, rolling updates
The system balances the strict consistency requirements of Raft with the performance needs of ANN search through careful read/write path separation and intelligent caching strategies. The metadata service acts as the brain for dynamic sharding decisions while maintaining tenant isolation guarantees.
Option 1: Each tenant gets a fixed number of shards (or one shard) and we scale by adding more shards per tenant? But then shards are not shared between tenants -> perfect isolation but inefficient for small tenants.
Option 2: Shared shards with tenant ID in every record and we filter by tenant at query time. Then we need to know which shards might contain a tenant's data. We can have a mapping from tenant to the set of shards that have that tenant's data. But then if we move a vector from one shard to another, we update that mapping.
Given the requirement for tenant isolation, we might want to avoid having a single shard contain multiple tenants because then a noisy neighbor can affect. So let's go with Option 1: each tenant has its own set of shards. But then we have to manage many shards.
Alternatively, we can have a hybrid:
- For small tenants, we put them in shared shards but with a hard limit on the number of vectors per tenant in a shared shard, and we can move a tenant to its own shard when it grows.
However, the requirement says "tenant isolation", so we must ensure that a tenant's data is not on the same shard as another tenant? Or can we have shared shards but with strict access control?
The problem does not specify, so let's assume we want hard isolation: each tenant's data is stored in a set of shards that are not shared with other tenants. Then we can have:
code
Metadata:
- Tenant T has shards [S1, S2, ...]. Each shard is a Raft group and only contains vectors for tenant T.
Then we can have multiple tenants on the same node? Yes, but they are in different shards (Raft groups). So node can host shards from multiple tenants.
This way, we can move shards (which are for a single tenant) between nodes for load balancing.
But then if a tenant is small, we might have a shard with very few vectors. That's inefficient. So we can have a shard that contains multiple tenants if we group small tenants together? But then we lose isolation.
Given the requirement for isolation, we might have to accept some inefficiency for small tenants. Alternatively, we can have a shard that is shared by multiple tenants but we enforce at the application level that only one tenant uses it? That doesn't make sense.
Let me re-read: "tenant isolation". In multi-tenant systems, isolation can be at different levels:
- Data isolation: each tenant's data is stored separately ( physically or logically )
- Performance isolation: one tenant's load does not affect another.
If we share a shard (Raft group) among multiple tenants, then the Raft log and state machine will handle writes for multiple tenants. This might lead to contention and also a failure in one tenant's operation (like a big write) might affect the Raft group for all tenants in that shard.
So to have performance isolation, we want each tenant (or at least each tenant that is above a certain size) to have its own Raft group.
We can design:
code
- For a new tenant, assign it to a shared shard (with a capacity limit) until it grows beyond that limit, then split the tenant's data into its own set of shards.
But then we have to move data from the shared shard to the new shards. This is complex.
Alternatively, we can have a fixed set of shards (say 1000) and assign each tenant to one or more shards by a hash of tenant ID. Then each shard can have multiple tenants. But then we don't have isolation by shard.
Since the requirement is "tenant isolation", I think we need to ensure that a tenant's data is not co-located with another tenant's data on the same Raft group. So each Raft group (shard) is dedicated to one tenant.
Then we have:
code
Tenant T -> [Shard1, Shard2, ...] (each shard is a Raft group for T)
And we can have multiple tenants on the same node, but each in their own Raft group.
Now, how do we partition a tenant's data across multiple shards? We can partition by vector ID range or by hash of vector ID modulo the number of shards for that tenant.
Then, when we add a new shard for a tenant (because the tenant grew), we have to split the key range and move half of the vectors from an existing shard to the new one. This is similar to resharding in databases.
But note: we are using Raft for each shard, so moving data between Raft groups is non-trivial.
Alternatively, we can have a design where the number of shards per tenant is fixed at tenant creation and we pre-allocate. Then if a tenant needs more, we have to create a new set of shards and move the data. This is complex.
Given the complexity, maybe we start with one shard per tenant and then allow splitting when the shard becomes too big? But then we have to support moving data between Raft groups.
Let's assume we want to support dynamic sharding per tenant: we can add or remove shards for a tenant.
Steps for splitting a tenant's shard:
code
Let's say we have tenant T with one shard S1 (Raft group). We decide to split S1 into S1 and S2.
We create a new Raft group S2 (with its own log and state machine). We then need to move half of the vectors from S1 to S2.
How to do this without downtime?
We can:
1. Create S2 and start it (with no data).
2. We change the metadata for tenant T to include both S1 and S2, but we need to decide which vector goes to which. We can change the partition function: previously all vectors for T went to S1. Now we want to split by hash(vector_id) mod 2? But that would move half of the vectors.
3. But we have existing vectors in S1. We need to copy them to S2.
4. We can do:
a. Update the metadata to say that tenant T uses both S1 and S2, and the partition function is now mod 2. But we don't change the routing for new writes? We have to change the routing for all writes (and reads) to go to the correct shard. But we have existing data in S1 that now should be in S2.
b. We can do a background process that reads from S1 and writes to S2 for the vectors that belong to S2. But during this, new writes might be going to S1 for vectors that should be in S2.
This is very complex.
Alternatively, we can have a two-phase approach:
code
Phase 1: Duplicate writes. We change the application to write to both S1 and S2 for a while? But then we have to delete from S1 later.
Phase 2: Once we have copied all existing data, we switch reads to read from both and then delete from S1.
But note: Raft groups are independent, so we have to ensure that the copy is consistent.
Given the complexity, maybe we avoid splitting a shard and instead have a design where we can have many shards from the beginning and assign vectors to shards by a consistent hashing ring that we can change gradually.
Let's consider:
code
We have a ring of shards (each shard is a Raft group). For each tenant, we assign a set of shards (maybe by hashing tenant ID and taking a few consecutive shards). Then for a vector, we assign it to one of the tenant's shards by hashing the vector ID and picking the shard.
Then, to rebalance, we can move shards between nodes (which is easier because the shard is independent) and we can change the ring (add/remove shards) and then migrate the data for the affected keys.
But if we change the ring, then for a given tenant, the set of shards might change? We can keep the tenant's set of shards fixed and only move the physical location of the shard (i.e., which node hosts the Raft group). Then we don't have to move data between shards, just move the entire Raft group to another node.
That is easier: we can use Raft's own membership change to move the shard (Raft group) to a new node. But note: we want to balance shards across nodes, so we might move a shard from a hot node to a cold node.
So let's design:
- We have a fixed set of shards (say 1024) that are created at the beginning. Each shard is a Raft group and is assigned to one or more tenants? But we want isolation, so each shard is assigned to only one tenant? Then we need at least as many shards as tenants? That could be too many.
Alternatively, we can have a shard be shared by multiple tenants? But then we lose isolation.
Given the requirement for isolation, let's stick to one tenant per shard. Then we must have at least as many shards as tenants. But if we have 1 million tenants, that's too many Raft groups.
So we must allow multiple tenants per shard? But then how do we isolate? We can have a tenant ID in every operation and the shard's state machine will store vectors for multiple tenants and filter by tenant. Then we can have:
Shard S contains vectors for tenants T1, T2, ...
And we have a mapping: tenant T uses shards [S1, S2, ...] (a set of shards that contain T's data).
Then, if we want to isolate a tenant, we can move its data to a new shard (by copying and then deleting the old). But that is complex.
Given the time, let's simplify:
We will design for multi-tenancy with tenant isolation at the shard level: each shard is dedicated to one tenant.
Then, we have:
Metadata:
- For each tenant T, we have a list of shard IDs that belong to T.
- For each shard ID, we have the Raft group (nodes that are in the group) and the current leader.
Partitioning within a tenant's shards: we assign each vector to one of the tenant's shards by hash(vector_id) mod (number of shards for T).
Then, when we want to add a new shard for a tenant (because the tenant is big and we want to split), we:
1. Create a new shard (Raft group) and add it to the tenant's list of shards.
2. Change the partition function to use the new number of shards (so new vectors will be assigned to the new shard as well).
3. Then we need to move existing vectors that now belong to the new shard. We can do this by:
a. For each old shard, we iterate over its vectors and for each vector, if it now belongs to the new shard (by the new partition function), we copy it to the new shard and then delete it from the old shard.
4. But during this, new writes might be happening. We have to make sure that we don't lose updates.
This is very complex and we might need to lock the tenant during this operation? But that would be downtime.
Alternatively, we can avoid splitting a tenant's shard and instead have a fixed number of shards per tenant at creation time? But then we have to guess the size.
Given the complexity, maybe we design for:
code
- Each tenant has exactly one shard (Raft group). Then we don't have to split. But then for large tenants, the shard might become too big for one node? We can have the Raft group span multiple nodes (so the shard is replicated on multiple nodes) but the data is still on one node? No, Raft requires that the log is the same on all replicas, so all replicas have the full data. So if we have a large tenant, we might need to split.
So we must support splitting.
Given the time constraints, let's outline a simpler design:
code
We will have:
- A metadata service (implemented as a Raft group itself) that stores:
* Tenants: for each tenant, the list of shards (shard IDs) that belong to it.
* Shards: for each shard, the Raft group configuration (list of nodes) and the current leader.
- Partitioning: we use consistent hashing on the vector ID (or tenant ID + vector ID) to assign a vector to a shard. But note: we want tenant isolation, so we want all vectors for a tenant to be in the tenant's shards. So we first map tenant to a set of shards, then within that set, we map vector to a specific shard by hash(vector_id) mod (number of shards for tenant).
- When we create a tenant, we assign it to a set of shards (maybe one initially). We can also assign a shard to multiple tenants? No, because we want isolation. So each shard is assigned to exactly one tenant.
- Then, when a tenant grows, we split one of its shards into two. We do:
Let S be the shard to split.
Create a new shard S2 (Raft group) and assign it to the tenant.
Now the tenant has two shards: S and S2.
We change the partition function for the tenant: previously all vectors went to S. Now we use mod 2.
Then we need to move half of the vectors from S to S2.
How?
We can have a background process that:
For each vector in S:
Compute which shard it belongs to now (S or S2).
If it belongs to S2, then:
- Read the vector from S (via a Raft read? But we want to copy the current state, so we need to get the latest value. We can do a read from the leader of S to get the vector.
- Write the vector to S2 (through the Raft log of S2).
But during this, new writes to S might happen for vectors that should be in S2. We have two options:
Option 1: Pause writes to S (by making S unavailable) until the migration is done? Not acceptable.
Option 2: We do a two-phase migration:
Phase 1: Copy existing data from S to S2. We take a consistent snapshot? We can use Raft's snapshot mechanism? But we want to move only half.
Alternatively, we can:
a. Change the partition function for new writes so that new vectors for the tenant go to either S or S2 based on the new rule. But we have to change the application to know about the new partition? Or the client library must know.
b. Then, we migrate the old data. But during migration, a vector might be updated in S and then we copy the old version to S2? We need to capture the latest.
This is very complex.
Given the time, we might have to assume that we don't support splitting a shard. Instead, we over-provision the number of shards per tenant at creation. Or we have a fixed global shard set and assign tenants to shards by hash, and then we can move a tenant's data from one shard to another by copying and then deleting? But then we have to update the mapping.
Alternatively, we can have a design where the shard is not tied to a tenant. Instead, we have:
- A global set of shards (Raft groups) that are shared by multiple tenants, but each shard has a list of tenants that are allowed to use it.
Then, when a tenant grows, we can move it to its own set of shards by:
1. Create new shards for the tenant.
2. Copy the tenant's data from the old shards to the new ones.
3. Update the metadata so that the tenant uses only the new shards.
4. Delete the tenant's data from the old shards.
But then we have to handle concurrent writes during the copy.
This is still complex.
Given the complexity and the fact that we are designing at a high level, let's assume:
code
- We have a fixed number of shards (say 1024) that are created at system startup and are never split or merged. Each shard is a Raft group.
- We assign each tenant to a set of shards (by hashing the tenant ID). For example, tenant T is assigned to shards [h(T), h(T)+1, ..., h(T)+n-1] mod 1024. Then, within the tenant's shards, we partition the vectors by hash(vector_id) mod (number of shards for T).
- Then, when we add a new node, we can move entire shards (Raft groups) from one node to another to balance load. This is easier because we just change the Raft group membership.
- For tenant isolation: since each tenant's data is on a fixed set of shards, and these shards might be shared with other tenants? Wait, if we assign by hash, then multiple tenants will be on the same shard. So we don't have isolation.
So to have isolation, we must have each shard dedicated to one tenant. Then we need at least as many shards as tenants. But we can have a shard that is shared by multiple tenants if we use a different assignment: we assign each tenant to a single shard (by hash) and then if a tenant becomes too big, we assign it to multiple shards? But then we have to split the tenant's data across multiple shards, and each shard is still shared? No, if we assign a tenant to multiple shards, then each of those shards will have only that tenant? Or we can have a shard that has multiple tenants, but then we lose isolation.
Let me clarify: we want each tenant's data to be isolated from other tenants. That means that no shard should contain data from two different tenants. So each shard is dedicated to one tenant.
Then, for a tenant with a lot of data, we need multiple shards (all dedicated to that tenant). So we have:
Tenant T -> [S1, S2, ...] (each Si is a Raft group and only contains vectors for T)
And we can have a tenant that uses only one shard.
Then, when we create a new tenant, we assign it to one or more shards that are currently unused (or we create new shards). We can have a pool of unused shards.
Then, when we add a new node, we can move shards (which are for a single tenant) to the new node.
This seems manageable.
So let's go with:
code
- We have a fixed set of shards (Raft groups) that are either assigned to a tenant or unassigned.
- Metadata stores:
* Shard -> Tenant (if assigned) and the Raft group configuration.
* Tenant -> List of shards.
- Partitioning within a tenant: if a tenant has multiple shards, we partition by hash(vector_id) mod (number of shards for the tenant).
- Then, when we want to add more shards for a tenant (because it grew), we:
a. Find unassigned shards (or create new ones? but we said fixed set, so we have a pool of unassigned shards).
b. Assign the new shard to the tenant.
c. Update the partition function for the tenant to include the new shard.
d. Then we need to move existing vectors that now belong to the new shard.
How to move the vectors?
We can have a background process that:
For each existing shard of the tenant (old ones):
For each vector in that shard:
Compute the new shard (using the new number of shards).
If the new shard is different, then:
- Read the vector from the old shard (via Raft read from leader? But we want to copy the current state, so we need to get the latest value. We can do a read from the leader of the old shard, but note that during the copy, the vector might be updated. We need to capture the update.
This is complex because we have to copy and then delete, and during the copy, there might be updates.
We can do:
Step 1: Change the partition function for the tenant to the new number of shards. But we don't change the routing for writes yet? We have to change the client library to use the new partition function. Then new writes will go to the correct shard (which might be the new one). But old data is still in the old shards.
Step 2: We copy the existing data from old shards to the new shard(s). But during the copy, a vector might be updated in the old shard and then we copy the old version? We need to get the latest version.
We can do:
For each vector in the old shard, we do:
Read the vector from the old shard (with the latest index, so we get the latest value).
Then write it to the new shard (if it belongs there). But note: the write to the new shard will be a new entry in the Raft log of the new shard.
Then, after we have copied all, we delete the vector from the old shard? But what if the vector was updated after we read it? We might have copied an old version and then deleted the new version?
This is a classic problem of data migration in a distributed system.
Given the complexity, we might have to accept that we will have a period of inconsistency? Or we can use a two-phase commit? But that's heavy.
Alternatively, we can do:
We stop accepting writes for the tenant during the migration? But that's downtime.
Given the requirement for high availability, we cannot have downtime.
So we need a online migration.
One approach:
We change the partition function and start routing new writes to the new shards (if the vector belongs there) and also to the old shards? But then we have duplicates? We don't want duplicates.
Instead, we can:
For the migration period, we write to both the old and new shard? Then we read from both and merge? Then delete from the old.
This is complex.
Given the time, we might have to leave the resharding as a future work and assume that we have a fixed number of shards per tenant at creation and we don't change it.
Given the above, let's simplify the design:
code
We will have:
- A fixed set of shards (say 1024) that are Raft groups. Each shard is assigned to at most one tenant.
- When a tenant is created, we assign it to one or more shards (from the pool of unassigned shards). The number of shards per tenant is fixed at creation and cannot be changed.
- Then, we can move shards between nodes for load balancing, but we cannot change the number of shards per tenant.
This avoids the complex resharding.
Then, we have:
Metadata:
- For each shard, the tenant it belongs to (or null) and the Raft group (list of nodes) and the current leader.
Partitioning for a tenant T with shards [S1, S2, ..., Sn]:
For a vector with ID v, we compute: shard = S_{ hash(v) mod n }
Then, when a client wants to write a vector for tenant T, it looks up the list of shards for T from metadata, computes which shard by hash(v) mod n, and then sends the write to the leader of that shard.
Similarly for read (search).
Then, we can balance by moving shards (Raft groups) from one node to another. This is done by changing the Raft group membership and then starting the shard on the new node.
Failover: if a node fails, the Raft groups on that node will failover to the remaining replicas. The metadata service needs to be updated (by the Raft group itself? or by monitoring) to reflect the new leader.
Tenant isolation: since each shard is for one tenant, and we don't share shards, we have isolation.
But what if a tenant is very small and we assign it one shard? Then that shard might be underutilized. We can assign multiple small tenants to the same shard? But then we lose isolation.
So we have a trade-off.
Given the requirement for isolation, we choose to not share shards between tenants. Then we must have at least as many shards as tenants. But we can have a fixed pool of shards (1024) and if we have more than 1024 tenants, then we cannot assign a shard to each tenant? Then we have to share.
So we can have:
- If the number of tenants is less than the number of shards, then each tenant gets one or more dedicated shards.
- If the number of tenants is more than the number of shards, then we have to share shards among multiple tenants? But then we lose isolation.
Alternatively, we can have a two-level design:
- We have a set of "shard groups" (each is a Raft group) that are shared by multiple tenants, but within a shard group, we partition by tenant ID? Then we can have:
Shard group S has tenants [T1, T2, ...]. For each tenant, we partition the vector space within the shard group? But then the shard group is shared and we don't have isolation at the Raft group level.
This is getting too complex.
Given the time, I think we have to make a decision:
code
We design for:
- Each shard (Raft group) is dedicated to one tenant.
- We have a fixed pool of shards (say 1024). When a tenant is created, we assign it one or more shards from the pool (if available). If no shard is available, we cannot create the tenant? Or we wait.
- Then, we can have at most 1024 tenants (if each gets one shard) or more if some tenants get multiple shards? Actually, if we assign multiple shards to a tenant, then we have fewer tenants.
So the maximum number of tenants is 1024 (if each gets one) and minimum is 1 (if one tenant gets all).
But we can have more than 1024 tenants if we allow sharing? We said no.
So we are limited to 1024 tenants. That might be acceptable for a demo but not for production.
Alternatively, we can have a dynamic number of shards? We can create and destroy shards? But then we have to manage the pool.
Let's change:
We don't have a fixed pool. We create shards on demand. Each tenant gets at least one shard. We can create as many shards as we need, but each shard is for one tenant.
Then, when we add a new node, we can move shards (which are for one tenant) to the new node.
But then we have to assign a unique ID to each shard and track them in metadata.
This is similar to the first design but without a fixed pool.
So:
- When a tenant is created, we create one shard (Raft group) for it. The shard is initially on one node (or we can have multiple replicas on different nodes).
- Then, if the tenant grows, we can create additional shards for the tenant and split the data.
But we said splitting is complex.
Given the complexity of splitting, we might avoid it and instead:
- When we create a tenant, we create one shard for it.
- If the shard becomes too big (in terms of number of vectors or storage), we create a new shard for the same tenant and then we have to migrate half of the vectors.
We can do the migration without downtime by:
1. Create a new shard S2 for tenant T.
2. Change the partition function for T to use two shards (S1 and S2) by hash(vector_id) mod 2.
3. Then, we need to move the vectors that now belong to S2 from S1 to S2.
4. We can do:
a. We change the client library to use the new partition function. Then new writes for vectors that belong to S2 will go to S2. But existing vectors in S1 that belong to S2 are still in S1.
b. We run a background job that:
For each vector in S1:
Compute which shard it belongs to (S1 or S2) using the new partition function.
If it belongs to S2, then:
- Read the vector from S1 (with the latest index) and write it to S2.
- But note: during this, the vector might be updated in S1. We are reading an old version? We need to read the latest.
c. We can use a "copy-on-write" or we can pause writes? Not acceptable.
5. Alternatively, we can use a two-phase approach:
Phase 1: For each vector in S1, we write it to S2 (if it belongs there) and mark it as copied in S1? But then we have to update S1 to mark, and that's a write.
Phase 2: Then we delete the vector from S1.
But during phase 1, if the vector is updated in S1, we might have:
- We read the old version and write to S2.
- Then an update happens in S1, so S1 has the new version, but S2 has the old.
- Then we delete from S1? We lose the update.
So we need to capture the latest version at the moment we delete.
6. We can do:
For each vector in S1:
Step A: Read the vector from S1 (with the latest index, say index i).
Step B: Write the vector to S2 (with the same vector ID). This will be a new entry in S2's log.
Step C: Then, we delete the vector from S1? But what if after step A and before step C, the vector is updated in S1? Then we have:
- The update in S1 is after index i, so when we read at index i, we don't see it.
- Then we write the old version to S2 and then delete from S1, so we lose the update.
So we need to repeat until we get the latest.
7. We can do:
We copy the vector from S1 to S2, but we don't delete from S1 immediately. Then, for new writes, we write to both S1 and S2? That would be duplicate.
8. Alternatively, we can use a "shadow" period:
- Change the partition function so that new writes go to both S1 and S2 for vectors that belong to S2? Then we have two copies.
- Then, we copy the existing data from S1 to S2.
- Then, we switch reads to read from S2 for vectors that belong to S2.
- Then, we delete from S1.
But during the shadow period, we have two copies and we have to update both on write. Then we have to merge updates? This is like a dual-write.
Given the complexity, we might decide that we don't support splitting a shard. Instead, we assign a fixed number of shards per tenant at creation and we don't change it.
Then, we have:
- Each tenant is created with a fixed number of shards (say 1 or more). We don't change it.
- We can move shards between nodes for load balancing.
- We can add more shards for a tenant only by creating a new tenant? Not acceptable.
So we must support splitting.
After careful thought, I think we can do:
code
We use a version number for the partition function.
Let's say for tenant T, the current partition function is:
shard_id = (hash(vector_id) mod N) + offset
where N is the current number of shards for T, and offset is the starting index in the global shard list.
When we split, we double N (or increase by one). We change the partition function and start routing new writes to the new shard for vectors that now map to it.
For existing vectors, we do:
We run a background job that for each vector in the old shard, if it now maps to the new shard, we copy it to the new shard.
But during the copy, the vector might be updated. We need to get the latest version.
We can do:
We copy the vector from the old shard (using a read with the latest index) and write to the new shard.
Then, we mark the vector in the old shard as "migrated" (with a tombstone or a flag). But then if the vector is updated after we copy, we lose the update.
So we need to repeat the copy until we are sure we have the latest.
Alternatively, we can change the write path:
During the migration, we write to both the old and new shard for vectors that belong to the new shard? Then we have two copies and we need to resolve conflicts? We can use a timestamp or version.
Then, after the migration, we read from the new shard and then delete from the old.
This is getting too complex for the scope.
Given the time, I will design a system that:
code
- Does not support dynamic resharding (splitting/merging) for a tenant. The number of shards per tenant is fixed at creation.
- We can move shards (which are for one tenant) between nodes for load balancing.
- We can add new shards for a tenant only by creating a new tenant and moving the data? Not.
So we have to accept that if a tenant grows beyond the capacity of its shards, we cannot scale it.
This is a limitation.
Alternatively, we can design the shard to be horizontally scalable within the Raft group? But Raft requires that the entire log is on every replica, so we cannot scale a single shard beyond one node's storage.
So we must have multiple shards for a large tenant.
Given the above, I think we have to implement resharding. But for the sake of this design, let's outline the steps for resharding without going into the gory details.
We'll assume we have a background migration process that:
code
- For a tenant T, we decide to split one of its shards S into two: S and S2.
Steps:
1. Create a new Raft group S2 and assign it to tenant T.
2. Update metadata: tenant T now has shards [S, S2] and the partition function is changed to mod 2.
3. Change the client library to use the new partition function (so new writes for vectors that belong to S2 go to S2).
4. Start a background job that:
a. Iterates over all vectors in S (using a scan operation? But Raft log doesn't support scan, we have to scan the state machine. We can have an iterator in the state machine).
b. For each vector, compute the new shard (S or S2). If it belongs to S2, then:
i. Read the vector from S (with the latest index) and write it to S2.
ii. Mark the vector in S as "migrated" (but we don't delete yet).
c. We repeat until we have copied all vectors? But what about updates during the copy?
5. We can do multiple passes. In each pass, we copy the vectors that are not yet migrated or that have been updated since last copy.
6. Once we are confident that S2 has all the latest vectors, we switch reads for vectors that belong to S2 to read from S2 (by updating the client library? or by metadata?).
7. Then, we delete the vectors that belong to S2 from S.
But note: during the migration, we have to handle writes:
- Writes for vectors that belong to S (by new partition) go to S.
- Writes for vectors that belong to S2 go to S2 (if we have updated the client library) or to S? We updated the client library at step 3, so new writes for vectors that belong to S2 go to S2.
But what about vectors that are being migrated? They are in S and we are copying to S2. If they are updated in S after we copied, we have to copy again.
We can have a "migration state" per vector:
- In S, we store for each vector a flag: migrated (boolean) and a migration version.
- When we copy a vector, we set the migration version in S2 and in S we set the flag and the version.
- When we write to a vector in S, if the flag is set and the version in S2 is old, we also write to S2? That would be dual write.
This is very complex.
Given the time, I will leave resharding as an advanced feature and assume we have a fixed number of shards per tenant.
Now, let's design the components:
code
1. Node:
- Runs multiple Raft groups (one for each shard it hosts).
- Runs a Raft network (gossip? or we have a separate membership service?).
2. Metadata Service:
- We can have a separate Raft group for metadata, or we can use one of the shard groups? But metadata is critical and small.
Let's have a separate Raft group for metadata (with 3 nodes for example) that stores:
Shard:
- shard_id (unique)
- tenant_id (if assigned, else null)
- Raft group configuration: list of nodes (node addresses) that are in the group for this shard.
- current leader (can be derived from Raft, but we cache)
Tenant:
- tenant_id
- list of shard_ids assigned to this tenant.
Then, when we want to write a vector for tenant T with vector ID v:
- Read the metadata (or cache) to get the list of shards for T.
- Compute the shard by hash(v) mod len(shards).
- Look up the shard configuration from metadata to get the Raft group nodes and the current leader (or we can contact any node in the group and it will forward to leader).
Then, we send the write to the leader of that shard's Raft group.
3. Shard (Raft group):
- State machine: a vector index (like HNSW) but with tenant isolation? Since each shard is for one tenant, we don't need tenant ID in the state machine. But wait, what if we later decide to share shards? Let's keep tenant ID in the vector? Actually, if each shard is for one tenant, then we don't need tenant ID in the vector. But then if we want to move a vector from one shard to another (for resharding) we have to know the tenant? We know the tenant from the shard.
So in the shard's state machine, we store vectors without tenant ID because the shard is dedicated.
But then if we want to have a shared shard in the future, we would need tenant ID.
Let's store tenant ID in the vector anyway, so that we can support shared shards if we change our mind.
So the state machine stores:
Map<vector_id, (tenant_id, vector_data, metadata)>
But since the shard is for one tenant, the tenant_id should be the same for all vectors? Not necessarily if we allow sharing.
Given the requirement for isolation, we are not sharing, so we can skip tenant ID in the shard. But then if we want to move a vector to a different shard (for resharding) we have to know the tenant to update the metadata? Actually, when we move a vector from shard S1 to S2, we are moving it within the same tenant, so we don't need to change the tenant-shard mapping? We are just moving within the tenant's set of shards.
So in the shard, we don't need tenant ID because the shard is for one tenant. But then when we copy a vector from S1 to S2, we don't change the tenant.
So we can store without tenant ID.
However, for ANN search, we might want to filter by tenant? But if the shard is for one tenant, then all vectors are for that tenant.
So we can skip.
4. Operations:
- AddVector(tenant_id, vector_id, vector, metadata):
Client -> Metadata: get shards for tenant_id.
Compute shard.
Send to leader of shard.
The shard's state machine applies the log entry: if vector_id exists, replace; else insert.
- DeleteVector(tenant_id, vector_id):
Similar.
- Search(tenant_id, query_vector, k):
Client -> Metadata: get shards for tenant_id.
For each shard (or we can do parallel? but then we have to merge results) we send the search to the leader (or a follower) and then merge the top-k.
But note: if the tenant has multiple shards, we have to search all shards and then combine.
5. Failover:
- Each Raft group will handle failover by itself. If the leader fails, a new leader is elected.
- The metadata service needs to know the current leader for each shard. We can have the Raft group update the metadata when a new leader is elected? Or the metadata can cache and update on failure.
We can have:
- When a client wants to contact a shard, it first contacts the metadata to get the leader. But if the leader is down, the metadata might have stale info.
- We can have the client try the leader and if it fails, it asks metadata again? Or we can have the Raft group members forward to the current leader.
Standard Raft: if you contact a follower, it will forward to the leader.
So we can have the client contact any node in the shard's Raft group (from the configuration) and if that node is not the leader, it will forward.
Then, we don't need to cache the leader in metadata. We can just store the list of nodes for the shard.
6. Replica consistency:
- Since we use Raft, all replicas in a shard will have the same state (linearizable).
7. ANN accuracy checks:
- We need to check the accuracy of the ANN index. We can do this by:
Periodically, on each shard, run a ground truth search (brute force) on a sample of queries and compare with the ANN search results.
We can have a background process on each node that does this for the shards it hosts and reports to a monitoring system.
8. Tenant isolation:
- Each shard is for one tenant (as per our design) so data is isolated.
- Also, we can have quotas per tenant (number of vectors, storage) enforced by the shard? The shard can check the tenant's quota? But the shard only has one tenant, so we can have a quota for the shard.
- We can also have resource isolation at the node level: we can limit the resources (CPU, memory) used by a shard (tenant) by using cgroups or containers.
Given the above, let's write the design in a structured way.
However, note: the above design does not support dynamic resharding (changing the number of shards per tenant). We have to accept that.
If we want to support dynamic resharding, we have to implement the complex migration.
Given the time, I'll present the design without dynamic resharding (fixed number of shards per tenant).
But the requirement says "dynamic sharding", so we must support adding/removing shards.
Let's try to support adding a new shard for a tenant without splitting:
code
We can have a tenant with one shard. When we want to add a second shard, we create a new shard and then we have to move half of the vectors.
We can do:
Step 1: Create new shard S2 for tenant T.
Step 2: Update metadata: tenant T now has shards [S1, S2] and the partition function is mod 2.
Step 3: Change the client library to use the new partition function (so new vectors are assigned to S1 or S2).
Step 4: We copy the existing vectors from S1 to S2 that belong to S2.
But how to copy without losing updates?
We can do:
We copy each vector from S1 to S2, but we also start writing to both S1 and S2 for vectors that belong to S2? Then we have two copies and we need to delete from S1 later.
This is similar to the previous.
Alternatively, we can do:
We stop writes to the tenant? Not acceptable.
Given the complexity, I think we have to implement a two-phase copy with versioning.
We assign a version to each vector (using a timestamp or a logical clock). When we copy, we copy the vector with its version. Then, when we write to the old shard, if the vector's version is older than the one in the new shard, we ignore? But then we lose updates.
Instead, we can:
During the migration, we write to both shards for vectors that belong to the new shard. Then we have two copies and we need to resolve conflicts by version.
Then, after the migration, we switch reads to the new shard and then delete from the old.
Steps:
Let T have shards [S1] initially. We want to add S2.
1. Create S2.
2. Update metadata: T has [S1, S2] and partition function mod 2.
3. Change the client to write to both S1 and S2 for vectors that belong to S2? But how does the client know? The client uses the partition function to decide the primary shard. We can change the client to write to both the primary and the new shard for vectors that belong to the new shard? But then we have to know which vectors are being migrated.
Alternatively, we can have a "migration mode" for the tenant:
- We set a flag in metadata that tenant T is being migrated to have 2 shards.
- The client, when writing a vector for T, computes the primary shard (by mod 1? because we are migrating) and then also writes to the new shard if the vector belongs to the new shard? But then we have to compute the new shard mapping.
This is messy.
Given the time, I think we have to accept that dynamic resharding is very complex and we might not be able to design it fully in this exercise.
So, I will design:
code
- We have a fixed number of shards per tenant at creation.
- We can move shards between nodes.
- We do not support changing the number of shards per tenant.
But the requirement says "dynamic sharding", so we must support adding/removing shards.
Let's re-interpret "dynamic sharding" as the ability to rebalance shards across nodes (moving shards) and not necessarily changing the number of shards per tenant.
In many systems, "dynamic sharding" means that we can add/remove shards and rebalance.
But if we cannot change the number of shards per tenant, then we cannot add more shards for a tenant that is growing.
So we have to support changing the number of shards per tenant.
Given the above, I will outline the steps for resharding without going into the implementation details of the background migration.
We'll assume we have a background job that:
code
For a tenant T, we decide to increase the number of shards from N to M.
Steps:
1. Create M-N new shards (Raft groups) for the tenant T.
2. Update the metadata: tenant T now has M shards (the old N shards plus the new M-N shards) and the partition function is mod M.
3. Change the client library (or the routing layer) to use the new partition function.
4. Start a background migration that:
For each old shard S (from the N old shards):
For each vector in S:
Compute the new shard (using mod M).
If the new shard is different from S, then:
- Copy the vector to the new shard.
- Mark the vector in S as "migrated" (but don't delete yet).
But we have to handle updates during migration.
5. We can do:
We copy the vector from S to the new shard, but we also set a "migration" flag in S.
Then, for writes to a vector that has the migration flag set in S, we write to both S and the new shard? Then we have two copies and we need to delete from S later.
Then, after we have copied all vectors (and we are sure that the new shard has the latest version) we can delete from S.
6. To know which version is latest, we can use a timestamp or a version number that increments on each write.
7. We can have the state machine in each shard store a version for each vector.
8. During migration, when we copy, we copy the version.
9. Then, when we write to a vector in S, if the vector has a migration flag and the version in the new shard is older, we update the new shard? But then we have to update both.
This is very complex.
Given the time, I think we have to leave the resharding algorithm as a placeholder.
So, in summary:
code
We design a distributed vector database with:
- Metadata service (Raft group) that stores:
* Shard: shard_id, tenant_id (or null if unassigned), list of nodes (Raft group members)
* Tenant: tenant_id, list of shard_ids
- Each shard is a Raft group that stores vectors for a single tenant (but we store tenant_id in the vector for future flexibility).
- Partitioning: for a tenant with shards [S1, S2, ..., Sn], we assign vector with ID v to shard S_{hash(v) mod n}.
- Operations:
Write:
Client gets tenant's shards from metadata, computes target shard, and sends write to the leader of that shard's Raft group.
Search:
Client gets tenant's shards, sends search query to each shard (in parallel) and merges the results (by score) to get top-k.
- Failover: handled by Raft.
- Replica consistency: Raft ensures linearizable writes.
- ANN accuracy checks: background jobs on each node that periodically run brute-force on a sample and compare.
- Tenant isolation: each shard is for one tenant, so data is isolated. Also, we can enforce resource limits per shard.
- Dynamic sharding: we can add new shards for a tenant (by creating new Raft groups and updating the tenant's shard list) and then migrate data. The migration is done by a background job that copies vectors from old shards to new ones. We assume we have a way to handle concurrent updates (by versioning) and eventually delete the old copies.
- Balancing: we can move shards (Raft groups) between nodes by changing the Raft group membership (using Raft's joint consensus) and then starting the shard on the new node.
This is a high-level design.
Now, we need to write the answer in a structured way.
Let's break it down:
code
System Components:
1. Metadata Service
2. Shard (Raft Group)
3. Node
4. Client
Workflows:
- Write
- Search
- Shard Migration (for a tenant)
- Shard Rebalancing (moving a shard to another node)
- Failover
We'll write the design in text.
Note: We are not implementing, so we can be high-level.
Let's write.
I'll design a comprehensive distributed vector database system that meets all your requirements. This is a sophisticated system combining Raft consensus with dynamic sharding for vector workloads.