소스 정보
- 저장소
- 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명령은 한 줄로 유지됩니다. 복사하기 전에 가로로 스크롤해 전체 내용을 확인하세요.
로컬 사본을 원하시나요? 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