Consistent Hashing
"The principle advantage of consistent hashing is that departure or arrival of a node only affects its immediate neighbors and other nodes remain unaffected." — DeCandia و همکاران، Dynamo: Amazon's Highly Available Key-value Store، SOSP ۲۰۰۷، بخش ۴٫۲
خلاصه: در Consistent Hashing کلیدها و nodeها روی یک دایرهٔ مشترک از مقدارهای hash قرار میگیرند؛ با اضافه یا حذف یک node فقط کلیدهای مجاور جابهجا میشوند (حدود K/n از K کلید)، نه تقریباً همهٔ کلیدها مثل hash(key) % n. تمرکز: hash ring، virtual node (token)، replication روی ring، hotspot و نابرابری بار، bounded-load، jump hash، rendezvous (HRW)، Maglev، hash slot (عدد ۱۶۳۸۴ در Redis Cluster)، هزینهٔ resharding و رفتار واقعی هر محصول. هدف یادگیری: برای cache، دیتابیس shardشده یا load balancer یک روش جایگذاری انتخاب کنید، تعداد کلیدهای جابهجاشده و میزان ناعادلانهبودن بار را پیشبینی کنید و عددها را از یک آزمایش Go اندازهگیریشده بخوانید.
این صفحه مرجع کامل جایگذاری کلیدها با hash روی مجموعهای از nodeهای متغیر است. صاحب ring، virtual nodeها، rendezvous hashing، jump hash، Maglev، bounded loadها، هزینهٔ resharding و تفاوت Cassandra / Dynamo / Redis Cluster است. partitioning اعلانی و shard key در PostgreSQL را دوباره تدریس نمیکند (Partitioning & Sharding in PostgreSQL)؛ نردبان مقیاس (Storage & Data Scaling)، مدل داده و quorumهای سبک Dynamo (Wide-Column & Key-Value at Scale)، ساختماندادهٔ Redis (Redis)، replication (Replication, Read Replicas & Failover) و ساختارهای احتمالاتی (Bloom Filters) در صفحههای خودشان هستند.
نقشهٔ صفحه
| دنبال چه میگردید | کجا بروید |
|---|---|
| جدولی که در یک دقیقه حفظ شود | همهچیز در یک دقیقه |
چرا hash(key) % n کافی نیست | چرا Consistent Hashing وجود دارد |
| Karger 1997، Dynamo، rendezvous، ketama، jump hash، Maglev، bounded loads | از کجا آمده |
| یک روش با timeline و کد SQL، Go و Laravel | مفهومها، یکییکی |
| PostgreSQL، MySQL، Cassandra، Redis، MongoDB، Kafka، nginx، HAProxy و Envoy واقعاً چه میکنند | رفتار هر محصول |
| token range، preference list، gossip، hash tag و پاسخهای خطا | سازوکار |
| دستورهای Memcached، Redis، Cassandra و cache tag | راهحل مسئلههای کلاسیک |
| کدام روش برای کدام بار کاری | انتخاب روش |
| مونولیت، میکروسرویس، replica و مقیاس ۱x تا ۱۰۰x | در معماری |
| بازتولید عددهای این صفحه | آزمایشگاه |
| باورهای غلط، چکیده، واژهنامه | بدفهمیها، چکیده، واژهنامه |
همهچیز در یک دقیقه
روشها. هر ردیف در بخش مفهومها باز میشود. «جابهجایی» یعنی سهم کلیدهایی که هنگام افزودن یک node به n node صاحبشان عوض میشود.
| روش | ایدهٔ یکخطی | جابهجایی هنگام join | توازن | حافظهٔ هر client | هزینهٔ lookup | کاربرد |
|---|---|---|---|---|---|---|
Modulo hash(key) % n | جایگاه در فهرست nodeها | حدود n/(n+1) (۸۶٪ برای ۶ به ۷) | کامل | فهرست O(n) | O(1) | partitioner پیشفرض Kafka، hash partition در PostgreSQL / MySQL، gomemcache |
| Hash ring با یک token برای هر node | node مالک کمان پیش از نقطهاش | حدود 1/(n+1) | ضعیف (max/mean حدود ۲٫۶ در ۶ node) | O(n) | O(log n) | شکل درسی |
| Hash ring با virtual node (token) | چند نقطه برای هر node | حدود 1/(n+1) | خوب با بیش از ۱۰۰ token | O(n x T) | O(log nT) | Dynamo، Cassandra، Riak، ketama، Envoy ring_hash |
| Fixed hash slots | کلید به slot با hash، slot به node با جدول | دقیقاً slotهایی که جابهجا میکنید | هرچه تخصیص بدهید | O(slots) | O(1) | Redis Cluster (۱۶۳۸۴)، Dynamo strategy 3، Couchbase vBucket، shardهای Citus |
| Jump consistent hash | کلید با احتمال 1/(n+1) به bucket جدید «میپرد» | دقیقاً 1/(n+1) | تقریباً کامل | هیچ | O(ln n) | storeهای shardشده با شماره |
| Rendezvous (HRW) | هر node به کلید امتیاز میدهد، بیشترین برنده است | حدود 1/(n+1) | تقریباً کامل | O(n) نام | O(n) | cache، CDN، انتخاب top-k replica |
| Maglev | جدول بزرگ lookup که با permutation پر میشود | حدود 1/(n+1) بهاضافهٔ کمی | تقریباً کامل | جدول O(M) | O(1) | Google Maglev، Envoy maglev |
| Bounded-load ring | ring بهعلاوهٔ سقف ceil(c x average) | کمی بیش از ring ساده | حداکثر c برابر میانگین | ring + شمارنده | O(log nT) و probing | HAProxy hash-balance-factor |
عددهایی که مهماند (در آزمایشگاه اندازهگیری شده؛ ۱۲۰٬۰۰۰ کلید، ۶ node و افزودن node هفتم):
| روش | کلید جابهجاشده | جابهجایی به nodeای غیر از node جدید | max/mean بار در ۶ node |
|---|---|---|---|
| Modulo | 85.6% | 71.3% (85,601 کلید بین nodeهای قدیمی جابهجا شد) | 1.0x |
| Ring، 1 token | 15.9% | 0 | 1.47x در این اجرا، 2.56x میانگین |
| Ring، 16 token | 16.2% | 0 | 1.62x در این اجرا، 1.35x میانگین |
| Ring، 256 token | 15.3% | 0 | 1.18x در این اجرا، 1.10x میانگین |
| Jump hash | 14.2% | 0 | 1.01x |
| Rendezvous | 14.3% | 0 | 1.01x |
| Maglev (65537 slot) | 14.6% | 288 کلید | 1.02x |
سه کاری که باید کرد.
| وضعیت | کار درست |
|---|---|
| لایهٔ cache که بزرگ و کوچک میشود (Memcached، Redis بهعنوان cache) | ring از نوع ketama (۱۰۰ تا ۲۰۰ نقطه برای هر server، با وزن) یا rendezvous؛ هرگز modulo |
| دیتابیسی که باید در پسزمینه rebalance شود | تعداد ثابتی partition کوچک (slot، vnode، shard) و جدولی که partition را به node نگاشت میکند؛ partition را جابهجا کنید نه کلید را |
| load balancer با کلید چسبنده و ترافیک نامتوازن | Consistent hashing بهعلاوهٔ bounded load (hash-balance-factor از ۱۲۵ تا ۲۰۰ در HAProxy) یا Maglev |
چرا Consistent Hashing وجود دارد
مجموعهای از node و جریانی از کلید دارید. هر client باید بدون پرسیدن از کسی بداند کلید روی کدام node است. جواب بدیهی node = hash(key) % n است: کاملاً متوازن و تقریباً رایگان، تا لحظهای که n عوض شود. آنوقت hash(key) % n و hash(key) % (n+1) فقط برای حدود یکی از هر n+1 کلید یکساناند؛ پس تقریباً همهٔ کلیدها صاحبشان را عوض میکنند: cache در یک ثانیه خالی میشود و دیتابیس shardشده باید تقریباً همهٔ داده را کپی کند. Karger و همکاران در مقالهٔ ۱۹۹۷ همین شکست را توصیف میکنند: "When the range of the hash function (p in the example) changed, almost every item would be hashed to a new location. Suddenly, all cached data is useless because clients are looking for it in a different location."
| ساده (modulo) | Consistent |
|---|---|
| یک خط، بدون state، توازن کامل | state دارد (ring، جدول یا فهرست node)، توازن آماری است یا باید مهندسی شود |
تغییر n حدود n/(n+1) کلیدها را جابهجا میکند | تغییر n حدود 1/(n+1) کلیدها را جابهجا میکند |
همهٔ clientها باید در یک لحظه n یکسان داشته باشند | clientهایی با فهرست کمی متفاوت بیشتر وقتها همنظرند (ویژگی «spread» در Karger) |
| برای تعداد ثابت shard که هرگز تغییر نمیکند مناسب است | برای وقتی که node میآید و میرود لازم است: cache، autoscaling، خرابی |
| تابع hash ضعیف هم گاهی کار میکند | تابع hash باید bitها را خوب مخلوط کند، چون موقعیتها مقایسه میشوند |
تمثیلی که در این صفحه تکرار میکنیم: خیابان دایرهای داروخانهها. هر خانه روی دایره شمارهای دارد و پیک بسته را به اولین داروخانه در جهت عقربههای ساعت میرساند. وقتی داروخانهٔ جدیدی باز میشود فقط بستههای قطعهٔ پیش از خودش را میگیرد. با modulo، باز کردن یک داروخانه همهٔ داروخانهها را دوباره شمارهگذاری میکند و هر خانه به جای دیگری میرود. virtual nodeها زنجیرهاند: یک شرکت شعبههای کوچک زیادی دور دایره باز میکند؛ وقتی آن شرکت میبندد کارش بین همسایههای متعدد پخش میشود نه روی یکی.
سه برداشت نادرست رایج، از همین اول
- «Consistent hashing بار را متوازن میکند.» جابهجایی را کمینه میکند. توازن از virtual node، جدول مهندسیشده (Maglev، slot) یا سقف (bounded load) میآید. ring ساده با یک نقطه برای هر node نامتوازن است: در ۲۰ cluster ششنفره میانگین max/mean برابر 2.56 و بدترین حالت 4.04 اندازه گرفتیم.
- «Consistent hashing یعنی هیچ دادهای جابهجا نمیشود.» فقط حدود
1/(n+1)کلیدها جابهجا میشوند، ولی باید stream شوند و باید معلوم باشد نسخهٔ قدیمی کی پاک شود (nodetool cleanupدر Cassandra). جابهجایی ارزان است، نه رایگان. - «این قابلیت دیتابیس است.» hash partitioning در PostgreSQL و MySQL از modulo ساده استفاده میکند؛ partitioner پیشفرض Kafka
murmur2(key) % numPartitionsاست؛ DynamoDB و MongoDB داخل خودشان hash میکنند و chunk را rebalance میکنند. Consistent hashing واقعی در storeهای سبک Dynamo، Redis Cluster (به شکل slot ثابت)، کتابخانههای client و load balancerها زندگی میکند.
از کجا آمده
۱۹۹۷، Karger، Lehman، Leighton، Panigrahy، Levine و Lewin در MIT consistent hashing را برای cache وب معرفی کردند که «hot spot» را کم کند: clientهایی که دید ناقص و متفاوتی از مجموعهٔ cacheها دارند باید باز هم یک شیء را به مجموعهٔ کوچکی از cacheها نگاشت کنند. تعریفشان: "When a machine is added to or removed from the set of caches, the expected fraction of objects that must be moved to a new cache is the minimum needed to maintain a balanced load across the caches." این ویژگی را smoothness مینامند و دو ویژگی دیگر هم دارند: «spread» (در همهٔ viewهای clientها، یک شیء به چند cache مختلف نگاشت میشود) و «load» (چند شیء مختلف به یک cache نگاشت میشود). شرکت Akamai از همین کار بیرون آمد (این یک منبع ثانویه است؛ خود مقاله دربارهٔ پروتکل است).
۱۹۹۶ و ۱۹۹۸، Thaler و Ravishankar در University of Michigan rendezvous hashing یا Highest Random Weight (HRW) را ابداع کردند: هر client برای یک کلید به هر server امتیاز میدهد و بیشترین را انتخاب میکند. گزارش فنی CSE-TR-316-96 و مقالهٔ ۱۹۹۸ در IEEE/ACM Transactions on Networking با عنوان "Using Name-Based Mappings to Increase Hit Rates" آن را توصیف میکنند (برای تاریخها از مقالهٔ ویکیپدیا بهعنوان منبع ثانویه استفاده شده است).
حدود ۲۰۰۷، ketama (Last.fm) نگاشت modulo را در clientهای memcached عوض کرد. README میگوید: "This meant that whenever we added or removed servers from the pool, everything hashed to different servers, which effectively wiped the entire cache." هر server را به "several (100-200)" نقطه روی دایرهای به نام continuum hash میکند.
۲۰۰۷، Dynamo (Amazon، SOSP) ring را به لایهٔ ذخیرهسازی تبدیل کرد: virtual nodeهایی به نام token، فهرست N node متمایز (preference list) و بعداً سه strategy برای partitioning (بخش ۶٫۲)، چون token تصادفی bootstrap و archive را دردناک میکرد. Cassandra و Riak این طراحی را به ارث بردند؛ مستندات Cassandra میگوید "maps every node to one or more tokens on a continuous hash ring".
۲۰۱۴، Lamping و Veach (Google) jump consistent hash را منتشر کردند: "a fast, minimal memory, consistent hash algorithm that can be expressed in about 5 lines of code".
۲۰۱۶، Maglev (Google، NSDI) یک consistent hash مبتنی بر جدول lookup برای load balancerهای شبکه آورد و Mirrokni، Thorup و Zadimoghaddam (Google) consistent hashing با bounded loads را معرفی کردند که حالا در HAProxy و چند proxy دیگر هست.
Redis Cluster (۲۰۱۵، Redis 3.0) راه دیگری رفت: نه ring، بلکه ۱۶۳۸۴ hash slot ثابت با جدول صریح slot به node.
Hash ring در برابر hash slot
ring و جدول slot دو راه برای یادداشت «کدام node صاحب کدام بخش از فضای hash است» هستند. ring جدول را از نام nodeها محاسبه میکند (هر client میتواند خودش بسازد)؛ slot جدول را صریح ذخیره میکند (کسی باید آن را پخش کند). strategy 3 در Dynamo پل بین این دو است: "Q/S tokens per node, equal-sized partitions". بخش Hash slot آن را پوشش میدهد.
مفهومها، یکییکی
هر بلوک همین ترتیب را دارد: به زبان ساده، باور غلط رایج، تعریف، timeline، سناریوی واقعی، چه کسی آن را فراهم میکند و راهحل با SQL، Go و Laravel. کد Go همهٔ بلوکها یک ماژول کوچک فقط با کتابخانهٔ استاندارد است، academy/consistent-hashing، و فایلهای PHP برای Laravel 13 / PHP 8.3 نوشته شدهاند.
Modulo hashing و چرا میشکند حیاتی
به زبان ساده: serverها را از ۰ تا n-1 شماره میزنید و هر کلید را به server شمارهٔ hash(key) mod n میفرستید. کاملاً متوازن است و حافظه نمیخواهد. وقتی n عوض شود تقریباً هر کلید جای دیگری میافتد.
بدفهمی رایج: «تابع hash خوب، resize را ارزان میکند.» مشکل hash نیست، mod n است. برای اینکه h mod n و h mod (n+1) برابر شوند کلید باید تصادفی خاص را برآورده کند که برای حدود 1/(n+1) کلیدها رخ میدهد، هر hashی که باشد.
تعریف: owner(key) = nodes[H(key) mod n]. رفتن از n به n+1 node حدود n/(n+1) کلیدها را جابهجا میکند و برخلاف consistent hashing، این کلیدها بین nodeهای قدیمی هم جابهجا میشوند.
key h mod 6 h mod 7 verdict (adding a 7th cache node)
1 user:1001 2 5 moved: cache miss, DB hit
2 user:1002 4 4 stays (about 1 key in 7)
3 user:1003 0 3 moved
4 user:1004 5 1 moved
5 -- after the change about 86% of lookups miss: a thundering herd on the databaseسناریوهای واقعی: روزی که pool مربوط به Memcached از ۶ به ۷ server میرسد و hit rate برای یک ساعت از ۹۸٪ به ۱۴٪ میافتد و دیتابیس بار را میگیرد؛ MySQL shardشدهای که user_id % 4 به user_id % 5 تبدیل میشود و همهٔ ردیفها باید کپی شوند؛ topic در Kafka که تعداد partition آن زیاد میشود و کلیدهایی که ضمانت ترتیب داشتند به partition دیگری میروند (BuiltInPartitioner در Kafka این را حساب میکند: Utils.toPositive(Utils.murmur2(serializedKey)) % numPartitions).
| محصول | modulo کجا استفاده میشود | نتیجه |
|---|---|---|
| PostgreSQL | Hash partitioning: FOR VALUES WITH (MODULUS m, REMAINDER r)؛ "the hash value of the partition key divided by the specified modulus will produce the specified remainder" | تغییر m یعنی partitionبندی دوباره ردیفها (partition را با modulus بزرگتر تقسیم کنید یا داده را جابهجا کنید) |
| MySQL (InnoDB) | PARTITION BY HASH(expr): شمارهٔ partition برابر N = MOD(expr, num)؛ LINEAR HASH الگوریتم توان دو دارد | تغییر تعداد partition ردیفها را دوباره پخش میکند؛ LINEAR HASH کمتر جابهجا میکند ولی اندازهها نابرابرتر میشود |
| Kafka | murmur2(key) % numPartitions | افزودن partition ترتیب هر کلید موجود را میشکند |
Go gomemcache | crc32.ChecksumIEEE(key) % len(servers) در selector.go | افزودن server بیشتر کلیدها را جابهجا میکند |
PHP Memcached | OPT_DISTRIBUTION: "Currently supported methods are modulo and consistent hashing" | consistent را صریح انتخاب کنید |
راهحل: از روش consistent استفاده کنید (بلوکهای بعدی). اگر ناچار به modulo هستید، n را در تمام عمر داده ثابت نگه دارید و زیاد بگیرید: ۲۵۶ یا ۱۰۲۴ shard منطقی انتخاب کنید و shardها را با جدول به serverها نگاشت کنید؛ این همان ایدهٔ hash slot است. در SQL این جدول دادهای معمولی است:
-- Logical shards are fixed forever; only the shard -> node mapping changes.
CREATE TABLE shard_map (
shard_id int PRIMARY KEY, -- 0..1023, hash(key) % 1024
node text NOT NULL, -- 'db-3.internal'
moved_at timestamptz NOT NULL DEFAULT now()
);
-- Resharding = copy one shard, then flip one row. 1/n of the shards move, not all keys.
UPDATE shard_map SET node = 'db-7.internal', moved_at = now() WHERE shard_id = 412;
-- Route a key (the application hashes, the database only stores the map):
SELECT node FROM shard_map WHERE shard_id = (abs(hashtextextended('user:1001', 0)) % 1024);(hashtextextended تابع داخلی PostgreSQL است و ثبات آن بین نسخهها مستند نشده؛ وقتی نتیجه باید از upgrade جان به در ببرد، در application با یک تابع مستند hash کنید.)
Go: شکست در ۱۰ خط دیده میشود، بخش modulo در cmd/movement. Laravel: کد crc32($key) % count($servers) را خودتان ننویسید؛ از گزینههای Memcached زیر یا از ShardRing استفاده کنید.
Hash ring حیاتی
به زبان ساده: بازهٔ مقدارهای hash را به شکل دایره خم کنید. هر node را روی hash نامش بگذارید. هر کلید به اولین node در جهت عقربههای ساعت از hash خودش میرود.
بدفهمی رایج: «ring ساختماندادهای است که nodeها را دور هم حلقه میکند.» توپولوژی شبکه نیست. آرایهای مرتب از عددهاست با binary search و wrap-around؛ nodeها لازم نیست همدیگر را بشناسند تا جایگذاری کار کند.
تعریف: فرض کنید H به [0, 2^64) نگاشت میکند. node با نام v موقعیت H(name(v)) را میگیرد. کلید k مال node با کوچکترین موقعیت >= H(k) است (بهصورت دوری، برگشت به کوچکترین). node مسئول بازهٔ بین پیشین خودش و خودش است. Dynamo: "Each node in the system is assigned a random value within this space which represents its 'position' on the ring ... walking the ring clockwise to find the first node with a position larger than the item's position."
event ring (positions, schematic) owner of key k
1 ring = [A@10, B@48, C@85] A B C --
2 hash(k) = 60 between B and C C (first clockwise)
3 node D joins at 70 A B [k=60] D@70 C D takes k (60 < 70 <= 85)
4 node D leaves again A B C C owns k again
5 hash(k) = 90, past the last point wraps around to A@10 Aسناریوهای واقعی: pool مربوط به Memcached جلوی کاتالوگ محصولات؛ CDN که برای یک URL edge cache را انتخاب میکند؛ client کشف سرویس که برای یک session id backend را انتخاب میکند؛ sharding سمت client برای کلیدهای Redis.
| کجا | شکل ring |
|---|---|
| Dynamo / Cassandra / Riak | ring از token؛ node مالک کمان پیش از هر token خود است |
ketama (libmemcached، PHP Memcached) | «continuum» با ۱۰۰ تا ۲۰۰ نقطه برای هر server، بر پایهٔ MD5 |
| nginx | hash $request_uri consistent; "the ketama consistent hashing method will be used" |
| HAProxy | hash-type consistent: "the hash table is a tree filled with many occurrences of each server" |
| Envoy | ring_hash: "the addition or removal of one host from a set of N hosts will affect only 1/N requests" |
راهحل (Go). ring آموزشی ring/ring.go است: slice مرتب از (position, node)، sort.Search برای lookup و Add و Remove که slice را دوباره میسازند.
// Package ring is a teaching consistent-hash ring with virtual nodes,
// replica walking and bounded-load placement (Karger et al. 1997, the
// Dynamo paper section 4, Mirrokni, Thorup & Zadimoghaddam 2016).
package ring
import (
"errors"
"fmt"
"math"
"sort"
"academy/consistent-hashing/hashutil"
)
type point struct {
pos uint64
node string
}
// Ring maps keys to nodes. It is not safe for concurrent writes; guard
// it with a sync.RWMutex or swap whole immutable rings atomically.
type Ring struct {
points []point // sorted by pos
tokens map[string]int
}
// New returns an empty ring.
func New() *Ring { return &Ring{tokens: map[string]int{}} }
// Add places a node on the ring at `tokens` positions (virtual nodes).
// Give a bigger machine more tokens, exactly as Dynamo section 4.2 says.
func (r *Ring) Add(node string, tokens int) {
r.Remove(node)
for i := 0; i < tokens; i++ {
r.points = append(r.points, point{hashutil.Sum64(fmt.Sprintf("%s#%d", node, i)), node})
}
r.tokens[node] = tokens
sort.Slice(r.points, func(i, j int) bool { return r.points[i].pos < r.points[j].pos })
}
// Remove deletes every token of node. Its ranges fall to the next
// token clockwise, which with many vnodes belongs to many different nodes.
func (r *Ring) Remove(node string) {
if _, ok := r.tokens[node]; !ok {
return
}
kept := r.points[:0]
for _, p := range r.points {
if p.node != node {
kept = append(kept, p)
}
}
r.points = kept
delete(r.tokens, node)
}
// Nodes returns the number of physical nodes.
func (r *Ring) Nodes() int { return len(r.tokens) }
// index returns the first point at or after the key's position,
// wrapping to 0 past the top of the ring.
func (r *Ring) index(key string) int {
h := hashutil.Sum64(key)
i := sort.Search(len(r.points), func(i int) bool { return r.points[i].pos >= h })
if i == len(r.points) {
i = 0
}
return i
}
// Locate returns the node that owns key (the primary replica).
func (r *Ring) Locate(key string) (string, error) {
if len(r.points) == 0 {
return "", errors.New("ring: empty")
}
return r.points[r.index(key)].node, nil
}
// Replicas returns the preference list: walk clockwise and collect n
// DISTINCT physical nodes, skipping further vnodes of a node already
// chosen (Dynamo section 4.3).
func (r *Ring) Replicas(key string, n int) []string {
if len(r.points) == 0 {
return nil
}
if n > len(r.tokens) {
n = len(r.tokens)
}
out := make([]string, 0, n)
seen := make(map[string]bool, n)
for i, step := r.index(key), 0; len(out) < n && step < len(r.points); step++ {
p := r.points[(i+step)%len(r.points)]
if !seen[p.node] {
seen[p.node] = true
out = append(out, p.node)
}
}
return out
}
// Bounded wraps a Ring with a per-node capacity of ceil(c * average
// load): consistent hashing with bounded loads. A key whose first node is
// full moves clockwise to the first node with room.
type Bounded struct {
R *Ring
C float64 // balance factor c = 1 + epsilon, for example 1.25
load map[string]int
sum int
}
// NewBounded returns a bounded-load view of r.
func NewBounded(r *Ring, c float64) *Bounded {
return &Bounded{R: r, C: c, load: map[string]int{}}
}
// Acquire assigns one unit of load for key and returns the chosen node.
func (b *Bounded) Acquire(key string) string {
capacity := int(math.Ceil(b.C * float64(b.sum+1) / float64(b.R.Nodes())))
i := b.R.index(key)
for step := 0; step < len(b.R.points); step++ {
p := b.R.points[(i+step)%len(b.R.points)]
if b.load[p.node] < capacity {
b.load[p.node]++
b.sum++
return p.node
}
}
panic("ring: no node has capacity (C must be > 1)")
}
// Release gives one unit of load back to node.
func (b *Bounded) Release(node string) {
if b.load[node] > 0 {
b.load[node]--
b.sum--
}
}
// Load returns the current load per node.
func (b *Bounded) Load() map[string]int { return b.load }SQL ring ندارد؛ ring را در application یا client دیتابیس نگه دارید و فقط عضویت را ذخیره کنید:
CREATE TABLE ring_members (
node text PRIMARY KEY,
tokens int NOT NULL DEFAULT 160 CHECK (tokens > 0), -- weight: more tokens, more data
state text NOT NULL DEFAULT 'joining' -- joining | normal | leaving
);Laravel: ShardRing همان الگوریتم در PHP 8.3 با موقعیتهای hash('xxh3', ...) است.
<?php
declare(strict_types=1);
namespace App\Redis;
use InvalidArgumentException;
/**
* Consistent-hash ring with virtual nodes (Karger 1997; Dynamo section 4.2).
* Immutable: to change membership build a new ring and swap it in.
*/
final class ShardRing
{
/** @var list<int> sorted token positions */
private array $positions = [];
/** @var array<int, string> position => physical node name */
private array $owners = [];
/** @var array<string, int> node => number of tokens */
private array $tokens = [];
/**
* @param array<string, int> $nodes node name => token count (weight)
*/
public function __construct(array $nodes)
{
if ($nodes === []) {
throw new InvalidArgumentException('A ring needs at least one node.');
}
foreach ($nodes as $name => $tokens) {
$this->tokens[$name] = $tokens;
for ($i = 0; $i < $tokens; $i++) {
// On a collision the later token wins; with 32-bit positions
// and a few thousand tokens that is astronomically rare.
$this->owners[self::position("{$name}#{$i}")] = $name;
}
}
ksort($this->owners);
$this->positions = array_keys($this->owners);
}
/** 32-bit position from xxh3 (PHP 8.1+). Stable across processes and hosts. */
public static function position(string $value): int
{
return (int) hexdec(substr(hash('xxh3', $value), 0, 8));
}
/** Primary owner: first token at or after the key, wrapping past the top. */
public function locate(string $key): string
{
return $this->owners[$this->positions[$this->indexOf($key)]];
}
/**
* Preference list: walk clockwise and collect $count DISTINCT nodes.
*
* @return list<string>
*/
public function replicas(string $key, int $count): array
{
$count = min($count, count($this->tokens));
$total = count($this->positions);
$start = $this->indexOf($key);
$chosen = [];
for ($step = 0; $step < $total && count($chosen) < $count; $step++) {
$node = $this->owners[$this->positions[($start + $step) % $total]];
$chosen[$node] = true;
}
return array_keys($chosen);
}
private function indexOf(string $key): int
{
$h = self::position($key);
$lo = 0;
$hi = count($this->positions);
// Lower bound: first index whose position >= $h.
while ($lo < $hi) {
$mid = intdiv($lo + $hi, 2);
if ($this->positions[$mid] < $h) {
$lo = $mid + 1;
} else {
$hi = $mid;
}
}
return $lo === count($this->positions) ? 0 : $lo;
}
}Virtual node (token) حیاتی
به زبان ساده: بهجای یک نقطه برای هر server، به هر server نقطههای زیادی پراکنده دور دایره بدهید. هر server صاحب کمانهای کوچک بسیار میشود؛ سهم کل به برابری نزدیک میشود و وقتی server میآید یا میرود بارش از همسایههای زیاد میآید یا به آنها میرود.
بدفهمی رایج: «virtual node بیشتر همیشه بهتر است.» مستندات Cassandra هزینه را میگوید: "Every token introduces up to 2 * (RF - 1) additional neighbors on the token ring, which means that there are more combinations of node failures where we lose availability for a portion of the token ring." repair و range scan هم range بیشتری لمس میکنند.
تعریف: virtual node (اصطلاح Dynamo) یا token (اصطلاح Cassandra) یک موقعیت روی ring است که مال یک node فیزیکی است. Dynamo: "A virtual node looks like a single node in the system, but each node can be responsible for more than one virtual node." مقاله اضافه میکند که تعداد virtual nodeهای هر node را میتوان از ظرفیتش تعیین کرد، "accounting for heterogeneity in the physical infrastructure".
step what happens
1 node E (2x memory) joins with 320 tokens other nodes have 160 each
2 each token takes the arc just before it E steals many small slices from many nodes
3 E ends up with about 2/(n+1) of the data proportional to tokens, as Dynamo section 4.2 intends
4 later E fails its 320 arcs fall to 320 different successors, so every survivor gains about the sameسناریوهای واقعی: pool ناهمگن Memcached که weight همان حافظه به MB است (فایل server در ketama: "Just use the number of megs allocated to the server as the weight"); cluster Cassandra با nodeهای ۱۶ و ۳۲ هستهای و num_tokens متفاوت؛ cluster Riak با ۶۴ partition.
اثر اندازهگیریشدهٔ token (۲۰ cluster ششنفره، هرکدام ۶۰٬۰۰۰ کلید، max/mean بار):
| token برای هر node | میانگین max/mean | بدترین max/mean | برداشت |
|---|---|---|---|
| 1 | 2.56 | 4.04 | یک node ممکن است چهار برابر سهمش را داشته باشد |
| 16 | 1.35 | 1.60 | پیشفرض num_tokens در Cassandra 4؛ داغترین node ۳۵٪ بیش از میانگین دارد |
| 64 | 1.15 | 1.35 | |
| 256 | 1.10 | 1.16 | پیشفرض Cassandra 2.x |
| 1024 | 1.04 | 1.07 | انحراف معیار تقریباً با 1/sqrt(T) کم میشود |
| محصول | پیشفرض و knob |
|---|---|
| Cassandra | num_tokens پیشفرض ۱۶ (در cassandra.yaml مستند)؛ در 2.x "the only token allocation algorithm available was picking random tokens" و پیشفرض ۲۵۶ بود؛ از 3.x گزینههای allocate_tokens_for_keyspace / allocate_tokens_for_local_replication_factor tokenها را قطعی انتخاب میکنند تا با تعداد کم هم توازن حفظ شود |
| Dynamo (مقاله) | در strategy 1 تعداد T token تصادفی برای هر node؛ strategy 3 تعداد Q partition ثابت میگیرد و به هر node مقدار Q/S میدهد |
| Riak | اندازهٔ ثابت ring (تعداد partition)، هر node تعداد partitions/nodes vnode اجرا میکند |
| ketama / libmemcached | ۱۰۰ تا ۲۰۰ نقطه برای هر server، بر حسب weight |
Envoy ring_hash | minimum_ring_size و maximum_ring_size؛ gaugeهای min_hashes_per_host / max_hashes_per_host را مانیتور کنید |
| Redis Cluster | token ندارد: slot دارد |
راهحل: در Go با r.Add(node, tokens) و tokenهای متناسب با ظرفیت؛ در Laravel وزنها را به ShardRing بدهید؛ در SQL tokenها را در ring_members ذخیره کنید. histogram توزیع در آزمایشگاه است.
Replication روی ring و preference list حیاتی
به زبان ساده: node مالک کلید نسخهٔ اول را نگه میدارد؛ nodeهای بعدی در جهت عقربهها نسخههای دیگر را. فهرست nodeهای یک کلید همان preference list است.
بدفهمی رایج: «replicaها N token بعدیاند.» با virtual node، tokenهای بعدی اغلب مال همان ماشین فیزیکیاند و سه نسخه روی یک server میافتد. پیمایش باید tokenهای nodeای را که قبلاً انتخاب شده رد کند. Dynamo: "the preference list for a key is constructed by skipping positions in the ring to ensure that the list contains only distinct physical nodes."
تعریف: با replication factor برابر N (حرف N در Dynamo، RF در Cassandra)، replicaهای کلید k اولین N node فیزیکی متمایزند که از H(k) در جهت عقربهها میبینیم. Dynamo میگوید "each node is responsible for the region of the ring between it and its Nth predecessor". استراتژیهای آگاه از rack یا datacenter (در Cassandra NetworkTopologyStrategy) nodeهای rackی را که نسخه دارد هم رد میکنند. فهرست Dynamo بیش از N node دارد تا nodeهای خراب جایگزین شوند (hinted handoff، sloppy quorum).
ring tokens clockwise from H(k) decision (RF = 3)
1 C2 (node C) take C
2 A3 (node A) take A
3 C3 (node C again) skip: node C already chosen
4 B3 (node B) take B -> preference list [C, A, B]
5 a write with W=2, a read with R=2 R + W > N = 3, so reads overlap writes (Dynamo)سناریوهای واقعی: نوشتن در Cassandra با QUORUM و RF=3 به coordinator میرود و دو تا از سه replica تأیید میکنند؛ خرابی یک node باعث میشود preference list آن را رد کند و hint به node بعدی بنویسد؛ خرابی یک rack همهٔ replicaهای یک range را از بین میبرد چون استراتژی آگاه از rack نبود.
| محصول | replicaها چطور انتخاب میشوند |
|---|---|
| Dynamo | N node متمایز بعدی در جهت عقربهها؛ preference list بلندتر از N برای خرابی |
| Cassandra | "we 'walk' the ring in a clockwise fashion until we encounter three distinct nodes"؛ SimpleStrategy rack را نادیده میگیرد، NetworkTopologyStrategy datacenter و rack را رعایت میکند |
| Riak | مالک partition بهعلاوهٔ "the vnodes responsible for the next N-1 partitions" |
| Redis Cluster | ring ندارد: هر slot یک master و چند replica دارد که هنگام راهاندازی تعیین میشود (CLUSTER REPLICATE) |
| MongoDB | replica set برای هر shard، مستقل از جایگذاری |
| DynamoDB | پنهان؛ سرویس بین Availability Zoneها replicate میکند |
راهحل (Go): ring.Replicas(key, 3) در ماژول آموزشی slice را میپیماید و مجموعهٔ seen نگه میدارد. Laravel: ShardRing::replicas($key, 3). SQL: جایگذاری را فقط وقتی در کاتالوگ نگه دارید که سیستم مبتنی بر slot است:
SELECT node FROM shard_replicas WHERE shard_id = 412 ORDER BY replica_rank; -- rank 0 is the primaryHash slot (partition ثابت) حیاتی
به زبان ساده: فضای hash را یک بار برای همیشه به تعداد ثابتی بخش کوچک (slot) ببرید. جدولی میگوید کدام node صاحب کدام slotهاست. برای rebalance، slotها را کامل جابهجا کنید و جدول را عوض کنید.
بدفهمی رایج: «Redis Cluster همان consistent hashing است.» مشخصات Redis Cluster این سازوکار را hash slot مینامد و ring ندارد: HASH_SLOT = CRC16(key) mod 16384. نگاشت کلید به slot همان modulo است و هرگز عوض نمیشود؛ فقط جدول slot به node عوض میشود، پس resharding دقیقاً همان slotهایی را جابهجا میکند که انتخاب کردهاید.
تعریف: Redis: "The cluster's key space is split into 16384 slots, effectively setting an upper limit for the cluster size of 16384 master nodes (however, the suggested max size of nodes is on the order of ~ 1000 nodes)." Hash tag: "If the key contains a "{...}" pattern only the substring between { and } is hashed in order to obtain the hash slot". strategy 3 در مقالهٔ Dynamo همین ایده است: Q partition مساوی ثابت که هر node مقدار Q/S از آنها را نگه میدارد. vBucketهای Couchbase، shardهای Citus ("a row is stored in a shard if the hash of the value in the distribution column falls within the shard's hash range")، keyspace id در Vitess، chunkهای hashشدهٔ MongoDB، shardهای Elasticsearch و partitionهای Riak همه گونههایی از همین هستند.
step effect
1 cluster of 3 masters, slots 0-5460 | 5461-10922 | 10923-16383
2 client: CRC16("foo") mod 16384 = 12182 slot 12182 belongs to master C
3 redis-cli --cluster add-node, then reshard new master D owns no slot yet, serves nothing
4 CLUSTER SETSLOT 700 MIGRATING / IMPORTING slot 700 moves key by key (MIGRATE)
5 client asks A for a key in slot 700 A answers -MOVED 700 10.0.0.4:6379 (after the move) or -ASK 700 ... (during)
6 client refreshes its slot table the next 1/4 of all slots move; no key outside them is touchedسناریوهای واقعی: رشد Redis Cluster از ۳ به ۴ master (۲۵٪ slotها جابهجا میشود)؛ سرویس سبد خریدی که {tenant:42}:cart و {tenant:42}:orders را در یک slot نگه میدارد تا SMOVE کار کند؛ Black Friday که از قبل روی ۱۶۳۸۴ slot تقسیم کردهاید و فقط slot جابهجا میکنید.
| پرسش | پاسخ |
|---|---|
| چرا ۱۶۳۸۴؟ | مشخصات عدد ۱۶۳۸۴ را ثابت میکند و میگوید سقف cluster ۱۶۳۸۴ master است و حدود ۱۰۰۰ node حداکثر عملی پیشنهادی است. توضیح معمول برای انتخاب نکردن ۶۵۵۳۶ (پیامهای heartbeat بیتمپ slot را حمل میکنند و بیتمپ کوچکتر ارزانتر است) از توضیحات نویسندهٔ Redis میآید، نه از خود مشخصات |
| کلید بدون tag؟ | کل کلید hash میشود |
| اگر کلیدهای یک دستور در slotهای مختلف باشند؟ | سرور CROSSSLOT Keys in request don't hash to the same slot جواب میدهد |
| چه کسی جدول را میداند؟ | هر node و هر client هوشمند؛ clientها آن را cache میکنند و با MOVED اصلاح میکنند |
راهحل (Go): ماژول آموزشی slots/slots.go CRC16 و قاعدهٔ hash tag را پیاده میکند و بررسی میکند slot(foo) = 12182 باشد، همان مقداری که Redis برای CLUSTER KEYSLOT foo میدهد. Laravel: ClusterKeys::slot() و ClusterKeys::tenantKey(). SQL: جدول shard_map از بلوک modulo همین الگو در قالب رابطهای است.
// Package slots reproduces Redis Cluster key-to-slot mapping:
// HASH_SLOT = CRC16(key) mod 16384, with the {hash tag} exception.
package slots
// Count is the number of hash slots in Redis Cluster.
const Count = 16384
// crc16 is CRC-16/XMODEM (poly 0x1021, init 0), as in the cluster spec.
func crc16(b []byte) uint16 {
var crc uint16
for _, c := range b {
crc ^= uint16(c) << 8
for i := 0; i < 8; i++ {
if crc&0x8000 != 0 {
crc = crc<<1 ^ 0x1021
} else {
crc <<= 1
}
}
}
return crc
}
// Slot returns the hash slot of key, honouring hash tags: if the key has
// a '{', a later '}' and at least one byte between the first '{' and the
// first '}' after it, only those bytes are hashed.
func Slot(key string) int {
for s := 0; s < len(key); s++ {
if key[s] != '{' {
continue
}
for e := s + 1; e < len(key); e++ {
if key[e] == '}' {
if e == s+1 {
return int(crc16([]byte(key)) % Count)
}
return int(crc16([]byte(key[s+1:e])) % Count)
}
}
break
}
return int(crc16([]byte(key)) % Count)
}
// Assign splits the slots into n contiguous ranges, as redis-cli
// --cluster create does for n masters; it returns the owner of each slot.
func Assign(n int) []int {
owner := make([]int, Count)
for i := range owner {
owner[i] = i * n / Count
}
return owner
}Hotspot و نابرابری بار مهم
به زبان ساده: حتی وقتی هر node همان تعداد کلید را دارد، یک node ممکن است بیشتر درخواستها را بگیرد، چون بعضی کلیدها بسیار بیشتر خوانده میشوند یا چون کمانها هماندازه نیستند.
بدفهمی رایج: «توزیع یکنواخت کلید یعنی بار یکنواخت.» نویسندگان Dynamo میگویند این فقط وقتی درست است که "the access distribution of keys is not highly skewed"، و طراحیشان فرض میکند "there are enough keys in the popular end of the distribution" تا کلیدهای محبوب پخش شوند. یک کلید وایرال هر hashی را شکست میدهد: به یک جا hash میشود.
تعریف: سه منبع نابرابری هست: کمانهای نابرابر (token کم)، ظرفیت نابرابر (weight غلط)، دسترسی کج (hot key). Dynamo «load balancing efficiency» را اندازه میگیرد: "the ratio of average number of requests served by each node to the maximum number of requests served by the hottest node".
cause symptom fix
1 one token per node max/mean 2.6 on average (4.0 worst, measured) more tokens or Maglev/slots
2 weights ignored small machine saturates first tokens proportional to capacity
3 one viral key one node at 100% CPU, others idle replicate the hot key (read from replicas), local cache, key splitting "key#0..key#7", bounded loads
4 a hot tag or counter one Redis slot is the bottleneck shard the counter: counter:{0..15}, sum on read
5 time-ordered keys on range all writes to the newest range hash the key (MongoDB hashed shard key) or prefix a bucketسناریوهای واقعی: پروفایل یک سلبریتی روی یک server از Memcached؛ شمارندهٔ INCR در Redis برای rate limit سراسری که یک shard را ذوب میکند؛ partition در Cassandra برای یک tenant که ۳۰٪ ترافیک را دارد؛ collection در MongoDB که با ObjectId shard شده و "the chunk with an upper bound of MaxKey receives the majority incoming writes" و shard key از نوع hashed درجها را پخش میکند.
| راهکار | برای | کمک نمیکند |
|---|---|---|
| token بیشتر / تعداد slot بیشتر | کمانهای نابرابر | یک hot key |
| Bounded-load hashing | کجی بار روی node | کلیدی که از ظرفیت یک node هم داغتر است |
شکستن کلید (key#0 .. key#7) | hot key خواندنی یا نوشتنی | خوانندهها باید ادغام کنند، atomicity تککلیدی از دست میرود |
| cache محلی (داخل process) یا CDN جلوتر | خواندن داغ | نوشتن داغ |
| خواندن از هر replica | خواندن داغ | کهنگی باید مجاز باشد |
راهحل (Go): اول اندازه بگیرید؛ دستور distribution histogram و max/mean را چاپ میکند. SQL: SELECT shard_id, count(*) FROM orders GROUP BY 1 ORDER BY 2 DESC کجی را پیدا میکند؛ pg_stat_statements پرسوجوهای داغ را. Laravel: شمارندهٔ داغ را روی n کلید پخش کنید:
// Spread a hot counter over 16 keys; each INCR hits a different slot, a read sums them.
Redis::incr('likes:post:'.$postId.':'.random_int(0, 15));
$total = array_sum(Redis::mget(array_map(fn ($i) => "likes:post:$postId:$i", range(0, 15))));(روی Redis Cluster، MGET بالا CROSSSLOT میشود؛ از hash tag مثل likes:{post:$postId}:$i استفاده کنید تا ۱۶ کلید در یک slot بمانند و پخششدن را فدا کنید، یا ۱۶ GET جدا را با pipeline بفرستید. همین مبادله نکتهٔ اصلی است.)
Bounded-load consistent hashing مهم
به زبان ساده: به هر node ظرفیت «کمی بیشتر از میانگین» بدهید. کلید به node عادیاش میرود، مگر آنکه پر باشد؛ در این صورت در جهت عقربهها به node بعدی که جا دارد میرود.
بدفهمی رایج: «bounded load الگوریتم جداگانهای است.» یک ring ساده بهعلاوهٔ شمارنده و حلقه است: Mirrokni و همکاران از "the consistent hashing scheme where current balls and bins are hashed to a unit cycle, and a ball is placed in the first bin succeeding it in clock-wise order" شروع میکنند و "apply the idea of linear probing by forwarding the ball on the circle to the first non-full bin".
تعریف: برای پارامتر توازن c = 1 + epsilon > 1، هیچ bin بیش از ceil(c x m / n) از m توپ روی n bin نمیگیرد. مقاله ثابت میکند وقتی توپ یا bin درج یا حذف میشود، تعداد انتظاری جابهجاییها در ضریب O(1/epsilon^2) از بهینه است (برای epsilon <= 1). consistent hashing ساده چنین سقفی ندارد: "the load balancing of these schemes is no better than a random assignment of clients to servers, so with n of each, we expect many servers to be overloaded with Θ(log n/log log n) clients."
event (n = 4 nodes, c = 1.25, average load 100) decision
1 key k hashes to node B, B has 124 of cap 125 accepted, B = 125
2 next key hashes to B again B is full: probe clockwise
3 C has 90 < 125 placed on C (and remembered)
4 request finishes Release(C): counters go down
5 c = 1.0 would be exact balance and many moves; c = 2 is nearly plain hashingسناریوهای واقعی: cache قطعههای ویدئو که عنوانهای محبوب همه روی یک server میچسبند؛ gateway stateful که tenant را برای locality در cache به همان backend میفرستد ولی هرگز بالای ۱۲۵٪ میانگین بار؛ matchmaker بازی.
| محصول | knob |
|---|---|
| HAProxy | hash-balance-factor <factor>: "Setting <factor> to 0 (the default) disables the feature. Otherwise, <factor> is a percentage greater than 100. For example, if <factor> is 150, then no server will be allowed to have a load more than 1.5 times the average." "Reasonable values are from 125 to 200." |
| Envoy | خود ring_hash و Maglev سقف ندارند؛ از overload management یا سیاستهای load-aware استفاده کنید |
| nginx | hash ... consistent گزینهٔ bounded-load ندارد |
| ماژول آموزشی Go | ring.NewBounded(r, 1.25) |
اندازهگیری (۱۲۰٬۰۰۰ کلید، ۶ node، ۱۶ token و ۲۰٪ ترافیک روی ۲۵۰ کلید داغ): ring ساده max/mean برابر 1.73 میدهد (یک node با 34,535 در برابر میانگین 20,000)، ring محدود با c = 1.25 دقیقاً 1.25 میدهد (25,000).
راهحل (Go): b := ring.NewBounded(r, 1.25); node := b.Acquire(key); defer b.Release(node). SQL: معادلی ندارد؛ شمارندههای بار در application یا proxy هستند. Laravel: شمارندهٔ in-flight هر node را با Cache::increment() نگه دارید و ShardRing::replicas($key, $n) را برای اولین node زیر سقف بپیمایید.
Jump consistent hash مهم
به زبان ساده: تابعی پنجخطی که با کلید و تعداد bucketها (n) یک bucket از ۰ تا n-1 برمیگرداند، بهطوریکه بزرگکردن n به n+1 دقیقاً 1/(n+1) کلیدها را جابهجا میکند، همه به bucket جدید، و اصلاً حافظه نمیخواهد.
بدفهمی رایج: «jump hash ring بهتری است.» نمیتواند node را نام ببرد: "jump consistent hash does not support arbitrary server names, but only returns a shard number". bucket دلخواه را هم نمیشود حذف کرد: حذف bucket شمارهٔ ۳ از ۱۰ تا شمارهٔ ۴ تا ۹ را دوباره شماره میزند.
تعریف: Lamping و Veach: "The function satisfies the two properties: (1) about the same number of keys map to each bucket, and (2) the mapping from key to bucket is perturbed as little as possible when the number of buckets is changed." چکیده میافزاید: "Its main limitation is that the buckets must be numbered sequentially, which makes it more suitable for data storage applications than for distributed web caching." در مقایسه با ring کارگر، "requires no storage, is faster, and does a better job of evenly dividing the key space". زمان انتظاری O(ln n) است.
n key k lands in bucket rule
1 1 0 only one bucket
2 2 0 or 1: moves to 1 with probability 1/2 the new bucket b = n-1 steals each key with prob 1/n
3 7 stays unless it jumps to 6 (prob 1/7) a key either stays or moves to the new bucket
4 8 stays unless it jumps to 7 (prob 1/8)
5 -- never moves between two old buckets, so a shard can be split by copying 1/(n+1) of the data to the new shardسناریوهای واقعی: store کلید-مقدار shardشده که shardها شماره دارند و فقط در انتها اضافه میکنید؛ ناوگان شمارهدار cache worker که شماره همان ordinal در StatefulSet کوبرنتیز است (worker-0 .. worker-n) و فقط از دم scale میشود؛ partitionبندی map-reduce.
| ویژگی | Jump hash | Ring با vnode |
|---|---|---|
| حافظه | هیچ | O(n x T) |
| توازن | تقریباً کامل (اندازهگیری max/mean 1.01) | آماری (1.04 تا 1.35 با 64 تا 1024 token) |
| افزودن/حذف دلخواه | خیر: فقط آخرین bucket | بله |
| وزن | خیر | بله (token) |
| node با نام | خیر | بله |
| lookup | O(ln n) | O(log nT) |
راهحل (Go): jump/jump.go همان الگوریتم ۵ خطی مقاله با کلید uint64 است؛ ابتدا کلید را به ۶۴ بیت hash کنید.
// Package jump implements Jump Consistent Hash (Lamping & Veach, 2014).
package jump
// Hash maps a 64-bit key to a bucket in [0, buckets). It needs no memory,
// but buckets must be numbered 0..n-1 and only the highest-numbered
// bucket can be removed without moving unrelated keys.
func Hash(key uint64, buckets int) int {
var b int64 = -1
var j int64
for j < int64(buckets) {
b = j
key = key*2862933555777941757 + 1
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
}
return int(b)
}SQL: جدول shard شمارهدار (shard_id 0..n-1) با آن جور است؛ پیادهسازی stored procedure ممکن است ولی حلقه در application اجرا میشود. Laravel: حلقه را با intdiv و محاسبهٔ float پورت کنید؛ سرریز عدد صحیح را در نظر بگیرید (عدد صحیح PHP علامتدار ۶۴ بیتی است و سرریز به float میشود؛ برای قابلحمل بودن از gmp_* یا ماسک ۳۲ بیتی استفاده کنید).
Rendezvous (highest random weight) hashing مهم
به زبان ساده: برای هر کلید، هر node از جفت (node، کلید) یک امتیاز حساب میکند؛ کلید به node با بیشترین امتیاز میرود. اگر nodeای ناپدید شود فقط کلیدهای خودش بالاترین امتیازدهندهٔ جدید دارند. اگر node تازه بیاید فقط کلیدهایی را میبرد که برایشان بالاترین امتیاز را دارد.
بدفهمی رایج: «همان consistent hashing با نام دیگر است.» هدف یکی است، سازوکار فرق دارد: ring ندارد، token ندارد، جز نام nodeها state ندارد و مجموعهٔ replica مفت به دست میآید: k امتیاز برتر. هزینهاش O(n) برای هر lookup است. ویکیپدیا آن را چنین توصیف میکند: "an algorithm that allows clients to achieve distributed agreement on a set of k options out of a possible set of n options".
تعریف: owner(k) = argmax over nodes v of H(v, k). Thaler و Ravishankar آن را معرفی کردند (گزارش فنی ۱۹۹۶، IEEE/ACM ToN ۱۹۹۸). گونههای وزندار هست؛ کد آموزشی وزن برابر میگیرد.
node scores for key k (schematic) score
1 cache-1 0x91...
2 cache-2 0xe4... <- highest, owner
3 cache-3 0x2a...
4 cache-2 is removed owner becomes the next highest: cache-1
5 other keys whose top score was never cache-2 unchangedسناریوهای واقعی: pool کوچک (کمتر از حدود ۵۰ node) از cacheها که O(n) ارزان است؛ انتخاب ۳ replica برتر یک shard بدون ring؛ انتخاب worker تجمیع برای یک tenant در pipeline داده؛ انتخاب edge در CDN (کاربرد انگیزهدهنده در مقالهٔ ۱۹۹۸: hit rate پراکسیها).
| محصول / کتابخانه | Rendezvous |
|---|---|
کتابخانههای Go مثل github.com/dgryski/go-rendezvous | وجود دارند؛ ماژول آموزشی ۴۰ خط است |
| Apache Ignite | تابع affinity از نوع rendezvous پیشفرض نگاشت partition به node است (مستندات Ignite؛ دوباره دریافت نشده) |
| Kafka، Cassandra، Redis | استفاده نمیشود |
راهحل (Go): rendezvous/rendezvous.go: Locate یک حلقه است، Top(key, k) replicaها را میدهد. در Laravel: nodeها را با usort بر اساس hash('xxh3', $node.$key) مرتب کنید. در SQL شکل خوبی ندارد؛ index عبارتی روی hash(node || key) کمک نمیکند چون امتیاز به فهرست nodeها وابسته است.
// Package rendezvous implements Highest Random Weight hashing
// (Thaler & Ravishankar). Every node scores every key; the top score wins.
package rendezvous
import (
"sort"
"academy/consistent-hashing/hashutil"
)
// Set is a group of node names.
type Set struct{ nodes []string }
// New returns a Set with the given nodes.
func New(nodes ...string) *Set { return &Set{nodes: append([]string(nil), nodes...)} }
// Add appends a node. Remove deletes one. Neither moves unrelated keys.
func (s *Set) Add(n string) { s.nodes = append(s.nodes, n) }
// Remove deletes a node by name.
func (s *Set) Remove(n string) {
for i, x := range s.nodes {
if x == n {
s.nodes = append(s.nodes[:i], s.nodes[i+1:]...)
return
}
}
}
func score(node, key string) uint64 { return hashutil.Sum64(node + "\x00" + key) }
// Locate returns the node with the highest score for key: O(n) per lookup.
func (s *Set) Locate(key string) string {
var best string
var bestScore uint64
for i, n := range s.nodes {
if sc := score(n, key); i == 0 || sc > bestScore {
best, bestScore = n, sc
}
}
return best
}
// Top returns the k highest-scoring nodes: the replica set of key.
func (s *Set) Top(key string, k int) []string {
type scored struct {
node string
score uint64
}
all := make([]scored, 0, len(s.nodes))
for _, n := range s.nodes {
all = append(all, scored{n, score(n, key)})
}
sort.Slice(all, func(i, j int) bool { return all[i].score > all[j].score })
if k > len(all) {
k = len(all)
}
out := make([]string, k)
for i := range out {
out[i] = all[i].node
}
return out
}Maglev hashing تکمیلی
به زبان ساده: جدول lookup بزرگی (۶۵٬۵۳۷ یا ۶۵۵٬۳۷۳ خانه) از پیش میسازید که هر backend تقریباً سهم برابری از خانهها دارد و طوری پخش شدهاند که حذف یک backend فقط خانههای خودش را بهاضافهٔ چند خانهٔ اضافه بازنویسی میکند. hash بسته یک خانه را انتخاب میکند؛ جدول backend را میگوید. lookup فقط یک خواندن آرایه است.
بدفهمی رایج: «Maglev گونهای از rendezvous با حافظهٔ بهتر است.» روش ساخت جدول lookup است: backendها نوبتی اولین خانهٔ آزاد مورد علاقهشان را برمیدارند که سهم تقریباً مساوی را تضمین میکند، به قیمت کمی اختلال بیش از حداقل.
تعریف: Eisenbud و همکاران: "The basic idea of Maglev hashing is to assign a preference list of all the lookup table positions to each backend. Then all the backends take turns filling their most-preferred table positions that are still empty, until the lookup table is completely filled in." permutation برای backend شمارهٔ i برابر (offset + j x skip) mod M است با offset = h1(name) mod M و skip = h2(name) mod (M-1) + 1 و "M must be a prime number so that all values of skip are relatively prime to it". وزنها با "altering the relative frequency of the backends' turns" ساخته میشوند. Maglev یک جدول per-connection هم نگه میدارد تا هنگام تغییر جدول، flowهای بلند را حفظ کند.
M = 7, backends B0 B1 B2: the toy example of the Maglev paper (Tables 1 and 2)
1 permutations: B0 = 3 0 4 1 5 2 6 B1 = 0 2 4 6 1 3 5 B2 = 3 4 5 6 0 1 2
2 round 1: B0 takes 3, B1 takes 0, B2 wants 3 (taken) so takes 4
3 round 2: B0 takes 1 (0 and 4 are taken), B1 takes 2, B2 takes 5
4 round 3: B0 takes 6. Table: 0=B1 1=B0 2=B1 3=B0 4=B2 5=B2 6=B0 (3, 2, 2 slots)
5 remove B1: refill with B0 and B2 only -> 0=B0 1=B0 2=B0 3=B0 4=B2 5=B2 6=B2
6 changed: slots 0 and 2 (B1's own) plus slot 6 (B0 -> B2): "only one other entry (row 6) needs to be changed"
7 measured here (M = 65537, 6 -> 7 backends): 14.6% of keys move, 288 of them not to the new backendسناریوهای واقعی: load balancer شبکه جلوی فرانتاند جستوجو که برای هر five-tuple تصمیم میگیرد؛ sidecar در service mesh که upstream را انتخاب میکند؛ proxy مربوط به Redis که باید در O(1) shard را انتخاب کند.
| محصول | تنظیم |
|---|---|
| Google Maglev | جدول 65537 (کوچک) و 655373 (بزرگ) در ارزیابی مقاله |
| Envoy | load balancer از نوع maglev، اندازهٔ جدول ثابت 65537 بهصورت پیشفرض (table_size)؛ "Maglev has substantially faster table lookup build times as well as host selection times (approximately 10x and 5x respectively ...). While Maglev aims for minimal disruption, it is not as stable as ring hash when upstream hosts change ... approximately double the keys will move" |
| Cilium و سایر load balancerهای eBPF | جدول lookup به سبک Maglev ارائه میدهند (مستندات vendor؛ دوباره دریافت نشده) |
راهحل (Go): maglev/maglev.go حلقهٔ پر کردن جدول و Share() را برای بررسی توازن پیاده میکند. Laravel و SQL به Maglev نیاز ندارند؛ جایش در proxy لایهٔ ۴/۷ است.
// Package maglev implements the Maglev lookup-table construction
// (Eisenbud et al., NSDI 2016): each backend has a permutation of table
// slots; backends take turns claiming their next free preferred slot.
package maglev
import "academy/consistent-hashing/hashutil"
// DefaultSize is a prime. The paper uses 65537 for small and 655373 for
// large tables. M must be prime so every skip is coprime with it.
const DefaultSize = 65537
// Table is a filled lookup table of backend indexes.
type Table struct {
backends []string
entry []int
}
// New builds a table of size m (prime) for the backends.
func New(backends []string, m int) *Table {
n := len(backends)
offset := make([]int, n)
skip := make([]int, n)
for i, b := range backends {
offset[i] = int(hashutil.Sum64Seed(b, 1) % uint64(m))
skip[i] = int(hashutil.Sum64Seed(b, 2)%uint64(m-1)) + 1
}
next := make([]int, n)
entry := make([]int, m)
for i := range entry {
entry[i] = -1
}
filled := 0
for filled < m {
for i := 0; i < n && filled < m; i++ {
c := (offset[i] + next[i]*skip[i]) % m
for entry[c] >= 0 {
next[i]++
c = (offset[i] + next[i]*skip[i]) % m
}
entry[c] = i
next[i]++
filled++
}
}
return &Table{backends: append([]string(nil), backends...), entry: entry}
}
// Locate returns the backend for key: one hash and one array read.
func (t *Table) Locate(key string) string {
return t.backends[t.entry[hashutil.Sum64(key)%uint64(len(t.entry))]]
}
// Share returns how many table slots each backend owns.
func (t *Table) Share() map[string]int {
out := make(map[string]int, len(t.backends))
for _, e := range t.entry {
out[t.backends[e]]++
}
return out
}هزینهٔ resharding: جابهجایی K/n کلید حیاتی
به زبان ساده: وقتی node شمارهٔ n+1 اضافه میشود باید K/(n+1) از K کلید را داشته باشد. consistent hashing دقیقاً همانها را از بقیهٔ nodeها میگیرد و چیز دیگری را جابهجا نمیکند.
بدفهمی رایج: «zero downtime یعنی جابهجایی آنی است.» جابهجایی گرانترین بخش است: داده باید از nodeهای موجود که ترافیک میدهند stream شود. Dynamo گزارش میدهد با token تصادفی در فصل شلوغ "the bootstrapping has taken almost a day to complete"، چون "the nodes handing the key ranges off to the new node have to scan their local persistence store".
تعریف: کران پایین برای join برابر K/(n+1) کلید و برای leave برابر K/n است. consistent hashing تا ضرایب ثابت به آن میرسد (ring، HRW، jump). modulo حدود K x n/(n+1) را جابهجا میکند.
| رویداد (۶ به ۷ node، ۱۲۰٬۰۰۰ کلید) | Modulo | Consistent | یادداشت |
|---|---|---|---|
| کلیدهای جابهجاشده | 102,776 (85.6%) | 17,000 تا 19,400 (14.2% تا 16.2%) | حالت ایدئال 17,143 (14.3%) |
| مقصد آنها | هرجا | فقط node جدید (Maglev: چند مورد اضافه) | در آزمایشگاه اندازهگیری شده |
| Slot (Redis Cluster) | 8,191 از 16,384 slot (50.0%) اگر سادهلوحانه به ۷ بازهٔ پیوسته بازتقسیم کنید | 2,340 (14.3%) اگر فقط master جدید را پر کنید | با جابهجا کردن slot ریبالانس کنید، نه با محاسبهٔ دوبارهٔ بازهها |
phase (Cassandra, adding node X) cost
1 X starts with auto_bootstrap=true joins the ring, state UJ (joining)
2 X streams its token ranges from the current replicas network + disk read on the donors
3 X becomes UN (normal); donors still hold stale copies disk is not freed yet
4 nodetool cleanup on every donor deletes keys they no longer own
5 repair later Merkle trees must be rebuilt for changed ranges (Dynamo section 6.2)سناریوهای واقعی: لایهٔ Memcached با autoscale که هر روز بزرگ میشود؛ گسترش Cassandra از ۶ به ۹ node پیش از حراج؛ Redis Cluster که دو master میگیرد و با redis-cli --cluster rebalance تعداد 5,460 slot را جابهجا میکند؛ topic در Kafka که partitionهایش دو برابر میشود و برای مدتی ترتیب هر کلید را میشکند چون Kafka consistent hashing ندارد.
| محصول | resharding چطور انجام میشود |
|---|---|
| Cassandra | Bootstrap rangeها را stream میکند؛ nodetool cleanup دادههای جابهجاشده را حذف میکند؛ nodetool decommission rangeها را برمیگرداند |
| Redis Cluster | CLUSTER SETSLOT MIGRATING/IMPORTING و MIGRATE که با redis-cli --cluster reshard یا rebalance هماهنگ میشود؛ clientها -MOVED و -ASK را دنبال میکنند |
| MongoDB | balancer chunkها را بین shardها مهاجرت میدهد؛ از 8.0 شاردکردن collection "creates 1 chunk per shard by default and migrates across the cluster" |
| PostgreSQL | Hash partition: re-partition (partition جدید با modulus جدید attach کنید، ردیفها را جابهجا کنید)؛ Citus: rebalance_table_shards() shardها را جابهجا میکند |
| DynamoDB | خودکار: سرویس partitionها را تقسیم و جابهجا میکند؛ شما نمیبینید |
| CockroachDB | مبتنی بر range (نه hash): rangeها بر اساس اندازه تقسیم و خودکار rebalance میشوند، بدون hash ring |
راهحل (SQL): اول کپی کنید، بعد سوئیچ؛ برای جابهجایی منطقی shard در PostgreSQL: CREATE PUBLICATION، subscribe روی مقصد، صبر برای sync، سپس UPDATE shard_map و بعد حذف روی مبدأ. Go: دستور movement کلیدهای جابهجاشده را برای هر روش میشمارد. Laravel: پس از افزودن server به Memcached انتظار cold ratio حدود 1/(n+1) را داشته باشید؛ با یک job پیشگرم کنید تا دیتابیس missها را نگیرد.
تابع hash: FNV، xxHash، murmur، CRC16، MD5 مهم
به زبان ساده: جایگذاری فقط به اندازهٔ تابع hash یکنواخت است. موقعیتهای node#1، node#2، node#3 باید دور از هم بیفتند و hash ارزانی که فقط bitهای پایین را عوض میکند چنین نمیکند.
بدفهمی رایج: «هر hash ۶۴ بیتی برای ring خوب است.» FNV-1a پایدار، ساده و در کتابخانهٔ استاندارد Go است (hash/fnv: New32، New32a، New64، New64a، New128)، ولی وقتی فقط بایتهای آخر فرق دارند bitهای بالای آن کم عوض میشود و موقعیتهای ring بهصورت عدد مقایسه میشوند، پس برچسبهای شبیه هم خوشه میشوند. ماژول آموزشی به همین دلیل بعد از FNV یک finalizer از نوع splitmix64 میگذارد. توابع hash در hash/maphash در Go seed تصادفی هر process دارند و هرگز نباید برای جایگذاری مشترک بین processها استفاده شوند.
تعریف و انتخاب هر محصول:
| Hash | چه کسی استفاده میکند | یادداشت |
|---|---|---|
| CRC16 (XMODEM) mod 16384 | Redis Cluster | "In our tests CRC16 behaved remarkably well in distributing different kinds of keys evenly across the 16384 slots." |
| Murmur3 (بازهٔ token از -2^63 تا 2^63-1) | Murmur3Partitioner در Cassandra (partitioner پیشفرض)؛ RandomPartitioner (MD5) و ByteOrderedPartitioner قدیمیاند | partitioner "can NOT be changed without reloading all data" |
| Murmur2 | partitioner پیشفرض producer در Kafka | modulo است، consistent نیست |
| MD5 | ketama / حالت «libketama-compatible» در libmemcached | در نسخهٔ اصلی ۴ موقعیت از هر digest MD5 |
| SHA-1 ۱۶۰ بیتی | Riak ("a 160-bit binary hash of each bucket/key pair")، Dynamo (MD5 ۱۲۸ بیتی در مقاله) | |
| xxHash (XXH64، XXH3) | Go github.com/cespare/xxhash/v2 (Sum64، Sum64String)، PHP 8.1 hash('xxh3') / xxh64 | سریع، avalanche خوب، غیررمزنگاری |
| sdbm + avalanche | پیشفرض hash-type consistent در HAProxy | جایگزینها: djb2، wt6، crc32 |
| FNV-1a | hash/fnv در stdlib Go، بسیاری از cacheهای کوچک | avalanche ضعیف روی کلید کوتاه؛ finalizer اضافه کنید |
قواعد: hash باید بین processها، hostها، زبانها و نسخههای نرمافزار پایدار باشد (وگرنه دو client اختلاف نظر دارند)؛ از hashهای randomized زبان (hash() پایتون، maphash در Go، spl_object_id در PHP) استفاده نکنید؛ بایتها را hash کنید نه شیء؛ hash را در schema داده مستند کنید چون تغییرش همهچیز را دوباره نگاشت میکند.
راهحل (Go): hashutil/hashutil.go ۲۵ خط است. Laravel: hash('xxh3', $key)؛ از crc32() برای موقعیت روی ring ۶۴ بیتی دوری کنید (۳۲ بیتی و خطی است). SQL: hashtext() در PostgreSQL داخلی است؛ از hash در application یا ('x'||left(md5(k),16))::bit(64)::bigint استفاده کنید.
// Package hashutil holds the hash functions used by the teaching
// implementations. Only the standard library is used: hash/fnv for the
// base hash and a splitmix64 finalizer to repair its weak avalanche.
package hashutil
import "hash/fnv"
// FNV64a is the raw 64-bit FNV-1a hash. It is fast and stable across
// processes and releases, but its high bits change little when only the
// last bytes of the input change ("node-1#1", "node-1#2", ...). Placing
// vnodes with it directly clusters them on the ring.
func FNV64a(s string) uint64 {
h := fnv.New64a()
_, _ = h.Write([]byte(s))
return h.Sum64()
}
// Mix is the splitmix64 finalizer: every input bit flips about half of the
// output bits. It is cheap and deterministic.
func Mix(x uint64) uint64 {
x ^= x >> 30
x *= 0xbf58476d1ce4e5b9
x ^= x >> 27
x *= 0x94d049bb133111eb
x ^= x >> 31
return x
}
// Sum64 is FNV-1a followed by Mix. Use it wherever a position on a ring,
// a score or a table index is derived from a string. In production code
// prefer xxhash (github.com/cespare/xxhash/v2) or murmur3; the shape of
// the code does not change.
func Sum64(s string) uint64 { return Mix(FNV64a(s)) }
// Sum64Seed derives an independent hash from the same input, used where
// an algorithm needs two or more hash functions (Maglev offset and skip).
func Sum64Seed(s string, seed uint64) uint64 {
return Mix(FNV64a(s) ^ Mix(seed+0x9e3779b97f4a7c15))
}رفتار هر محصول
قاعدهٔ ما این است که «هیچ قابلیتی را بدون نام محصول نگوییم»؛ پس هر محصول یک بار: چه چیزی را hash میکند، با تغییر عضویت چه چیزی جابهجا میشود و knob چیست.
| محصول | روش جایگذاری | با join / leave یک node | Hash و knob |
|---|---|---|---|
| Amazon Dynamo (مقاله) | ring با token؛ بعداً Q partition ثابت (strategy 3) | rangeها را «میدزدد»؛ bootstrap با token تصادفی میتواند یک روز طول بکشد | MD5، T token، Q partition |
| Amazon DynamoDB | پنهان: "the value of the partition key as input to an internal hash function"؛ خروجی "determines the partition" | تقسیم و جابهجایی خودکار partition | چیزی عرضه نمیشود |
| Apache Cassandra | token ring + vnode | bootstrap، cleanup و decommission با nodetool | Murmur3Partitioner، num_tokens پیشفرض ۱۶، allocate_tokens_for_keyspace |
| Riak KV | ring از partitionهای ثابت، هر کدام یک vnode | handoff partitionها بین nodeها | hash ۱۶۰ بیتی bucket/key، اندازهٔ ring |
| Redis Cluster | ۱۶۳۸۴ hash slot ثابت | مهاجرت slot با MIGRATE و MOVED/ASK | CRC16، hash tag، cluster-require-full-coverage |
| Memcached + client با ketama | continuum با ۱۰۰ تا ۲۰۰ نقطه برای هر server | فقط حدود 1/(n+1) کلیدها دوباره نگاشت میشوند | MD5، weight |
| MongoDB | chunkهای hashed یا ranged، balancer | مهاجرت chunk | shard key بهصورت { field: "hashed" }؛ "hashed indexes truncate floating point numbers to 64-bit integers before hashing" |
| PostgreSQL | hash partitioning (modulus/remainder)؛ بازههای hash در Citus | re-partition؛ rebalance_table_shards | hash داخلی هر نوع |
| MySQL / InnoDB | PARTITION BY HASH / KEY / LINEAR HASH | تعریف دوبارهٔ partitionها، ردیفها کپی میشوند | MOD(expr, num) |
| SQL Server | توزیع hash ندارد؛ partition function مبتنی بر range است | sharding در سطح application | ستون محاسبهای + range function |
| Oracle | hash partitioning با تعداد partition ثابت | افزودن / coalesce کردن partition | hash داخلی |
| SQLite | یک فایل؛ توزیع ندارد | سطح application (یک فایل برای هر tenant) | ندارد |
| CockroachDB | مبتنی بر range، نه hash | rangeها بر اساس اندازه تقسیم و rebalance میشوند | ندارد |
| Google Spanner | splitهای مبتنی بر range | خودکار | ندارد |
| Kafka | murmur2(key) % partitions | افزودن partition نگاشت کلید به partition را بههم میریزد | رابط Partitioner سفارشی |
| nginx | hash $key consistent; (ketama) | "only a few keys will be remapped" | hash ... consistent |
| HAProxy | hash-type consistent، hash-balance-factor | فقط وابستگیهای همان node جابهجا میشود | پیشفرض sdbm؛ hash-type map-based شبیه modulo است |
| Envoy | ring_hash و maglev | 1/N درخواستها (ring) | minimum_ring_size، table_size |
کجا استفاده میشود
| لایه | سیستمها | کلیدی که hash میشود |
|---|---|---|
| storeهای توزیعشده | Dynamo، Cassandra، Riak، Voldemort | partition key |
| cacheهای حافظهای | clientهای Memcached (ketama)، Twemproxy، sharding سمت client در Redis | کلید cache |
| دیتابیسهای cluster | Redis Cluster، Couchbase (vBucket)، Citus، Vitess | shard key / slot |
| load balancer و proxy | Maglev، Envoy، nginx، HAProxy، CDNهای Cloudflare و Akamai | IP کلاینت، URL، session |
| streaming | partitionهای Kafka (در مقایسه: modulo)، Key_Shared در Pulsar (بازههای hash) | کلید پیام |
| object store | Ceph CRUSH (تابع جایگذاری، خویشاوند)، ring در OpenStack Swift | مسیر شیء |
سازوکار
lookup در ring. ring آرایهٔ مرتب points[] از (position, node) است. Locate(key) مقدار h = H(key) را حساب میکند و با binary search اولین اندیس با points[i].pos >= h را مییابد؛ اگر از انتها گذشت به اندیس ۰ برمیگردد. هزینه: یک hash بهاضافهٔ O(log(n x T)) مقایسه. هزینهٔ بازسازی در Add در کد آموزشی O(nT log nT) است؛ کد production کل ring غیرقابلتغییر را اتمیک عوض میکند و خوانندهها هرگز قفل نمیگیرند.
operation complexity notes
1 Locate O(log(nT)) binary search over n x T points
2 Add node O(T log(nT)) insert T tokens; only arcs before them change owner
3 Remove node O(nT) rebuild without its tokens
4 Replicas(k, N) O(N + skips) walk clockwise, skip duplicates
5 memory O(nT) 160 tokens x 100 nodes = 16,000 points (about 256 KB)توافق روی عضویت. ring فقط وقتی کار میکند که همهٔ clientها دید یکسان داشته باشند. Dynamo از پروتکل gossip استفاده میکند تا "every node in the system can determine which nodes should be in this list for any particular key"؛ Cassandra هم gossip دارد؛ Redis Cluster از باس gossip با بیتمپ مالکیت slot؛ HAProxy میخواهد "all servers have the exact same IDs" روی چند load balancer تا توزیع یکسان شود. وقتی دو دید با هم نمیخوانند، درخواستها به node اشتباه میروند: Redis با -MOVED جواب میدهد، coordinatorهای Cassandra forward میکنند، cacheها صرفاً miss میشوند.
redirectionها و خطاهای Redis Cluster:
| پاسخ | معنی | کار client |
|---|---|---|
-MOVED 3999 127.0.0.1:6381 | slot شمارهٔ 3999 حالا روی آن node است | جدول slot را بهروز کن، همانجا دوباره بفرست |
-ASK 3999 127.0.0.1:6381 | slot در حال مهاجرت است؛ این یک کلید روی مقصد است | ASKING و سپس دستور را به مقصد بفرست، جدول را عوض نکن |
-CROSSSLOT Keys in request don't hash to the same slot | دستور چندکلیدی چند slot را پوشش میدهد | hash tag یا دستورهای جدا |
-CLUSTERDOWN The cluster is down | بعضی slotها مالک ندارند (و پوشش کامل لازم است) | صبر برای failover یا تعمیر |
-TRYAGAIN | دستور چندکلیدی هنگام مهاجرت | کمی بعد دوباره امتحان کن |
دستورهای عملیاتی Cassandra: nodetool status (حالتهای UN، UJ، UL، DN)، nodetool ring، nodetool describering <keyspace>، nodetool getendpoints <keyspace> <table> <key> (replica set یک کلید را چاپ میکند)، nodetool cleanup، nodetool decommission، nodetool removenode. tokenرنجها نیمباز هستند: (t1, t2].
رفتار هنگام خرابی. در ring ساده، با خرابی یک node کمان آن به node بعدی در جهت عقربه میافتد و بار آن دو برابر میشود («cascade» که vnode درمانش است). با T token بار روی nodeهای زیاد پخش میشود. preference list در Dynamo بلندتر از N است تا نوشتن به node سالم بعدی برود و بعداً تحویل شود (hinted handoff).
Smoothness، spread و load (Karger). Smoothness = جابهجایی هنگام تغییر عضویت کمینه است؛ spread = تعداد cacheهای هر شیء در دیدهای ناهمگون محدود است؛ load = تعداد شیء هر cache محدود است. jump hash و Maglev یک دید یکسان (coordinator) فرض میکنند، پس spread را کنار میگذارند.
راهحل مسئلههای کلاسیک
| مسئله | راهحل | چگونه | مزیت | هزینه یا محدودیت |
|---|---|---|---|---|
| تغییر اندازهٔ pool مربوط به Memcached cache را پاک میکند | توزیع ketama در client | Memcached::DISTRIBUTION_CONSISTENT + OPT_LIBKETAMA_COMPATIBLE؛ weight برای هر server | فقط حدود 1/(n+1) miss | replication و failover ندارد؛ کمی نامتوازن |
| cache در Redis که از یک node بزرگتر میشود | Redis Cluster (بومی) | options.cluster = 'redis' در Laravel، nodeهای seed در clusters.default | failover، resharding، مدیریت MOVED | دستورهای چندکلیدی hash tag میخواهند |
| cache دادههای مصرفی در Redis بدون cluster | sharding سمت client | Predis با clusters و بدون options.cluster؛ یا ShardRing | ساده | failover و پروتکل resharding ندارد |
| sticky session پشت load balancer | hash $cookie consistent / hash-type consistent | nginx یا HAProxy | با تغییر backendها locality حفظ میشود | بار نامتوازن، hash-balance-factor اضافه کنید |
| یک tenant یک shard را ذوب میکند | bounded loads یا شکستن tenant | hash-balance-factor 150؛ یا بازهٔ slot اختصاصی برای tenant | node داغ را سقف میگذارد | کلیدهای tenant از node خانگیشان بیرون میروند |
| hot key در cache | خواندن از replica یا شکستن کلید | key#0..key#7، cache محلی | خواندن را پخش میکند | fan-out در invalidation |
| هممکانی کلیدهای مرتبط | Hash tag | {tenant:42}:cart در Redis Cluster | دستورهای چندکلیدی و Lua مجاز میشوند | tenantهای داغ slot داغ میسازند |
| resharding آنلاین دیتابیس SQL | shard منطقی ثابت + shard_map | logical replication برای هر shard، سوئیچ یک ردیف | فقط 1/n داده جابهجا میشود | به router در application نیاز دارد |
| ring نامتوازن | token بیشتر، Maglev یا slot | num_tokens، جدول بزرگتر | max/mean کمتر | metadata بیشتر |
Memcached با ketama در Laravel
<?php
// config/cache.php (Laravel 13): Memcached with consistent (ketama) distribution.
// The PHP Memcached extension defaults to modulo distribution; without these
// two options, adding a server to this list re-maps almost every key.
return [
'stores' => [
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'options' => [
// libketama-compatible: MD5 key hash + weighted consistent hashing.
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
// weight = number of ring points, like the ketama server file
['host' => env('MEMCACHED_A', '10.0.2.11'), 'port' => 11211, 'weight' => 100],
['host' => env('MEMCACHED_B', '10.0.2.12'), 'port' => 11211, 'weight' => 100],
['host' => env('MEMCACHED_C', '10.0.2.13'), 'port' => 11211, 'weight' => 200],
],
],
],
];افزونهٔ Memcached در PHP دو گزینه را مستند کرده است: OPT_DISTRIBUTION "Specifies the method of distributing item keys to the servers. Currently supported methods are modulo and consistent hashing" و OPT_LIBKETAMA_COMPATIBLE که "sets the item key hashing algorithm to MD5 and distribution to weighted consistent hashing". مستندات Laravel فیلد weight هر server را نشان میدهد که libketama آن را به نقطهٔ ring تبدیل میکند.
پیکربندی Redis Cluster در Laravel
Laravel 13 بهطور پیشفرض clustering بومی را برمیگزیند: "By default, Laravel will use native Redis clustering since the options.cluster configuration value is set to redis. Redis clustering is a great default option, as it gracefully handles failover." برای sharding سمت client "you may remove the options.cluster configuration value" و هشدار: "client-side sharding does not handle failover; therefore, it is primarily suited for transient cached data that is available from another primary data store." فایل زیر هر دو شکل را همراه connectionهای مستقل مورد استفادهٔ shard resolver نشان میدهد.
<?php
// config/database.php (Laravel 13): the redis block, two deployment shapes.
use Illuminate\Support\Str;
return [
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
// 'redis' (the default) = native Redis Cluster: the client learns the
// 16384-slot map from the cluster and follows MOVED and ASK redirections.
// Remove this line for client-side sharding with Predis instead.
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
],
// Native cluster: list a few seed nodes; the client discovers the rest.
'clusters' => [
'default' => [
['host' => env('REDIS_NODE_1', '10.0.0.11'), 'port' => 6379, 'password' => env('REDIS_PASSWORD')],
['host' => env('REDIS_NODE_2', '10.0.0.12'), 'port' => 6379, 'password' => env('REDIS_PASSWORD')],
['host' => env('REDIS_NODE_3', '10.0.0.13'), 'port' => 6379, 'password' => env('REDIS_PASSWORD')],
],
],
// Independent single-node connections, used by App\Redis\ShardResolver.
// Client-side sharding has no failover and no resharding protocol, so
// keep it for cache data that also exists in a primary store.
'shard-a' => ['host' => env('REDIS_SHARD_A', '10.0.1.11'), 'port' => 6379, 'database' => 0],
'shard-b' => ['host' => env('REDIS_SHARD_B', '10.0.1.12'), 'port' => 6379, 'database' => 0],
'shard-c' => ['host' => env('REDIS_SHARD_C', '10.0.1.13'), 'port' => 6379, 'database' => 0],
],
];shard resolver و طراحی کلید
<?php
declare(strict_types=1);
namespace App\Redis;
use Illuminate\Redis\Connections\Connection;
use Illuminate\Support\Facades\Redis;
/**
* Maps a key to one of the single-node connections in config/database.php.
* Use it for client-side sharding of expendable data (cache, counters).
* For data you cannot lose, use native Redis Cluster instead.
*/
final class ShardResolver
{
public function __construct(private readonly ShardRing $ring)
{
}
/** Build from the connection names; a bigger machine gets more tokens. */
public static function fromConfig(): self
{
return new self(new ShardRing([
'shard-a' => 160,
'shard-b' => 160,
'shard-c' => 320, // twice the memory, twice the tokens
]));
}
public function connectionFor(string $key): Connection
{
return Redis::connection($this->ring->locate($key));
}
public function get(string $key): mixed
{
return $this->connectionFor($key)->get($key);
}
public function put(string $key, string $value, int $ttlSeconds): void
{
$this->connectionFor($key)->setex($key, $ttlSeconds, $value);
}
/**
* Multi-key reads must be grouped per shard first; there is no cross-shard
* MGET. Returns key => value (null for misses).
*
* @param list<string> $keys
* @return array<string, mixed>
*/
public function many(array $keys): array
{
$byShard = [];
foreach ($keys as $key) {
$byShard[$this->ring->locate($key)][] = $key;
}
$out = [];
foreach ($byShard as $shard => $shardKeys) {
$values = Redis::connection($shard)->mget($shardKeys);
foreach ($shardKeys as $i => $key) {
$out[$key] = ($values[$i] ?? false) === false ? null : $values[$i];
}
}
return $out;
}
}<?php
declare(strict_types=1);
namespace App\Redis;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
/**
* Key design for native Redis Cluster: hash tags keep related keys in one
* slot, so multi-key commands, MULTI/EXEC and Lua scripts keep working.
*/
final class ClusterKeys
{
/** CRC-16/XMODEM, the function the cluster spec uses. */
public static function crc16(string $data): int
{
$crc = 0;
for ($i = 0, $n = strlen($data); $i < $n; $i++) {
$crc ^= ord($data[$i]) << 8;
for ($bit = 0; $bit < 8; $bit++) {
$crc = ($crc & 0x8000) ? (($crc << 1) ^ 0x1021) : ($crc << 1);
$crc &= 0xFFFF;
}
}
return $crc;
}
/** HASH_SLOT = CRC16(key) mod 16384, with the {hash tag} rule. */
public static function slot(string $key): int
{
$open = strpos($key, '{');
if ($open !== false) {
$close = strpos($key, '}', $open + 1);
if ($close !== false && $close > $open + 1) {
$key = substr($key, $open + 1, $close - $open - 1);
}
}
return self::crc16($key) % 16384;
}
/** One tenant, one slot: {tenant:42}:cart, {tenant:42}:orders ... */
public static function tenantKey(int $tenantId, string $name): string
{
return "{tenant:{$tenantId}}:{$name}";
}
public static function moveCartToOrders(int $tenantId, string $cartItem): void
{
$cart = self::tenantKey($tenantId, 'cart');
$orders = self::tenantKey($tenantId, 'orders');
// SMOVE names two keys, so both must live in one slot. With the
// {tenant:N} tag they do; without it the server answers
// "CROSSSLOT Keys in request don't hash to the same slot".
Redis::smove($cart, $orders, $cartItem);
}
/**
* Cache::tags() on the redis driver keeps one sorted set per tag
* (key "tag:<name>:entries"). On a cluster that set lives in ONE slot,
* so a very hot tag is a hot shard, and flushing a tag must visit every
* slot that holds one of its entries.
*/
public static function rememberProduct(int $id, callable $load): mixed
{
return Cache::tags(['products', "product:{$id}"])->remember("product:{$id}", 600, $load);
}
public static function forgetProduct(int $id): void
{
Cache::tags(["product:{$id}"])->flush();
}
}Cache tag و sharding. Cache::tags(['a','b']) در store مربوط به Redis با یک sorted set برای هر tag با نام tag:<name>:entries پیاده شده (در Illuminate\Cache\RedisTagSet بررسی شده)؛ هر put یک ZADD در آن انجام میدهد و flush() مجموعه را میخواند و entryها را (در دستههای ۱۰۰۰ تایی) حذف میکند. روی cluster، RedisTaggedCache در Laravel برای connectionهای cluster مسیر دیگری میرود (flushClusteredConnection، pipelineهای DEL تککلیدی برای Predis cluster) چون کلیدها در slotهای مختلف hash میشوند و یک دستور چندکلیدی CROSSSLOT میشود. دو نتیجه: مجموعهٔ tag داغ در یک slot است، پس هر نوشتن cache برای آن tag به یک shard میخورد؛ و flush کردن tag همهٔ slotهایی را که entry دارند میگردد. برای مسیرهای داغ tagهای کم و درشت یا کلید بهازای هر entity با forget() صریح را ترجیح دهید؛ مستندات Laravel هم میگوید tag روی driverهای file، dynamodb، database و storage پشتیبانی نمیشود.
اندازهگیری جایگذاری در Go
دستور movement همهٔ روشها را از یک آزمایش یکسان میگذراند (۶ node، افزودن node هفتم، شمردن کلیدهای جابهجاشده) و بررسی slot در Redis را چاپ میکند.
// Command movement measures how many keys change owner when a 7th node
// joins 6 existing nodes, for modulo hashing and each consistent scheme,
// and prints the Redis Cluster slot check.
package main
import (
"fmt"
"academy/consistent-hashing/hashutil"
"academy/consistent-hashing/jump"
"academy/consistent-hashing/maglev"
"academy/consistent-hashing/rendezvous"
"academy/consistent-hashing/ring"
"academy/consistent-hashing/slots"
)
const keys = 120_000
func key(i int) string { return fmt.Sprintf("user:%d", i) }
// moved counts keys whose owner differs between two placement functions.
func moved(before, after func(string) string) (int, int) {
m, toNew := 0, 0
for i := 0; i < keys; i++ {
a, b := before(key(i)), after(key(i))
if a != b {
m++
if b == "node-6" {
toNew++
}
}
}
return m, toNew
}
func main() {
old := make([]string, 6)
for i := range old {
old[i] = fmt.Sprintf("node-%d", i)
}
grown := append(append([]string(nil), old...), "node-6")
fmt.Printf("adding node-6 to 6 nodes, %d keys; ideal movement = 1/7 = %.1f%%\n\n", keys, 100.0/7)
fmt.Printf("%-26s %8s %8s %s\n", "scheme", "moved", "share", "moved to a node other than node-6")
print := func(name string, before, after func(string) string) {
m, to := moved(before, after)
fmt.Printf("%-26s %8d %7.1f%% %d\n", name, m, 100*float64(m)/keys, m-to)
}
mod := func(nodes []string) func(string) string {
return func(k string) string { return nodes[hashutil.Sum64(k)%uint64(len(nodes))] }
}
print("modulo hash % n", mod(old), mod(grown))
for _, t := range []int{1, 16, 256} {
r1, r2 := ring.New(), ring.New()
for _, n := range old {
r1.Add(n, t)
r2.Add(n, t)
}
r2.Add("node-6", t)
loc := func(r *ring.Ring) func(string) string {
return func(k string) string { n, _ := r.Locate(k); return n }
}
print(fmt.Sprintf("ring, %d token(s)/node", t), loc(r1), loc(r2))
}
jmp := func(nodes []string) func(string) string {
return func(k string) string { return nodes[jump.Hash(hashutil.Sum64(k), len(nodes))] }
}
print("jump hash", jmp(old), jmp(grown))
h1, h2 := rendezvous.New(old...), rendezvous.New(grown...)
print("rendezvous (HRW)", h1.Locate, h2.Locate)
m1, m2 := maglev.New(old, maglev.DefaultSize), maglev.New(grown, maglev.DefaultSize)
print("maglev, table 65537", m1.Locate, m2.Locate)
// Redis Cluster: a key's slot never changes; only slot ownership does.
fmt.Println()
fmt.Printf("slot(foo)=%d (CLUSTER KEYSLOT foo is 12182)\n", slots.Slot("foo"))
fmt.Printf("slot({user1000}.following)=%d slot({user1000}.followers)=%d slot(user1000)=%d\n",
slots.Slot("{user1000}.following"), slots.Slot("{user1000}.followers"), slots.Slot("user1000"))
before, after := slots.Assign(6), slots.Assign(7)
mv := 0
for s := range before {
if before[s] != after[s] {
mv++
}
}
fmt.Printf("naive re-split of 16384 slots from 6 to 7 masters moves %d slots (%.1f%%); a rebalance that only fills node-6 moves %d (%.1f%%)\n",
mv, 100*float64(mv)/slots.Count, slots.Count/7, 100.0/7)
}فایل ring (ring/ring.go، بالاتر) Add، Remove، Locate، Replicas و wrapper به نام Bounded را دارد. برای slot ثابت از ماژول slots و جدول owner[slot] = node استفاده کنید؛ جابهجا کردن یک slot یک انتساب بهعلاوهٔ کپی داده است.
انتخاب روش
| بار کاری | پیشنهاد | تکنیک اضافه | دلیل |
|---|---|---|---|
| Memcached یا Redis بهعنوان cache، nodeها میآیند و میروند | ring از نوع ketama یا slotهای Redis Cluster | weight بر اساس حافظه، job پیشگرم | resize نباید cache را پاک کند |
| store پایدار کلید-مقدار، ۱۰ تا ۱۰۰۰ node | ring با token (Cassandra) یا slot (Redis Cluster، Dynamo strategy 3) | جایگذاری replica آگاه از rack، allocate_tokens_for_keyspace | rebalance در سطح node، پخش خرابی |
| shardهای شمارهدار، افزودن فقط از انتها | Jump hash | shard_map برای تقسیمهای بعدی | بدون حافظه، توازن کامل |
| تعداد node کم (کمتر از ۵۰) و نیاز به top-k | Rendezvous (HRW) | گونهٔ وزندار | سادهترین، بدون state |
| load balancer لایهٔ ۴/۷ با میلیونها flow | Maglev | جدول connection tracking | lookup از O(1)، مقاوم |
| load balancing با locality در cache و بار کج | ring + bounded load | hash-balance-factor از ۱۲۵ تا ۲۰۰ | node داغ را سقف میگذارد |
| تعداد ثابت shard که هرگز resize نمیشود (دیتابیس رابطهای) | Modulo روی shardهای منطقی زیاد | جدول shard_map | resize با جابهجایی shard |
| partitionهای log شبیه Kafka | Modulo روی تعداد ثابت partition | تعداد را از قبل برنامهریزی کنید | ترتیب به نگاشت کلید به partition وابسته است |
| هر چیزی که range scan میخواهد | range partitioning (نه hash) | پیشوند hash برای نقطههای داغ | hash ترتیب کلید را نابود میکند |
در معماری: از یک process تا سیستم توزیعشده
مونولیت (یک process، یک دیتابیس)
یک process و یک دیتابیس نیازی به روش جایگذاری ندارند: ردیف همانجایی است که هست. consistent hashing اول بار به شکل cache پیدا میشود: مونولیتی که یک Redis دارد از آن استفاده نمیکند؛ لحظهای که Memcached دوم را برای page cache اضافه میکنید به OPT_DISTRIBUTION از نوع consistent نیاز دارید تا رفتن به سه تا cache را پاک نکند. یک PostgreSQL منفرد با جدول hash-partitioned (MODULUS 8) سادهترین استفادهٔ درست از modulo است: تعداد partition در طراحی ثابت است و planner partitionها را prune میکند. Partitioning & Sharding in PostgreSQL را ببینید.
مونولیت ماژولار / چند دیتابیس
وقتی ماژولها دیتابیس خودشان را دارند (orders، billing، catalogue)، هر دیتابیس بهاعتبار ماژول یک shard از کل سیستم است، نه بهاعتبار کلید. اگر ماژولی از یک node بزرگتر شد، جدولهایش را با tenant id و shard_map شارد کنید: ۱۰۲۴ shard منطقی، ۴ دیتابیس فیزیکی برای شروع. router یک کلاس است (TenantShardRouter) که tenant_id را hash میکند، shard را در جدول مییابد و با DB::connection($node) اتصال را انتخاب میکند. hash tag در Redis کلیدهای یک tenant را کنار هم نگه میدارد؛ partition key در Cassandra همان tenant است.
میکروسرویس
هر سرویس مالک دادهاش است و جایگذاری را مستقل انتخاب میکند. جایی که hash از مرز سرویس عبور میکند کلید پیام است: order-service رویدادها را با key = order_id به topic کافکا با ۱۲ partition میفرستد؛ murmur2(key) % 12 partition را تعیین میکند، پس همهٔ رویدادهای یک سفارش ترتیب دارند. بالا بردن ۱۲ به ۲۴ کلیدها را جابهجا میکند، پس topicها را از قبل بزرگ بگیرید یا نسخهدار کنید. در لبه، sidecar از نوع Envoy جلوی ناوگان cache مربوط به catalogue با ring_hash و مسیر درخواست بهعنوان کلید هر محصول را روی یک cache server نگه میدارد؛ محصول داغ با bounded load یا cache محلی کنترل میشود. saga یا outbox جایی است که باید یادمان باشد هیچ روش جایگذاری atomicity بین کلیدها را نمیدهد: Distributed SQL, Consensus & 2PC را ببینید.
داده توزیعشده (replica، cache، SQL شاردشده یا توزیعشده، چندمنطقهای)
در store سبک Dynamo ring مجموعهٔ replica و سطح consistency (QUORUM، LOCAL_QUORUM) تعیین میکند چند تا از آنها باید جواب بدهند؛ read-your-writes به R + W > N نیاز دارد. هنگام تغییر عضویت rangeها در حال انتقالاند: Cassandra stream میکند، Redis ASK جواب میدهد و مدتی کلید میتواند روی دو node باشد، پس خواندن ممکن است کهنه باشد. cacheها جلوی دیتابیس مسئله را چند برابر میکنند: cache با ring-hash که یک node را از دست بدهد برشش را از دست میدهد، دیتابیس بار کامل آن برش را میبیند و thundering herd رخ میدهد؛ با request coalescing (singleflight در Go، Cache::lock / Cache::flexible در Laravel) و پیشگرم کردن محافظت کنید. چندمنطقهای: ring را برای هر منطقه نگه دارید و با پیشوند منطقه مسیریابی کنید، یا از سیستمهای مبتنی بر range (CockroachDB، Spanner) که بر اساس locality جایگذاری میکنند استفاده کنید. Replication, Read Replicas & Failover و Eventual Consistency in Database Systems را ببینید.
مسیر مقیاس: ۱x، ۱۰x، ۱۰۰x
| بار | شکل معمول | جایگذاری |
|---|---|---|
| 1x | یک PostgreSQL، یک Redis | هیچ |
| 10x | Redis Cluster با ۳ master یا ۳ Memcached با ketama؛ read replica | slot / ring؛ ۱۰۲۴ shard منطقی دیتابیس در shard_map |
| 100x | ring در Cassandra یا DynamoDB، صدها slot در Redis، لایهٔ Maglev/Envoy | token یا slot، bounded load برای hot key، replica آگاه از rack |
| 1000x | معماری cell چندمنطقهای | hash به cellها (هر cell یک stack کامل)، مسیریابی consistent در لبه |
در هر پله قاعده یکی است: تعداد partitionهای منطقی (slot، shard) را زود ثابت کنید، partition را کامل جابهجا کنید و hash و جدول مسیریابی را نسخهدار نگه دارید.
آزمایشگاه
همهچیز فقط با کتابخانهٔ استاندارد اجرا میشود. از ریشهٔ مخزن:
cd docs/snippets/database/consistent-hashing/go
gofmt -l . && go vet ./... # both silent
go run ./cmd/distribution # histograms for ring, jump, HRW, Maglev, bounded load
go run ./cmd/movement # keys moved when node 7 joins; Redis slot checkماژولها: hashutil (FNV-1a بهعلاوهٔ finalizer از نوع splitmix64)، ring (vnode، replica، bounded load)، jump، rendezvous، maglev، slots (CRC16، hash tag).
آزمایش ۱: histogram توزیع پیش و پس از افزودن node
distribution histogram را برای ۶ node چاپ میکند؛ movement node هفتم را اضافه میکند. خروجی اندازهگیریشده (۱۲۰٬۰۰۰ کلید، قطعی، خلاصهشده):
ring, 1 token(s) per node (max/mean = 1.47) node-0 27570 #### node-1 14961 ## node-3 11162 # node-5 29385 ####
ring, 256 token(s) per node (max/mean = 1.18) node-0 23622 node-3 16928 node-5 21188
jump hash (max/mean = 1.01) every node 19890 .. 20114
rendezvous (HRW) (max/mean = 1.01) every node 19867 .. 20135
maglev, table 65537 (max/mean = 1.02) every node 19773 .. 20379
skewed traffic, plain ring, 16 tokens (max/mean = 1.73) node-5 34535
skewed traffic, bounded load c=1.25 (max/mean = 1.25) node-5 25000پس از افزودن node-6، بار مورد انتظار هر node برابر 17,143 است. histogram را با هفت نام دوباره اجرا کنید تا شکل «پس از» را ببینید؛ دستور movement نشان میدهد برای رسیدن به آن چه چیزی باید جابهجا میشد:
adding node-6 to 6 nodes, 120000 keys; ideal movement = 1/7 = 14.3%
scheme moved share moved to a node other than node-6
modulo hash % n 102776 85.6% 85601
ring, 1 token(s)/node 19051 15.9% 0
ring, 16 token(s)/node 19385 16.2% 0
ring, 256 token(s)/node 18409 15.3% 0
jump hash 17073 14.2% 0
rendezvous (HRW) 17132 14.3% 0
maglev, table 65537 17564 14.6% 288
slot(foo)=12182 (CLUSTER KEYSLOT foo is 12182)آزمایش ۲: اثر token
بلوک آخر distribution بهازای هر تعداد token، ۲۰ cluster را اجرا میکند. انتظار: میانگین max/mean از 2.56 (یک token) به 1.35 (16)، 1.15 (64)، 1.10 (256) و 1.04 (1024) میرسد.
آزمایش ۳: بررسی slot در یک Redis Cluster واقعی
docker run -d --name rc -p 7000-7005:7000-7005 grokzen/redis-cluster:latest # any 6-node cluster image
redis-cli -c -p 7000 CLUSTER KEYSLOT foo # 12182
redis-cli -c -p 7000 CLUSTER KEYSLOT '{user1000}.following' # same as for {user1000}.followers
redis-cli -c -p 7000 MSET a 1 b 2 # (error) CROSSSLOT Keys in request don't hash to the same slot
redis-cli -c -p 7000 MSET '{t}a' 1 '{t}b' 2 # OK
redis-cli -p 7000 CLUSTER SLOTS | head # slot ranges per masterآزمایش ۴: مالکیت token در Cassandra
docker run -d --name c1 cassandra:5
docker exec c1 nodetool status
docker exec c1 nodetool ring | head
docker exec c1 cqlsh -e "CREATE KEYSPACE ks WITH replication={'class':'SimpleStrategy','replication_factor':1}; CREATE TABLE ks.t(k text PRIMARY KEY, v int);"
docker exec c1 nodetool getendpoints ks t some-key # the replica set of a keyبدفهمیهای رایج
| باور | واقعیت |
|---|---|
| «Consistent hashing بار را یکنواخت میکند» | جابهجایی را کمینه میکند؛ یکنواختی به token زیاد، slot، Maglev یا bounded load نیاز دارد (یک token: max/mean میانگین 2.56، بدترین 4.04) |
| «افزودن node در modulo حدود 1/n کلیدها را جابهجا میکند» | حدود n/(n+1) جابهجا میشود (85.6% برای ۶ به ۷) و بین nodeهای قدیمی هم هست |
| «Redis Cluster ring دارد» | ۱۶۳۸۴ hash slot ثابت با CRC16 mod 16384 و جدول صریح دارد |
| «partitionهای Kafka از consistent hashing استفاده میکنند» | murmur2(key) % numPartitions: افزودن partition کلیدها را دوباره نگاشت میکند |
| «hash partitioning در PostgreSQL / MySQL ارزان resize میشود» | تغییر modulus ردیفها را دوباره partition میکند |
| «virtual node بیشتر همیشه بهتر است» | Cassandra دربارهٔ هزینهٔ دسترسپذیری، repair و scan هشدار میدهد؛ ۱۶ تا ۲۵۶ معمول است |
| «replicaها N token بعدیاند» | N node فیزیکی متمایز بعدیاند |
| «Jump hash جای ring را میگیرد» | bucketها را شماره میزند، bucket دلخواه را نمیتوان حذف کرد و وزن نمیگیرد |
| «Consistent hashing hot key را حل میکند» | یک کلید روی یک node مینشیند؛ replication، شکستن کلید یا bounded load لازم است |
| «هر تابع hash کافی است» | موقعیتها avalanche خوب میخواهند: FNV-1a تنها vnodeها را خوشه میکند؛ hash() پایتون و maphash در Go در هر process فرق دارند |
| «resharding رایگان است چون فقط 1/n جابهجا میشود» | stream، cleanup، بازسازی Merkle tree و پیشگرم کردن cache هزینه دارند (Dynamo: نزدیک یک روز) |
| «sharding سمت client در Laravel failover را مدیریت میکند» | مستندات Laravel: نمیکند؛ برای دادههای cache مصرفی نگهش دارید |
چکیده (Cheat sheet)
| موضوع | چه چیزی یادتان بماند |
|---|---|
| Modulo | h % n: با تغییر n حدود n/(n+1) کلیدها جابهجا میشود |
| Ring | موقعیتهای مرتب، اولین نقطهٔ >= hash(key)، برگشت دوری؛ join حدود 1/(n+1) جابهجا میکند |
| Vnode | ۱۰۰ تا ۲۰۰ نقطه برای هر server (ketama)؛ num_tokens: 16 پیشفرض Cassandra؛ weight = token |
| Replication | N node فیزیکی متمایز بعدی در جهت عقربه؛ tokenهای همان node را رد کن |
| Hash slot | Redis Cluster: CRC16(key) mod 16384، جدول slot به node، {tag} هممکانی میآورد |
| Bounded load | سقف ceil(c x mean)، probing در جهت عقربه؛ hash-balance-factor در HAProxy بین ۱۲۵ تا ۲۰۰ |
| Jump hash | ۵ خط، بدون حافظه، bucket از 0..n-1، فقط آخری میتواند برود |
| Rendezvous | به همهٔ nodeها امتیاز بده، بیشترین برنده؛ O(n)؛ top-k = replicaها |
| Maglev | جدول اول M (65537)، permutation برای هر backend، lookup از O(1) |
| Hotspot | hash یک کلید را نمیشکند: replicate کن، کلید را بشکن، بار را سقف بگذار |
| تابع hash | پایدار بین processها، avalanche خوب: xxHash، murmur3، CRC16؛ FNV-1a به finalizer نیاز دارد |
| Laravel Redis | options.cluster = 'redis' = Cluster بومی؛ برای sharding سمت client با Predis آن را بردارید |
| Laravel Memcached | OPT_DISTRIBUTION => DISTRIBUTION_CONSISTENT + OPT_LIBKETAMA_COMPATIBLE |
| Resharding | partition جابهجا کن نه کلید؛ nodetool cleanup، redis-cli --cluster rebalance |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا hash(key) % n وقتی cache ششنفره هفتنفره میشود حدود ۸۶٪ کلیدها را دوباره نگاشت میکند؟ حیاتی
پاسخ
پاسخ: باقیمانده به پیمانهٔ ۶ و ۷ فقط برای حدود ۱ از ۷ کلید یکی است، هر hashی که باشد. حدود n/(n+1) کلیدها صاحبشان را عوض میکنند و بین nodeهای قدیمی هم جابهجا میشوند. Modulo hashing را ببینید.
۲ — در ring با یک token برای هر node، کلیدهای node حذفشده به چه کسی میرسد؟ virtual node چه چیزی را عوض میکند؟ حیاتی
پاسخ
پاسخ: node بعدی در جهت عقربه کل کمان را میگیرد و بارش دو برابر میشود. با T token کمانها بسیار و کوچکاند و مال جانشینهای متفاوتی هستند، پس بار پخش میشود. Virtual node را ببینید.
۳ — Dynamo با virtual node چطور preference list میسازد؟ تکمیلی
پاسخ
پاسخ: ring را در جهت عقربه میپیماید و اولین N node فیزیکی متمایز را برمیدارد و tokenهای nodeای را که قبلاً انتخاب شده رد میکند. Replication روی ring را ببینید.
۴ — HASH_SLOT در Redis Cluster چیست و hash tag چه میکند؟ حیاتی
پاسخ
پاسخ: CRC16(key) mod 16384؛ اگر کلید {...} با دستکم یک بایت داخلش داشته باشد فقط همان زیررشته hash میشود، پس {user1000}.following و {user1000}.followers در یک slot میافتند و در دستورهای چندکلیدی با هم قابل استفادهاند. Hash slot را ببینید.
۵ — چرا jump hash نمیتواند node شمارهٔ ۳ از ۱۰ را حذف کند؟ تکمیلی
پاسخ
پاسخ: عددی از 0 تا n-1 میدهد و نام ندارد؛ حذف bucket شمارهٔ ۳ باید bucketهای ۴ تا ۹ را دوباره شماره بزند و کلیدهایشان را جابهجا کند. فقط bucket با بالاترین شماره میتواند برود. Jump hash را ببینید.
۶ — سقف ceil(c x m / n) در bounded load چه تضمین میکند و بهایش چیست؟ تکمیلی
پاسخ
پاسخ: هیچ node بیش از c برابر میانگین بار نمیگیرد؛ بهایش تعداد جابهجایی کمی بیشتر از consistent hashing ساده (در ضریب O(1/epsilon^2) برای epsilon <= 1) و نگهداشتن یک شمارنده است. Bounded-load consistent hashing را ببینید.
۷ — در Laravel 13 چطور Redis Cluster را در برابر sharding سمت client تنظیم میکنید؟ تکمیلی
پاسخ
پاسخ: Cluster بومی پیشفرض است: options.cluster = 'redis' بهعلاوهٔ nodeهای seed در clusters.default. برای sharding سمت client (Predis) options.cluster را بردارید؛ failover ندارد و فقط برای دادههای cache مصرفی مناسب است. پیکربندی Redis Cluster در Laravel را ببینید.
۸ — از میان hash partitioning در PostgreSQL، partitioner پیشفرض Kafka و Cassandra کدام consistent hashing واقعی دارد؟ مهم
پاسخ
پاسخ: فقط Cassandra (token ring). PostgreSQL از modulus/remainder و Kafka از murmur2(key) % numPartitions استفاده میکند. رفتار هر محصول را ببینید.
۹ — یک کلید سلبریتی روی ring خوب یک node را زیر بار میبرد. سه راهکار نام ببرید. حیاتی
پاسخ
پاسخ: خواندن را به چند replica پخش کنید، کلید را بشکنید (key#0..key#7)، cache محلی یا CDN جلویش بگذارید یا از bounded-load hashing استفاده کنید تا سرریز به همسایه برود. Hotspot را ببینید.
۱۰ — چرا انتخاب تابع hash بخشی از قالب داده است؟ مهم
پاسخ
پاسخ: هر client باید موقعیت یکسان حساب کند؛ تغییر hash همهٔ کلیدها را دوباره نگاشت میکند. از hash پایدار و مستند (xxHash، murmur3، CRC16) استفاده کنید و هرگز از hash تصادفی هر process. تابع hash را ببینید.
واژهنامه
| واژه | معنی |
|---|---|
| Consistent hashing (هش سازگار) | نگاشت کلید به node طوری که تغییر عضویت فقط حدود 1/(n+1) کلیدها را جابهجا کند |
| Modulo hashing | hash(key) mod n؛ با تغییر n حدود n/(n+1) کلیدها را دوباره نگاشت میکند |
| Hash ring (حلقهٔ هش) | فضای hash خمشده به دایره؛ موقعیتها عددی مقایسه میشوند و دوریاند |
| Token | یک موقعیت روی ring سبک Dynamo که مال یک node است (اصطلاح Cassandra) |
| Virtual node (vnode، گرهٔ مجازی) | token که مثل یک server مجازی دیده میشود؛ هر node فیزیکی چند تا دارد |
num_tokens | تنظیم Cassandra: تعداد token هر node؛ پیشفرض ۱۶ |
| Preference list | فهرست مرتب nodeهای متمایز مسئول یک کلید |
| Replication factor (RF، N) | تعداد replica هر کلید |
| Hash slot | بخش ثابتی از فضای hash؛ Redis Cluster ۱۶۳۸۴ تا دارد |
| Hash tag | بخش {...} کلید Redis که فقط آن hash میشود تا کلیدها هممکان شوند |
CROSSSLOT | خطای Redis Cluster برای دستور چندکلیدی که چند slot را پوشش میدهد |
MOVED / ASK | redirectionهای Redis Cluster: دائمی در برابر هنگام مهاجرت |
MIGRATE | دستور Redis که کلید را به node دیگر میبرد؛ در resharding به کار میرود |
| Bootstrap | پیوستن node جدید به ring و stream کردن rangeهایش |
nodetool cleanup | دستور Cassandra که دادههایی را که node دیگر مالکشان نیست حذف میکند |
| Partitioner | مؤلفهٔ Cassandra که partition keyها را به token hash میکند (Murmur3Partitioner) |
| Bounded loads | Consistent hashing با سقف ceil(c x average) برای هر node |
Balance factor c | 1 + epsilon؛ در HAProxy بهصورت درصد با hash-balance-factor |
| Jump consistent hash | الگوریتم بدون حافظهٔ Lamping و Veach روی bucketهای شمارهدار |
| Rendezvous / HRW | Highest Random Weight: هر node به کلید امتیاز میدهد و بیشترین برنده است |
| Maglev hashing | consistent hash مبتنی بر جدول lookup از load balancer گوگل (اندازهٔ جدول اول M) |
| Continuum | نام ketama برای ring نقطههایش |
| Ketama | طرح hash برای clientهای memcached (۱۰۰ تا ۲۰۰ نقطه برای هر server، MD5) |
| Smoothness، spread، load | سه ویژگی سازگاری در Karger |
| Hotspot (نقطهٔ داغ) | node (یا کلید) با بار نامتناسب |
| Load balancing efficiency | mean load / max load در Dynamo |
| Avalanche | ویژگی اینکه تغییر یک بیت ورودی حدود نیمی از بیتهای خروجی را عوض کند |
| Hinted handoff | Dynamo/Cassandra: node دیگری نوشتن را برای replica خاموش نگه میدارد |
| Sloppy quorum | quorum روی N node سالم اول preference list، نه N node اول |
| Gossip | پروتکل عضویت همتابههمتا در Dynamo، Cassandra و Redis Cluster |
| Logical shard | partition کوچک ثابت، چندتا روی هر node فیزیکی، بهصورت یکجا جابهجا میشود |
shard_map | جدولی که shard منطقی را به node فیزیکی نگاشت میکند |
| Thundering herd | missهای همزمان زیاد که پس از نگاشت دوباره به دیتابیس میخورند |
hash-type consistent | HAProxy: جدول server درختی با تکرارهای زیاد هر server |
ring_hash / maglev | سیاستهای load balancing سازگار در Envoy |
OPT_LIBKETAMA_COMPATIBLE | گزینهٔ Memcached در PHP: MD5 و توزیع consistent وزندار |
Cache::tags | tagگذاری cache در Laravel؛ در Redis یک sorted set برای هر tag |
hash/fnv | hashهای FNV در کتابخانهٔ استاندارد Go (New64a) |
xxhash | hash سریع غیررمزنگاری؛ در Go github.com/cespare/xxhash/v2 و در PHP hash('xxh3') |
| Murmur2 / Murmur3 | hashهای partitionبندی Kafka / Cassandra |
| CRC16 | CRC ۱۶ بیتی که Redis Cluster برای slot استفاده میکند |
| Strategy 3 (Dynamo) | Q partition مساوی که هر node مقدار Q/S از آنها را نگه میدارد |
| vBucket | slot ثابت در Couchbase، همان ایدهٔ hash slot |
| Merkle tree | درخت hash برای anti-entropy repair؛ با تغییر rangeها باید بازسازی شود |
منابع
- Karger, Lehman, Leighton, Panigrahy, Levine, Lewin, "Consistent Hashing and Random Trees: Distributed Caching Protocols for Relieving Hot Spots on the World Wide Web", STOC 1997. PDF
- DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007, sections 4.2, 4.3, 6.2. PDF
- Lamping, Veach, "A Fast, Minimal Memory, Consistent Hash Algorithm", 2014. arXiv 1406.2294
- Mirrokni, Thorup, Zadimoghaddam, "Consistent Hashing with Bounded Loads", 2016. arXiv 1608.01350
- Eisenbud et al., "Maglev: A Fast and Reliable Software Network Load Balancer", NSDI 2016. PDF
- Thaler, Ravishankar, "A Name-Based Mapping Scheme for Rendezvous", CSE-TR-316-96. PDF; secondary: Wikipedia, Rendezvous hashing
- Redis: Redis Cluster specification
- Apache Cassandra: Dynamo architecture (token ring, vnodes), cassandra.yaml
- RJ, libketama README
- nginx:
ngx_http_upstream_modulehash directive - HAProxy: Configuration manual (
hash-type,hash-balance-factor) - Envoy: Load balancers: ring hash and Maglev
- Riak KV: Clusters
- MongoDB: Hashed Sharding
- Amazon DynamoDB: Partitions and data distribution
- PostgreSQL: Table partitioning; MySQL 8.4 (via web.archive.org): HASH partitioning; Citus: Data modeling
- Apache Kafka source:
BuiltInPartitioner.java - Go:
hash/fnv,xxhash/v2; gomemcacheselector.go - PHP: Memcached constants
- Laravel 13: Redis, Cache; framework source:
RedisTaggedCache.php,RedisTagSet.php