Skip to main content

ShardChooser

Trait ShardChooser 

Source
pub trait ShardChooser: Send + Sync {
    // Required methods
    fn choose_for_model(&self, shard_key: &Value) -> String;
    fn choose_for_query(&self, hints: &QueryHints) -> Vec<String>;

    // Provided method
    fn all_shards(&self) -> Vec<String> { ... }
}
Expand description

Trait for determining which shard(s) to use for operations.

Implement this trait to define your sharding strategy. Common strategies:

  • Modulo hashing: shard_key % shard_count
  • Range-based: Partition by key ranges (e.g., user IDs 0-1M → shard_0)
  • Consistent hashing: Minimize rebalancing when adding/removing shards
  • Tenant-based: Map tenant IDs directly to shard names

§Example

struct TenantShardChooser {
    tenant_to_shard: HashMap<String, String>,
    default_shard: String,
}

impl ShardChooser for TenantShardChooser {
    fn choose_for_model(&self, shard_key: &Value) -> String {
        if let Value::Text(tenant_id) = shard_key {
            self.tenant_to_shard
                .get(tenant_id)
                .cloned()
                .unwrap_or_else(|| self.default_shard.clone())
        } else {
            self.default_shard.clone()
        }
    }

    fn choose_for_query(&self, hints: &QueryHints) -> Vec<String> {
        if let Some(Value::Text(tenant_id)) = &hints.shard_key_value {
            vec![self.choose_for_model(&Value::Text(tenant_id.clone()))]
        } else {
            // Query all shards
            self.tenant_to_shard.values().cloned().collect()
        }
    }
}

Required Methods§

Source

fn choose_for_model(&self, shard_key: &Value) -> String

Choose the shard for a model based on its shard key value.

This is used for INSERT, UPDATE, and DELETE operations where the shard key is known from the model instance.

§Arguments
  • shard_key - The value of the model’s shard key field
§Returns

The name of the shard to use (must match a shard registered in ShardedPool).

Source

fn choose_for_query(&self, hints: &QueryHints) -> Vec<String>

Choose which shards to query based on query hints.

For queries where the shard key isn’t directly available (e.g., range queries, joins, aggregations), this method returns the list of shards to query.

§Arguments
  • hints - Query routing hints (target shards, shard key value, etc.)
§Returns

List of shard names to query. For point queries with a known shard key, this should return a single shard. For scatter-gather, return all shards.

Provided Methods§

Source

fn all_shards(&self) -> Vec<String>

Get all registered shard names.

Default implementation returns an empty vec; override if your chooser tracks shard names internally.

Implementors§