DDIA·واژه‌هاTERMS

نقشه راهRoadmap/ واژه‌نامهGlossary/ فصل ۴Chapter 4

۴4ذخیره‌سازی و بازیابیStorage and retrieval

۲۵ واژه از فصل ۴ — هر کدام با یک مثال روزمره، یک نمودار و تلهٔ رایج.25 terms from chapter 4, each with an everyday example, a diagram and the usual trap.

چند پرش، و رکورد جلوی توست.A few hops and the record is in front of you.

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دنبال یک اسم در دفترچه تلفن کاغذی می‌گردی. صفحه‌به‌صفحه ورق نمی‌زنی؛ دفترچه را وسط باز می‌کنی، می‌بینی اسم قبل از این صفحه است یا بعدش، و نصف بعدی را رد می‌کنی. سه چهار تا از این نصف‌کردن‌ها و رسیدی.You are hunting a name in a paper address book. You do not flip page by page; you open it in the middle, see whether the name falls before or after, and drop half the book. Three or four of those halvings and you are there.

تشبیه و تصویر ذهنیThe analogy

حالا تصور کن این دفترچه هر شب توسط چند نفر به‌روز می‌شود. هر صفحه فقط چند جا برای اسم دارد و همیشه مرتب است. وقتی صفحه پر شد، وسطش را باز می‌کنی و به دو صفحهٔ مرتب تبدیلش می‌کنی و یکی را به شاخهٔ بالاتر معرفی می‌کنی؛ پس دفترچه همیشه مرتب می‌ماند و همیشه با چند پرش می‌رسد. بهای این نظم این است که درج یک اسم ممکن است یک صفحه را نصف کند و دو جا را تغییر دهد، نه یک جا.Now imagine several people update that book every night. Each page holds only so many names and is always sorted. When a page fills, you split it in the middle, make two sorted pages, and tell the level above about the new one; the book stays sorted and stays a few hops deep. The price of that order is that inserting one name may split a page and touch two places, not one.

B-tree · درجاB-tree · in placeصفحهٔ ثابت، عمق ۳ تا ۴fixed pages, depth 3–4خواندن: چند پرشread: a few hopsنوشتن: صفحه + WALwrite: page + WALLSM-tree · فقط افزودنLSM-tree · append onlymemtable و SSTablememtable and SSTablesخواندن: چند جا را بگردread: check several placesنوشتن: فقط دنبالهwrite: append only
دو خانوادهٔ ایندکس، دو بهای متفاوت: B-tree در جا به‌روز می‌شود، LSM فقط می‌افزاید و بعد فشرده می‌کند.Two index families, two different bills: a B-tree updates in place, an LSM only appends and compacts later.

و بعدش، فنیAnd now, technically

درخت B یک درخت متوازن است که هر گره‌اش یک صفحهٔ با اندازهٔ ثابت است: آرایهٔ مرتبی از کلیدها به‌همراه اشاره‌گر به فرزندان. با میلیون‌ها ردیف، عمق درخت سه یا چهار سطح می‌ماند، یعنی سه یا چهار خواندن صفحه؛ و چون هر صفحه چند صد کلید را جا می‌دهد، ضریب شاخه‌بندی بالاست و درخت کم‌عمق می‌ماند. نوشتن جای خود را در صفحه پیدا می‌کند و همان‌جا به‌روز می‌شود؛ اگر صفحه پر باشد نصف می‌شود. به همین دلیل هر نوشتن ممکن است چند صفحه را لمس کند و نوشتن تصادفی تولید کند، و برای تحمل خرابی باید همراه WAL بیاید. در عوض، پیمایش بازه‌ای طبیعی و ارزان است، چون برگ‌ها به هم زنجیر شده‌اند.A B-tree is a balanced tree whose nodes are fixed-size pages: a sorted array of keys plus pointers to children. With millions of rows the depth stays at three or four levels, meaning three or four page reads, and because each page holds hundreds of keys the branching factor is high and the tree stays shallow. A write locates its slot and updates in place; if the page is full it splits. That is why a write may touch several pages and produce random I/O, and why a B-tree needs a WAL for crash safety. In exchange, range scans are natural and cheap because leaf pages are chained together.

≈ 4 KBاندازهٔ معمول یک صفحه، هم‌اندازهٔ صفحهٔ دیسکa typical page, matched to the disk page
3–4عمق درخت برای میلیون‌ها ردیفtree depth for millions of rows
~hundredsکلید در هر صفحه، یعنی ضریب شاخه‌بندی بالاkeys per page, which is why branching is wide

چرا اندازهٔ صفحه مهم استWhy the page size matters

دیسک و SSD داده را صفحه‌صفحه می‌خوانند، نه بایت‌به‌بایت. اگر گرهٔ درخت دقیقاً یک صفحه باشد، هر پرش فقط یک خواندن است و هیچ بایتی هدر نمی‌رود. اگر گره کوچک‌تر از صفحه باشد، هر خواندن بخشی از صفحه را بیهوده می‌آورد؛ اگر بزرگ‌تر باشد، یک پرش چند خواندن می‌شود. به همین دلیل اندازهٔ صفحه در اکثر موتورها ۴ یا ۸ کیلوبایت است و درخت با همان واحد تنظیم می‌شود.Disks and SSDs read data in pages, not bytes. If a tree node is exactly one page, every hop is exactly one read and no byte is wasted. A node smaller than a page wastes part of every read; a node larger than a page turns one hop into several reads. That is why most engines settle on 4 or 8 KB pages and shape the tree around that unit.

قفل‌ها و همزمانی روی همین صفحه‌هاLatches on those same pages

چون هر نوشتن یک یا چند صفحه را لمس می‌کند، دو نوشتن که به یک صفحه برسند باید پشت سر هم بنشینند؛ این همان نقطه‌ای است که contention از آن بیرون می‌آید. موتورهای جدی با قفل‌های کوتاه (latch) روی صفحه و با جدا کردن خواندن از نوشتن (MVCC) این اصطکاک را کم می‌کنند، ولی هیچ‌کدام جادو نیست: اگر همهٔ نوشتن‌ها به یک صفحه برسند، همان صفحه گلوگاه است، هر قدر هم که درخت متوازن باشد.Because a write touches one or more pages, two writes that reach the same page must take turns; that is where contention comes from. Serious engines reduce the friction with short page latches and by separating readers from writers through MVCC, but none of it is magic: if every write lands on the same page, that page is the bottleneck no matter how balanced the tree is.

B-tree در برابر LSM-treeB-tree versus LSM-tree

B-treeB-treeLSM-treeLSM-tree
خواندن نقطه‌ایPoint readچند پرش، پیش‌بینی‌پذیرa few hops, predictableچند ساختار را باید بگرددmust check several structures
نوشتنWriteدر جا، با احتمال شکستن صفحهin place, may split a pageفقط افزودن، بسیار ارزان‌ترappend only, much cheaper
پیمایش بازه‌ایRange scanطبیعی و ارزانnatural and cheapروی چند فایل مرتب، با ادغامmerge across sorted files
هزینهٔ پنهانHidden costنوشتن تصادفیrandom writesفشرده‌سازی پس‌زمینهbackground compaction

تلهٔ رایجThe usual trap

فکر کردن این‌که درخت باید همیشه در حافظه بماند. عملاً گلوگاه، خواندن صفحه است: هر سطح بیشتر یا صفحهٔ بزرگ‌تر، مستقیماً تأخیر را بالا می‌برد. ترتیب این‌که کدام صفحه در بافر می‌ماند هم مهم است؛ درخت به‌تنهایی کش نیست.Assuming the tree stays in memory. In practice the page read is the bottleneck: each extra level or oversized page raises latency directly. Which pages stay in the buffer pool matters just as much; a tree on its own is not a cache.

«نه» قطعی است؛ «شاید» را چطور می‌فهمی؟The no is final; what do you do with maybe?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

قبل از اینکه صندلی عروسی را اضافه کنی، فهرست مهمان‌ها را نگاه می‌کنی. اگر اسمی در فهرست نبود، با خیال راحت می‌گویی دعوت نشده. اگر بود، باز هم مطمئن نیستی؛ شاید هم‌نام باشد و آدم دیگری باشد. آن‌وقت باید نام خانوادگی را چک کنی. فیلتر بلوم هم دقیقاً همین دو جواب را می‌دهد: «قطعاً نیست» و «شاید هست».Before adding a chair for the wedding you check the guest list. If a name is not on it, you can safely say that person was not invited. If it is, you are still not sure: it may be a different person with the same first name, so you go and check the surname. A Bloom filter gives exactly those two answers: definitely not, and maybe.

تشبیه و تصویر ذهنیThe analogy

فهرست مهمان‌ها را روی یک دیوار آجری کوچک نگه می‌داری: برای هر اسم، سه آجر را رنگ می‌زنی. بعداً برای پرسیدن «این آدم دعوت است؟» همان سه آجر را نگاه می‌کنی. اگر یکی سفید باشد، قطعاً دعوت نیست. اگر هر سه رنگی باشند، شاید دعوت باشد. مشکل وقتی است که دو اسم مختلف همان سه آجر را رنگ کرده باشند؛ آن‌وقت جواب «شاید» می‌شود و باید دفتر اصلی را باز کنی. بدتر اینکه آجرها را نمی‌شود پاک کرد، چون نمی‌دانی رنگ یک آجر را کدام اسم گذاشته؛ پس حذف در این فیلتر ساده جایی ندارد.You keep the guest list on a small brick wall: for each name you paint three bricks. Later, to ask whether a person is invited, you look at those three bricks. If one is still bare, they are definitely not invited. If all three are painted, maybe they are. Trouble starts when two different names painted the same three bricks; then the answer is maybe and you have to open the real list. Worse, bricks cannot be unpainted, because you no longer know which name painted a brick, so simple deletion has no place here.

بیت ۱bit 1بیت ۲bit 2بیت ۳bit 3بیت ۴bit 4نانbreadشیرmilkتخم‌مرغeggsبیت مشترک یعنی احتمال مثبت کاذبa shared bit means a false positive is possible
سه کلید روی چهار بیت؛ کلید تازه‌ای که هش‌هایش به همین بیت‌ها بخورد، «شاید هست» می‌گیرد.Three keys over four bits; a new key hashing onto the same bits is told maybe.

و بعدش، فنیAnd now, technically

فیلتر بلوم یک آرایهٔ بیتی با m بیت و k تابع هش است. برای درج یک کلید، هر k تابع یک بیت را برمی‌گردانند و همه را یک می‌کنی. برای پرسیدن، همان k بیت را می‌خوانی: اگر حتی یکی صفر باشد، کلید قطعاً در مجموعه نیست؛ اگر همه یک باشند، شاید باشد. خطای منفی ندارد، چون درج همیشه همان بیت‌ها را یک می‌کند. خطای مثبت دارد، چون بیت‌ها بین کلیدها مشترک‌اند. با حدود ده بیت برای هر کلید و هفت هش، نرخ مثبت کاذب نزدیک یک درصد می‌شود. در LSM هر SSTable یک فیلتر دارد و پیش از هر خواندن دیسک پرسیده می‌شود؛ در شبکه هم برای رد کردن درخواست‌های قطعاً ناموجود به کار می‌رود. حذف پشتیبانی نمی‌شود، مگر با شمارنده یا بازسازی دوره‌ای فیلتر.A Bloom filter is a bit array of m bits plus k hash functions. To insert a key you hash it k ways and set those k bits to one. To ask whether a key is present you read the same k bits: if any is zero the key is definitely absent; if all are one it may be present. There are no false negatives, because insertion always sets all of them. False positives exist because different keys share bits. With about ten bits per key and seven hashes, the false-positive rate lands near one percent. In an LSM tree every SSTable carries a filter, so most reads for missing keys never touch the disk; in a network service the same filter rejects requests that cannot match. Deletion is not supported: clearing bits would erase other keys' evidence, unless you keep counters or rebuild the filter.

≈ 1%نرخ مثبت کاذب با ۱۰ بیت برای هر کلید و ۷ هشfalse-positive rate at 10 bits per key and 7 hashes
~10 bitsهزینهٔ حافظه برای هر کلید در همین تنظیمmemory per key at that setting
0خطای منفی؛ اگر بگوید نیست، واقعاً نیستfalse negatives: a no is always true

چرا حذف وجود نداردWhy there is no delete

بیت‌ها مشترک‌اند و فیلتر نمی‌داند کدام کلید کدام بیت را روشن کرده است. اگر برای حذف یک کلید بیت‌هایش را صفر کنی، ممکن است بیت کلید دیگری را هم خاموش کرده باشی و آن کلید به «قطعاً نیست» تبدیل شود؛ یعنی خطای منفی، همان چیزی که فیلتر قرار بود هرگز نداشته باشد. راه اول استفاده از شمارنده است: به‌جای یک بیت، یک عدد کوچک نگه می‌داری که با هر درج زیاد و با هر حذف کم می‌شود، ولی حافظه سه چهار برابر می‌شود. راه دوم بازسازی دوره‌ای فیلتر از داده است؛ ساده‌تر، ولی نیاز به دانستن کل مجموعه دارد.The bits are shared, and the filter has no idea which key set which one. Clearing a deleted key's bits can switch off a bit another key depends on, turning that key into definitely not: a false negative, the one error the filter was supposed to never make. One answer is counting: keep a small counter per slot that each insert increments and each delete decrements, at three or four times the memory. The other is rebuilding the filter from the data periodically, which is simpler but needs the whole set.

فیلتر کجا خرجش را درمی‌آوردWhere the filter pays for itself

در LSM، پرسیدن یک فیلتر تقریباً مجانی است و یک خواندن دیسک گران. اگر فیلتر بگوید «نیست»، به‌جای یک read تصادفی چند بیت خواندی؛ با صدها فایل در هر لایه، این تفاوت همان چیزی است که تأخیر خواندن را قابل قبول نگه می‌دارد. نکتهٔ ظریف اندازه است: فیلتر برای تعداد مشخصی کلید ساخته می‌شود. اگر داده بیشتر از پیش‌بینی رشد کند، بیت‌ها اشباع می‌شوند و نرخ مثبت کاذب از یک درصد به سی چهل درصد می‌رسد، بی‌آنکه خطایی رخ دهد. در آن حالت فیلتر هم حافظه می‌خورد هم CPU، ولی دیگر چیزی را رد نمی‌کند.In an LSM, asking a filter is almost free and reading a disk page is not; when the filter says absent you spent a few bits instead of a random read, and across hundreds of files per level that is what keeps read latency bearable. The subtle part is sizing. A filter is built for a fixed number of keys. Let the data outgrow the forecast and the bits saturate, the false-positive rate climbs from one percent to thirty or forty, and nothing raises an error. The filter then costs memory and CPU while rejecting almost nothing.

تلهٔ رایجThe usual trap

ساختن فیلتر برای یک اندازه و ریختن چند برابر آن داده داخلش. فیلتر خطا نمی‌دهد؛ فقط کم‌کم همه‌چیز را «شاید هست» می‌گوید و خواندن‌ها دوباره به دیسک می‌خورند، بی‌آنکه کسی بفهمد چرا کند شده‌اند. اندازه را با رشد داده بازبینی کن، یا فیلتر را بخش‌بخش کن تا بخش داغ در حافظه بماند.Sizing the filter once and then pouring several times that data into it. The filter raises no error; it slowly answers maybe to everything and reads fall back to disk, and nobody can say why things got slow. Revisit the size as data grows, or partition the filter so the hot part stays in memory.

columnar storage

ذخیره‌سازی ستونی فصل ۴Chapter 4 · دیدن در متنsee in context

اگر فقط یک ستون را می‌خواهی، چرا بقیه را بخوانی؟If you need one column, why read the rest?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دفتر نمرهٔ معلم را ببین: هر دانش‌آموز یک ردیف دارد و هر درس یک ستون. معلم برای حساب کردن معدل ریاضی فقط ستون ریاضی را می‌خواند؛ لازم نیست نمرهٔ فارسی و علوم هر دانش‌آموز را هم بخواند. حالا فکر کن همهٔ نمره‌های ریاضی پشت سر هم روی یک صفحه نوشته شده بودند؛ جمع زدنشان چند لحظه بیشتر طول نمی‌کشید. ذخیرهٔ ستونی همین کار را با دیسک می‌کند: دادهٔ هر ستون کنار هم می‌نشیند، نه ردیف‌های کامل.Look at a teacher's gradebook: each student has a row, each subject a column. To compute the maths average the teacher reads only the maths column; she does not need every student's Persian and science marks. Now imagine all the maths marks written one after another on a single page; adding them up would take moments. Columnar storage does that with disk: one column's values sit together, not whole rows.

تشبیه و تصویر ذهنیThe analogy

چرا این کار جواب می‌دهد؟ چون وقتی چند هزار مقدار از یک جنس را پشت سر هم می‌گذاری، همه‌شان عدد، تاریخ، یا یک رشتهٔ کوتاه تکراری‌اند. عددهای پشت سر هم را می‌شود ارزان فشرده کرد و برای جمع زدن، پردازنده می‌تواند یک دستور را روی ده‌ها مقدار همزمان اجرا کند. اما اگر کسی یک ردیف کامل بخواهد، مثلاً کل پروندهٔ یک دانش‌آموز، باید از هر ستون یک تیکه بردارد و دوباره کنار هم بچیند؛ همین کار در سیستم ردیفی یک خواندن بود. پس انتخاب ستونی یا ردیفی به این بستگی دارد که سؤال تو «چند ردیف، چند ستون» است یا «یک ردیف، همهٔ ستون‌ها». ذخیرهٔ ستونی برای سؤال اول ساخته شده و برای دومی بد است.Why does it work? Because thousands of values of one kind written together are all numbers, dates, or a short repeated string. Runs of similar values compress cheaply, and for a sum the processor can apply one instruction to dozens of values at once. But if someone wants one whole row, a single student's record, you have to take a slice from every column and reassemble it, which was one read in a row store. So the choice depends on whether your question is few rows and few columns or one row and all columns. Columnar storage is built for the first question and is bad at the second.

ردیفی · OLTPRow store · OLTPهر ردیف کنار همa row lives togetherخواندن یک ردیف ارزانone row read is cheapاسکن یک ستون گرانscanning a column is costlyستونی · OLAPColumn store · OLAPهر ستون کنار همa column lives togetherاسکن یک ستون ارزانone column scan is cheapنوشتن یک ردیف گرانwriting one row is costly
یکی ردیف را کنار هم می‌چیند، دیگری ستون را؛ هر کدام برای یک جور سؤال ساخته شده است.One lays rows out together, the other columns; each is built for a different question.

و بعدش، فنیAnd now, technically

در ذخیرهٔ ستونی، مقادیر هر ستون در بلوک‌های پیوسته روی دیسک می‌نشینند و هر بلوک معمولاً با دیکشنری، RLE یا بیت‌فشرده ذخیره می‌شود. چون همهٔ مقادیر یک بلوک از یک نوع و اغلب شبیه هم‌اند، فشرده‌سازی چند برابر بهتر از ردیفی جواب می‌دهد و همان بایت‌ها دوباره خوانده می‌شوند. هر بلوک آمار کوچکی هم دارد: کمینه و بیشینهٔ هر ستون، که به موتور اجازه می‌دهد کل بلوک را رد کند. اجرای برداری یک عملگر را روی هزاران مقدار همزمان اعمال می‌کند و ماده‌سازی دیرهنگام ستون‌های دیگر را تا لحظهٔ لازم نمی‌خواند. نوشتن یک ردیف کامل اما گران است، چون باید به چند بلوک مختلف دست بزند؛ برای همین انبارهای داده دسته‌ای می‌نویسند و به‌روزرسانی را به حذف و درج دوباره تبدیل می‌کنند. Parquet و ORC همین طرح را در فایل پیاده می‌کنند.In columnar storage each column's values live in contiguous blocks, and a block is usually dictionary-encoded, run-length encoded, or bit-packed. Because a block holds one type and often similar values, compression does several times better than row storage and fewer bytes cross the bus. Each block also carries small statistics, minimum and maximum per column, so the engine can skip whole blocks. Vectorized execution applies one operator to thousands of values at once, and late materialization avoids reading other columns until they are needed. Writing one full row is expensive, since it touches several blocks, which is why warehouses write in batches and turn updates into deletes plus inserts. Parquet and ORC implement exactly this layout in a file.

1–3ستون‌هایی که یک پرس‌وجوی تحلیلی از ده‌ها ستون می‌خواندcolumns a typical analytical query reads out of dozens
5–10×فشرده‌سازی معمول ستونی با دیکشنری و RLEtypical columnar compression with dictionary and RLE
O(rows)پیمایش یک ستون، بدون خواندن ستون‌های دیگرscanning one column without reading the others

چرا ستون‌ها این‌قدر خوب فشرده می‌شوندWhy columns compress so well

در یک ستون، همهٔ مقادیر از یک نوع‌اند و اغلب از یک دامنهٔ کوچک می‌آیند: کشور، وضعیت سفارش، ماه. وقتی هزار مقدار تکراری پشت سر هم باشد، به‌جای هزار بار نوشتن، یک بار می‌نویسی که این مقدار هزار بار تکرار شده. اگر دامنه کوچک باشد، هر مقدار به چند بیت تبدیل می‌شود. برای ستون‌های مرتب، تفاضل گرفتن از مقدار قبلی، اعداد بزرگ را به اعداد کوچک تبدیل می‌کند. هیچ‌کدام از این‌ها در ذخیرهٔ ردیفی جواب نمی‌دهد، چون در یک ردیف، کشور و مبلغ و تاریخ کنار هم می‌نشینند و هیچ‌کدام شبیه بقیه نیست.In one column every value shares a type and usually a small domain: country, order status, month. A thousand identical values in a row become one value plus a count instead of a thousand copies. A small domain allows a few bits per value. For sorted columns, taking the difference from the previous value turns big numbers into small ones. None of this works in row storage, where country, amount and date sit side by side inside a row and none of them looks like its neighbour.

چرا OLTP ستونی نیستWhy OLTP is not columnar

کار تراکنشی یک ردیف را می‌خواهد، کامل و همان لحظه: سفارش تازه، موجودی، وضعیت پرداخت. در ذخیرهٔ ستونی، همان یک ردیف به ده‌ها بلوک مختلف پخش شده و نوشتنش یعنی دست زدن به چند فایل و احتمالاً بازنویسی بلوک. علاوه بر این، هر بلوک فشرده است و تغییر یک مقدار یعنی باز کردن و دوباره بستن آن. برای همین سیستم‌های تراکنشی ردیفی می‌مانند و ذخیرهٔ ستونی جای انبار داده و گزارش‌گیری است، جایی که نوشتن دسته‌ای و خواندن سنگین است.Transactional work wants one row, whole and immediately: a new order, a stock level, a payment status. In columnar storage that single row is spread over dozens of blocks, so writing it means touching several files and probably rewriting a block. Each block is compressed as well, so changing one value means opening and closing it again. That is why transactional systems stay row-oriented and columnar storage belongs to warehouses and reporting, where writes arrive in batches and reads are heavy.

تلهٔ رایجThe usual trap

آوردن یک انبار ستونی برای کار تراکنشی، یا زدن SELECT * روی جدول ستونی. لحظه‌ای که همهٔ ستون‌ها را می‌خواهی، مزیت ستونی به ضرر تبدیل می‌شود: باید ده‌ها بلوک را باز کنی و ردیف‌ها را دوباره بسازی، و همان پرس‌وجو که در سیستم ردیفی یک خواندن بود، اینجا ده‌ها خواندن است.Bringing a column store to transactional work, or running SELECT star on a columnar table. The moment you want every column, the columnar advantage reverses: dozens of blocks open and rows get reassembled, and a query that was one read in a row store becomes dozens.

compaction

فشرده‌سازی فصل ۴Chapter 4 · دیدن در متنsee in context همچنینalso in فصل ۱۲ch 12

چرا فایل‌ها فقط زیاد می‌شوند و کم نمی‌شوند؟Why do the files only grow and never shrink?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

رسیدهای خرید را در یک جعبه می‌ریزی. هر چند ماه یک بار جعبه را خالی می‌کنی: رسیدهای تکراری و باطل‌شده را دور می‌ریزی، بقیه را به ترتیب تاریخ می‌چینی و در جعبهٔ کوچک‌تری می‌گذاری. تا آن روز، پیدا کردن یک رسید یعنی زیر و رو کردن کل جعبه. compaction هم دقیقاً همین نظافت دوره‌ای است، فقط با فایل‌های داده.You drop shopping receipts into a box. Every few months you empty it: duplicate and cancelled receipts go out, the rest are sorted by date and moved to a smaller box. Until that day, finding one receipt means turning the whole box over. Compaction is that periodic tidy-up, for data files.

تشبیه و تصویر ذهنیThe analogy

دو دسته رسید داری که هر کدام به ترتیب تاریخ مرتب‌اند. برای ادغام، لازم نیست همه را دوباره بخوانی و از نو بچینی؛ دو انگشت روی دو دسته می‌گذاری، هر بار قدیمی‌تر را برمی‌داری و جلو می‌روی. این کار خطی است و با حجم کار متناسب. حالا بهایش: همان لحظه که تو مشغول مرتب کردن هستی، مغازه باز است و رسید تازه هم می‌آید. اگر مرتب کردن عقب بیفتد، جعبه پر می‌شود و پیدا کردن هر چیز کندتر. اگر هم خیلی سریع و پشت سر هم مرتب کنی، وقت و دیسک زیادی صرف کارهایی می‌شود که شاید هیچ‌وقت لازم نشوند. compaction همین معامله را هر روز با تو می‌کند.You have two stacks of receipts, each already sorted by date. To merge them you do not re-read and re-sort everything; you put a finger on each stack, take the older slip each time, and move forward. The work is linear in the input. Now the bill: while you are sorting, the shop is open and new receipts keep arriving. Let the tidying fall behind and the box overflows, and finding anything gets slow. Tidy too eagerly and you spend time and disk on work that may never be needed. Compaction makes that trade every day.

SSTableهای تازهfresh SSTablesلایهٔ کوچکthe small levelانتخاب لایهpick a levelسیاست ادغامmerge policyادغام مرتبmerge in orderچند فایل، یک پیمایشk files, one passحذف تکراری و مردهdrop stale and deadسنگ‌قبرtombstonesفایل تازهone new fileقدیمی‌ها می‌روندold ones go
چند فایل هم‌پوشان با یک پیمایش ادغام می‌شوند؛ نسخهٔ تازه می‌ماند، مرده‌ها می‌روند.Overlapping files merge in one pass; the newest version survives, the dead ones go.

و بعدش، فنیAnd now, technically

در درخت LSM، هر نوشتن یک SSTable تازه می‌سازد و فایل‌ها تغییرناپذیرند؛ پس نسخه‌های قدیمی یک کلید و نشانه‌های حذف روی دیسک جمع می‌شوند. compaction چند فایل هم‌پوشان را انتخاب می‌کند، آن‌ها را با یک پیمایش ادغام مرتب می‌خواند، جدیدترین نسخهٔ هر کلید را نگه می‌دارد و خروجی را به‌صورت فایل تازه در لایهٔ بعد می‌نویسد. دو سیاست رایج دارد: size-tiered که فایل‌های هم‌اندازه را با هم ادغام می‌کند و نوشتن ارزان‌تری دارد، و leveled که هر لایه را مرتب نگه می‌دارد و خواندن را ارزان‌تر می‌کند ولی نوشتن را گران‌تر. هر بایت داده چند بار در طول عمرش بازنویسی می‌شود و همین write amplification است. نشانهٔ حذف تا پایان دورهٔ مهلت نگه داشته می‌شود، چون ممکن است نسخهٔ قدیمی روی نودی باشد که هنوز حذف را ندیده است. اگر compaction از نوشتن عقب بماند، فضای دیسک پر می‌شود و تأخیر نوشتن بالا می‌رود.In an LSM tree every write creates a fresh SSTable and the files never change, so old versions of a key and deletion markers pile up on disk. Compaction picks a set of overlapping files, merges them in one sorted pass, keeps the newest version of each key, and writes the result as a new file in the next level. Two policies dominate: size-tiered, which merges similarly sized files and keeps writes cheap, and leveled, which keeps each level sorted and makes reads cheaper at the price of more writing. Every byte is rewritten several times over its life, which is write amplification. A tombstone is kept until its grace period ends, because an old version may still sit on a node that has not seen the delete. When compaction falls behind the write rate, disk fills and write latency climbs.

2–10×ضریب نوشتن اضافی: هر بایت چند بار جابه‌جا می‌شودextra write factor: how often each byte is rewritten
L0 → Lnلایه‌ها؛ هر لایه بزرگ‌تر، مرتب‌تر و سردترthe levels: each larger, more sorted, colder
p99جایی که عقب‌افتادن compaction خودش را نشان می‌دهدwhere a compaction backlog shows up

سنگ‌قبر و بازگشت مردهTombstones and the returning dead

حذف در LSM یعنی نوشتن یک نشانه که می‌گوید این کلید مرده است. تا وقتی آن نشانه روی دیسک باشد، خواندن‌ها کلید را پیدا می‌کنند و «نیست» جواب می‌دهند. compaction نشانه را وقتی دور می‌ریزد که مطمئن باشد نسخهٔ قدیمی هم دیگر جایی نیست. در یک سیستم توزیع‌شده، این «مطمئن» گران است: ممکن است نودی مدت‌ها آفلاین بوده و هنوز نسخهٔ قدیمی را داشته باشد. اگر نشانه زودتر پاک شود، آن نود برمی‌گردد و ردیف حذف‌شده مثل روح ظاهر می‌شود. برای همین دورهٔ مهلت باید از حداکثر زمان قطعی نودها بیشتر باشد.In an LSM, deleting means writing a marker that says this key is dead. While the marker is on disk, reads find the key and answer absent. Compaction drops the marker only once it is sure no older version survives anywhere. In a distributed system that certainty is expensive: a node may have been down for a long time and still hold the old value. Clear the marker too early and that node comes back with the deleted row, a ghost in the data. The grace period therefore has to exceed the longest node outage you tolerate.

بدهی compactionCompaction debt

compaction از نوشتن عقب می‌ماند، و این عقب‌ماندگی جمع می‌شود. اول فقط فایل‌های بیشتری روی دیسک می‌مانند و خواندن کندتر می‌شود؛ بعد، نوشتن باید صبر کند تا جای خالی برای ریختن memtable باشد و تأخیر می‌پرد. بدترین حالت وقتی است که دیسک تقریباً پر است و compaction برای آزاد کردن جا به منابع بیشتری نیاز دارد که همان لحظه در دسترس نیست. راه‌حل عملی، محدود کردن نرخ نوشتن و هشدار روی فضای آزاد است، نه امید به اینکه compaction خودش را برساند.Compaction lags the write rate, and the lag accumulates. First more files stay on disk and reads slow down; then a write has to wait for room to flush the memtable and latency spikes. The worst case is a nearly full disk needing compaction to free space, while compaction needs the resources that are now scarce. The practical answer is to throttle writers and alert on free space, not to hope compaction catches up.

تلهٔ رایجThe usual trap

پاک کردن نشانهٔ حذف پیش از آنکه همهٔ نسخه‌ها دیده باشند. در یک خوشه با نودهای گاهی آفلاین، این کار ردیف حذف‌شده را برمی‌گرداند و کسی هم نمی‌فهمد از کجا آمده. دورهٔ مهلت را از حداکثر قطعی نودها بزرگ‌تر بگیر، وگرنه حذف فقط یک آرزو است.Dropping a tombstone before every replica has seen it. In a cluster whose nodes occasionally go offline, that brings the deleted row back and nobody can explain where it came from. Set the grace period above your longest outage, or deletion is only a wish.

compression

فشرده‌سازی داده فصل ۴Chapter 4 · دیدن در متنsee in context

همان داده، جای کمتر — به چه قیمتی؟The same data in less space — at what price?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

لباس‌های زمستانی را در کیسهٔ خلأ می‌گذاری تا در چمدان جا شوند. حالا دو برابر لباس جا می‌شود، ولی هر بار که یک پیراهن می‌خواهی باید کیسه را باز کنی و دوباره هوا را بیرون بکشی. فشرده‌سازی داده هم همین معامله است: جا کم می‌شود، دسترسی گران.You pack winter clothes into vacuum bags so they fit the suitcase. Now twice as much fits, but every time you want one shirt you have to open the bag and pull the air out again. Compressing data is the same trade: less space, dearer access.

تشبیه و تصویر ذهنیThe analogy

بعضی چیزها خوب فشرده می‌شوند و بعضی نه. لباس‌های تاشدنی جای زیادی باز می‌کنند؛ یک گلدان سرامیکی هیچ. در داده هم متن، کلیدهای مرتب و ستون‌هایی که هزار بار یک مقدار را تکرار می‌کنند خوب فشرده می‌شوند، ولی شناسه‌های تصادفی، فایل عکس و هر چیزی که از قبل رمزنگاری شده باشد تقریباً هیچ سودی نمی‌دهد. نکتهٔ دوم اندازهٔ واحد است: کیسه‌های کوچک‌تر را می‌شود جدا باز کرد، پس فقط همان کیسه‌ای را باز می‌کنی که لازم داری؛ به همین دلیل داده را بلوک‌بلوک فشرده می‌کنند، نه یک‌جا.Some things compress well and some do not. Foldable clothes free up a lot of room; a ceramic vase none at all. In data, text, sorted keys and columns that repeat one value a thousand times compress well, while random identifiers, photos and anything already encrypted gain almost nothing. The second point is the unit of packing: small bags can be opened one at a time, so you only open the bag you need, which is why data is compressed block by block and not all at once.

و بعدش، فنیAnd now, technically

فشرده‌سازی بی‌اتلاف، داده را طوری کد می‌کند که بازسازی دقیق ممکن باشد؛ فشرده‌سازی باتلاف چیزی را دور می‌ریزد و برای متن و لاگ جایی ندارد. الگوریتم‌ها روی یک طیف‌اند: LZ4 و Snappy ارزان‌اند و نسبت متوسط می‌دهند، zstd و gzip کندترند و بهتر فشرده می‌کنند. در پایگاه داده، فشرده‌سازی معمولاً در سطح بلوک یا صفحه اعمال می‌شود تا پیمایش بازه‌ای و چک‌سام سالم بمانند. در ذخیره‌سازی ستونی، بخشی از فشرده‌سازی اصلاً الگوریتم نیست: کدگذاری دیکشنری، بیت‌مپ و کدگذاری طول-تکرار، همان کار را با ساختار داده انجام می‌دهند. آنچه فشرده می‌شود سه ویژگی دارد: تکرار، ترتیب، و کاردینالیتی کم. تنها چیزی که هیچ‌وقت فشرده نمی‌شود دادهٔ رمزنگاری‌شده است؛ اول فشرده کن، بعد رمزنگاری کن، نه برعکس.Lossless compression encodes data so it can be rebuilt exactly; lossy compression throws information away and has no place in logs or text. Algorithms sit on a spectrum: LZ4 and Snappy are cheap and give moderate ratios, zstd and gzip are slower and compress better. In a database, compression is usually applied per block or page so that range scans and checksums stay intact. In columnar storage part of the compression is not an algorithm at all: dictionary, bitmap and run-length encodings do the same job with a data structure. What compresses shares three traits: repetition, order, and low cardinality. The one thing that never compresses is encrypted data, so compress first and encrypt second, never the reverse.

≈ 2–4×نسبت معمول برای متن و لاگ‌های تکراریa typical ratio for text and repetitive logs
4–128 KBاندازهٔ معمول بلوکی که یک واحد فشرده می‌شودa typical block size for one compressed unit
≈ 1×دادهٔ رمزنگاری‌شده یا از قبل فشرده؛ سودی نداردencrypted or already compressed data gains almost nothing

تلهٔ رایجThe usual trap

فشرده کردن داده‌ای که از قبل رمزنگاری شده و تعجب از این‌که چیزی کوچک نشد، یا گذاشتن بالاترین سطح فشرده‌سازی روی مسیر داغ و کشف این‌که حالا پردازنده گلوگاه است. سطح را با نوع داده و بودجهٔ CPU انتخاب کن، نه با عددی که در بنچمارک سایت سازنده دیده‌ای.Compressing data that is already encrypted and wondering why it did not shrink, or putting the highest compression level on the hot path and discovering the processor is now the bottleneck. Pick the level from your data and your CPU budget, not from a number on a vendor's benchmark page.

crash recovery

بازیابی پس از خرابی فصل ۴Chapter 4 · دیدن در متنsee in context همچنینalso in فصل ۹ch 9

بعد از قطعی برق، کار از کجا شروع می‌شود؟After the power dies, where does the work resume?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

داشتی یک پیام بلند می‌نوشتی و گوشی خاموش شد. تا شارژ وصل نشده کاری نمی‌کنی؛ اول نگاه می‌کنی چه چیزی از متن مانده، بعد ادامه می‌دهی. بازیابی پس از خرابی هم همین نگاه اول است: بفهم چه کاری تمام شده و چه کاری نصفه مانده، بعد راه بیفت.You were typing a long message when the phone died. Until it charges you do nothing else; first you look at how much of the text survived, then you carry on. Crash recovery is that first look: work out what finished and what stopped halfway, then move.

تشبیه و تصویر ذهنیThe analogy

قاعدهٔ فروشگاه این است که هیچ فروش نیمه‌کاره‌ای دیده نشود: اگر رسید چاپ شده، فروش هست؛ اگر نه، نیست. صبح روز بعد صندوق‌دار دفتر سفارش را باز می‌کند و دو کار می‌کند. هر خطی که در دفتر هست ولی در حساب نیامده را دوباره ثبت می‌کند، و هر خطی که وسط کار رها شده و تأیید نشده را دور می‌ریزد. بعد باید مطمئن شود که تکرار یک خط، جمع را دو برابر نمی‌کند؛ وگرنه بازپخش، خودش یک خرابی تازه می‌سازد.The shop's rule is that no half-finished sale is ever visible: if the receipt printed, the sale exists; if not, it does not. The next morning the cashier opens the order book and does two things. Every line in the book that never reached the ledger is applied again, and every line left unconfirmed is dropped. Then the cashier has to be sure that replaying a line does not double the total, or the recovery itself becomes a fresh corruption.

خرابیCrashوسط نوشتنmid-writeچک‌پوینت آخرLast checkpointنقطهٔ شروعwhere replay startsبازپخشReplayredo و undoredo and undoسرویسServingحالا قبول می‌کندaccepting again
از آخرین نقطهٔ سالم جلو می‌رویم: کارهای تأییدشده تکرار و کارهای نصفه دور ریخته می‌شوند.Start at the last good point: acknowledged work is redone, unfinished work is discarded.

و بعدش، فنیAnd now, technically

هنگام بالا آمدن، موتور اول آخرین چک‌پوینت سالم را پیدا می‌کند و از آنجا WAL را جلو می‌برد: کارهای تأییدشده دوباره اعمال (redo) و کارهای تأییدنشده برگردانده (undo) می‌شوند. سپس ساختارهای حافظه ساخته می‌شوند: memtable از لاگ پر می‌شود، بافر خالی است و صفحه‌های نیمه‌کاره با چک‌سام یا doublewrite شناسایی و از نسخهٔ سالم بازسازی می‌شوند. کلید درستی، idempotent بودن بازپخش است؛ هر رکورد با LSN خودش همراه است تا اعمال دوباره، نتیجه را عوض نکند. زمان بازیابی با مقدار لاگِ پس از چک‌پوینت متناسب است، پس چک‌پوینت هم بخشی از طراحی بازیابی است، نه یک کار نگهداری. دو خرابی رایج: خرابیِ وسط خودِ بازیابی، که باید از نو قابل اجرا باشد؛ و خرابیِ انتهای لاگ، که فقط تا آخرین رکورد سالم بریده می‌شود.On startup the engine finds the last intact checkpoint and replays the WAL from there: acknowledged work is reapplied (redo) and unacknowledged work is rolled back (undo). Then the in-memory structures are rebuilt: the memtable is refilled from the log, the buffer pool is empty, and half-written pages are found by checksum or doublewrite and restored from a good copy. The key property is idempotent replay; every record carries its LSN so applying it twice cannot change the result. Recovery time is proportional to the log written since the last checkpoint, which makes checkpointing part of the recovery design rather than housekeeping. Two classic failures: a crash during recovery itself, which must simply be restartable, and a corrupt log tail, which is truncated at the last good record.

checkpointنقطهٔ شروعی که زمان بازیابی را کوتاه می‌کندthe starting point that bounds recovery time
redo + undoتکرار کارهای تأییدشده و برگرداندن بقیهredo what was acknowledged, undo the rest
LSNهمراه هر رکورد، تا اعمال دوباره بی‌اثر باشدon each record, so repeat application is harmless

تلهٔ رایجThe usual trap

هیچ‌وقت امتحان نکردن بازیابی. تیم‌ها failover را تمرین می‌کنند و آن را بازیابی حساب می‌کنند، در حالی که failover یعنی نسخهٔ دیگری جواب بدهد، نه این‌که همین نسخه با لاگ سالم بالا بیاید. یک بار در محیط تست، وسط نوشتن، پروسه را بکش و ببین چقدر طول می‌کشد و آیا دادهٔ تأییدشده سر جایش است.Never testing recovery. Teams rehearse failover and count it as recovery, when failover only means another replica answers — not that this one restarts cleanly from its log. Once in a test environment, kill the process mid-write and see how long it takes and whether the acknowledged data is still there.

اگر همین حالا برق برود، چه چیزی می‌ماند؟If the power died right now, what would survive?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

شام مانده را اول در بشقاب می‌گذاری؛ اگر مهمان رسید، همین کافی است. برای فردا می‌گذاری در یخچال. برای هفتهٔ بعد در فریزر. هر پله کندتر و گران‌تر است، ولی غذا بیشتر می‌ماند. دوام داده هم همین پله‌ها را دارد: هر پله از یک جور خرابی جان سالم به در می‌برد و پلهٔ بالاتر بیشتر.Leftover dinner goes on a plate first; if a guest turns up, that is enough. For tomorrow it goes in the fridge. For next week, the freezer. Each step is slower and costlier, and the food keeps longer. Data durability has the same steps: each one survives a different kind of failure, and the higher step survives more.

تشبیه و تصویر ذهنیThe analogy

بشقاب روی میز از یک کرش برنامه جان سالم به در نمی‌برد. یخچال از کرش جان سالم به در می‌برد، ولی از قطعی برق نه. فریزر از قطعی برق هم جان سالم به در می‌برد، تا وقتی خودش خراب نشود. اگر غذای مهم را در فریزر خانهٔ همسایه هم بگذاری، از آتش‌سوزی این خانه هم در امان است؛ این همان نسخهٔ دوم روی ماشین دیگر است. هر پله یک هزینه دارد: جا، وقت، و کار بیشتری که باید هماهنگ بماند. سؤال درست این نیست که «دوام دارد یا نه»، این است که «در برابر کدام خرابی، با چه تأخیری، و با چه هزینه‌ای».The plate on the table survives no process crash. The fridge survives a crash but not a power cut. The freezer survives the power cut until it breaks itself. Put the important meal in the neighbour's freezer and it also survives a fire in this house; that is the second copy on another machine. Every step costs something: space, time, and more coordination to keep straight. The right question is not whether it is durable but against which failure, with what delay, at what price.

حافظهٔ برنامه · با کرش می‌رودprocess memory · lost on a crashکش سیستم‌عامل · با برق می‌رودpage cache · lost on power lossکش دیسک · تا وقتی باتری داردdisk cache · while the battery lastsرسانه · تا خرابی دیسکthe medium · until the disk diesنسخهٔ دوم · تا خرابی سایتsecond copy · until the site dies
هر پله از یک خرابی بزرگ‌تر جان سالم به در می‌برد و هر پله کندتر و گران‌تر است.Each step survives a bigger failure, and each step is slower and more expensive.

و بعدش، فنیAnd now, technically

دوام یعنی پس از قطع برق، کرش فرایند یا خرابی دیسک، داده‌ای که به مشتری «ثبت شد» گفت‌ه‌ای هنوز باشد. زنجیره‌ای از لایه‌ها وجود دارد: حافظهٔ فرایند، کش صفحهٔ سیستم‌عامل، کش خود دیسک، و رسانه. write فقط داده را به کش صفحه می‌برد و fsync است که آن را به رسانه می‌رساند. کش دیسک اگر باتری‌دار باشد تا حدی دوام می‌دهد، ولی روی SSDهای مصرفی گاهی تأیید می‌کند بدون اینکه واقعاً نوشته باشد. replication یک لایهٔ دیگر اضافه می‌کند: نسخهٔ دوم روی ماشین دیگر، از خرابی دیسک و گاهی از خرابی کل مرکز محافظت می‌کند، ولی نسخهٔ async ممکن است چند ثانیهٔ آخر را نداشته باشد. RPO می‌گوید چند ثانیه داده را می‌شود از دست داد و RTO می‌گوید برگشتن چقدر طول می‌کشد. این دو با هم معنی دوام را می‌سازند؛ هیچ‌کدام تنها کافی نیست.Durability means that after a power cut, a process crash or a disk failure, the data you told the customer was recorded is still there. There is a chain of layers: process memory, the operating system's page cache, the disk's own cache, and the medium. write only reaches the page cache; fsync is what pushes it to the medium. A battery-backed disk cache helps for a while, but consumer SSDs sometimes acknowledge writes they never made. Replication adds another layer: a second copy on another machine protects against disk failure and sometimes a whole data centre, though an asynchronous copy may be missing the last few seconds. RPO says how much data you may lose, RTO says how long recovery takes, and together they define what durable actually means here.

fsyncمرز واقعی دوام روی یک ماشینthe real durability boundary on one machine
RPO = 0یعنی هیچ کامیت تأییدشده‌ای در خرابی گم نمی‌شودno acknowledged commit is lost in a failure
2+ copiesنسخهٔ دوم، وقتی خرابی از یک دیسک بزرگ‌تر می‌شودa second copy, once failure outgrows one disk

دوام با پشتیبان‌گیری فرق داردDurability is not backup

پشتیبان برای برگشتن از خطای انسانی است؛ دوام برای جان سالم بردن از خرابی سخت‌افزار. اگر کسی جدولی را اشتباهی پاک کند، دوام هیچ کاری نمی‌کند: حذف هم دقیقاً و با دوام ثبت شده است. اگر دیسک بسوزد، پشتیبان نجات می‌دهد، ولی از آخرین نسخهٔ پشتیبان به بعد از دست رفته است. سیستم جدی به هر دو نیاز دارد، چون هر کدام یک جور خرابی را پوشش می‌دهند و هیچ‌کدام جای دیگری را نمی‌گیرد. اشتباه رایج این است که replication را پشتیبان حساب کنیم؛ حذف اشتباهی با همان سرعت به نسخهٔ دوم هم می‌رسد.Backup is for recovering from human error; durability is for surviving hardware failure. If someone drops a table by mistake, durability does nothing: the delete was recorded durably too. If a disk burns, the backup saves you, but everything since the last backup is gone. A serious system needs both, because each covers a different failure and neither replaces the other. The common mistake is counting replication as backup: a mistaken delete propagates to the second copy just as fast.

قیمت هر پلهThe price of each step

پلهٔ اول تقریباً مجانی است و پلهٔ آخر گران. fsync روی هر نوشتن، توان را می‌خورد؛ به همین دلیل خیلی از سیستم‌ها پیش‌فرض آن را کم می‌کنند و بعد در گزارش حادثه می‌فهمند که چند صد تراکنش آخر نبوده‌اند. نسخهٔ دوم همزمان، تأخیر نوشتن را به کندترین نسخه گره می‌زند. نسخهٔ async تأخیر را کم می‌کند و در عوض پنجرهٔ گم شدن داده باز می‌کند. هیچ‌کدام «بهترین» نیست؛ انتخاب درست از جواب این سؤال می‌آید که اگر همین حالا خرابی بیاید، چند ثانیه از دست رفتن قابل قبول است و مشتری چه چیزی را باور کرده است.The first step is nearly free and the last is expensive. fsync on every write eats throughput, which is why many systems weaken it by default and later learn from an incident report that the last few hundred transactions were missing. A synchronous second copy ties write latency to the slowest replica. An asynchronous copy lowers latency and opens a window of loss. None of them is best; the right choice comes from answering how many seconds of loss are acceptable right now, and what exactly the customer was told.

تلهٔ رایجThe usual trap

حساب کردن replication به‌عنوان دوام، وقتی نسخهٔ دوم async است. رهبر کامیت را تأیید می‌کند، نسخهٔ دوم هنوز نرسیده، رهبر می‌میرد و آن چند ثانیهٔ آخر با او می‌رود؛ مشتری رسید دارد، سیستم ندارد. اگر RPO صفر می‌خواهی، باید نوشتن تا تأیید نسخهٔ همزمان صبر کند و بهای تأخیرش را هم بپردازی.Counting replication as durability when the second copy is asynchronous. The leader acknowledges, the replica has not caught up, the leader dies, and those last seconds die with it: the customer holds a receipt for data the system does not have. If you want an RPO of zero, the write has to wait for the synchronous replica, and you have to pay its latency.

fsync

همگام‌سازی با دیسک فصل ۴Chapter 4 · دیدن در متنsee in context

«نوشتم» یعنی کجا نوشتم؟Written where, exactly?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

چند صفحه در واژه‌پرداز تایپ کرده‌ای. تا وقتی ذخیره نزدی، متن روی نمایشگر است و به نظر می‌رسد وجود دارد؛ ولی اگر برق برود، از آخرین ذخیره به بعد نیست. زدن ذخیره همان لحظه‌ای است که متن از «توی دست» به «روی کاغذ» می‌رود. fsync هم دقیقاً همان دکمه است، برای یک فایل یا یک تراکنش.You have typed a few pages in a word processor. Until you hit save, the text is on the screen and seems to exist; but if the power dies, everything since the last save is gone. Hitting save is the moment the text moves from your hands onto paper. fsync is that button, for a file or a transaction.

تشبیه و تصویر ذهنیThe analogy

کارمند دفتری را تصور کن که هر برگه را اول در سبد «بعداً بایگانی می‌کنم» می‌گذارد. کارش سریع است و به تو می‌گوید «رسید». اگر همان شب ساختمان بسوزد، سبد هم می‌سوزد. fsync یعنی بگویی «همین حالا بایگانی کن و وقتی قفسه نشست، به من خبر بده». حالا او باید بلند شود، برود، برگه را در قفسه بگذارد و برگردد؛ همین چند ثانیه، تفاوت بین یک میلی‌ثانیه و چند میلی‌ثانیه در هر نوشتن است. اگر هزار نامه در دقیقه داری، فرستادن کارمند برای هر نامه فاجعه است؛ به همین دلیل سیستم‌ها چند نامه را با هم می‌فرستند.Imagine a clerk who first drops every sheet into a tray marked file this later. He is fast and tells you it is done. If the building burns that night, the tray burns too. fsync means telling him to file it right now and come back when the drawer is shut. Now he has to stand up, walk over, file the sheet and return; those seconds are the difference between one millisecond and several per write. With a thousand letters a minute, sending the clerk for each one is a disaster, which is why systems send several at once.

فراخوانی نوشتنwrite() returnsفقط در حافظهmemory onlyصفحهٔ کثیفa dirty pageدر صف دیسکqueued for diskfsyncfsyncمنتظر تأییدwaits for the deviceرسانهthe mediumحالا پایدارdurable at last
نوشتن فوراً برمی‌گردد؛ فقط fsync است که تا نشستن داده روی رسانه صبر می‌کند.The write returns immediately; only fsync waits until the data sits on the medium.

و بعدش، فنیAnd now, technically

write داده را در کش صفحهٔ سیستم‌عامل می‌نشاند و فوراً برمی‌گردد؛ داده «کثیف» است، نه پایدار. fsync آن صفحه‌ها را به دستگاه می‌فرستد، فرمان flush می‌دهد، و تا تأیید رسیدن به رسانه صبر می‌کند. fdatasync همین کار را برای داده می‌کند و از فراداده‌های غیرضروری صرف‌نظر می‌کند. روی SSD یک fsync معمولاً چند دهم میلی‌ثانیه است و روی دیسک چرخان چند میلی‌ثانیه؛ گران‌ترین بخش هر کامیت همین است. برای دوام یک نام فایل تازه، باید دایرکتوری را هم fsync کرد، وگرنه ممکن است فایل پس از خرابی نباشد. fsync خطا هم برمی‌گرداند و اینجا دام بزرگ است: بعضی هسته‌ها پس از خطای دیسک، نوشتن‌های بعدی را دور می‌ریزند و fsync بعدی موفق گزارش می‌شود. پس خطای fsync را نمی‌شود با تلاش دوباره نادیده گرفت.write places the data in the operating system's page cache and returns at once; the data is dirty, not durable. fsync sends those pages to the device, issues a flush, and waits for the medium to confirm. fdatasync does the same for the data and skips metadata you do not need. On an SSD an fsync is usually a few tenths of a millisecond, on a spinning disk a few milliseconds, and it is the most expensive part of a commit. Making a new file name durable also needs an fsync on the directory, or the file may be missing after a crash. fsync returns errors too, and that is the big trap: some kernels discard later writes after a disk error and the next fsync reports success. An fsync error cannot be waved away by retrying.

≈ 0.1–0.5 msهزینهٔ معمول یک fsync روی SSDa typical fsync on an SSD
≈ 5–10 msهمان کار روی یک دیسک چرخانthe same on a spinning disk
1 fsyncبرای هر کامیت، مگر اینکه گروهی شوندper commit, unless commits are grouped

چرا این‌قدر گران استWhy it costs so much

هزینه نه از نوشتن چند بایت می‌آید، از انتظار. دستگاه باید محتوای کش خودش را روی رسانه بنشاند و تا تمام شدن آن کار خبری نمی‌دهد. یک دیسک چرخان برای این کار باید سرش را جابه‌جا کند و صبر کند تا بخش درست زیر هد بیاید؛ یک SSD باید صفحه را برنامه‌ریزی و پاک کند. اگر برای هر تراکنش یک fsync بزنی، تأخیر دیسک مستقیماً به تأخیر تراکنش تبدیل می‌شود و سقف توان هم به همان تعداد در ثانیه می‌رسد. برای همین است که batch کردن، کامیت گروهی و کش باتری‌دار این‌قدر مهم‌اند: همه برای کم کردن تعداد fsync در هر ثانیه‌اند، نه برای کم کردن تعداد نوشتن.The cost is not the few bytes, it is the waiting. The device has to put its cache on the medium and reports back only when that is done. A spinning disk has to move its head and wait for the right sector; an SSD has to program and erase a page. fsync per transaction turns disk latency straight into transaction latency and caps throughput at the device's flush rate. That is why batching, group commit and battery-backed caches matter so much: they reduce fsyncs per second, not writes per second.

fsync که خطا می‌دهدWhen fsync fails

این بخش را جدی بگیر، چون در تست‌ها دیده نمی‌شود. اگر fsync برای یک فایل خطا برگرداند، بعضی هسته‌ها صفحه‌های کثیف را دور می‌ریزند و نوشتن بعدی روی همان فایل موفق گزارش می‌شود؛ یعنی برنامه فکر می‌کند داده‌اش پایدار است، در حالی که نیست. رفتار درست این است که خطا را به بالاتر منتقل کنی، آن فایل یا آن تراکنش را شکست‌خورده اعلام کنی، و اگر داده‌ای از دست رفته، از نسخهٔ سالم بازسازی کنی. نادیده گرفتن خطا و تلاش دوباره، بدترین گزینه است.Take this part seriously, because tests never show it. When fsync fails on a file, some kernels drop the dirty pages and the next write to that same file reports success, so the application believes the data is durable when it is not. The correct move is to propagate the error, mark that file or transaction as failed, and rebuild from a good copy if data was lost. Ignoring the error and retrying is the worst option.

تلهٔ رایجThe usual trap

تأیید تراکنش پیش از fsync، یا fsync زدن برای هر نوشتن در باری که هزار تراکنش در ثانیه دارد. اولی داده را در برق‌رفت می‌بَرد، دومی توان را به کف می‌رساند. اگر بین این دو گیر کرده‌ای، جواب معمولاً کامیت گروهی است نه حذف fsync.Acknowledging before fsync, or calling fsync per write under a thousand transactions a second. The first loses data in a power cut, the second flattens throughput. If you are stuck between them, the answer is usually group commit, not removing fsync.

group commit

کامیت گروهی فصل ۴Chapter 4 · دیدن در متنsee in context همچنینalso in فصل ۸ch 8

چرا هر تراکنش باید جداگانه صبر کند؟Why should every commit wait on its own?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

در ساختمان اداری، آسانسور هر نیم دقیقه یک بار می‌آید و هر بار ده نفر سوار می‌شوند. اگر برای هر نفر جدا بیاید، تعداد سفرها آن‌قدر زیاد می‌شود که هیچ‌کس به موقع نمی‌رسد. همان یک بار آمدن، هزینه را بین همه تقسیم می‌کند. کامیت گروهی هم چند تراکنش را در یک fsync سوار می‌کند.In an office building the lift comes every half minute and carries ten people. If it came separately for each person, there would be so many trips that nobody arrives on time. That one trip shares the cost across everyone. Group commit puts several transactions on one fsync.

تشبیه و تصویر ذهنیThe analogy

صف نانوایی را ببین: نانوا هر بار که تنور را باز می‌کند، ده نان بیرون می‌آورد. اگر برای هر نان تنور را باز و بسته کند، همه کندتر می‌شوند و گرمای تنور هم هدر می‌رود. صف کمی طولانی‌تر می‌شود، ولی کار تنور یک بار انجام شده. کامیت گروهی هم یک پنجرهٔ کوتاه جمع می‌کند: هر تراکنش کمی بیشتر صبر می‌کند و در عوض یک fsync به‌جای صد fsync انجام می‌شود. اگر پنجره یک میلی‌ثانیه باشد، کسی متوجه نمی‌شود؛ اگر صد میلی‌ثانیه باشد، همه متوجه می‌شوند.Watch a bakery queue: each time the baker opens the oven he pulls out ten loaves. Open and close it for every single loaf and everyone waits longer while the oven's heat leaks away. The queue grows a little and the oven works once. Group commit closes a short window: each transaction waits slightly longer and one fsync covers a hundred. With a one-millisecond window nobody notices; with a hundred, everybody does.

رسیدن کامیتcommit arrivesدر صف می‌ایستدjoins the queueبستن دستهbatch closesپنجرهٔ کوتاهa short windowیک fsyncone fsyncبرای همهfor all of themتأیید همهall ackedبا همtogether
چند کامیت در یک پنجره جمع می‌شوند و یک fsync دوام همه را با هم می‌آورد.Several commits gather in one window, and one fsync makes them all durable together.

و بعدش، فنیAnd now, technically

در کامیت گروهی، رهبر نوشتن‌ها را از چند کلاینت در یک صف جمع می‌کند و همهٔ رکوردهای WAL را پشت سر هم می‌نویسد، بعد یک fsync می‌زند و پس از برگشتن آن، همه را تأیید می‌کند. هر تراکنش همان رکورد خودش را دارد و همان یک fsync دوام همه را پوشش می‌دهد. توان از این راه چند برابر می‌شود، چون هزینهٔ اصلی هر کامیت انتظار دیسک است نه نوشتن چند بایت. بهایش تأخیر اضافه است: هر تراکنش تا بسته شدن پنجره صبر می‌کند. در replication همزمان، گروه باید از همهٔ نسخه‌ها تأیید بگیرد و کندترین نسخه سرعت کل گروه را تعیین می‌کند. اگر fsync شکست بخورد، هیچ‌کدام از تراکنش‌های آن گروه نباید تأیید شوند؛ اینجا خوش‌شانسی نیست، سادگی است.With group commit, the leader collects writes from several clients into a queue, appends all their WAL records in order, calls fsync once, and acknowledges everyone when it returns. Each transaction keeps its own record and that single fsync covers all of them. Throughput multiplies because the expensive part of a commit is waiting for the disk, not writing bytes. The price is added latency: every transaction waits for the window to close. With synchronous replication the batch must be acknowledged by every replica, so the slowest one sets the group's speed. If the fsync fails, none of that group may be acknowledged; that is not luck, it is simplicity.

N → 1تعداد fsync برای N کامیت همزمانfsyncs for N concurrent commits
1 fsyncهزینهٔ گروه، نه هزینهٔ هر تراکنشthe group's cost, not each transaction's
p99جایی که پنجرهٔ بزرگ خودش را نشان می‌دهدwhere an oversized window shows up

تأخیر اضافه از کجا می‌آیدWhere the added latency comes from

هر تراکنش دو انتظار دارد: انتظار برای بسته شدن پنجره، و انتظار برای fsync. اولی را می‌شود با کوچک نگه داشتن پنجره کم کرد؛ دومی هزینهٔ اجتناب‌ناپذیر دیسک است. اگر پنجره را بزرگ کنی، توان بالا می‌رود و p99 بد می‌شود، چون تراکنشی که یک میکروثانیه بعد از بسته شدن دسته رسیده باید کل پنجرهٔ بعدی را صبر کند. تنظیم درست معمولاً پنجره‌ای در حد چند دهم میلی‌ثانیه است: به‌قدری بزرگ که چند کامیت را جمع کند، به‌قدری کوچک که کسی در تأخیر گم نشود.Every transaction waits twice: for the window to close, and for the fsync. The first can be shrunk; the second is the disk's unavoidable cost. A large window raises throughput and ruins p99, because a transaction arriving a microsecond after the batch closed waits for the whole next window. A sane setting is a few tenths of a millisecond: big enough to gather several commits, small enough that nobody is lost in the latency.

یک دیسک کند، کل گروه را می‌خواباندOne slow disk stalls the group

با کامیت گروهی، سرنوشت چند تراکنش به یک fsync گره می‌خورد. اگر آن یک fsync کند باشد، همه با هم کند می‌شوند؛ اگر شکست بخورد، همه با هم شکست می‌خورند. این ویژگی امنیت است، نه باگ: بهتر است هیچ‌کدام تأیید نشوند تا اینکه بعضی تأیید شوند و بعضی نه. اما برای پایش مهم است که بدانی یک دیسک مشکوک می‌تواند p99 کل سیستم را خراب کند، بدون اینکه آن دیسک در نمودار میانگین دیده شود.With group commit, several transactions share one fsync. If that fsync is slow they all slow down; if it fails they all fail. That is safety, not a bug: better that none are acknowledged than some are and some are not. For monitoring it matters that one suspect disk can wreck the whole system's p99 without ever showing up in an average.

تلهٔ رایجThe usual trap

تنظیم پنجره فقط با نگاه به میانگین توان. پنجرهٔ بزرگ میانگین را زیبا می‌کند و p99 را خراب؛ چون هر تراکنش بدشانس، کل پنجره را صبر می‌کند. توان و p99 را با هم ببین و پنجره را از چند دهم میلی‌ثانیه بالاتر نبر، مگر اینکه اندازه‌گیری خلافش را نشان دهد.Tuning the window by looking only at average throughput. A large window flatters the average and wrecks p99, because every unlucky transaction waits a whole window. Watch throughput and p99 together and keep the window at a few tenths of a millisecond unless a measurement says otherwise.

چطور هر کلید همیشه به همان عدد می‌رسد؟How does a key always land on the same number?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

در پارکینگ، بلیت شمارهٔ ۴۷ را به قفسهٔ شمارهٔ ۷ می‌فرستند، چون رقم آخرش ۷ است. هر بار همان بلیت به همان قفسه می‌رود، و کسی لازم نیست یادش بماند کجا گذاشته — فقط قاعده را بلد است.In a car park, ticket 47 is sent to rack seven because its last digit is seven. The same ticket always goes to the same rack, and nobody has to remember where it went — you only know the rule.

تشبیه و تصویر ذهنیThe analogy

کتابخانه‌ای را تصور کن که کتاب‌ها را بر اساس حرف اولشان در قفسه می‌چیند. حرف اول یک قاعده است که همیشه یک جواب می‌دهد، پس پیدا کردن کتاب با دانستن اسمش ممکن است. ولی دو نکتهٔ مهم هم دارد. اول، همهٔ کتاب‌هایی که با «م» شروع می‌شوند در یک قفسه جمع می‌شوند؛ یکنواختی واقعی وجود ندارد. دوم، اگر قفسه پر شود و کتابخانه طبقهٔ تازه بسازد، قاعده عوض می‌شود و بخش بزرگی از کتاب‌ها باید جابه‌جا شوند. هر دو نکته دقیقاً همان مشکلاتی است که هر سیستم هشی هم با آن دست‌وپنجه نرم می‌کند.Picture a library that shelves books by their first letter. The first letter is a rule that always gives the same answer, so a book can be found by knowing its title. But two important things follow. Every book starting with the same letter piles into one shelf; real uniformity does not exist. And if that shelf fills and the library adds a floor, the rule changes and a large share of the books must move. Both issues are exactly what every hash-based system wrestles with.

کلیدKeyمثلاً عدد ۴۷say 47تابع هشHash functionقطعیdeterministicشمارهٔ سبدBucket number۴۷ تقسیم بر ۱۰47 mod 10
کلید وارد تابع هش می‌شود و شمارهٔ سبد بیرون می‌آید؛ همان کلید، همیشه همان سبد.A key goes into the hash function and a bucket number comes out; same key, same bucket.

و بعدش، فنیAnd now, technically

تابع هش هر ورودی را به یک عدد با طول ثابت تبدیل می‌کند و سه خصلت لازم دارد: قطعی باشد (همان ورودی همیشه همان خروجی)، خروجی‌اش یکنواخت پخش شود، و محاسبه‌اش ارزان باشد. برخورد (collision) طبیعی است: دو کلید مختلف می‌توانند به یک سبد برسند، و سیستم باید با زنجیره‌کردن یا جست‌وجوی باز کنارش بیاید. هش در سه جای معماری تکرار می‌شود. در ایندکس هشی، که پیدا کردن سریع است ولی پیمایش بازه‌ای ممکن نیست چون ترتیب از دست رفته. در تقسیم داده، که کلید به سبد، و سبد به shard نگاشت می‌شود. و در پیوند هشی، که دو مجموعه بر اساس کلید پیوند به یک سبد می‌روند تا بتوانند کنار هم تطبیق داده شوند. هش رمزنگاری‌شی چیز دیگری است: برای یکپارچگی و امضا، نه برای تقسیم داده.A hash function maps any input to a fixed-size number and needs three properties: deterministic (same input, same output), evenly distributed output, and cheap to compute. Collisions are normal: two different keys can land in one bucket, and the system must cope with chaining or open addressing. Hashing recurs in three architectural places: a hash index, which is fast for lookups but cannot serve range scans because order is gone; partitioning, where a key maps to a bucket and a bucket to a shard; and hash join, where both sets go to a bucket by join key so they can be matched side by side. A cryptographic hash is a different animal: for integrity and signatures, not for distributing data.

1 bucketهر کلید دقیقاً به یک سبد می‌رسد، اگر تابع ثابت بماندa key lands in exactly one bucket, as long as the function is fixed
N → N+1با mod N، تغییر تعداد سبدها تقریباً همهٔ کلیدها را جابه‌جا می‌کندwith mod N, changing the bucket count moves almost every key

چرا mod N شکننده استWhy mod N is brittle

اگر تعداد سبدها ثابت باشد، mod N یک انتخاب کامل است: ارزان، قطعی، و بدون نیاز به حافظه. مشکل دقیقاً وقتی شروع می‌شود که N عوض شود. با رفتن از N به N+1، تقریباً هر کلید باقی‌ماندهٔ متفاوتی می‌گیرد و مجبور است جابه‌جا شود؛ یعنی یک ماشین اضافه می‌کنی و تقریباً همهٔ داده جابه‌جا می‌شود. راه‌حل‌های عملی دو دسته‌اند: تعداد سبد را ثابت و بزرگ بگیر و در طول رشد فقط سبدها را بین ماشین‌ها جابه‌جا کن، یا از هش سازگار استفاده کن که با تغییر تعداد گره‌ها فقط همان بخش کوچکی که باید، جابه‌جا می‌شود.If the bucket count never changes, mod N is a perfect choice: cheap, deterministic, stateless. The trouble starts exactly when N changes. Going from N to N+1 gives almost every key a different remainder and forces a move; you add one machine and almost all the data moves. Practical answers split two ways: fix a large bucket count and only move buckets between machines as you grow, or use consistent hashing, where changing the node count moves only the small part that must move.

تلهٔ رایجThe usual trap

قاطی کردن هش با رمزنگاری. تابع هش فقط یک قاعدهٔ تقسیم است و هیچ تضمین امنیتی ندارد؛ دو کلید می‌توانند عمداً به یک سبد بیایند. اگر امنیت یا یکپارچگی می‌خواهی، همان تابع کافی نیست و به هش رمزنگاری‌شی و مقایسهٔ محتوا نیاز داری.Confusing a hash with cryptography. A hash function is just a distribution rule with no security guarantee; two keys can deliberately collide. If you need security or integrity, the plain function is not enough and you need a cryptographic hash plus a content comparison.

اگر فقط تساوی می‌خواهی، چرا درخت؟If you only need equality, why a tree?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

در مهمانی کتت را به مسئول رخت‌کن می‌دهی و یک شماره می‌گیری. آخر شب شماره را می‌دهی و او مستقیم می‌رود سر همان چوب‌لباسی؛ قفسه را نمی‌گردد. ایندکس هشی هم همین شماره را از خود کلید می‌سازد، پس لازم نیست دنبال چیزی بگردد، فقط حساب می‌کند.At a party you hand your coat to the attendant and get a numbered tag. At the end of the night you give back the number and he walks straight to that hook; he does not search the rail. A hash index builds that number from the key itself, so it does not search either — it computes.

تشبیه و تصویر ذهنیThe analogy

شماره از خود کت ساخته می‌شود، نه از ترتیب آمدن. پس همان کت همیشه به همان قلاب می‌رسد و هیچ فهرستی لازم نیست. ولی این شماره‌ها ترتیب ندارند: کت‌های ۴۱ و ۴۲ هیچ ربطی به هم ندارند، فقط تصادفاً کنار هم افتاده‌اند. اگر کسی بپرسد «کت‌های بین چهل تا پنجاه را بیاور»، هیچ راهی نیست جز نگاه کردن به همه. مشکل دوم وقتی پیش می‌آید که دو کت شمارهٔ یکسان بگیرند؛ آن‌وقت باید هر دو را بیاوری و مقایسه کنی. و اگر جمعیت سالن دو برابر شود، قفسه‌های جدید لازم است و شماره‌های قبلی دیگر معنا ندارند.The number comes from the coat itself, not from arrival order, so the same coat always reaches the same hook and no list is needed. But those numbers carry no order: coats 41 and 42 have nothing to do with each other, they just landed side by side. If someone asks for the coats between forty and fifty, there is no route but looking at every one. The second problem is two coats getting the same number; then you must fetch both and compare. And if the party doubles, new racks are needed and the old numbers stop meaning anything.

و بعدش، فنیAnd now, technically

ایندکس هشی یک آرایه از سبدهاست: با hash(key) به یک سبد می‌رسی و سبد فهرست محل رکوردها را دارد. جست‌وجوی تساوی یک محاسبه و یک خواندن است، بدون پیمایش درخت. برخورد را با زنجیره حل می‌کنند: چند کلید در یک سبد می‌نشینند و درون سبد مقایسه می‌شوند. تعداد سبدها ثابت نمی‌ماند؛ با رشد داده باید سبدها زیاد شوند و کلیدها دوباره پخش شوند، یا از hashing قابل توسعه استفاده شود که یکی‌یکی سبد می‌افزاید. در موتورهای کلید-مقدار ساده، تمام ایندکس در حافظه است و مقدارها در یک لاگ فقط-افزودنی روی دیسک. چیزی که گران تمام می‌شود ترتیب است: هش ترتیب کلید را نابود می‌کند، پس پیمایش بازه‌ای و مرتب‌سازی روی آن معنا ندارد و به اسکن کامل تبدیل می‌شود.A hash index is an array of buckets: hash(key) takes you to one bucket, and the bucket lists where the records are. An equality lookup is one computation and one read, with no tree walk. Collisions are handled by chaining: several keys share a bucket and are compared inside it. The bucket count cannot stay fixed; as data grows the array must grow and every key must be redistributed, or you use extendible hashing that adds buckets one at a time. In simple key-value engines the whole index sits in memory and the values sit in an append-only log on disk. The expensive part is ordering: hashing destroys it, so range scans and ORDER BY become a full scan.

O(1)جست‌وجوی تساوی، به‌طور میانگینan equality lookup, on average
hash % nنقشهٔ کلید به سبد؛ n تعداد سبدهاkey to bucket; n is the bucket count
O(n)هر پرس‌وجوی بازه‌ای: اسکن کاملany range query: a full scan

تلهٔ رایجThe usual trap

گذاشتن ایندکس هشی روی ستونی که بعداً با بازه خوانده می‌شود، مثل زمان. در توسعه همه‌چیز سریع است، چون فقط تساوی می‌زنید؛ بعد کوئری «سفارش‌های ۲۴ ساعت گذشته» می‌رسد و یک اسکن کامل می‌شود، بی‌آنکه کسی تصمیمی گرفته باشد.Putting a hash index on a column you later read by range, such as a timestamp. Everything is fast in development because you only test equality; then a query for the last twenty-four hours of orders arrives and becomes a full scan, and nobody ever decided that.

in-memory database

پایگاه دادهٔ درون‌حافظه‌ای فصل ۴Chapter 4 · دیدن در متنsee in context

اگر همه‌چیز در حافظه باشد، دیسک چه کاره است؟If everything is in memory, what is the disk for?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

آشپز سفارش‌های امروز را روی پیشخوان می‌گذارد، نه در انبار. دستش تند است، چون هر لحظه لازمشان دارد و همه جلوی چشمش است. ولی اگر پیشخوان جمع شود، آن سفارش‌ها دیگر نیستند؛ پیشخوان جای نگه‌داشتن دائمی نیست.A cook keeps today's orders on the counter, not in the storeroom. Her hands are quick because she needs them any second and they are all in sight. But if the counter is cleared, those orders are gone; the counter was never meant for keeping things.

تشبیه و تصویر ذهنیThe analogy

فرق پیشخوان و انبار فقط سرعت نیست، جنس کار است. پیشخوان گران است و کوچک، ولی در دسترس؛ انبار ارزان است و بزرگ، ولی هر بار باید راه بروی. برای همین چیزهایی که مدام لازم می‌شوند روی پیشخوان‌اند و بقیه در انبار. در پایگاه دادهٔ درون‌حافظه‌ای هم همین تصمیم گرفته شده: همه‌چیز روی پیشخوان است، پس باید دو چیز را از بیرون اضافه کنی. یکی سقف: پیشخوان بزرگ‌تر از حافظه نمی‌شود. دیگری دوام: اگر پیشخوان را قاب نگیری، یک ری‌استارت همه‌چیز را پاک می‌کند.The difference between counter and storeroom is not only speed, it is what the space is for. The counter is expensive and small but within reach; the storeroom is cheap and vast but costs a walk. So the things needed constantly sit on the counter and the rest go to storage. An in-memory database has already made that choice: everything is on the counter, which means two things must be added from outside. One is a ceiling, since the counter cannot grow past memory. The other is durability, because without a frame around the counter a restart wipes it.

و بعدش، فنیAnd now, technically

در پایگاه دادهٔ درون‌حافظه‌ای، نسخهٔ اصلی داده در حافظه است و دیسک برای دوام نگه داشته می‌شود، نه برای خواندن. دسترسی به حافظه در حد صد نانوثانیه است، در حالی که یک خواندن تصادفی از SSD ده‌ها میکروثانیه هزینه دارد. دوام دو راه دارد: snapshot دوره‌ای از کل داده، که با fork و copy-on-write گرفته می‌شود، یا یک لاگ دستورها که هر تغییر را می‌نویسد و هنگام راه‌اندازی بازپخش می‌شود. هر دو هزینه دارند: snapshot بزرگ ممکن است حافظه را لحظه‌ای نزدیک دو برابر کند، و فاصلهٔ بین دو snapshot همان مقدار داده‌ای است که یک خرابی می‌تواند ببرد. چون همه‌چیز در حافظه است، کنترل همزمانی ساده‌تر می‌شود و بعضی موتورها کل کار را در یک رشته انجام می‌دهند. محدودیت واقعی حافظه است: اگر داده از آن بگذرد، یا باید بخشی حذف شود یا سر از دیسک دربیاورد، و آن‌وقت دیگر این نام را ندارد.In an in-memory database the authoritative copy lives in memory and the disk exists for durability, not for reads. Memory access is around a hundred nanoseconds, while one random read from an SSD costs tens of microseconds. Durability takes two forms: a periodic snapshot of the whole data set, taken with fork and copy-on-write, or a command log that records every change and is replayed at startup. Both cost something: a large snapshot may briefly double memory use, and the gap between snapshots is exactly how much data a crash can take. Because everything is in memory, concurrency control gets simpler, and some engines run the whole thing on one thread. The real limit is memory: if the data outgrows it, part of it must be evicted or spill to disk, and then the name no longer fits.

≈ 100 nsدسترسی به حافظه؛ حدوداً صد برابر سریع‌تر از SSDmemory access, roughly a hundred times faster than an SSD
1 copyنسخهٔ اصلی در حافظه؛ دیسک فقط برای دوامone authoritative copy in memory; the disk only for durability
≈ 2×حافظهٔ لحظه‌ای هنگام snapshot با fork و COWtransient memory during a fork-and-COW snapshot

تلهٔ رایجThe usual trap

راه انداختنش بدون دوام و پنداشتن این‌که replication جای آن را می‌گیرد. نسخهٔ دوم فقط وقتی کمک می‌کند که خودش هم زنده بماند؛ دو نود که هم‌زمان ری‌استارت می‌شوند، دو حافظهٔ خالی‌اند. دوام را صریح تنظیم کن و یک بار بازیابی از snapshot و لاگ را واقعاً امتحان کن.Running it with durability off and assuming replication covers you. A second copy only helps if it stays alive; two nodes restarting together are two empty memories. Configure durability explicitly and actually rehearse one restore from snapshot plus log.

چرا جست‌وجوی سریع، نوشتن را کند می‌کند؟Why does a fast lookup slow the write down?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دنبال مبحثی در یک کتاب فنی می‌گردی. آخر کتاب یک فهرست الفبایی هست: «فشرده‌سازی — ص ۱۴۲». مستقیم به همان صفحه می‌روی. آن فهرست چند صفحه اضافه دارد و وقتی کتاب بازنویسی می‌شود باید دوباره ساخته شود، ولی بدون آن باید صدها صفحه را ورق می‌زدی. ایندکس هم همان فهرست است، برای یک جدول.You are hunting a topic in a technical book. At the back there is an alphabetical index: compression, page 142. You go straight to that page. The index costs a few extra pages and has to be redone when the book is reissued, but without it you would be flipping through hundreds of pages. An index is that list, for a table.

تشبیه و تصویر ذهنیThe analogy

فهرست انتهای کتاب یک نکتهٔ ظریف دارد: فقط برای سؤال‌هایی جواب می‌دهد که با کلید فهرست جور باشند. فهرست الفبایی به «صفحهٔ ۱۴۲ چیست» جواب می‌دهد، ولی به «کدام صفحه‌ها دربارهٔ فلان نمودارند» نه. اگر دو فهرست بسازی، کتاب دو برابر کار دارد و هر ویرایش باید هر دو را به‌روز کند. اگر فهرست را برای کلمه‌ای بسازی که در همهٔ صفحه‌ها آمده، فهرست بی‌فایده است. و اگر کتاب را عوض کنی و فهرست را نه، بدتر از نداشتن فهرست است: آدم را مطمئن می‌فرستد جای اشتباه.A book index has a subtle rule: it only answers questions shaped like its key. An alphabetical index answers what is on page 142, not which pages discuss that one diagram. Build two indexes and the book costs twice the work, and every revision has to update both. Build an index for a word that appears on every page and it is useless. Change the book but not the index and it is worse than no index: it sends you somewhere wrong with confidence.

درج ردیفinsert the rowجدول اصلیthe heapکلید در ایندکسkey into the indexB-tree یا LSMB-tree or LSMجست‌وجو با کلیدlookup by keyچند پرشa few hopsپریدن به ردیفfetch the rowخواندن نهاییthe last read
مسیر یک جست‌وجوی ایندکسی: از کلید تا صفحه، و بعد یک پرش به خود ردیف.The path of an indexed lookup: key to page, then one hop to the row itself.

و بعدش، فنیAnd now, technically

ایندکس یک ساختار مشتق‌شده است که از کلید جست‌وجو به محل رکورد می‌رسد؛ درخت B یا درخت LSM هر دو همین نقش را با هزینه‌های متفاوت بازی می‌کنند. ایندکس اصلی ترتیب فیزیکی رکوردها را تعیین می‌کند و ایندکس ثانویه یک ساختار جداگانه است که می‌تواند چند تا باشد. چون ایندکس مشتق‌شده است، هر درج و حذف و به‌روزرسانی باید آن را هم تغییر دهد؛ پس هر ایندکس یک نوشتن اضافه و کمی فضاست. کوئری‌پلنر با آمار انتخاب می‌کند که از ایندکس استفاده کند یا کل جدول را بخواند؛ برای ستونی که تقریباً همهٔ ردیف‌ها یک مقدار دارند، اسکن کامل ارزان‌تر است. ایندکس پوشا ستون‌های لازم را در خودش دارد و خواندن ردیف اصلی را حذف می‌کند. ایندکس‌های بلااستفاده فقط نوشتن را کند می‌کنند و فضای دیسک را می‌خورند.An index is a derived structure that maps a search key to a record's location; a B-tree or an LSM tree both play that role at different costs. The primary index defines the physical order of records, and secondary indexes are separate structures, of which you may have several. Because the index is derived, every insert, delete and update must change it too, so each index adds a write and some space. The query planner uses statistics to choose between the index and a full scan; for a column where almost every row holds the same value, scanning is cheaper. A covering index carries the needed columns itself and skips the heap fetch. Unused indexes only slow writes down and eat disk.

+1 writeهر ایندکس، یک نوشتن اضافه در هر درجeach index adds one write per insert
O(log n)هزینهٔ رسیدن به یک کلید در درخت متوازنthe cost of reaching a key in a balanced tree
seq scanگاهی ارزان‌تر از ایندکس، وقتی ستون انتخاب‌پذیر نیستsometimes cheaper than the index, when the column is not selective

هر ایندکس، یک نوشتن اضافهEvery index is one more write

جدول با پنج ایندکس، هر درج را شش بار انجام می‌دهد: یک بار در جدول و پنج بار در ساختارهای ایندکس. این هزینه در بار خواندنی دیده نمی‌شود و در بار نوشتنی بی‌رحمانه است. علاوه بر تعداد، ترتیب هم مهم است: اگر همهٔ ایندکس‌ها روی کلیدهایی باشند که با هم رشد می‌کنند، نوشتن‌ها به یک صفحه می‌رسند و رقابت روی همان صفحه بالا می‌رود. راه درست این است که ایندکس‌ها را از روی کوئری‌های واقعی انتخاب کنی، نه از روی حدس، و ایندکس‌هایی را که هیچ کوئری‌ای استفاده نمی‌کند حذف کنی.A table with five indexes performs every insert six times: once in the table and five times in index structures. The cost is invisible under read load and brutal under write load. Beyond the count, order matters: if every index is on keys that grow together, writes land on the same page and contention rises on it. The right move is to choose indexes from real queries rather than guesses, and to drop the ones no query uses.

ایندکس بد از نداشتنش بدتر استA bad index is worse than none

ایندکسی که تقریباً همهٔ ردیف‌ها را برمی‌گرداند، هیچ کاری برای کوئری نمی‌کند، ولی هزینهٔ نوشتن و فضایش را می‌پردازی. ایندکس روی ستونی با دو مقدار ممکن، همین حالت را دارد. بدتر، ایندکسی است که کوئری‌پلنر را فریب می‌دهد: آمار کهنه می‌گوید انتخاب‌پذیر است، پلنر به آن اعتماد می‌کند و برای هر ردیف یک خواندن تصادفی می‌زند؛ نتیجه از اسکن کامل کندتر می‌شود. آمار را به‌روز نگه دار و پلن واقعی کوئری‌های کند را بخوان، نه فقط وجود ایندکس را.An index that returns almost every row does nothing for the query while you still pay its write cost and space. An index on a column with two possible values is exactly that. Worse is an index that misleads the planner: stale statistics say it is selective, the planner trusts them, and it does one random read per row, ending up slower than a full scan. Keep statistics fresh and read the actual plan of slow queries, not just the list of indexes.

تلهٔ رایجThe usual trap

ایندکس گذاشتن روی هر ستونی که در WHERE دیده می‌شود. هر ایندکس نوشتن را کند می‌کند و بعضی‌ها هیچ‌وقت استفاده نمی‌شوند؛ بعد در بار نوشتنی معلوم می‌شود که بیشتر هزینه را ایندکس‌هایی می‌سازند که کسی سراغشان نمی‌رود. ایندکس را از روی کوئری‌های واقعی انتخاب کن و ایندکس بلااستفاده را حذف کن.Indexing every column that shows up in a WHERE clause. Each index slows writes and some are never used; under write load it turns out most of the cost comes from indexes nobody queries. Choose indexes from real queries and drop the unused ones.

inverted index

ایندکس معکوس فصل ۴Chapter 4 · دیدن در متنsee in context

چطور یک واژه را در میلیون‌ها سند پیدا می‌کنی؟How do you find one word across a million documents?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دفترچهٔ دستور پخت داری. آخر دفترچه برای خودت فهرستی نوشته‌ای: «تخم‌مرغ: ص ۳، ۷، ۱۲» و «دارچین: ص ۹». حالا برای پیدا کردن همهٔ دستورهایی که تخم‌مرغ دارند، لازم نیست کل دفترچه را ورق بزنی. آن فهرست از واژه به صفحه رفته است، نه از صفحه به واژه. ایندکس معکوس هم همین است.You keep a notebook of recipes. At the back you have written your own list: eggs, pages 3, 7, 12; cinnamon, page 9. Now to find every recipe with eggs you do not have to flip through the notebook. That list goes from word to page, not page to word. An inverted index is exactly that.

تشبیه و تصویر ذهنیThe analogy

ساختن این فهرست کار خودش را دارد. باید هر صفحه را بخوانی، واژه‌ها را جدا کنی و یکدست کنی: «تخم‌مرغ» و «تخم مرغ» و «تخم‌مرغ» باید یک چیز حساب شوند، وگرنه فهرست سه تیکه می‌شود. واژه‌هایی مثل «و» در همهٔ صفحه‌ها هستند و فهرستشان به اندازهٔ کل دفترچه می‌شود، پس کنارشان می‌گذاری. اگر بعداً یک دستور اضافه کنی، باید چند جای فهرست را عوض کنی؛ و اگر بخواهی عبارت دو کلمه‌ای را پیدا کنی، فقط دانستن صفحه کافی نیست، باید بدانی آن دو واژه کنار هم آمده‌اند یا نه.Building that list is work. You read every page, split the words, and normalise them: egg, eggs and Egg have to count as one thing or the list splits three ways. Words like and appear on every page and their list would be as long as the notebook, so you leave them out. Add one recipe later and several places in the list change; and to find a two-word phrase, knowing the page is not enough, you need to know whether those words sat next to each other.

همهٔ اسنادall documentsنان → سند ۲، ۷bread → doc 2, 7شیر → سند ۲، ۹milk → doc 2, 9تخم‌مرغ → سند ۷eggs → doc 7هر واژه یک فهرست دارد؛ پرس‌وجو یعنی اشتراک همین فهرست‌هاone list per term; a query intersects those lists
هر سند به چند فهرست می‌رود؛ برای همین یک سند می‌تواند در چند فهرست باشد.Each document goes into several lists, which is why one document can appear in more than one.

و بعدش، فنیAnd now, technically

ایندکس معکوس دو بخش دارد: دیکشنری واژه‌ها و برای هر واژه یک postings list از شناسهٔ سندها. ساختش یعنی توکنایز کردن متن، نرمال‌سازی، ریشه‌یابی، و حذف واژه‌های بسیار پرتکرار. پرس‌وجوی چند واژه‌ای با اشتراک یا ادغام فهرست‌های مرتب جواب داده می‌شود؛ چون شناسه‌ها مرتب‌اند، ادغام خطی است. برای جست‌وجوی عبارت، کنار هر شناسه موقعیت واژه هم ذخیره می‌شود. شناسه‌ها را با اختلاف و کدگذاری متغیر فشرده می‌کنند. در موتورهای جست‌وجو، داده در segmentهای تغییرناپذیر نوشته می‌شود و هر حذف یک نشانهٔ حذف است؛ segmentها در پس‌زمینه ادغام می‌شوند، شبیه همان کاری که LSM می‌کند. رتبه‌بندی هم روی همین فهرست‌ها حساب می‌شود، با شمارش تکرار و معکوس تعداد سندها.An inverted index has two parts: a dictionary of terms and, for each term, a postings list of document ids. Building it means tokenising text, normalising it, stemming, and dropping very frequent terms. A multi-word query is answered by intersecting or merging sorted lists, which is linear because ids are sorted. Phrase search also stores the position of each term beside each id. Ids are compressed by storing the gap between them and using variable-length codes. Search engines write data into immutable segments and record each delete as a marker; segments merge in the background, much like an LSM tree. Ranking is computed over those same lists, from term counts and the inverse of document frequency.

1 term → nهر واژه به فهرستی از سندها نگاشته می‌شودeach term maps to a list of documents
postingsشناسه‌ها مرتب‌اند، پس ادغام خطی استids stay sorted, so merging is linear
positionsبرای جست‌وجوی عبارت، جای واژه هم ذخیره می‌شودfor phrase search, the word's position is stored

نرمال‌سازی، نصف کارNormalisation is half the job

اگر متن را همان‌طور که هست ایندکس کنی، جست‌وجو بدجوری می‌شود. «کتاب» و «کتاب‌ها» باید یک ریشه پیدا کنند، حروف عربی و فارسی باید یک‌شکل شوند، و نیم‌فاصله باید قبل از توکن‌سازی درست دیده شود. هر تصمیمی در این مرحله، بعداً برگشت‌ناپذیر است: اگر واژه‌ای را به ریشه‌اش برده باشی، نمی‌توانی دقیقاً همان شکل اصلی را جست‌وجو کنی، مگر اینکه شکل اصلی را هم نگه داری. موتورهای جدی هر دو را نگه می‌دارند و همین باعث می‌شود ایندکس از متن اصلی بزرگ‌تر شود.Index the text as-is and search goes wrong. Book and books must share a stem, Arabic and Persian letter forms must collapse into one, and the zero-width non-joiner has to be handled before tokenising. Every decision here is hard to reverse: once a term is stemmed, you cannot search the exact original form unless you kept it. Serious engines keep both, which is part of why a search index is larger than its text.

چرا به‌روزرسانی سخت استWhy updates are hard

postings list یک ساختار مرتب است و درج یک سند در میان آن، همهٔ شناسه‌های بعدی را جابه‌جا می‌کند. تغییر یک سند هم یعنی حذف آن از ده‌ها فهرست و درج دوباره در ده‌ها فهرست. برای همین موتورهای جست‌وجو به‌جای به‌روزرسانی درجا، segment تازه می‌سازند و segmentهای قدیمی را در پس‌زمینه ادغام می‌کنند؛ همان الگوی LSM. نتیجه این است که تازگی نتایج همیشه فوری نیست و «حذف‌شده» تا ادغام بعدی در ایندکس می‌ماند و باید در نتایج فیلتر شود.A postings list is sorted, so inserting one document shifts every later id. Editing a document means removing it from dozens of lists and inserting it into dozens again. That is why search engines build fresh segments instead of updating in place and merge old ones in the background, the LSM pattern again. The result is that freshness is never instant, and a deleted document stays in the index until the next merge and has to be filtered out of results.

تلهٔ رایجThe usual trap

فکر کردن این‌که ایندکس معکوس را می‌شود مثل یک جدول معمولی و تراکنشی به‌روز کرد. هر ویرایش یک سند، ده‌ها فهرست را لمس می‌کند و هزینه‌اش با محبوبیت واژه‌ها بالا می‌رود؛ برای همین موتورها دسته‌ای می‌نویسند و نتایج تازه را با تأخیر می‌دهند. اگر تازگی فوری لازم داری، باید همین تأخیر را در طراحی حساب کنی.Assuming an inverted index can be updated like an ordinary transactional table. Editing one document touches dozens of lists and the cost grows with how popular its words are, which is why engines write in batches and serve fresh results with a delay. If you need instant freshness, budget for that delay in the design.

چرا نوشتنِ سریع، خواندن را کند می‌کند؟Why does a fast write make the read slow?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دفتر یادداشت روزانه‌ات را باز می‌کنی و می‌بینی یک جمله را اشتباه نوشته‌ای. پاک‌کن نداری و کل صفحه را دوباره نمی‌نویسی؛ خط می‌زنی و در خط بعدی نسخهٔ درست را می‌نویسی. چند ماه بعد، دفتر پر از خط‌خوردگی است و برای پیدا کردن یک خاطره باید از آخر به اول بگردی. یک روز همه را در دفتر تازه‌ای پاک‌نویس می‌کنی. درخت LSM دقیقاً همین کار را با داده می‌کند.You open your diary and see a sentence you got wrong. There is no eraser and you do not rewrite the page; you cross it out and write the correct version on the next line. Months later the diary is full of crossings, and to find a memory you search from the back. One day you copy everything into a fresh notebook. An LSM tree treats data exactly like that.

تشبیه و تصویر ذهنیThe analogy

نوشتن در دفتر همیشه یک کار است: یک خط اضافه کن. به همین دلیل سریع است. خواندن اما گران است: باید ببینی آخرین نسخه کجاست، شاید چند خط پایین‌تر، شاید در دفتر قبلی. برای اینکه خواندن خیلی بد نشود، هر چند وقت یک بار دفترها را مرتب می‌کنی و نسخه‌های قدیمی و خط‌خورده را حذف می‌کنی. اگر مرتب‌سازی عقب بیفتد، خواندن کند می‌شود و دیسک پر؛ اگر پشت سر هم مرتب کنی، نوشتن کند می‌شود. تمام تنظیم درخت LSM همین تعادل است: چه وقت و چقدر مرتب کن.Writing in the diary is always one action: add a line, which is why it is fast. Reading is expensive: you have to find where the latest version lives, maybe a few lines down, maybe in the previous notebook. To keep reading from getting terrible you tidy the notebooks now and then, dropping old crossed-out versions. Let the tidying fall behind and reads slow down and the shelf fills; tidy constantly and writes slow down. Every LSM setting is that balance: when to tidy, and how much.

نوشتنwriteتراکنشa transactionmemtable + WALmemtable + WALدر حافظه، مرتبsorted in memoryریختن به دیسکflush to diskیک SSTablean SSTableفشرده‌سازیcompactionادغام لایه‌هاmerging levels
نوشتن در حافظه جمع می‌شود، مرتب به دیسک می‌رود، و فشرده‌سازی نسخه‌های مرده را پاک می‌کند.Writes gather in memory, flush to disk sorted, and compaction clears the dead versions.

و بعدش، فنیAnd now, technically

هر نوشتن اول به memtable می‌رود، یک نگاشت مرتب در حافظه، و همزمان در WAL ثبت می‌شود. وقتی memtable پر شد، به‌صورت یک SSTable، فایل مرتب و تغییرناپذیر، روی دیسک ریخته می‌شود و memtable تازه شروع می‌کند. خواندن از جدیدترین جا به قدیمی‌ترین می‌رود: اول memtable، بعد فایل‌های تازه، بعد لایه‌های پایین‌تر، تا نسخهٔ کلید را پیدا کند؛ bloom filter در هر SSTable خیلی از این جست‌وجوها را حذف می‌کند. compaction در پس‌زمینه فایل‌ها را ادغام می‌کند و نسخه‌های قدیمی و نشانه‌های حذف را دور می‌ریزد. نوشتن ترتیبی است، پس توان نوشتن بالا می‌رود؛ در عوض خواندن به چند ساختار نگاه می‌کند و فشرده‌سازی، دیسک و CPU و پهنای باند می‌خورد. پیمایش بازه‌ای هم یعنی ادغام همزمان چند فایل مرتب.Every write goes first to a memtable, a sorted map in memory, and is recorded in a WAL at the same time. When the memtable fills it is flushed to disk as an SSTable, a sorted immutable file, and a fresh memtable starts. A read moves from newest to oldest: memtable, then recent files, then lower levels, until it finds the key's latest version; a Bloom filter per SSTable removes many of those lookups. Background compaction merges files and discards old versions and deletion markers. Writes are sequential, so write throughput is high; reads in exchange check several structures, and compaction consumes disk, CPU and bandwidth. A range scan means merging several sorted files at once.

memtableنوشتن اول اینجا می‌نشیند، مرتب و در حافظهwrites land here first, sorted and in memory
2–10×ضریب نوشتن اضافی در طول عمر دادهextra write factor over the data's life
0..Nخواندن ممکن است چند لایه را بگرددa read may walk several levels

خواندن، گران‌ترین بخشThe read is the expensive part

در درخت LSM نوشتن تقریباً مجانی است و خواندن باید هزینه‌اش را بدهد. اگر کلید در memtable نباشد، باید فایل‌های لایهٔ صفر را بگردی که ممکن است همپوشان باشند، و بعد سراغ لایه‌های پایین‌تر بروی. هر لایه یک خواندن بالقوه است، و اگر bloom filter نبود، هر خواندن یک read تصادفی بود. دو چیز این هزینه را مهار می‌کند: فیلترها که بیشتر فایل‌های بی‌ربط را رد می‌کنند، و leveled compaction که هر لایه را مرتب نگه می‌دارد تا در هر لایه فقط یک فایل کاندید باشد.In an LSM tree the write is almost free and the read pays for it. If the key is not in the memtable you search the level-zero files, which may overlap, then move to lower levels. Each level is a potential read, and without a Bloom filter each read would be a random one. Two things contain the cost: filters that reject most irrelevant files, and leveled compaction that keeps each level sorted so only one file per level can be a candidate.

مالیات پنهان: fشرده‌سازیThe hidden tax: compaction

هر بایت داده در طول عمرش چند بار بازنویسی می‌شود و این جایی است که توان نوشتن خرج می‌شود. در بار سنگین، compaction با نوشتن رقابت می‌کند و اگر عقب بماند، صف نوشتن پر می‌شود و تأخیر می‌پرد. بدترین حالت برای p99 است، نه برای میانگین: بیشتر وقت‌ها همه‌چیز خوب است و هر چند دقیقه یک بار یک توقف. برای همین سیستم‌های جدی compaction را محدود و پایش می‌کنند و روی فضای آزاد دیسک هشدار می‌گذارند؛ بدون آن، درخت LSM در آزمایش عالی و در تولید شکننده است.Every byte is rewritten several times over its life, and that is where write capacity goes. Under load compaction competes with writes, and if it falls behind the write queue fills and latency jumps. It hurts p99, not the average: most of the time all is well, then every few minutes there is a stall. Serious systems throttle and monitor compaction and alert on free disk; without that, an LSM tree is excellent in a benchmark and fragile in production.

تلهٔ رایجThe usual trap

فرض کردن این‌که LSM برای هر باری بهتر است. اگر بار خواندنی سنگین و نوشتن سبک باشد، چند ساختار برای هر خواندن و فشرده‌سازی مداوم، بدتر از یک درخت B کار می‌کند. و اگر compaction را پایش نکنی، اولین نشانهٔ مشکل یک توقف ناگهانی نوشتن است، نه یک هشدار.Assuming an LSM tree wins every workload. With heavy reads and light writes, checking several structures plus constant compaction does worse than a B-tree. And without compaction monitoring, the first sign of trouble is a sudden write stall, not an alert.

memtable

جدول حافظه‌ای فصل ۴Chapter 4 · دیدن در متنsee in context

قبل از دیسک، نوشتن کجا می‌نشیند؟Where does a write land before the disk?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

روی درِ یخچال یک تختهٔ سفید کوچک داری و هر خرید امروز را همان‌جا می‌نویسی: نان، ماست، بنزین. نوشتن رویش دو ثانیه است، ولی جای کمی دارد. آخر هفته همه را به ترتیب در دفتر حساب می‌نویسی و تخته را پاک می‌کنی. نوشتن‌های تازه هم همین‌جا زندگی می‌کنند: روی تخته می‌مانند تا پر شود، بعد یک‌جا و مرتب به دفتر می‌روند.There is a small whiteboard on the fridge door, and every purchase today goes on it: bread, yoghurt, petrol. Writing there takes two seconds, but it holds very little. At the end of the week you copy everything into the ledger, in order, and wipe the board. Fresh writes live exactly there: on the board until it fills, then moved to the ledger in one sorted sweep.

تشبیه و تصویر ذهنیThe analogy

تختهٔ آشپزخانه سه ویژگی دارد که آن را از دفتر جدا می‌کند. اول، نوشتن رویش تقریباً بی‌دردسر است، چون فقط یک خط تازه اضافه می‌کنی و چیزی را پاک نمی‌کنی. دوم، چون هر روز کنارش می‌نویسی، خط‌ها خودشان مرتب می‌شوند و پیدا کردن «ماست» در آن یک نگاه است. سوم، وقتی پر شد کل تخته را یک‌جا به دفتر منتقل می‌کنی، نه خط‌به‌خط؛ و همین کار نوشتن را ارزان نگه می‌دارد. بهایش این است که تخته شکننده است: یک دستمال خیس و همه‌چیز رفته. برای همین کنارش یک دفترچهٔ کوچک می‌گذاری و پیش از نوشتن روی تخته، همان خط را در آن هم ثبت می‌کنی؛ اگر تخته پاک شد، از روی دفترچه بازسازی می‌شود.The kitchen board has three properties the ledger does not. Writing on it is almost free, because you only add a line and never rub one out. Because you write on it every day, the lines come out sorted anyway, so finding “yoghurt” is a glance. And when it fills, you copy the whole board across in one sweep instead of line by line, which is what keeps writing cheap. The bill is that the board is fragile: one wet cloth and it is gone. So you keep a small notebook beside it and copy each line there before writing on the board; if the board is wiped, the notebook rebuilds it.

نوشتن کلاینتClient writeبدون ترتیبunorderedافزودن به WALAppend to WALروی دیسکon diskدرج در memtableInsert in memtableمرتب، در حافظهsorted, in memoryپر شدنMemtable fullfreeze و صفfreeze and queueریختن به SSTableFlush to SSTableترتیبیsequential
نوشتن اول در حافظه می‌نشیند، مرتب می‌ماند، و در یک حرکت ترتیبی به فایل روی دیسک تبدیل می‌شود.A write lands in memory first, stays sorted, and leaves as one sequential file on disk.

و بعدش، فنیAnd now, technically

memtable یک نگاشت مرتب در حافظه است، معمولاً skiplist یا درخت متوازن، که نوشتن‌های تازه را نگه می‌دارد. مسیر نوشتن این است: اول رکورد در WAL پایدار می‌شود، بعد در memtable درج می‌شود، و بعد به کلاینت پاسخ داده می‌شود. خواندن از تازه‌ترین جا شروع می‌شود: اول memtable، بعد memtableهای فریزشده، بعد SSTableهای دیسک؛ چون کلیدها در هر لایه مرتب‌اند، ادغام چند منبع ساده است. وقتی حجم memtable از آستانه بگذرد فریز می‌شود و یک memtable تازه نوشتن‌ها را می‌پذیرد؛ نسخهٔ فریزشده در پس‌زمینه به یک SSTable تبدیل می‌شود، و این تبدیل یک پیمایش ترتیبی است، نه هزار نوشتن تصادفی. اگر ریختن به دیسک از نوشتن عقب بماند، موتور نوشتن را کند یا متوقف می‌کند؛ این backpressure عمدی است، چون حافظه کران دارد. حذف هم در memtable یک نشانهٔ حذف است، نه پاک کردن.A memtable is a sorted in-memory map, usually a skiplist or a balanced tree, holding the newest writes. The write path is: the record becomes durable in the WAL, the key goes into the memtable, then the client is acknowledged. Reads start at the newest place: the memtable first, then frozen memtables, then SSTables on disk; because every layer is sorted, merging several sources is straightforward. When the memtable passes its size threshold it is frozen and a fresh one accepts writes; the frozen copy is turned into an SSTable in the background, and that conversion is one sequential pass, not a thousand random writes. If flushing falls behind, the engine slows or stops writes; that backpressure is deliberate, because memory is bounded. A delete is a tombstone here, not an erasure.

≈ 64 MBآستانهٔ معمول پر شدن؛ بعد از آن فریز و ریختنa common flush threshold; after it, freeze and flush
1همیشه فقط یک memtable نوشتن را می‌پذیردonly one memtable accepts writes at a time
O(log n)هزینهٔ درج در skiplist مرتبinsert cost into a sorted skiplist

چرا حافظه، وقتی دیسک هم هست؟Why memory at all, when there is a disk

دیسک نوشتن کوچک و پراکنده را دوست ندارد و SSD هم برای هر نوشتن تصادفی چند برابر هزینه می‌دهد. memtable وسط می‌ایستد تا نوشتن‌های پراکندهٔ برنامه را جمع کند، مرتب کند، و بعد در یک حرکت بزرگ و ترتیبی تحویل دیسک بدهد. سود دوم این است که تازه‌ترین داده اصلاً به دیسک نمی‌خورد: وقتی کلاینت چیزی را همین حالا نوشته و دوباره می‌خواند، جواب از حافظه می‌آید. بهایش این است که حافظه گران‌ترین نوع ذخیره‌سازی است و اندازه‌اش سقف دارد؛ برای همین memtable یک ساختار دائمی نیست، یک بافر هوشمند است.A disk dislikes small scattered writes, and an SSD pays several times over for each random one. The memtable stands in the middle so the application's scattered writes can be gathered, sorted, and handed to the disk in one large sequential move. The second gain is that the freshest data never touches the disk: when a client writes something now and reads it back immediately, the answer comes from memory. The bill is that memory is the most expensive storage there is and its size is capped, which is why a memtable is not a permanent home but a smart buffer.

وقتی memtable عقب می‌ماندWhen the memtable falls behind

حافظه سقف دارد، پس اگر ریختن به دیسک یا compaction نتواند با نوشتن همراه شود، موتور چاره‌ای جز کند کردن یا نگه داشتن نوشتن ندارد. این همان لحظه‌ای است که تأخیر از یک خط صاف به یک دیوار تبدیل می‌شود، و در داشبوردها معمولاً با اسم کلی «write stall» ظاهر می‌شود. کوچک گرفتن memtable هم رایگان نیست: فایل‌های کوچک و زیاد می‌سازد، compaction را بیشتر می‌کند و خواندن را کند. بزرگ گرفتنش هم بازیابی را طولانی می‌کند، چون باید لاگ بیشتری بازپخش شود. عدد درست بین این دو است و با بار واقعی پیدا می‌شود، نه با کپی کردن از یک وبلاگ.Memory has a ceiling, so if flushing or compaction cannot keep up with writes the engine has no choice but to slow them or hold them. That is the moment latency turns from a flat line into a wall, and it usually shows up in dashboards under the blunt name write stall. A small memtable is not free either: it produces many small files, more compaction and slower reads. A large one makes recovery longer, because more of the log must be replayed. The right number sits between the two and comes from your own load, not from a blog post.

memtable در برابر SSTablememtable versus SSTable

memtablememtableSSTableSSTable
محلLocationحافظهmemoryدیسکdisk
تغییرپذیریMutabilityدرجا به‌روز می‌شودupdated in placeتغییرناپذیر، یک بار نوشتنimmutable, written once
نوشتنWriteدرج سریع، بدون I/Ofast insert, no I/Oپیمایش ترتیبیsequential pass
دوامDurabilityفقط با WALonly through the WALروی رسانهon the medium

تلهٔ رایجThe usual trap

با memtable مثل یک کش رفتار کردن که هر وقت جا کم شد کوچکش می‌کنی، یا برای گرفتن سرعت بیشتر WAL را خاموش کردن. آن‌وقت نوشتن‌هایی که به مشتری «ثبت شد» گفتی فقط در حافظه بودند و یک ری‌استارت کافی است تا نباشند.Treating the memtable like a cache you shrink whenever memory is tight, or switching off the WAL for a little extra speed. Then the writes you told the customer were recorded existed only in memory, and one restart is enough to make them never have happened.

صفحه پر شد؛ رکورد تازه کجا برود؟The page is full; where does the new record go?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دفترچهٔ تلفن کوچکت پر شده و باید اسم تازه‌ای را وسط الفبا جا بدهی. یک صفحه را به دو صفحهٔ مرتب می‌شکنی و توی فهرست بالای دفترچه می‌نویسی که از این اسم به بعد در صفحهٔ بعدی است. کار تمام است، ولی دو جا را دست زدی، نه یکی.Your small address book is full and a new name has to go in the middle of the alphabet. You break one page into two sorted pages and update the tab at the top of the book to say that from this name on it continues on the next page. Done — but you touched two places, not one.

تشبیه و تصویر ذهنیThe analogy

اگر همان دفترچه را همیشه از آخر پر کنی، هر اسم تازه آخرین صفحه را می‌شکند و صفحه‌های نیمه‌خالی زیادی پشت سرت می‌مانند. اگر از وسط پر کنی، هر شکستن یک تب بالای دفترچه را هم عوض می‌کند، و اگر آن تب هم پر باشد، خودش می‌شکند و یک سطح به دفترچه اضافه می‌شود. برای همین دفترچه‌ها را کمی خالی نگه می‌دارند: چند خط آخر هر صفحه را خالی می‌گذاری تا اسم بعدی جا شود. بهایش کاغذ بیشتر است، سودش این است که کمتر می‌شکنی.If you always fill that book from the back, every new name splits the last page and leaves a trail of half-empty pages behind you. If you fill from the middle, every split also changes a tab at the front, and if that tab page is full it splits too and the book gains a level. That is why books are kept slightly loose: leave a few lines free at the end of each page so the next name fits. The price is more paper, the gain is fewer splits.

و بعدش، فنیAnd now, technically

درج در درخت B با پایین رفتن تا برگ شروع می‌شود؛ اگر جا باشد، کلید همان‌جا درج می‌شود. اگر برگ پر باشد، صفحهٔ تازه‌ای گرفته می‌شود، حدود نیمی از کلیدها به آن منتقل می‌شود و کلید میانی به والد فرستاده می‌شود. والد هم ممکن است پر باشد و بشکند، و همین تا ریشه بالا می‌رود؛ شکستن ریشه تنها حالتی است که عمق درخت را یک واحد زیاد می‌کند. هزینه‌اش دو نوشتن صفحه به‌جای یکی است، به‌علاوهٔ رکوردهای WAL برای هر دو صفحه، و قفل‌های کوتاهی که باید نگه داشته شوند. موتورها معمولاً صفحه را کامل پر نمی‌کنند و ده تا سی درصد فضا را خالی می‌گذارند تا شکستن بعدی دیرتر برسد. با کلیدهای همیشه صعودی، همیشه آخرین صفحه می‌شکند و همان لبه به گلوگاه تبدیل می‌شود.An insert descends to a leaf; with room, the key goes in place. If the leaf is full, a new page is allocated, roughly half the keys move across, and the middle key is pushed to the parent. The parent may itself be full and split, and that can climb to the root; a root split is the only case that raises the tree's depth by one. The cost is two page writes instead of one, plus WAL records for both pages, plus the short latches held across the operation. Engines usually do not fill pages completely and leave ten to thirty percent free so the next split comes later. With ever-increasing keys the rightmost page splits every time, and that edge becomes the bottleneck.

2 pagesنوشتن برای یک درج، وقتی صفحه پر استwrites for one insert when the page is full
≈ 50%پرشدگی هر نیمه بعد از یک شکستن سادهfill level of each half after a plain split
1 levelرشد عمق، فقط وقتی ریشه بشکندdepth grows only when the root splits

تلهٔ رایجThe usual trap

فرض کردن این‌که شکستن صفحه نادر است. با کلیدهای صعودی مثل زمان یا شناسهٔ خودافزا، هر درج آخرین صفحه را می‌شکند و همان لبه داغ می‌شود؛ در همان حال بقیهٔ درخت نیمه‌خالی است. اگر fill factor را هم بی‌دلیل زیاد کنی، بعد از یک بارگذاری انبوه، نوشتن‌ها به شکستن پشت‌سرهم تبدیل می‌شوند.Assuming page splits are rare. With increasing keys such as timestamps or auto-increment ids, every insert splits the last page and that edge runs hot while the rest of the tree sits half empty. Force the fill factor too high and, after a bulk load, writes turn into a run of splits.

از ده جواب درست، چند تا را آوردی؟Of ten correct answers, how many did you bring back?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

از دوستت می‌خواهی پنج تا از بهترین کبابی‌های شهر را نام ببرد. پنج اسم می‌گوید، ولی تو می‌دانی دو تای دیگر هم بودند که جا افتادند. بازخوانی همین است: از کل جواب‌های درست، چند تا را آورد.You ask a friend to name the five best kebab places in town. He names five, but you know two more belonged on the list and were left out. That is recall: out of all the correct answers, how many came back.

تشبیه و تصویر ذهنیThe analogy

دوست دیگری را تصور کن که بیست اسم می‌گوید تا چیزی جا نیفتد. بازخوانی‌اش بالاست، ولی حالا باید بیست جا را امتحان کنی تا سه تای خوب پیدا شود. این همان معامله است: هر چه بیشتر بگردی، چیزهای بیشتری پیدا می‌کنی و چیزهای بی‌ربط بیشتری هم تحویل می‌دهی. پس بازخوانی تنها معیار نیست؛ باید کنارش بگویی چقدر از آنچه دادی درست بود. و هر دو فقط وقتی معنا دارند که بگویی «چند تا» را نگاه می‌کنی، چون پنج تای اول با پنجاه تای اول یکی نیست.Picture another friend who names twenty places so nothing is missed. His recall is high, but now you must try twenty to find three good ones. That is the trade: the wider you search, the more you find and the more irrelevant things you hand over. So recall alone is not a verdict; it has to be quoted next to how much of what you returned was right. And both only mean something once you say how many results you looked at, because the first five and the first fifty are not the same question.

و بعدش، فنیAnd now, technically

بازخوانی در جست‌وجوی تقریبی با recall@k سنجیده می‌شود: از k نتیجهٔ برتر واقعی، چند تا در k نتیجهٔ برگشتی بوده است. مبنای سنجش، جست‌وجوی دقیق روی یک نمونه است، چون در تولید کسی جواب درست را از قبل نمی‌داند. در ایندکس برداری، پارامترهایی مثل ef_search در HNSW و nprobe در IVF بازخوانی را جابه‌جا می‌کنند: بیشتر بگرد، بازخوانی بالاتر، تأخیر بیشتر. عدد معمول در سیستم تنظیم‌شده بین ۰٫۹ تا ۰٫۹۹ است و بالاتر از آن معمولاً گران است. دو دام مهم: نمونه‌ای که برای سنجش استفاده می‌کنی باید از دادهٔ ساخت ایندکس جدا باشد، وگرنه عدد را خوب می‌بینی و در تولید نمی‌بینی؛ و بازخوانی بعد از تغییر توزیع داده یا عوض شدن مدل embedding بی‌سروصدا افت می‌کند.In approximate search, recall is measured as recall@k: of the true top k results, how many appeared in the k returned. The yardstick is exact search over a sample, because in production nobody knows the right answer in advance. In a vector index, parameters such as ef_search in HNSW and nprobe in IVF move recall directly: search wider, recall rises, latency rises. A tuned system usually lands between 0.9 and 0.99, and above that it tends to get expensive. Two traps matter: the sample you measure on must be separate from the data the index was built with, or the number looks good and production does not; and recall decays quietly after the data distribution shifts or the embedding model changes.

recall@10چند درصد از ده همسایهٔ واقعی برگشته‌اندwhat share of the true ten neighbours came back
0.9–0.99بازهٔ معمول در یک ایندکس برداری تنظیم‌شدهa typical range for a tuned vector index
1.0جست‌وجوی دقیق؛ مبنای سنجش، نه هدف تولیدexact search: the yardstick, not the production target

تلهٔ رایجThe usual trap

تنظیم کردن برای تأخیر و هیچ‌وقت اندازه نگرفتن بازخوانی. سیستم کار می‌کند، کند نیست، و کسی شکایت نمی‌کند؛ در حالی که از ده نتیجهٔ برتر فقط چهار تا برمی‌گردد و کاربر فکر می‌کند چیز دیگری وجود ندارد.Tuning for latency and never measuring recall. The system runs, it is not slow, nobody complains — while only four of the true top ten come back and users conclude the rest does not exist.

SSTable

جدول رشته‌ای مرتب فصل ۴Chapter 4 · دیدن در متنsee in context

فایلی که دیگر عوض نمی‌شود، چه بردی دارد؟What is a file that never changes good for?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

دفتر حساب ماه قبل را صحافی کرده‌ای و دیگر تویش نمی‌نویسی. چون صفحه‌ها مرتب‌اند و کسی دستشان نمی‌زند، هر روزی را که بخواهی در چند ثانیه پیدا می‌کنی. اگر خرید دیروز اشتباه ثبت شده، پاکش نمی‌کنی؛ در دفتر این ماه یادداشت تازه‌ای می‌نویسی که «آن ردیف را نادیده بگیر». فایل‌های ذخیره‌سازی هم همین قرار را دارند: یک بار نوشته می‌شوند و هر اصلاح یک نسخهٔ تازه‌تر است.You had last month's ledger bound into a book, and you never write in it again. Because the pages are sorted and nobody touches them, any day you want is a few seconds away. If yesterday's purchase was recorded wrong, you do not erase it; you write a fresh note in this month's ledger saying “ignore that line”. Storage files make the same deal: written once, kept sorted, and every correction is a newer version.

تشبیه و تصویر ذهنیThe analogy

چون دفتر صحافی‌شده دیگر عوض نمی‌شود، سه چیز راحت می‌شود. چند نفر می‌توانند هم‌زمان بخوانند و کسی لازم نیست قفل بگذارد، چون هیچ‌کس قرار نیست چیزی را تغییر دهد. می‌شود از آن نسخهٔ پشتیبان گرفت بی‌آنکه وسط کار چیزی عوض شود. و اگر موقع صحافی ورق‌های آخر خراب شد، فقط همان دفتر دور انداخته می‌شود. بهایش سه چیز است: نمی‌توانی درجا اصلاح کنی، پس نسخه‌های قدیمی روی هم جمع می‌شوند؛ برای پیدا کردن یک اسم باید فهرست داخل دفتر را داشته باشی، وگرنه ورق زدن از اول تا آخر تنها راه است؛ و برای اینکه قفسه از دفترها پر نشود، باید هر چند وقت چند دفتر را در یک دفتر تازه ادغام کنی.Because the bound ledger never changes, three things get easy. Several people can read at once and nobody needs a lock, since nobody is going to alter anything. You can copy it for backup while it is in use. And if the last sheets were damaged during binding, you throw away that one book. The bill comes in three parts: you cannot correct in place, so old versions pile up; to find a name you need the index inside the cover, or your only option is flipping from the first page; and to keep the shelf from filling with books, every so often you merge several of them into a fresh one.

پاورقی فایلfile footerفیلتر بلومbloom filterایندکس بلوک‌هاblock indexبلوک دادهdata block
مسیر خواندن از انتهای فایل شروع می‌شود: پاورقی، فیلتر، ایندکس، و آخر یک بلوک.A read starts at the end of the file: footer, filter, index, and finally one block.

و بعدش، فنیAnd now, technically

SSTable یعنی جدول رشته‌ای مرتب: دنباله‌ای از جفت‌های کلید-مقدار که کلیدها به ترتیب مرتب‌اند و فایل یک بار نوشته و دیگر تغییر نمی‌کند. فایل معمولاً به بلوک‌های چند کیلوبایتی شکسته می‌شود و کنارش یک ایندکس کوچک نگه می‌دارند که آخرین کلید هر بلوک را می‌گوید؛ کنار آن یک فیلتر بلوم و در انتها یک پاورقی که محل ایندکس و فیلتر را نشان می‌دهد. خواندن سه پرش است: از فیلتر بپرس، در ایندکس بلوک را پیدا کن، همان یک بلوک را بخوان و داخلش بگرد. نوشتن از یک memtable مرتب ساخته می‌شود: یک پیمایش ترتیبی، بدون هیچ نوشتن تصادفی، و به همین دلیل توان نوشتن بالاست. چون فایل تغییرناپذیر است، خواننده‌ها قفل نمی‌خواهند و یک نوشتن نیمه‌کاره فقط یک فایل دورانداختنی است. بهایش فضاست: نسخه‌های قدیمی و نشانه‌های حذف می‌مانند تا compaction جمعشان کند.An SSTable is a sorted string table: a sequence of key-value pairs with keys in order, written once and never modified. The file is split into blocks of a few kilobytes, with a small index beside them holding the last key of each block, a Bloom filter next to that, and a footer at the end pointing at both. A read is three hops: ask the filter, find the block in the index, read that one block and scan inside it. Writing it is built from a sorted memtable as a single sequential pass with no random writes, which is why write throughput is high. Because the file is immutable, readers need no locks and a half-written file is simply discarded. The bill is space: old versions and tombstones stay until compaction collects them.

≈ 4 KBاندازهٔ معمول یک بلوک دادهa typical data block
1 passساخت فایل از memtable، در یک پیمایش ترتیبیbuilt from the memtable in one sequential pass
O(log b)جست‌وجوی ایندکس برای پیدا کردن بلوک درستindex search to find the right block

چرا تغییرناپذیری این‌قدر می‌ارزدWhy immutability pays

وقتی فایل تغییر نمی‌کند، خیلی چیزها ساده می‌شوند. خواننده‌ها می‌توانند بدون هیچ قفلی بخوانند، چون هیچ نویسنده‌ای وسط کار صفحه‌ها را جابه‌جا نمی‌کند. اگر سیستم وسط نوشتن فایل بمیرد، فایل ناقص را دور می‌ریزی؛ لازم نیست تعمیرش کنی، چون نسخهٔ قبلی سالم است. بکاپ گرفتن هم یعنی کپی کردن فایلی که کسی تغییرش نمی‌دهد. اما این سادگی از جای دیگری صورت‌حساب می‌آید: هزینهٔ اصلاح، از لحظهٔ نوشتن به لحظهٔ compaction منتقل می‌شود، و آن‌جاست که دوباره دیسک و CPU خرج می‌شود.When a file does not change, a lot of things get simple. Readers can read with no lock at all, because no writer is shuffling pages underneath them. If the system dies mid-write, you throw the partial file away; there is nothing to repair, because the previous version is intact. Backup means copying a file nobody mutates. But that simplicity is paid for elsewhere: the cost of correction moves from write time to compaction time, and that is where disk and CPU get spent again.

یک خواندن، از داخل فایلOne read, inside the file

ترتیب خواندن مهم است، چون هر پرش گران است. اول فیلتر بلوم: اگر بگوید نیست، پرونده بسته می‌شود. بعد ایندکس بلوک‌ها، که به قدری کوچک است که در حافظه جا می‌شود و کلید هر بلوک را می‌داند؛ با جست‌وجوی دودویی، بلوک درست پیدا می‌شود. بعد یک بلوک خوانده می‌شود و درونش را خطی می‌گردی. برای پیمایش بازه‌ای، بلوک‌ها پشت سر هم خوانده می‌شوند، که برای دیسک و SSD نزدیک به حالت ایده‌آل است. مشکل جایی شروع می‌شود که یک کلید در چند فایل باشد؛ آن‌وقت همین مسیر چند بار تکرار می‌شود و این همان read amplification است.The order of the hops matters because each one is expensive. First the Bloom filter: if it says absent, the file is closed. Then the block index, small enough to sit in memory and holding each block's last key; a binary search picks the right block. Then one block is read and scanned linearly inside. For a range scan the blocks are read back to back, which is close to the ideal case for both disk and SSD. Trouble begins when one key lives in several files: the same path repeats, and that repetition is read amplification.

تلهٔ رایجThe usual trap

فکر کردن این‌که SSTable یک جدول معمولی است که می‌شود سطرهایش را حذف یا اصلاح کرد. حذف در واقع یک نشانهٔ حذف است و تا وقتی compaction همهٔ نسخه‌های قدیمی را ندیده باید بماند؛ پاک کردنش ردیف مرده را برمی‌گرداند. نکتهٔ دوم این‌که یک کلید می‌تواند در چند فایل باشد، پس خواندن ارزان نیست مگر این‌که فیلتر و ایندکس جلویش را بگیرند.Assuming an SSTable is an ordinary table whose rows you can delete or update. A delete is really a tombstone, and it must stay until compaction has seen every older version; removing it early resurrects the dead row. Second, one key may sit in several files, so reads are not cheap unless the filter and the index stop most of them.

بهترین سه تا را می‌خواهی، نه همه را.You want the best three, not all of them.

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

کنار صندوق هلو ایستاده‌ای و می‌خواهی سه تا از رسیده‌ترین‌ها را برای مهمانی برداری. همهٔ هلوی صندوق را جدا نمی‌کنی و مرتب نمی‌کنی؛ سه تا در دستت می‌گیری و از این به بعد هر هلوی تازه را فقط با بدترینِ آن سه مقایسه می‌کنی. آخر کار بهترین سه‌تای صندوق را داری، بی‌آنکه کل صندوق را مرتب کرده باشی.You are standing at a crate of peaches and want the three ripest for a party. You do not lay out and sort the whole crate; you take three in your hand and from then on compare each new peach only with the worst of those three. At the end you hold the best three in the crate, without ever sorting the crate.

تشبیه و تصویر ذهنیThe analogy

این حرکت فقط وقتی جواب می‌دهد که k کوچک باشد. اگر بخواهی نیمی از صندوق را جدا کنی، دیگر «سه خانه در دست» معنا ندارد و باید همه را یک‌جا بچینی. نکتهٔ دوم این است که با همین روش نمی‌توانی بگویی «چهارمی کدام است»؛ برای آن باید یک خانهٔ چهارم هم نگه داری. و اگر صندوق‌ها جدا باشند و کسی از هر صندوق سه تای برتر را به تو بدهد، باز هم نمی‌توانی فقط آن‌ها را روی هم بریزی؛ ممکن است هر سه تای برتر کل مهمانی از یک صندوق آمده باشند، ولی تو چهارمی آن صندوق را نداشته باشی.This only works while k is small. If you wanted half the crate set aside, three in hand stops meaning anything and you have to lay them all out. Second, this method cannot tell you which peach is fourth; for that you must keep a fourth slot. And if the crates are separate and someone hands you the best three from each, you still cannot just pile them up: all three winners overall might come from one crate, and you never saw that crate's fourth.

و بعدش، فنیAnd now, technically

کارآمدترین راه، یک هیپ کمینه به اندازهٔ k است: یک پاس روی داده، و برای هر آیتم یک مقایسه با کوچک‌ترین عضو هیپ؛ اگر بزرگ‌تر بود، جای آن را می‌گیرد. هزینه O(N log k) و حافظه O(k) است، در حالی که مرتب کردن کامل O(N log N) و حافظه‌ای به اندازهٔ کل داده می‌خواهد. برای صد میلیون ردیف و k برابر ده، این تفاوت بین چند ده ثانیه و حدود یک ثانیه است. اگر ایندکس بر اساس همان امتیاز مرتب باشد، لازم نیست همه را بخوانی: به ترتیب از ایندکس می‌خوانی و وقتی امتیاز باقی ردیف‌ها از k-امین نمی‌تواند بالاتر برود، تمام می‌کنی. در حالت توزیع‌شده، هر shard k نتیجهٔ محلی می‌دهد و هماهنگ‌کننده ادغام می‌کند؛ این فقط وقتی درست است که امتیاز هر سند به سندهای دیگر وابسته نباشد. اگر امتیاز به آمار کل مجموعه وابسته باشد، رتبه‌بندی هر shard تقریبی است و ادغام هم تقریبی می‌ماند.The efficient way is a min-heap of size k: one pass over the data, one comparison per item against the heap's smallest member, replacing it when the item is larger. That costs O(N log k) time and O(k) memory, where a full sort needs O(N log N) and memory proportional to the data. For a hundred million rows and k of ten, that is the difference between tens of seconds and about one second. If an index is already ordered by the same score, you need not read everything: walk the index in order and stop once the remaining rows cannot beat the k-th score. Distributed, each shard returns its local top k and a coordinator merges them; that is correct only when a document's score does not depend on other documents. When the score depends on whole-collection statistics, each shard's ranking is approximate and the merged result stays approximate.

O(N log k)یک پاس با هیپ به اندازهٔ k، به‌جای مرتب‌سازی کاملone pass with a k-sized heap instead of a full sort
O(k)حافظه؛ فقط k خانه، نه کل مجموعهmemory: k slots, not the whole collection
k × shardsدر حالت توزیع‌شده، k از هر shard و بعد ادغامdistributed: k from each shard, then merge

تلهٔ رایجThe usual trap

گرفتن top-k از هر shard و چسباندنشان به هم، بدون ادغام درست. اگر امتیاز هر سند به آمار کل مجموعه وابسته باشد، رتبه‌بندی هر shard با رتبه‌بندی کلی فرق دارد و نتیجه مرتب به نظر می‌رسد ولی غلط است؛ هیچ خطایی هم در کار نیست که بیدارت کند.Taking each shard's top k and concatenating them without a real merge. If scores depend on whole-collection statistics, each shard's ranking differs from the global one, and the result looks neatly ordered while being wrong; nothing raises an error to wake you up.

trigram index

ایندکس سه‌حرفی فصل ۴Chapter 4 · دیدن در متنsee in context

وسط یک کلمه را چطور پیدا می‌کنی؟How do you find the middle of a word?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

نصف یک جمله را از یک کتاب یادت است و مطمئنی در آن سه حرف «بار» پشت سر هم آمده. کتاب را باز می‌کنی و دنبال همان تکه می‌گردی، نه دنبال کل جمله؛ مشکل این است که کلمه را از اول نمی‌دانی، پس فهرست الفبایی به کارت نمی‌آید. ایندکس سه‌حرفی از قبل همین تکه‌های سه‌حرفی را فهرست کرده تا این جست‌وجو یک نگاه باشد.You half remember a sentence from a book and you are sure the three letters “bar” appear together in it. You open the book and hunt for that fragment, not the whole sentence; the trouble is you do not know how the word begins, so an alphabetical list is no help. A trigram index has already listed those three-letter fragments so the search is a single lookup.

تشبیه و تصویر ذهنیThe analogy

ترفند در این است که هر تکهٔ سه‌حرفی، هر جای کلمه که باشد، خودش یک سه‌حرف پشت سر هم است. پس اگر همهٔ سه‌حرف‌های پشت سر هم را فهرست کنی، هیچ تطابقی نمی‌تواند قایم شود. بعد سه‌حرف‌های الگوی خودت را می‌گیری، فهرست هر کدام را می‌آوری و فقط جاهایی را نگه می‌داری که در همهٔ فهرست‌ها آمده‌اند؛ آخر سر همان چند کاندید را با چشم می‌بینی. دو محدودیت دارد. الگوی کوتاه‌تر از سه حرف هیچ سه‌حرفی ندارد، پس از فهرست کاری برنمی‌آید. و سه‌حرف‌های بسیار رایج، مثل «است»، تقریباً در همه چیز هستند، پس فهرستشان به‌تنهایی هیچ چیز را کوچک نمی‌کند.The trick is that any fragment of three characters, wherever it sits in a word, contains a three-letter run. So if you list every consecutive triple, no match can hide. Then you take the triples of your own pattern, pull each list and keep only the places present in all of them; finally you look at those few candidates by eye. Two limits follow. A pattern shorter than three characters has no trigram at all, so the list cannot help. And very common triples, like “ing”, appear almost everywhere, so their list alone narrows nothing.

و بعدش، فنیAnd now, technically

ساخت ایندکس یعنی برای هر رشته یک پنجرهٔ سه‌حرفی روی متن بلغزانی و هر سه‌حرف را به فهرست شناسهٔ رکوردها اضافه کنی؛ برای این‌که ابتدا و انتهای رشته هم گرفته شود، رشته را با یک نشانگر مرزی پر می‌کنند. پرس‌وجو دو مرحله دارد: از الگو، مثل LIKE با درصد در دو طرف یا یک عبارت باقاعده، تکه‌های سه‌حرفیِ ثابت را بیرون می‌کشی، فهرست‌ها را اشتراک می‌گیری، و بعد کاندیدهای باقی‌مانده را با خود الگو بررسی می‌کنی. هزینه تقریباً به اندازهٔ کوتاه‌ترین فهرست است، نه به اندازهٔ کل جدول. اندازهٔ ایندکس با تعداد سه‌حرف‌های متمایز هر رشته بالا می‌رود و می‌تواند از خود متن بزرگ‌تر شود. نرمال‌سازی، حساسیت به حروف بزرگ و کوچک و فاصله‌ها باید از قبل تصمیم گرفته شود، وگرنه دو رشتهٔ یکسان دو کلید متفاوت می‌گیرند.Building the index means sliding a three-character window over each string and appending each triple to the posting list of that string's id; boundary markers are padded in so prefixes and suffixes are covered too. A query has two stages: pull the fixed triples out of the pattern — a LIKE with wildcards on both sides, or a regular expression — intersect their lists, then check the surviving candidates against the real pattern. Cost is roughly the shortest list, not the whole table. Index size grows with the number of distinct triples per string and can exceed the text itself. Normalisation, case sensitivity and whitespace must be decided up front, or two identical strings end up with different keys.

3طول پنجره؛ کوتاه‌ترین زیررشته‌ای که ایندکس می‌شودwindow length: the shortest substring an index can hold
≈ nبرای رشته‌ای با n حرف، حدود n سه‌حرفabout n triples for a string of n characters
1–2الگوهایی با این تعداد حرف، از ایندکس رد می‌شوندpatterns this short get no help from the index

تلهٔ رایجThe usual trap

ساختن ایندکس سه‌حرفی و انتظار سرعت برای جست‌وجوی دو حرفی یا تک‌حرفی. آن پرس‌وجوها هیچ سه‌حرفی ندارند، پس پلنر مجبور است کل جدول را بخواند؛ در حالی که تیم فکر می‌کند «ایندکس داریم». کوتاه‌ترین طول الگویی که پشتیبانی می‌کنید را از قبل بدانید و در رابط کاربری هم همان را اعمال کنید.Building a trigram index and expecting speed for a two- or one-character search. Those queries have no trigram at all, so the planner falls back to reading the whole table while the team believes the index covers them. Decide the shortest pattern you support and enforce it in the interface too.

vector index

ایندکس برداری فصل ۴Chapter 4 · دیدن در متنsee in context

«نزدیک‌ترین معنی» را چطور پیدا می‌کنی؟How do you find the nearest meaning?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

یک کتاب را دوست داشتی و می‌روی کتاب‌فروشی. نمی‌گویی اسم کتاب را بیاور؛ می‌گویی «چیزی شبیه همین». فروشنده هم ده هزار کتاب را از حفظ نیست؛ فقط می‌داند کدام قفسه نزدیک‌تر است و همان‌جا را نشان می‌دهد. ایندکس برداری همین کار را می‌کند: به‌جای گشتن در همه، سراغ نزدیک‌ترین قفسه‌ها می‌رود؛ و ممکن است کتاب درست یک قفسه آن‌طرف‌تر باشد.You loved a book, so you walk into a bookshop. You do not ask for the title; you say “something like this one”. The bookseller does not know all ten thousand books by heart, but knows which shelf sits nearest and points there. A vector index does the same: instead of searching everything it goes to the nearest shelves, and the right book may be one shelf further along.

تشبیه و تصویر ذهنیThe analogy

قفسه‌بندی بر اساس حال‌وهوا یک تصمیم دائمی است. کتابی که هم غمگین است هم ماجراجو فقط در یک قفسه جا می‌گیرد و از قفسهٔ دیگر جا می‌ماند. کتاب تازه هم تا کسی آن را در قفسه‌ای نگذارد، عملاً پیدا نمی‌شود. اگر مشتری بگوید «کمی غمگین‌تر از این، ولی نه خیلی»، فروشنده باید چند قفسه را نگاه کند و همان‌جا است که سرعت کم می‌شود. اگر قفسه‌ها را از نو بچینی همه‌چیز بهتر می‌شود، ولی تا وقتی نچیده‌اند جست‌وجو با نقشهٔ قدیمی انجام می‌شود. یک پرسش هم هست که با قفسه هرگز جواب نمی‌گیری: «کدام سه تایشان ارزان‌ترند؟» چون قفسه‌ها بر اساس قیمت مرتب نشده‌اند.Shelving by mood is a permanent decision. A book that is both sad and adventurous fits one shelf and is lost to the other. A new book is effectively unfindable until someone shelves it. If a customer says “a bit sadder than this, but not much”, the bookseller has to check several shelves, and that is where the speed goes. Reshelving everything helps, but until then searches run against the old map. And one question the shelves can never answer: which three of these are cheapest, since nothing is ordered by price.

HNSW · گرافHNSW · graphساخت: درج تکیbuild: insert one by oneحافظه: بردار + یالmemory: vectors + linksحذف: نشانه‌گذاریdelete: mark onlyIVF · خوشهIVF · clustersساخت: خوشه‌بندی دسته‌ایbuild: batch clusteringحافظه: بردار + مرکزهاmemory: vectors + centroidsحذف: بازآموزی خوشه‌هاdelete: retrain clusters
دو راه برای نزدیک شدن به جواب درست: پیمایش یک گراف چندلایه، یا گشتن در چند خوشهٔ نزدیک.Two ways to get near the right answer: walk a layered graph, or search a few nearby clusters.

و بعدش، فنیAnd now, technically

ایندکس برداری روی بردارهای عددی کار می‌کند: هر آیتم به یک بردار با چند صد بُعد تبدیل می‌شود و «شبیه» یعنی نزدیک از نظر فاصله، معمولاً کسینوسی یا اقلیدسی. خود بردارها بیشترین حافظه را می‌برند: یک میلیون بردار ۷۶۸ بُعدی از نوع float32 حدود سه گیگابایت است، پیش از آن‌که ایندکس چیزی اضافه کند. دو ساختار رایج دارد. HNSW یک گراف چندلایه می‌سازد و با پیمایش حریصانه به همسایه‌های نزدیک‌تر می‌رود؛ درج تکی انجام می‌شود، ولی گراف حافظه و یال می‌خواهد و حذف واقعی در آن سخت است. IVF نقاط را با k-means خوشه‌بندی می‌کند و فقط چند خوشهٔ نزدیک را می‌گردد؛ ساختش دسته‌ای است و اگر توزیع داده عوض شود خوشه‌ها کهنه می‌شوند. در هر دو جواب تقریبی است: کیفیت را با recall@k می‌سنجند و جست‌وجوی دقیق، که فاصله تا همه را حساب می‌کند، مبنای همین سنجش است.A vector index works on numeric vectors: each item becomes a vector of a few hundred dimensions, and similar means close, usually by cosine or Euclidean distance. The vectors themselves dominate memory: a million 768-dimensional float32 vectors are about three gigabytes before the index adds anything. Two structures are common. HNSW builds a layered graph and walks greedily toward closer neighbours; inserts are one at a time, but the graph costs memory and edges, and true deletion is awkward. IVF clusters the points with k-means and searches only a few nearby clusters; it is built in batches, and if the data distribution shifts the clusters go stale. Both are approximate: quality is measured by recall@k, with exact search over every point as the yardstick.

N × d × 4حافظهٔ خام بردارها: N بردار d بُعدی از نوع float32raw vector memory: N vectors, d dimensions, float32
384–1536بازهٔ معمول تعداد بُعدهای embeddinga typical range of embedding dimensions
recall@kمعیار کیفیت: چند درصد از k همسایهٔ واقعی برگشتهquality: what share of the true k neighbours came back

چرا تقریبی است، نه فقط کندWhy it is approximate, not merely slow

در فضای دوبعدی می‌شود نقطه‌ها را مرتب کرد و با جست‌وجوی دودویی نزدیک‌ترین را یافت؛ در چند صد بُعد چنین ترتیبی وجود ندارد که همهٔ معنی‌ها را حفظ کند. ایندکس برداری به‌جای مرتب کردن، فضا را هرس می‌کند: گراف یا خوشه‌ها می‌گویند کجا بعید است جواب باشد، و همین هرس کردن است که گاهی جواب درست را هم بیرون می‌گذارد. پس تقریب یک نقص پیاده‌سازی نیست، نتیجهٔ مستقیم همین کار است. برای همین هم کیفیت با recall سنجیده می‌شود، نه با درست یا غلط.In two dimensions you can sort points and binary-search the nearest one; in a few hundred dimensions no such order preserves all the meaning. A vector index prunes space instead of sorting it: the graph or the clusters say where the answer probably is not, and that same pruning sometimes throws the right answer out. So approximation is not an implementation defect, it is the direct result of the method. That is why quality is measured by recall rather than right or wrong.

فیلتر کردن، جایی که همه گیر می‌کنندFiltering, where everyone gets stuck

در عمل هیچ‌کس فقط «شبیه‌ترین» را نمی‌خواهد؛ می‌خواهد «شبیه‌ترین کتاب‌های فارسی که موجودند». اگر اول فیلتر کنی و بعد بگردی، ممکن است آن‌قدر کاندید کم شود که گراف یا خوشه‌ها به جواب نرسند و کمتر از k نتیجه بگیری. اگر اول بگردی و بعد فیلتر کنی، ممکن است بعد از فیلتر صفر نتیجه بمانی. راه عملی این است که فیلتر را داخل پیمایش اعمال کنی، یا ایندکس را بر اساس یک بُعد پرکاربرد مثل زبان یا مشتری تکه‌تکه نگه داری تا هر پرس‌وجو فقط بخش خودش را بگردد.In practice nobody wants only the most similar item; they want the most similar Persian books that are in stock. Filter first and search second, and the candidate pool can shrink so far that the graph or the clusters never reach the answer, so you get fewer than k results. Search first and filter second, and you can end up with zero. The workable answer is to apply the filter inside the walk, or to keep the index partitioned by a common dimension such as language or tenant so each query only touches its own slice.

تلهٔ رایجThe usual trap

بعد از عوض کردن مدل embedding، بردارهای قدیمی را نگه داشتن و بردارهای تازه را کنارشان گذاشتن. دو مدل مختلف دو فضای مختصات مختلف می‌سازند؛ فاصله بین یک بردار قدیمی و یک بردار تازه معنا ندارد، ولی ایندکس هیچ خطایی نمی‌دهد و جواب‌های بی‌معنی را با همان اطمینان قبلی برمی‌گرداند.Keeping the old vectors after swapping the embedding model and adding the new ones beside them. Two models define two different coordinate spaces; the distance between an old vector and a new one means nothing, yet the index raises no error and returns nonsense with all its former confidence.

WAL

لاگ پیش‌نوشت فصل ۴Chapter 4 · دیدن در متنsee in context همچنینalso in فصل ۸ch 8

اگر برق برود، از کجا می‌فهمی چه کاری انجام شده؟If the power dies, how do you know what already happened?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

قبل از اینکه بروی خرید، یک تکه کاغذ برمی‌داری و می‌نویسی «نان، شیر، تخم‌مرغ». حالا اگر وسط راه کسی زنگ بزند و ذهنت پاک شود، لازم نیست همه چیز را از حفظ یادت بیاید؛ همان کاغذ مسیر را به تو برمی‌گرداند. WAL هم همین کاغذ است، فقط برای دیتابیس.Before you leave for the shop you grab a scrap of paper and write “bread, milk, eggs”. If someone calls and your head empties, you do not have to reconstruct the plan from memory; the paper hands it back. A WAL is that scrap of paper, for a database.

تشبیه و تصویر ذهنیThe analogy

رستورانی را تصور کن که آشپز وقت ندارد هر سفارش را همان لحظه در دفتر حساب ثبت کند. مسئول صندوق اول سفارش را روی یک نوار کاغذی دنباله‌دار می‌زند: میز چهار، دو پرس، ساعت ۲۰:۱۴. این نوار ارزان است و فقط یک سرش اضافه می‌شود، پس سریع نوشته می‌شود. ثبت در دفتر اصلی (حساب‌ها، موجودی، گزارش روزانه) بعداً و با حوصله انجام می‌شود. اگر وسط شب برق برود، نوار کاغذی همان جاست و از رویش همه چیز بازسازی می‌شود. تنها چیزی که نباید گم شود، نوار است؛ بقیه قابل بازسازی است.Imagine a restaurant whose chef has no time to update the ledger for every order. The cashier first writes each order on a long paper roll: table four, two portions, 20:14. The roll is cheap and only ever appended to, so writing to it is fast. Updating the real ledger — accounts, stock, the daily report — happens later and with care. If the power dies at midnight, the roll is still there and everything is rebuilt from it. The only thing that must not be lost is the roll; the rest is recomputable.

درخواست نوشتنWrite requestکلاینتclientافزودن به WALAppend to WALترتیبی، سریعsequential, fastبه‌روزرسانی حافظهUpdate memoryصفحه یا memtablepage or memtableپاسخ موفقAck the writeحالا پایدار استnow it is durable
مسیر نوشتن: اول لاگ ترتیبی روی دیسک، بعد ساختار حافظه، و فقط بعد پاسخ به کلاینت.The write path: the sequential log on disk first, the in-memory structure second, the client's answer last.

و بعدش، فنیAnd now, technically

WAL یعنی هر تغییر، پیش از اعمال شدن روی ساختار اصلی، به‌صورت رکوردهای فقط-افزودنی روی دیسک نوشته می‌شود. کلید ارزان بودنش این است که نوشتن ترتیبی است: دیسک و SSD برای نوشتن دنباله‌ای چند برابر سریع‌تر از نوشتن تصادفی در جاهای مختلف کار می‌کنند. مرز دوام با fsync مشخص می‌شود؛ نوشتن در بافر سیستم‌عامل یعنی «شاید از دست برود»، fsync یعنی «روی رسانه نشسته است». یک تراکنش وقتی کامیت‌شده حساب می‌شود که رکوردش در WAL پایدار شده باشد، و همین است که می‌شود یک write را قبل از رسیدن به صفحه‌های اصلی به کلاینت تأیید کرد. در بازیابی، موتور از آخرین چک‌پوینت WAL را بازپخش می‌کند و وضعیت را می‌سازد.A WAL writes every change as append-only records on disk before touching the main structure. What makes it cheap is that it is sequential: disks and SSDs sustain far higher throughput on sequential appends than on random in-place writes. The durability boundary is fsync; sitting in the operating system's buffer means “might be lost”, sitting on the medium means “it happened”. A transaction is committed when its WAL record is durable, which is exactly why a write can be acknowledged before the main pages are updated. On recovery the engine replays the log from the last checkpoint and rebuilds the state.

1 fsyncمعمولاً چند دهم میلی‌ثانیه روی SSD؛ گران‌ترین بخش هر کامیتusually a few tenths of a millisecond on an SSD; the priciest part of a commit
5–10×برتری معمول نوشتن ترتیبی بر تصادفی روی SSDtypical sequential-over-random write advantage on an SSD
N writesبا group commit، چند کامیت در یک fsync جمع می‌شوندwith group commit, several commits share one fsync

چرا اول لاگ، بعد خود داده؟Why log first, data second

اگر ساختار اصلی در جای خودش به‌روز شود، هر نوشتن چند صفحه را لمس می‌کند و این صفحات روی دیسک پخش‌اند؛ نتیجه نوشتن تصادفی و کند است. بدتر، اگر خرابی وسط نوشتن رخ دهد، بعضی صفحه‌ها تازه‌اند و بعضی قدیم و ساختار ناسازگار می‌شود. لاگ هر دو مشکل را حل می‌کند: یک دنبالهٔ ترتیبی است، پس ارزان است، و یک نقطهٔ حقیقت دارد، پس بازیابی فقط کافی است از انتهای سالم ادامه دهد. ساختار اصلی می‌تواند هر وقت، با حوصله و به‌صورت گروهی به‌روز شود.Updating the main structure in place touches several pages per write, and those pages are scattered on disk, which turns one logical write into many random ones. Worse, a crash mid-write leaves some pages new and some old, which corrupts the structure. A log fixes both: it is one sequential stream, so it is cheap, and it has a single truth boundary, so recovery just resumes from the last good point. The main structure can then be updated later, calmly and in batches.

قیمتش را کجا می‌دهیWhere the bill arrives

هر نوشتن دو بار انجام می‌شود: یک بار در لاگ، یک بار در ساختار اصلی. این همان write amplification است و روی SSD که تعداد نوشتن عمرش را می‌کاهد، مستقیماً پول است. راه‌حل‌های عملی سه‌تاست: group commit برای جمع کردن چند fsync در یکی، چک‌پوینت دوره‌ای تا لاگ بی‌نهایت رشد نکند، و فشرده‌سازی دوره‌ای روی بخش‌های قدیمی. اگر لاگ را روی همان دیسکی بگذاری که داده روی آن است، نوشتن لاگ، نوشتن داده را کند می‌کند؛ به همین دلیل سیستم‌های جدی گاهی لاگ را روی دیسک جدا می‌برند.Every write happens twice: once in the log, once in the structure. That is write amplification, and on an SSD, where write counts shorten life, it is money. Three practical answers exist: group commit to share one fsync across several commits, periodic checkpoints so the log cannot grow forever, and background compaction of the old segments. And if the log lives on the same device as the data, log writes slow data writes down, which is why serious systems sometimes put the log on its own device.

تلهٔ رایجThe usual trap

تأیید کردن نوشتن پیش از fsync. خیلی‌ها فکر می‌کنند «نوشتم تو لاگ» یعنی پایدار شد، در حالی که تا وقتی سیستم‌عامل بافر را روی رسانه ننشانده، یک قطعی برق همه‌اش را می‌برد — و آن‌وقت کشف می‌کنی تراکنشی که به مشتری «ثبت شد» گفتی، هیچ‌جا نیست.Acknowledging a write before fsync. Many assume “it is in the log” means durable, but until the operating system has pushed its buffer to the medium a power cut erases it — and you discover that a transaction you told the customer was recorded exists nowhere.

write amplification

تقویت نوشتن فصل ۴Chapter 4 · دیدن در متنsee in context

یک بایت بنویسی، رسانه چند بایت می‌نویسد؟You write one byte; how many does the medium write?

مثال روزمره، بدون اصطلاحThe everyday one, no jargon

فرم اداری را پر کرده‌ای و یک کلمه‌اش غلط است. کارمند می‌گوید این فرم قابل اصلاح نیست و باید کل فرم را از نو بنویسی. یک کلمه را عوض کردی، ولی سه برگ کاغذ مصرف شد. تقویت نوشتن همین را اندازه می‌گیرد: به ازای هر چیزی که نوشتی، واقعاً چند برابر نوشته شد.You filled in an official form and one word is wrong. The clerk says the form cannot be corrected and the whole thing must be rewritten. You changed one word and used up three sheets of paper. Write amplification measures exactly that: for each thing you wrote, how many times over it was really written.

تشبیه و تصویر ذهنیThe analogy

دفتری که قانونش «هر اصلاح، بازنویسی کل صفحه» است، برای بازرسی خوب است و برای نوشتن بد. دفتر دیگری که حاشیه دارد و اجازه می‌دهد خط تازه اضافه کنی، سریع است، ولی برای پیدا کردن آخرین نسخه باید کل حاشیه را بخوانی. این همان معاملهٔ اصلی است: تقویت نوشتن، تقویت خواندن و تقویت فضا سه صورت‌حساب از یک بودجه‌اند و نمی‌شود هر سه را هم‌زمان کوچک کرد. هر بار که یکی را بهینه می‌کنی، ببین کدام یکی بزرگ‌تر شده؛ معمولاً همان است که یک ماه بعد اذیتت می‌کند.A ledger whose rule is “every correction rewrites the whole page” is good for auditing and bad for writing. Another that leaves wide margins and lets you append a fresh line is fast to write, but to find the latest version you must read all the margins. That is the core trade: write, read and space amplification are three bills from one budget, and you cannot shrink all three at once. Whenever you optimise one, look at which one grew; that is usually the one that bites a month later.

1×فقط لاگlog only2–5×درخت BB-tree4–10×LSM · tieredLSM tiered10–30×LSM · leveledLSM leveled
هر خانواده یک بهای نوشتن دارد؛ این‌ها مرتبهٔ بزرگی‌اند، نه اندازه‌گیری یک سیستم خاص.Each family pays a different write bill; these are orders of magnitude, not one system measured.

و بعدش، فنیAnd now, technically

تقویت نوشتن نسبت بایت‌های نوشته‌شده روی رسانه به بایت‌های نوشته‌شده توسط برنامه است؛ عدد دو یعنی هر بایت دو بار نوشته شد. چهار منبع دارد. اول، واحد نوشتن: رسانه ۴ تا ۸ کیلوبایت را یک‌جا می‌نویسد، پس تغییر ۱۰۰ بایت در یک صفحه یعنی نوشتن کل صفحه؛ WAL این را کم می‌کند چون رکورد کوچک و ترتیبی است، ولی صفحه در چک‌پوینت باید یک بار نوشته شود. دوم، compaction در LSM: هر بایت در طول عمرش چند بار با فایل‌های هم‌سطح ادغام می‌شود و با leveled compaction به ده تا سی برابر می‌رسد. سوم، خود SSD: کنترلر داده را در بلوک‌های پاک‌شدنی می‌نویسد و برای دور ریختن یک بلوک، دادهٔ سالم بقیهٔ بلوک را جابه‌جا می‌کند. چهارم، replication که نسخه‌ها را زیاد می‌کند ولی تقویت محلی را عوض نمی‌کند.Write amplification is bytes written to the medium divided by bytes written by the application; a value of two means every byte was written twice. It has four sources. First, the write unit: the medium writes four to eight kilobytes at a time, so changing one hundred bytes in a page writes the whole page; the WAL reduces this because its records are small and sequential, but the page still has to be written once at checkpoint. Second, LSM compaction: each byte is merged with files at its level several times over its life, reaching ten to thirty times under leveled compaction. Third, the SSD itself: the controller writes in erasable blocks, and to reclaim one block it relocates the surviving data inside it. Fourth, replication, which multiplies copies but does not change local amplification.

10–30×تقویت نوشتن معمول LSM با compaction سطح‌بندی‌شدهtypical LSM write amplification under leveled compaction
4–8 KBواحد نوشتن؛ تغییر کوچک، نوشتن کل واحدthe write unit; a small change writes the whole unit
3تقویت‌هایی که با هم معامله می‌کنند: نوشتن، خواندن، فضاthe three that trade off: write, read, space

سه تقویت، یک بودجهThree amplifications, one budget

نوشتن، خواندن و فضا سه هزینهٔ جدا نیستند؛ سه راه برای پرداخت همان کارند. درخت LSM با نوشتن ارزان شروع می‌کند، ولی نسخه‌های مرده را نگه می‌دارد و برای هر خواندن باید چند فایل را ببیند. درخت B نوشتن را گران‌تر می‌کند تا خواندن پیش‌بینی‌پذیر بماند و فضا هدر نرود. leveled compaction در LSM تعادل را به سمت خواندن می‌برد و نوشتن را گران می‌کند؛ size-tiered برعکس. پس سؤال درست «کدام سریع‌تر است» نیست، «کدام صورت‌حساب را می‌توانی بپردازی» است: اگر بار نوشتنی سنگین داری، خواندن اضافه را تحمل کن.Write, read and space are not three separate costs; they are three ways to pay for the same work. An LSM starts cheap on writes but keeps dead versions and checks several files per read. A B-tree writes more so that reads stay predictable and space is not wasted. Leveled compaction in an LSM shifts the balance toward reads and makes writes expensive; size-tiered does the reverse. So the real question is not which is faster but which bill you can afford: with a heavy write load, accept the extra reads.

چرا روی SSD مهم‌تر استWhy it matters more on an SSD

هر سلول حافظهٔ فلش تعداد محدودی نوشتن و پاک کردن را تحمل می‌کند، و تقویت نوشتن همان تعداد را چند برابر می‌کند: سی برابر نوشتن برنامه یعنی سی برابر ساییدگی، حتی اگر سرعت امروز خوب باشد. این هزینه در ابتدا دیده نمی‌شود و بعد از ماه‌ها به‌صورت افت توان نوشتن یا دیسکی که ناگهان فقط خواندنی می‌شود ظاهر می‌شود. برای همین باید بایت‌های رسانه را اندازه بگیری، نه بایت‌های برنامه را؛ شمارنده‌های خود دیسک و آمار موتور هر دو این را نشان می‌دهند. فضای آزاد هم مهم است: SSD پرتر، برای هر نوشتن جابه‌جایی بیشتری می‌کند.Every flash cell tolerates a limited number of writes and erases, and write amplification multiplies them: thirty times the application's writes is thirty times the wear, even if today's speed looks fine. The bill is invisible at first, then shows up months later as falling write throughput or a disk that abruptly goes read-only. That is why you measure the medium's bytes, not the application's; the drive's own counters and the engine's metrics both show it. Free space matters too: the fuller the SSD, the more it must shuffle for each write.

تلهٔ رایجThe usual trap

نگاه کردن به بایت‌های برنامه و نتیجه گرفتن این‌که «ما فقط چند مگابایت در ثانیه می‌نویسیم». عددی که عمر دیسک و توان واقعی را تعیین می‌کند، بایت‌های رسانه است و می‌تواند بیست سی برابر بزرگ‌تر باشد.Watching application bytes and concluding “we only write a few megabytes a second”. The number that decides disk life and real throughput is the medium's bytes, and it can be twenty or thirty times larger.