ソース情報
- リポジトリ
- tools-only/X-Skills
- ソースの最終更新活動
- 2026年2月9日 04:32
- 検出された SKILL.md の言語
- 英語
- スター
- 7
- フォーク
- 1
インストール方法
デフォルトでは、最初にソースを確認する Prompt が選択されています。直接コマンドに切り替えるか、ローカルコピーをダウンロードすることもできます。
ソースファイルを確認
インストールを決める前に、SKILL.md と SkillsMP に表示されている付属ファイルをお読みください。
メニュー
デフォルトでは、最初にソースを確認する Prompt が選択されています。直接コマンドに切り替えるか、ローカルコピーをダウンロードすることもできます。
インストールを決める前に、SKILL.md と SkillsMP に表示されている付属ファイルをお読みください。
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
直接コマンドでは確認用 Prompt が省略されます。実行前にソースを確認してください。
npx skills add https://github.com/tools-only/X-Skills --skill shardingコマンドは1行のまま表示されます。コピー前に横へスクロールして全体を確認してください。
ローカルで確認しますか?SkillsMP が現在取得できるファイルをダウンロードできます。
Index of Build Systems Skills
Coordination patterns for distributed dataflow systems including barriers, epochs, and distributed snapshots
Windowing, sessionization, time-series aggregation, and late data handling for streaming systems
SOC 職業分類に基づく
SKILL.md を表示中
| name | sharding |
| description | Implement horizontal database sharding for massive scale applications |
| shortcut | shar |
Design and implement horizontal database sharding strategies to distribute data across multiple database instances, enabling applications to scale beyond single-server limitations with consistent hashing, automatic rebalancing, and cross-shard query coordination.
Use /sharding when you need to:
DON'T use this when:
This command implements consistent hashing with virtual nodes because:
Alternative considered: Range-based sharding
Alternative considered: Directory-based sharding
Before running this command:
Select sharding approach based on data access patterns and scale requirements.
Choose immutable, high-cardinality key that distributes data evenly (user_id, tenant_id).
Build connection pooling and routing logic to direct queries to correct shard.
Perform zero-downtime migration from monolithic to sharded architecture.
Track shard load distribution and rebalance data as needed.
The command generates:
sharding/shard_router.py - Consistent hashing router implementationsharding/shard_manager.js - Shard connection pool managermigration/shard_migration.sql - Data migration scripts per shardmonitoring/shard_health.sql - Per-shard metrics and health checksdocs/sharding_architecture.md - Architecture documentation and runbooks# sharding/consistent_hash_router.py
import hashlib
import bisect
from typing import List, Dict, Optional, Any
from dataclasses import dataclass
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class ShardConfig:
"""Configuration for a database shard."""
shard_id: int
host: str
port: int
database: str
weight: int = 1 # Relative weight for load distribution
status: str = 'active' # active, readonly, maintenance
class ConsistentHashRouter:
"""
Consistent hashing implementation with virtual nodes.
Virtual nodes ensure even distribution even with heterogeneous shard sizes.
Adding/removing shards only affects K/n keys where n = number of shards.
"""
def __init__(self, virtual_nodes: int = 150):
"""
Initialize consistent hash ring.
Args:
virtual_nodes: Number of virtual nodes per physical shard.
More nodes = better distribution, higher memory usage.
"""
self.virtual_nodes = virtual_nodes
self.ring: List[int] = [] # Sorted hash values
self.ring_map: [, ShardConfig] = {}
.shards: [, ShardConfig] = {}
() -> :
.shards[shard.shard_id] = shard
num_vnodes = .virtual_nodes * shard.weight
i (num_vnodes):
vnode_key =
hash_value = ._(vnode_key)
bisect.insort(.ring, hash_value)
.ring_map[hash_value] = shard
logger.info(
)
() -> :
shard_id .shards:
ValueError()
shard = .shards[shard_id]
num_vnodes = .virtual_nodes * shard.weight
removed_count =
i (num_vnodes):
vnode_key =
hash_value = ._(vnode_key)
hash_value .ring_map:
.ring.remove(hash_value)
.ring_map[hash_value]
removed_count +=
.shards[shard_id]
logger.info(
)
() -> [ShardConfig]:
.ring:
ValueError()
key_hash = ._(key)
idx = bisect.bisect_right(.ring, key_hash)
idx == (.ring):
idx =
shard = .ring_map[.ring[idx]]
shard.status == :
logger.warning()
._find_next_active_shard(idx)
shard
() -> [ShardConfig]:
i ((.ring)):
idx = (start_idx + i) % (.ring)
shard = .ring_map[.ring[idx]]
shard.status == :
shard
ValueError()
() -> :
(hashlib.md5(key.encode()).hexdigest(), )
() -> [, ]:
distribution = {shard_id: shard_id .shards}
i ():
shard = .get_shard((i))
distribution[shard.shard_id] +=
distribution
() -> [, ]:
distribution = .get_shard_distribution()
total = (distribution.values())
expected_per_shard = total / (.shards)
imbalance = {}
shard_id, count distribution.items():
deviation = (count - expected_per_shard) / expected_per_shard *
imbalance[shard_id] = {
: count,
: expected_per_shard,
: (deviation, )
}
max_deviation = (s[] s imbalance.values())
{
: max_deviation < ,
: max_deviation,
: imbalance,
: (
max_deviation >
)
}
__name__ == :
router = ConsistentHashRouter(virtual_nodes=)
router.add_shard(ShardConfig(
shard_id=,
host=,
port=,
database=,
weight=
))
router.add_shard(ShardConfig(
shard_id=,
host=,
port=,
database=,
weight=
))
router.add_shard(ShardConfig(
shard_id=,
host=,
port=,
database=,
weight=
))
user_id =
shard = router.get_shard(user_id)
()
balance_report = router.rebalance_check()
()
()
()
// sharding/shard_connection_pool.js
const { Pool } = require('pg');
const crypto = require('crypto');
class ShardConnectionPool {
constructor(shardConfigs) {
this.shards = new Map();
this.virtualNodes = 150;
this.ring = [];
this.ringMap = new Map();
// Initialize connection pools for each shard
shardConfigs.forEach(config => {
const pool = new Pool({
host: config.host,
port: config.port,
database: config.database,
user: config.user,
password: config.password,
max: 20, // Max connections per shard
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
});
..(config., {
config,
pool,
: {
: ,
: ,
:
}
});
.(config);
});
.();
}
() {
numVNodes = . * (config. || );
( i = ; i < numVNodes; i++) {
vnodeKey = ;
hash = .(vnodeKey);
..(hash);
..(hash, config.);
}
..( a - b);
}
() {
(
crypto.().(key).().(, ),
);
}
() {
(.. === ) {
();
}
keyHash = .(key);
idx = ..( h >= keyHash);
(idx === -) {
idx = ;
}
..(.[idx]);
}
() {
shardId = .(shardKey);
shard = ..(shardId);
(!shard) {
();
}
startTime = .();
{
result = shard..(sql, params);
shard..++;
latency = .() - startTime;
shard.. =
(shard.. * (shard.. - ) + latency) /
shard..;
result;
} (error) {
shard..++;
.(, error);
error;
}
}
() {
promises = .(..()).( shard => {
{
result = shard..(sql, params);
{
: shard..,
: result.,
:
};
} (error) {
{
: shard..,
: error.,
:
};
}
});
results = .(promises);
allRows = results
.( r.)
.( r.);
{
: allRows,
: results
};
}
() {
shardId = .(shardKey);
shard = ..(shardId);
client = shard..();
{
client.();
result = (client);
client.();
result;
} (error) {
client.();
error;
} {
client.();
}
}
() {
stats = {};
( [shardId, shard] .) {
stats[shardId] = {
...shard.,
: shard..,
: shard..,
: shard..
};
}
stats;
}
() {
( shard ..()) {
shard..();
}
}
}
shardPool = ([
{
: ,
: ,
: ,
: ,
: ,
: ,
:
},
{
: ,
: ,
: ,
: ,
: ,
: ,
:
}
]);
userId = ;
user = shardPool.(
userId,
,
[userId]
);
allActiveUsers = shardPool.(
,
[]
);
.();
shardPool.(userId, (client) => {
client.(
,
[, userId]
);
client.(
,
[userId, -, ]
);
});
( {
stats = shardPool.();
.(, .(stats, , ));
}, );
# sharding/geo_shard_router.py
from typing import Dict, Optional
from dataclasses import dataclass
from enum import Enum
class Region(Enum):
"""Geographic regions for data residency compliance."""
US_EAST = 'us-east'
US_WEST = 'us-west'
EU_WEST = 'eu-west'
ASIA_PACIFIC = 'asia-pacific'
@dataclass
class GeoShardConfig:
region: Region
shard_id: int
host: str
port: int
database: str
data_residency_compliant: bool = True
class GeographicShardRouter:
"""
Route queries to region-specific shards for GDPR/data residency compliance.
Each user/tenant is assigned to a geographic region and all their data
resides in shards within that region.
"""
def __init__(self):
self.region_shards: Dict[Region, list[GeoShardConfig]] = {}
self.user_region_map: Dict[str, Region] = {} # user_id -> region
def add_region_shard(self, shard: GeoShardConfig) -> None:
"""Add shard for specific geographic region."""
shard.region .region_shards:
.region_shards[shard.region] = []
.region_shards[shard.region].append(shard)
()
() -> :
user_id .user_region_map:
ValueError(
)
.user_region_map[user_id] = region
()
() -> [GeoShardConfig]:
region = .user_region_map.get(user_id)
region:
ValueError()
shards = .region_shards.get(region)
shards:
ValueError()
shard_idx = (user_id) % (shards)
shards[shard_idx]
() -> :
user_region = .user_region_map.get(user_id)
user_region != shard.region:
ValueError(
)
geo_router = GeographicShardRouter()
geo_router.add_region_shard(GeoShardConfig(
region=Region.US_EAST,
shard_id=,
host=,
port=,
database=
))
geo_router.add_region_shard(GeoShardConfig(
region=Region.EU_WEST,
shard_id=,
host=,
port=,
database=,
data_residency_compliant=
))
geo_router.assign_user_region(, Region.US_EAST)
geo_router.assign_user_region(, Region.EU_WEST)
us_user_shard = geo_router.get_shard_for_user()
()
eu_user_shard = geo_router.get_shard_for_user()
()
| Error | Cause | Solution |
|---|---|---|
| "No shards available" | All shards offline or empty ring | Add at least one shard, check shard health |
| "Cross-shard foreign key violation" | Reference to data on different shard | Denormalize data or use application-level joins |
| "Shard rebalancing in progress" | Data migration active | Retry query or route to new shard |
| "Distributed transaction failure" | 2PC coordinator unreachable | Implement saga pattern or idempotent operations |
| "Hotspot detected on shard" | Uneven key distribution | Rebalance with more virtual nodes or reshard |
Sharding Strategies
consistent_hash: Best for even distribution, minimal rebalancingrange: Simple, good for time-series, prone to hotspotsdirectory: Flexible, requires lookup table maintenancegeographic: Data residency compliance, region isolationVirtual Nodes
Connection Pooling
max_connections_per_shard: 10-50 depending on loadidle_timeout: 30-60 secondsconnection_timeout: 2-5 secondsDO:
DON'T:
/database-partition-manager - Partition tables within shards/database-replication-manager - Set up replicas per shard/database-migration-manager - Migrate data between shards/database-health-monitor - Monitor per-shard health metrics