Verwenden Datenbank sharding für horizontal scaling
Sharding distributes Daten across multiple databases durch ein shard Schlüssel. Lernen sharding strategies, cross-shard queries, und trade-offs.
- 1
Sharding splits a large database into smaller shards, each holding a subset of data. The shard key determines which shard holds each row. Strategies: range (A-M on shard 1, N-Z on shard 2), hash (hash(key) % num_shards), directory (lookup table). Sharding enables horizontal scaling but complicates cross-shard queries, joins, and transactions.
- 2 Hash-Rechner →
Use a hash function to determine the shard: shard = hash(shard_key) % num_shards. This distributes data evenly. Use a consistent hash (see consistent hashing) to minimize data movement when adding/removing shards. The hash tool computes the shard assignment for a given key.
- 3 SQL-Formatierer →
Formatieren queries that target a specific shard. Each shard has the same schema — the application routes queries to the correct shard based on the shard key. Cross-shard queries (without the shard key) must query all shards and merge results — avoid these for performance.
Häufige Fragen
- When should I shard?
- When a single database cannot handle the load (CPU, memory, disk, IOPS) or data size. Vertical scaling (bigger server) is simpler — try it first. Shard when you hit vertical scaling limits or need geographic data distribution. Sharding adds significant complexity — do not shard prematurely.
- How do I choose a shard key?
- Choose a key that: distributes data evenly (high cardinality), is present in most queries (enables shard routing), rarely changes (minimizes resharding), and groups related data (avoids cross-shard joins). Common choices: user_id, tenant_id, geographic region. Avoid hot keys that concentrate traffic on one shard.