CAP Under a Real Partition, CP vs AP, PACELC & Tunable Consistency
"The "2 of 3" formulation was always misleading because it tended to oversimplify the tensions among properties." — Eric Brewer، CAP Twelve Years Later: How the "Rules" Have Changed، IEEE Computer، فوریهٔ ۲۰۱۲ (بازنشر InfoQ)
خلاصه (Summary): وقتی شبکهٔ بین replicaها قطع میشود، هر عملیاتی که به هر دو طرف نیاز دارد یا باید صبر کند یا بدون طرف دیگر جواب بدهد؛ CAP اسم همین انتخاب است، PACELC هزینهٔ سازگاری در یک روز عادی (تأخیر) را اضافه میکند و سازگاری تنظیمپذیر (Tunable consistency) اجازه میدهد این هزینه را برای هر درخواست بپردازید، نه برای کل دیتابیس. تمرکز (Focus): حدس Brewer در ۲۰۰۰ و اثبات Gilbert و Lynch در ۲۰۰۲ (C یعنی linearizability، A یعنی هر گره سالم پاسخ بدهد، P یعنی گمشدن دلخواه پیامها)، آنچه CAP نمیگوید (افسانهٔ CA، «دو تا از سه تا»، بدون partition انتخابی در کار نیست)، چرخهٔ عمر partition از نگاه Brewer (تشخیص، partition mode، بازیابی، جبران)، رفتار CP و AP با تنظیمهای دقیق etcd، ZooKeeper، Consul، Cassandra، DynamoDB، MongoDB، PostgreSQL، Kafka، Spanner و CockroachDB، PACELC (PA/EL، PC/EC، PA/EC، PC/EL)، quorum و R + W > N، sloppy quorum، hinted handoff و read repair، harvest و yield، split brain و fencing، و تصمیمگیری برای هر قلم داده، همراه با کد Go و Laravel و یک آزمایشگاه. هدف یادگیری (Learning goal): برای هر قلم داده در یک طراحی بتوانید بگویید خواندن و نوشتنش در هر طرف partition و در یک روز عادی چه میشود، تنظیم محصولی را که همین رفتار را میدهد انتخاب کنید، قواعد partition mode و بازیابی (از جمله جبران) را بنویسید و توضیح بدهید چرا «دیتابیس ما CP است» جواب کافی نیست.
این فصل گروه Consistency & Distributed Data را باز میکند. مالک تصمیم در سطح سیستم است: هر عملیات هنگام partition و در روز عادی به چه تضمینی نیاز دارد و کدام تنظیم آن را میدهد. خودِ مدلها (linearizability در برابر serializability، causal، read-your-writes) در Consistency Models آموزش داده میشوند؛ سازوکار replication در موتورها در Eventual Consistency in Database Systems، Replication, Read Replicas & Failover و Distributed SQL, Consensus & 2PC؛ توپولوژیها و حل تعارض در Replication Topologies؛ درونیات repair در Merkle Trees, Read Repair, Anti-Entropy & Tombstones؛ lease و fencing در Distributed Locking و Leader Election؛ دادهٔ ادغامپذیر در CRDTs؛ تجربهٔ کاربری سازگاری نهایی در Event-Driven Architecture؛ و ACID در برابر BASE در ACID vs BASE.
نقشهٔ صفحه
| دنبال چه هستید | بروید به |
|---|---|
| کل صفحه در سه جدول | همهچیز در یک دقیقه |
| چرا partition اصلاً انتخاب را تحمیل میکند | چرا وجود دارد |
| Fox و Brewer ۱۹۹۹، Brewer ۲۰۰۰، Gilbert و Lynch ۲۰۰۲، Abadi ۲۰۱۲، Kleppmann ۲۰۱۵ | از کجا آمده |
| صورت دقیق قضیه و سه تعریفش | CAP، Linearizability، Availability، Partition |
| «سیستم CA» و «دو تا انتخاب کن» | آنچه CAP نمیگوید |
| هنگام partition و بعد از آن چه کنیم | Partition mode، جبران |
| کدام محصول رد میکند و کدام واگرا میشود | CP در محصولات، AP در محصولات، Split brain و fencing |
| نیمهٔ تأخیرِ این مصالحه | PACELC |
| R + W > N، سطحهای Cassandra، sloppy quorum | Quorum، سطحهای Cassandra، Sloppy quorum |
| تنظیمهای محصولها یکییکی | etcd/ZooKeeper/Consul، MongoDB، PostgreSQL، Kafka، Spanner/CockroachDB، DynamoDB |
| پاسخ ناقص به جای خطا | Harvest و yield |
| پول در برابر لایک | تصمیم برای هر قلم داده، UX سازگاری نهایی |
| فرمولها، تنظیمها، پیامهای خطا | سازوکار |
| کد | Go، Laravel |
| حادثههای کلاسیک و راهحلشان | حل مسئلههای کلاسیک |
| کدام تنظیم کِی | انتخاب |
| از یک پردازه تا چند region | در معماری |
| خودتان اجرا کنید | آزمایشگاه |
| باورهای غلط، چکیده، خودآزمایی، واژهها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
قضیه، با تعریفهای واقعیاش (Gilbert و Lynch ۲۰۰۲).
| حرف | در اثبات یعنی | یعنی نیست |
|---|---|---|
| C (سازگاری، Consistency) | Linearizability یا atomic consistency: یک ترتیب کلی از عملیاتها که هر کدام در لحظهای بین فراخوانی و بازگشتش اثر میکند؛ خواندنی که بعد از تمامشدن یک نوشتن شروع شده، همان نوشتن یا بعدی را برمیگرداند | C در ACID (قیدها) یا «داده خراب نشده» |
| A (دسترسپذیری، Availability) | "every request received by a non-failing node in the system must result in a response" | «دسترسپذیری بالا»، uptime نود و نه درصد، یا «یک گره جواب میدهد» |
| P (تحمل partition، Partition tolerance) | رفتار درست حتی وقتی "the network will be allowed to lose arbitrarily many messages sent from one node to another" | گزینهای که بشود خاموشش کرد: شبکهها واقعاً پیام گم میکنند |
| نتیجه | هنگام partition، عملیاتی که به هر دو طرف نیاز دارد نمیتواند هم linearizable باشد و هم از هر گره زنده جواب بگیرد | «همیشه هر دو تا از C و A و P را میتوانید انتخاب کنید» |
تصمیم partition در محصولات واقعی (تنظیم پیشفرض یا رایج، سپس تنظیمی که آن را جابهجا میکند).
| محصول | هنگام partition، بهطور پیشفرض | تنظیم |
|---|---|---|
| etcd | سمت اکثریت سرویس میدهد؛ اقلیت etcdserver: request timed out / no leader برمیگرداند (CP) | خواندن --consistency=s (serializable) در اقلیت جواب میدهد، شاید کهنه |
| ZooKeeper | نوشتن به اکثریت نیاز دارد (CP)؛ خواندن را سرور متصل جواب میدهد، linearizable نیست | sync() پیش از خواندن؛ read-only mode به اقلیت اجازهٔ خواندن میدهد |
| Consul | حالت default در HTTP API به leader نیاز دارد؛ DNS از حالت stale استفاده میکند | ?consistent (یک رفتوبرگشت quorum اضافه) یا ?stale |
| Cassandra | بسته به consistency level هر درخواست: ONE جواب میدهد (AP)، QUORUM ممکن است با UnavailableException شکست بخورد (شبیه CP) | ONE، QUORUM، LOCAL_QUORUM، EACH_QUORUM، ALL، SERIAL |
| DynamoDB | خواندن eventually consistent (پیشفرض)؛ global table در حالت MREC ناهمگام تکثیر میکند و last writer wins | ConsistentRead=true؛ global table در حالت MRSC (سه Region) |
| MongoDB | primary در سمت اکثریت؛ { w: "majority" } پیشفرض رایج است؛ اقلیت primary ندارد | write concern w و wtimeout؛ read concern local/majority/linearizable؛ read preference |
| PostgreSQL | streaming replication ناهمگام پیشفرض است: primary commit میکند و standbyها عقب میمانند | synchronous_standby_names + synchronous_commit (remote_apply، on، remote_write، local، off) |
| Kafka | acks=all (پیشفرض producer) منتظر ISR میماند؛ ISR میتواند تا خود leader کوچک شود (min.insync.replicas=1 پیشفرض) | min.insync.replicas=2؛ unclean.leader.election.enable=false (پیشفرض) |
| Spanner، CockroachDB | اکثریت Paxos/Raft برای هر range یا split: سمت اقلیت از دسترس خارج است (CP) | چیدمان replicaها؛ خواندن از follower یا کهنه، تازگی را با نزدیکی معاوضه میکند |
دستهبندی PACELC (Abadi ۲۰۱۲، تنظیمهای پیشفرض).
| دسته | هنگام partition | در غیر این صورت (کار عادی) | نمونهها از مقاله و مستندات |
|---|---|---|---|
| PA/EL | دسترسپذیر میماند | تأخیر کم به جای سازگاری | پیشفرض Dynamo، Cassandra و Riak؛ خواندن eventually consistent در DynamoDB |
| PC/EC | سازگار میماند | سازگاری به جای تأخیر | VoltDB/H-Store، Megastore، BigTable، HBase؛ Spanner، CockroachDB، etcd (طبق مستنداتشان) |
| PA/EC | دسترسپذیر میماند (نوشتههای primary قدیمی بعداً rollback میشوند) | خواندن و نوشتن سازگار | MongoDB، طبق دستهبندی Abadi در ۲۰۱۲ |
| PC/EL | سازگاری بیشتر از حالت عادی کم نمیشود، دسترسپذیری میافتد | تأخیر به جای سازگاری | Yahoo PNUTS |
این تصویر کل قضیه در یک آزمایش است: سه replica و یک برش بین n0/n1 و n2. با quorum اکثریت، گره اقلیت درخواست را رد میکند (زنده است ولی به معنای CAP دسترسپذیر نیست)؛ با خواندن و نوشتن تکreplica، هر دو طرف جواب میدهند، واگرا میشوند و هنگام بهبود (heal) یکی از مقدارهای تأییدشده با last-write-wins دور ریخته میشود. شبیهسازی Go در بخش Go دقیقاً همین را بازتولید میکند.
چرا وجود دارد
تکثیر (Replication) برای این است که داده از خرابی یک ماشین جان سالم به در ببرد و نزدیک کاربرانش باشد. به محض اینکه دو نسخه داریم، هر بهروزرسانی باید به هر دو برسد و شبکهٔ بینشان قابل اعتماد نیست: لینک قطع میشود، سوئیچ اشتباه پیکربندی میشود، یک توقف GC یا صف پر، heartbeat را آنقدر عقب میاندازد که شبیه خرابی به نظر برسد. replicaای که صدای همتایانش را نمیشنود، برای درخواستی که به آنها وابسته است فقط دو گزینهٔ صادقانه دارد: صبر کند (یا رد کند) و درست بماند، یا با آنچه دارد جواب بدهد و خطر اشتباه را بپذیرد. گزینهٔ سومی که هر دو را داشته باشد وجود ندارد.
| ترجیح سازگاری (CP برای این عملیات) | ترجیح دسترسپذیری (AP برای این عملیات) |
|---|---|
| سمت اقلیت خطا یا timeout برمیگرداند | هر replica زنده جواب میدهد |
| هر پاسخ linearizable است | پاسخ ممکن است کهنه باشد؛ نوشتنهای همزمان تعارض پیدا میکنند |
| ناوردا (invariant)ها مثل موجودی ≥ 0 یا یکتایی نام کاربری خودبهخود حفظ میشوند | ناورداها باید بعد از partition بازگردانده شوند (جبران) |
| به اکثریت، leader یا lease نیاز دارد | به حل تعارض نیاز دارد: last-write-wins، merge، CRDT |
| هر روز هزینهٔ تأخیر دارد (رفتوبرگشت quorum) | هزینهٔ کار آشتیدادن و طراحی UX دارد |
| مناسب پول، موجودی انبار، قفل، پیکربندی، نامهای یکتا | مناسب سبد خرید، لایک، فید، presence، تلهمتری |
تصویر روزمرهای که در کل صفحه به کار میرود: دو شعبهٔ بانک که یک دفتر حساب را تلفنی با هم شریکاند. وقتی خط قطع میشود، هر شعبه یا تا وصلشدن دوباره پول نقد نمیدهد (سازگار، دسترسناپذیر) یا روی نسخهٔ خودش از دفتر پول میدهد و بعداً حساب را صاف میکند (دسترسپذیر، ناسازگار). جواب واقعی Brewer در مثال ATM بین این دو است: تا یک سقف کوچک پول بده، همهچیز را یادداشت کن و اگر حساب بعداً جور درنیامد، کارمزد اضافهبرداشت بگیر. همین جواب میانه، یعنی partition mode بهعلاوهٔ جبران، کاری است که سیستمهای واقعی میکنند.
سه بدفهمی رایج، از همین اول
- «دو تا از سه تا را انتخاب کن.» P را انتخاب نمیکنید؛ partition برایتان اتفاق میافتد. و وقتی partition نیست، CAP اجازهٔ داشتن هم C و هم A را میدهد. Brewer در ۲۰۱۲: "because partitions are rare, there is little reason to forfeit C or A when the system is not partitioned."
- «دیتابیس ما CP است، پس سازگاریم.» بیشتر پیکربندیهای واقعی به معنای دقیق نه CP هستند نه AP. Kleppmann نشان میدهد replication تکleader با خواندن از follower "neither CAP-consistent nor CAP-available" است و ZooKeeper بهطور پیشفرض خواندن linearizable نمیدهد. عملیات و تنظیم را دستهبندی کنید، نه محصول را.
- «سازگاری نهایی (Eventual consistency) بهای دسترسپذیری است.» بسیاری از سیستمها در روز عادی و به خاطر تأخیر eventually consistent هستند، نه به خاطر partition. Abadi: "it is wrong to assume that DDBSs that reduce consistency in the absence of any partitions are doing so due to CAP-based decision-making." این همان نیمهٔ ELC در PACELC است.
از کجا آمده
Year Who / what What it added
1 1999 Fox & Brewer, "Harvest, Yield, and "Strong CAP Principle ... Pick at most 2"; harvest vs yield
Scalable Tolerant Systems" (HotOS)
2 2000 Brewer, PODC keynote (July 19) "You can have at most two of these properties for any
shared-data system"; ACID vs BASE as a spectrum
3 2002 Gilbert & Lynch, SIGACT News Formal proof: asynchronous model, atomic (linearizable)
object, availability, arbitrary message loss
4 2007 DeCandia et al., Dynamo (SOSP) (N,R,W) quorums, sloppy quorum, hinted handoff, (3,2,2)
5 2010 Abadi, blog "Problems with CAP" Latency/consistency trade-off named; PACELC first sketched
6 2012 Brewer, "CAP Twelve Years Later" Partition mode, recovery, compensation; CA is probabilistic
6 2012 Abadi, IEEE Computer PACELC: PA/EL, PC/EC, PA/EC, PC/EL
6 2012 Gilbert & Lynch, "Perspectives on CAP" CAP as one case of safety vs liveness
7 2015 Kleppmann, blog and arXiv "A Critique of "Please stop calling databases CP or AP"; delay-sensitivity
the CAP Theorem"
8 2017 Brewer, "Spanner, TrueTime & the CAP Theorem" "technically a CP system", "effectively CA"Fox و Brewer (۱۹۹۹). نخستین صورت مکتوب: "Strong CAP Principle. Strong Consistency, High Availability, Partition-resilience: Pick at most 2." در همان مقاله آن را نرم هم میکنند ("a Weak CAP Principle which we have yet to characterize precisely") و harvest و yield را بهعنوان جواب مهندسی معرفی میکنند: به جای هیچ جوابی، جواب ناقص بده.
Brewer در PODC ۲۰۰۰. اسلایدی با عنوان «The CAP Theorem» میگوید "Theorem: You can have at most two of these properties for any shared-data system" و برای هر گوشه مثال میآورد: دیتابیسهای تکسایت و خوشهای برای «forfeit partitions»، دیتابیسهای توزیعشده، قفل توزیعشده و پروتکلهای اکثریت برای «forfeit availability» ("Make minority partitions unavailable")، و Coda، web caching و DNS برای «forfeit consistency». همان سخنرانی ACID را در برابر BASE ("Basically Available, Soft-state, Eventual consistency") گذاشت و گفت "But I think it's a spectrum".
Gilbert و Lynch (۲۰۰۲). حدس را با تعریفهای دقیق به قضیه تبدیل کردند (بخش CAP) و با استدلال دو گروهی اثباتش کردند: اگر همهٔ پیامهای بین گروه G1 و G2 گم شوند، نوشتنی در G1 و سپس خواندنی در G2 نمیتواند آن نوشتن را برگرداند. نسخهٔ partially synchronous را هم ثابت کردند و دربارهٔ سیستمهای quorum نوشتند: "if certain failure patterns occur, then the liveness condition is weakened and the service no longer returns responses."
Abadi (وبلاگ ۲۰۱۰، مقالهٔ ۲۰۱۲). دید سیستمهایی که معمولاً «AP» نامیده میشوند همیشه سازگاری را کنار میگذارند، نه فقط هنگام partition، و دلیلش تأخیر است. PACELC شاخهٔ «else» را اضافه میکند.
Brewer (۲۰۱۲). توصیه را برای مهندسان بازنویسی کرد: CAP دربارهٔ timeout است ("a partition is a time bound on communication")، partition باید آگاهانه مدیریت شود ("detect the start of a partition"، "enter an explicit partition mode"، "initiate partition recovery") و اشتباههای partition mode با جبران (Compensation) اصلاح میشوند.
Kleppmann (۲۰۱۵). نشان داد که تعریفهای دقیق تقریباً هیچ سیستمی را تمیز دستهبندی نمیکنند و پیشنهاد کرد به جایش وابستگی تأخیر عملیات به تأخیر شبکه را بسنجیم. پست وبلاگش کوتاهترین اصلاحیه برای تبلیغات «CP در برابر AP» است.
فهرست مفاهیم
هر بلوک یک ترتیب ثابت دارد: به زبان ساده، باور غلط رایج، تعریف، timeline یا جریان درخواست، سناریوی واقعی، رفتار محصولات و راه درست.
CAP، دقیق بیانشده حیاتی
به زبان ساده: اگر replicaها نتوانند با هم حرف بزنند، replicaای که درخواستی وابسته به طرف دیگر میگیرد یا باید صبر کند یا بدون آن جواب بدهد. صبرِ بیپایان یعنی دسترسناپذیری؛ جوابدادن بدون طرف دیگر ممکن است غلط باشد.
بدفهمی رایج: «CAP میگوید دیتابیس توزیعشده همیشه فقط دو تا از سه ویژگی را دارد.» قضیه دربارهٔ اجراهایی است که در آنها پیام گم میشود. بدون گمشدن پیام، سیستم میتواند هم سازگار و هم دسترسپذیر باشد (Gilbert و Lynch، بخش 3.2.2: "If there are no partitions, it is clearly possible to provide atomic, available data").
تعریف: قضیهٔ ۱ Gilbert و Lynch: در مدل شبکهٔ ناهمگام (asynchronous) نمیتوان شیء خواندن/نوشتنی ساخت که در همهٔ اجراهای منصفانه، از جمله آنهایی که پیام گم میشود، هم availability و هم atomic consistency را تضمین کند. قضیهٔ ۲ همین را برای مدل partially synchronous که گرهها ساعت دارند تکرار میکند: "It is still impossible to have an always available, atomic data object when arbitrary messages may be lost". نتیجهٔ 1.1 نکتهٔ ظریف است: چون گره نمیتواند پیام گمشده را از پیام کُند تشخیص بدهد، حتی نمیشود قول داد فقط در اجراهای بدون گمشدن سازگار باشیم و همیشه هم دسترسپذیر بمانیم.
The proof in four lines (two groups G1 = {n0, n1}, G2 = {n2}; every message between them is lost)
1 client A -> n0: write(x = 1) n0 must answer (availability), so it acknowledges without G2
2 client B -> n2: read(x) starts after step 1 finished
3 n2 cannot have heard of the write all G1 -> G2 messages were lost
4 n2 must answer (availability) it returns the old value: not linearizable. Contradiction.سناریوی واقعی: سرویس پرداختی روی دو availability zone که لینک بین zoneها ۴۰ ثانیه قطع میشود؛ control plane کوبرنتیز که یک گره را از اکثریت etcd از دست میدهد؛ اپ موبایلی که آفلاین کار میکند (یک partition بینهایت طولانی بین گوشی و سرور)؛ دیتابیس چند-region هنگام قطع کابل.
رفتار محصولات: هر محصول تکثیرشده برای هر عملیات انتخاب میکند. سیستمهای مبتنی بر اکثریت (etcd، نوشتن در ZooKeeper، Consul، Spanner، CockroachDB، primary در MongoDB) در سمت اقلیت رد میکنند؛ storeهای سبک Dynamo در سطحهای پایین (ONE در Cassandra، r=1 در Riak) در هر دو طرف جواب میدهند.
راه درست: در سند طراحی برای هر عملیات بنویسید: «هنگام partition، در سمت اقلیت، این عملیات (الف) تا N میلیثانیه صبر میکند و شکست میخورد، (ب) از دادهٔ محلی جواب میدهد، یا (ج) با ریسک محدود جواب میدهد». بعد تنظیم را انتخاب کنید.
سازگاری در CAP همان linearizability است حیاتی
به زبان ساده: سیستم طوری رفتار میکند که انگار یک نسخه از داده وجود دارد و هر عملیات در یک لحظه بین شروع و پایانش انجام شده. وقتی کلاینتی مقداری را دید، دیگر هیچکس نباید مقدار قدیمیتری ببیند.
بدفهمی رایج: «سازگاری CAP همان C در ACID است» یا «تراکنش serializable یعنی CAP-consistent». سازگاری ACID یعنی قیدها برقرارند؛ serializability یعنی تراکنشها معادل یک ترتیب سریالیاند، نه لزوماً ترتیب زمان واقعی. Kleppmann: "Consistency in CAP actually means linearizability, which is a very specific (and very strong) notion of consistency." SSI در PostgreSQL سریالپذیری میدهد، نه linearizability (Kleppmann). پانویس Gilbert و Lynch هم همین تمایز را میگذارد.
تعریف: Gilbert و Lynch 2.1: "there must exist a total order on all operations such that each operation looks as if it were completed at a single instant." پیامدش: "any read operation that begins after a write operation completes must return that value, or the result of a later write operation." خانوادهٔ کامل مدلها در Consistency Models است.
Client A Client B Linearizable?
1 write(x = 2) starts
2 write(x = 2) returns ok
3 read(x) starts and returns 1 NO: the read began after the write completed
---- versus ----
1 write(x = 2) starts
2 read(x) starts and returns 1 yes: the write had not completed
3 write(x = 2) returns okسناریوی واقعی: lease رهبری که در etcd ذخیره شده (اگر خواندن کهنه بگوید lease آزاد است، دو leader خواهیم داشت)؛ بررسی یکتایی نام کاربری؛ نقشهٔ صندلی که دو نفر نباید یک صندلی را رزرو کنند؛ feature flagی که وقتی API گفت خاموش است باید همهجا خاموش باشد.
| محصول | مسیر linearizable | بهطور پیشفرض linearizable نیست |
|---|---|---|
| etcd | همهٔ عملیات جز watch ("etcd ensures linearizability for all other operations by default") | خواندن --consistency=s؛ watchها |
| ZooKeeper | نوشتن؛ خواندنی که پیش از آن sync() آمده | خواندن ساده (از سرور متصل) |
| MongoDB | readConcern: "linearizable" روی primary، یک سند، همراه نوشتن w: "majority" | local، majority (majority-committed ولی شاید عقب) |
| Cassandra | lightweight transaction (شرط IF) با SERIAL / LOCAL_SERIAL | خواندن و نوشتن quorum (Kleppmann: موارد مرزی sloppy quorum و read repair) |
| Spanner | هر تراکنش read-write و strong read (external consistency) | stale read با مرز زمانی |
| PostgreSQL | خواندن روی primary | خواندن روی standby (مگر با remote_apply و مسیریابی دقیق) |
راه درست: linearizability را فقط برای عملیاتی بخواهید که واقعاً لازمش دارند (قفل، یکتایی، موجودی، انتخاب leader) و برای همان فراخوانیها از مسیر linearizable صریح محصول استفاده کنید.
دسترسپذیری در CAP حیاتی
به زبان ساده: هر گره زندهای که درخواستی میگیرد، دیر یا زود جواب میدهد، حتی اگر نتواند با هیچکس حرف بزند.
بدفهمی رایج: «خوشهٔ ما ۹۹٫۹۹٪ uptime دارد، پس به معنای CAP دسترسپذیر است.» دسترسپذیری CAP از یک جهت خیلی سختگیرتر است (هر گره سالم، نه فقط «سرویس») و از جهت دیگر خیلی سستتر (هیچ مهلتی ندارد). Kleppmann: "Many so-called "highly available" (i.e. low downtime) systems actually do not meet this definition of availability." هر دیتابیس تکleader در این آزمون رد میشود: کلاینتی که از leader جدا افتاده نمیتواند بنویسد.
تعریف: Gilbert و Lynch 2.2: "every request received by a non-failing node in the system must result in a response." و اضافه میکنند "it puts no bound on how long the algorithm may run before terminating". Brewer در ۲۰۱۲ مهلت را برمیگرداند: تصمیم partition سرِ یک timeout گرفته میشود.
Three replicas, partition {n0, n1} | {n2}, client talks to n2
1 t=0 client -> n2: write(x)
2 t=0+ n2 sends to n0, n1; messages are lost
3 t=500ms n2's timeout fires
4 CP choice: n2 returns an error -> not CAP-available (node is alive and refused)
5 AP choice: n2 stores x and returns ok -> available; consistency is now at riskسناریوی واقعی: سبد خریدی که باید در هر خرابی «افزودن به سبد» را بپذیرد (انگیزهٔ Dynamo: "customers should be able to view and add items to their shopping cart even if disks are failing, network routes are flapping, or data centers are being destroyed by tornados")؛ صفحهٔ وضعیت سرویس؛ endpoint دریافت تلهمتری.
راه درست: دسترسپذیری را بهصورت SLO با مهلت و دامنه بیان کنید («p99 زیر ۳۰۰ میلیثانیه از هر region با از دست رفتن یک region»)، نه بهصورت یک حرف از CAP؛ ببینید SLAs, SLOs, SLIs & Error Budgets.
Partition: واقعاً چیست حیاتی
به زبان ساده: partition هر وضعیتی است که در آن بعضی replicaها نتوانند بهموقع به بقیه پیام برسانند. قطع کابل، firewall اشتباه، سوئیچ خراب، گره پربار که بعد از timeout جواب میدهد، توقف GC: از بیرون همه یکسان دیده میشوند.
بدفهمی رایج: «partition رویداد نادری است که در آن شبکه تمیز دو نیم میشود.» اغلب جزئی است (A به B میرسد، B به C، ولی A به C نه)، یکطرفه است (پیام A به B میرسد ولی برعکس نه) و کوتاه است. Brewer: "there is no global notion of a partition, since some nodes might detect a partition, and others might not." و "a partition is a time bound on communication": اگر timeout را کم کنید، partition بیشتری میبینید.
تعریف: Gilbert و Lynch آن را گمشدن پیام مدل میکنند: "any pattern of message loss can be modeled as a temporary partition separating the communicating nodes at the exact instant the message is lost." در عمل، گره وقتی timeoutش سر میرسد partition را اعلام میکند.
A one-sided partition (A -> B works, B -> A is dropped by a firewall rule)
1 A: heartbeat -> B B receives it, thinks A is fine
2 B: ack -> A dropped
3 A: no ack within 1 s A declares B dead, B does not declare A dead
4 A (if leader) steps down; B keeps sending writes to A -> each side has a different viewسناریوی واقعی: یک availability zone در AWS با گمشدن بخشی از بستهها؛ توقف طولانی GC روی leader در ZooKeeper که followerها را به انتخاب leader جدید وامیدارد؛ گرههای کوبرنتیز که API server را گم میکنند ولی podهایشان همچنان سرویس میدهند؛ لینک WAN با utilisation صددرصد. چقدر رایج است؟ Brewer در ۲۰۱۷ برای علتهای حادثه در Spanner گزارش میدهد: "The Network category, under 8%, is where partitions and networking configuration problems appear."
راه درست: timeoutها را آشکارساز partition بدانید و آنها را آگاهانه برای هر عملیات تنظیم کنید (Timeouts, Retries & Jitter)؛ برای partition جزئی و یکطرفه طراحی کنید، نه فقط برش تمیز؛ آن را آزمایش کنید (Chaos Engineering).
آنچه CAP نمیگوید: افسانهٔ CA و «دو تا انتخاب کن» حیاتی
به زبان ساده: برای سیستم توزیعشده نمیتوانید «CA» انتخاب کنید، چون نمیتوانید انتخاب کنید که partition نداشته باشید. فقط انتخاب میکنید وقتی رخ داد چه شود.
بدفهمی رایج: «خوشهٔ رابطهای تکسایت یک سیستم CA است.» Fox و Brewer «CA without P» را فهرست کرده بودند (تراکنش توزیعشده "can only do so in the absence of a network partition")، ولی Brewer در ۲۰۱۲ اصلاحش میکند: "If the choice is CA, and then there is a partition, the choice must revert to C or A. It is best to think about this probabilistically: choosing CA should mean that the probability of a partition is far less than that of other systemic failures."
تعریف: «CA» فقط بهعنوان یک گزارهٔ احتمالاتی معنا دارد: partition آنقدر نادر است، درون یک دیتاسنتر یا روی شبکهٔ خصوصی Google، که کاربران میتوانند نادیدهاش بگیرند. Brewer در ۲۰۱۷ دربارهٔ Spanner: "It is technically a CP system"، ولی میتواند ادعای «effectively CA» را توجیه کند چون دسترسپذیریاش به اندازهٔ کافی بالاست ("better than 5 9s" در داخل Google).
The "pick two" story vs what actually happens in a CA-labelled system
1 Normal day: two-node cluster, synchronous replication looks C and A
2 Link between nodes fails
3 Option 1: both keep accepting writes now AP (split brain risk)
4 Option 2: one stops (quorum, fencing, manual) now CP
5 There is no option 3 "CA" just meant "we had not decided"سناریوی واقعی: جفت دوگرهی PostgreSQL با failover خودکار و بدون witness که standby را ارتقا میدهد در حالی که primary قدیمی هنوز نوشتن میپذیرد؛ MySQL فعال-فعال در دو دیتاسنتر با برچسب «CA» در اسلایدهای معماری؛ جفت primary/replica در Redis پشت Sentinel با فقط دو Sentinel.
راه درست: هیچوقت برای سیستم چندگرهی «CA» ننویسید؛ بنویسید کدام طرف به کار ادامه میدهد (اکثریت، یک witness، region اصلیِ تعیینشده) و طرف دیگر چه میکند. تعداد رأیدهنده را فرد بگیرید یا witness بگذارید (MRSC در DynamoDB از "two replicas and one witness" استفاده میکند).
چرخهٔ عمر partition: تشخیص، partition mode، بازیابی حیاتی
به زبان ساده: partition را حالتی بدانید که سیستم عمداً واردش میشود، قواعد خودش را دارد و با یک روال تمیزکاری از آن بیرون میآید.
بدفهمی رایج: «CP یا AP یک ویژگی ایستاست؛ چیزی برای طراحی نیست.» توصیهٔ اصلی Brewer در ۲۰۱۲ برعکس است: "The key idea is to manage partitions very explicitly, including not only detection, but also a specific recovery process and a plan for all of the invariants that might be violated during a partition."
تعریف: سه گام (Brewer ۲۰۱۲): "detect the start of a partition"، "enter an explicit partition mode that may limit some operations" و "initiate partition recovery when communication is restored". در partition mode دو راهبرد هست: "limit some operations, thereby reducing availability" یا "record extra information about the operations that will be helpful during partition recovery". بازیابی (Partition recovery) دو کار دارد: دوباره سازگارکردن وضعیت، و جبران اشتباههایی که هنگام partition رخ داده.
نمودار بالا همین چرخه را نشان میدهد: وضعیت S در کار عادی، شروع partition بین دو عملیات، تشخیص با timeout در هر گره بهطور جداگانه، دو طرف که در partition mode به S1 و S2 میرسند و لاگ مینویسند، و بازیابی که لاگها را در S' ادغام میکند و ناورداهای شکسته را جبران میکند.
ATM example (Brewer 2012), balance 100, stand-in limit k = 200
1 t0 ATM -> bank: authorise(150) normal mode: bank says ok, balance 100 is not enough -> refused
2 t1 link fails; ATM times out partition detected -> stand-in (partition mode)
3 t2 withdraw 150 net withdrawn 150 <= 200 -> approved, logged
4 t3 withdraw 100 150 + 100 > 200 -> refused (bounded risk)
5 t4 deposit 20 always allowed (cannot break balance >= 0), logged
6 t5 link restored recovery: replay log, balance 100 - 150 + 20 = -30
7 t6 invariant broken compensation: overdraft fee, repayment requestسناریوی واقعی: ATMها و کارتخوانها (سقف آفلاین)؛ سیستمهای فروشگاهی با اتصال ناپایدار؛ check-in هواپیمایی که overbook میکند و پای گیت جبران میکند (مثال overbooking در Brewer)؛ اپهای offline-first که ویرایشها را در صف نگه میدارند؛ سیستم انباری که هنگام قطع WAN سفارشها را جمع میکند و بعداً موجودی را آشتی میدهد.
| محصول / الگو | امکان partition mode |
|---|---|
| Riak، Cassandra | پذیرش نوشتن در هر دو طرف؛ ثبت نسخهها (vector clock در Riak، timestamp در Cassandra) |
| DynamoDB global tables MREC | هر Region به پذیرش نوشتن ادامه میدهد؛ هنگام آشتی "last writer wins" |
| همگامسازی سبک CouchDB، اپهای آفلاین | نوشتن محلی با تاریخچهٔ revision؛ تعارضها بعد از sync نمایان میشوند |
| کارتخوانها، ATMها | floor limit / سقف stand-in، لاگ محلی، ارسال دستهای |
| Sagaها | تراکنشهای جبرانی (Saga Pattern) |
راه درست: برای هر ناوردا تصمیم بگیرید: «هنگام partition حفظش کن (عملیات را محدود کن)» یا «ریسکش را بپذیر و بعداً بازگردان (لاگ کن و جبران کن)». بستهٔ atm در Go دقیقاً همین روال است.
جبران و ناورداها مهم
به زبان ساده: اگر بگذارید هر دو طرف کار کنند، بعضی قاعدهها میشکنند؛ جبران (Compensation) اقدام کسبوکاری است که بعداً خسارت را جبران میکند: بازپرداخت، کارمزد، ایمیل عذرخواهی، لغو سفارش تکراری.
بدفهمی رایج: «last-write-wins یا merge در CRDT تعارض را حل میکند، پس چیزی برای جبران نیست.» merge وضعیت را درست میکند؛ اقدامهای بیرونیشده (پول نقدی که داده شده، ایمیلی که رفته، صندلیای که قولش داده شده) را برنمیگرداند. Brewer: "Recovering from externalized mistakes typically requires some history about externalized outputs."
تعریف: عملیات جبرانی یک ناوردا را بازمیگرداند یا یک اثر را معکوس میکند و آن را کسبوکار تعریف میکند، نه دیتابیس. Brewer: "designers must create compensating operations that both restore an invariant and more broadly correct an externalized mistake." عملیات جابهجاپذیر (commutative) همگرایی وضعیت را خودکار میکنند ("Restoring state is easy because the operations are commutative") و جبران آنچه را همگرایی نمیتواند، پوشش میدهد.
Duplicate order during a partition (Brewer's example, as a sequence)
1 Side A: order #A1 for user 7, charge card externalised (money moved)
2 Side B: order #B1 for user 7, same cart, charge externalised again
3 Recovery: logs merged, two orders with identical content within 30 s
4 Decide: intentional or duplicate? (idempotency key would have told us)
5 Compensate: cancel #B1, refund, email "we charged you twice by mistake and refunded"سناریوی واقعی: overbooking هواپیمایی؛ کارتهایی که بعد از طوفان retry دو بار شارژ شدهاند؛ دو انبار که آخرین واحد را ارسال میکنند؛ دو کاربر که یک نام کاربری را در دو region ثبت میکنند (یکی باید تغییر نام بدهد)؛ feature flagی که در هر طرف متفاوت تغییر کرده.
راه درست: هر جا میشود اقدام بیرونی را تا روشنشدن حقیقت عقب بیندازید ("This is another reason to delay risky operations")؛ به هر عملیات کلید idempotency بدهید تا تکراریها قابل تشخیص باشند (API Idempotency)؛ لاگ عملیات نگه دارید، نه فقط وضعیت؛ و جبران را همراه خود feature بنویسید.
رفتار CP در محصولات واقعی حیاتی
به زبان ساده: تنظیم CP فقط جایی کار میکند که اکثریت (یا leader، یا صاحب lease) در دسترس باشد؛ همهجای دیگر به جای جواب احتمالاً غلط، خطا برمیگرداند.
بدفهمی رایج: «CP یعنی سیستم هنگام partition از کار میافتد.» فقط سمت اقلیت، و فقط برای عملیاتی که به اکثریت نیاز دارند. سمت اکثریت به سرویس ادامه میدهد. Fox و Brewer: "replicas and majority voting to get PC (the minority is unavailable)."
تعریف: عملیاتی CP پیکربندی شده که به تأیید quorumی نیاز دارد که با هر quorum دیگر اشتراک دارد (اکثریت، Raft/Paxos، یا R + W > N با عضویت سختگیرانه) و وقتی نتواند آن را بگیرد شکست میخورد.
etcd, 3 members, partition {m1, m2} | {m3}, client on m3
1 client -> m3: put /lock/leader = svc-b
2 m3 is a follower; it forwards to the leader m1 lost
3 after the request timeout "etcdserver: request timed out" (gRPC Unavailable)
4 client -> m3: get /lock/leader (default linearizable) needs consensus -> fails or times out
5 client -> m3: get /lock/leader --consistency=s answers from m3's local store: possibly staleسناریوی واقعی: API serverهای کوبرنتیز با اکثریت etcd کار میکنند و گرههای zone جداافتاده نمیتوانند وضعیت خوشه را عوض کنند؛ topic در Kafka با min.insync.replicas=2 که وقتی فقط leader مانده نوشتن را رد میکند (NOT_ENOUGH_REPLICAS)؛ replica set در MongoDB که primary قدیمی در سمت اقلیت کنار میرود؛ rangeهای CockroachDB که اکثریت Raftشان آن طرف برش است.
| محصول | قاعدهٔ quorum | رفتار سمت اقلیت | خطایی که میبینید |
|---|---|---|---|
| etcd | اکثریت Raft | نوشتن و خواندن linearizable شکست میخورند | etcdserver: request timed out، etcdserver: no leader |
| ZooKeeper | اکثریت (ZAB) برای نوشتن | نوشتن شکست میخورد؛ خواندن همچنان از سرور محلی | connection loss / انقضای session در کلاینت |
| Consul | اکثریت Raft | خواندن default و consistent شکست میخورد؛ stale کار میکند | HTTP 500 با "No cluster leader" (معمول) |
| MongoDB | اکثریت primary انتخاب میکند | primary نیست؛ نوشتن شکست میخورد؛ خواندن primaryPreferred/secondary کار میکند | NotWritablePrimary (10107)، PrimarySteppedDown (189) |
| Kafka | ISR، min.insync.replicas | نوشتن با acks=all وقتی ISR کوچک است رد میشود | NOT_ENOUGH_REPLICAS (19) |
| CockroachDB | اکثریت Raft برای هر range | rangeهای بدون اکثریت دسترسناپذیرند | دستور معطل میماند، بعد خطای retry/timeout |
| Spanner | اکثریت Paxos برای هر split | splitهای بدون اکثریت دسترسناپذیرند | UNAVAILABLE / deadline exceeded (gRPC معمول) |
| PostgreSQL sync rep | standbyهای همگامِ نامبرده | commit منتظر standby میماند، شاید برای همیشه | canceling wait for synchronous replication due to user request هنگام لغو |
راه درست: تعداد فردی رأیدهنده در سه failure domain بگذارید تا از دست رفتن هر domain قابل تحمل باشد؛ به کلاینتها timeout و خطای روشن برای نمایش بدهید («موقتاً در دسترس نیست، دوباره تلاش کنید»)؛ هر جا میشود کلاینتها را به سمت اکثریت هدایت کنید (Load Balancing).
رفتار AP در محصولات واقعی حیاتی
به زبان ساده: تنظیم AP از هر replicaای که در دسترس است جواب میدهد و اختلافها را بعداً درست میکند.
بدفهمی رایج: «AP یعنی اصلاً سازگاری نیست.» تنظیمهای AP معمولاً سازگاری نهایی بهعلاوهٔ تضمینهای مشخص session میدهند و از طریق hinted handoff، read repair و anti-entropy همگرا میشوند؛ چیزی که نمیتوانند بدهند linearizability هنگام partition است.
تعریف: عملیاتی AP پیکربندی شده که با تأیید هر replica در دسترس موفق میشود (R یا W برابر ۱، sloppy quorum، خواندن محلی)، واگرایی را میپذیرد و تعارض را با یک قاعده حل میکند (last write wins، siblingها، merge در CRDT).
Cassandra RF=3, partition {r1, r2} | {r3}, writes at ONE on both sides
1 client X -> r1: UPDATE cart SET items = items + {'book'} ONE: r1 acks; r2 gets it; r3 gets a hint later
2 client Y -> r3: UPDATE cart SET items = items + {'pen'} ONE: r3 acks
3 client Y -> r3: SELECT items (ONE) {'pen'} (does not see 'book')
4 heal: hints replayed, read repair, repair {'book','pen'} set elements merge per element
5 but for a plain column: last write wins by timestamp one of two values is goneسناریوی واقعی: سبد خرید Amazon (در Dynamo: "an “add to cart” operation is never lost"، هرچند آیتمهای حذفشده ممکن است برگردند)؛ لایک و شمارندهٔ بازدید؛ presence (نقطههای «آنلاین»)؛ دریافت تلهمتری IoT؛ DNS (که Brewer زیر «forfeit consistency» آورده بود).
| محصول | تنظیم AP | سازوکار همگرایی | قاعدهٔ تعارض |
|---|---|---|---|
| Dynamo (مقاله) | sloppy quorum، (3,2,2) رایج، W=1 برای بیشترین دسترسپذیری | hinted handoff، anti-entropy با Merkle tree | vector clock؛ کلاینت siblingها را merge میکند |
| Cassandra | ONE، LOCAL_ONE، ANY | hint، read repair، nodetool repair (Merkle tree) | last write wins برای هر ستون با timestamp |
| Riak KV | r و w کمتر از quorum؛ sloppy quorum پیشفرض (PR = PW = 0) | hinted handoff، read repair، active anti-entropy | vector clock / sibling یا LWW |
| DynamoDB | خواندن eventually consistent؛ global table در MREC | تکثیر داخلی "typically within a second or less" | "last writer wins" بین Regionها |
| Consul | خواندن ?stale و DNS | رسیدن به لاگ Raft | ندارد (فقط خواندن) |
| ZooKeeper | read-only mode (از 3.4.0) در اقلیت | پیوستن دوباره به quorum | ندارد (فقط خواندن) |
راه درست: دادهٔ AP را ادغامپذیر کنید (set، counter، CRDT: CRDTs)؛ روی دادهٔ AP خواندن-تغییر-نوشتن نکنید؛ کهنگی را در UI نشان بدهید؛ و repair را زمانبندیشده اجرا کنید (Merkle Trees, Read Repair, Anti-Entropy & Tombstones).
Split brain و fencing مهم
به زبان ساده: split brain یعنی دو گره هر دو خیال میکنند leader هستند و هر دو نوشتن میپذیرند. fencing روشی است که جلوی آسیبزدن leader قدیمی را میگیرد.
بدفهمی رایج: «انتخاب leader تضمین میکند فقط یک leader داریم.» تضمین میکند از دید اکثریت در هر term حداکثر یک leader باشد؛ leader قدیمیای که خبر را نشنیده هنوز میتواند کار کند. MongoDB خودش مینویسد: "two nodes in a replica set may transiently believe that they are the primary, but at most, one of them will be able to complete writes with { w: "majority" } write concern."
تعریف: fencing به هر نوشتن یک توکن صعودی (term، epoch، revision در lease) میچسباند تا storage نوشتن با توکن قدیمیتر را رد کند؛ یا گره قدیمی را فیزیکی جدا میکند (STONITH). جزئیات در Distributed Locking و Leader Election.
Old primary P1 on the minority side, new primary P2 elected on the majority
1 P1 (term 5) still believes it is primary accepts write w=1 from a client on its side
2 P2 (term 6) accepts writes on majority side
3 with w:majority, P1 cannot get 2 of 3 acks the client gets a write concern error or timeout
4 with w:1, P1 acknowledges the write is later rolled back when P1 rejoins
5 storage with fencing: rejects any write tagged term 5 after it has seen term 6سناریوی واقعی: دو primary در PostgreSQL بعد از اینکه ابزار failover یک standby را بدون fence کردن primary قدیمی ارتقا داد؛ failover در Redis Sentinel که کلاینتها هنوز در master قدیمی مینویسند؛ «leader» یک cron که صورتحساب شبانه را دو بار اجرا میکند؛ unclean leader election در Kafka که replica عقبافتاده را انتخاب میکند.
راه درست: نوشتن اکثریتی (w: "majority"، acks=all + min.insync.replicas، Raft) تا leader کهنه نتواند تأیید بدهد؛ توکن fencing روی اثرهای بیرونی؛ lease کوتاهتر از timeout آشکارساز خرابی؛ تعداد فرد رأیدهنده.
PACELC: مصالحه وقتی هیچ چیز خراب نیست حیاتی
به زبان ساده: CAP فقط دربارهٔ روزهای بد حرف میزند. در روزهای عادی هم سازگاری هزینه دارد: صبرکردن برای replicaهای دیگر. PACELC هر دو سؤال را میپرسد.
بدفهمی رایج: «اگر partition نادر است، CAP مهم نیست و همهچیز را میتوانیم داشته باشیم.» partition نادر است ولی تأخیر تکثیر همیشگی است. Abadi: CAP "is only relevant in the arguably rare case of a network partition"، در حالی که مصالحهٔ تأخیر "is present at all times during system operation".
تعریف: Abadi ۲۰۱۲: "if there is a partition (P), how does the system trade off availability and consistency (A and C); else (E), when the system is running normally in the absence of partitions, how does the system trade off latency (L) and consistency (C)?" و یادآوری میکند که بخش ELC "only applies to systems that replicate data".
نمودار، PACELC را بهصورت درخت تصمیم نشان میدهد: سؤال اول اینکه هنگام partition چه چیزی کنار گذاشته میشود (PA یا PC) و سؤال دوم اینکه در کار عادی (else) تأخیر یا سازگاری (EL یا EC)؛ محصولات طبق تنظیم پیشفرضشان در چهار خانه نشستهاند و کادر پایین یادآوری میکند که سیستمهای تنظیمپذیر برای هر درخواست خانه عوض میکنند.
Same write, no partition, replicas in Frankfurt (coordinator), Frankfurt, Virginia
1 EL setting (W=1) ack after the local replica writes ~1 ms
2 EC setting (W=2 of 3) ack after the second Frankfurt replica ~2 ms
3 EC setting, if the second-nearest replica is in Virginia ~85 ms (one transatlantic round trip)
4 EC setting (W=3) ack after every replica ~90 ms, and fails if any one is downسناریوی واقعی: store پروفایل کاربری جهانی (PA/EL کافی است: عکس پروفایل میتواند یک ثانیه قدیمی باشد)؛ دفتر کل بانک (PC/EC)؛ فید اجتماعی (PA/EL)؛ store پیکربندی (PC/EC)؛ PNUTS: نسخهٔ master نزدیک کاربر، نسخههای دور ناهمگام (PC/EL).
| دسته | دستهبندی Abadi (۲۰۱۲) | معنایش برای طراحی شما |
|---|---|---|
| PA/EL | "The default versions of Dynamo, Cassandra, and Riak are PA/EL systems" | سریع و دسترسپذیر؛ merge و UX کهنگی را طراحی کنید |
| PC/EC | "Fully ACID systems such as VoltDB/H-Store and Megastore are PC/EC"؛ BigTable، HBase | هر روز تأخیر quorum و دسترسناپذیری اقلیت را میپردازید |
| PA/EC | "MongoDB can be classified as a PA/EC system" | در حالت عادی سازگار؛ بعد از برش، نوشتههای تأییدشده توسط primary قدیمی ممکن است rollback شوند |
| PC/EL | "PNUTS is a PC/EL system" | در حالت عادی سریع، هنگام partition بدتر نمیشود؛ به جایش دسترسپذیری میافتد |
راه درست: هر عملیات را دو بار دستهبندی کنید («هنگام partition: رد یا جواب؟»، «حالت عادی: منتظر چه کسی؟») و برای شاخهٔ E عدد بگذارید، از Latency Budgets & Tail Latency. بستهٔ pacelc در Go تأخیر شاخهٔ E را برای هر سطح Cassandra حساب میکند.
سازگاری تنظیمپذیر و quorum: R + W > N حیاتی
به زبان ساده: با N نسخه، اگر نوشتن منتظر W تا از آنها بماند و خواندن از R تا بپرسد و R + W بزرگتر از N باشد، هر مجموعهٔ خواندن دستکم یک replica مشترک با هر مجموعهٔ نوشتن دارد، پس خواندن میتواند آخرین نوشتن تأییدشده را ببیند.
بدفهمی رایج: «R + W > N یعنی linearizability.» همپوشانی میدهد، نه linearizability: نوشتنهای همزمان، sloppy quorum، نوشتن شکستخوردهای که نیمه اعمال شده و رقابت در read repair هنوز میتوانند تاریخچهٔ غیر linearizable بسازند. Abadi: سیستمهای سبک Dynamo "cannot achieve full consistency as defined by Gilbert and Lynch, even if R + W > N". Kleppmann حذفهایی که زنده میشوند و کمشدن تعداد replicaها از W را علتها میشمارد.
تعریف: Dynamo: "R is the minimum number of nodes that must participate in a successful read operation. W is the minimum number of nodes that must participate in a successful write operation. Setting R and W such that R + W > N yields a quorum-like system." تأخیر "is dictated by the slowest of the R (or W) replicas". پیکربندی رایج Dynamo برابر (N,R,W) = (3,2,2) بود.
در نیمهٔ بالای نمودار، مجموعهٔ نوشتن (A و B) و مجموعهٔ خواندن (B و C) روی B همپوشانی دارند؛ در نیمهٔ پایین، C از دسترس خارج است و یک گره جانشین (D) نوشتن را با hint «برای C» میپذیرد و وقتی C برگشت آن را تحویل میدهد؛ همینجاست که sloppy quorum تضمین همپوشانی را از دست میدهد.
N=3. Which (R, W) pairs overlap, and what each survives
1 R=1 W=1 1+1=2 not > 3 fastest; reads may miss writes survives 2 down (each op)
2 R=1 W=3 1+3=4 > 3 fast reads; every write needs all three writes fail with 1 down
3 R=3 W=1 4 > 3 fast writes; reads need all three reads fail with 1 down
4 R=2 W=2 4 > 3 balanced; the usual QUORUM/QUORUM survives 1 down for both
5 R=1 W=2 3 not > 3 majority writes, local reads: stale reads possible on the minorityسناریوی واقعی: QUORUM/QUORUM در Cassandra برای حسابهای کاربری؛ نوشتن ONE و خواندن ALL برای لاگ پرنوشتنی که بهندرت خوانده میشود؛ LOCAL_QUORUM در هر region برای سرویسی که جهانی مستقر شده؛ bucketهای Riak با n_val: 5, r: 3, w: 3.
راه درست: R و W را از نیاز عملیات و بودجهٔ خرابیاش انتخاب کنید: Survives(N, k) = N − k replica میتوانند برای عملیاتی که k تأیید لازم دارد غایب باشند. برای هر چیزی که واقعاً linearizability لازم دارد (compare-and-set، یکتایی) از مسیر اجماع استفاده کنید (LWT با SERIAL در Cassandra، etcd، primary در SQL).
سطحهای سازگاری Cassandra حیاتی
به زبان ساده: به جای انتخاب عدد R و W، هر درخواست در Cassandra سطحی مثل ONE یا QUORUM را نام میبرد و coordinator منتظر همان تعداد پاسخ replica میماند.
بدفهمی رایج: «ONE فقط روی یک replica مینویسد.» مستندات Cassandra: "Write operations are always sent to all replicas, regardless of consistency level. The consistency level simply controls how many responses the coordinator waits for before responding to the client."
تعریف: سطحهای Cassandra "are a version of Dynamo’s R + W > N consistency mechanism". با replication factor (RF) در هر دیتاسنتر:
| سطح | پاسخهای لازم | کاربرد معمول |
|---|---|---|
ONE | "Only a single replica must respond." | خواندن/نوشتن سریع دادهٔ ادغامپذیر |
TWO، THREE | دو / سه replica | نادر؛ دوام بیشتر بدون اکثریت |
QUORUM | "A majority (n/2 + 1) of the replicas must respond" در همهٔ دیتاسنترها | خواندن و نوشتنِ نسبتاً قوی در یک region |
LOCAL_QUORUM | اکثریت replicaهای دیتاسنتر coordinator | سرویس چند-region: "reads are guaranteed to see the latest write from within the same datacenter" |
EACH_QUORUM | اکثریت در هر دیتاسنتر | نوشتنی که باید پیش از تأیید در همهٔ regionها باشد |
ALL | همهٔ replicaها | تقریباً هرگز؛ یک replica خاموش درخواست را شکست میدهد |
LOCAL_ONE | یک replica، هرگز در دیتاسنتر دور | کمترین تأخیر برای خواندن محلی |
ANY | یک replica "or the coordinator may store a hint"؛ فقط نوشتن | بیشترین دسترسپذیری نوشتن، ضعیفترین دوام |
SERIAL / LOCAL_SERIAL | فاز Paxos در lightweight transaction (شرط IF) | compare-and-set، یکتایی |
Two datacenters, RF eu=3 us=3 (6 replicas), coordinator in eu; no failures (output of the Go pacelc package)
1 LOCAL_ONE needs 1 -> waits 1ms, survives 5 replicas down
2 LOCAL_QUORUM needs 2 -> waits 2ms, survives 4 replicas down (but not the loss of 2 eu replicas)
3 QUORUM needs 4 -> waits 85ms, at least one transatlantic response
4 EACH_QUORUM needs 4 -> waits 88ms, 2 in eu and 2 in us
5 ALL needs 6 -> waits 90ms, survives 0 replicas downسناریوی واقعی: اپ پیامرسانی که در هر region با LOCAL_QUORUM مینویسد و میخواند (read-your-writes برای کاربرانی که خانهشان آن region است)؛ پرچم تقلبی که باید پیش از پرداخت در همهٔ regionها باشد (EACH_QUORUM)؛ INSERT ... IF NOT EXISTS برای نام کاربری (LWT با SERIAL).
راه درست: cqlsh> CONSISTENCY LOCAL_QUORUM; برای یک session، برای هر دستور در driverها (gocql.LocalQuorum در gocql) و QUORUM را از مسیرهای داغ چند-region دور نگه دارید مگر رفتوبرگشت بینregion را بپذیرید. بررسی عمیق: Cassandra & ScyllaDB.
Sloppy quorum، hinted handoff و read repair مهم
به زبان ساده: وقتی replica اصلی یک کلید در دسترس نیست، sloppy quorum به گره دیگری اجازه میدهد نوشتن را از طرف او با یک یادداشت («این مال C است») بپذیرد؛ وقتی C برگشت، صاحب یادداشت آن را تحویل میدهد. read repair replicaهای کهنهای را که هنگام خواندن دیده میشوند درست میکند.
بدفهمی رایج: «sloppy quorum همچنان همپوشانی R + W > N را تضمین میکند.» نمیکند: تأییدهای W ممکن است از جانشینها بیاید و خواندن بعدی از replicaهای اصلی میتواند تا تحویل hint آن نوشتن را نبیند. این بهای دسترسپذیری است.
تعریف: Dynamo: "does not enforce strict quorum membership and instead it uses a “sloppy quorum”; all read and write operations are performed on the first N healthy nodes from the preference list". جانشین replica دارای hint را "in a separate local database that is scanned periodically" نگه میدارد و وقتی مقصد برگشت تحویلش میدهد. Riak این failover را "sloppy quorum" مینامد و با PR/PW خاموشش میکند: "Setting PR and/or PW to non-zero values produces a mode of operation called strict quorum." Cassandra hint ذخیره میکند ولی فقط در ANY آن را جزو consistency level حساب میکند. read repair و anti-entropy بهترینتلاشاند ("These techniques are only best-effort"، مستندات Cassandra)؛ repair با Merkle tree همگرایی را تضمین میکند.
Dynamo-style N=3, preference list for key k: A, B, C, D ...; C is down
1 put(k, v): coordinator sends to A, B and D (first 3 healthy) W=2 met by A and B (or A and D)
2 D stores v with hint "for C"
3 get(k) with R=2 from A, C (C just came back, hint not yet sent) if A is slow, R could be C + B ... C is stale
4 D detects C is up, sends v, deletes its copy hinted handoff
5 a read that sees different versions writes back the newest read repairسناریوی واقعی: سبد خریدی که باید هنگام خرابی یک rack نوشتن بپذیرد؛ دریافت IoT هنگام restartهای پیاپی؛ bucketهای Riak با pw=2 برای سفارشها (سختگیر) و sloppy پیشفرض برای sessionها.
راه درست: hintها را برای پنجرهٔ محدود نگه دارید (max_hint_window در Cassandra، پیشفرض سه ساعت) و repair کامل را در مهلت tombstone اجرا کنید؛ برای دادهای که خواندن-تغییر-نوشتن میشود quorum سختگیر را ترجیح بدهید؛ ببینید Merkle Trees, Read Repair, Anti-Entropy & Tombstones.
خواندن linearizable در برابر serializable در etcd، ZooKeeper و Consul مهم
به زبان ساده: سرویسهای هماهنگی برای نوشتن CP هستند، ولی بیشترشان اجازه میدهند برای هر خواندن انتخاب کنید: «از اکثریت بپرس» (درست، کُندتر، در اقلیت شکست میخورد) یا «از گرهای که به آن وصلم بپرس» (سریع، در اقلیت کار میکند، شاید کهنه).
بدفهمی رایج: «ZooKeeper CP است، پس خواندنش linearizable است.» خواندن در ZooKeeper را سروری جواب میدهد که کلاینت به آن وصل است. مستندات هشدار میدهند که کلاینتها ممکن است "Simultaneously Consistent Cross-Client Views" را فرض کنند در حالی که ZooKeeper آن را نمیدهد؛ "Client B should call the sync() method from the ZooKeeper API method before it performs its read."
تعریف: etcd: "By default, Range is linearizable; it reflects the current consensus of the cluster. For better performance and availability, in exchange for possible stale reads, a serializable range request is served locally without needing to reach consensus with other nodes in the cluster." به واژه دقت کنید: «serializable read» در etcd یعنی خواندن محلیِ عضو، شاید کهنه، نه سطح جداسازی serializable در SQL. سه حالت Consul: default ("strongly consistent in almost all cases")، consistent ("requires that a leader verify with a quorum of peers that it is still leader")، stale ("allows any server to handle the read regardless of whether it is the leader"؛ "Consul DNS queries use stale mode by default").
etcd, partition {m1, m2} | {m3}, value /cfg/flag changed to "on" on the majority side
1 etcdctl --endpoints=m3 get /cfg/flag timeout (needs consensus)
2 etcdctl --endpoints=m3 get /cfg/flag --consistency=s "off" (stale, but answered)
3 etcdctl --endpoints=m1 get /cfg/flag "on"
4 watch on m3 no events until m3 rejoins| سرویس | خواندن linearizable | خواندن سریع / دسترسپذیر | مرز کهنگی |
|---|---|---|---|
| etcd | پیشفرض (--consistency=l) | --consistency=s، clientv3.WithSerializable() | ذکر نشده |
| ZooKeeper | sync() و سپس خواندن | خواندن ساده؛ read-only mode در اقلیت | «tens of seconds» (تضمین Timeliness) |
| Consul | ?consistent | ?stale (و DNS بهطور پیشفرض) | "generally consistent to within 50 milliseconds of the leader, though there is no upper limit" |
راه درست: خواندن linearizable برای قفل، بررسی leader و هر چیزی که پشتش تصمیم نوشتن میآید؛ خواندن serializable/stale برای داشبورد، cache کشف سرویس و DNS؛ و هرگز با خواندن کهنه تصمیم نگیرید چه کسی قفل را دارد.
Write concern و read concern در MongoDB حیاتی
به زبان ساده: write concern میگوید پیش از گفتن «ok» چند عضو باید نوشتن را داشته باشند؛ read concern میگوید دادهای که میخوانید تا چه حد باید commit شده باشد. این دو با هم تعیین میکنند MongoDB برای عملیات شما CP رفتار کند یا نه.
بدفهمی رایج: «w: "majority" بهتنهایی خواندن را سازگار میکند.» خواندن در سطح پیشفرض local میتواند دادهای برگرداند که بعداً rollback میشود و خواندن majority اگر به secondary عقبافتاده برود، هنوز میتواند از آخرین نوشتن خودتان عقب باشد. linearizability به نوشتن w: "majority" و خواندن "linearizable" روی primary نیاز دارد.
تعریف: مستندات MongoDB: "{ w: "majority" } is the default write concern for most MongoDB deployments" (یعنی w:majority؛ در بعضی چیدمانهای دارای arbiter پیشفرض { w: 1 } میشود). wtimeout انتظار را محدود میکند: بدون آن، اگر concern دستنیافتنی باشد "the write operation will block indefinitely" و با آن، نوشتن خطای write concern برمیگرداند "even if the required write concern will eventually succeed" (داده برگردانده نمیشود). سطحهای read concern: local، available، majority، linearizable، snapshot. linearizable: فقط روی primary، یک سند با فیلتر یکتا، و "Always use maxTimeMS with linearizable read concern in case a majority of data bearing members are unavailable."
3-member replica set P-S-S; P is cut off with one client
1 client -> P: insert {w: 1} ok (acknowledged by P alone)
2 majority side elects S1 as new primary
3 P steps down when it notices it lost the majority
4 P rejoins: its unreplicated write is rolled back (written to the rollback directory)
5 same with {w: "majority", wtimeout: 2000}: P cannot reach 2 of 3 -> write concern error after 2 s
6 find({_id: 5}).readConcern("linearizable").maxTimeMS(10000) on P -> MaxTimeMSExpired, never stale| تنظیم | قول | رفتار هنگام partition |
|---|---|---|
w: 1 | primary آن را دارد | نوشتههای تأییدشده ممکن است بعد از برش rollback شوند |
w: "majority" (+ j: true) | اکثریت آن را دارد (journalشده وقتی writeConcernMajorityJournalDefault برابر true است) | primary قدیمی نمیتواند تأیید بدهد |
readConcern: "local" | هرچه این عضو دارد | میتواند دادهای بخواند که بعداً rollback میشود |
readConcern: "majority" | دادهٔ majority-committed در نقطهٔ majority-commit عضو | هرگز rollback نمیشود؛ شاید کهنه |
readConcern: "linearizable" | همهٔ نوشتنهای majority که پیش از شروع خواندن تأیید شدهاند را منعکس میکند | به جای جواب کهنه شکست میخورد (با maxTimeMS) |
read preference nearest / secondary | هر عضو | در اقلیت جواب میدهد، کهنه (maxStalenessSeconds ≥ 90) |
راه درست: هر جا پول یا state machine در کار است نوشتن اکثریتی با wtimeout؛ خواندن linearizable با maxTimeMS فقط برای معدود خواندنهایی که تصمیمی میگیرند؛ session با causal consistency برای read-your-writes؛ nearest برای فید. MongoLedger در Laravel نسخهٔ CP را پیاده میکند.
synchronous_commit و تکثیر همگام در PostgreSQL حیاتی
به زبان ساده: primary در PostgreSQL بهطور پیشفرض بدون انتظار برای هیچ standbyای میگوید «commit شد». تکثیر همگام (Synchronous replication) COMMIT را منتظر یک یا چند standby نامبرده نگه میدارد و synchronous_commit تعیین میکند آنها تا کجا باید پیش رفته باشند.
بدفهمی رایج: «تکثیر همگام یعنی standbyها همیشه تازهترین داده را نشان میدهند.» با synchronous_commit = on، standby WAL را flush کرده ولی شاید هنوز اعمال نکرده، پس خواندن روی standby میتواند کهنه باشد؛ فقط remote_apply منتظر قابلمشاهدهشدن میماند. و تکثیر همگام primary را برای نوشتن CP میکند: اگر standbyها در دسترس نباشند، commitها منتظر میمانند.
تعریف: synchronous_commit: "Valid values are remote_apply, on (the default), remote_write, local, and off." با تنظیمبودن synchronous_standby_names، on منتظر flush روی standby، remote_write منتظر نوشتن در OS آن، remote_apply تا تغییر "visible to queries on the standby(s)" شود ("In simple cases, this allows for load balancing with causal consistency")، local فقط برای flush محلی، و off حتی برای آن هم نه (crash ممکن است commitهای اخیر را از بین ببرد، ولی هرگز خراب نمیکند). synchronous_standby_names صورتهای FIRST num_sync (...) (اولویتدار) و ANY num_sync (...) (quorum) را میپذیرد. هشدار: وقتی همه را لازم بدانید، commitها "may never be completed if any one of the synchronous standbys should crash".
-- Primary: quorum commit, any 1 of 2 standbys must confirm
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (standby_a, standby_b)';
SELECT pg_reload_conf();
-- Which standbys are synchronous right now?
SELECT application_name, state, sync_state, replay_lag
FROM pg_stat_replication;
-- Per transaction: money waits for visibility on a standby, likes do not wait at all
BEGIN;
SET LOCAL synchronous_commit TO 'remote_apply';
UPDATE wallets SET balance = balance - 80 WHERE id = 7 AND balance >= 80;
COMMIT;
BEGIN;
SET LOCAL synchronous_commit TO OFF;
INSERT INTO post_likes (post_id, user_id, created_at) VALUES (42, 7, now()) ON CONFLICT DO NOTHING;
COMMIT; synchronous_standby_names = 'standby_a' (one required), standby_a is partitioned away
1 client: COMMIT primary flushes locally, waits for standby_a
2 ... waits ... CP: no acknowledgement without the standby
3 operator cancels the query (pg_cancel_backend) WARNING: canceling wait for synchronous replication due to user request
4 DETAIL: The transaction has already committed locally, but might not have been replicated to the standby.
5 the transaction is NOT rolled back cancelling the wait is not an abortسناریوی واقعی: دیتابیس پرداخت با ANY 1 (a, b) در دو zone؛ read-your-writes روی standbyها با remote_apply برای سرویس پروفایل؛ نوشتنهای تحلیلی با synchronous_commit = off؛ چیدمان تکstandby که وقتی دیسک standby پر شد همهٔ نوشتنها را منجمد کرد.
راه درست: همیشه نامزدهای standby بیشتری از تعداد لازم نام ببرید (ANY 1 (a, b))، pg_stat_replication.sync_state را پایش کنید، synchronous_commit را برای هر تراکنش بر اساس قلم داده تنظیم کنید و به یاد داشته باشید که انتظار لغوشده دادهٔ commitشده ولی تکثیرنشده باقی میگذارد.
acks، min.insync.replicas و unclean leader election در Kafka مهم
به زبان ساده: producer در Kafka انتخاب میکند پیش از «فرستاده شد» چند replica باید رکورد را داشته باشند؛ topic حداقل تعداد replica همگام را انتخاب میکند که زیر آن نوشتن را رد میکند؛ و خوشه انتخاب میکند وقتی همهٔ replicaهای خوب رفتهاند، replica عقبافتاده حق leader شدن دارد یا نه.
بدفهمی رایج: «acks=all یعنی همهٔ replicaها.» یعنی همهٔ replicaهای همگام (in-sync)، و مجموعهٔ همگام میتواند تا خود leader کوچک شود. با پیشفرض min.insync.replicas=1، acks=all میتواند با یک broker تأیید شود.
تعریف: acks در producer: 0، 1، all (= -1، پیشفرض)؛ all "guarantees that the record will not be lost as long as at least one in-sync replica remains alive." min.insync.replicas (پیشفرض ۱): وقتی "the current ISR set contains fewer than min.insync.replicas members, then the producer will raise an exception (either NotEnoughReplicas or NotEnoughReplicasAfterAppend)". دستور مستند: "replication factor of 3, set min.insync.replicas to 2, and produce with acks of "all"." unclean.leader.election.enable (پیشفرض false): انتخاب replica خارج از ISR "may result in data loss"؛ سند طراحی آن را "a simple tradeoff between availability and consistency" مینامد.
Topic RF=3, min.insync.replicas=2, producer acks=all; brokers b1 (leader), b2, b3
1 b2 and b3 partitioned from b1; ISR shrinks to {b1}
2 producer -> b1: produce rejected: NOT_ENOUGH_REPLICAS (19) -> CP for writes
3 with min.insync.replicas=1 accepted by b1 alone; lost if b1 dies before b2/b3 catch up
4 b1 dies; b2 was not in ISR
5 unclean.leader.election.enable=false partition offline until an ISR member returns (C over A)
6 unclean.leader.election.enable=true b2 becomes leader; records only b1 had are gone (A over C)سناریوی واقعی: topic رویدادهای سفارش که نباید رکورد از دست بدهد (RF 3، min.insync.replicas=2، acks=all، producer idempotent)؛ topic متریک که uptime را ترجیح میدهد (acks=1)؛ خوشهای که دو broker از دست داده و اپراتوری که باید دربارهٔ فعالکردن unclean election تصمیم بگیرد.
راه درست: برای رویدادهای کسبوکاری RF 3، min.insync.replicas=2، acks=all، enable.idempotence=true و unclean election خاموش؛ بررسی عمیق در Kafka in Depth و Delivery Guarantees.
Spanner، TrueTime و CockroachDB: «effectively CA» مهم
به زبان ساده: Spanner و CockroachDB سیستم CP هستند: هر تکه داده در یک گروه اجماع زندگی میکند و طرفی که اکثریت ندارد متوقف میشود. Spanner ساعتهای بسیار دقیقی اضافه میکند تا خواندن قوی و ترتیب جهانی ارزان شود، و شبکهٔ Google partition را آنقدر نادر میکند که کاربران آن را همیشه در دسترس فرض میکنند.
بدفهمی رایج: «Spanner قضیهٔ CAP را شکست داد.» Brewer در ۲۰۱۷: "The purist answer is “no” because partitions can happen and in fact have happened at Google, and during (some) partitions, Spanner chooses C and forfeits A. It is technically a CP system."
تعریف: TrueTime به هر سرور یک بازهٔ زمانی با عدمقطعیت محدود میدهد؛ Spanner به هر تراکنش "a timestamp that reflects the instant at which Spanner considers it to have occurred" میدهد و عدمقطعیت را صبر میکند (commit wait) تا timestampها ترتیب زمان واقعی را رعایت کنند: external consistency، که در آن "the system behaves as if all transactions run sequentially". تیم CockroachDB خلاصه میکند: "In Spanner’s case, Google mentions an upper bound of 7ms"، در حالی که NTP "somewhere between 100ms and 250ms" میدهد؛ پس "While Spanner always waits after writes, CockroachDB sometimes retries reads" (restart به خاطر عدمقطعیت) و "If the configured maximum offset is exceeded by any node, it self-terminates." تکثیر در CockroachDB: "The number of failures that can be tolerated is equal to (Replication factor - 1)/2."
Spanner commit with TrueTime (simplified)
1 TT.now() = [earliest, latest], width ~ a few ms
2 assign commit timestamp s = latest
3 Paxos: replicate to a majority of the split (minority side: unavailable)
4 commit wait: until TT.now().earliest > s then release locks and acknowledge
5 any transaction that starts after the ack gets a larger timestamp -> external consistencyسناریوی واقعی: دفترهای مالی و موجودی جهانی که در آنها چند میلیثانیه commit wait از مدیریت تعارض چند-region بهتر است؛ جدولهای چند-region در CockroachDB با locality از نوع REGIONAL BY ROW تا گروه اجماع نزدیک کاربرانش بماند؛ follower read برای تحلیل.
راه درست: replicaها را طوری بچینید که اکثریتِ دادهٔ داغ در یک کلانشهر باشد (تأخیر EC کم) و در عین حال از دست رفتن یک zone را تحمل کند؛ هر جا تازگی مهم نیست از stale/follower read استفاده کنید؛ در CockroachDB همگامسازی ساعت را یک وابستگی production بدانید. جزئیات موتور: Distributed SQL, Consensus & 2PC.
DynamoDB: ConsistentRead و global tableهای MREC و MRSC مهم
به زبان ساده: درون یک Region برای هر خواندن بین خواندن eventually consistent ارزان و خواندن strongly consistent انتخاب میکنید؛ بین Regionها برای هر جدول بین تکثیر ناهمگام با last-writer-wins و تکثیر همگام سهRegionی انتخاب میکنید.
بدفهمی رایج: «DynamoDB یک سیستم AP است.» خواندن strongly consistent تکRegion وجود دارد (ConsistentRead=true) و global table در حالت MRSC تضمین میکند "Strongly consistent read operations on any MRSC replica always return the latest version of an item". با این حال پیشفرض eventual است: "Eventually consistent is the default read consistent model for all read operations."
تعریف: خواندن eventually consistent "are half the cost of strongly consistent reads"؛ خواندن از GSI و stream همیشه eventually consistent است. MREC (پیشفرض global table): تکثیر ناهمگام "typically within a second or less" و حل تعارض با "last writer wins". MRSC: "must be deployed in exactly three Regions"، سه replica یا دو replica و یک witness؛ نوشتن روی آیتمی که جای دیگر در حال تغییر است با ReplicatedWriteConflictException شکست میخورد و قابل retry است؛ RPO صفر؛ تأخیر بیشتر برای نوشتن و خواندن قوی.
Global table, user 7 updates profile in eu-west-1, reads in us-east-1 500 ms later
1 MREC: write acked in eu-west-1 (local latency)
2 MREC: us-east-1 strongly consistent read may return the old profile (Region-local strong only)
3 MREC: concurrent edit in us-east-1 last writer wins; one edit silently lost
4 MRSC: write waits for another Region higher latency (PC/EC)
5 MRSC: concurrent edit elsewhere ReplicatedWriteConflictException -> retryسناریوی واقعی: store نشست روی MREC (از دست رفتن یک ویرایش قابل قبول است)؛ جدول اعتبار یا موجودی روی MRSC؛ کاتالوگ محصول که با خواندن eventually consistent و نصف هزینه خوانده میشود.
راه درست: ConsistentRead: true (ConsistentRead *bool در AWS SDK for Go v2) فقط برای خواندنهایی که باید آخرین نوشتن را ببینند؛ MREC بهعلاوهٔ بهروزرسانی idempotent و جابهجاپذیر برای sessionها و سبدهای تکثیرشدهٔ جهانی؛ MRSC برای دادهای که هرگز نباید بین Regionها واگرا شود.
Harvest و yield مهم
به زبان ساده: به جای «جواب یا خطا»، با بخشی از داده جواب بدهید. yield یعنی چند درصد درخواستها جواب میگیرند؛ harvest یعنی هر جواب چقدر کامل است.
بدفهمی رایج: «دسترسپذیری صفر و یکی است.» Fox و Brewer: "In the presence of faults there is typically a tradeoff between providing no answer (reducing yield) and providing an imperfect answer (maintaining yield, but reducing harvest)."
تعریف: "yield, which is the probability of completing a request, and harvest, which measures the fraction of the data reflected in the response, i.e. the completeness of the answer to the query." مثال مقاله: "in a 100-node cluster a single-node fault reduces the harvest by 1%". بعضی برنامهها harvest کمتر را نمیپذیرند (خوانش دودویی یک حسگر)؛ جستوجو، پیشنهاد و تجمیعها میپذیرند.
Search over 100 shards, 3 shards on the far side of a partition
1 Option yield-first: return results from 97 shards, flag "partial": harvest 97%, yield 100%
2 Option harvest-first: wait/timeout for all 100, return 503: harvest 100% of nothing, yield drops
3 Option per item: orders page = must be complete (harvest 100%), recommendations = 97% is fineسناریوی واقعی: نتیجهٔ ناقص در Elasticsearch وقتی shardها شکست میخورند ("timed_out": true، _shards.failed)؛ داشبوردی که پنلهای regionهای در دسترس را نشان میدهد و بقیه را خاکستری میکند؛ صفحهٔ محصولی که ویجت «دیگران این را هم خریدند» را حذف میکند؛ نتیجهٔ «good-enough» در Dean و Barroso (Latency Budgets & Tail Latency).
راه درست: پاسخ را به بخشهای لازم و اختیاری بشکنید؛ به بخش اختیاری مهلت کوتاه بدهید؛ پاسخ ناقص را صریح علامت بزنید؛ الگوهای graceful degradation در Bulkheads & Graceful Degradation.
تصمیم برای هر قلم داده: پول در برابر لایک حیاتی
به زبان ساده: یک برنامه انواع زیادی داده دارد که هزینهٔ غلطبودنشان فرق میکند. CP یا AP، و EC یا EL را برای هر نوع انتخاب کنید، نه یک بار برای کل دیتابیس.
بدفهمی رایج: «Cassandra را انتخاب کردیم، پس AP هستیم» (یا «PostgreSQL را انتخاب کردیم، پس سازگاریم»). Brewer: "the choice between C and A can occur many times within the same system at very fine granularity; not only can subsystems make different choices, but the choice can change according to the operation or even the specific data or user involved."
تعریف: برای هر قلم داده سؤالهای تعیینکننده اینهاست: یک جواب غلط چه هزینهای دارد، عملیات قابل merge یا جبران هست یا نه، اقدام بیرونیشده است یا نه، و کاربر چه تأخیری را تحمل میکند.
One checkout request touching four items, during a cross-zone partition
1 cart contents AP: accept on the local side, merge as a set user keeps shopping
2 stock reservation CP: needs the majority; minority -> "try again" no overselling
3 payment CP + idempotency key; externalised -> never guess no double charge
4 "recently viewed" AP/EL: local replica, may be a minute old nobody notices| قلم داده | انتخاب هنگام partition | انتخاب در حالت عادی | نمونهٔ تنظیم | چرا |
|---|---|---|---|---|
| موجودی کیف پول، دفتر کل | PC | EC | remote_apply در PG، w: "majority" + linearizable در Mongo، Spanner | جواب غلط = پول گمشده |
| موجودی انبار، صندلی، بلیت | PC (یا AP محدود با سقف رزرو) | EC | LWT با SERIAL در Cassandra، FOR UPDATE در SQL | oversell دیده میشود و گران است |
| یکتایی نام کاربری / ایمیل | PC | EC | unique index روی primary، تراکنش etcd | تکراریها جبران انسانی میخواهند |
| قفل، leader، پیکربندی | PC | EC | etcd linearizable، sync() در ZooKeeper | دو leader همهچیز را خراب میکند |
| پروفایل، تنظیمات | PA با read-your-writes | EL | sticky در Laravel، PreventStaleDatabaseReads، LOCAL_QUORUM | نویسنده باید ویرایش خودش را ببیند |
| سبد خرید | PA | EL | setها در Dynamo/Cassandra، CRDT | از دست رفتن یک افزودن به سبد یعنی از دست رفتن درآمد |
| لایک، بازدید، شمارنده | PA | EL | ONE، synchronous_commit = off در PG، sharded counter | تقریبی کافی است |
| فید، پیشنهاد | PA (harvest کمتر از ۱۰۰٪) | EL | خواندن از replica، cache | چند ثانیه کهنگی مشکلی نیست |
راه درست: این جدول را در سند طراحی نگه دارید و یک بار در کد رمزگذاریاش کنید (ConsistencyPolicy در Laravel همین کار را میکند) تا هر قلم دادهٔ تازه تصمیم صریح لازم داشته باشد.
«سازگاری نهایی کافی است»: UXی که لازم دارد مهم
به زبان ساده: سازگاری نهایی فقط وقتی کافی است که رابط کاربری برایش طراحی شده باشد؛ وگرنه کاربر میبیند ویرایشش ناپدید شد، دو بار کلیک میکند و باگ گزارش میدهد.
بدفهمی رایج: «تأخیر تکثیر چند میلیثانیه است، کسی متوجه نمیشود.» کاربری که همین الان نوشته دقیقاً همان کسی است که فوراً میخواند، و تأخیر هنگام بار، failover و partition جهش میکند. Brewer: partition mode "gives rise to a fundamental user-interface challenge, which is to communicate that tasks are in progress but not complete."
تعریف: الگوهای UX: read-your-writes برای نویسنده (session چسبنده، خواندن از primary برای یک پنجرهٔ زمانی، توکن علّی)، UI خوشبینانه با وضعیت در انتظار، نشانهٔ «موقت» (Brewer: Bayou مدخلهای موقت را با رنگ دیگری نشان میداد)، retry ایدمپوتنت، و برچسب صریح «تقریبی» روی شمارندهها. بیشتر در Event-Driven Architecture.
Without UX design vs with it (profile name change, replica lag 3 s)
1 POST /profile name=Sara primary: ok
2 redirect GET /profile replica: name=Sarah (old) user: "it did not save", edits again
---- with read-your-writes ----
1 POST /profile name=Sara primary: ok; session marks "wrote at t"
2 GET /profile within 5 s routed to the primary user sees Sara
3 GET /profile after 5 s replica (caught up)سناریوی واقعی: رویکرد Facebook که Brewer شرح میدهد: بعد از بهروزرسانی "the update goes to the master copy directly as do all the user’s reads for a short time" و "After 20 seconds, the user’s traffic reverts to the closer copy"؛ PreventStaleDatabaseReads در Laravel همین کار را برای هر session میکند (پیشفرض دو ثانیه).
راه درست: در Laravel، 'sticky' => true بهعلاوهٔ PreventStaleDatabaseReads::for(5)؛ در MongoDB، session با causal consistency؛ در Cassandra، LOCAL_QUORUM در هر دو جهت برای کاربرانی که خانهشان یک region است؛ برای نوشتنهایی که از صف عبور میکنند وضعیت «در انتظار» نشان بدهید.
سازوکار (Mechanics)
حساب quorum و خرابی
| کمیت | فرمول | N=3 | N=5 |
|---|---|---|---|
| اکثریت (Majority) | ⌊N/2⌋ + 1 | 2 | 3 |
| شرط همپوشانی | R + W > N | 2 + 2 | 3 + 3 |
| خرابیهایی که عملیات اکثریتی تحمل میکند | N − majority = ⌊(N−1)/2⌋ | 1 | 2 |
| همپوشانی نوشتن-نوشتن (دو نوشتن متعارض هر دو موفق نشوند) | W > N/2 | W ≥ 2 | W ≥ 3 |
| تأخیر عملیاتی که k تأیید لازم دارد | RTT k-امین replica سریع | دومین سریع | سومین سریع |
| خرابیهای قابل تحمل در CockroachDB | (RF − 1)/2 | 1 | 2 |
| پیشفرضهای Riak | n_val برابر 3، PR = PW = 0 (sloppy) |
تنظیمها، محصول به محصول
| محصول | تنظیم | مقدارها (پیشفرض اول یا مشخصشده) | اثر بر CAP/PACELC |
|---|---|---|---|
| Cassandra | consistency level برای هر دستور | ONE، TWO، THREE، QUORUM، LOCAL_QUORUM، EACH_QUORUM، ALL، LOCAL_ONE، ANY | هر درخواست را بین PA/EL و PC/EC جابهجا میکند |
| Cassandra | serial consistency | SERIAL، LOCAL_SERIAL | فاز Paxos در LWT (CAS linearizable) |
| DynamoDB | ConsistentRead | false (پیشفرض)، true | خواندن قوی دو برابر هزینه دارد، فقط جدول و LSI |
| DynamoDB global tables | حالت سازگاری | MREC (پیشفرض)، MRSC | MRSC: سه Region، RPO صفر، تأخیر بیشتر |
| MongoDB | write concern | w: "majority" (پیشفرض ضمنی در بیشتر استقرارها)، w: 1، w: n، j، wtimeout | majority = نوشتن تأییدشده rollback نمیشود |
| MongoDB | read concern | local (پیشفرض)، available، majority، linearizable، snapshot | linearizable به جای کهنهشدن رد میکند |
| MongoDB | read preference | primary (پیشفرض)، primaryPreferred، secondary، secondaryPreferred، nearest، maxStalenessSeconds (≥ 90) | خواندن از secondary هنگام partition جواب میدهد، کهنه |
| PostgreSQL | synchronous_commit | on (پیشفرض)، remote_apply، remote_write، local، off | برای هر تراکنش؛ سطحهای remote به synchronous_standby_names نیاز دارند |
| PostgreSQL | synchronous_standby_names | خالی (ناهمگام، پیشفرض)، FIRST n (...)، ANY n (...) | commitها منتظر standby میمانند: CP برای نوشتن |
| Kafka | acks در producer | all (پیشفرض)، 1، 0 | دوام تأیید |
| Kafka | min.insync.replicas | 1 (پیشفرض) | ≥ 2 باعث میشود acks=all وقتی ISR کوچک است رد کند |
| Kafka | unclean.leader.election.enable | false (پیشفرض) | true = دسترسپذیری به جای سازگاری |
| etcd | سازگاری خواندن | linearizable (پیشفرض)، serializable (--consistency=s، WithSerializable()) | serializable در اقلیت جواب میدهد |
| ZooKeeper | sync()، read-only mode | بهطور پیشفرض خاموش | sync() = خواندن linearizable؛ read-only = خواندن AP |
| Consul | حالت خواندن | default (HTTP)، stale (پیشفرض DNS)، consistent | stale بدون leader کار میکند |
| Riak KV | n_val، r، w، pr، pw، dw | n_val برابر 3، pr/pw برابر 0 | pr/pw > 0 = strict quorum |
| CockroachDB | replication factor، cockroach start --max-offset | RF 3؛ --max-offset با "Default: 500ms" | خرابی قابل تحمل = (RF − 1)/2؛ "If observed clock offsets exceed this limit, servers will crash" |
| Laravel | sticky، PreventStaleDatabaseReads، usingWritePdo | خاموش مگر پیکربندی شود | read-your-writes روی MySQL/PostgreSQL تکثیرشده |
پیامهای خطایی که واقعاً میبینید
| محصول | پیام یا کد (عین متن) | معنا |
|---|---|---|
| Cassandra | Cannot achieve consistency level QUORUM. Required 2 but only 1 alive. (UnavailableException) | coordinator میداند replicaهای زنده کماند: پیش از تلاش رد میشود |
| Cassandra | Operation timed out - received only 1 responses. (timeout خواندن/نوشتن) | replicaها زنده فرض شده بودند ولی بهموقع جواب ندادند؛ نوشتن ممکن است نیمه اعمال شده باشد |
| Kafka | NOT_ENOUGH_REPLICAS (19): "Messages are rejected since there are fewer in-sync replicas than required." | ISR زیر min.insync.replicas |
| Kafka | NOT_ENOUGH_REPLICAS_AFTER_APPEND (20): "Messages are written to the log, but to fewer in-sync replicas than required." | نتیجه نامعلوم؛ با idempotence دوباره تلاش کنید |
| Kafka | NOT_LEADER_OR_FOLLOWER (6) | رهبری جابهجا شده؛ کلاینت metadata را تازه میکند |
| etcd | etcdserver: no leader، etcdserver: request timed out (gRPC Unavailable) | عضو quorum یا leader را از دست داده |
| MongoDB | WriteConcernTimeout (64، write concern error) | اکثریت در مهلت wtimeout نرسید؛ نوشتن روی primary برگردانده نمیشود |
| MongoDB | MaxTimeMSExpired (50) | خواندن linearizable نتوانست بهموقع اکثریت را تأیید کند |
| MongoDB | NotWritablePrimary (10107)، PrimarySteppedDown (189) | نوشتن به عضوی رفته که primary نیست (یا دیگر نیست) |
| PostgreSQL | WARNING: canceling wait for synchronous replication due to user request + DETAIL: The transaction has already committed locally, but might not have been replicated to the standby. | انتظار sync rep لغو شد؛ commit سر جایش است |
| DynamoDB | ReplicatedWriteConflictException | MRSC: آیتم در Region دیگری در حال تغییر است؛ دوباره تلاش کنید |
Go
ماژول academy/cap-pacelc فقط از کتابخانهٔ استاندارد استفاده میکند. register همان رجیستر تکثیرشدهٔ سهگرهی با تزریق partition است، atm همان partition mode در مثال Brewer همراه با جبران، pacelc حساب quorum و تأخیر، و cmd/capsim خروجی آزمایشگاه را چاپ میکند.
Before
کیف پولی که روی دو سایت تکثیر شده، ناوردا را روی نسخهٔ محلی بررسی میکند و بعداً تکثیر میکند، انگار partition وجود ندارد («CA»). تست اضافهبرداشت را مستند میکند، پنهانش نمیکند.
// Package before shows the design CAP warns about: a wallet replicated to
// two sites that accepts withdrawals on whichever replica the request reaches,
// assuming the network never splits ("CA"). It is not broken code; it is the
// common default of "read local, write local, replicate later".
package before
import "errors"
// ErrInsufficientFunds is returned when the local replica sees too little money.
var ErrInsufficientFunds = errors.New("insufficient funds")
// Site is one replica of the wallet (for example one datacenter).
type Site struct {
Balance int64
outbox []int64 // deltas not yet shipped to the peer
}
// Wallet holds two replicas and a flag that says whether they can talk.
type Wallet struct {
Sites [2]*Site
Connected bool
}
// New creates a wallet whose two replicas both start with balance.
func New(balance int64) *Wallet {
return &Wallet{Sites: [2]*Site{{Balance: balance}, {Balance: balance}}, Connected: true}
}
// Withdraw checks the invariant (balance >= amount) against the LOCAL replica
// only, applies the change locally and queues it for the peer. During a
// partition both sites can approve withdrawals against the same money.
func (w *Wallet) Withdraw(site int, amount int64) error {
s := w.Sites[site]
if s.Balance < amount {
return ErrInsufficientFunds
}
s.Balance -= amount
s.outbox = append(s.outbox, -amount)
if w.Connected {
w.flush()
}
return nil
}
// Reconnect ships every queued delta to the other site. Nothing checks the
// invariant again, so the merged balance can be negative.
func (w *Wallet) Reconnect() {
w.Connected = true
w.flush()
}
func (w *Wallet) flush() {
for i, s := range w.Sites {
peer := w.Sites[1-i]
for _, d := range s.outbox {
peer.Balance += d
}
s.outbox = nil
}
}package before
import "testing"
// The test documents the failure, it does not hide it: two sites approve
// 80 each against a balance of 100 while partitioned.
func TestPartitionOverdraws(t *testing.T) {
w := New(100)
w.Connected = false // the link between the sites fails
if err := w.Withdraw(0, 80); err != nil {
t.Fatalf("site 0: %v", err)
}
if err := w.Withdraw(1, 80); err != nil {
t.Fatalf("site 1: %v", err)
}
w.Reconnect()
for i, s := range w.Sites {
if s.Balance != -60 {
t.Fatalf("site %d balance = %d, want -60 (invariant silently broken)", i, s.Balance)
}
}
}
func TestConnectedIsFine(t *testing.T) {
w := New(100)
if err := w.Withdraw(0, 80); err != nil {
t.Fatal(err)
}
if err := w.Withdraw(1, 80); err != ErrInsufficientFunds {
t.Fatalf("err = %v, want ErrInsufficientFunds", err)
}
}After
رجیستر تکثیرشدهای که رفتار CAPاش یک پیکربندی است. CP (R = W = 2 روی سه گره، با read repair) همان رجیستر quorum الگوریتم ABD است: نوشتن اول بالاترین stamp را از replicaهای در دسترس یاد میگیرد تا stampها هرگز عقب نروند، و اقلیت ErrUnavailable برمیگرداند. AP (R = W = 1، با hinted handoff) همهجا جواب میدهد؛ Heal hintها را بازپخش میکند، anti-entropy با last-write-wins اجرا میکند و هر مقدار تأییدشدهای را که دور ریخته گزارش میدهد، چون برنامه باید آنها را جبران کند.
// Package register simulates a single replicated register on N nodes with
// partition injection. The same code behaves as a CP system or as an AP
// system depending only on Config: how many replicas must answer a read (R),
// how many must acknowledge a write (W), and whether the coordinator keeps
// hints for unreachable replicas.
//
// Operations are applied synchronously inside one process, so the only source
// of disagreement between replicas is the partition itself. That isolates the
// CAP decision from every other effect.
package register
import (
"errors"
"fmt"
"sort"
"sync"
)
// ErrUnavailable is what a CP configuration returns on the minority side:
// the node is alive, but it cannot reach enough replicas to answer safely.
var ErrUnavailable = errors.New("unavailable: not enough replicas reachable")
// Stamp orders versions: a Lamport-style counter, ties broken by node id.
type Stamp struct {
Counter uint64
Node int
}
// Less reports whether s is older than o.
func (s Stamp) Less(o Stamp) bool {
if s.Counter != o.Counter {
return s.Counter < o.Counter
}
return s.Node < o.Node
}
// Version is a value with the stamp of the write that produced it.
type Version struct {
Value string
Stamp Stamp
}
// Config chooses the trade-off.
type Config struct {
R int // replicas that must answer a read
W int // replicas that must acknowledge a write
HintedHandoff bool // keep writes for unreachable replicas and replay them on heal
ReadRepair bool // write the newest version back to stale replicas a read contacted
}
// CP: majority reads and writes on three nodes (R + W > N), with read repair,
// which together form the ABD quorum register. The minority side refuses.
var CP = Config{R: 2, W: 2, ReadRepair: true}
// AP: any single replica answers (R = W = 1), hints cover unreachable replicas.
// Both sides accept writes and diverge; Heal converges them.
var AP = Config{R: 1, W: 1, HintedHandoff: true}
type hint struct {
holder, target int
v Version
}
// HealReport says what convergence had to do after the partition.
type HealReport struct {
HintsDelivered int // hinted writes replayed to their target
Repaired int // replicas changed by anti-entropy
Discarded []string // acknowledged values overwritten by last-write-wins
}
// Cluster is N replicas of one register plus the network between them.
type Cluster struct {
mu sync.Mutex
cfg Config
replicas []Version
group []int // nodes with the same group id can talk
hints []hint
parents map[Stamp][]Stamp // versions each write had seen (its causal past)
}
// New creates n replicas holding the empty value.
func New(n int, cfg Config) *Cluster {
if cfg.R < 1 || cfg.W < 1 || cfg.R > n || cfg.W > n {
panic(fmt.Sprintf("register: invalid R=%d W=%d for N=%d", cfg.R, cfg.W, n))
}
return &Cluster{cfg: cfg, replicas: make([]Version, n), group: make([]int, n), parents: map[Stamp][]Stamp{}}
}
// Partition splits the network. Each argument is a set of node ids that can
// still talk to each other; nodes not listed end up alone.
func (c *Cluster) Partition(groups ...[]int) {
c.mu.Lock()
defer c.mu.Unlock()
for i := range c.group {
c.group[i] = -1 - i // alone by default
}
for g, nodes := range groups {
for _, n := range nodes {
c.group[n] = g
}
}
}
// reachable returns the nodes coord can talk to, coord first.
func (c *Cluster) reachable(coord int) []int {
out := []int{coord}
for n := range c.replicas {
if n != coord && c.group[n] == c.group[coord] {
out = append(out, n)
}
}
return out
}
// Write stores value through coordinator coord. With W > 1 the coordinator
// first learns the highest stamp from the replicas it can reach, so its new
// stamp is larger than every acknowledged write (phase one of ABD).
func (c *Cluster) Write(coord int, value string) error {
c.mu.Lock()
defer c.mu.Unlock()
reach := c.reachable(coord)
if len(reach) < c.cfg.W {
return fmt.Errorf("write via node %d: %w (reached %d, need W=%d)", coord, ErrUnavailable, len(reach), c.cfg.W)
}
consulted := reach[:1]
if c.cfg.W > 1 {
consulted = reach
}
highest := c.replicas[coord].Stamp
var seen []Stamp
for _, n := range consulted {
seen = append(seen, c.replicas[n].Stamp)
if highest.Less(c.replicas[n].Stamp) {
highest = c.replicas[n].Stamp
}
}
v := Version{Value: value, Stamp: Stamp{Counter: highest.Counter + 1, Node: coord}}
c.parents[v.Stamp] = seen
// Like Cassandra, the write goes to every replica it can reach; W only
// decides how many acknowledgements the client waits for.
for _, n := range reach {
c.apply(n, v)
}
if c.cfg.HintedHandoff {
for n := range c.replicas {
if c.group[n] != c.group[coord] {
c.hints = append(c.hints, hint{holder: coord, target: n, v: v})
}
}
}
return nil
}
// Read returns the value seen by R replicas reachable from coord, preferring
// coord itself. With R = 1 that is the local replica, possibly stale.
func (c *Cluster) Read(coord int) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
reach := c.reachable(coord)
if len(reach) < c.cfg.R {
return "", fmt.Errorf("read via node %d: %w (reached %d, need R=%d)", coord, ErrUnavailable, len(reach), c.cfg.R)
}
asked := reach[:c.cfg.R]
newest := c.replicas[asked[0]]
for _, n := range asked[1:] {
if newest.Stamp.Less(c.replicas[n].Stamp) {
newest = c.replicas[n]
}
}
if c.cfg.ReadRepair {
for _, n := range asked {
c.apply(n, newest)
}
}
return newest.Value, nil
}
// Heal restores the network, replays hints, then runs anti-entropy: every
// replica converges to the newest stamp (last write wins). A value that is
// overwritten by a version whose writer never saw it was acknowledged on one
// side and is now lost; Heal reports it, because the application must
// compensate for it. LWW alone drops it silently.
func (c *Cluster) Heal() HealReport {
c.mu.Lock()
defer c.mu.Unlock()
for i := range c.group {
c.group[i] = 0
}
var rep HealReport
lost := map[string]bool{}
overwrite := func(n int, v Version) bool {
old := c.replicas[n]
if !c.apply(n, v) {
return false
}
if old.Stamp != (Stamp{}) && !c.descends(v.Stamp, old.Stamp) {
lost[old.Value] = true
}
return true
}
for _, h := range c.hints {
if overwrite(h.target, h.v) {
rep.HintsDelivered++
}
}
c.hints = nil
winner := c.replicas[0]
for _, v := range c.replicas[1:] {
if winner.Stamp.Less(v.Stamp) {
winner = v
}
}
for n := range c.replicas {
if overwrite(n, winner) {
rep.Repaired++
}
}
for v := range lost {
rep.Discarded = append(rep.Discarded, v)
}
sort.Strings(rep.Discarded)
return rep
}
// descends reports whether the write stamped s had old in its causal past.
func (c *Cluster) descends(s, old Stamp) bool {
stack, visited := []Stamp{s}, map[Stamp]bool{}
for len(stack) > 0 {
cur := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if cur == old {
return true
}
if visited[cur] {
continue
}
visited[cur] = true
stack = append(stack, c.parents[cur]...)
}
return false
}
// Values returns every replica's current value, by node id.
func (c *Cluster) Values() []string {
c.mu.Lock()
defer c.mu.Unlock()
out := make([]string, len(c.replicas))
for i, v := range c.replicas {
out[i] = v.Value
}
return out
}
// apply stores v on node n if it is newer; reports whether it changed.
func (c *Cluster) apply(n int, v Version) bool {
if c.replicas[n].Stamp.Less(v.Stamp) {
c.replicas[n] = v
return true
}
return false
}تستها رد درخواست در اقلیت، واگرایی و همگرایی AP، hinted handoff بهتنهایی، خواندن کهنه در R + W = N و یک زمانبندی تصادفی ۲۰۰۰ عملیاتی را پوشش میدهند که در آن CP هرگز مقدار کهنه برنمیگرداند و AP برمیگرداند:
package register
import (
"errors"
"math/rand"
"reflect"
"testing"
)
// Three nodes, partition {0,1} | {2}. CP: the majority side keeps working,
// node 2 is alive but refuses (it gives up A to keep C).
func TestCPMinorityRefuses(t *testing.T) {
c := New(3, CP)
if err := c.Write(0, "v1"); err != nil {
t.Fatal(err)
}
c.Partition([]int{0, 1}, []int{2})
if err := c.Write(0, "v2"); err != nil {
t.Fatalf("majority write: %v", err)
}
if err := c.Write(2, "x"); !errors.Is(err, ErrUnavailable) {
t.Fatalf("minority write err = %v, want ErrUnavailable", err)
}
if _, err := c.Read(2); !errors.Is(err, ErrUnavailable) {
t.Fatalf("minority read err = %v, want ErrUnavailable", err)
}
if got, _ := c.Read(1); got != "v2" {
t.Fatalf("majority read = %q, want v2", got)
}
rep := c.Heal()
if len(rep.Discarded) != 0 {
t.Fatalf("CP must not discard acknowledged writes, got %v", rep.Discarded)
}
if got, err := c.Read(2); err != nil || got != "v2" {
t.Fatalf("after heal read(2) = %q, %v", got, err)
}
}
// AP: both sides accept, readers see different values, heal converges with
// last-write-wins and reports the acknowledged value it threw away.
func TestAPDivergesThenConverges(t *testing.T) {
c := New(3, AP)
if err := c.Write(0, "v1"); err != nil {
t.Fatal(err)
}
c.Partition([]int{0, 1}, []int{2})
if err := c.Write(0, "left"); err != nil {
t.Fatal(err)
}
if err := c.Write(2, "right"); err != nil {
t.Fatal(err)
}
l, _ := c.Read(1)
r, _ := c.Read(2)
if l != "left" || r != "right" {
t.Fatalf("during partition reads = %q / %q, want left / right", l, r)
}
rep := c.Heal()
// The hint for "left" reaches node 2 but loses (same counter, lower node
// id); the two hints for "right" overwrite "left" on nodes 0 and 1.
if rep.HintsDelivered != 2 {
t.Fatalf("hints delivered = %d, want 2", rep.HintsDelivered)
}
if !reflect.DeepEqual(rep.Discarded, []string{"left"}) {
t.Fatalf("discarded = %v, want [left]", rep.Discarded)
}
if got := c.Values(); !reflect.DeepEqual(got, []string{"right", "right", "right"}) {
t.Fatalf("values after heal = %v", got)
}
}
// Hinted handoff alone repairs a replica that only missed writes.
func TestHintedHandoffRepairsMissedWrites(t *testing.T) {
c := New(3, AP)
c.Partition([]int{0, 1}, []int{2})
if err := c.Write(0, "only-left"); err != nil {
t.Fatal(err)
}
rep := c.Heal()
if rep.HintsDelivered != 1 || len(rep.Discarded) != 0 {
t.Fatalf("report = %+v, want 1 hint and nothing discarded", rep)
}
if got := c.Values(); !reflect.DeepEqual(got, []string{"only-left", "only-left", "only-left"}) {
t.Fatalf("values = %v", got)
}
}
// R + W = N (1 + 2 = 3) is not a quorum system: the write succeeds on the
// majority, and a read on the minority answers, stale, without any error.
func TestRPlusWNotGreaterThanNIsStale(t *testing.T) {
c := New(3, Config{R: 1, W: 2})
if err := c.Write(0, "old"); err != nil {
t.Fatal(err)
}
c.Partition([]int{0, 1}, []int{2})
if err := c.Write(0, "new"); err != nil {
t.Fatal(err)
}
got, err := c.Read(2)
if err != nil || got != "old" {
t.Fatalf("read(2) = %q, %v; want stale \"old\" and no error", got, err)
}
}
// Random partitions and operations. CP: every successful read returns the
// last acknowledged write (operations are sequential, so that is exactly
// linearizability here). AP: the same schedule produces stale reads.
func TestRandomScheduleCPNeverStale(t *testing.T) {
cp, ap := runSchedule(CP), runSchedule(AP)
if cp.stale != 0 {
t.Fatalf("CP returned %d stale reads", cp.stale)
}
if cp.refused == 0 {
t.Fatalf("CP never refused; the schedule did not exercise partitions")
}
if ap.stale == 0 || ap.refused != 0 {
t.Fatalf("AP: stale=%d refused=%d; want stale > 0 and refused = 0", ap.stale, ap.refused)
}
t.Logf("CP: refused=%d stale=%d | AP: refused=%d stale=%d", cp.refused, cp.stale, ap.refused, ap.stale)
}
type outcome struct{ refused, stale int }
func runSchedule(cfg Config) outcome {
rng := rand.New(rand.NewSource(42))
c := New(3, cfg)
splits := [][][]int{nil, {{0, 1}, {2}}, {{0, 2}, {1}}, {{1, 2}, {0}}, {{0}, {1}, {2}}}
var o outcome
last := ""
for i := 0; i < 2000; i++ {
if i%50 == 0 {
s := splits[rng.Intn(len(splits))]
if s == nil {
c.Heal()
} else {
c.Partition(s...)
}
}
node := rng.Intn(3)
if rng.Intn(2) == 0 {
v := string(rune('a' + i%26))
if err := c.Write(node, v); err != nil {
o.refused++
continue
}
last = v
} else {
got, err := c.Read(node)
if err != nil {
o.refused++
continue
}
if got != last {
o.stale++
}
}
}
return o
}Partition mode با ریسک محدود و جبران (ATM در مثال Brewer): برداشت آنلاین دفتر کل را بررسی میکند؛ برداشت آفلاین تا یک سقف خالص مجاز است و لاگ میشود؛ Recover تغییرهای جابهجاپذیر را بازپخش میکند و اگر ناوردا شکسته باشد کارمزد میگیرد.
// Package atm implements Brewer's ATM example from "CAP Twelve Years Later":
// detect the partition, enter an explicit partition mode that limits risk
// (stand-in mode: net withdrawals up to a limit), keep a log, and on recovery
// restore state and compensate for invariant violations.
package atm
import (
"errors"
"fmt"
)
var (
// ErrInsufficientFunds: online, the authoritative balance is too low.
ErrInsufficientFunds = errors.New("insufficient funds")
// ErrStandInLimit: offline, the bounded-risk limit is used up.
ErrStandInLimit = errors.New("stand-in limit reached; try again later")
)
// Ledger is the bank's authoritative account (the consistent side).
type Ledger struct {
Balance int64
}
// Op is one operation recorded while partitioned. Deposits and withdrawals
// are commutative deltas, so replay order does not change the final state.
type Op struct {
ATM string
Amount int64 // negative for withdrawals
}
// Compensation is the business action recovery takes for a broken invariant.
type Compensation struct {
Reason string
Fee int64
}
// Report is the result of partition recovery.
type Report struct {
Replayed int
FinalBalance int64
Compensations []Compensation
}
// ATM serves one location. Online it checks the ledger; in partition mode it
// approves withdrawals while the net amount stays within Limit.
type ATM struct {
Name string
Limit int64
ledger *Ledger
online bool
netOut int64 // withdrawals minus deposits during this partition
log []Op
}
// New connects an ATM to the ledger.
func New(name string, ledger *Ledger, limit int64) *ATM {
return &ATM{Name: name, Limit: limit, ledger: ledger, online: true}
}
// LinkDown is called when the ATM detects the partition (a timeout talking to
// the bank). It switches to partition mode.
func (a *ATM) LinkDown() { a.online = false }
// Online reports whether the ATM is in normal mode.
func (a *ATM) Online() bool { return a.online }
// Withdraw dispenses cash. The externalised action (cash leaving the machine)
// is exactly why the offline path bounds the risk instead of trusting a guess.
func (a *ATM) Withdraw(amount int64) error {
if a.online {
if a.ledger.Balance < amount {
return ErrInsufficientFunds
}
a.ledger.Balance -= amount
return nil
}
if a.netOut+amount > a.Limit {
return fmt.Errorf("%s: %w (net %d of %d)", a.Name, ErrStandInLimit, a.netOut, a.Limit)
}
a.netOut += amount
a.log = append(a.log, Op{ATM: a.Name, Amount: -amount})
return nil
}
// Deposit is always accepted: it cannot violate balance >= 0.
func (a *ATM) Deposit(amount int64) {
if a.online {
a.ledger.Balance += amount
return
}
a.netOut -= amount
a.log = append(a.log, Op{ATM: a.Name, Amount: amount})
}
// Recover ends partition mode for every ATM given: it replays their logs into
// the ledger (state convergence) and then checks the invariant once, with the
// truth known (compensation). overdraftFee is the bank's chosen compensation.
func Recover(ledger *Ledger, overdraftFee int64, atms ...*ATM) Report {
var rep Report
for _, a := range atms {
for _, op := range a.log {
ledger.Balance += op.Amount
rep.Replayed++
}
a.log, a.netOut, a.online = nil, 0, true
}
if ledger.Balance < 0 {
rep.Compensations = append(rep.Compensations, Compensation{
Reason: fmt.Sprintf("overdrawn by %d during partition; fee charged, repayment requested", -ledger.Balance),
Fee: overdraftFee,
})
ledger.Balance -= overdraftFee
}
rep.FinalBalance = ledger.Balance
return rep
}package atm
import (
"errors"
"testing"
)
func TestOnlineEnforcesInvariant(t *testing.T) {
l := &Ledger{Balance: 100}
a := New("A", l, 200)
if err := a.Withdraw(150); !errors.Is(err, ErrInsufficientFunds) {
t.Fatalf("err = %v, want ErrInsufficientFunds", err)
}
}
// Two ATMs lose the link. Each may dispense up to its limit, so the bank's
// worst case is bounded (2 x 200), and recovery compensates.
func TestPartitionModeBoundsRiskAndRecoveryCompensates(t *testing.T) {
l := &Ledger{Balance: 100}
a, b := New("A", l, 200), New("B", l, 200)
a.LinkDown()
b.LinkDown()
if err := a.Withdraw(150); err != nil {
t.Fatalf("A: %v", err)
}
if err := b.Withdraw(100); err != nil {
t.Fatalf("B: %v", err)
}
if err := a.Withdraw(100); !errors.Is(err, ErrStandInLimit) {
t.Fatalf("A second withdrawal err = %v, want ErrStandInLimit", err)
}
b.Deposit(20) // deposits always work and free up stand-in room
rep := Recover(l, 25, a, b)
if rep.Replayed != 3 {
t.Fatalf("replayed %d ops, want 3", rep.Replayed)
}
// 100 - 150 - 100 + 20 = -130, then a 25 fee.
if rep.FinalBalance != -155 || len(rep.Compensations) != 1 {
t.Fatalf("report = %+v", rep)
}
if !a.Online() || !b.Online() {
t.Fatal("ATMs must return to normal mode after recovery")
}
}
func TestRecoveryWithoutViolationNeedsNoCompensation(t *testing.T) {
l := &Ledger{Balance: 500}
a := New("A", l, 200)
a.LinkDown()
if err := a.Withdraw(200); err != nil {
t.Fatal(err)
}
rep := Recover(l, 25, a)
if rep.FinalBalance != 300 || len(rep.Compensations) != 0 {
t.Fatalf("report = %+v", rep)
}
}حساب PACELC: همپوشانی، تحمل خرابی، سطحهای Cassandra در چند دیتاسنتر و تأخیر هر سطح بدون خرابی (بهای «else»):
// Package pacelc holds the arithmetic behind tunable consistency: whether a
// read/write combination overlaps (R + W > N), how many replicas each
// Cassandra-style level needs, how many failures it survives, and what it
// costs in latency when nothing is failing (the "ELC" half of PACELC).
package pacelc
import (
"fmt"
"sort"
"time"
)
// Majority is floor(n/2) + 1.
func Majority(n int) int { return n/2 + 1 }
// Overlaps reports whether every read set intersects every write set.
func Overlaps(n, r, w int) bool { return r+w > n }
// Survives is how many replicas may be down or partitioned away while an
// operation that needs k of n acknowledgements still succeeds.
func Survives(n, k int) int { return n - k }
// Topology is replicas per datacenter plus the coordinator's datacenter.
type Topology struct {
RF map[string]int
Local string
}
func (t Topology) total() int {
sum := 0
for _, n := range t.RF {
sum += n
}
return sum
}
// Required returns how many replica responses a level waits for, and per
// datacenter minimums for the levels that have them (Cassandra semantics).
func (t Topology) Required(level string) (total int, perDC map[string]int, err error) {
switch level {
case "ONE", "LOCAL_ONE", "ANY":
return 1, nil, nil
case "TWO":
return 2, nil, nil
case "THREE":
return 3, nil, nil
case "QUORUM":
return Majority(t.total()), nil, nil
case "ALL":
return t.total(), nil, nil
case "LOCAL_QUORUM":
q := Majority(t.RF[t.Local])
return q, map[string]int{t.Local: q}, nil
case "EACH_QUORUM":
perDC = map[string]int{}
for dc, n := range t.RF {
perDC[dc] = Majority(n)
total += perDC[dc]
}
return total, perDC, nil
}
return 0, nil, fmt.Errorf("unknown consistency level %q", level)
}
// Replica is one copy with its round-trip time from the coordinator.
type Replica struct {
DC string
RTT time.Duration
}
// Latency is the time a level takes with no failures: the coordinator waits
// for the k-th fastest response that also satisfies every per-DC minimum.
// LOCAL_ONE must be answered in the local datacenter.
func (t Topology) Latency(level string, replicas []Replica) (time.Duration, error) {
total, perDC, err := t.Required(level)
if err != nil {
return 0, err
}
if level == "LOCAL_ONE" {
perDC = map[string]int{t.Local: 1}
}
rs := append([]Replica(nil), replicas...)
sort.Slice(rs, func(i, j int) bool { return rs[i].RTT < rs[j].RTT })
got := map[string]int{}
n := 0
for _, r := range rs {
got[r.DC]++
n++
if n >= total && satisfied(got, perDC) {
return r.RTT, nil
}
}
return 0, fmt.Errorf("level %s cannot be met by %d replicas", level, len(replicas))
}
func satisfied(got, need map[string]int) bool {
for dc, k := range need {
if got[dc] < k {
return false
}
}
return true
}package pacelc
import (
"testing"
"time"
)
func TestOverlapAndSurvival(t *testing.T) {
cases := []struct {
n, r, w int
overlaps bool
}{
{3, 2, 2, true}, // QUORUM / QUORUM
{3, 1, 3, true}, // ONE reads, ALL writes
{3, 1, 1, false}, // ONE / ONE: fastest, may be stale
{3, 1, 2, false}, // R + W = N is not enough
{5, 3, 3, true},
}
for _, c := range cases {
if got := Overlaps(c.n, c.r, c.w); got != c.overlaps {
t.Errorf("Overlaps(%d,%d,%d) = %v", c.n, c.r, c.w, got)
}
}
if Survives(3, Majority(3)) != 1 || Survives(5, Majority(5)) != 2 || Survives(3, 3) != 0 {
t.Fatal("survival arithmetic wrong")
}
}
// Two datacenters, RF 3 each (the Cassandra NetworkTopologyStrategy shape).
func TestCassandraLevels(t *testing.T) {
topo := Topology{RF: map[string]int{"eu": 3, "us": 3}, Local: "eu"}
want := map[string]int{"ONE": 1, "QUORUM": 4, "LOCAL_QUORUM": 2, "EACH_QUORUM": 4, "ALL": 6}
for level, n := range want {
got, _, err := topo.Required(level)
if err != nil || got != n {
t.Errorf("%s: got %d, %v; want %d", level, got, err, n)
}
}
}
// ELC: with no partition, the price of consistency is waiting for the
// slowest replica in the required set.
func TestLatencyIsTheElseBranch(t *testing.T) {
topo := Topology{RF: map[string]int{"eu": 3, "us": 3}, Local: "eu"}
replicas := []Replica{
{"eu", 1 * time.Millisecond}, {"eu", 2 * time.Millisecond}, {"eu", 3 * time.Millisecond},
{"us", 85 * time.Millisecond}, {"us", 88 * time.Millisecond}, {"us", 90 * time.Millisecond},
}
want := map[string]time.Duration{
"LOCAL_ONE": 1 * time.Millisecond,
"LOCAL_QUORUM": 2 * time.Millisecond,
"QUORUM": 85 * time.Millisecond, // 4 of 6 must include a US replica
"EACH_QUORUM": 88 * time.Millisecond, // 2 in EU and 2 in US
"ALL": 90 * time.Millisecond,
}
for level, d := range want {
got, err := topo.Latency(level, replicas)
if err != nil || got != d {
t.Errorf("%s: got %v, %v; want %v", level, got, err, d)
}
}
}برنامهٔ آزمایشگاه:
// Command capsim prints the experiments used in the chapter's lab: the same
// three-node register under a partition with CP and AP settings, the ATM
// partition mode, and the latency cost of each Cassandra-style level.
package main
import (
"fmt"
"time"
"academy/cap-pacelc/atm"
"academy/cap-pacelc/pacelc"
"academy/cap-pacelc/register"
)
func main() {
for _, mode := range []struct {
name string
cfg register.Config
}{{"CP (R=2, W=2)", register.CP}, {"AP (R=1, W=1, hints)", register.AP}} {
fmt.Printf("== %s, partition {n0,n1} | {n2}\n", mode.name)
c := register.New(3, mode.cfg)
_ = c.Write(0, "v1")
c.Partition([]int{0, 1}, []int{2})
report("write n0=left ", c.Write(0, "left"))
report("write n2=right", c.Write(2, "right"))
for _, n := range []int{1, 2} {
v, err := c.Read(n)
if err != nil {
fmt.Printf(" read n%d -> %v\n", n, err)
continue
}
fmt.Printf(" read n%d -> %q\n", n, v)
}
fmt.Printf(" replicas %v\n", c.Values())
rep := c.Heal()
fmt.Printf(" heal hints=%d repaired=%d discarded=%v -> %v\n",
rep.HintsDelivered, rep.Repaired, rep.Discarded, c.Values())
}
fmt.Println("== ATM stand-in mode (limit 200), balance 100")
l := &atm.Ledger{Balance: 100}
a, b := atm.New("A", l, 200), atm.New("B", l, 200)
a.LinkDown()
b.LinkDown()
report("A withdraw 150", a.Withdraw(150))
report("B withdraw 100", b.Withdraw(100))
report("A withdraw 100", a.Withdraw(100))
rep := atm.Recover(l, 25, a, b)
fmt.Printf(" recover replayed=%d final=%d compensations=%v\n", rep.Replayed, rep.FinalBalance, rep.Compensations)
fmt.Println("== ELC: latency per level, RF eu=3 us=3, coordinator in eu")
topo := pacelc.Topology{RF: map[string]int{"eu": 3, "us": 3}, Local: "eu"}
rs := []pacelc.Replica{
{DC: "eu", RTT: 1 * time.Millisecond}, {DC: "eu", RTT: 2 * time.Millisecond}, {DC: "eu", RTT: 3 * time.Millisecond},
{DC: "us", RTT: 85 * time.Millisecond}, {DC: "us", RTT: 88 * time.Millisecond}, {DC: "us", RTT: 90 * time.Millisecond},
}
for _, level := range []string{"LOCAL_ONE", "LOCAL_QUORUM", "QUORUM", "EACH_QUORUM", "ALL"} {
need, _, _ := topo.Required(level)
d, _ := topo.Latency(level, rs)
fmt.Printf(" %-12s needs %d -> waits %v, survives %d replica(s) down\n", level, need, d, pacelc.Survives(6, need))
}
}
func report(what string, err error) {
if err != nil {
fmt.Printf(" %s -> %v\n", what, err)
return
}
fmt.Printf(" %s -> ok\n", what)
}نگاه Go
| کلاینت Go | تنظیم | نکته |
|---|---|---|
go.etcd.io/etcd/client/v3 | clientv3.WithSerializable() روی Get | پیشفرض linearizable است؛ serializable محلیِ عضو است |
go.mongodb.org/mongo-driver/v2 | writeconcern.Majority()، readconcern.Majority()، readconcern.Linearizable() | روی گزینههای client، database یا collection |
github.com/gocql/gocql | gocql.One، gocql.Quorum، gocql.LocalQuorum، gocql.EachQuorum؛ Query.SerialConsistency | برای هر query یا هر session |
github.com/aws/aws-sdk-go-v2/service/dynamodb | GetItemInput.ConsistentRead *bool | aws.Bool(true) برای خواندن قوی |
github.com/jackc/pgx/v5 | SET LOCAL synchronous_commit TO ... درون tx | انتخاب دوام و قابلمشاهدهبودن برای هر تراکنش |
github.com/twmb/franz-go/pkg/kgo | kgo.RequiredAcks(kgo.AllISRAcks()) | topic همچنان به min.insync.replicas=2 نیاز دارد |
context.WithTimeout | هر فراخوانی quorum | timeout همان آشکارساز partition شماست؛ برای هر عملیات انتخابش کنید |
errors.Is(err, register.ErrUnavailable) | نگاشت به HTTP 503 + Retry-After | رد صادقانه، قرارداد CP با فراخواننده است |
Laravel
Before
یک controller، یک connection، همهٔ خواندنها از replica، بررسی-سپس-بهروزرسانی بدون قفل، و دوام یکسان برای پول و لایک:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/**
* One consistency setting for every kind of data, and the invariant checked
* against whatever replica the read connection happens to pick.
*
* - The SELECT goes to a read replica (asynchronous replication: may be stale).
* - The check and the UPDATE are separate statements with no lock.
* - The commit returns as soon as the primary flushed its own WAL; a failover
* to an asynchronous standby can lose it.
* - After the withdrawal, the next page load reads the replica again and may
* show the old balance.
*/
class WalletControllerBefore
{
public function withdraw(Request $request, int $walletId): JsonResponse
{
$amount = (int) $request->integer('amount');
$balance = DB::table('wallets')->where('id', $walletId)->value('balance');
if ($balance < $amount) {
return response()->json(['error' => 'insufficient funds'], 422);
}
DB::table('wallets')->where('id', $walletId)->update(['balance' => $balance - $amount]);
return response()->json(['balance' => $balance - $amount]);
}
}After
Connectionهایی که به اسم تضمینشان نامگذاری شدهاند: primary و replicaهای PostgreSQL با sticky، یک connection «سازگار» برای MongoDB (w برابر majority، wTimeoutMS، readConcernLevel برابر majority، خواندن از primary) و یک connection «فید» (نزدیکترین عضو، w: 1، maxStalenessSeconds):
<?php
// config/database.php (excerpt): the consistency choice is part of the
// connection definition, so name connections after the guarantee they give.
return [
'default' => env('DB_CONNECTION', 'pgsql'),
'connections' => [
// PostgreSQL primary + asynchronous read replicas. 'sticky' sends reads
// to the write host after this request wrote (read-your-writes inside
// one request). Synchronous replication itself is configured on the
// server: synchronous_standby_names = 'ANY 1 (standby_a, standby_b)'.
'pgsql' => [
'driver' => 'pgsql',
'read' => [
'host' => [
env('DB_READ_HOST_1', 'replica-1.db.internal'),
env('DB_READ_HOST_2', 'replica-2.db.internal'),
],
],
'write' => [
'host' => [env('DB_WRITE_HOST', 'primary.db.internal')],
],
'sticky' => true,
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'shop'),
'username' => env('DB_USERNAME', 'shop'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'verify-full'),
],
// MongoDB replica set, "consistent" profile: majority writes with a
// bounded wait, majority reads from the primary. URI options from the
// MongoDB PHP driver; laravel-mongodb passes 'options' through.
'mongodb' => [
'driver' => 'mongodb',
'dsn' => env('MONGODB_URI', 'mongodb://mongo-a.internal,mongo-b.internal,mongo-c.internal/?replicaSet=rs0'),
'database' => env('MONGODB_DATABASE', 'shop'),
'options' => [
'w' => 'majority',
'wTimeoutMS' => 2000,
'journal' => true,
'readConcernLevel' => 'majority',
'readPreference' => 'primary',
'retryWrites' => true,
],
],
// Same replica set, "fast" profile for feeds and counters: the nearest
// member answers, possibly a lagging secondary (maxStalenessSeconds
// must be at least 90 when set).
'mongodb_feed' => [
'driver' => 'mongodb',
'dsn' => env('MONGODB_URI', 'mongodb://mongo-a.internal,mongo-b.internal,mongo-c.internal/?replicaSet=rs0'),
'database' => env('MONGODB_DATABASE', 'shop'),
'options' => [
'w' => 1,
'readConcernLevel' => 'local',
'readPreference' => 'nearest',
'maxStalenessSeconds' => 120,
],
],
],
];جدول تصمیم بهصورت کد: یک enum که هر سطح را به تنظیمهای مشخص نگاشت میکند و یک policy که برای قلم دادهای که کسی دربارهٔ آن تصمیم نگرفته جواب نمیدهد:
<?php
namespace App\Support;
/**
* What a use case needs, decided per data item, not per database.
* Each case maps to concrete knobs in PostgreSQL and MongoDB.
*/
enum Consistency: string
{
// Money, stock, unique usernames: refuse rather than guess (CP choice).
case Linearizable = 'linearizable';
// Profile edits, settings: the author must see their own write.
case ReadYourWrites = 'read-your-writes';
// Likes, view counts, feeds: any replica, converge later (AP choice).
case Eventual = 'eventual';
/** PostgreSQL synchronous_commit for writes of this kind. */
public function synchronousCommit(): string
{
return match ($this) {
self::Linearizable => 'remote_apply', // visible on the sync standby before COMMIT returns
self::ReadYourWrites => 'on', // durable on the sync standby
self::Eventual => 'off', // do not even wait for the local WAL flush
};
}
/** MongoDB read concern level for reads of this kind. */
public function mongoReadConcern(): string
{
return match ($this) {
self::Linearizable => 'linearizable',
self::ReadYourWrites => 'majority',
self::Eventual => 'local',
};
}
/** What the API does when the consistent path is not reachable. */
public function onPartition(): string
{
return match ($this) {
self::Linearizable => 'refuse with 503 and Retry-After',
self::ReadYourWrites => 'read from the primary; refuse writes if it is gone',
self::Eventual => 'serve the nearest replica, mark the answer as possibly stale',
};
}
}<?php
namespace App\Support;
use InvalidArgumentException;
/**
* The per-data-item decision table from the chapter, as code. Reviewing a new
* feature means adding one row here and justifying it.
*/
final class ConsistencyPolicy
{
/** @var array<string, Consistency> */
private const ITEMS = [
'wallet.balance' => Consistency::Linearizable,
'inventory.stock' => Consistency::Linearizable,
'user.username' => Consistency::Linearizable,
'user.profile' => Consistency::ReadYourWrites,
'user.settings' => Consistency::ReadYourWrites,
'post.likes' => Consistency::Eventual,
'post.views' => Consistency::Eventual,
'feed.timeline' => Consistency::Eventual,
];
public static function for(string $item): Consistency
{
return self::ITEMS[$item]
?? throw new InvalidArgumentException("No consistency decision recorded for [{$item}].");
}
/** @return array<string, Consistency> */
public static function all(): array
{
return self::ITEMS;
}
}پول روی PostgreSQL: SET LOCAL synchronous_commit TO 'remote_apply' درون تراکنش، قفل سطر، کلید idempotency و قید CHECK در schema:
<?php
namespace App\Services;
use App\Support\ConsistencyPolicy;
use DomainException;
use Illuminate\Support\Facades\DB;
/**
* Money is a CP item: the check and the change happen on the primary under a
* row lock, and COMMIT returns only after a synchronous standby has applied
* the change. If no synchronous standby answers, COMMIT waits: the system
* gives up availability for this operation instead of risking a lost debit.
*/
final class WalletService
{
public function withdraw(int $walletId, int $amount, string $idempotencyKey): int
{
$level = ConsistencyPolicy::for('wallet.balance');
return DB::transaction(function () use ($walletId, $amount, $idempotencyKey, $level): int {
// Per-transaction override; the default for the server stays 'on'.
DB::statement("SET LOCAL synchronous_commit TO '{$level->synchronousCommit()}'");
$done = DB::table('wallet_entries')->where('idempotency_key', $idempotencyKey)->first();
if ($done !== null) {
return (int) DB::table('wallets')->where('id', $walletId)->value('balance');
}
$wallet = DB::table('wallets')->where('id', $walletId)->lockForUpdate()->first();
if ($wallet === null || $wallet->balance < $amount) {
throw new DomainException('insufficient funds');
}
DB::table('wallets')->where('id', $walletId)->update([
'balance' => DB::raw('balance - '.(int) $amount),
'updated_at' => now(),
]);
DB::table('wallet_entries')->insert([
'wallet_id' => $walletId,
'amount' => -$amount,
'idempotency_key' => $idempotencyKey,
'created_at' => now(),
]);
return (int) $wallet->balance - $amount;
}, 3);
}
}لایک روی PostgreSQL: synchronous_commit فقط برای این تراکنش خاموش، درج ایدمپوتنت، خواندن از replica:
<?php
namespace App\Services;
use App\Support\ConsistencyPolicy;
use Illuminate\Support\Facades\DB;
/**
* Likes are an AP/EL item: losing the last few hundred milliseconds of likes
* in a crash is acceptable, waiting for a standby on every tap is not.
* Reads come from a replica and may lag; the UI shows the count as approximate.
*/
final class LikeService
{
public function like(int $postId, int $userId): void
{
$level = ConsistencyPolicy::for('post.likes');
DB::transaction(function () use ($postId, $userId, $level): void {
DB::statement("SET LOCAL synchronous_commit TO '{$level->synchronousCommit()}'");
// Idempotent by construction: one row per (post, user).
$inserted = DB::table('post_likes')->insertOrIgnore([
'post_id' => $postId,
'user_id' => $userId,
'created_at' => now(),
]);
if ($inserted === 1) {
DB::table('posts')->where('id', $postId)->increment('likes_count');
}
});
}
public function count(int $postId): int
{
// Avoid stickiness on purpose: any replica is fine for this number.
return (int) DB::table('posts')->where('id', $postId)->value('likes_count');
}
}پول روی MongoDB: یک handle برای collection با WriteConcern::MAJORITY (wtimeout دو ثانیه، journalشده) و read concern از نوع linearizable؛ findOne محدود به maxTimeMS؛ خطای write concern به معنای «نتیجه نامعلوم، با همان کلید دوباره تلاش کن»:
<?php
namespace App\Services;
use App\Support\ConsistencyPolicy;
use Illuminate\Support\Facades\DB;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Collection;
use MongoDB\Driver\Exception\BulkWriteException;
use MongoDB\Driver\Exception\ExecutionTimeoutException;
use MongoDB\Driver\ReadConcern;
use MongoDB\Driver\WriteConcern;
use RuntimeException;
/**
* The same CP choice on MongoDB: w:majority with a bounded wait, and a
* linearizable read of one document by a unique key, bounded by maxTimeMS.
* On a minority partition both calls fail instead of returning stale data.
*/
final class MongoLedger
{
private function collection(): Collection
{
$level = ConsistencyPolicy::for('wallet.balance');
return DB::connection('mongodb')
->getDatabase()
->selectCollection('wallets', [
'writeConcern' => new WriteConcern(WriteConcern::MAJORITY, 2000, true),
'readConcern' => new ReadConcern($level->mongoReadConcern()),
]);
}
public function credit(string $walletId, int $amount, string $idempotencyKey): void
{
try {
$this->collection()->updateOne(
['_id' => $walletId, 'applied' => ['$ne' => $idempotencyKey]],
[
'$inc' => ['balance' => $amount],
'$push' => ['applied' => ['$each' => [$idempotencyKey], '$slice' => -1000]],
'$set' => ['updated_at' => new UTCDateTime],
],
);
} catch (BulkWriteException $e) {
// A write concern error does not undo the write on the primary:
// the outcome is unknown, so the caller retries with the same key.
throw new RuntimeException('credit not confirmed by a majority; retry with the same key', 0, $e);
}
}
public function balance(string $walletId): int
{
try {
$doc = $this->collection()->findOne(['_id' => $walletId], ['maxTimeMS' => 1000]);
} catch (ExecutionTimeoutException $e) {
throw new RuntimeException('no majority-confirmed primary within 1 s', 0, $e);
}
return (int) ($doc['balance'] ?? 0);
}
}قرارداد HTTP: قلمهای CP با 503 و Retry-After جواب میدهند، موجودی صاحب حساب با usingWritePdo از primary خوانده میشود و قلمهای AP برچسب تقریبی میگیرند:
<?php
namespace App\Http\Controllers;
use App\Services\LikeService;
use App\Services\WalletService;
use DomainException;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/**
* The HTTP face of the per-item decision: CP items refuse honestly with 503,
* AP items answer and say the answer may be stale, read-your-writes items read
* from the primary for the author.
*/
class WalletController
{
public function __construct(
private readonly WalletService $wallets,
private readonly LikeService $likes,
) {}
public function withdraw(Request $request, int $walletId): JsonResponse
{
$validated = $request->validate(['amount' => ['required', 'integer', 'min:1']]);
$key = (string) $request->header('Idempotency-Key');
abort_if($key === '', 400, 'Idempotency-Key header required');
try {
$balance = $this->wallets->withdraw($walletId, $validated['amount'], $key);
} catch (DomainException $e) {
return response()->json(['error' => $e->getMessage()], 422);
} catch (QueryException $e) {
// Primary unreachable or failing over: say so instead of guessing.
return response()->json(['error' => 'temporarily unavailable'], 503, ['Retry-After' => '5']);
}
return response()->json(['balance' => $balance]);
}
public function show(int $walletId): JsonResponse
{
// The owner looking at their balance right after a withdrawal: read the
// primary for this callback only, whatever stickiness says.
$wallet = DB::connection()->usingWritePdo(
fn ($connection) => $connection->table('wallets')->where('id', $walletId)->first(),
);
return response()->json(['balance' => $wallet?->balance]);
}
public function likes(int $postId): JsonResponse
{
return response()->json([
'likes' => $this->likes->count($postId),
'approximate' => true,
])->header('Cache-Control', 'public, max-age=5');
}
}read-your-writes در سطح session با PreventStaleDatabaseReads::for(5):
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads;
// Session-level read-your-writes: for 5 seconds after a request in this
// session wrote to the default connection, its reads use the write host.
// It must run after StartSession, which the web group already includes.
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->web(append: [
PreventStaleDatabaseReads::for(5),
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})
->create();Schema و تستها:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('wallets', function (Blueprint $table) {
$table->id();
$table->bigInteger('balance')->default(0);
$table->timestamps();
});
// The invariant lives in the database, so no code path can skip it.
DB::statement('ALTER TABLE wallets ADD CONSTRAINT wallets_balance_non_negative CHECK (balance >= 0)');
Schema::create('wallet_entries', function (Blueprint $table) {
$table->id();
$table->foreignId('wallet_id')->constrained();
$table->bigInteger('amount');
$table->string('idempotency_key', 64)->unique();
$table->timestamp('created_at');
});
Schema::create('post_likes', function (Blueprint $table) {
$table->unsignedBigInteger('post_id');
$table->unsignedBigInteger('user_id');
$table->timestamp('created_at');
$table->primary(['post_id', 'user_id']);
});
}
public function down(): void
{
Schema::dropIfExists('post_likes');
Schema::dropIfExists('wallet_entries');
Schema::dropIfExists('wallets');
}
};<?php
namespace Tests\Unit;
use App\Support\Consistency;
use App\Support\ConsistencyPolicy;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
class ConsistencyPolicyTest extends TestCase
{
public function test_money_is_linearizable_and_waits_for_the_standby(): void
{
$level = ConsistencyPolicy::for('wallet.balance');
$this->assertSame(Consistency::Linearizable, $level);
$this->assertSame('remote_apply', $level->synchronousCommit());
$this->assertSame('linearizable', $level->mongoReadConcern());
}
public function test_likes_are_eventual_and_skip_the_flush(): void
{
$this->assertSame('off', ConsistencyPolicy::for('post.likes')->synchronousCommit());
}
public function test_every_item_needs_an_explicit_decision(): void
{
$this->expectException(InvalidArgumentException::class);
ConsistencyPolicy::for('cart.items');
}
}نگاه Laravel
| امکان Laravel | کاربرد برای سازگاری | نکته (مستندات Laravel 13) |
|---|---|---|
hostهای read / write | هدایت خواندن به replicaها | "When multiple values exist in the host configuration array, a database host will be randomly chosen for each request" |
'sticky' => true | read-your-writes درون یک درخواست | بعد از نوشتن در چرخهٔ درخواست "any further "read" operations will use the "write" connection" |
DB::withoutAffectingStickiness() | نوشتنهای نگهداری که نباید خواندن را به primary بچسبانند | پیشرفت job، timestampهای audit |
middleware از نوع PreventStaleDatabaseReads | read-your-writes بین درخواستهای یک session | "By default, requests within two seconds of a write will use the write connection"؛ ::for(5)؛ بعد از StartSession |
DB::connection()->usingWritePdo(fn ...) | اجبار خواندن از primary برای یک callback | ترجیح خواندن قبلی را حتی با exception بازمیگرداند |
DB::transaction(fn, attempts) + DB::statement('SET LOCAL ...') | synchronous_commit برای هر تراکنش | SET LOCAL تا COMMIT/ROLLBACK میماند |
lockForUpdate() | بررسی-سپس-اقدام روی primary | برای آن سطر روی یک primary، linearizable |
insertOrIgnore() | نوشتن AP ایدمپوتنت | کلید یکتا dedup را انجام میدهد |
options در laravel-mongodb | w، wTimeoutMS، journal، readConcernLevel، readPreference، maxStalenessSeconds | گزینههای URI کتابخانهٔ PHP مخصوص MongoDB |
getDatabase()->selectCollection($name, [...]) | writeConcern / readConcern برای هر collection | MongoDB\Driver\WriteConcern، ReadConcern::LINEARIZABLE |
حل مسئلههای کلاسیک
اضافهبرداشت هنگام partition
| راهحل | چگونه | مزیت | هزینه / محدودیت |
|---|---|---|---|
| CP روی موجودی | commit اکثریتی / sync rep، قفل سطر | ناوردا همیشه برقرار است | سمت اقلیت نمیتواند برداشت کند |
| partition mode محدود | سقف stand-in برای هر سایت (ATM)، لاگ، آشتی | دسترسپذیر با بدترین حالت معلوم | جبران لازم است (کارمزد، پیگیری) |
| Escrow / تقسیم بودجه | بخشی از موجودی از پیش به هر سایت داده میشود | هر سایت بدون ریسک محلی تصمیم میگیرد | بودجهٔ استفادهنشده قفل است؛ توازن دوباره لازم است |
| رزرو سپس برداشت | رزرو در سمت CP، برداشت بعداً | وضعیت روشن برای کاربر | دو گام، timeoutها |
نویسنده نوشتهٔ خودش را نمیبیند
| راهحل | چگونه | مزیت | هزینه / محدودیت |
|---|---|---|---|
| چسبندگی در سطح درخواست | sticky در Laravel | یک خط | فقط درون همان درخواست |
| پنجرهٔ session | PreventStaleDatabaseReads::for(n)، به سبک Facebook با ۲۰ ثانیه | redirectها را هم پوشش میدهد | بار اضافه روی primary بعد از نوشتن |
| توکن علّی | session با causal consistency در MongoDB؛ causality token در CockroachDB | دقیق | کلاینت باید توکن را حمل کند |
| قابلمشاهدهشدن پیش از تأیید | remote_apply در PG، LOCAL_QUORUM در هر دو جهت در Cassandra | بعدش هر replica کافی است | تأخیر نوشتن بیشتر |
دو leader بعد از یک اختلال شبکه (split brain)
| راهحل | چگونه | مزیت | هزینه / محدودیت |
|---|---|---|---|
| نوشتن اکثریتی | w: "majority"، acks=all + min.insync.replicas=2، Raft | leader قدیمی نمیتواند تأیید بدهد | سه failure domain لازم است |
| توکن fencing | storage epochهای پایینتر را رد میکند | از اثرهای بیرونی محافظت میکند | هر منبع باید توکن را بررسی کند |
| lease با حاشیه | lease کوتاهتر از تشخیص خرابی؛ مرز ساعت | ساده | به محدودبودن رانش ساعت وابسته است |
| witness / رأیدهندهٔ فرد | witness در DynamoDB MRSC، رأیدهنده در zone سوم | گره را باز میکند | زیرساخت اضافه |
QUORUM بین regionها خیلی کند است
| راهحل | چگونه | مزیت | هزینه / محدودیت |
|---|---|---|---|
LOCAL_QUORUM در هر دو جهت | کاربران خانهٔ region دارند | تأخیر محلی، read-your-writes در هر region | خوانندهٔ بینregion ممکن است کهنه ببیند |
| region خانه برای هر رکورد | نوشتن به region رکورد میرود (سبک PNUTS) | برای region خانه سریع | نویسندهٔ دور RTT میپردازد |
| چیدمان گروه اجماع | REGIONAL BY ROW در CockroachDB، region رهبر در Spanner | CP با تأخیر محلی برای بیشتر موارد | از دست رفتن region را فقط با ۳ region یا بیشتر تحمل میکند |
EACH_QUORUM فقط جایی که لازم است | پرچم تقلب، اعتبارها | قوی بین regionها جایی که مهم است | بیشترین تأخیر نوشتن |
نوشتنها بعد از مرگ یک standby معطل میمانند (PostgreSQL)
| راهحل | چگونه | مزیت | هزینه / محدودیت |
|---|---|---|---|
| quorum از نامزدها | ANY 1 (a, b) یا FIRST 1 (a, b) | یک standby میتواند بمیرد | دو standby لازم است |
| پایش | هشدار روی pg_stat_replication.sync_state | هشدار زودهنگام | کار عملیاتی |
| روال صریح تنزل | runbook برای تغییر synchronous_standby_names و reload | دسترسپذیری برمیگردد | پنجرهای که commitها تکثیر نمیشوند (A آگاهانه انتخاب میشود) |
| سطح برای هر تراکنش | synchronous_commit برابر local/off برای نوشتنهای غیرحیاتی | فقط نوشتنهای حیاتی منتظر میمانند | نظم در کد |
نوشتنهای تأییدشده بعد از بهبود partition ناپدید میشوند
| راهحل | چگونه | مزیت | هزینه / محدودیت |
|---|---|---|---|
| پرهیز از LWW روی دادهٔ خواندن-تغییر-نوشتن | برای آن فیلدها مسیر CP یا LWT | بدون از دست رفتن بیصدا | تأخیر، دسترسپذیری |
| نوعهای ادغامپذیر | set/map/counter در Cassandra، CRDT | نیت هر دو طرف میماند | هر ناوردایی ادغامپذیر نیست |
| Siblingها | vector clock در Riak/Dynamo، merge در برنامه | هیچ چیز بیصدا حذف نمیشود | برنامه باید merge کند |
| تشخیص و جبران | لاگ نسخههای دورریخته (HealReport.Discarded در Go) | کسبوکار میتواند تعمیر کند | فرایند جبران لازم است |
Producer خطای NotEnoughReplicas میگیرد (Kafka)
| راهحل | چگونه | مزیت | هزینه / محدودیت |
|---|---|---|---|
| retry با idempotence | enable.idempotence=true، delivery.timeout.ms محدود | بدون تکرار | producer تا کوچکبودن ISR معطل میماند |
| بافر محلی (outbox) | رویدادها تا پذیرفتهشدن در outbox دیتابیس میمانند | بدون از دست رفتن، سرویس سر پا میماند | تأخیر (Transactional Outbox) |
پایینآوردن موقت min.insync.replicas | تصمیم اپراتور | دسترسپذیری | ریسک دوام: A را صریح انتخاب کنید |
انتخاب
بر اساس قلم داده
| وضعیت | توصیه | تکنیک تکمیلی | دلیل |
|---|---|---|---|
| دفتر کل، موجودی، پرداخت | PC/EC: commit همگام (remote_apply یا on)، w: "majority"، Spanner/CockroachDB | کلید idempotency، قید CHECK، 503 + Retry-After | یک جواب غلط از رد کردن گرانتر است |
| موجودی انبار با فروش ویژه | PC/EC با یک استخر رزرو AP محدود برای هر region | escrow، جبران (ایمیل backorder) | توازن بین دسترسپذیری و ریسک oversell |
| نام یکتا، قفل، انتخاب leader | PC/EC: etcd/ZooKeeper linearizable، unique index در SQL، LWT با SERIAL | توکن fencing | تکراریها بدون انسان قابل بازگشت نیستند |
| پروفایل، تنظیمات کاربر | PA/EL با read-your-writes | sticky، پنجرهٔ session، LOCAL_QUORUM | فقط نویسنده کهنگی را میبیند |
| سبد خرید، فهرست علاقهمندی | PA/EL | set، CRDT، افزودن ایدمپوتنت | همیشهقابلنوشتن از ترتیب سختگیرانه بهتر است |
| شمارنده، لایک، بازدید | PA/EL | sharded counter، ONE، synchronous_commit = off | تقریبی قابل قبول است |
| فید، جستوجو، پیشنهاد | PA/EL با harvest کمتر از ۱۰۰٪ | نتیجهٔ ناقص، مهلت | yield از کاملبودن مهمتر است |
| پیکربندی و feature flag | نوشتن PC/EC، خواندن AP از cache با TTL | watch، پیکربندی نسخهدار | نوشتن نادر، خواندن همهجا |
| session جهانی | PA/EL (DynamoDB MREC، Cassandra LOCAL_QUORUM) | TTL، بهروزرسانی ایدمپوتنت | از دست رفتن یک ویرایش قابل قبول است |
| دادهٔ قوی بین regionها | PC/EC (Spanner، CockroachDB، DynamoDB MRSC) | اکثریت را نزدیک نویسندهها بگذارید | RTT روی نوشتن، RPO صفر |
بر اساس سؤال محصول
| نیاز شما | انتخاب | پرهیز |
|---|---|---|
| خواندن قوی روی store هماهنگی | خواندن پیشفرض etcd، sync() + خواندن در ZooKeeper، ?consistent در Consul | خواندن stale/serializable برای تصمیم قفل |
| خواندن قوی تکسند در MongoDB | w: "majority" + readConcern: "linearizable" + maxTimeMS | w: 1 با خواندن از secondary |
| read-your-writes روی replicaهای SQL | sticky + PreventStaleDatabaseReads در Laravel، یا remote_apply در PG | خواندن از replica تصادفی درست بعد از نوشتن |
| بدون از دست رفتن نوشتن تأییدشده در Kafka | RF 3، min.insync.replicas=2، acks=all، unclean election خاموش | acks=1 برای رویدادهای کسبوکاری |
| Cassandra چند-region کمتأخیر | LOCAL_QUORUM / LOCAL_ONE | QUORUM در مسیرهای داغ |
| key-value چند-region که هرگز واگرا نشود | DynamoDB MRSC | MREC بهعلاوهٔ خواندن-تغییر-نوشتن |
در معماری: از یک پردازه تا سیستم توزیعشده
CAP از لحظهای مهم میشود که وضعیت در جای دومی کپی شود که میتواند در دسترس نباشد. تصمیم از «کدام دیتابیس» به «کدام عملیات، هنگام کدام خرابی» منتقل میشود.
Monolith (یکپارچه): یک پردازه، یک دیتابیس
یک primary در PostgreSQL و یک برنامه سیستم CAP نیست: یک نسخه هست و اگر در دسترس نباشد هیچ چیز کار نمیکند (C، نه A). سادهترین استفادهٔ درست این است که تا وقتی replica لازم نشده همینطور بماند، با یک standby همگام برای دوام (synchronous_standby_names = 'ANY 1 (a, b)') و replicaهای ناهمگام فقط برای گزارش. مثال مشخص: فروشگاهی با ۵۰ سفارش در دقیقه روی یک primary؛ checkout مجانی linearizable است چون هر خواندن به primary میرود.
Modular monolith: مرز بدون شبکه
ماژولها پردازه را شریکاند ولی نباید فرضها را شریک باشند: همین حالا به دادهٔ هر ماژول برچسب سازگاری بدهید (جدول ConsistencyPolicy)، حتی اگر همهچیز هنوز روی یک primary است. وقتی ماژول کاتالوگ بعداً خواندنهایش را به replicaها منتقل کرد، فقط سطرهای همان ماژول از «primary» به «replica + sticky» تغییر میکنند. مثال: کاتالوگ محصولات را با hostهای read در Laravel از replica میخواند و ماژول سفارش خواندن از primary و lockForUpdate را نگه میدارد.
Microservices (میکروسرویسها): CAP بین سرویسها
هر فراخوانی سرویس یک لینک تکثیر است که میتواند partition شود. سرویس سفارش نمیتواند با سرویس پرداخت linearizable باشد؛ یا دسترسپذیر است (سفارش را «در انتظار» میپذیرد) یا سازگار (تا جواب پرداخت رد میکند). شکل رایج:
Checkout across services during a partition between orders and payments
1 POST /orders (Idempotency-Key k) orders: insert order "pending" + outbox row (local transaction, CP on its own DB)
2 outbox relay -> Kafka orders.created acks=all, min.insync.replicas=2 (refuses if ISR too small)
3 payments unreachable orders stays "pending"; UI shows "payment in progress"
4 payments back: consumes, charges once inbox dedup on k; emits payment.succeeded
5 orders -> "confirmed"; if it fails saga compensation: release stock, email the userهر سرویس برای دادهٔ خودش CP یا AP را انتخاب میکند؛ بین سرویسها طبق طراحی سازگاری نهایی دارید که با outbox، consumer ایدمپوتنت و saga امن میشود (Saga Pattern، Idempotent Consumers).
داده توزیعشده (Distributed data): replica، cache، region
اینجا CAP و PACELC معنای تحتاللفظی دارند. replicaهای خواندن برای خواندن AP/EL هستند (به اندازهٔ lag کهنه)؛ cacheها ذاتاً AP هستند ("expiration-based caching to get AP" در Fox و Brewer)؛ نوشتن چند-region یا PA/EL با حل تعارض است (DynamoDB MREC، LOCAL_QUORUM در Cassandra) یا PC/EC با چیدمان اجماع (Spanner، CockroachDB، DynamoDB MRSC). مثال: یک SaaS جهانی دادهٔ هر tenant را در region خانه نگه میدارد (PC/EC درون region، standby همگام ANY 1 در zone دیگر)، داشبوردها را از replicaهای بینregion سرویس میدهد (PA/EL، با برچسب «۳ ثانیه پیش بهروز شد») و sessionها را در DynamoDB MREC نگه میدارد.
مسیر مقیاس (Scaling path): ۱×، ۱۰×، ۱۰۰×
| مقیاس | شکل | تصمیم CAP/PACELC |
|---|---|---|
| 1x | یک primary، standby همگام در zone دیگر | اگر standby اجباری باشد برای نوشتن C به جای A؛ quorum از standbyها برای نگهداشتن A |
| 10x | primary + replicaهای خواندن، cache، صف | خواندن بر اساس قلم: primary برای نویسندهها و پول، replica برای بقیه (sticky، پنجرهٔ session) |
| 100x | shard یا چند-region؛ Cassandra/DynamoDB برای قلمهای پرحجم، Spanner/CockroachDB یا SQL shardشده برای پول | سطح برای هر عملیات (LOCAL_QUORUM، ConsistentRead)، runbook برای partition mode، jobهای جبران، تست chaos برای partition |
آزمایشگاه: یک رجیستر بهصورت CP و AP، partition mode و تأخیر quorum
گامهای ۱ و ۲ در یک پردازه اجرا میشوند (Go 1.24 به بالا، بدون شبکه). گامهای ۳ تا ۶ به خوشهٔ واقعی نیاز دارند و خروجی موردانتظار؛ اجرا نشده هستند: به چیدمان چندگرهی نیاز دارند که این فصل راهاندازی نمیکند.
# 1) Tests (run)
cd docs/snippets/system-design/cap-pacelc/go
go test ./...
# ok academy/cap-pacelc/atm
# ok academy/cap-pacelc/before
# ok academy/cap-pacelc/pacelc
# ok academy/cap-pacelc/register
go test -run TestRandomScheduleCPNeverStale -v ./register
# register_test.go: CP: refused=875 stale=0 | AP: refused=0 stale=420# 2) The simulation (run; output is deterministic)
go run ./cmd/capsim
# == CP (R=2, W=2), partition {n0,n1} | {n2}
# write n0=left -> ok
# write n2=right -> write via node 2: unavailable: not enough replicas reachable (reached 1, need W=2)
# read n1 -> "left"
# read n2 -> read via node 2: unavailable: not enough replicas reachable (reached 1, need R=2)
# replicas [left left v1]
# heal hints=0 repaired=1 discarded=[] -> [left left left]
# == AP (R=1, W=1, hints), partition {n0,n1} | {n2}
# write n0=left -> ok
# write n2=right -> ok
# read n1 -> "left"
# read n2 -> "right"
# replicas [left left right]
# heal hints=2 repaired=0 discarded=[left] -> [right right right]
# == ATM stand-in mode (limit 200), balance 100
# A withdraw 150 -> ok
# B withdraw 100 -> ok
# A withdraw 100 -> A: stand-in limit reached; try again later (net 150 of 200)
# recover replayed=2 final=-175 compensations=[{overdrawn by 150 during partition; fee charged, repayment requested 25}]
# == ELC: latency per level, RF eu=3 us=3, coordinator in eu
# LOCAL_ONE needs 1 -> waits 1ms, survives 5 replica(s) down
# LOCAL_QUORUM needs 2 -> waits 2ms, survives 4 replica(s) down
# QUORUM needs 4 -> waits 85ms, survives 2 replica(s) down
# EACH_QUORUM needs 4 -> waits 88ms, survives 2 replica(s) down
# ALL needs 6 -> waits 90ms, survives 0 replica(s) down-- 3) Cassandra, 3 nodes, RF 3 (expected, not run). Stop two nodes, then in cqlsh:
CREATE KEYSPACE lab WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3};
CREATE TABLE lab.kv (k text PRIMARY KEY, v text);
CONSISTENCY QUORUM;
INSERT INTO lab.kv (k, v) VALUES ('a', '1');
-- expected: Unavailable ... Cannot achieve consistency level QUORUM. Required 2 but only 1 alive.
CONSISTENCY ONE;
INSERT INTO lab.kv (k, v) VALUES ('a', '1');
-- expected: succeeds (AP for this request); restarted nodes receive hints
SERIAL CONSISTENCY SERIAL;
INSERT INTO lab.kv (k, v) VALUES ('user:sara', 'id-7') IF NOT EXISTS;
-- expected with 2 nodes down: unavailable (Paxos needs a majority)# 4) etcd, 3 members; block member 3 from the others (expected, not run)
etcdctl --endpoints=http://192.0.2.13:2379 put /cfg/flag on
# expected: Error: etcdserver: request timed out
etcdctl --endpoints=http://192.0.2.13:2379 get /cfg/flag --consistency=s
# expected: /cfg/flag off (stale but answered)
etcdctl --endpoints=http://192.0.2.11:2379 get /cfg/flag
# expected: /cfg/flag on (majority side)// 5) MongoDB replica set rs0 (P-S-S); isolate the primary with one client (expected, not run)
db.wallets.insertOne({ _id: 7, balance: 100 }, { writeConcern: { w: "majority", wtimeout: 2000 } })
// expected on the isolated primary: write concern error, code 64 WriteConcernTimeout, after 2 s
db.wallets.find({ _id: 7 }).readConcern("linearizable").maxTimeMS(3000)
// expected: MaxTimeMSExpired (50), never a stale document
db.getMongo().setReadPref("nearest")
db.wallets.find({ _id: 7 }).readConcern("local")
// expected from a minority secondary: answers, possibly stale# 6) PostgreSQL primary with synchronous_standby_names = 'standby_a'; stop standby_a (expected, not run)
psql -h primary -c "BEGIN; UPDATE wallets SET balance = balance - 1 WHERE id = 7; COMMIT;"
# expected: hangs at COMMIT. In another session: SELECT pg_cancel_backend(<pid>);
# expected in the first session:
# WARNING: canceling wait for synchronous replication due to user request
# DETAIL: The transaction has already committed locally, but might not have been replicated to the standby.
psql -h primary -c "ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (standby_a, standby_b)'; " -c "SELECT pg_reload_conf();"
# expected: commits proceed as soon as standby_b confirmsبدفهمیهای رایج
| باور | واقعیت |
|---|---|
| از C و A و P هر دو تا را میشود انتخاب کرد | P اختیاری نیست؛ انتخاب بین C و A هنگام partition است، برای هر عملیات |
| سیستم توزیعشدهٔ CA وجود دارد | «CA» فقط یعنی partition آنقدر نادر است که بشود نادیدهاش گرفت (Brewer ۲۰۱۷: Spanner «effectively CA» ولی از نظر فنی CP) |
| سازگاری CAP همان سازگاری ACID است | C در CAP یعنی linearizability عملیات منفرد؛ C در ACID یعنی حفظ قیدها |
| serializable یعنی linearizable | serializability تراکنشها را مرتب میکند، نه لزوماً به ترتیب زمان واقعی؛ SSI در PostgreSQL linearizable نیست |
| دسترسپذیری CAP یعنی uptime | یعنی به "every request received by a non-failing node" جواب داده شود؛ سیستمهای تکleader در آن رد میشوند |
| دیتابیسها یا CP هستند یا AP | بیشتر پیکربندیها هیچکدام نیستند؛ عملیات و تنظیم را دستهبندی کنید (Kleppmann) |
| R + W > N یعنی linearizability | همپوشانی میدهد؛ sloppy quorum، LWW و نوشتن همزمان هنوز linearizability را میشکنند |
| سازگاری نهایی به خاطر partition رخ میدهد | معمولاً برای تأخیر در روزهای عادی انتخاب میشود: همان EL در PACELC |
acks=all منتظر همهٔ replicaها میماند | منتظر ISR فعلی است که میتواند فقط خود leader باشد، مگر min.insync.replicas ≥ 2 |
| تکثیر همگام standbyها را برای خواندن بهروز نگه میدارد | فقط remote_apply منتظر قابلمشاهدهشدن میماند؛ on منتظر flush است |
| لغو یک commit همگامِ معطل آن را rollback میکند | تراکنش "has already committed locally" |
w: "majority" همهٔ خواندنها را درست میکند | خواندن هم به read concern از نوع majority یا linearizable و عضو درست نیاز دارد |
| خواندن ZooKeeper linearizable است چون CP است | خواندن ساده از سرور متصل میآید؛ از sync() استفاده کنید |
| last-write-wins تعارض را حل میکند | یکی از آنها را دور میریزد؛ جبران یا merge همچنان کار شماست |
| partition برش تمیز و متقارن است | اغلب جزئی، یکطرفه و کوتاه است؛ تشخیص برای هر گره جداگانه و با timeout است |
چکیده (Cheat sheet)
| موضوع | به خاطر بسپارید |
|---|---|
| CAP | هنگام partition، عملیاتی که به هر دو طرف نیاز دارد یا linearizable است یا همیشه جواب میگیرد، نه هر دو |
| تعریفها | C = linearizable؛ A = هر گره سالم جواب میدهد؛ P = گمشدن دلخواه پیام |
| Partition | "a time bound on communication"؛ با timeout و برای هر گره جداگانه تشخیص داده میشود |
| CA | انتخاب نیست؛ ادعای احتمالاتی است («effectively CA») |
| چرخهٔ عمر partition | تشخیص ← partition mode (محدودکردن یا لاگ) ← بازیابی (merge + جبران) |
| PACELC | P: A یا C؛ Else: L یا C. PA/EL، PC/EC، PA/EC (MongoDB)، PC/EL (PNUTS) |
| Quorum | اکثریت = ⌊N/2⌋+1؛ R + W > N همپوشانی دارد؛ N − k خرابی را تحمل میکند |
| Cassandra | در چند-region LOCAL_QUORUM؛ QUORUM از regionها عبور میکند؛ SERIAL برای CAS |
| Sloppy quorum | جانشینها با hint نوشتن را میپذیرند؛ همپوشانی تضمین نیست؛ pr/pw > 0 در Riak = strict |
| etcd / ZK / Consul | linearizable پیشفرض / sync() / ?consistent؛ خواندن سریع: --consistency=s / ساده / ?stale |
| MongoDB | w: "majority" + wtimeout؛ linearizable + maxTimeMS روی primary، یک سند |
| PostgreSQL | ANY 1 (a, b)؛ synchronous_commit برای هر تراکنش: remote_apply > on > remote_write > local > off |
| Kafka | RF 3، min.insync.replicas=2، acks=all، unclean election خاموش |
| DynamoDB | ConsistentRead=true دو برابر هزینه؛ MREC با LWW در برابر MRSC با سه Region |
| Harvest/yield | جواب ناقص yield را حفظ میکند؛ علامتش بزنید |
| هر قلم داده | پول/قفل/یکتایی CP؛ سبد/لایک/فید AP؛ پروفایل AP + read-your-writes |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — خوشهٔ سهعضوی etcd به {1, 2} | {3} تقسیم شده. برای یک put و یک get پیشفرض که به عضو ۳ فرستاده شوند چه میشود، و کلاینت چطور هنوز میتواند آنجا بخواند؟ مهم
پاسخ
پاسخ: هر دو به اجماع نیاز دارند: put با etcdserver: request timed out شکست میخورد و get پیشفرض linearizable سرویس داده نمیشود. خواندن serializable (etcdctl get --consistency=s یا clientv3.WithSerializable()) از store محلی عضو ۳ جواب میدهد، شاید کهنه. این یعنی فقط برای همان خواندن A را به C ترجیح دادهاید.
۲ — چرا «CA» برای سیستمی که روی بیش از یک ماشین اجرا میشود انتخاب معتبری نیست؟ حیاتی
پاسخ
پاسخ: نمیتوانید انتخاب کنید که partition نداشته باشید. وقتی رخ دهد، سیستم باید یا رد کند (C) یا جواب بدهد (A). Brewer ۲۰۱۲: "If the choice is CA, and then there is a partition, the choice must revert to C or A." CA فقط میتواند یعنی partition آنقدر نادر است که نادیده گرفته شود، مثل «effectively CA» در Spanner.
۳ — با تعریفهای دقیق، چرا primary در PostgreSQL با replicaهای خواندن ناهمگام نه CP است نه AP؟ تکمیلی
پاسخ
پاسخ: AP نیست: کلاینتی که از primary جدا افتاده نمیتواند بنویسد، پس هر گره سالم جواب نمیدهد. CP نیست: خواندن از replica ناهمگام میتواند کهنه باشد، پس خواندنها linearizable نیستند. نکتهٔ Kleppmann: چنین سیستمهایی "neither CAP-consistent nor CAP-available" هستند.
۴ — N = 3. ترکیبهای (R, W) = (1, 2) و (2, 2) را هنگام partition {A, B} | {C} مقایسه کنید. مهم
پاسخ
پاسخ: (1, 2): نوشتن در سمت اکثریت موفق است؛ خواندن در C با مقدار قدیمی موفق میشود (کهنه، بدون خطا) چون 1 + 2 = 3 بزرگتر از 3 نیست. (2, 2): خواندن و نوشتن در سمت اکثریت موفقاند؛ هر دو در C شکست میخورند. تست TestRPlusWNotGreaterThanNIsStale در Go حالت اول را نشان میدهد.
۵ — دو دیتاسنتر هر کدام با RF 3. QUORUM، LOCAL_QUORUM و EACH_QUORUM به چند replica نیاز دارند و کدام در هر درخواست از اقیانوس عبور میکند؟ تکمیلی
پاسخ
پاسخ: QUORUM به ۴ از ۶ نیاز دارد، پس دستکم یک replica دور: هر درخواست یک رفتوبرگشت بینregion میپردازد. LOCAL_QUORUM به ۲ replica محلی نیاز دارد. EACH_QUORUM در هر دیتاسنتر ۲ تا (در مجموع ۴) میخواهد و آن هم از اقیانوس عبور میکند.
۶ — PACELC چه چیزی به CAP اضافه میکند و یک استقرار پیشفرض Cassandra و Spanner را چطور دستهبندی میکنید؟ مهم
پاسخ
پاسخ: مصالحهٔ «else» بین تأخیر و سازگاری وقتی partition نیست. Cassandra پیشفرض (Abadi) PA/EL است: هنگام partition دسترسپذیر و در حالت عادی کمتأخیر به بهای سازگاری. Spanner PC/EC است: در سمت اقلیت رد میکند و در حالت عادی تأخیر quorum و commit wait را میپردازد.
۷ — سه گام Brewer برای مدیریت partition را با مثال ATM شرح دهید. تکمیلی
پاسخ
پاسخ: تشخیص: ارتباط ATM با بانک timeout میشود. partition mode: حالت stand-in برداشت خالص را تا یک سقف (مثلاً ۲۰۰ دلار) مجاز میکند و لاگ مینویسد؛ واریز همیشه مجاز است. بازیابی: لاگ بازپخش میشود (جابهجاپذیر)، موجودی ≥ 0 بررسی میشود و تخلفها با کارمزد و درخواست بازپرداخت جبران میشوند.
۸ — commit در PostgreSQL معطل مانده چون تنها standby همگام در دسترس نیست؛ اپراتور آن را لغو میکند. آیا تراکنش rollback میشود؟ مهم
پاسخ
پاسخ: نه. PostgreSQL هشدار "canceling wait for synchronous replication due to user request" را با جزئیات "The transaction has already committed locally, but might not have been replicated to the standby." میدهد. از ANY 1 (a, b) استفاده کنید تا از دست رفتن یک standby قابل تحمل باشد.
۹ — topicی در Kafka با RF 3 و min.insync.replicas=1 داریم و producerها acks=all میفرستند. دو follower از ISR خارج میشوند. ریسک دوام چیست و راه درست کدام است؟ مهم
پاسخ
پاسخ: ISR فقط leader است، پس acks=all با یک broker برآورده میشود؛ اگر آن broker پیش از رسیدن followerها بمیرد، رکوردهای تأییدشده از بین میروند (یا با unclean election خاموش، partition آفلاین میماند). min.insync.replicas=2 بگذارید تا به جایش نوشتن با NOT_ENOUGH_REPLICAS رد شود.
۱۰ — کدام تنظیمهای MongoDB خواندن linearizable موجودی را میدهند و کلاینت چه چیزی باید اضافه کند تا خواندن روی primary اقلیت معطل نماند؟ تکمیلی
پاسخ
پاسخ: نوشتن با w: "majority"، خواندن با readConcern: "linearizable" روی primary و با فیلتری که دقیقاً یک سند را مشخص کند؛ بهعلاوهٔ maxTimeMS، چون "Always use maxTimeMS with linearizable read concern in case a majority of data bearing members are unavailable."
۱۱ — در یک اپ خرید اجتماعی یک قلم داده که CP میکنید و یکی که AP میکنید را با تنظیمش نام ببرید. حیاتی
پاسخ
پاسخ: CP: موجودی کیف پول یا تعداد انبار، با SET LOCAL synchronous_commit TO 'remote_apply' و قفل سطر (یا majority/linearizable در MongoDB). AP: لایکها، با synchronous_commit = off و خواندن از replica (یا ONE در Cassandra)، با برچسب تقریبی.
۱۲ — harvest و yield چیستند و یک صفحهٔ جستوجو هنگام partition چطور از آنها استفاده میکند؟ تکمیلی
پاسخ
پاسخ: yield احتمال تکمیل یک درخواست است؛ harvest کسری از داده که در جواب منعکس شده. هنگام partitionی که ۳ از ۱۰۰ shard را پنهان کرده، صفحه نتیجهٔ ۹۷ shard را برمیگرداند (harvest ۹۷٪، yield حفظ شده) و به جای شکست، آن را ناقص علامت میزند.
واژهنامه (Glossary)
| واژه | معنا |
|---|---|
| قضیهٔ CAP (CAP theorem) | هنگام partition، شیء خواندن/نوشتن تکثیرشده نمیتواند هم linearizable باشد و هم همیشه دسترسپذیر (Gilbert و Lynch ۲۰۰۲) |
| سازگاری در CAP (Consistency) | linearizability، که atomic consistency هم نامیده میشود |
| Linearizability | یک ترتیب کلی از عملیات سازگار با زمان واقعی؛ هر عملیات در لحظهای بین فراخوانی و بازگشت اثر میکند |
| خواندن linearizable (Linearizable read) | خواندنی که تضمین میکند هر نوشتن تأییدشده پیش از شروعش را ببیند (پیشفرض etcd، linearizable در MongoDB) |
| خواندن serializable در etcd (Serializable read) | خواندن محلی عضو که شاید کهنه باشد؛ همان سطح جداسازی serializable در SQL نیست |
| دسترسپذیری در CAP (Availability) | هر درخواستی که گره سالم دریافت کند به پاسخ برسد |
| تحمل partition (Partition tolerance) | رفتار درست وقتی تعداد دلخواهی از پیامهای بین گرهها گم میشود |
| Partition شبکه (Network partition) | بعضی گرهها نمیتوانند بهموقع پیام رد و بدل کنند؛ با timeout تشخیص داده میشود و میتواند جزئی یا یکطرفه باشد |
| CP | عملیات/پیکربندیای که در طرف بدون quorum رد میکند تا سازگار بماند |
| AP | عملیات/پیکربندیای که در همهٔ طرفها جواب میدهد و بعداً آشتی میدهد |
| افسانهٔ CA (CA myth) | این تصور که سیستم توزیعشده میتواند از partition کنار بکشد؛ در بهترین حالت «effectively CA» |
| Partition mode | حالتی صریح که هنگام تشخیص partition وارد آن میشوید: عملیات پرریسک را محدود کنید، همهچیز را لاگ کنید |
| بازیابی partition (Partition recovery) | ادغام وضعیت بعد از partition و جبران ناورداهای نقضشده |
| جبران (Compensation) | اقدام کسبوکاری که یک ناوردا را بازمیگرداند یا اشتباه بیرونیشده را اصلاح میکند |
| ناوردا (Invariant) | قاعدهای که داده باید رعایت کند، مثل موجودی ≥ 0 یا یکتایی نام کاربری |
| Stand-in mode | partition mode در مثال ATM از Brewer: برداشت آفلاین تا یک سقف |
| PACELC | اگر Partition: A یا C؛ در غیر این صورت (Else): Latency یا Consistency (Abadi ۲۰۱۲) |
| PA/EL، PC/EC، PA/EC، PC/EL | چهار دستهٔ PACELC |
| تأخیر در PACELC (Latency) | زمانی که سازگاری در یک روز عادی هزینه دارد: انتظار برای replicaهای دور |
| سازگاری تنظیمپذیر (Tunable consistency) | انتخاب سازگاری برای هر درخواست (سطحهای Cassandra، ConsistentRead در DynamoDB، concernهای Mongo) |
| Quorum | مجموعهای از replicaها که تأییدشان لازم است؛ quorumهای اکثریتی همپوشانی دارند |
| اکثریت (Majority) | ⌊N/2⌋ + 1 replica |
| R + W > N | اندازههای quorum خواندن و نوشتن که مجموعههایشان همیشه همپوشانی دارند |
| N، R، W | replication factor، quorum خواندن، quorum نوشتن (Dynamo) |
| ONE، TWO، THREE | سطحهایی در Cassandra که همان تعداد پاسخ replica میخواهند |
| QUORUM | در Cassandra: اکثریت همهٔ replicaها در همهٔ دیتاسنترها |
| LOCAL_QUORUM | در Cassandra: اکثریت در دیتاسنتر coordinator |
| EACH_QUORUM | در Cassandra: اکثریت در هر دیتاسنتر |
| ALL | در Cassandra: همهٔ replicaها |
| LOCAL_ONE | در Cassandra: یک replica در دیتاسنتر محلی |
| ANY | سطح نوشتن در Cassandra که hint ذخیرهشده را هم میپذیرد |
| SERIAL / LOCAL_SERIAL | serial consistency در Cassandra برای فاز Paxos در lightweight transaction |
| Lightweight transaction (LWT) | نوشتن شرطی (IF) در Cassandra با Paxos |
| Sloppy quorum | quorumی که با اولین N گره سالم، شاید جانشین، برآورده میشود (Dynamo، Riak) |
| Strict quorum | فقط replicaهای اصلی حساب میشوند (pr/pw > 0 در Riak) |
| Hinted handoff | جانشین نوشتن مربوط به replica در دسترسنبوده را نگه میدارد و بعداً تحویل میدهد |
| Read repair | خواندنی که replicaهای واگرا ببیند، جدیدترین نسخه را بازمینویسد |
| Anti-entropy | مقایسهٔ پسزمینهٔ replicaها (Merkle tree) که همگرایی را تضمین میکند |
| Last write wins (LWW) | قاعدهٔ تعارضی که نسخه با بزرگترین timestamp را نگه میدارد و بقیه را دور میریزد |
| Vector clock | شمارندههای هر گره که نسخههای همزمان را تشخیص میدهند (Dynamo، Riak) |
| Write concern | شرط تأیید در MongoDB: w، j، wtimeout |
| w:majority | write concern در MongoDB که اکثریت اعضای رأیدهنده را میخواهد |
| wtimeout | مهلت write concern؛ وقتی سر برسد نوشتن برگردانده نمیشود |
| Read concern | تضمین خواندن در MongoDB: local، available، majority، linearizable، snapshot |
| Read preference | انتخاب عضو در MongoDB: primary، secondary، nearest، … |
| maxTimeMS | محدودیت زمانی سمت سرور برای یک عملیات |
| synchronous_commit | انتظار commit برای هر تراکنش در PostgreSQL: remote_apply، on، remote_write، local، off |
| synchronous_standby_names | فهرست standbyهای همگام در PostgreSQL، با FIRST n یا ANY n |
| remote_apply | commit منتظر میماند تا standby تغییر را اعمال کند (قابل مشاهده برای queryها) |
| acks=all | producer در Kafka منتظر همهٔ replicaهای همگام میماند |
| ISR | replicaهای همگام (in-sync) در Kafka: replicaهایی که به leader رسیدهاند |
| min.insync.replicas | حداقل اندازهٔ ISR در Kafka برای موفقیت نوشتن با acks=all |
| Unclean leader election | انتخاب replica خارج از ISR در Kafka؛ دسترسپذیری به جای سازگاری |
| Split brain | دو گره همزمان مثل leader رفتار میکنند |
| Fencing | رد عملیات leader قدیمی با یک توکن صعودی |
| TrueTime | API ساعت Google که بازهای با عدمقطعیت محدود برمیگرداند |
| Commit wait | انتظار Spanner برای گذشتن عدمقطعیت ساعت پیش از تأیید |
| External consistency | تضمین Spanner: تراکنشها به ترتیب commit در زمان واقعی دیده میشوند |
| Effectively CA | سیستم CP که partitionهایش آنقدر نادرند که کاربران دسترسپذیری را فرض میکنند |
| MREC / MRSC | global tableهای DynamoDB: سازگاری نهایی در برابر سازگاری قوی چند-Region |
| Witness | عضو رأیدهندهای که دادهٔ قابل خواندن نگه نمیدارد (DynamoDB MRSC) |
| ConsistentRead | پارامتر DynamoDB برای خواندن strongly consistent |
| Harvest | کسری از داده که در پاسخ منعکس شده |
| Yield | احتمال تکمیل یک درخواست |
| BASE | Basically Available، Soft state، Eventual consistency (Brewer ۲۰۰۰) |
| سازگاری نهایی (Eventual consistency) | اگر بهروزرسانیها متوقف شوند replicaها همگرا میشوند؛ بدون مرز زمانی |
| Read-your-writes | یک session نوشتههای خودش را میبیند |
| Sticky در Laravel | بعد از نوشتن در یک درخواست، خواندنهای همان درخواست از write connection میروند |
| PreventStaleDatabaseReads | middleware در Laravel که خواندنهای یک session را برای پنجرهای بعد از نوشتن به write connection میفرستد |
| Delay-sensitivity | جایگزین Kleppmann برای CAP: وابستگی تأخیر عملیات به تأخیر شبکه |
| رجیستر ABD (ABD register) | الگوریتم quorum از Attiya، Bar-Noy و Dolev برای رجیستر linearizable (پیکربندی CP در Go) |
| Dynamo | مقالهٔ ۲۰۰۷ آمازون دربارهٔ key-value store: quorum، sloppy quorum، hinted handoff |
| Riak | key-value store به سبک Dynamo با n_val، r، w، pr، pw |
| PNUTS | store شرکت Yahoo با master برای هر رکورد؛ نمونهٔ PC/EL در Abadi |
منابع (References)
- Seth Gilbert, Nancy Lynch — Brewer's Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services, SIGACT News 2002 (author copy): https://www.comp.nus.edu.sg/~gilbert/pubs/BrewersConjecture-SigAct.pdf (MIT copy: https://groups.csail.mit.edu/tds/papers/Gilbert/Brewer6.pdf)
- Seth Gilbert, Nancy Lynch — Perspectives on the CAP Theorem, IEEE Computer 2012: https://groups.csail.mit.edu/tds/papers/Gilbert/Brewer2.pdf
- Eric Brewer — Towards Robust Distributed Systems, PODC 2000 keynote slides: https://people.eecs.berkeley.edu/~brewer/cs262b-2004/PODC-keynote.pdf
- Eric Brewer — CAP Twelve Years Later: How the "Rules" Have Changed, IEEE Computer 2012 (InfoQ): https://www.infoq.com/articles/cap-twelve-years-later-how-the-rules-have-changed/
- Eric Brewer — Spanner, TrueTime and the CAP Theorem, 2017: https://research.google/pubs/spanner-truetime-and-the-cap-theorem/ (PDF: https://research.google.com/pubs/archive/45855.pdf)
- Armando Fox, Eric Brewer — Harvest, Yield, and Scalable Tolerant Systems, HotOS 1999: https://s3.amazonaws.com/systemsandpapers/papers/FOX_Brewer_99-Harvest_Yield_and_Scalable_Tolerant_Systems.pdf
- Daniel Abadi — Consistency Tradeoffs in Modern Distributed Database System Design, IEEE Computer 2012: https://www.cs.umd.edu/~abadi/papers/abadi-pacelc.pdf
- Daniel Abadi — Problems with CAP, and Yahoo's little known NoSQL system (2010): https://dbmsmusings.blogspot.com/2010/04/problems-with-cap-and-yahoos-little.html
- Martin Kleppmann — Please stop calling databases CP or AP (2015): https://martin.kleppmann.com/2015/05/11/please-stop-calling-databases-cp-or-ap.html
- Martin Kleppmann — A Critique of the CAP Theorem, arXiv:1509.05393: https://arxiv.org/abs/1509.05393
- DeCandia et al. — Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007: https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf
- Apache Cassandra — Dynamo architecture (tunable consistency, hints, read repair): https://cassandra.apache.org/doc/latest/cassandra/architecture/dynamo.html
- Apache Cassandra — cqlsh (
CONSISTENCY,SERIAL CONSISTENCY): https://cassandra.apache.org/doc/latest/cassandra/managing/tools/cqlsh.html - Apache Cassandra source —
UnavailableException: https://raw.githubusercontent.com/apache/cassandra/trunk/src/java/org/apache/cassandra/exceptions/UnavailableException.java - Apache Cassandra source —
RequestTimeoutException: https://raw.githubusercontent.com/apache/cassandra/trunk/src/java/org/apache/cassandra/exceptions/RequestTimeoutException.java - Amazon DynamoDB — Read consistency: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
- Amazon DynamoDB — Global tables, how it works (MREC, MRSC): https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/V2globaltables_HowItWorks.html
- MongoDB — Write concern: https://www.mongodb.com/docs/manual/reference/write-concern/
- MongoDB — Read concern: https://www.mongodb.com/docs/manual/reference/read-concern/
- MongoDB — Read concern "linearizable": https://www.mongodb.com/docs/manual/reference/read-concern-linearizable/
- MongoDB — Error codes (
error_codes.yml): https://raw.githubusercontent.com/mongodb/mongo/master/src/mongo/base/error_codes.yml - etcd — API guarantees: https://etcd.io/docs/v3.5/learning/api_guarantees/
- etcd — API reference (Range serializable): https://etcd.io/docs/v3.5/learning/api/
- etcd — etcdctl README (
--consistency): https://raw.githubusercontent.com/etcd-io/etcd/main/etcdctl/README.md - etcd — gRPC error strings (
rpctypes/error.go): https://raw.githubusercontent.com/etcd-io/etcd/main/api/v3rpc/rpctypes/error.go - ZooKeeper — Programmer's Guide (consistency guarantees,
sync()): https://zookeeper.apache.org/doc/r3.9.4/zookeeperProgrammers.html - HashiCorp Consul — Consistency modes: https://developer.hashicorp.com/consul/api-docs/features/consistency
- PostgreSQL — Write Ahead Log settings (
synchronous_commit): https://www.postgresql.org/docs/current/runtime-config-wal.html - PostgreSQL — Replication settings (
synchronous_standby_names): https://www.postgresql.org/docs/current/runtime-config-replication.html - PostgreSQL — Log-shipping standby servers (synchronous replication): https://www.postgresql.org/docs/current/warm-standby.html
- PostgreSQL source —
syncrep.c(cancel warnings): https://raw.githubusercontent.com/postgres/postgres/master/src/backend/replication/syncrep.c - Apache Kafka — Producer configs (
acks): https://kafka.apache.org/44/configuration/producer-configs/ - Apache Kafka — Topic configs (
min.insync.replicas,unclean.leader.election.enable): https://kafka.apache.org/44/configuration/topic-configs/ - Apache Kafka — Design (replication, ISR, unclean leader election): https://kafka.apache.org/44/design/design/
- Apache Kafka source —
Errors.java: https://raw.githubusercontent.com/apache/kafka/trunk/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java - Google Cloud Spanner — TrueTime and external consistency: https://cloud.google.com/spanner/docs/true-time-external-consistency
- CockroachDB — Replication layer: https://www.cockroachlabs.com/docs/stable/architecture/replication-layer
- Cockroach Labs blog — Living Without Atomic Clocks: https://www.cockroachlabs.com/blog/living-without-atomic-clocks/
- CockroachDB —
cockroach start(--max-offset): https://www.cockroachlabs.com/docs/stable/cockroach-start - CockroachDB — Multi-region overview (
REGIONAL BY ROW): https://www.cockroachlabs.com/docs/stable/multiregion-overview - Apache Cassandra — Hints (
max_hint_window): https://cassandra.apache.org/doc/latest/cassandra/managing/operating/hints.html - Riak KV — Replication properties (
n_val,r,w,pr,pw, sloppy quorum): https://docs.riak.com/riak/kv/latest/developing/app-guide/replication-properties/index.html - Riak KV — Eventual consistency: https://docs.riak.com/riak/kv/latest/learn/concepts/eventual-consistency/index.html
- Laravel 13 — Database (read/write connections, sticky,
PreventStaleDatabaseReads,usingWritePdo): https://laravel.com/docs/13.x/database - Laravel framework source —
PreventStaleDatabaseReads: https://raw.githubusercontent.com/laravel/framework/13.x/src/Illuminate/Foundation/Http/Middleware/PreventStaleDatabaseReads.php - MongoDB Laravel integration — Connection options: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/fundamentals/connection/connection-options/
- MongoDB Laravel integration source —
Connection.php(getDatabase): https://raw.githubusercontent.com/mongodb/laravel-mongodb/5.x/src/Connection.php - MongoDB PHP library —
MongoDB\Database::selectCollection(): https://www.mongodb.com/docs/php-library/current/reference/method/MongoDBDatabase-selectCollection/ - PHP manual —
MongoDB\Driver\ReadConcern: https://www.php.net/manual/en/class.mongodb-driver-readconcern.php - PHP manual —
MongoDB\Driver\WriteConcern::__construct: https://www.php.net/manual/en/mongodb-driver-writeconcern.construct.php - Go — etcd
clientv3: https://pkg.go.dev/go.etcd.io/etcd/client/v3 - Go — MongoDB driver v2
readconcern: https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/mongo/readconcern - Go — MongoDB driver v2
writeconcern: https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/mongo/writeconcern - Go — gocql: https://pkg.go.dev/github.com/gocql/gocql
- Go — franz-go
kgo: https://pkg.go.dev/github.com/twmb/franz-go/pkg/kgo - Go — AWS SDK for Go v2 DynamoDB: https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb