Skip to content

Consistency Models: Linearizability vs Serializability, Causal, Client-Centric, Convergence ​

"Linearizability provides the illusion that each operation applied by concurrent processes takes effect instantaneously at some point between its invocation and its response" — Maurice Herlihy و Jeannette Wing، Linearizability: A Correctness Condition for Concurrent Objects، ACM TOPLAS، ۱۹۹۰

خلاصه (Summary): مدل سازگاری (Consistency Model) قرارداد میان یک سیستم replicated و کلاینت‌هایش است: یک read با توجه به همهٔ نوشتن‌ها و زمانشان، مجاز است چه نتیجه‌ای برگرداند. این صفحه کل نقشه را از linearizability و strict serializability در بالا تا eventual consistency در پایین می‌چیند و نشان می‌دهد هر محصول واقعی هر سطح را چطور عرضه می‌کند. تمرکز (Focus): linearizability (رفتار تک‌نسخه‌ای و ترتیب زمان واقعی)، sequential consistency، causal و causal+، PRAM/FIFO، eventual و strong eventual consistency، چهار session guarantee، خانوادهٔ تراکنشی (serializable، strict serializable، snapshot isolation، read committed)، اینکه چرا linearizability و serializability دو محور جدا هستند، read خطی در سیستم‌های Raft و Paxos (ReadIndex، lease read، quorum read)، ساعت‌ها (Lamport، vector، HLC، TrueTime)، رفتار محصولات (Spanner، CockroachDB، Cassandra، DynamoDB، MongoDB، Redis، PostgreSQL)، همگرایی، تست با Jepsen، Elle، Knossos و Porcupine، و انتخاب برای هر use case. هدف یادگیری (Learning goal): برای هر قابلیت بگویید به کدام مدل سازگاری نیاز دارد و کاربر زیر مدل ضعیف‌تر چه می‌بیند؛ یک anomaly را در history تشخیص دهید؛ محصول را طوری تنظیم کنید که آن مدل را بدهد (read concern، ConsistentRead، IF NOT EXISTS، version token، sticky read)؛ و ادعا را با یک checker تست کنید، نه با بروشور.

این فصل در گروه Consistency & Distributed Data است، درست بعد از CAP زیر partition واقعی، CP در برابر AP و PACELC که می‌گوید زیر partition باید انتخاب کنید، و پیش از ACID در برابر BASE و توپولوژی‌های Replication که می‌گویند replicaها چطور به هم وصل می‌شوند. قاب توزیع‌شدهٔ سازگاری مال این صفحه است. ناهنجاری‌های درون یک دیتابیس (dirty read، write skew، phantom) در Isolation Levelها آموزش داده شده‌اند؛ سازوکار replication و lag در Replication، Read Replica و Failover؛ درونِ consensus در Distributed SQL، Consensus و 2PC؛ ساعت‌ها با عمق کامل در Vector Clock، Lamport Clock و علیت توزیع‌شده؛ ترمیم و anti-entropy در Merkle Tree، Read Repair، Anti-Entropy و Tombstone؛ و ادغام ساختاری در CRDTها.

نقشهٔ صفحه ​

دنبال چه هستیدبروید به
کل صفحه در سه جدولهمه‌چیز در یک دقیقه
مدل سازگاری دقیقاً چیستچرا وجود دارد
Lamport، Herlihy و Wing، Terry، COPS، Spanner، Jepsenاز کجا آمده
Linearizability و CAS registerLinearizability
Sequential consistencySequential
Causal، causal+، PRAM/FIFOCausal، PRAM
Eventual، strong eventual، همگراییEventual و همگرایی
Read-your-writes، monotonic reads/writes، writes-follow-readsSession guarantees
Serializable، strict serializable، snapshot isolation، read committedمدل‌های تراکنشی
تفاوت linearizability و serializabilityLinearizability در برابر serializability
ReadIndex، lease read، quorum readRead خطی در سیستم‌های consensus
Lamport، vector، HLC، TrueTime، clock skewساعت‌ها
Spanner، CockroachDB، Cassandra، DynamoDB، MongoDB، Redis، PostgreSQL واقعاً چه می‌دهندمحصولات
تنظیم‌ها و پیام‌های خطاسازوکار
کدGo، Laravel
پروفایل کهنه، رزرو دوبل، پاسخ پیش از سؤال، clock skewحل مسئله‌های کلاسیک
Jepsen، Elle، Knossos، Porcupineتست سازگاری
کدام مدل برای کدام قابلیتانتخاب
از monolith تا چندمنطقه‌ایدر معماری
اجرای checker و session clientآزمایشگاه
باورهای غلط، چکیده، خودآزمایی، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه ​

مدل‌های تک‌شیئی، از قوی به ضعیف.

مدلبه زبان سادهمثال کوچکِ چیزی که ممنوع می‌کندزیر partition در دسترس است؟نمونهٔ محصول
Linearizableمثل یک نسخهٔ واحد رفتار می‌کند؛ هر عملیات در یک لحظه درون بازهٔ فراخوانی‌اش اثر می‌کندwrite مقدار 1 جواب OK داده؛ readی که بعدش شروع شده 0 برمی‌گرداندنهread پیش‌فرض etcd؛ read concern "linearizable" در MongoDB؛ LWT در Cassandra روی یک partition
Sequentialیک ترتیب کل که همه قبولش دارند، ترتیب خود هر کلاینت حفظ می‌شود؛ ممکن است از زمان واقعی عقب باشدکلاینت write خودش را می‌بیند و بعد دیگر نمی‌بیندنهمدل حافظهٔ CPU در مقالهٔ Lamport؛ read از followerهای یک log در Raft
Causal (و causal+)علت پیش از معلول برای همه؛ نوشتن‌های بی‌ربط ممکن است با ترتیب متفاوت دیده شوندپاسخ «آره» پیش از سؤال «ناهار؟» دیده شودSticky availablesessionهای causally consistent در MongoDB؛ COPS
PRAM / FIFOنوشتن‌های هر نویسنده به همان ترتیبی دیده می‌شوند که صادر شده‌اندویرایش دوم کاربر پیش از ویرایش اولش دیده شودSticky availableصف تک‌partition؛ log مرتب به‌ازای هر کلید
Session guaranteesیک کلاینت هیچ‌وقت با تاریخچهٔ خودش تناقض نمی‌بیندکامنتی که خودتان گذاشتید بعد از ارسال غیبش بزندRYW sticky؛ MR/MW/WFR کاملاًsticky در Laravel، version token، session در MongoDB
Eventualاگر نوشتن متوقف شود، replicaها در نهایت برابر می‌شونددر کوتاه‌مدت هیچ‌چیزبلهread پیش‌فرض DynamoDB؛ ONE در Cassandra؛ replicaهای Redis
Strong eventualreplicaهایی که updateهای یکسان دیده‌اند برابرند، بدون مرحلهٔ حل تعارضدو replica با updateهای یکسان ولی حالت متفاوتبلهstoreها و کتابخانه‌های مبتنی بر CRDT (ببینید CRDTها)

مدل‌های تراکنشی، از قوی به ضعیف.

مدلبه زبان سادهچه چیزی نسبت به ردیف بعدی اضافه می‌کندنمونهٔ محصول
Strict serializable / external consistencyتراکنش‌ها یکی‌یکی اجرا می‌شوند، با ترتیبی که زمان واقعی را رعایت می‌کندترتیب زمان واقعیSpanner (پیش‌فرض)؛ یک دیتابیس تک‌گرهٔ SERIALIZABLE
Serializableتراکنش‌ها معادل یک اجرای یکی‌یکی هستندنه write skew، نه phantomSERIALIZABLE در CockroachDB (پیش‌فرض)؛ SSI در PostgreSQL
Snapshot isolationهر تراکنش یک snapshot سازگار می‌خواند؛ روی یک ردیف، اولین commit برنده استنه non-repeatable read، نه lost update روی یک ردیفREPEATABLE READ در PostgreSQL؛ قوی‌ترین سطح Oracle (طبق بررسی HAT، serializable نیست)؛ تراکنش‌های "snapshot" در MongoDB
Read committedهر statement فقط دادهٔ commitشده می‌بیندنه dirty readپیش‌فرض PostgreSQL؛ READ COMMITTED در CockroachDB؛ read آیتم در DynamoDB

ابزارهایی که یک مدل را می‌سازند، و هزینه‌شان.

ابزارچه می‌دهدهزینهبخش
یک leader + consensus (Raft، Paxos)write خطییک رفت‌وبرگشت quorum برای هر writeRead در consensus
ReadIndex یا quorum readread خطییک دور heartbeat یا quorum برای هر readRead در consensus
Lease read روی leaderread خطی، به شرط رفتار درست ساعت‌هادرستی وابسته به clock skew محدودRead در consensus
Commit wait در TrueTimestrict serializability در مقیاس سیارهحدود 2 x epsilon انتظار برای هر commitساعت‌ها
HLC + پنجرهٔ عدم‌قطعیتserializability، و linearizability تک‌کلیدی تا وقتی skew زیر --max-offset استrestart شدن readهاساعت‌ها
Version token (LSN، GTID، operationTime)read-your-writes و monotonic reads روی replicafallback به primary وقتی replica عقب استSession guarantees
ردیابی وابستگی (COPS) یا session causalcausal+متادیتا برای هر write، دیرتر دیده‌شدنCausal
CRDT، anti-entropy، read repairهمگراییمعنای ادغام باید با داده جور باشدEventual
Strict serializableSerializableRepeatable readSnapshot isolationCursor stabilityMonotonic atomic viewRead committedRead uncommittedLinearizableSequentialCausalWrites follow readsPRAMMonotonic readsMonotonic writesRead your writesmulti-object transactionssingle-object operationsunavailable during a partitionsticky available (client stays on one node)totally availableArrow = implies (stronger to weaker). After jepsen.io/consistency/models.

این نقشه بازسازی سلسله‌مراتب Jepsen است. هر پیکان یعنی «نتیجه می‌دهد» (implies): هر history که strict serializable باشد، linearizable و serializable هم هست؛ هر history خطی، sequential است؛ و همین‌طور به پایین. رنگ، بهای دسترس‌پذیری است. جمع‌بندی خود Jepsen: "All models at or stronger than cursor stability, snapshot isolation, and sequential cannot be totally available in asynchronous networks. All models at or stronger than read your writes can be at most sticky available."

چرا وجود دارد ​

همین که از یک مقدار دو نسخه نگه دارید (replica، cache، منطقهٔ دوم)، ممکن است به یک read نسخه‌ای جواب بدهد که هنوز از آخرین write خبر ندارد. مدل سازگاری (Consistency Model) پاسخ مکتوب به این سؤال است: «آن read اجازه دارد چه برگرداند؟» Jepsen دقیقش را می‌گوید: "A consistency model is a safety property which declares what a system can do. Formally, a consistency model defines a set of histories that a system can legally execute." یک history فهرست عملیات‌ها با زمان فراخوانی، زمان پاسخ و نتیجه است. مدل، صافی‌ای روی historyهاست: مجاز یا غیرمجاز.

مدل قوی‌ترمدل ضعیف‌تر
استدلال درباره‌اش آسان است: «مثل یک ماشین رفتار می‌کند»هر قابلیت باید به دادهٔ کهنه یا جابه‌جا فکر کند
هماهنگی لازم دارد: leader، quorum، انتظارهر replica تنها جواب می‌دهد
تأخیر بیشتر، مخصوصاً بین منطقه‌ها (یک رفت‌وبرگشت یا بیشتر برای هر عملیات)تأخیر محلی
در سمت اقلیت partition در دسترس نیستدر هر دو سمت در دسترس است
throughput کمتر برای هر کلید (رقابت، consensus)با تعداد replica مقیاس می‌گیرد
باگ به شکل خطا و timeout دیده می‌شودباگ به شکل دادهٔ غلط، چند روز بعد، دیده می‌شود

تمثیلی که در کل صفحه به کار می‌بریم: تقویم کاغذی آشپزخانه و گوشی‌های اعضای خانواده. یک تقویم کاغذی روی دیوار آشپزخانه linearizable است: یک نسخه هست و همین که کسی بنویسد «دندان‌پزشکی، سه‌شنبه ساعت ۳»، هر کس بعد از آن نگاه کند می‌بیندش. حالا هر کس یک تقویم همگام روی گوشی دارد. Eventual consistency یعنی «گوشی‌ها هر وقت Wi-Fi گرفتند همگام می‌شوند». Read-your-writes یعنی «دست‌کم گوشی خودم چیزی را که همین الان اضافه کردم نشان می‌دهد». Monotonic reads یعنی «گوشی من هیچ‌وقت نسخهٔ قدیمی‌تری از هفته را نسبت به آنچه قبلاً نشانم داده نشان نمی‌دهد». Causal consistency یعنی «اگر مامان وقت دندان‌پزشکی را به‌خاطر عوض شدن پرواز بابا جابه‌جا کرد، هیچ‌کس وقت جدید دندان‌پزشکی را بدون تغییر پرواز نمی‌بیند». Serializability دربارهٔ یک جلسهٔ برنامه‌ریزی کامل است: «جای سه‌شنبه و پنج‌شنبه را عوض کن» باید یا کامل انجام شود یا اصلاً، انگار یک نفر تنها انجامش داده.

سه بدفهمی رایج، از همین ابتدا ​

  1. «Strong consistency» یک معنا دارد. فروشنده‌ها این واژه را برای read خطی (etcd)، برای «از leader بخوان» (ConsistentRead در DynamoDB)، برای تراکنش serializable (CockroachDB) و برای external consistency (Spanner) به کار می‌برند. همیشه بپرسید: تک‌شیء یا تراکنش، و آیا ترتیب زمان واقعی هم در آن هست؟
  2. «Serializable از linearizable قوی‌تر است.» این‌ها دو محور جدا هستند. Serializability دربارهٔ تراکنش‌های چندشیئی است و از زمان واقعی چیزی نمی‌گوید؛ linearizability دربارهٔ عملیات تکی است و همه‌چیز را دربارهٔ زمان واقعی می‌گوید. Peter Bailis: "Linearizability is a guarantee about single operations on single objects." ترکیب این دو strict serializability است.
  3. «C در CAP همان C در ACID است.» C در CAP یعنی linearizability (Kleppmann: "Consistency in CAP actually means linearizability"). C در ACID یعنی «invariantهای برنامه برقرار می‌مانند» که دیتابیس از راه isolation، یعنی I، به آن کمک می‌کند.

از کجا آمده ​

۱۹۷۸، رابطهٔ happened-before. مقالهٔ Leslie Lamport با نام Time, Clocks, and the Ordering of Events in a Distributed System رابطهٔ «happened before» را به‌عنوان یک ترتیب جزئی (Partial Order) روی رویدادها تعریف کرد، همراه با ساعت‌های منطقی (Logical Clock) که به آن احترام می‌گذارند. همهٔ مدل‌های causal این صفحه روی همین رابطه ساخته شده‌اند.

۱۹۷۹، sequential consistency. مقالهٔ دیگر Lamport با نام How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs چندپردازنده‌ای را sequentially consistent نامید که در آن "the result of any execution is the same as if the operations of all the processors were executed in some sequential order, and the operations of each individual processor appear in this sequence in the order specified by its program."

۱۹۸۸، PRAM. Lipton و Sandberg حافظهٔ coherent را شل کردند تا write‌های هر پردازنده به ترتیب خودش دیده شود ولی writeهای پردازنده‌های مختلف بتوانند جاهای مختلف به ترتیب متفاوت درهم شوند (صفحهٔ PRAM در Jepsen).

۱۹۹۰، linearizability. Herlihy و Wing قید زمان واقعی (Real-Time) را افزودند و نشان دادند که این ویژگی ترکیب‌پذیر (Composable) است: اگر هر شیء linearizable باشد، کل سیستم هم هست. همچنین آن را کنار مفهوم دیتابیسی گذاشتند: "Linearizability can be viewed as a special case of strict serializability where transactions are restricted to consist of a single operation applied to a single object."

۱۹۹۴، session guarantees. Terry، Demers، Petersen، Spreitzer، Theimer و Welch در پروژهٔ Bayou در Xerox PARC چهار تضمین تعریف کردند که یک کلاینت تنها حتی از یک store با الگوی «read-any/write-any» هم می‌تواند بگیرد: "Read Your Writes - read operations reflect previous writes. Monotonic Reads - successive reads reflect a non-decreasing set of writes. Writes Follow Reads - writes are propagated after reads on which they depend. Monotonic Writes - writes are propagated after writes that logically precede them."

۲۰۰۰ تا ۲۰۱۲، CAP و پیامدهایش. حدس Brewer (۲۰۰۰) و اثبات Gilbert و Lynch (۲۰۰۲) linearizability را همان «C»ای کردند که همهٔ معمارها بر سرش بحث می‌کنند؛ ببینید CAP و PACELC.

۲۰۱۱، causal+. مقالهٔ COPS از Lloyd، Freedman، Kaminsky و Andersen مدلی را نام‌گذاری کرد به اسم "causal consistency with convergent conflict handling, or causal+" و نشان داد این مدل بین دیتاسنترها مقیاس می‌گیرد.

۲۰۱۲، Spanner. مقالهٔ OSDI گوگل تراکنش‌های externally consistent را در مقیاس جهانی با TrueTime ارائه کرد: "if a transaction T1 commits before another transaction T2 starts, then T1’s commit timestamp is smaller than T2’s."

۲۰۱۳، HAT. مقالهٔ Highly Available Transactions از Bailis و همکاران همهٔ isolation levelها و session guaranteeها را به دو دسته تقسیم کرد: «بدون هماهنگی ممکن» و «ناممکن». Read Committed و session guaranteeها با دسترس‌پذیری بالا ممکن‌اند؛ Snapshot Isolation و Repeatable Read نه.

۲۰۱۳ تا امروز، Jepsen. تحلیل‌های Jepsen از Kyle Kingsbury، checkerهای Knossos و Elle و نقشهٔ سازگاری jepsen.io پرسش «این دیتابیس واقعاً کدام مدل را می‌دهد» را به چیزی تبدیل کردند که می‌شود تستش کرد.

text
     Year   Idea                                    What it gave practitioners
1    1978   Happened-before, Lamport clocks          Causality without synchronised clocks
2    1979   Sequential consistency                    One agreed order, per-process order kept
3    1988   PRAM (pipelined RAM)                      Per-writer FIFO order only
4    1990   Linearizability (Herlihy and Wing)        Real-time single-copy semantics, composable
5    1994   Session guarantees (Bayou)                RYW, MR, WFR, MW for one client
6    2002   CAP proof (Gilbert and Lynch)             Linearizable + available + partitions: pick two
7    2011   COPS causal+                              Causal + convergence at data-centre scale
8    2012   Spanner TrueTime, external consistency    Strict serializability across continents
9    2013   Highly Available Transactions             Which levels need coordination
10   2014   Hybrid logical clocks                     Physical-time-like timestamps that respect causality
11   2013+  Jepsen, Knossos, Elle, Porcupine          Consistency claims checked against histories

فهرست مفاهیم ​

هر بلوک ترتیب ثابتی دارد: به زبان ساده، باور غلط رایج، تعریف، timeline، سناریوی واقعی، اینکه محصولات چه می‌دهند، و راه درست استفاده.

Linearizability حیاتی ​

به زبان ساده: سیستم طوری رفتار می‌کند که انگار فقط یک نسخه از داده وجود دارد، و هر عملیات در یک لحظه، جایی میان زمانی که صدایش می‌زنید و زمانی که برمی‌گردد، اثر می‌کند.

بدفهمی رایج: «اگر replication همگام (Synchronous) باشد، readها خطی‌اند.» لزوماً نه: followerی که write را دریافت کرده شاید هنوز آن را اعمال نکرده باشد، و leader قدیمی که برکنار شده ولی خبر ندارد هنوز می‌تواند به read جواب بدهد. Linearizability ویژگی کل مسیر read و write است، failover هم جزوش.

تعریف: یک history خطی است اگر ترتیبی کلی از همهٔ عملیات‌ها وجود داشته باشد که (۱) با مشخصهٔ ترتیبی شیء جور باشد (register آخرین مقدار نوشته‌شده را برمی‌گرداند)، و (۲) ترتیب زمان واقعی (Real-Time Order) را رعایت کند: اگر عملیات A پیش از فراخوانی B برگشته باشد، A پیش از B می‌آید. بیان Jepsen: "every operation appears to take place atomically, in some order, consistent with the real-time ordering of those operations". به آن atomic consistency، معنای تک‌نسخه‌ای (Single-Copy) یا «C در CAP» هم می‌گویند. چون محلی (ترکیب‌پذیر) است، می‌توانید برای هر کلید جدا استدلال کنید.

text
     Client A                     Client B                     Client C
1    write(x=1) invoked
2                                 read(x) invoked
3                                 read(x) returns 1            (point after A's write took effect)
4                                                              read(x) invoked (after B returned)
5                                                              read(x) returns 0  <- ILLEGAL: value went back in time
6    write(x=1) returns ok
     Overlapping operations may be ordered either way; non-overlapping ones may not.
ABCABCwrite(1) ... okread() = 1read() = 0write(1) ... okread() = 0read() = 1NOT linearizableLinearizableC started after B returned, yet saw the older valueorder: B read 0, A write 1, C read 1timetimeBar = invocation to response. Dot = the instant the operation appears to take effect (linearization point).Both histories are sequentially consistent; only real-time order separates them.

در تصویر، میله بازهٔ فراخوانی تا پاسخ است و نقطه لحظه‌ای است که عملیات ظاهراً اثر می‌کند (نقطهٔ linearization). در سمت چپ، C بعد از برگشتن B شروع کرده و باز مقدار قدیمی را دیده: غیرمجاز. در سمت راست ترتیب «B صفر می‌خواند، A یک می‌نویسد، C یک می‌خواند» مجاز است.

CAS register. مدلی که بیش از همه تستش می‌کنید یک register با read، write و مقایسه-و-جایگزینی (Compare-and-Set، CAS) است. CAS خطی همان چیزی است که leader election، قفل توزیع‌شده، نام کاربری یکتا و «رزرو آخرین صندلی» را درست می‌کند: دو فراخوانی همزمان cas(free -> taken) نباید هر دو موفق شوند. تراکنش‌های etcd (Txn با Compare روی mod_revision)، UPDATE ... IF در Cassandra، ConditionExpression روی یک آیتم در DynamoDB و SET key value NX روی یک primary در Redis همه یک CAS روی یک کلید عرضه می‌کنند.

سناریوی واقعی: ثبت نام کاربری («sara آزاد است؟ بگیرش»)؛ رزرو صندلی یا موجودی برای آخرین واحد؛ leader election و fencing token (Leader Election، قفل توزیع‌شده)؛ سرویس feature flag که «خاموش» باید همین حالا برای همهٔ سرورها خاموش باشد؛ بررسی موجودی پیش از برداشت روی کلید یک حساب.

چه چیزی فراهمش می‌کند:

محصولعملیات خطیچطورنکته
etcdهمهٔ readها و writeها به‌طور پیش‌فرضRaft؛ readها با ReadIndexدرخواست در حالت «serializable» محلی است و ممکن است کهنه باشد
MongoDBread با readConcern: "linearizable" روی primary، write با w: "majority"primary با اکثریت تأیید می‌کند که هنوز primary استفقط یک سند؛ کندتر؛ maxTimeMS لازم است
Cassandra / ScyllaDBLightweight transaction (IF NOT EXISTS، IF col = ?)Paxos برای هر partition"non-negligible performance cost"؛ فقط درون یک partition
DynamoDBwrite شرطی روی یک آیتم؛ read با ConsistentRead: true روی جدول پایهleader پارتیشن آن آیتمنه برای GSI و Stream؛ global table به MRSC نیاز دارد
Spannerهمهٔ تراکنش‌های read-write و strong readPaxos + TrueTimecommit wait تأخیر اضافه می‌کند
CockroachDBعملیات تک‌کلیدی تا وقتی clock skew درون --max-offset استRaft + leaseholder + HLCبین چند کلید ادعا نمی‌شود (ببینید ساعت‌ها)
Redis (یک primary)دستورها روی primary تا وقتی primary می‌مانداجرای تک‌نخیreplication ناهمگام: failover می‌تواند writeهای تأییدشده را از دست بدهد
PostgreSQL (یک primary)هر statement روی primaryیک درخت پردازه، یک WALread روی standbyها خطی نیست

راه درست: عملیاتی را که باید خطی باشد (claim، رزرو، قفل، یکتایی) به مسیر primary یا consensus بفرستید و آن مسیر را کوچک نگه دارید؛ آن را به شکل یک CAS روی یک کلید بنویسید؛ و با linearizability checker تستش کنید (Go).

Sequential consistency مهم ​

به زبان ساده: همه یک ترتیب واحد از عملیات‌ها را می‌بینند و عملیات هر کلاینت به همان ترتیبی می‌ماند که صادر کرده، ولی این ترتیب ممکن است از ساعت دیواری عقب باشد.

بدفهمی رایج: «Sequential تقریباً همان linearizable است.» تکهٔ گمشده دقیقاً همانی است که کاربر می‌بیند: زمان واقعی. زیر sequential consistency، یک write می‌تواند OK برگرداند و کلاینت دیگری بعد از آن هنوز مقدار قدیمی را بخواند، چون آن کلاینت اجازه دارد در ترتیب توافق‌شده «عقب» باشد. چیزی که ممنوع است برگشتن است: Jepsen می‌گوید "once a process A has observed some operation from process B, it can never observe a state prior to B."

تعریف: تعریف Lamport در ۱۹۷۹ که بالاتر نقل شد. Viotti و Vukolić آن را به SingleOrder به‌علاوهٔ ترتیب هر process می‌شکنند، بدون قید RealTime.

text
     Client A                  Client B
1    write(x=1) -> ok
2                              read(x) -> 0     legal under sequential: B's read ordered before A's write
3                              read(x) -> 1
4                              read(x) -> 0     ILLEGAL: B already saw 1 and cannot go back

سناریوی واقعی: اتاق گفت‌وگویی که همه باید پیام‌ها را به یک ترتیب ببینند ولی چند صد میلی‌ثانیه تأخیر اشکالی ندارد؛ state machine تکثیرشده‌ای که followerهایش از state اعمال‌شدهٔ خودشان read جواب می‌دهند (sequential هستند، نه linearizable)؛ حافظهٔ CPU چندهسته‌ای (زمینهٔ اصلی Lamport).

چه چیزی فراهمش می‌کند:

محصول / تنظیمرفتار
read از follower در Raft یا Paxos (حالت serializable در etcd)یک ترتیب log؛ follower می‌تواند عقب باشد: شبه‌sequential و کهنه
Total order broadcast (یک partition در Kafka)هر consumer همان ترتیب یک partition را می‌بیند، هر کدام با سرعت خودش
مدل‌های حافظهٔ x86-TSO، ARM، Java و Goبه‌طور پیش‌فرض ضعیف‌تر از sequential؛ فقط برای برنامه‌های بدون data race sequential هستند

راه درست: اگر قابلیتی «دیر ولی هیچ‌وقت نامرتب» را تحمل می‌کند، read از follower یک log مبتنی بر consensus خیلی ارزان‌تر از read خطی است. اگر کاربر با یک کانال جانبی مقایسه می‌کند («همین الان تلفنی گفتم»)، به linearizability نیاز دارید.

Causal consistency و causal+ حیاتی ​

به زبان ساده: اگر یک write می‌توانسته روی write دیگری اثر بگذارد (پست شما را خواندم و جواب دادم)، همه آن‌ها را به همین ترتیب می‌بینند؛ writeهای بی‌ربط ممکن است برای افراد مختلف با ترتیب متفاوت ظاهر شوند.

بدفهمی رایج: «Causal consistency ساعت‌های همگام لازم دارد.» چیزی که لازم دارد ردیابی وابستگی (Dependency Tracking) است: vector clock، فهرست صریح وابستگی‌ها (COPS) یا یک session token (operationTime و cluster time در MongoDB). ساعت دیواری نمی‌تواند بگوید «B، A را دیده بود».

تعریف: عملیات‌هایی که رابطهٔ علّی دارند (ترتیب برنامه، reads-from و بستار تعدی‌شان، یعنی happened-before لمپورت) را همهٔ processها با یک ترتیب می‌بینند. عملیات همزمان می‌توانند با هر ترتیبی دیده شوند. Causal+ (در COPS) حل تعارض همگرا (Convergent Conflict Handling) را اضافه می‌کند: replicaهایی که writeهای یکسان دیده‌اند در حالت یکسان تمام می‌کنند. مثال Jepsen: Attiya می‌پرسد «ناهار؟»، Barbarella می‌گوید «آره» و Cyrus می‌گوید «نه»؛ ناظرها می‌توانند «آره» و «نه» را با هر ترتیبی ببینند، ولی هیچ‌کس جواب را پیش از سؤال نمی‌بیند.

text
     DC Europe                         DC Asia                          Observer in DC US
1    Ana posts photo P (w1)
2    Ana removes boss from ACL (w2)
3                                      Ben reads ACL (sees w2)
4                                      Ben comments "nice!" on P (w3, depends on w1)
5                                                                       receives w3 first
6                                                                       causal: w3 held back until w1 arrives
7                                                                       eventual only: comment on a photo that does not exist yet

سناریوی واقعی: فیدهای اجتماعی (کامنت پیش از پستی که به آن جواب می‌دهد)؛ کنترل دسترسی («رئیس را از آلبوم حذف کن، بعد عکس‌های مهمانی را آپلود کن»: مثال انگیزشی کلاسیک COPS)؛ چت با threadها؛ ویرایش مشارکتی؛ سبد خریدی که «حذف کالا» نباید پیش از «افزودن کالا» دیده شود.

چه چیزی فراهمش می‌کند:

محصولسازوکارتضمینشرط
sessionهای causally consistent در MongoDBoperationTime + cluster time؛ driverها afterClusterTime را می‌گذارندRYW، MR، MW، WFR درون sessionread concern برابر "majority" و write concern برابر "majority"
COPS / Eiger (پژوهشی)فهرست صریح وابستگی برای هر writeCausal+ بین دیتاسنترهاوابستگی‌ها پیش از دیده‌شدن write بررسی می‌شوند
storeهای سبک Dynamo با version vectorVersion vector، siblingتشخیص همزمانی، ادغام در برنامهکلاینت‌ها باید siblingها را حل کنند
کتابخانه‌های CRDT (Automerge، Yjs)تحویل causal + تابع ادغامStrong eventual + causalداده باید با CRDT جور باشد (CRDTها)

Jepsen همچنین می‌گوید causal consistency «sticky available» است: هنگام partition هر کلاینت می‌تواند پیش برود، به شرط اینکه روی همان سرور بماند.

راه درست: علیت را همراه درخواست حمل کنید. در MongoDB برای هر جریان منطقی کاربر یک session causally consistent با read و write concern اکثریتی بسازید و operationTime session را بین سرویس‌ها پاس بدهید. در لایهٔ read از replica که خودتان می‌سازید، یک version token برای هر session بخش session-level را می‌دهد (Session guarantees).

PRAM و FIFO consistency تکمیلی ​

به زبان ساده: writeهای هر نویسنده همه‌جا به همان ترتیبی می‌رسند که خودش انجام داده؛ writeهای نویسنده‌های مختلف ممکن است روی هر replica جور دیگری درهم شوند.

بدفهمی رایج: «FIFO همان causal است.» FIFO قاعدهٔ writes-follow-reads را ندارد: اگر Ben بعد از خواندن پست Ana جواب بدهد، FIFO جلوی اینکه کسی اول جواب را ببیند نمی‌گیرد، چون دو write دو نویسندهٔ متفاوت دارند.

تعریف: Jepsen: "It enforces that any pair of writes executed by a single process are observed (everywhere) in the order the process executed them". و: "PRAM is exactly equivalent to read your writes, monotonic writes, and monotonic reads."

text
     Ana (writer)            Replica R1             Replica R2
1    w1: title="Draft"
2    w2: title="Final"
3                            applies w1, w2         applies w1, w2      FIFO: never w2 then w1
4    Ben writes w3 after reading w2
5                            applies w3             applies w3 before w1 allowed: different writer

سناریوی واقعی: یک partition در Kafka با کلید کاربر (ترتیب برای هر کلید؛ ببینید Ordering و Partitioning)؛ TCP درون یک اتصال؛ log همگام‌سازی هر دستگاه.

چه چیزی فراهمش می‌کند: یک log مرتب به‌ازای هر نویسنده یا هر کلید (partition در Kafka، یک Redis Stream، replication slot منطقی در PostgreSQL برای یک جدول) برای آن نویسنده یا کلید FIFO می‌دهد.

راه درست: پیام‌ها و writeهای تکثیرشده را با کلید موجودیتی بفرستید که ترتیبش مهم است؛ هر جا علیت بین موجودیت‌ها مهم شد، به causal بروید.

Eventual consistency، strong eventual consistency و همگرایی حیاتی ​

به زبان ساده: اگر همه نوشتن را متوقف کنند، همهٔ نسخه‌ها در نهایت یکی می‌شوند. تا آن موقع، یک read می‌تواند هر چیزی را که زمانی نوشته شده، قدیم یا جدید، با هر ترتیبی برگرداند.

بدفهمی رایج: «در نهایت یعنی ظرف یک ثانیه.» Eventual consistency هیچ کران زمانی و هیچ تضمین ترتیبی ندارد؛ DynamoDB برای global tableها عدد معمولی را مستند کرده ("typically within a second") ولی این مشاهدهٔ عملیاتی است، نه بخشی از مدل. همچنین نمی‌گوید کدام مقدار برنده است.

تعریف: eventual consistency: فقط liveness، یعنی همگرایی بعد از توقف writeها. Strong eventual consistency (Shapiro و همکاران ۲۰۱۱): هر دو replica که مجموعهٔ یکسانی از updateها را دریافت کرده‌اند در حالت یکسانی هستند، بدون rollback و بدون دور حل تعارض. همگرایی (Convergence) سازوکار است: anti-entropy (مقایسه با Merkle tree)، read repair، hinted handoff، gossip، و یک ادغام قطعی (last-writer-wins با timestamp، version vector با sibling، یا CRDT).

text
     Client           Replica A           Replica B           Replica C
1    write x=1  ->    x=1 (ack)
2    read x     ->                        x=0  (stale read: legal)
3                     gossip / hinted handoff -> x=1         x=0
4                     anti-entropy (Merkle compare) ------>   x=1
5    read x     ->                                            x=1  converged

سناریوی واقعی: شمارندهٔ like و بازدید؛ read کاتالوگ محصول پشت CDN؛ DNS؛ ایندکس جست‌وجویی که از دیتابیس تغذیه می‌شود؛ analytics؛ حضور آنلاین (نقطه‌های «آنلاین»)؛ ادغام سبد خرید در Dynamo آمازون.

چه چیزی فراهمش می‌کند:

محصولپیش‌فرضسازوکار همگرایی
DynamoDBread با eventual consistency (نصف قیمت strong)replication درون Region؛ MREC برای global tableها
Cassandraقابل تنظیم: ONE، QUORUM، LOCAL_QUORUM، ALLRead repair، hinted handoff، anti-entropy repair (Merkle tree)، LWW با timestamp نوشتن
replicaهای Redis / Redis Clusterreplication ناهمگامresync کامل یا جزئی؛ «آخرین failover برنده است»
read replicaهای PostgreSQL / MySQLstreaming ناهمگامبازپخش WAL / binlog
CDN، DNSبر پایهٔ TTLانقضا و revalidation

سطوح قابل‌تنظیم Cassandra "a version of Dynamo’s R + W > N consistency mechanism" هستند: با write و read در QUORUM، مجموعهٔ replicaها هم‌پوشانی دارند و این برای writeهای تمام‌شده read-your-writes می‌دهد، ولی بدون LWT خطی نیست (دو write همزمان quorum با timestamp کلاینت مرتب می‌شوند).

راه درست: پیش از رفتن به eventual، قاعدهٔ ادغام را تعیین کنید (LWW updateهای همزمان را گم می‌کند؛ هر جا گم شدن update مهم است CRDT یا sibling به کار ببرید)؛ readها را idempotent و UI را تحمل‌کنندهٔ «چند ثانیه کهنه» بسازید؛ برای دادهٔ خود کاربر session guarantee اضافه کنید. سازوکار ترمیم در Merkle Tree و Anti-Entropy و پروتکل‌های Gossip است.

Session guarantees (سازگاری کلاینت‌محور) حیاتی ​

به زبان ساده: نمی‌توانید به هر کاربر قول تازه‌ترین داده را بدهید، ولی می‌توانید قول بدهید سیستم هیچ‌وقت با کاری که خود او کرده یا دیده تناقض نشان ندهد.

بدفهمی رایج: «sticky session روی load balancer به ما read-your-writes می‌دهد.» این کاربر را به یک سرور برنامه سنجاق می‌کند، نه به یک replica دیتابیس؛ سرور برنامه هنوز از هر replicaیی که pool بدهد می‌خواند. و گزینهٔ sticky در Laravel فقط تا پایان همان request دوام دارد.

تعریف (Terry و همکاران ۱۹۹۴، Jepsen):

تضمینقولناهنجاری‌ای که جلویش را می‌گیرددسترس‌پذیری (Jepsen)
Read-your-writes (RYW، read-my-writes)read، writeهای قبلی همین session را بازتاب می‌دهد«پروفایلم را ذخیره کردم و اسم قدیمی برگشت»Sticky available
Monotonic reads (MR)readهای پیاپی هیچ‌وقت به حالت قدیمی‌تر برنمی‌گردندکامنتی ظاهر می‌شود و با refresh غیب می‌شودکاملاً در دسترس
Monotonic writes (MW)writeهای این session همه‌جا به ترتیب اعمال می‌شوندویرایش دوم پیش از اول اعمال می‌شود و اولی برنده می‌شودکاملاً در دسترس
Writes-follow-reads (WFR، علیت session)write بعد از writeهایی که این session خوانده مرتب می‌شودپاسخ پیش از پیامی که به آن جواب می‌دهد دیده می‌شودکاملاً در دسترس
text
     User session          App server         Primary (LSN)        Replica R1 (replayed)
1    POST /profile  ->     UPDATE ...   ->    commit at 0/3000148
2                          token = 0/3000148 stored in session
3    GET /profile   ->     R1 replayed >= 0/3000148 ?            0/3000100
4                          no -> read from primary: new name (RYW holds)
5    GET /profile   ->     R1 replayed >= 0/3000148 ?            0/3000200
6                          yes -> read from R1, token.read = 0/3000200 (MR holds from now on)
Browsersession cookieApp server APOST /profileApp server BGET /profilePrimarypg_current_wal_lsn()Replica 1replayed 0/3000100Replica 2replayed 0/30002001. UPDATE, COMMITtoken 0/3000148token in sessiontoken sent back2. replayed >= token?3a. no: read primary3b. yes: read hereSame idea, other products:MongoDB: operationTime,driver sets afterClusterTimeCockroachDB: AS OFSYSTEM TIME timestampRaft / etcd: log indexor revision

تصویر همان جریان را نشان می‌دهد: request دوم روی سرور برنامهٔ دیگری می‌نشیند، ولی token همراه session رفته است؛ replica اول عقب است و read به primary می‌رود، replica دوم جلوتر است و خودش جواب می‌دهد.

سناریوی واقعی: ویرایش پروفایل و صفحهٔ تنظیمات؛ ارسال کامنت و دیدنش؛ جریان checkout (سبد، سپس خلاصهٔ سفارش)؛ پنل ادمین که اپراتور قیمتی را عوض می‌کند و بلافاصله چکش می‌کند؛ اپ موبایل که بین Wi-Fi و شبکهٔ سلولی جابه‌جا می‌شود (لبهٔ متفاوت، replica متفاوت).

چه چیزی فراهمش می‌کند:

محصول / قابلیتRYWMRMWWFRدامنه
sticky => true در Laravelفقط همان requestفقط همان requestبله (یک primary)بله (یک primary)یک request HTTP
PreventStaleDatabaseReads در Laravel 13.xتا N ثانیه (پیش‌فرض 2) بعد از writeهمان پنجرهبلهبلهیک session، connection پیش‌فرض
version token با LSN / GTID (کد همین صفحه)بلهبلهبلهبلههر چیزی که token را حمل کند
session causally consistent در MongoDB با majority/majorityبلهبلهبلهبلهیک session (token قابل پاس دادن)
ConsistentRead: true در DynamoDBبله (جدول پایه، LSI)بلهبلهبلهبرای هر read، هزینهٔ 2 برابر
write و read با QUORUM در Cassandraبله برای writeهای تمام‌شدهبا writeهای ناموفق تضمین نیستLWW با timestampنهبرای هر درخواست
synchronous_commit = remote_apply در PostgreSQLبله روی standbyهای همگامبلهبلهبلههمهٔ sessionها؛ commit کندتر

راه درست: یک version token (LSN روی primary، مجموعهٔ GTID در MySQL، operationTime در MongoDB، اندیس Raft) را در session کاربر یا یک header پاسخ نگه دارید؛ فقط وقتی از replica بخوانید که دست‌کم تا آن token را اعمال کرده باشد؛ وگرنه کمی صبر کنید یا از primary بخوانید. کد در Go و Laravel.

مدل‌های تراکنشی: serializable، strict serializable، snapshot isolation، read committed حیاتی ​

به زبان ساده: مدل‌های تراکنشی می‌گویند گروه‌هایی از read و write روی چندین ردیف چطور درهم می‌شوند؛ مدل‌های تک‌شیئی می‌گویند یک کلید در طول زمان چطور رفتار می‌کند. یک دیتابیس توزیع‌شده باید به هر دو سؤال جواب بدهد.

بدفهمی رایج: «دیتابیس من serializable است، پس readی که بعد از commit بیاید آن commit را می‌بیند.» Serializability به‌تنهایی اجازه می‌دهد دیتابیس read بعدی شما را پیش از commit قبلی مرتب کند. Jepsen حالت افراطی‌اش را می‌گوید: "a serializable database can always return the empty state for any reads, by appearing to execute those reads at time 0." سیستم‌های واقعی عمداً این کار را نمی‌کنند، ولی read سریالی از replica عقب‌مانده یا با timestamp کهنه دقیقاً نسخهٔ ملایمی از همین است.

تعریف:

  • Serializable: نتیجه برابر یک اجرای سریالی از تراکنش‌های commitشده است. نه قید زمان واقعی، نه قید هر process.
  • Strict serializable (strong 1SR، در واژگان Spanner external consistency): serializable، به‌علاوهٔ اینکه ترتیب سریالی زمان واقعی را رعایت کند. Jepsen: "You can think of strict serializability as serializability’s total order of transactional multi-object operations, plus linearizability’s real-time constraints."
  • Snapshot isolation (SI): هر تراکنش از snapshotی می‌خواند که در شروعش گرفته شده و فقط وقتی commit می‌کند که هیچ تراکنش همزمانی همان ردیف‌ها را ننوشته باشد (اولین commit برنده). write skew مجاز است.
  • Read committed (RC): هر read فقط دادهٔ commitشده می‌بیند؛ statementهای مختلف ممکن است snapshotهای متفاوت ببینند.

خود ناهنجاری‌ها (dirty read، non-repeatable read، phantom، lost update، write skew) با timelineهای دوجلسه‌ای در Isolation Levelها آموزش داده شده‌اند؛ سؤال این‌جا این است که وقتی داده توزیع‌شده است چه عوض می‌شود.

text
     T1 (writer, region A)                    T2 (reader, region B, starts after T1 commits)
1    BEGIN; UPDATE accounts SET bal=bal-100 WHERE id=1;
2    COMMIT;  -- returns at 10:00:00.000
3                                             BEGIN;  -- 10:00:00.050, user saw T1's confirmation
4                                             SELECT bal FROM accounts WHERE id=1;
5    serializable only:      may read the pre-T1 balance (T2 ordered first); still a valid serial order
6    strict serializable:    must read the post-T1 balance

سناریوی واقعی: انتقال پول و بعد صفحهٔ صورت‌حساب؛ «تأیید سفارش» و بعد داشبورد انبار؛ کاهش موجودی در یک منطقه و بررسی موجودی در منطقهٔ دیگر؛ اسکریپت migration که می‌نویسد و verifierی که می‌خواند.

چه چیزی فراهمش می‌کند:

محصولسطح پیش‌فرضقوی‌ترین سطحترتیب زمان واقعی؟
SpannerSerializable با external consistency (repeatable read هم ارائه می‌شود)External consistencyبله، با commit wait در TrueTime
CockroachDBSERIALIZABLESERIALIZABLElinearizable تک‌کلیدی تا وقتی skew درون --max-offset است؛ «causal reverse» بین کلیدها ممکن است
PostgreSQLREAD COMMITTEDSERIALIZABLE (SSI)روی primary در عمل بله؛ روی standbyها نه
MySQL InnoDBREPEATABLE READSERIALIZABLE (2PL)فقط روی primary
MongoDBتراکنش‌ها با read از snapshot و readConcern: "snapshot"Snapshot isolationبا write اکثریتی، روی primary
DynamoDBread committed برای هر آیتم؛ TransactWriteItems سریال‌پذیرSerializable برای تراکنش‌هاread با strong consistency روی جدول پایه
Cassandraدر مستندات DML که این‌جا استفاده شد تراکنش ACID چندپارتیشنی نیست؛ LWT برای هر partitionخطی برای هر partition با LWTبرای هر partition

نتیجهٔ HAT از Bailis در یک خط: Read Committed و session guaranteeها با دسترس‌پذیری بالا ممکن‌اند؛ "Snapshot Isolation and Repeatable Read isolation are not HAT-compliant" و serializability هم نیست.

راه درست: سطح را برای هر دستهٔ تراکنش جدا انتخاب کنید (ببینید انتخاب)؛ اگر جریانی از یک commit دیده‌شده توسط کاربر عبور می‌کند و بعد می‌خواند، مطمئن شوید مسیر read سخت‌گیر است (primary، leaseholder، ConsistentRead) یا token حمل می‌کند.

Linearizability در برابر serializability حیاتی ​

به زبان ساده: linearizability جواب می‌دهد «آیا یک کلید مثل یک نسخه، در زمان واقعی، رفتار می‌کند؟» serializability جواب می‌دهد «آیا تراکنش‌های کامل طوری رفتار می‌کنند که انگار یکی‌یکی، با یک ترتیبی، اجرا شده‌اند؟» strict serializability به هر دو بله می‌گوید.

بدفهمی رایج: «Serializable یعنی linearizable.» Bailis: "Unlike linearizability, serializability does not—by itself—impose any real-time constraints on the ordering of transactions." و در جهت عکس، کلیدهای تکیِ خطی جلوی write skew میان دو کلید را نمی‌گیرند.

تعریف: جدول دوبه‌دوی تصویر را ببینید. Linearizability ترکیب‌پذیر است (خطی بودن هر شیء یعنی خطی بودن سیستم)؛ serializability ترکیب‌پذیر نیست (دو دیتابیس serializable کنار هم بدون هماهنگ‌کننده serializable نیستند).

Some total order, no real-time ruleTotal order that respects real timeSingle objectone key / registerTransactionsmany objects at onceSequential consistencyper-client program order kepta client may lag behind othersLamport 1979; CPU memory modelsLinearizabilityacts like one copy, changes instantlyetcd default reads, Raft ReadIndex or lease reads,MongoDB "linearizable" read concernHerlihy and Wing 1990; CAP's CSerializabilitytransactions equal some serial runmay order a later txn before an earlier oneCockroachDB SERIALIZABLE (claimed level),any SERIALIZABLE read on a lagging replicaStrict serializabilityserializable + linearizableSpanner "external consistency",a single-node SERIALIZABLE database:one clock already gives real-time orderLinearizability is the single-operation, single-object special case of strict serializability (Herlihy and Wing).

ستون‌ها «ترتیب کل بدون قید زمان واقعی» و «ترتیب کلی که زمان واقعی را رعایت می‌کند» هستند و ردیف‌ها «یک شیء» و «تراکنش روی چند شیء». خانهٔ پایین-راست، یعنی strict serializability، اشتراک دو ویژگی است.

text
     Linearizable but not serializable (two keys, each linearizable, no transactions)
1    T1: read x=0, read y=0, write x=1 (doctor 1 goes off call: "y is still on")
2    T2: read x=0, read y=0, write y=1 (doctor 2 goes off call: "x is still on")
3    every single operation is linearizable; together: nobody on call (write skew)

     Serializable but not linearizable (stale snapshot)
4    T1 commits balance=0 at 10:00:00.000 and the user sees "done"
5    T2 starts 10:00:00.050 on a replica with snapshot 09:59:59.900, reads balance=100
6    serial order T2, T1 is legal; real time is violated

سناریوی واقعی: برنامهٔ کشیک و رزرو اتاق جلسه به serializability نیاز دارند (invariant چندردیفی)؛ leader election و claim نام کاربری به linearizability نیاز دارند (تک‌کلید، زمان واقعی)؛ دفتر کلی که پیام «انتقال انجام شد» می‌دهد به هر دو.

چه چیزی فراهمش می‌کند: جدول محصولات را ببینید.

راه درست: هنگام نوشتن نیازمندی هر دو ویژگی را بگویید: «تراکنش‌های serializable روی سفارش و موجودی، و صفحهٔ سفارش باید پرداخت تأییدشده را نشان بدهد» یعنی strict serializability روی آن مسیر read.

Read خطی در سیستم‌های consensus: ReadIndex، lease read، quorum read مهم ​

به زبان ساده: write از راه Raft یا Paxos خطی است چون از log عبور می‌کند؛ بخش دشوار read است، چون گره‌ای که جواب می‌دهد ممکن است leader قدیمی‌ای باشد که نفهمیده جایگزین شده.

بدفهمی رایج: «read از leader در Raft خطی است.» فقط اگر leader اول ثابت کند هنوز leader است. مقالهٔ Raft: "Linearizable reads must not return stale data, and Raft needs two extra precautions to guarantee this without using the log."

تعریف:

روشچطورهزینهریسک
Read از راه logread را مثل یک write از log عبور بدهیک دور کامل consensus + دیسکهیچ، ولی کند
ReadIndexleader اندیس commit خود را ثبت می‌کند، با یک دور heartbeat به اکثریت رهبری را تأیید می‌کند، صبر می‌کند تا آن اندیس اعمال شود، بعد می‌خواندیک دور شبکه، بدون نوشتن روی دیسکهیچ (یک no-op commitشده از term جاری لازم است)
Lease readleader یک lease زمانی دارد و تا معتبر است محلی می‌خواندبدون دور شبکه"this would rely on timing for safety (it assumes bounded clock skew)"
Read از follower با ReadIndexfollower اندیس read را از leader می‌گیرد، صبر می‌کند اعمال شود، محلی می‌خواندیک دور تا leaderهیچ
Quorum read (به سبک Dynamo)از R replica بخوان، تازه‌ترین را بردار؛ با read repair پیش از برگرداندنR پاسخفقط با «write back پیش از برگرداندن» و بدون sloppy quorum همزمان خطی است
Read کهنه / از followerstate محلی را بخوانهیچدر بهترین حالت sequential، کهنه
text
     Old leader L1 (partitioned)       New leader L2 (majority side)        Client
1    still believes it is leader
2                                      elected in term 8, commits x=2
3                                                                           read x via L1 with lease expired?
4    lease read with skewed clock:     returns x=1  <- stale, not linearizable
5    ReadIndex: heartbeat to majority fails -> L1 cannot serve the read (correct)

سناریوی واقعی: readهای etcd (به‌طور پیش‌فرض خطی، و storeی که پشت API server در Kubernetes است)؛ read از leaseholder در CockroachDB؛ read concern linearizable در MongoDB؛ هر سرویس Raft دست‌ساز که readها را بدون دور ReadIndex از «leader» جواب می‌دهد.

چه چیزی فراهمش می‌کند:

محصولread پیش‌فرضread خطیگزینهٔ ارزان‌تر
etcdخطی (ReadIndex)پیش‌فرضحالت serializable (clientv3.WithSerializable()): محلی، شاید کهنه
CockroachDBread از leaseholder (strongly consistent)پیش‌فرضFollower read با AS OF SYSTEM TIME follower_read_timestamp()
MongoDBread concern پیش‌فرض سراسری"linearizable" روی primary"majority" روی secondaryها (درون session، causal)
SpannerStrong readپیش‌فرضreadهای bounded یا exact staleness

راه درست: برای دادهٔ هماهنگی از حالت خطی محصول استفاده کنید و برای داشبوردها از حالت کهنه‌اش؛ هیچ‌وقت lease read را بدون کران clock skew و پایش، خودتان پیاده نکنید.

ساعت‌ها: Lamport، vector، hybrid logical clock، TrueTime مهم ​

به زبان ساده: برای مرتب کردن رویدادها روی چند ماشین یا به یک هماهنگ‌کننده نیاز دارید، یا به ساعت منطقی‌ای که علیت را دنبال کند، یا به ساعت‌های فیزیکی با یک خطای مشخص.

بدفهمی رایج: «NTP ساعت‌ها را در یک میلی‌ثانیه نگه می‌دارد، پس ترتیب timestamp همان ترتیب زمان واقعی است.» NTP یک offset معمول می‌دهد، نه یک کران؛ یک VM متوقف‌شده، باگ leap second یا یک upstream خراب می‌تواند ساعت را چند ثانیه جابه‌جا کند. در این حالت last-writer-wins با ساعت دیواری بی‌صدا write جدیدتر را دور می‌اندازد.

تعریف (هر کدام یک خط؛ عمقش در Vector Clock و علیت):

ساعتچه چیزی را می‌گیرداندازهچه کسی استفاده می‌کند
Lamport clockترتیبی کل که با happened-before سازگار است (اگر a → b آنگاه L(a) < L(b)، نه برعکس)یک عدد صحیحtermها و اندیس‌های log در Raft از همین جنس‌اند؛ offsetهای Kafka برای هر partition
Vector clock / version vectorhappened-before دقیق و تشخیص همزمانییک شمارنده برای هر گرهsiblingهای سبک Dynamo، تحویل CRDT
Hybrid logical clock (HLC)timestamp شبیه زمان فیزیکی + شمارندهٔ منطقی؛ علیت را رعایت می‌کند64 بیت + شمارندهCockroachDB ("Time and hybrid logical clocks" در مستندات transaction layer)
TrueTimeبازهٔ [earliest, latest] که تضمین می‌شود زمان مطلق را دربر دارددو timestampSpanner

مقالهٔ HLC: "we propose a hybrid logical clock, HLC, that combines the best of logical clocks and physical clocks." مقالهٔ Spanner گزارش می‌دهد که عدم‌قطعیت TrueTime، یعنی epsilon، "is typically a sawtooth function of time, varying from about 1 to 7 ms over each poll interval."

Spanner (TrueTime): wait out the uncertainty, then acknowledgeTT.now() = [earliest, latest]commit waits = TT.now().latestTT.after(s) true: replyepsilon is typically 1-7 ms (about 4 ms) in the 2012 paper; every later transaction gets a larger timestamp.CockroachDB (HLC, no atomic clocks): read with an uncertainty windowread timestamp tvalue written at t+120 mst + max-offset (default 500ms)A value inside [t, t+max-offset] might have committed before the read started: push t past it, refresh reads, or restart(ReadWithinUncertaintyIntervalError). A node whose clock drifts past 80% of max-offset vs half the cluster shuts down.

تصویر دو راه را کنار هم می‌گذارد: Spanner عدم‌قطعیت را «صبر می‌کند» تا تمام شود و بعد پاسخ می‌دهد؛ CockroachDB بدون ساعت اتمی، readها را با یک پنجرهٔ عدم‌قطعیت (Uncertainty Window) انجام می‌دهد و هر مقداری که درون آن پنجره بیفتد timestamp تراکنش را جلو می‌برد یا تراکنش را restart می‌کند.

text
     Spanner commit (TrueTime)                      CockroachDB read (HLC + uncertainty)
1    acquire locks, s = TT.now().latest             txn timestamp t = local HLC now
2    Paxos-replicate the commit record              read key k: newest version at 10:00:00.120 > t?
3    commit wait: until TT.after(s) is true         is it within [t, t + max-offset]?
4    release locks, reply                           yes -> uncertain: push t past it, refresh reads
5    any later txn gets a larger timestamp           refresh fails -> ReadWithinUncertaintyIntervalError, retry

Clock skew و پنجرهٔ عدم‌قطعیت. CockroachDB قرارداد را مکتوب کرده: "While serializable consistency is maintained under SERIALIZABLE isolation regardless of clock skew, skew outside the configured clock offset bounds can result in violations of single-key linearizability between causally dependent transactions." کران همان --max-offset است با "Default: 500ms"، و "when a node detects that its clock is out of sync with at least half of the other nodes in the cluster by 80% of the maximum offset allowed, it crashes immediately." جمع‌بندی خود Cockroach Labs: "While Spanner provides linearizability, CockroachDB only goes as far as to claim serializability".

سناریوی واقعی: حل تعارض LWW در Cassandra (timestamp کلاینت یا coordinator)؛ مرتب کردن رویدادها در logهای چندین host؛ دیتابیس‌های جهانی؛ leaseهای منقضی‌شونده.

چه چیزی فراهمش می‌کند: جدول بالا را ببینید؛ قطعهٔ HLC در Go الگوریتم را در حدود ۶۰ خط نشان می‌دهد.

راه درست: برای ترتیب از ساعت منطقی یا هیبریدی استفاده کنید، از ساعت فیزیکی فقط با کرانی که پایشش می‌کنید (هشدار offset در chrony/NTP، AWS Time Sync / PTP هر جا در دسترس است)، و هیچ‌وقت LWW با ساعت دیواری را برای داده‌ای که هر دو update همزمانش مهم است به کار نبرید.

محصولات مدل‌هایشان را چطور عرضه می‌کنند حیاتی ​

به زبان ساده: هر محصول یک پیش‌فرض دارد که از آنچه فکر می‌کنید ضعیف‌تر است و یک کلید که آن را قوی‌تر و کندتر می‌کند. هر دو را بشناسید.

بدفهمی رایج: «ما از یک دیتابیس strongly consistent استفاده می‌کنیم، پس مشکلی نداریم.» بیشتر حادثه‌ها از مسیر readی که بعداً اضافه کردید می‌آیند: یک replica، یک cache، یک ایندکس جست‌وجو، یک GSI، یک follower read.

تعریف: ماتریس زیر برای هر محصول پیش‌فرض، قوی‌ترین گزینه و کلید را می‌آورد.

محصولپیش‌فرض برای readقوی‌ترین گزینهکلید / تنظیممراقب باشید
SpannerStrong read، تراکنش RW با external consistencyExternal consistencyStale read در یک timestamp انتخابی یا bounded stalenessCommit wait (حدود 2 x epsilon)
CockroachDBSERIALIZABLE، read از leaseholderSERIALIZABLE (+ linearizable تک‌کلیدی)AS OF SYSTEM TIME follower_read_timestamp() برای follower read--max-offset (500ms)، retryهای 40001
CassandraConsistency level برای هر درخواست (در driver صریح تنظیمش کنید؛ ONE سریع‌ترین و ضعیف‌ترین است)LWT: IF NOT EXISTS / IF با SERIAL / LOCAL_SERIALCONSISTENCY QUORUM در cqlsh، تنظیمات driverLWT برای هر partition و پرهزینه است؛ قاطی کردن write با LWT و بدون LWT روی یک داده خرابش می‌کند
DynamoDBEventually consistent (ConsistentRead: false)ConsistentRead: true؛ تراکنش‌ها؛ global table با MRSCConsistentRead روی GetItem، Query، Scanنه روی GSI و Stream؛ 2 برابر read unit
MongoDBread concern پیش‌فرض سراسری (معمولاً "local")، write concern پیش‌فرض سراسری majorityread با "linearizable"؛ session causally consistentreadConcern، writeConcern، readPreference، startSession({causalConsistency: true})causal فقط با majority/majority؛ هر session یک thread
Redis / Redis Clusterprimary تا زنده است خطی است؛ replicaها ناهمگامWAIT numreplicas timeout (دوام، نه سازگاری)WAIT، min-replicas-to-write"WAIT does not make Redis a strongly consistent store"؛ failover می‌تواند writeهای تأییدشده را گم کند
PostgreSQLprimary: هر isolation level؛ standbyها: کهنهsynchronous_commit = remote_apply + synchronous_standby_namestoken session با pg_current_wal_lsn() / pg_last_wal_replay_lsn()remote_apply تأخیر replay را به هر commit اضافه می‌کند
etcdخطیخطیحالت درخواست serializable (WithSerializable())«serializable» این‌جا یعنی محلی و شاید کهنه

سناریوی واقعی: تیمی برای یک الگوی دسترسی تازه readها را به GSIهای DynamoDB می‌برد و read-your-writes را می‌شکند؛ کلاستر Cassandra با write و read در ONE باعث می‌شود «unlike» برگردد؛ یک قفل Redis دو بار از failover جان سالم به در می‌برد؛ read از secondary در MongoDB وضعیت دیروز سفارش را نشان می‌دهد.

راه درست: نیازمندی سازگاری را کنار هر مسیر read در سند طراحی بنویسید و با کلید محصول از همین جدول جفتش کنید.

سازوکار ​

هزینهٔ هر تضمین به رفت‌وبرگشت ​

برآورد سرانگشتی با RTT بین‌منطقه‌ای حدود ۷۰ میلی‌ثانیه (برآورد برچسب‌دار؛ عدد خودتان را اندازه بگیرید):

عملیاتهماهنگیتأخیر در یک منطقهتأخیر بین منطقه‌ها
Read با eventual consistencyهیچیک hop محلییک hop محلی
Read از leader با ReadIndexheartbeat به اکثریت+1 RTT درون منطقه+1 RTT بین منطقه‌ای اگر رأی‌دهنده‌ها پخش‌اند
Write خطی (Raft/Paxos)append اکثریت+1 RTT + fsync+1 RTT بین منطقه‌ای (حدود 70 ms)
Commit تراکنش RW در SpannerPaxos + commit wait+ حدود 2 x epsilon+ RTT + حدود 2 x epsilon
Read از replica با session tokenیک بررسی pg_last_wal_replay_lsn()+1 query کوچک، یا fallback به primaryمحلی، مگر replica عقب باشد
Commit با remote_apply در PostgreSQLstandby پیش از پاسخ WAL را اعمال می‌کند+ زمان replay روی standby+ RTT + replay

تنظیم‌ها ​

sql
-- PostgreSQL: version tokens for read-your-writes
SELECT pg_current_wal_lsn();                                   -- on the primary, after COMMIT: e.g. 0/3000148
SELECT pg_last_wal_replay_lsn() >= '0/3000148'::pg_lsn AS ok;  -- on a standby
SELECT now() - pg_last_xact_replay_timestamp() AS replay_lag;  -- monitoring
-- PostgreSQL: make every commit visible on synchronous standbys before it returns
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (standby_a, standby_b)';
ALTER SYSTEM SET synchronous_commit = 'remote_apply';
SELECT pg_reload_conf();

-- CockroachDB: follower read with bounded, known staleness
SELECT * FROM orders AS OF SYSTEM TIME follower_read_timestamp() WHERE id = 42;
SHOW TRANSACTION ISOLATION LEVEL;                               -- serializable

-- Cassandra CQL: linearizable claim on one partition (Paxos)
INSERT INTO usernames (name, user_id) VALUES ('sara', 7) IF NOT EXISTS;
UPDATE seats SET holder = 7 WHERE event = 'e1' AND seat = 'A12' IF holder = null;
-- cqlsh: CONSISTENCY QUORUM; SERIAL CONSISTENCY LOCAL_SERIAL;
محصولتنظیممقادیراثر
MongoDBreadConcernlocal، available، majority، linearizable، snapshotیک read اجازه دارد چه برگرداند
MongoDBwriteConcernw: 1، w: "majority"، j: true، wtimeoutwrite کی تأیید می‌شود
MongoDBگزینهٔ session به نام causalConsistencytrue (پیش‌فرض startSession وقتی snapshot نیست)driver مقدار afterClusterTime را می‌گذارد
DynamoDBConsistentReadtrue / falseread قوی در برابر eventual، هزینهٔ 2 برابر
CassandraConsistency levelONE، LOCAL_ONE، QUORUM، LOCAL_QUORUM، EACH_QUORUM، ALLچند replica باید جواب بدهند
CassandraSerial consistencySERIAL، LOCAL_SERIALدامنهٔ Paxos برای LWT
CockroachDB--max-offsetپیش‌فرض 500msپنجرهٔ عدم‌قطعیت و آستانهٔ خاموش شدن خودکار گره
PostgreSQLsynchronous_commitoff، local، remote_write، on، remote_applycommit تا کجا صبر می‌کند
PostgreSQLmax_standby_streaming_delayپیش‌فرض 30sreplay چقدر می‌تواند به‌خاطر queryهای standby متوقف شود (منبع lag)
RedisWAIT n ms / min-replicas-to-writeعدد صحیحتأیید از replicaها؛ consensus نیست
etcdسازگاری درخواستlinearizable (پیش‌فرض)، serializableReadIndex در برابر read محلی
Laravelsticky، PreventStaleDatabaseReads::for(n)bool، ثانیهبعد از write از connection نوشتن بخوان

پیام‌های خطایی که واقعاً می‌بینید ​

محصولپیام / کدمعناچه باید کرد
CockroachDBReadWithinUncertaintyIntervalError (SQLSTATE 40001)مقداری درون پنجرهٔ عدم‌قطعیت باعث restart شدتراکنش را retry کنید؛ clock skew را کم کنید
PostgreSQLSQLSTATE 40001 could not serialize access due to read/write dependencies among transactionsتعارض serializable (SSI)retry با backoff
CockroachDBخطاهای retry تراکنش با SQLSTATE 40001تعارض serializable یا timestamp جلو رانده‌شدهکل تراکنش را retry کنید
Cassandraردیف نتیجهٔ LWT با [applied] = FalseCAS باخت؛ مقادیر فعلی برگردانده می‌شودبه‌عنوان نتیجهٔ عادی «گرفته شده» رفتار کنید
Cassandratimeout در write از نوع LWTدور Paxos timeout شد؛ نتیجه نامعلومپیش از retry با SERIAL دوباره بخوانید
Redis Cluster-MOVED / -ASKslot جابه‌جا شده؛ کلاینت باید redirect کندکلاینت هوشمند مدیریتش می‌کند؛ علامت سازگاری نیست
standby در PostgreSQLلغو query روی standby بعد از max_standby_streaming_delay (پیش‌فرض 30 ثانیه)replay برای پیشروی لازم است؛ مستندات آن را تعارض با WAL در آستانهٔ اعمال می‌نامندretry، hot_standby_feedback، یا read از primary

Go ​

Before ​

writeها به leader می‌روند و readها به «هر replica». هیچ session guarantee‌ای در کار نیست؛ روی لپ‌تاپ کار می‌کند و در production کاربر را ناامید می‌کند.

go
// Package before shows the common first version of read scaling: writes go
// to the leader, every read goes to "any replica". It works in development
// (replicas are never behind on a laptop) and surprises users in production:
// a user saves a form, the redirect reads from a lagging replica, and the old
// value comes back. Nothing here is a bug in the code; the design simply
// promises no session guarantee at all.
package before

import (
	"context"
	"math/rand/v2"

	"academy/consistency-models/session"
)

// Store routes writes to the leader and reads to a random replica.
type Store struct {
	Leader   session.Leader
	Replicas []session.Replica
	Rand     *rand.Rand
}

// Put writes through the leader and forgets the version it got back.
func (s *Store) Put(ctx context.Context, key, value string) error {
	_, err := s.Leader.Put(ctx, key, value, 0)
	return err
}

// Get reads from any replica, however far behind it is.
func (s *Store) Get(ctx context.Context, key string) (string, error) {
	r := s.Replicas[s.Rand.IntN(len(s.Replicas))]
	v, _, err := r.Get(ctx, key)
	return v, err
}

After: کلاینت session guarantee با version token ​

کلاینت یک Token{Write, Read} نگه می‌دارد: بالاترین جایگاه log که نوشته و بالاترین که خوانده. replica فقط وقتی read را جواب می‌دهد که دست‌کم تا کفِ لازمِ تضمین‌های فعال را اعمال کرده باشد؛ وگرنه کلاینت تا MaxWait صبر می‌کند یا از leader می‌خواند. token به شکل "w.r" رمز می‌شود، پس می‌تواند در cookie یا header بین سرورهای برنامه سفر کند.

go
// Package session layers Terry et al.'s session guarantees (read-your-writes,
// monotonic reads, writes-follow-reads, monotonic writes) on top of a
// single-leader store with asynchronously replicated followers. The client
// carries a version token: the highest log position it wrote and the highest
// position it has read. A replica may serve a read only if it has applied at
// least that position; otherwise the client waits briefly or goes to the leader.
//
// The version is a position in the leader's replication log: a PostgreSQL
// LSN, a MySQL GTID set, a MongoDB operationTime or a Raft index all play this
// role in real systems.
package session

import (
	"context"
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
)

// Version is a position in the leader's log. Larger means "includes more writes".
type Version uint64

// Replica can report how far it has applied the log and serve reads.
type Replica interface {
	Name() string
	Applied(ctx context.Context) (Version, error)
	// Get returns the value and the applied position the read was served at.
	Get(ctx context.Context, key string) (value string, asOf Version, err error)
}

// Leader accepts writes. after is the client's dependency: the leader must not
// order the write before it (trivial for one leader; real work for multi-leader).
type Leader interface {
	Replica
	Put(ctx context.Context, key, value string, after Version) (Version, error)
}

// Guarantee is a bit set of session guarantees.
type Guarantee uint8

const (
	ReadYourWrites Guarantee = 1 << iota
	MonotonicReads
	WritesFollowReads
	MonotonicWrites
	All = ReadYourWrites | MonotonicReads | WritesFollowReads | MonotonicWrites
)

// Token is the session state. It is small enough to live in a cookie, an
// HTTP header or a server-side session, so the guarantee survives load
// balancing across application servers.
type Token struct {
	Write Version // highest version this session wrote
	Read  Version // highest version this session observed
}

// Encode renders the token as "w.r", e.g. for a header value.
func (t Token) Encode() string { return fmt.Sprintf("%d.%d", t.Write, t.Read) }

// DecodeToken parses Encode's output. An empty string is the zero token.
func DecodeToken(s string) (Token, error) {
	if s == "" {
		return Token{}, nil
	}
	w, r, ok := strings.Cut(s, ".")
	if !ok {
		return Token{}, errors.New("session: malformed token")
	}
	wv, err := strconv.ParseUint(w, 10, 64)
	if err != nil {
		return Token{}, fmt.Errorf("session: write part: %w", err)
	}
	rv, err := strconv.ParseUint(r, 10, 64)
	if err != nil {
		return Token{}, fmt.Errorf("session: read part: %w", err)
	}
	return Token{Write: Version(wv), Read: Version(rv)}, nil
}

// Stats counts where reads were served, for dashboards and the lab.
type Stats struct {
	ReplicaReads  int
	LeaderReads   int // fell back because no replica was fresh enough
	WaitedForLag  int // a replica caught up while we waited
	CheckFailures int // a replica could not report its position
}

// Client routes one session's operations. It is not safe for concurrent use;
// one session is one logical sequence of operations, as in Terry et al.
type Client struct {
	Leader     Leader
	Replicas   []Replica
	Guarantees Guarantee
	MaxWait    time.Duration // how long to wait for a lagging replica; 0 = never wait
	Poll       time.Duration // polling interval while waiting

	Token Token
	Stats Stats
	next  int // round-robin cursor
}

// floor is the minimum applied position a replica needs to serve this session.
func (c *Client) floor() Version {
	var f Version
	if c.Guarantees&ReadYourWrites != 0 && c.Token.Write > f {
		f = c.Token.Write
	}
	if c.Guarantees&MonotonicReads != 0 && c.Token.Read > f {
		f = c.Token.Read
	}
	return f
}

// Get reads key from the first replica that satisfies the session floor.
func (c *Client) Get(ctx context.Context, key string) (string, error) {
	floor := c.floor()
	for range c.Replicas {
		r := c.Replicas[c.next%len(c.Replicas)]
		c.next++
		applied, err := r.Applied(ctx)
		if err != nil {
			c.Stats.CheckFailures++
			continue
		}
		if applied < floor && !c.waitFor(ctx, r, floor) {
			continue
		}
		v, asOf, err := r.Get(ctx, key)
		if err != nil || asOf < floor { // re-check: the read itself is the proof
			continue
		}
		c.Stats.ReplicaReads++
		c.observe(asOf)
		return v, nil
	}
	v, asOf, err := c.Leader.Get(ctx, key)
	if err != nil {
		return "", err
	}
	c.Stats.LeaderReads++
	c.observe(asOf)
	return v, nil
}

func (c *Client) waitFor(ctx context.Context, r Replica, floor Version) bool {
	if c.MaxWait <= 0 {
		return false
	}
	poll := c.Poll
	if poll <= 0 {
		poll = time.Millisecond
	}
	deadline := time.Now().Add(c.MaxWait)
	for time.Now().Before(deadline) {
		select {
		case <-ctx.Done():
			return false
		case <-time.After(poll):
		}
		if applied, err := r.Applied(ctx); err == nil && applied >= floor {
			c.Stats.WaitedForLag++
			return true
		}
	}
	return false
}

func (c *Client) observe(v Version) {
	if v > c.Token.Read {
		c.Token.Read = v
	}
}

// Put writes through the leader, passing the session's dependency so that
// writes-follow-reads and monotonic writes hold even if writes are later
// replicated to other leaders or regions in a different order.
func (c *Client) Put(ctx context.Context, key, value string) error {
	var after Version
	if c.Guarantees&WritesFollowReads != 0 && c.Token.Read > after {
		after = c.Token.Read
	}
	if c.Guarantees&MonotonicWrites != 0 && c.Token.Write > after {
		after = c.Token.Write
	}
	v, err := c.Leader.Put(ctx, key, value, after)
	if err != nil {
		return err
	}
	if v > c.Token.Write {
		c.Token.Write = v
	}
	return nil
}

کلاستر درون‌حافظه‌ای که تست‌ها و آزمایشگاه از آن استفاده می‌کنند، با followerهایی که فقط وقتی دستور بگیرند log را اعمال می‌کنند:

go
package session

import (
	"context"
	"fmt"
	"sync"
)

// Cluster is an in-memory single-leader store with followers that apply the
// leader's log only when told to. Tests and the lab use it to create replica
// lag on purpose; it is not a database.
type Cluster struct {
	mu       sync.Mutex
	log      []entry
	leader   *node
	replicas []*node
}

type entry struct{ key, value string }

type node struct {
	c       *Cluster
	name    string
	applied Version
	data    map[string]string
}

// NewCluster creates a leader and n followers, all empty.
func NewCluster(n int) *Cluster {
	c := &Cluster{}
	c.leader = &node{c: c, name: "leader", data: map[string]string{}}
	for i := 0; i < n; i++ {
		c.replicas = append(c.replicas, &node{c: c, name: fmt.Sprintf("replica-%d", i+1), data: map[string]string{}})
	}
	return c
}

// Leader returns the writable node.
func (c *Cluster) Leader() Leader { return leaderNode{c.leader} }

// Replicas returns the followers as read-only replicas.
func (c *Cluster) Replicas() []Replica {
	out := make([]Replica, len(c.replicas))
	for i, r := range c.replicas {
		out[i] = r
	}
	return out
}

// Head is the leader's latest log position.
func (c *Cluster) Head() Version {
	c.mu.Lock()
	defer c.mu.Unlock()
	return Version(len(c.log))
}

// ApplyTo makes follower i apply the log up to position v (never backwards).
func (c *Cluster) ApplyTo(i int, v Version) {
	c.mu.Lock()
	defer c.mu.Unlock()
	r := c.replicas[i]
	if v > Version(len(c.log)) {
		v = Version(len(c.log))
	}
	for r.applied < v {
		e := c.log[r.applied]
		r.data[e.key] = e.value
		r.applied++
	}
}

func (n *node) Name() string { return n.name }

func (n *node) Applied(context.Context) (Version, error) {
	n.c.mu.Lock()
	defer n.c.mu.Unlock()
	return n.applied, nil
}

func (n *node) Get(_ context.Context, key string) (string, Version, error) {
	n.c.mu.Lock()
	defer n.c.mu.Unlock()
	return n.data[key], n.applied, nil
}

type leaderNode struct{ *node }

func (l leaderNode) Put(_ context.Context, key, value string, after Version) (Version, error) {
	c := l.c
	c.mu.Lock()
	defer c.mu.Unlock()
	if after > l.applied {
		return 0, fmt.Errorf("session: dependency %d not yet applied on leader (at %d)", after, l.applied)
	}
	c.log = append(c.log, entry{key, value})
	l.data[key] = value
	l.applied = Version(len(c.log))
	return l.applied, nil
}
go
package session

import (
	"context"
	"testing"
	"time"
)

func TestReadYourWritesFallsBackToLeaderWhenReplicasLag(t *testing.T) {
	ctx := context.Background()
	cl := NewCluster(2)
	c := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: All}

	if err := c.Put(ctx, "profile:7:name", "Sara"); err != nil {
		t.Fatal(err)
	}
	// No replica has applied anything yet.
	got, err := c.Get(ctx, "profile:7:name")
	if err != nil || got != "Sara" {
		t.Fatalf("got %q, %v; want Sara from the leader", got, err)
	}
	if c.Stats.LeaderReads != 1 || c.Stats.ReplicaReads != 0 {
		t.Fatalf("stats %+v", c.Stats)
	}
}

func TestReplicaServesOnceCaughtUp(t *testing.T) {
	ctx := context.Background()
	cl := NewCluster(2)
	c := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: All}
	_ = c.Put(ctx, "k", "v1")
	cl.ApplyTo(1, cl.Head()) // only replica-2 caught up

	got, _ := c.Get(ctx, "k")
	if got != "v1" || c.Stats.ReplicaReads != 1 {
		t.Fatalf("got %q stats %+v; want v1 from replica-2", got, c.Stats)
	}
}

func TestMonotonicReadsNeverGoBackwards(t *testing.T) {
	ctx := context.Background()
	cl := NewCluster(2)
	writer := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: All}
	_ = writer.Put(ctx, "k", "v1")
	_ = writer.Put(ctx, "k", "v2")
	cl.ApplyTo(0, 2) // replica-1 has v2
	cl.ApplyTo(1, 1) // replica-2 still has v1

	reader := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: MonotonicReads}
	first, _ := reader.Get(ctx, "k") // replica-1: v2, token.Read = 2
	second, _ := reader.Get(ctx, "k")
	if first != "v2" || second != "v2" {
		t.Fatalf("reads %q then %q; monotonic reads must not return v1 after v2", first, second)
	}

	naive := &Client{Leader: cl.Leader(), Replicas: cl.Replicas()} // no guarantees
	a, _ := naive.Get(ctx, "k")
	b, _ := naive.Get(ctx, "k")
	if a != "v2" || b != "v1" {
		t.Fatalf("naive reads %q then %q; expected the anomaly v2 then v1", a, b)
	}
}

func TestWaitForLaggingReplica(t *testing.T) {
	ctx := context.Background()
	cl := NewCluster(1)
	c := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: ReadYourWrites,
		MaxWait: 200 * time.Millisecond, Poll: time.Millisecond}
	_ = c.Put(ctx, "k", "v1")
	go func() {
		time.Sleep(5 * time.Millisecond)
		cl.ApplyTo(0, cl.Head())
	}()
	got, _ := c.Get(ctx, "k")
	if got != "v1" || c.Stats.WaitedForLag != 1 || c.Stats.LeaderReads != 0 {
		t.Fatalf("got %q stats %+v; want a replica read after waiting", got, c.Stats)
	}
}

func TestTokenRoundTrip(t *testing.T) {
	tok := Token{Write: 42, Read: 40}
	back, err := DecodeToken(tok.Encode())
	if err != nil || back != tok {
		t.Fatalf("round trip %v -> %q -> %v, %v", tok, tok.Encode(), back, err)
	}
	if _, err := DecodeToken("nonsense"); err == nil {
		t.Fatal("malformed token accepted")
	}
}

func TestTokenCarriedAcrossApplicationServers(t *testing.T) {
	ctx := context.Background()
	cl := NewCluster(1)
	appA := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: All}
	_ = appA.Put(ctx, "cart:9", "3 items")
	header := appA.Token.Encode() // sent back to the browser

	tok, _ := DecodeToken(header) // next request lands on another server
	appB := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: All, Token: tok}
	if got, _ := appB.Get(ctx, "cart:9"); got != "3 items" {
		t.Fatalf("got %q; token did not carry the session floor", got)
	}
}

Example: یک linearizability checker برای CAS register ​

یک جست‌وجوی کوچک به سبک Wing و Gong، همان خانوادهٔ الگوریتمی که Knossos و Porcupine پیاده می‌کنند: عملیاتی را انتخاب کن که می‌تواند بعدی باشد (برای linearizability: هیچ عملیات معلق دیگری پیش از فراخوانی‌اش برنگشته باشد؛ برای sequential consistency: عملیات بعدی یکی از کلاینت‌ها)، آن را روی مدل ترتیبی register اعمال کن، بازگشتی ادامه بده، و (مجموعهٔ عملیات linearize‌شده، حالت register) را memoize کن. عملیاتی که timeout خورده Pending است: شاید اثر کرده باشد، شاید نه.

go
// Package linearizability checks recorded histories of a single register
// (read, write, compare-and-set) against linearizability and, for contrast,
// sequential consistency. It is a small search in the spirit of Wing & Gong
// and Lowe (the algorithm family Porcupine and Knossos implement): pick an
// operation that may legally take effect next, apply it to the sequential
// model, recurse, and memoise (set of linearized ops, model state) so that the
// same dead end is never explored twice.
package linearizability

import (
	"fmt"
	"math"
	"strings"
)

// Kind is the operation type on the register.
type Kind int

const (
	Read  Kind = iota // returns the current value in Out
	Write             // sets the value to Arg
	CAS               // if value == Arg then value = Arg2; OK reports success
)

// Op is one completed (or pending) operation as a client observed it.
// Call and Return are timestamps from one monotonic clock on the test runner.
type Op struct {
	Client  int
	Kind    Kind
	Arg     int   // Write: new value. CAS: expected value.
	Arg2    int   // CAS: new value.
	Out     int   // Read: value returned.
	OK      bool  // CAS: whether it reported success.
	Call    int64 // invocation time
	Return  int64 // response time; ignored when Pending
	Pending bool  // timed out or crashed: may or may not have taken effect
}

func (o Op) String() string {
	switch o.Kind {
	case Read:
		return fmt.Sprintf("c%d read()=%d", o.Client, o.Out)
	case Write:
		return fmt.Sprintf("c%d write(%d)", o.Client, o.Arg)
	default:
		return fmt.Sprintf("c%d cas(%d->%d)=%v", o.Client, o.Arg, o.Arg2, o.OK)
	}
}

// Result is the verdict. Order is a witness linearization (indices into the
// history) when OK; Longest is the longest legal prefix found when not OK,
// which is where a human starts debugging.
type Result struct {
	OK      bool
	Order   []int
	Longest []int
}

// step applies op to state. It reports the new state and whether the
// observed output is legal for the sequential register.
func step(state int, op Op) (int, bool) {
	switch op.Kind {
	case Read:
		if op.Pending {
			return state, true
		}
		return state, op.Out == state
	case Write:
		return op.Arg, true
	default: // CAS
		if op.Pending { // outcome unknown: take the branch the state allows
			if state == op.Arg {
				return op.Arg2, true
			}
			return state, true
		}
		if state == op.Arg {
			return op.Arg2, op.OK
		}
		return state, !op.OK
	}
}

type candidateFn func(ops []Op, done []bool) []int

// Check reports whether history is linearizable for a register that starts
// at init: some total order exists that respects real time (if a returned
// before b was called, a comes first) and the register's sequential rules.
func Check(init int, history []Op) Result {
	return search(init, history, realTimeCandidates)
}

// CheckSequential reports whether history is sequentially consistent
// (Lamport 1979): some total order exists that respects each client's
// program order, but not real time across clients.
func CheckSequential(init int, history []Op) Result {
	return search(init, history, programOrderCandidates)
}

// realTimeCandidates: an op may go next if no other unlinearized,
// non-pending op returned before it was called.
func realTimeCandidates(ops []Op, done []bool) []int {
	minRet := int64(math.MaxInt64)
	for i, o := range ops {
		if !done[i] && !o.Pending && o.Return < minRet {
			minRet = o.Return
		}
	}
	var c []int
	for i, o := range ops {
		if !done[i] && o.Call <= minRet {
			c = append(c, i)
		}
	}
	return c
}

// programOrderCandidates: the earliest unlinearized op of every client.
func programOrderCandidates(ops []Op, done []bool) []int {
	first := map[int]int{}
	for i, o := range ops {
		if done[i] {
			continue
		}
		if j, ok := first[o.Client]; !ok || o.Call < ops[j].Call {
			first[o.Client] = i
		}
	}
	var c []int
	for i := range ops {
		if j, ok := first[ops[i].Client]; ok && j == i {
			c = append(c, i)
		}
	}
	return c
}

func search(init int, ops []Op, next candidateFn) Result {
	done := make([]bool, len(ops))
	seen := map[string]bool{}
	var order, longest []int

	required := 0
	for _, o := range ops {
		if !o.Pending {
			required++
		}
	}

	var dfs func(state, linearized int) bool
	dfs = func(state, linearized int) bool {
		if linearized == required {
			return true // pending ops may be left out: they never happened
		}
		key := memoKey(done, state)
		if seen[key] {
			return false
		}
		seen[key] = true
		for _, i := range next(ops, done) {
			ns, legal := step(state, ops[i])
			if !legal {
				continue
			}
			done[i] = true
			order = append(order, i)
			if len(order) > len(longest) {
				longest = append(longest[:0], order...)
			}
			add := 1
			if ops[i].Pending {
				add = 0
			}
			if dfs(ns, linearized+add) {
				return true
			}
			order = order[:len(order)-1]
			done[i] = false
		}
		return false
	}

	if dfs(init, 0) {
		return Result{OK: true, Order: append([]int(nil), order...)}
	}
	return Result{OK: false, Longest: longest}
}

func memoKey(done []bool, state int) string {
	var b strings.Builder
	for _, d := range done {
		if d {
			b.WriteByte('1')
		} else {
			b.WriteByte('0')
		}
	}
	fmt.Fprintf(&b, "|%d", state)
	return b.String()
}

// Describe renders an order of op indices for logs and the lab.
func Describe(history []Op, order []int) string {
	parts := make([]string, len(order))
	for k, i := range order {
		parts[k] = history[i].String()
	}
	return strings.Join(parts, " -> ")
}
go
package linearizability

import "testing"

func TestSequentialWriteThenReadIsLinearizable(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Return: 10},
		{Client: 2, Kind: Read, Out: 1, Call: 20, Return: 30},
	}
	if r := Check(0, h); !r.OK {
		t.Fatalf("want linearizable, longest prefix %v", r.Longest)
	}
}

// The classic stale read: the write returned before the read was called,
// yet the read saw the old value. A lagging replica produces exactly this.
func TestStaleReadAfterCompletedWriteIsNotLinearizable(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Return: 10},
		{Client: 2, Kind: Read, Out: 0, Call: 20, Return: 30},
	}
	if Check(0, h).OK {
		t.Fatal("stale read accepted as linearizable")
	}
	// Sequential consistency has no real-time rule: client 2's read may be
	// ordered before client 1's write.
	if !CheckSequential(0, h).OK {
		t.Fatal("history should be sequentially consistent")
	}
}

// During a slow write, two reads that do not overlap each other must not go
// "back in time": once one read saw 1, a later read may not see 0.
func TestNewThenOldDuringConcurrentWriteIsNotLinearizable(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Return: 100},
		{Client: 2, Kind: Read, Out: 1, Call: 10, Return: 20},
		{Client: 3, Kind: Read, Out: 0, Call: 30, Return: 40},
	}
	if Check(0, h).OK {
		t.Fatal("new-then-old accepted")
	}
}

func TestOldThenNewDuringConcurrentWriteIsLinearizable(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Return: 100},
		{Client: 2, Kind: Read, Out: 0, Call: 10, Return: 20},
		{Client: 3, Kind: Read, Out: 1, Call: 30, Return: 40},
	}
	r := Check(0, h)
	if !r.OK {
		t.Fatal("old-then-new rejected")
	}
	if got := Describe(h, r.Order); got != "c2 read()=0 -> c1 write(1) -> c3 read()=1" {
		t.Fatalf("unexpected witness %q", got)
	}
}

// Two concurrent compare-and-set calls from 0 to their own id cannot both win.
func TestTwoWinningCASIsNotLinearizable(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: CAS, Arg: 0, Arg2: 1, OK: true, Call: 0, Return: 50},
		{Client: 2, Kind: CAS, Arg: 0, Arg2: 2, OK: true, Call: 10, Return: 60},
	}
	if Check(0, h).OK {
		t.Fatal("two CAS winners accepted")
	}
	h[1].OK = false
	h = append(h, Op{Client: 3, Kind: Read, Out: 1, Call: 70, Return: 80})
	if !Check(0, h).OK {
		t.Fatal("one winner plus a consistent read rejected")
	}
}

// A write that timed out may or may not have happened; both outcomes are legal.
func TestPendingWriteMayOrMayNotTakeEffect(t *testing.T) {
	for _, seen := range []int{0, 1} {
		h := []Op{
			{Client: 1, Kind: Write, Arg: 1, Call: 0, Pending: true},
			{Client: 2, Kind: Read, Out: seen, Call: 20, Return: 30},
		}
		if !Check(0, h).OK {
			t.Fatalf("pending write, read %d rejected", seen)
		}
	}
	// But once a later read saw it, an even later read cannot un-see it.
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Pending: true},
		{Client: 2, Kind: Read, Out: 1, Call: 20, Return: 30},
		{Client: 2, Kind: Read, Out: 0, Call: 40, Return: 50},
	}
	if Check(0, h).OK {
		t.Fatal("pending write seen then unseen accepted")
	}
}

// Sequential consistency still forbids a client seeing its own writes undone.
func TestSequentialConsistencyKeepsProgramOrder(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Return: 10},
		{Client: 1, Kind: Read, Out: 0, Call: 20, Return: 30},
	}
	if CheckSequential(0, h).OK {
		t.Fatal("client read its own write undone")
	}
}

func BenchmarkCheck20Ops(b *testing.B) {
	var h []Op
	for i := 0; i < 10; i++ {
		t := int64(i * 10)
		h = append(h,
			Op{Client: 1, Kind: Write, Arg: i + 1, Call: t, Return: t + 15},
			Op{Client: 2, Kind: Read, Out: i, Call: t + 1, Return: t + 9},
		)
	}
	for b.Loop() {
		if !Check(0, h).OK {
			b.Fatal("expected linearizable")
		}
	}
}

Example: hybrid logical clock ​

go
// Package hlc is a hybrid logical clock (Kulkarni, Demirbas et al. 2014), the
// timestamp scheme CockroachDB uses. A timestamp is the largest
// physical time seen so far plus a logical counter that breaks ties. It stays
// close to wall-clock time, never goes backwards, and preserves Lamport's
// happened-before: if a sends a message that b receives, ts(a) < ts(b).
package hlc

import (
	"fmt"
	"sync"
	"time"
)

// Timestamp orders by Wall, then Logical.
type Timestamp struct {
	Wall    int64 // nanoseconds since the Unix epoch
	Logical uint32
}

// Less reports whether t is before u.
func (t Timestamp) Less(u Timestamp) bool {
	return t.Wall < u.Wall || (t.Wall == u.Wall && t.Logical < u.Logical)
}

func (t Timestamp) String() string { return fmt.Sprintf("%d.%d", t.Wall, t.Logical) }

// Clock is safe for concurrent use.
type Clock struct {
	mu        sync.Mutex
	physical  func() int64
	last      Timestamp
	maxOffset time.Duration
}

// ErrClockOffset reports a remote timestamp too far ahead of local physical
// time. CockroachDB treats the analogous condition (--max-offset, default
// 500ms) as fatal for the node, because past that bound its uncertainty
// interval no longer protects reads.
type ErrClockOffset struct{ Remote, Local int64 }

func (e ErrClockOffset) Error() string {
	return fmt.Sprintf("hlc: remote clock %v ahead of local", time.Duration(e.Remote-e.Local))
}

// New returns a clock reading physical time from now (nil = time.Now) that
// rejects remote timestamps more than maxOffset ahead (0 = no check).
func New(now func() int64, maxOffset time.Duration) *Clock {
	if now == nil {
		now = func() int64 { return time.Now().UnixNano() }
	}
	return &Clock{physical: now, maxOffset: maxOffset}
}

// Now returns a timestamp for a local or send event.
func (c *Clock) Now() Timestamp {
	c.mu.Lock()
	defer c.mu.Unlock()
	pt := c.physical()
	if pt > c.last.Wall {
		c.last = Timestamp{Wall: pt}
	} else {
		c.last.Logical++ // physical clock stalled or went backwards
	}
	return c.last
}

// Update merges a timestamp received from another node and returns the
// timestamp of the receive event, which is after both.
func (c *Clock) Update(remote Timestamp) (Timestamp, error) {
	c.mu.Lock()
	defer c.mu.Unlock()
	pt := c.physical()
	if c.maxOffset > 0 && remote.Wall-pt > int64(c.maxOffset) {
		return c.last, ErrClockOffset{Remote: remote.Wall, Local: pt}
	}
	switch {
	case pt > c.last.Wall && pt > remote.Wall:
		c.last = Timestamp{Wall: pt}
	case remote.Wall > c.last.Wall:
		c.last = Timestamp{Wall: remote.Wall, Logical: remote.Logical + 1}
	case c.last.Wall > remote.Wall:
		c.last.Logical++
	default: // equal walls
		c.last.Logical = max(c.last.Logical, remote.Logical) + 1
	}
	return c.last, nil
}

نگاه Go ​

  • Porcupine (github.com/anishathalye/porcupine) نسخهٔ production‌پسند همین checker است: "Porcupine is a fast linearizability checker used in both academia and industry"، که "a sequential specification as executable Go code, along with a concurrent history" می‌گیرد. P-compositionality را پیاده می‌کند (هر کلید جدا بررسی شود) و نقطه‌های linearization را در یک تصویر HTML نشان می‌دهد؛ README آن می‌گوید "etcd uses Porcupine's linearizability checker and visualizer in its robustness tests".
  • ضبط history: Call و Return را از time.Now() روی اجراکنندهٔ تست بگیرید (که خوانش ساعت monotonic را درون time.Time دارد)، هرگز از ساعت سرورها.
  • go.etcd.io/etcd/client/v3: readها به‌طور پیش‌فرض خطی‌اند؛ clientv3.WithSerializable() آن‌ها را محلی و شاید کهنه می‌کند. CAS یعنی Txn(ctx).If(clientv3.Compare(clientv3.ModRevision(k), "=", rev)).Then(...).
  • go.mongodb.org/mongo-driver/v2: options.Session().SetCausalConsistency(true) با readconcern.Majority() و writeconcern.Majority()؛ sess.OperationTime() را بین پردازه‌ها با AdvanceOperationTime پاس بدهید.
  • database/sql + pgx: دو pool از *sql.DB (primary و replicaها) به‌علاوهٔ بررسی token با SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn همهٔ چیزی است که session client روی PostgreSQL لازم دارد.
  • مدل حافظهٔ خود Go هم یک مدل سازگاری است: مدل حافظهٔ Go تضمینش را "DRF-SC: data-race-free programs execute in a sequentially consistent manner" می‌نامد، و sync/atomic را با "the same semantics as C++’s sequentially consistent atomics" مشخص می‌کند.

Laravel ​

Before ​

read/write split داریم، و redirect بعد از write از یک replica می‌خواند.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

/**
 * Before: read/write split without any session guarantee.
 *
 * The update goes to the primary. The redirect is a NEW request, so the
 * per-request 'sticky' flag is gone and show() reads from a replica that may
 * not have replayed the update yet: the user sees the old name.
 */
class ProfileController
{
    public function update(Request $request, int $id): RedirectResponse
    {
        DB::table('profiles')->where('id', $id)->update([
            'display_name' => (string) $request->input('display_name'),
            'updated_at' => now(),
        ]);

        return redirect()->route('profiles.show', $id);
    }

    public function show(int $id): View
    {
        $profile = DB::table('profiles')->where('id', $id)->first(); // any replica

        return view('profiles.show', ['profile' => $profile]);
    }
}

After ​

۱. connection. در Laravel 13 یک connection می‌تواند hostهای read و write داشته باشد؛ sticky بعد از یک write در همان request readها را به connection نوشتن می‌فرستد:

php
<?php

// config/database.php (excerpt): one logical PostgreSQL connection with a
// write host (primary) and read hosts (streaming-replication standbys).
// Laravel picks one read host at random per request.

return [
    'default' => env('DB_CONNECTION', 'pgsql'),

    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'read' => [
                'host' => explode(',', env('DB_READ_HOSTS', '127.0.0.1')),
            ],
            'write' => [
                'host' => [env('DB_WRITE_HOST', '127.0.0.1')],
            ],
            // After a write in THIS request, later reads in this request use
            // the write connection. It does nothing for the next request.
            'sticky' => true,

            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'app'),
            'username' => env('DB_USERNAME', 'app'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'search_path' => 'public',
            'sslmode' => 'prefer',
        ],
    ],
];

مستندات Laravel دامنه‌اش را صریح گفته‌اند: "If the sticky option is enabled and a "write" operation has been performed against the database during the current request cycle, any further "read" operations will use the "write" connection." redirect یک request تازه است.

۲. بین requestها، با پنجرهٔ زمانی (داخلی). Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads زمان آخرین write را در session نگه می‌دارد؛ "By default, requests within two seconds of a write will use the write connection for reads on that connection." با PreventStaleDatabaseReads::for(5) پنجره را بزرگ‌تر می‌کنید. ساده است ولی یک حدس است: اگر lag از پنجره بیشتر شود غلط است، و اگر replicaها ۵ میلی‌ثانیه عقب باشند بیهوده primary را شلوغ می‌کند.

php
<?php

use App\Http\Middleware\ReadYourWritesLsn;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(web: __DIR__.'/../routes/web.php')
    ->withMiddleware(function (Middleware $middleware): void {
        // Option A (built in, time window): for 5 s after this session wrote,
        // read from the write connection. Simple; wrong if lag exceeds 5 s,
        // wasteful if replicas catch up in 5 ms.
        $middleware->web(append: [
            PreventStaleDatabaseReads::for(5),
        ]);

        // Option B (version token): compare the session's last commit LSN with
        // what the chosen replica has replayed. Use A or B, not both.
        // $middleware->web(append: [ReadYourWritesLsn::class]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

۳. بین requestها، با version token (دقیق). بعد از یک write، LSN روی primary را ذخیره کنید؛ در request بعدی از replicaیی که Laravel برای همین request انتخاب کرده (برای هر request یک read host تصادفی) بپرسید آیا آن LSN را replay کرده؛ اگر نه، برای بقیهٔ request useWriteConnectionWhenReading() را صدا بزنید. middleware از hasModifiedRecords() استفاده می‌کند، همان پرچمی که middleware داخلی می‌خواند.

php
<?php

namespace App\Http\Middleware;

use App\Consistency\ReplicaLsn;
use Closure;
use Illuminate\Database\DatabaseManager;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Read-your-writes and monotonic reads across requests with a version token.
 *
 * After a request that wrote, store the primary's WAL position (LSN) in the
 * session. On the next request, ask the replica Laravel chose for this
 * request whether it has replayed that position; if not, send this request's
 * reads to the primary. Unlike a fixed time window, this is exact: it costs
 * one tiny query and never reads stale, however large the lag is.
 *
 * Must run after StartSession (append it to the 'web' group).
 */
class ReadYourWritesLsn
{
    public function __construct(
        private DatabaseManager $db,
        private ReplicaLsn $lsn,
    ) {}

    public function handle(Request $request, Closure $next, string $connection = 'pgsql'): Response
    {
        $conn = $this->db->connection($connection);
        $token = $request->session()->get(ReplicaLsn::SESSION_KEY);

        if (is_string($token) && ! $this->lsn->replicaHasReplayed($conn, $token)) {
            $conn->useWriteConnectionWhenReading();
        }

        $response = $next($request);

        if ($conn->hasModifiedRecords()) {
            $request->session()->put(ReplicaLsn::SESSION_KEY, $this->lsn->primaryPosition($conn));
        }

        return $response;
    }
}
php
<?php

namespace App\Consistency;

use Illuminate\Database\Connection;

/**
 * PostgreSQL WAL positions as session version tokens.
 */
class ReplicaLsn
{
    public const SESSION_KEY = '_pg_write_lsn';

    /** The primary's current WAL write position, e.g. "0/3000148". */
    public function primaryPosition(Connection $conn): string
    {
        $row = $conn->selectFromWriteConnection('select pg_current_wal_lsn()::text as lsn');

        return $row[0]->lsn;
    }

    /**
     * True if the read connection for this request has replayed $lsn.
     * pg_last_wal_replay_lsn() is NULL on a primary, which has everything.
     */
    public function replicaHasReplayed(Connection $conn, string $lsn): bool
    {
        $row = $conn->selectOne(
            'select coalesce(pg_last_wal_replay_lsn() >= ?::pg_lsn, true) as ok',
            [$lsn],
        );

        return (bool) $row->ok;
    }
}

۴. MongoDB causal consistency (سازگاری علّی در MongoDB). با mongodb/laravel-mongodb، DB::connection('mongodb')->getClient() یک MongoDB\Client برمی‌گرداند؛ startSession(['causalConsistency' => true]) به‌همراه read و write concern اکثریتی هر چهار session guarantee را حتی هنگام خواندن از secondaryها می‌دهد. بین requestها operationTime را حمل کنید و advanceOperationTime() را صدا بزنید.

php
<?php

namespace App\Mongo;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use MongoDB\BSON\Timestamp;
use MongoDB\Collection;
use MongoDB\Driver\ReadConcern;
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\Session;
use MongoDB\Driver\WriteConcern;

/**
 * MongoDB causal consistency from Laravel (mongodb/laravel-mongodb).
 *
 * Inside one causally consistent session, with "majority" read and write
 * concern, MongoDB guarantees read-your-writes, monotonic reads, monotonic
 * writes and writes-follow-reads, even when reads go to secondaries.
 * Across HTTP requests the session object is gone, so we carry its
 * operationTime in the Laravel session and advance the next session to it.
 */
class CausalProfileStore
{
    private const OP_TIME = '_mongo_operation_time';

    public function rename(Request $request, string $id, string $name): ?array
    {
        $session = $this->session($request);
        $profiles = $this->profiles();

        $profiles->updateOne(['_id' => $id], ['$set' => ['name' => $name]], ['session' => $session]);
        // Reads from a secondary, yet is guaranteed to see the update above.
        $doc = $profiles->findOne(['_id' => $id], ['session' => $session]);

        $this->remember($request, $session);
        $session->endSession();

        return $doc;
    }

    public function find(Request $request, string $id): ?array
    {
        $session = $this->session($request);
        $doc = $this->profiles()->findOne(['_id' => $id], ['session' => $session]);
        $this->remember($request, $session);
        $session->endSession();

        return $doc;
    }

    private function session(Request $request): Session
    {
        $client = DB::connection('mongodb')->getClient();
        $session = $client->startSession(['causalConsistency' => true]);

        $saved = $request->session()->get(self::OP_TIME);
        if (is_array($saved)) {
            // Timestamp(increment, timestamp). On a sharded cluster, also copy
            // the cluster time with $session->advanceClusterTime().
            $session->advanceOperationTime(new Timestamp($saved[1], $saved[0]));
        }

        return $session;
    }

    private function remember(Request $request, Session $session): void
    {
        $t = $session->getOperationTime();
        if ($t instanceof Timestamp) {
            $request->session()->put(self::OP_TIME, [$t->getTimestamp(), $t->getIncrement()]);
        }
    }

    private function profiles(): Collection
    {
        $client = DB::connection('mongodb')->getClient();

        return $client->selectCollection(config('database.connections.mongodb.database'), 'profiles', [
            'readConcern' => new ReadConcern(ReadConcern::MAJORITY),
            'writeConcern' => new WriteConcern(WriteConcern::MAJORITY),
            'readPreference' => new ReadPreference(ReadPreference::SECONDARY_PREFERRED),
            'typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array'],
        ]);
    }
}

نگاه Laravel ​

  • DB::withoutAffectingStickiness(fn () => ...) یک write انجام می‌دهد که readهای request را به primary نمی‌برد (heartbeat jobها، timestamp ممیزی)؛ در صفحهٔ database نسخهٔ 13.x مستند شده.
  • ->useWritePdo() روی query builder یک query را به primary می‌فرستد؛ DB::connection()->useWriteConnectionWhenReading() این کار را برای بقیهٔ request می‌کند؛ readهای درون DB::transaction() همیشه از PDO نوشتن استفاده می‌کنند.
  • jobی که بعد از یک write صف می‌شود ممکن است روی workerی اجرا شود که از replica می‌خواند؛ با ->afterCommit() dispatch کنید و token (یا شناسهٔ مدل به‌همراه useWritePdo()) را پاس بدهید تا job حالت پیش از write را نخواند.
  • cache هم یک replica است: Cache::remember() بعد از یک update تا پایان TTL مقدار قدیمی را می‌دهد، مگر در همان جریان Cache::forget() کنید (Caching).
  • workerهای Octane برنامه را بین requestها در حافظه نگه می‌دارند؛ هر tokenی که اضافه می‌کنید را در request یا session نگه دارید، هرگز در یک property استاتیک.

حل مسئله‌های کلاسیک ​

«پروفایلم را ذخیره کردم و قبلی برگشت» ​

راه‌حلچطورمزیتهزینه / محدودیت
دادهٔ خود کاربر را از primary بخوانreadهای /me/* را به primary بفرستبسیار سادهبار primary با تعداد کاربران فعال رشد می‌کند
پنجرهٔ زمانیPreventStaleDatabaseReads::for(n) در Laravelداخلی، یک خطحدس؛ وقتی lag از n بیشتر شود می‌شکند
Version tokenLSN/GTID/operationTime در session؛ بررسی replicaدقیق؛ replicaها هنوز بیشتر readها را جواب می‌دهندیک query کوچک اضافه؛ لوله‌کشی token
اعمال همگامremote_apply در PostgreSQLبدون تغییر در برنامههر commit منتظر replay می‌ماند
UI خوش‌بینانهمقدار ارسال‌شده را سمت کلاینت نشان بدهUX آنیتضمین داده نیست؛ tabهای دیگر همچنان کهنه‌اند

«دو نفر آخرین صندلی را رزرو کردند» ​

CAS خطی روی یک کلید. SQL با یک unique constraint روی primary، یا LWT در Cassandra، یا write شرطی در DynamoDB:

sql
-- PostgreSQL (primary): the unique index is the CAS
CREATE UNIQUE INDEX seats_one_holder ON seat_holds (event_id, seat);
INSERT INTO seat_holds (event_id, seat, user_id) VALUES (1, 'A12', 7)
ON CONFLICT DO NOTHING RETURNING user_id;   -- no row returned = someone else won

در DynamoDB همین کار PutItem با ConditionExpression: attribute_not_exists(pk) است؛ در Cassandra، INSERT ... IF NOT EXISTS و خواندن [applied]. هرگز روی replica بررسی نکنید و روی primary بنویسید.

«پاسخ پیش از پیامی که به آن جواب می‌دهد دیده شد» ​

Causal consistency: sessionهای causally consistent در MongoDB، یا نسخهٔ پیام والد را همراه پاسخ حمل کنید تا خواننده پاسخ را تا دیده شدن والد نگه دارد (یا والد را بیاورد). در pipelineهای رویداد، با شناسهٔ گفت‌وگو کلید بزنید تا یک partition ترتیب را حفظ کند.

«کامنت ظاهر می‌شود و با refresh غیب می‌شود» ​

Monotonic reads: session را به یک replica سنجاق کنید (consistent hashing روی شناسهٔ کاربر)، یا token.Read را نگه دارید و replicaهای عقب‌تر از آن را رد کنید. این دومین تضمینی است که کلاینت Go اعمال می‌کند.

«Clock skew ترتیب writeهای ما را به هم ریخت» ​

راه‌حلچطورمزیتهزینه
Timestamp از HLCهنگام دریافت، timestamp راه دور را ادغام کنترتیب علّی با زمان نزدیک به فیزیکیبرای ادعای زمان واقعی همچنان کران skew لازم است
Version vectorهمزمانی را تشخیص بده، siblingها را نگه دارهیچ update گم نمی‌شودادغام در برنامه
ترتیب تعیین‌شده توسط سروریک leader یا log ترتیب را تعیین کندسادهleader روی مسیر write
کران skew + خاموش شدنرفتار --max-offset در CockroachDBایمنی حفظ می‌شودگره‌ها با NTP خراب متوقف می‌شوند

«read به‌اصطلاح strongly consistent ما بعد از failover کهنه بود» ​

از مسیر read خطی محصول استفاده کنید (پیش‌فرض etcd، linearizable در MongoDB، ReadIndex)، write اکثریتی بزنید، و برای هر کاری که روی نتیجه اقدام می‌کند fencing token به کار ببرید (قفل توزیع‌شده).

تست سازگاری ​

ابزارچه چیزی را بررسی می‌کندورودینکته
Jepsenکل سیستم زیر partition، clock skew و crashکلاستر واقعی + nemesishistory تولید می‌کند و برای داوری از Knossos یا Elle استفاده می‌کند
Knossoslinearizability در historyهای تک‌شیئیرویدادهای invoke/ok/fail/info"attempts to show that the history is not linearizable" نسبت به یک مدل؛ نمایی نسبت به همزمانی
Elleisolation تراکنشی (G0، G1a/b/c، G2، write skew، lost update)تراکنش‌های list-append یا register"Elle is a transactional consistency checker for black-box databases"؛ "~linear in history length"
Porcupinelinearizability با spec به زبان Gosliceهای Operation یا Event در Goروی دادهٔ تست Jepsen از Knossos سریع‌تر است؛ visualizer دارد
checker همین صفحهخطی در برابر sequential، register با CASsliceهای Op در Goابزار آموزشی؛ تست‌ها هر ناهنجاری را نشان می‌دهند

انواع رویداد در Knossos واژگان هر history هستند: هر عملیات یک invoke و یک پایان دارد که "either ok if the operation took place, fail if the operation did not take place, or info if you're not sure what happened, e.g. the operation timed out." با info مثل Pending رفتار کنید (ممکن است هر زمانی بعد از فراخوانی رخ داده باشد)؛ به همین دلیل یک write که timeout خورده می‌تواند یک read بعدی را توضیح بدهد.

انتخاب ​

قابلیت / بار کاریمدل لازمچطور به دستش بیاوریداگر ضعیف‌تر باشد کاربر چه می‌بیند
claim نام کاربری یا ایمیلCAS خطیunique index روی primary، LWT، write شرطیدو حساب با یک نام
رزرو آخرین صندلی، موجودی flash saleCAS خطی یا تراکنش serializableON CONFLICT، IF، ConditionExpression، SERIALIZABLE + retryفروش بیش از موجودی
انتقال پول + صفحهٔ تأییدStrict serializable روی همان مسیرread از primary / Spanner / leaseholder بعد از commit«انتقال انجام شد» با موجودی قدیمی
Leader election، قفلخطی + fencingetcd، write شرطی در DynamoDBدو leader
پروفایل، تنظیمات، پست‌های خود کاربرRead-your-writes + monotonic readsVersion token، middleware در Laravel، session در MongoDBویرایش‌ها «برمی‌گردند»
کامنت، thread چتCausalsession causal، partition برای هر گفت‌وگوپاسخ پیش از سؤال
فید و timeline دیگرانEventual + monotonic readsreplica، cache، replica سنجاق‌شدهآیتم‌ها چشمک می‌زنند
شمارنده، like، بازدیدEventual / strong eventualشمارندهٔ CRDT، sharded counterچند ثانیه عددها کمی جابه‌جا
جست‌وجو، پیشنهادEventualایندکس‌گذاری ناهمگامآیتم تازه چند ثانیه دیده نمی‌شود
Analytics، گزارشSnapshot در یک timestampAS OF SYSTEM TIME، replica، انبار دادهمجموع‌های کمی قدیمی (برچسب بزنید)
write فعال-فعال چندمنطقه‌ایCausal+ یا CRDT، یا strict با Spanner/MRSCبرای هر موجودیت جدا انتخاب کنیدتعارض یا تأخیر بالای write

قاعدهٔ اثر روی UX: هر مدل ضعیف‌تر یک جمله در spec رابط کاربری لازم دارد: «بعد از ذخیره، صفحه از primary می‌خواند»، «شمارش‌ها ممکن است چند ثانیه قدیمی باشند»، حالت‌های «در انتظار» برای کار ناهمگام. اگر نمی‌توانید آن جمله را بنویسید، به مدل قوی‌تر نیاز دارید.

در معماری: از یک پردازه تا سیستم توزیع‌شده ​

مونولیت (Monolith): یک پردازه، یک دیتابیس ​

یک primary از PostgreSQL، بدون replica: هر read خطی است و هر تراکنش در SERIALIZABLE، strict serializable است (یک ساعت، یک WAL). مسئله‌های سازگاری این‌جا مسئله‌های isolation هستند (Isolation Levelها). مثال: یک فروشگاه Laravel با یک دیتابیس؛ تنها انتخاب سازگاری، isolation level در checkout است.

مونولیت ماژولار: مرز بدون شبکه ​

ماژول‌ها مالک جدول‌های خودشان‌اند ولی دیتابیس مشترک است، پس read بین ماژول‌ها اگر در یک تراکنش باشد همچنان سازگار است. اولین تضعیف با یک cache یا ایندکس جست‌وجو برای هر ماژول می‌آید: هر کدام یک replica با eventual consistency است. مثال: ماژول کاتالوگ محصول می‌نویسد؛ ماژول جست‌وجو از ایندکس Elasticsearch می‌خواند که از یک outbox تغذیه می‌شود، و صفحهٔ محصول از دیتابیس می‌خواند در حالی که فهرست از جست‌وجو؛ تعیین کنید کدام صفحه می‌تواند کهنه باشد.

میکروسرویس‌ها (Microservices): سازگاری در مرز سرویس تمام می‌شود ​

هر سرویس دیتابیس خودش را دارد؛ میان سرویس‌ها تراکنش مشترکی نیست، پس وضعیت بین سرویس‌ها ذاتاً eventually consistent است (saga، outbox، رویداد: ببینید Saga و Outbox). چیزی که هنوز می‌توانید به کاربر بدهید session guarantee و علیت از راه token است:

text
     Browser             Orders service            Payments service           Order page (BFF)
1    POST /orders ->     commit order (LSN o1)
2                        emit OrderPlaced via outbox
3                                                  charge, commit (LSN p7)
4    <- 201 + token {orders: o1}
5    GET /orders/1 ->                                                         reads Orders replica: replayed >= o1 ? else primary
6                                                                             payment status may be "pending": UI says so

دادهٔ توزیع‌شده: replica، cache، sharding و چندمنطقه‌ای ​

read replicaها eventual consistency به‌علاوهٔ هر لایهٔ sessionی که اضافه کنید می‌دهند؛ cacheها replica با TTL هستند؛ SQL شاردشده (Citus، Vitess) برای هر shard خطی است ولی read بین shardها به snapshot توزیع‌شده نیاز دارد؛ distributed SQL (CockroachDB، Spanner) کار سازگاری را با consensus و ساعت به درون دیتابیس می‌برد. چندمنطقه‌ای بودن انتخاب PACELC را برای هر جدول تحمیل می‌کند: REGIONAL BY ROW و global table در CockroachDB، پیکربندی‌های چندمنطقه‌ای Spanner، MREC در برابر MRSC در DynamoDB. سیم‌کشی replication در توپولوژی‌های Replication است.

مسیر مقیاس (Scaling path): 1x، 10x، 100x ​

بارچه عوض می‌شودمثال
1xیک primary؛ همه‌چیز سخت‌گیرLaravel + PostgreSQL، بدون replica
10xread replica + session token؛ cache با کهنگی صریح؛ CAS خطی روی primary می‌ماند۲ تا ۴ standby، ReadYourWritesLsn، cache در Redis با TTL
100xمدل برای هر قابلیت: شمارندهٔ CRDT، session causal برای دادهٔ اجتماعی، distributed SQL یا Spanner برای پول، follower read برای analytics، چندمنطقه‌ای با trade-off انتخاب‌شده؛ تست Jepsen/Elle در CI برای ادعاهایی که به آن‌ها تکیه می‌کنیدCockroachDB چندمنطقه‌ای + Kafka + Redis

آزمایشگاه: بررسی historyها و اندازه‌گیری stale read ​

Go تک‌پردازه، بدون شبکه و بدون container. حدود یک ثانیه اجرا می‌شود.

go
// Command lab runs the two experiments of the consistency-models chapter in
// one process, with fixed seeds so the output is reproducible:
//
//  1. three register histories through the linearizability and
//     sequential-consistency checkers;
//  2. 1,000 "save profile, then show profile" sessions against a leader with
//     two lagging followers, read naively and through the session client.
package main

import (
	"context"
	"fmt"
	"math/rand/v2"

	"academy/consistency-models/before"
	lin "academy/consistency-models/linearizability"
	"academy/consistency-models/session"
)

func main() {
	histories()
	sessions()
}

func histories() {
	cases := []struct {
		name string
		h    []lin.Op
	}{
		{"stale read after completed write", []lin.Op{
			{Client: 1, Kind: lin.Write, Arg: 1, Call: 0, Return: 10},
			{Client: 2, Kind: lin.Read, Out: 0, Call: 20, Return: 30},
		}},
		{"new-then-old during a slow write", []lin.Op{
			{Client: 1, Kind: lin.Write, Arg: 1, Call: 0, Return: 100},
			{Client: 2, Kind: lin.Read, Out: 1, Call: 10, Return: 20},
			{Client: 3, Kind: lin.Read, Out: 0, Call: 30, Return: 40},
		}},
		{"old-then-new during a slow write", []lin.Op{
			{Client: 1, Kind: lin.Write, Arg: 1, Call: 0, Return: 100},
			{Client: 2, Kind: lin.Read, Out: 0, Call: 10, Return: 20},
			{Client: 3, Kind: lin.Read, Out: 1, Call: 30, Return: 40},
		}},
	}
	for _, c := range cases {
		l := lin.Check(0, c.h)
		s := lin.CheckSequential(0, c.h)
		fmt.Printf("%-34s linearizable=%-5v sequential=%v\n", c.name, l.OK, s.OK)
		if l.OK {
			fmt.Printf("  witness: %s\n", lin.Describe(c.h, l.Order))
		} else {
			fmt.Printf("  longest legal prefix: %s\n", lin.Describe(c.h, l.Longest))
		}
	}
}

func sessions() {
	const n = 1000
	ctx := context.Background()
	rng := rand.New(rand.NewPCG(7, 7))

	run := func(name string, put func(k, v string) error, get func(k string) (string, error), cl *session.Cluster) {
		stale := 0
		for i := 0; i < n; i++ {
			key := fmt.Sprintf("profile:%d", i%50)
			want := fmt.Sprintf("v%d", i)
			if err := put(key, want); err != nil {
				panic(err)
			}
			// Each follower applies the log up to a random point: lag of 0-3 writes.
			for r := 0; r < 2; r++ {
				head := cl.Head()
				lag := session.Version(rng.IntN(4))
				if lag > head {
					lag = head
				}
				cl.ApplyTo(r, head-lag)
			}
			got, err := get(key)
			if err != nil {
				panic(err)
			}
			if got != want {
				stale++
			}
		}
		fmt.Printf("%-28s stale reads %4d / %d\n", name, stale, n)
	}

	cl1 := session.NewCluster(2)
	naive := &before.Store{Leader: cl1.Leader(), Replicas: cl1.Replicas(), Rand: rand.New(rand.NewPCG(1, 1))}
	run("before: any replica", func(k, v string) error { return naive.Put(ctx, k, v) },
		func(k string) (string, error) { return naive.Get(ctx, k) }, cl1)

	cl2 := session.NewCluster(2)
	c := &session.Client{Leader: cl2.Leader(), Replicas: cl2.Replicas(), Guarantees: session.All}
	run("after: session token", func(k, v string) error { return c.Put(ctx, k, v) },
		func(k string) (string, error) { return c.Get(ctx, k) }, cl2)
	fmt.Printf("  served by replicas %d, by leader %d (fallback)\n", c.Stats.ReplicaReads, c.Stats.LeaderReads)
}
bash
cd docs/snippets/system-design/consistency-models/go
go vet ./... && go test ./...
go run ./cmd/lab

خروجی یک اجرای واقعی روی ماشین نویسنده (Go 1.27، seedها درون برنامه ثابت‌اند):

text
stale read after completed write   linearizable=false sequential=true
  longest legal prefix: c1 write(1)
new-then-old during a slow write   linearizable=false sequential=true
  longest legal prefix: c1 write(1) -> c2 read()=1
old-then-new during a slow write   linearizable=true  sequential=true
  witness: c2 read()=0 -> c1 write(1) -> c3 read()=1
before: any replica          stale reads  750 / 1000
after: session token         stale reads    0 / 1000
  served by replicas 450, by leader 550 (fallback)

آزمایش‌ها.

  1. سه حکم را کنار تصویر timeline بخوانید: دو تای اول sequentially consistent هستند ولی خطی نیستند؛ فقط زمان واقعی آن‌ها را از هم جدا می‌کند.
  2. lag را در sessions() از rng.IntN(4) به rng.IntN(2) تغییر دهید: stale readهای store ساده تقریباً نصف می‌شوند و سهم replica در session client بالا می‌رود؛ stale همچنان صفر می‌ماند.
  3. فقط Guarantees: session.MonotonicReads بگذارید: stale readها برمی‌گردند (read-your-writes دیگر اعمال نمی‌شود)، ولی TestMonotonicReadsNeverGoBackwards همچنان pass می‌شود.
  4. یک write معلق به یکی از historyهای checker_test.go اضافه کنید و ببینید «دیده شد» و «دیده نشد» هر دو پذیرفته می‌شوند، ولی «دیده شد و بعد دیده نشد» نه.
  5. نسخهٔ PostgreSQL («خروجی موردانتظار؛ اجرا نشده»): یک primary و یک standby با streaming راه بیندازید، بعد از یک UPDATE روی primary SELECT pg_current_wal_lsn(); بزنید، سپس روی standby SELECT pg_last_wal_replay_lsn() >= '<lsn>'::pg_lsn; در حالت عادی ظرف چند میلی‌ثانیه t برمی‌گرداند، و بعد از SELECT pg_wal_replay_pause(); تا SELECT pg_wal_replay_resume(); مقدار f.

بدفهمی‌های رایج ​

باورواقعیت
«Strong consistency» یک سطح استممکن است linearizable، read از leader، serializable یا external consistency باشد؛ بپرسید کدام
Serializable یعنی linearizableserializability قید زمان واقعی ندارد؛ strict serializability آن را اضافه می‌کند
کلیدهای خطی تراکنش امن می‌دهنددو کلید خطی همچنان write skew را مجاز می‌دانند؛ برای invariant چندکلیدی serializability لازم است
quorum read و write (R + W > N) خطی استنه با sloppy quorum، نه با writeهای همزمانی که با timestamp مرتب می‌شوند، نه بدون read repair پیش از برگرداندن
replication همگام یعنی read از replica تازه استدریافت‌شده با اعمال‌شده فرق دارد؛ remote_apply در PostgreSQL تنظیمی است که منتظر دیده‌شدن می‌ماند
sticky session روی load balancer read-your-writes می‌دهدسرور برنامه را سنجاق می‌کند، نه replica را
sticky در Laravel مشکل redirect بعد از ذخیره را حل می‌کندیک request دوام دارد؛ از PreventStaleDatabaseReads یا token استفاده کنید
eventually consistent یعنی «ظرف یک ثانیه»در مدل کران زمانی نیست؛ lag را اندازه بگیرید و برایش هشدار بگذارید
readهای «serializable» در etcd از readهای خطی قوی‌ترنددر etcd، serializable یعنی محلی و شاید کهنه
WAIT در Redis، Redis را strongly consistent می‌کندمستندات خودش می‌گوید نه؛ failover هنوز می‌تواند writeهای تأییدشده را گم کند
sessionهای MongoDB با هر concernی causal هستندفقط با read concern اکثریتی و write concern اکثریتی
NTP timestampها را برای مرتب‌سازی امن می‌کندNTP کران سفت نمی‌دهد؛ از HLC، consensus یا بازه‌هایی به سبک TrueTime استفاده کنید
یک integration test موفق linearizability را ثابت می‌کندفقط یک checker روی historyهای همزمان فراوان زیر خطا شاهد می‌دهد

چکیده ​

موضوعبه خاطر بسپارید
مدل سازگاری (Consistency model)مجموعه‌ای از historyهای مجاز؛ یک ویژگی safety
Linearizableتک‌شیء، زمان واقعی، رفتار تک‌نسخه‌ای؛ ترکیب‌پذیر؛ C در CAP
Sequentialیک ترتیب، ترتیب هر process حفظ می‌شود، بدون زمان واقعی
Causalهمه‌جا علت پیش از معلول؛ sticky available؛ causal+ همگرایی را اضافه می‌کند
PRAM= RYW + MR + MW؛ FIFO برای هر نویسنده
Session guaranteesRYW، MR، MW، WFR (Terry ۱۹۹۴)؛ با version token پیاده کنید
Eventual / strong eventualهمگرایی وقتی writeها بایستند / حالت برابر برای updateهای برابر (CRDT)
Serializableیک ترتیب سریالی از تراکنش‌ها؛ بدون زمان واقعی
Strict serializableSerializable + linearizable = external consistency در Spanner
SI / RCsnapshot برای هر تراکنش (write skew مجاز) / دادهٔ commitشده برای هر statement
Read خطیReadIndex یا read از log؛ lease read فقط با clock skew محدود
ساعت‌هاLamport (ترتیب کل)، vector (همزمانی)، HLC (علّی + نزدیک به فیزیکی)، TrueTime (بازهٔ محدود)
CockroachDBSERIALIZABLE؛ تک‌کلید خطی درون --max-offset برابر 500ms
DynamoDBپیش‌فرض eventual؛ ConsistentRead روی جدول/LSI؛ MRSC برای global table
CassandraCL قابل تنظیم؛ LWT (Paxos) برای هر partition برای CAS
تستKnossos/Porcupine (linearizability)، Elle (تراکنش)، Jepsen (خطا)

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — write(x=1) کلاینت A در t=10 جواب OK داد. read(x) کلاینت B در t=20 شروع شد و 0 برگرداند. این کدام مدل‌ها را نقض می‌کند: linearizable، sequential، read-your-writes؟ حیاتی ​

پاسخ

پاسخ: linearizability را نقض می‌کند (ترتیب زمان واقعی). همچنان sequentially consistent است (read کلاینت B را می‌شود پیش از write کلاینت A گذاشت)، و read-your-writes مصداق ندارد چون read مال کلاینت دیگری است. ببینید Linearizability و آزمایشگاه.

۲ — چرا serializability برای «انتقال انجام شد، حالا موجودی را نشان بده» کافی نیست؟ مهم ​

پاسخ

پاسخ: Serializability به دیتابیس اجازه می‌دهد read بعدی را پیش از انتقال مرتب کند، مثلاً با جواب دادن از یک snapshot یا replica کهنه. روی آن مسیر read به strict serializability (external consistency) نیاز دارید، یا به tokenی که read تازه را تحمیل کند. ببینید مدل‌های تراکنشی.

۳ — چهار session guarantee را نام ببرید و برای هر کدام یک ناهنجاری قابل‌دیدن توسط کاربر بگویید. مهم ​

پاسخ

پاسخ: Read-your-writes (ویرایش خود کاربر غیب می‌شود)، monotonic reads (کامنت ظاهر و بعد غیب می‌شود)، monotonic writes (ویرایش دوم پیش از اول اعمال می‌شود)، writes-follow-reads (پاسخ پیش از پیام دیده می‌شود). ببینید Session guarantees.

۴ — گزینهٔ sticky در Laravel چه تضمینی می‌دهد، و PreventStaleDatabaseReads چه اضافه می‌کند؟ مهم ​

پاسخ

پاسخ: sticky بعد از یک write درون همان request، readها را به connection نوشتن می‌فرستد. PreventStaleDatabaseReads زمان آخرین write را در session نگه می‌دارد و در requestهای بعدی تا N ثانیه (پیش‌فرض 2) از connection نوشتن می‌خواند. version token این حدس زمانی را با بررسی دقیق LSN عوض می‌کند. ببینید Laravel.

۵ — دو فراخوانی همزمان cas(0 -> 1) و cas(0 -> 2) هر دو موفق برمی‌گردند. آیا history خطی است؟ چرا مهم است؟ مهم ​

پاسخ

پاسخ: نه: در هر ترتیب کلی، CAS دوم مقدار اولی را می‌بیند و شکست می‌خورد. این همان باگ رزرو دوبل یا دو leader است. TestTwoWinningCASIsNotLinearizable آن را کد کرده. ببینید Go.

۶ — leader در Raft چطور بدون نوشتن در log یک read خطی جواب می‌دهد، و چرا lease read پرریسک‌تر است؟ تکمیلی ​

پاسخ

پاسخ: ReadIndex: اندیس commit را ثبت می‌کند، با یک دور heartbeat به اکثریت رهبری را تأیید می‌کند (بعد از commit کردن یک no-op در term خودش)، صبر می‌کند تا آن اندیس اعمال شود و بعد می‌خواند. lease read از دور heartbeat صرف‌نظر می‌کند و به زمان تکیه دارد؛ مقالهٔ Raft می‌گوید "assumes bounded clock skew". ببینید Read در consensus.

۷ — اگر ساعت یک گره از --max-offset فراتر برود CockroachDB چه چیزی را تضمین می‌کند، و با آن چه می‌کند؟ تکمیلی ​

پاسخ

پاسخ: serializability حفظ می‌شود، ولی linearizability تک‌کلیدی میان تراکنش‌های وابستهٔ علّی می‌تواند نقض شود. گره‌ای که ساعتش با دست‌کم نیمی از کلاستر به اندازهٔ ۸۰٪ max offset اختلاف داشته باشد خودش را crash می‌کند. ببینید ساعت‌ها.

۸ — یک session causally consistent در MongoDB با چه شرطی هر چهار session guarantee را می‌دهد؟ تکمیلی ​

پاسخ

پاسخ: با read concern برابر "majority" و write concern برابر "majority"، و اینکه در هر لحظه فقط یک thread از session استفاده کند. بین پردازه‌ها operationTime (و cluster time) را پاس بدهید و session جدید را advance کنید. ببینید Causal.

۹ — تیم شما Cassandra را با write و read در QUORUM استفاده می‌کند. آیا جدول نام کاربری در برابر تکراری امن است؟ مهم ​

پاسخ

پاسخ: نه. quorumها هم‌پوشانی دارند پس writeهای تمام‌شده دیده می‌شوند، ولی دو insert همزمان هر دو پذیرفته و با timestamp مرتب می‌شوند. از INSERT ... IF NOT EXISTS (LWT، Paxos) استفاده کنید و [applied] را بررسی کنید. ببینید محصولات.

۱۰ — برای بررسی write skew در historyای از تراکنش‌های چندکلیدی از کدام ابزار استفاده می‌کنید، و برای یک register تکی از کدام؟ تکمیلی ​

پاسخ

پاسخ: برای تراکنش‌ها Elle (چرخه‌های وابستگی مثل G2 را پیدا می‌کند)؛ برای linearizability تک‌شیئی Knossos یا Porcupine (یا checker همین صفحه). ببینید تست.

واژه‌نامه ​

واژهمعنا
مدل سازگاری (Consistency model)مجموعه‌ای از historyها که سیستم مجاز است تولید کند؛ یک ویژگی safety
تاریخچه (History)عملیات‌ها با زمان فراخوانی، زمان پاسخ و نتیجه
ناهنجاری (Anomaly)الگویی در history که مدل ممنوعش کرده (stale read، write skew، lost update)
ترتیب زمان واقعی (Real-time order)A پیش از B است اگر A پیش از فراخوانی B برگشته باشد
معنای تک‌نسخه‌ای (Single-copy semantics)سیستم طوری رفتار می‌کند که انگار از هر شیء یک نسخه هست
Linearizabilityتک‌شیء، زمان واقعی، اتمی؛ Herlihy و Wing ۱۹۹۰
CAS registerregister با read، write و compare-and-set؛ شیء استاندارد تست linearizability
Sequential consistencyیک ترتیب کل که ترتیب برنامهٔ هر process را رعایت می‌کند؛ Lamport ۱۹۷۹
Causal consistencyعملیات با رابطهٔ علّی همه‌جا با یک ترتیب دیده می‌شوند
Causal+causal consistency با حل تعارض همگرا (COPS)
PRAM / FIFO consistencywriteهای هر process به ترتیب خودش دیده می‌شوند؛ = RYW + MR + MW
Eventual consistencyاگر writeها بایستند replicaها همگرا می‌شوند؛ بدون کران ترتیب یا زمان
Strong eventual consistencyreplicaهایی با updateهای دریافتی یکسان حالت یکسان دارند (CRDT)
همگرایی (Convergence)رسیدن replicaها به حالت یکسان از راه anti-entropy، read repair و ادغام
Session guaranteesتضمین‌های کلاینت‌محور: RYW، MR، MW، WFR (Terry و همکاران ۱۹۹۴)
Read-your-writesreadهای یک session writeهای قبلی خودش را بازتاب می‌دهند
Monotonic readsیک session هیچ‌وقت حالتی قدیمی‌تر از آنچه خوانده نمی‌خواند
Monotonic writeswriteهای یک session همه‌جا به ترتیب صدور اعمال می‌شوند
Writes-follow-readsیک write بعد از writeهایی که sessionش خوانده بود مرتب می‌شود
Serializabilityتراکنش‌ها معادل یک ترتیب سریالی‌اند
Strict serializabilityserializable با ترتیبی سازگار با زمان واقعی
External consistencyنام Spanner برای strict serializability
Snapshot isolationread از snapshot شروع؛ اولین commit برنده؛ write skew مجاز
Read committedهر read فقط دادهٔ commitشده می‌بیند
Lamport clockشمارندهٔ صحیح سازگار با happened-before
Vector clockیک شمارنده برای هر گره؛ همزمانی را تشخیص می‌دهد
Hybrid logical clockزمان فیزیکی به‌علاوهٔ شمارندهٔ منطقی، علیت را رعایت می‌کند
TrueTimeAPI ساعت Spanner که بازه‌ای محدود برمی‌گرداند
Clock skewاختلاف ساعت دو گره
پنجرهٔ عدم‌قطعیت (Uncertainty window)بازه‌ای بعد از timestamp یک read که ترتیب مقادیرش نامعلوم است (CockroachDB)
Commit waitصبر Spanner تا timestamp commit قطعاً گذشته باشد
Lease readread از leader با تکیه بر lease زمانی رهبری
ReadIndexread در Raft که اول با یک دور heartbeat رهبری را تأیید می‌کند
Quorum readread از R replica از N، تازه‌ترین برنده
Stale readreadی که writeِ تمام‌شده پیش از شروعش را نمی‌بیند
Replica lagفاصلهٔ state اعمال‌شدهٔ replica از leader
Sticky connectionبعد از write، readها از connection نوشتن (sticky در Laravel)
Version tokenجایگاه log (LSN، GTID، operationTime) که session حمل می‌کند تا کهنگی را محدود کند
LWTlightweight transaction در Cassandra: CAS مبتنی بر Paxos برای هر partition
Paxos / Raftپروتکل‌های consensus که یک log تکثیرشدهٔ خطی می‌دهند
Jepsenتست مبتنی بر تزریق خطا برای ادعاهای سازگاری سیستم‌های توزیع‌شده
Knossoschecker خطی بودن در Jepsen
Ellechecker ناهنجاری‌های تراکنشی در Jepsen
Porcupinechecker سریع linearizability به زبان Go
Linearizability checkerابزاری که برای یک history دنبال ترتیب مجازِ رعایت‌کنندهٔ زمان واقعی می‌گردد

منابع ​

ساخته‌شده توسط Morteza Negahi