Skip to content

Choosing a Database: Model the Queries, SQL vs NoSQL, Redis vs DynamoDB, Polyglot Persistence ​

"You shouldn't start designing your schema for DynamoDB until you know the questions it will need to answer." — Amazon Web Services، NoSQL design for DynamoDB، Amazon DynamoDB Developer Guide

خلاصه (Summary): انتخاب پایگاه داده تصمیمی دربارهٔ کوئری‌هاست، نه دربارهٔ برندها. هر الگوی دسترسی را با نرخ و شکلش بنویسید، نیاز سازگاری و تراکنش، سقف مقیاس، SLO تأخیر و آنچه تیم واقعاً می‌تواند اداره کند را کنارش بگذارید؛ آن وقت انتخاب تا حد زیادی خودش معلوم می‌شود. بیشتر سیستم‌ها در نهایت PostgreSQL را منبع حقیقت نگه می‌دارند و یکی دو store تخصصی را با CDC تغذیه می‌کنند. تمرکز (Focus): الگوی دسترسی و شکل کوئری (point lookup، range scan، full-text search، aggregation، graph traversal)، نسبت خواندن به نوشتن، نیاز سازگاری و تراکنش، نوسان schema، سقف مقیاس، SLO تأخیر، بلوغ عملیاتی، سرویس مدیریت‌شده، هزینه و lock-in؛ نقاط قوت رابطه‌ای و جایی که کم می‌آورد؛ embedding در برابر referencing در MongoDB؛ single-table design در DynamoDB و Cassandra؛ Redis به‌عنوان store اصلی یا cache؛ پایگاه‌های جست‌وجو، time series، گراف، برداری، distributed SQL و serverless؛ polyglot persistence به‌ازای هر bounded context؛ مهاجرت بین storeها با dual write، backfill و shadow read. هدف یادگیری (Learning goal): برای یک سیستم تازه جدول الگوهای دسترسی بسازید، برای هر bounded context یک store با دلیل یک‌خطی انتخاب کنید، طراحی کلید یا schema‌ای را نشان دهید که همهٔ الگوها را جواب می‌دهد، و مسیر رفتن به store دیگر را بدون cutover یک‌باره برنامه‌ریزی کنید.

این فصل در گروه Consistency & Distributed Data از مسیر system-design است و صاحب تصمیم است: ورودی‌ها، جدول‌های بده‌بستان و طراحی‌های کارشده. خود خانواده‌ها در NoSQL: Families & Data Models نقشه‌برداری شده‌اند و هر موتور صفحهٔ عمیق خودش را دارد: PostgreSQL، MongoDB، Redis، Cassandra و DynamoDB، پایگاه‌های گراف، Full-Text Search، Vector Search و pgvector، Distributed SQL و OLTP در برابر OLAP. روش سطح داده (از نیازمندی تا schema) در Database System Design است؛ partition key و hot partition در سطح سیستم در Sharding at System Level؛ سازوکار همگام نگه‌داشتن storeها در Transactional Outbox و Change Data Capture.

نقشهٔ صفحه ​

دنبال چه هستیدبروید به
کل تصمیم در سه جدولهمه‌چیز در یک دقیقه
چرا «SQL یا NoSQL» سؤال اول اشتباهی استچرا وجود دارد
polyglot persistence فاولر، Dynamo، single-table designاز کجا آمده
ورودی‌ها: الگوی دسترسی، سازگاری، schema، مقیاس، عملیاتالگوی دسترسی، سازگاری و تراکنش، نوسان schema، سقف مقیاس و تأخیر، عملیات، هزینه، lock-in
خانواده‌های store، هر کدام یک بلوکرابطه‌ای، سندی، key-value و wide-column، Redis، جست‌وجو، time series، گراف، برداری، Distributed SQL، Serverless
یک store برای هر bounded contextPolyglot persistence
رفتن از یک store به دیگریمهاجرت
واحدها، محدودیت‌ها، تنظیم‌ها، کدهای خطاسازوکار
کدGo، Laravel
اشتباه‌های کلاسیک و راه‌حلشانحل مسئله‌های کلاسیک
جدول تصمیم و سه طراحی کارشدهانتخاب
از monolith تا سیستم توزیع‌شدهدر معماری
اندازه‌گیری و contract testی که اجرا می‌شودآزمایشگاه
باورهای غلط، چکیده، خودآزمایی، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

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

شکل کوئری خانواده را تعیین می‌کند.

شکل کوئری (Query shape)به زبان سادهمثال کوچکجای طبیعیجایی که کم می‌آورد
جست‌وجوی نقطه‌ای (Point lookup)یک چیز را با کلیدش بیاورGET order 01J9Aهر storeی؛ key-value در مقیاس بالا ارزان‌ترین استهیچ‌جا، تا وقتی یک کلید داغ شود
پیمایش بازه روی یک کلید (Range scan)N مورد آخرِ یک مالک۲۰ سفارش آخر مشتری ۴۲ایندکس B-tree در PostgreSQL، sort key در DynamoDB و Cassandraبازه روی چند مالک در storeهای key-value
تراکنش چندموجودیتیچند چیز با هم عوض شوند یا هیچ‌کدامسفارش + موجودی + ردیف پرداخترابطه‌ای، distributed SQLkey-value (تراکنش محدود)، سند در چند سند
کوئری ad-hoc و joinسؤالی که کسی برایش برنامه نریخته«درآمد هر منطقه از مشتریانی که دو بار مرجوع کرده‌اند»رابطه‌ای، بعد انبار دادهkey-value و wide-column (بدون join)
جست‌وجوی متنی (Full-text search)پیدا کردن با کلمه و رتبه‌بندی با ارتباط«کفش دویدن قرمز سایز ۴۲»Elasticsearch، OpenSearch؛ برای حجم کم FTS در PostgreSQLهر store عملیاتی در مقیاس بالا
تجمیع (Aggregation) روی ردیف‌های زیادجمع، شمارش، صدک در طول زماندرخواست در دقیقه به‌ازای هر endpointClickHouse، TimescaleDB، InfluxDBstoreهای ردیفی روی primary
پیمایش گراف (Graph traversal)دنبال کردن رابطه‌ها در چند گامدوستانِ دوستانی که X را دوست دارندNeo4j؛ SQL بازگشتی برای موارد کم‌عمقjoin بیش از ۲ تا ۳ گام
شباهت (Similarity)نزدیک‌ترین همسایه‌های یک بردار«محصولات شبیه این عکس»pgvector، بعد پایگاه برداری اختصاصیstoreهای تطبیق دقیق

وعده و بهای هر خانواده.

خانوادهقوتبهامحصولات
رابطه‌ای (Relational)join، constraint، foreign key، تراکنش، SQL ad-hoc، ابزار پختهمقیاس نوشتن فراتر از یک primary کار sharding می‌خواهدPostgreSQL، MySQL، SQL Server، Oracle، SQLite
سندی (Document)aggregate یک‌جا ذخیره و خوانده می‌شود؛ فیلدهای منعطفinvariantهای بین‌سندی و join ضعیف‌ترندMongoDB، Couchbase، Firestore
Key-value / wide-columnتأخیر قابل‌پیش‌بینی در هر اندازه، افقی از روز اولفقط کوئری‌هایی که طراحی کرده‌اید؛ بدون joinDynamoDB، Cassandra، ScyllaDB، Bigtable
ساختار داده در حافظهخواندن میکروثانیه‌ای، شمارنده، set، streamهزینهٔ RAM؛ پایداری یک تنظیم است نه پیش‌فرضRedis، Valkey، Memcached (فقط cache)
موتور جست‌وجوارتباط، facet، typeaheadنسخهٔ مشتق‌شده، eventual، منبع حقیقت نیستElasticsearch، OpenSearch، Solr
Time series / ستونیتجمیع سریع، فشرده‌سازیبه‌روزرسانی نقطه‌ای و تراکنش ضعیفTimescaleDB، InfluxDB، ClickHouse
گرافپیمایش عمیق با عمق متغیرمهارت کمیاب؛ ضعیف در تجمیع انبوهNeo4j، Amazon Neptune
برداری (Vector)جست‌وجوی تقریبی نزدیک‌ترین همسایهتنظیم recall در برابر تأخیر، حافظهpgvector، Qdrant، Milvus، Pinecone
Distributed SQL (NewSQL)SQL و تراکنش روی چند گره و چند regionتأخیر هر نوشتن، هزینه، افزونهٔ کمترSpanner، CockroachDB، YugabyteDB، Vitess (MySQL شاردشده)

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

ورودیسؤالپاسخ نمونه
الگوی دسترسی (Access pattern)کدام کوئری‌ها، چند بار در ثانیه، با چه شکلی؟AP1 ثبت سفارش 200/s، AP2 گرفتن سفارش 1,500/s، AP3 سفارش‌های اخیر 400/s
نسبت خواندن به نوشتن (Read/write ratio)بیشتر خواندن، بیشتر نوشتن، یا هر دو؟10:1 برای سفارش؛ 1:50 برای telemetry
نیاز سازگاری (Consistency requirement)خواننده می‌تواند مقدار کهنه ببیند؟ تا چه مدت؟وضعیت سفارش: read-your-writes؛ پیشنهادها: چند دقیقه
نیاز تراکنش (Transaction requirement)کدام invariantها بیش از یک موجودیت را درگیر می‌کنند؟موجودی هنگام ثبت سفارش هرگز منفی نشود
نوسان schema (Schema volatility)فیلدها هر چند وقت عوض می‌شوند و چه کسی کنترلشان می‌کند؟ویژگی‌های محصول در هر دسته فرق دارد و هر هفته عوض می‌شود
سقف مقیاس (Scale ceiling)اندازه و نرخ نوشتن در سه سال؟ چند region؟140 GB در سال سفارش، یک region
SLO تأخیر (Latency SLO)صدک ۹۹ هدف برای هر الگوp99 برای AP2 زیر 20 ms
بلوغ عملیاتی (Operational maturity)ساعت ۳ بامداد چه کسی آن را اداره می‌کند؟ سرویس مدیریت‌شده هست؟دو توسعه‌دهندهٔ backend، بدون DBA: فقط managed
هزینه و lock-inقیمت هر درخواست، هر GB، هر گره؛ راه خروج؟DynamoDB on-demand در برابر Aurora؛ خروجی از طریق S3
1. Write the access patternsQPS, read:write, point/range/search/agg/graph2. Invariants across entities?transactions, foreign keys, ad-hoc queries3. Fits one primary + replicas?storage, write QPS, regions, latency SLOyesno, fewknownyesnoKey-value / wide-columnDynamoDB, Cassandra: single tableDocument storeMongoDB: aggregate read wholePostgreSQL by defaultrelational + JSONB + pgvectorDistributed SQLSpanner, CockroachDB, YugabyteDB, VitessAdd per patternonly when the main store strainsfull-text, facets:Elasticsearch / OpenSearchtime series, analytics:TimescaleDB, InfluxDB, ClickHousedeep traversals:Neo4jsimilarity:pgvector, then a vector DBcache, sessions, counters:Redisfed by CDC / outboxnever by dual writesplus

این تصویر روش کل فصل است. از الگوهای دسترسی شروع کنید، بپرسید آیا invariantها چند موجودیت را درگیر می‌کنند، و بپرسید آیا یک primary با replicaها بار را می‌کشد. بیشتر پاسخ‌ها به PostgreSQL می‌رسند. storeهای تخصصی در ستون راست به‌ازای هر الگو اضافه می‌شوند، با CDC یا outbox تغذیه می‌شوند و هرگز با نوشتن هم‌زمان برنامه در دو store.

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

هر پایگاه داده مجموعه‌ای از بده‌بستان‌هاست که در یک چیدمان ذخیره‌سازی منجمد شده. یک B-tree روی یک primary هر کوئری‌ای را که بتوانید به SQL بنویسید و تراکنش قوی می‌دهد، اما ظرفیت نوشتنش یک ماشین است. یک store کلید-مقدار با partitionبندی hash هر مقیاسی می‌دهد، اما فقط برای کوئری‌هایی که کلیدهایش برایشان طراحی شده. AWS این تفاوت را در راهنمای طراحی خودش گفته: در RDBMS "data can be queried flexibly, but queries are relatively expensive and don't scale well in high-traffic situations" و در DynamoDB "data can be queried efficiently in a limited number of ways, outside of which queries can be expensive and slow". تصمیم این است که برای هر workload با کدام‌یک از این دو جمله می‌توانید زندگی کنید.

storeهای کوئری‌منعطف (رابطه‌ای)storeهای کوئری‌طراحی‌شده (key-value، wide-column)
اول normalize، وقتی سؤال آمد ایندکس اضافه کناول سؤال‌ها را بدان، کلیدها را برای جوابشان شکل بده
join، constraint و تراکنش داخل موتورتکرار داده و invariant در برنامه
سؤال تازه = SQL تازه، شاید یک ایندکسسؤال تازه = ایندکس تازه یا backfill آیتم‌های تازه
اول عمودی، بعد با replica و کار sharding افقیبا افزودن partition افقی، در سرویس‌های managed خودکار
تأخیر به planی بستگی دارد که optimizer انتخاب می‌کندتأخیر صاف است چون هر کوئری lookup کلید یا بازه روی یک کلید است
اشتباه را بعداً ارزان می‌شود درست کرداشتباه در طراحی کلید بعداً گران درست می‌شود

تشبیهی که در کل صفحه به کار می‌بریم: کتابخانه، دستگاه فروش خودکار و کمد پرونده. کتابخانه‌ای با کتابدار (رابطه‌ای) به هر سؤالی جواب می‌دهد: «کتاب‌های نویسندگان متولد تبریز که بعد از ۱۹۹۰ چاپ شده‌اند و امانت نیستند». کمی طول می‌کشد و فقط یک میز جلو هست. دستگاه فروش خودکار (key-value) دقیقاً همان چیزی را که پشت دکمهٔ B4 است در یک ثانیه می‌دهد، و اگر دستگاه اضافه کنید با هر طول صفی، اما نمی‌تواند بگوید «ارزان‌ترین خوراکی بدون آجیل کدام است» مگر کسی ردیفی مخصوص همین سؤال پر کرده باشد. کمد پرونده با یک پوشه برای هر مشتری (سندی) همه‌چیز یک مشتری را یک‌جا می‌دهد، اما «همهٔ فاکتورهای بالای ۱۰۰۰ در همهٔ پوشه‌ها» یعنی باز کردن تک‌تک پوشه‌ها. بیشتر شرکت‌ها هم کتابخانه می‌خواهند و هم چند دستگاه فروش؛ مهارت در این است که هر سؤال جلوی دستگاه درستش برود.

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

  1. «NoSQL مقیاس‌پذیر است و SQL نیست.» یک primary از PostgreSQL با replicaها سهم بزرگی از workloadهای واقعی را می‌کشد و distributed SQL خودِ SQL را افقی می‌کند. چیزی که storeهای key-value واقعاً می‌دهند کارایی قابل‌پیش‌بینی در هر اندازه برای کوئری‌های طراحی‌شده است، به‌علاوهٔ مقیاس افقی مدیریت‌شده. اگر هنوز آن کوئری‌ها را ندارید، نمی‌توانید کلیدها را طراحی کنید.
  2. «بدون schema یعنی بدون کار روی schema.» schema از پایگاه داده به داخل هر خواننده منتقل می‌شود. مستندات JSON در PostgreSQL توصیه می‌کند حتی سندهای منعطف "have a somewhat fixed structure". مستندات مدل‌سازی MongoDB سراسر دربارهٔ طراحی schema است.
  3. «یک پایگاه داده برای همه‌چیز ساده‌تر است» یا برعکسش «برای هر کار بهترین ابزار». فاولر که polyglot persistence را جا انداخت در همان مقاله هشدار داد که "will come at a cost in complexity". هر store اضافه یعنی یک backup، ارتقا، بازبینی امنیتی و مهارت on-call دیگر. وقتی یکی اضافه کنید که الگویی اندازه‌گیری‌شده آن را بخواهد.

از کجا آمده ​

Polyglot persistence، ۲۰۱۱. مدخل PolyglotPersistence در bliki مارتین فاولر (۱۶ نوامبر ۲۰۱۱) اصطلاح polyglot programming نیل فورد از سال ۲۰۰۶ را وام گرفت و گفت "if you starting a new strategic enterprise application you should no longer be assuming that your persistence should be relational" و افزود "The relational option might be the right one - but you should seriously look at other alternatives." او Scott Leberknight را نخستین کسی می‌داند که این اصطلاح را به کار برد، و حرکت اصلی این فصل از متن خود اوست: "we'll be first asking how we want to manipulate the data and only then figuring out what technology is the best bet for it". مرز را هم او داد: "A component boundary is a good way to wrap a particular storage technology chosen for the way its data in manipulated."

Dynamo، ۲۰۰۷. ورنر فوگلز مقالهٔ Dynamo را برای SOSP 2007 در وبلاگش اعلام کرد و Dynamo را "internal technology developed at Amazon" برای یک store کلید-مقدار با دسترس‌پذیری بالا توصیف کرد. نوادگانش (Cassandra، Riak و سرویس مدیریت‌شدهٔ DynamoDB که طراحی داخلی متفاوتی دارد) خانوادهٔ key-value را شکل دادند. تاریخچهٔ خانواده‌ها در NoSQL: Families & Data Models است.

Spanner، ۲۰۱۲. مقالهٔ OSDI 2012 گوگل نشان داد تراکنش به سبک SQL بین مراکز داده ممکن است، با یک سرویس ساعت (TrueTime) برای مرتب کردن commitها. CockroachDB و YugabyteDB طراحی‌های متن‌باز را دنبال کردند؛ ببینید Distributed SQL, Consensus & 2PC.

Single-table design، ۲۰۱۸. جلسهٔ Rick Houlihan در AWS re:Invent 2018 با عنوان Amazon DynamoDB Deep Dive: Advanced Design Patterns for DynamoDB (DAT401) جملهٔ «اول الگوهای دسترسی، بعد کلیدها» را روش استاندارد DynamoDB کرد؛ راهنمای DynamoDB امروز می‌گوید "You should maintain as few tables as possible in a DynamoDB application."

PostgreSQL به‌عنوان پیش‌فرض، دههٔ ۲۰۲۰. JSONB، ستون‌های generated، partitioning، logical replication، افزونه‌هایی مثل pgvector و TimescaleDB و سرویس‌های serverless مدیریت‌شده (Neon، Aurora Serverless) جملهٔ «با PostgreSQL شروع کن» را پیش‌فرض رایج کردند؛ طبق postgresql.org، نسخهٔ PostgreSQL 19 در ۱۹ نوامبر ۲۰۲۶ منتشر شد.

text
     Year   Idea                                        What changed in practice
1    2006   Polyglot programming (Ford, via Fowler)     "Right tool per problem" applied to languages
2    2007   Dynamo paper (Amazon, SOSP)                 Highly available key-value, eventual consistency
3    2011   Polyglot persistence (Fowler)               Choose storage per component by data manipulation
4    2012   Spanner (Google, OSDI)                      SQL transactions across regions
5    2018   Houlihan DAT401, single-table design        DynamoDB modelling starts from access patterns
6    2020s  PostgreSQL + JSONB + extensions             One engine covers documents, vectors, time series
7    2020s  Serverless databases                        Pay per request or per second; scale to zero

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

پنج بلوک اول ورودی‌های تصمیم‌اند. ده بلوک بعدی خانواده‌هایی هستند که از میانشان انتخاب می‌کنید. دو بلوک آخر دربارهٔ وقتی است که بیش از یکی انتخاب می‌کنید و وقتی نظرتان عوض می‌شود.

الگوی دسترسی و شکل کوئری (Access patterns and query shapes) حیاتی ​

به زبان ساده: پیش از انتخاب پایگاه داده، هر سؤالی را که سیستم از داده‌اش می‌پرسد، تعداد دفعاتش و شکل جوابش را بنویسید.

بدفهمی رایج: «وقتی محصول ساخته شد کوئری‌ها را می‌فهمیم.» بیشترشان را همین حالا می‌دانید: صفحه‌ها، endpointهای API و jobهای مشخصات محصول‌اند. آن‌هایی که نمی‌دانید دلیل خوبی‌اند که یک store با کوئری منعطف را منبع حقیقت نگه دارید.

تعریف: الگوی دسترسی (Access pattern) عملیاتی نام‌دار و تکرارشونده روی داده است با ورودی‌های کلیدی، نتیجه، نرخ (QPS اوج) و نیاز سازگاری‌اش. شکل کوئری (Query shape) نوع کاری است که موتور باید انجام دهد: point lookup (یک کلید)، range scan (برشی مرتب از یک کلید یا ایندکس)، lookup چندکلیده، join، full-text search، aggregation روی ردیف‌های زیاد، graph traversal یا جست‌وجوی شباهت. نسبت خواندن به نوشتن (Read/write ratio) می‌گوید طراحی باید کدام سمت را بهینه کند.

text
     Step   What you write down                                   Ordering context example
1    List   Screens, endpoints, jobs, reports                     checkout, order page, "my orders", warehouse feed, finance report
2    Name   One line per access pattern                          AP1 place order; AP2 get order; AP3 latest 20 orders; AP4 PLACED feed; AP5 revenue report
3    Shape  Point / range / join / search / aggregate / graph     AP2 point; AP3 range on customer; AP4 range on status; AP5 aggregate
4    Rate   Peak QPS and read:write                               AP1 200 w/s; AP2 1,500 r/s; AP3 400 r/s; AP4 20 r/s; AP5 1/hour
5    Need   Consistency and latency SLO per pattern               AP2 read-your-writes, p99 20 ms; AP5 an hour stale is fine
6    Route  Which store answers which pattern                     AP1-AP4 system of record; AP5 analytics store via CDC

سناریوی واقعی: تیم یک marketplace چهارده الگوی دسترسی فهرست می‌کند؛ دوازده‌تا lookup نقطه‌ای و بازه‌ای بر اساس کاربر یا آگهی‌اند، یکی جست‌وجو و یکی گزارش ماهانهٔ مالی. جست‌وجو و گزارش به OpenSearch و انبار داده می‌روند و آن دوازده‌تا store اصلی را تعیین می‌کنند. یک محصول چت می‌بیند ۹۵ درصد خواندن‌ها «۵۰ پیام آخر یک کانال» است: range scan روی یک partition key، جای طبیعی‌اش Cassandra یا ScyllaDB (ببینید Cassandra و ScyllaDB). یک قابلیت تحلیلی معلوم می‌شود «group by روی هر ستونی که کاربر بخواهد» است: تجمیع ad-hoc، که storeهای key-value را برای آن قابلیت کنار می‌گذارد.

هر خانواده با هر شکل چه می‌کند:

شکلPostgreSQL / MySQLMongoDBDynamoDB / CassandraRedisElasticsearch / OpenSearchClickHouse
Point lookupایندکس کلید اصلیایندکس _idGetItem / partition keyGET، HGETALLبا _id، ولی near-real-timeممکن، ولی کارش نیست
بازه روی یک کلیدایندکس B-tree مرکبایندکس compoundsort key / clustering keysorted set با ZRANGEمرتب‌سازی روی یک فیلدترتیب کلید اصلی
Joinبومی$lookup، محدودندارد؛ denormalize کنیدنداردندارد؛ denormalize کنیدپشتیبانی می‌شود، بهتر با جدول‌های بُعد کوچک
فیلتر ad-hocهر ستون، با یا بی ایندکسهر فیلد؛ ایندکس برای سرعتScan (گران) یا ایندکس تازهنداردهر فیلد ایندکس‌شدههر ستون، سریع
Full-textFTS داخلی، برای پیکره‌های کوچک خوبAtlas Searchنداردماژول RediSearch (Redis Stack)قابلیت اصلیمحدود
Aggregationروی replica خوب، در مقیاس عظیم کندaggregation pipelineسمت برنامهفقط شمارندهaggregationهاقابلیت اصلی

راه درست: جدول الگوهای دسترسی را کنار schema در مخزن نگه دارید (port در Go همین فصل آن را به‌صورت comment دارد)، در بازبینی طراحی مرورش کنید و بخواهید هر endpoint تازه پیش از merge الگویش را نام ببرد. حساب ظرفیت هر الگو در Back-of-the-Envelope Capacity Estimation است.

نیاز سازگاری و تراکنش (Consistency and transaction requirements) حیاتی ​

به زبان ساده: معلوم کنید کدام واقعیت‌ها حتی یک ثانیه هم نباید غلط باشند و کدام‌ها می‌توانند کمی کهنه باشند؛ و کدام تغییرها باید با هم انجام شوند یا اصلاً نشوند.

بدفهمی رایج: «پایگاه‌های NoSQL تراکنش ندارند، پس ناامن‌اند.» DynamoDB دستور TransactWriteItems دارد، MongoDB تراکنش چندسندی دارد، Redis دستور MULTI/EXEC دارد. فرق در دامنه و هزینه است: DynamoDB "up to 100 write actions in a single all-or-nothing operation" را گروه می‌کند؛ MongoDB می‌گوید "a distributed transaction incurs a greater performance cost over single document writes" و نباید جای طراحی schema را بگیرد.

تعریف: نیاز سازگاری (Consistency requirement) میزان کهنگی‌ای است که خواننده ممکن است ببیند (strong، read-your-writes، bounded، eventual؛ ببینید Consistency Models). نیاز تراکنش (Transaction requirement) مجموعهٔ invariantهایی است که بیش از یک رکورد را درگیر می‌کنند (موجودی هنگام ثبت سفارش منفی نشود، جمع ترازهای دفتر کل صفر باشد) و اینکه آیا جداسازی serializable لازم دارند (Isolation Levels).

text
     T1 (checkout A)                              T2 (checkout B)              Store
1    read stock(sku-9) = 1
2                                                 read stock(sku-9) = 1
3    write order A; stock = 0
4                                                 write order B; stock = 0     key-value with no condition: oversold
5    -- relational: UPDATE stock SET qty = qty - 1 WHERE sku = 'sku-9' AND qty >= 1 in the same transaction as INSERT order
6    -- DynamoDB:  TransactWriteItems [Put order (attribute_not_exists), Update stock (ConditionExpression qty >= 1)]
7    -- either way: the invariant lives in one atomic step, never in application reads

سناریوی واقعی: پرداخت و دفتر کل (حساب دوطرفه باید تراز باشد؛ ببینید Payment Processing)؛ رزرو موجودی در فروش ویژه؛ رزرو صندلی؛ نام کاربری یکتا؛ سبد خرید (می‌تواند eventual باشد)؛ شمارندهٔ «لایک» (eventual و حتی تقریبی؛ ببینید Sharded Counters).

هر محصول چه می‌دهد:

محصولاتمی بودن تک‌رکوردتراکنش چندرکوردیسازگاری خواندن پیش‌فرض
PostgreSQLبلههر تعداد ردیف و جدول، تا SERIALIZABLEروی primary قوی؛ replicaها عقب‌اند
MySQL InnoDBبلههر ردیفی، پیش‌فرض REPEATABLE READروی primary قوی
MongoDBیک سند، با آرایه‌های تودرتوچندسندی؛ replica set یا sharded cluster لازم استپیش‌فرض خواندن از primary
DynamoDBیک آیتم، با condition expressionتا ۱۰۰ آیتم، مجموع 4 MB، یک حساب و یک Regioneventual مگر با ConsistentRead؛ GSIها همیشه eventual
Cassandraیک partition (lightweight transaction با Paxos)batch تراکنش ایزوله نیستقابل تنظیم (QUORUM، ONE)
Redisیک دستور؛ MULTI/EXEC یک بلوک را بدون درهم‌رفتگی اجرا می‌کندبا خطای دستور rollback نداردprimary؛ replicaها ناهمگام‌اند
Spanner / CockroachDBبلهتوزیع‌شده، serializableپیش‌فرض قوی

راه درست: invariantها را با نام فهرست کنید؛ برای هرکدام کوچک‌ترین واحد اتمی‌ای را که در بر می‌گیردش انتخاب کنید (یک ردیف، یک سند، یک آیتم، یک تراکنش). اگر یک invariant بین دو سرویس آینده پخش می‌شود، یا داده را کنار هم نگه دارید یا saga را بپذیرید (Saga). چارچوب ACID/BASE در ACID vs BASE و CAP و PACELC در CAP & PACELC است.

شکل داده و نوسان schema (Data shape and schema volatility) مهم ​

به زبان ساده: داده‌تان چقدر منظم است و ساختارش هر چند وقت عوض می‌شود؟

بدفهمی رایج: «ویژگی‌های محصول ما متغیرند، پس پایگاه سندی لازم داریم.» JSONB در PostgreSQL ویژگی‌های متغیر را کنار ستون‌های تایپ‌دار و با ایندکس GIN نگه می‌دارد؛ MySQL هم نوع JSON دارد. تغییرپذیری به‌تنهایی دلیل عوض کردن موتور نیست. تغییرپذیری به‌علاوهٔ «کل aggregate همیشه با هم خوانده و نوشته می‌شود» به‌علاوهٔ «invariant بین aggregateها نداریم» دلیل است.

تعریف: شکل داده یعنی داده جدولی است، درخت (aggregate با بخش‌های تودرتو)، گراف، دنباله (time series، log) یا بردار. نوسان schema (Schema volatility) یعنی مجموعهٔ فیلدها هر چند وقت عوض می‌شود و چه کسی کنترلش می‌کند (تیم شما، مدیر محصول، مشتری، طرف سوم).

text
     Week   Change                                            Relational + JSONB                   Document store
1    1      Laptop has ram_gb, cpu                            attributes jsonb                     fields in the document
2    3      Phones add sim_slots                              no migration, still jsonb            no migration
3    6      Filter by brand on every listing page             promote: generated column + index    add an index on attributes.brand
4    9      Finance needs price history with FK to suppliers  normal table, FK, transaction         separate collection, application checks

سناریوی واقعی: کاتالوگ محصول با ۴۰۰ دسته و ویژگی‌های متفاوت در هر دسته؛ فرم‌سازهایی که کاربر تعریفشان می‌کند؛ دریافت webhookهای طرف سوم که payloadشان بی‌خبر عوض می‌شود (JSONB خام را نگه دارید و آنچه لازم است استخراج کنید)؛ payload رویدادها با schema نسخه‌دار؛ دستگاه‌های IoT با فیلدهای وابسته به firmware.

هر محصول چه می‌دهد:

محصولبخش منعطفاعتبارسنجیایندکس روی فیلد منعطف
PostgreSQLستون jsonbCHECK با jsonb_typeof و jsonb_path_exists؛ ستون generatedGIN (jsonb_ops، jsonb_path_ops)، ایندکس expression
MySQL 8ستون JSONCHECK، تابع اعتبارسنجی JSON schemaستون generated، ایندکس multi-valued
MongoDBکل سندvalidator از نوع $jsonSchema روی collectionهر فیلد، ایندکس wildcard
DynamoDBهر attribute غیرکلیدیدر خود پایگاه نداردفقط attributeهای کلید و کلیدهای GSI
Cassandraستون‌های هر جدول، collection، UDTنوع‌های CQLایندکس ثانویه با ملاحظات

راه درست: برای هر چیزی که روی آن فیلتر، join، جمع یا constraint دارید ستون تایپ‌دار؛ برای دنبالهٔ بلند فیلدها JSONB؛ روزی که یک کوئری مدام به فیلدی از JSON نیاز پیدا کرد آن را به ستون generated ارتقا دهید. SQL آن در JSONB به بهانهٔ بی‌schema بودن است. طراحی schema به‌طور عمیق در Schema Design است.

سقف مقیاس، رشد و SLO تأخیر (Scale ceiling, growth and latency SLO) حیاتی ​

به زبان ساده: این سیستم چقدر بزرگ و پرمشغله می‌شود و هر جواب چقدر باید سریع باشد؟

بدفهمی رایج: «شاید خیلی بزرگ شویم، پس از روز اول پایگاهی لازم داریم که بی‌نهایت مقیاس‌پذیر باشد.» تخمین بزنید. روزی ۲۰۰ هزار سفارش با هر کدام 2 KB یعنی حدود 139 GB در سال (برنامهٔ آزمایشگاه همین را چاپ می‌کند)؛ این یعنی سال‌ها یک primary از PostgreSQL. انتخاب برای مقیاسی خیالی، join و کوئری ad-hoc امروز را از شما می‌گیرد.

تعریف: سقف مقیاس (Scale ceiling) یک طراحی باری است که در آن store انتخاب‌شده تغییر ساختاری لازم دارد (sharding، store تازه، طراحی کلید تازه). برای یک primary رابطه‌ای بیشتر throughput نوشتن و حافظهٔ working set است؛ برای store کلید-مقدار throughput هر partition و کلیدهای داغ. SLO تأخیر (Latency SLO) صدک هدف برای هر الگوی دسترسی است (SLAs, SLOs, SLIs، Latency Budgets & Tail Latency).

text
     Load      Ordering on PostgreSQL                        Ordering on DynamoDB
1    1x        one primary, one replica                       on-demand table, 2 partitions of throughput
2    10x       bigger instance, more replicas, PgBouncer      more partitions, automatic
3    100x      partitioning, then sharding (Citus) or         same design; hot-key review; per-partition
               distributed SQL; outbox to offload reads       limits 3,000 RCU / 1,000 WCU per partition
4    any       p99 depends on plans and locks                 p99 flat for designed queries

سناریوی واقعی: فروش بلیت ده دقیقه به ۵۰ برابر حالت عادی می‌رسد (Ticketing case study)؛ ناوگانی از IoT تمام روز ۱۰۰ هزار خوانش در ثانیه می‌نویسد؛ یک SaaS سازمانی ۲۰۰۰ مستأجر و 300 GB داده دارد و بیشتر می‌خواند؛ یک اپ جهانی در سه region نوشتن کم‌تأخیر می‌خواهد.

هر محصول چه می‌دهد:

محصولنوشتن را چطور مقیاس می‌دهدنشانهٔ عملی رسیدن به سقف
PostgreSQL (یک primary)عمودی؛ partitioning به نگهداری کمک می‌کند نه به پخش نوشتننرخ WAL، CPU، رقابت قفل، عقب‌ماندن vacuum
PostgreSQL + Citusشارد بر اساس distribution columnکوئری و تراکنش بین‌شاردی
MySQL + Vitessشارد با keyspace ID؛ Vitess "distributes data across multiple MySQL instances through sharding"join بین‌شاردی، عملیات resharding
DynamoDBpartition خودکار؛ on-demand "can start small and scale to millions of requests per second"partition key داغ، اندازهٔ آیتم 400 KB
Cassandra / ScyllaDBافزودن گره؛ حلقهٔ consistent hashاندازهٔ partition، tombstone، repair
Spanner / CockroachDB / YugabyteDBrangeها خودکار تقسیم و جابه‌جا می‌شوندتأخیر نوشتن بین regionها، هزینه

راه درست: با عدد تخمین بزنید نه با صفت (Capacity Estimation)؛ برنامهٔ ۱۰ برابر را پیش از نیاز بنویسید (Storage & Data Scaling)؛ storeی را انتخاب کنید که گام بعدیاش را می‌توانید اجرا کنید.

بلوغ عملیاتی، سرویس مدیریت‌شده، هزینه و lock-in مهم ​

به زبان ساده: بهترین پایگاه داده روی کاغذ، اگر کسی در تیم نتواند ساعت ۳ بامداد آن را از backup برگرداند، انتخاب غلطی است.

بدفهمی رایج: «سرویس مدیریت‌شده عملیات را حذف می‌کند.» patch کردن، سازوکار failover و سخت‌افزار را حذف می‌کند. برنامه‌ریزی ظرفیت، طراحی کلید، تنظیم کوئری، پایش هزینه، backupی که بازگرداندنش را آزموده‌اید و مسیر مهاجرت هنگام رفتن را حذف نمی‌کند.

تعریف: بلوغ عملیاتی (Operational maturity) توانایی اثبات‌شدهٔ تیم در استقرار، پایش، backup، بازگردانی، ارتقا و تنظیم یک store است. سرویس مدیریت‌شده (Managed service) مثل Amazon RDS/Aurora، DynamoDB، MongoDB Atlas، Google Cloud Spanner، Neon، PlanetScale، Elastic Cloud و ClickHouse Cloud بخشی از این بار را به فروشنده می‌دهد. Lock-in هزینهٔ رفتن است: APIهای اختصاصی، قالب خروجی داده و قابلیت‌هایی که جای دیگر معادل ندارند. اکوسیستم یعنی driverها، ORMها، ابزار migration، observability و نیرویی که می‌توانید استخدام کنید.

text
     Question                                     PostgreSQL on RDS         DynamoDB                 MongoDB Atlas
1    Who handles failover?                        AWS (Multi-AZ)            AWS (built in)           Atlas (replica set)
2    Who designs indexes and keys?                You                       You (keys are the design) You
3    API portable to another vendor?              Yes, wire protocol         No, AWS-only API          MongoDB API, self-host possible
4    How do you leave?                            pg_dump / logical repl.    Export to S3, rewrite code mongodump / change streams
5    Laravel support                              First-party pgsql driver   Cache/session drivers only mongodb/laravel-mongodb package

سناریوی واقعی: یک استارتاپ سه‌نفره DynamoDB را انتخاب می‌کند چون «serverless است» و بعد زیر فشار ددلاین single-table design یاد می‌گیرد؛ یک بانک Oracle را برای دفتر کل اصلی نگه می‌دارد چون تیم DBA و حسابرسی حول آن ساخته شده؛ تیمی Cassandra را بدون برنامهٔ repair خودش میزبانی می‌کند و بی‌صدا سازگاری داده را از دست می‌دهد؛ تیمی روی Aurora بیشتر از compute برای I/O پول می‌دهد.

هر محصول چه می‌دهد:

دغدغهPostgreSQLMySQLMongoDBDynamoDBCassandraRedis
سرویس مدیریت‌شدهRDS، Aurora، Cloud SQL، AlloyDB، Azure، Neon، SupabaseRDS، Aurora، PlanetScaleAtlas، DocumentDB (API سازگار)فقط AWSAstra DB، Amazon KeyspacesElastiCache، MemoryDB، Redis Cloud
پشتیبانی رسمی Laravel 13بلهبله (و MariaDB)با mongodb/laravel-mongodbdriver برای cache و sessionنهبله (facade Redis، cache، queue، session)
driver در Gopgxgo-sql-driver/mysqlmongo-go-driveraws-sdk-go-v2gocqlgo-redis
Lock-inکمکممتوسطزیادکمکم (fork به نام Valkey هست)

مستندات پایگاه داده در Laravel مجموعهٔ رسمی را فهرست می‌کند: "MariaDB 10.3+"، "MySQL 5.7+"، "PostgreSQL 10.0+"، "SQLite 3.26.0+" و "SQL Server 2017+"، و اضافه می‌کند که MongoDB از طریق بستهٔ mongodb/laravel-mongodb پشتیبانی می‌شود.

راه درست: هر نامزد را به‌ازای هر الگوی دسترسی قیمت بگذارید (درخواست، فضای ذخیره، I/O، backup، ترافیک خروجی)؛ storeی را ترجیح دهید که نسخهٔ مدیریت‌شده‌ای دارد که تیمتان می‌تواند اداره کند؛ داده را پشت یک repository port نگه دارید تا رفتن هزینهٔ یک adapter داشته باشد نه بازنویسی (Repositories).

رابطه‌ای: PostgreSQL به‌عنوان پیش‌فرض (Relational: PostgreSQL by default) حیاتی ​

به زبان ساده: جدول، ردیف، SQL و موتوری که قاعده‌های شما را اجرا می‌کند (unique، not null، foreign key، check) و هر سؤالی را که بتوانید بیان کنید جواب می‌دهد.

بدفهمی رایج: «join کند است، پس در مقیاس بالا از رابطه‌ای دوری کنید.» join روی کلیدهای ایندکس‌دار ارزان است؛ چیزی که مقیاس نمی‌گیرد join بی‌حد روی جدولی عظیم روی primary عملیاتی است. این مسئلهٔ مدل‌سازی و مسیریابی است (گزارش را به replica یا انبار داده بفرستید)، نه دلیلی برای از دست دادن constraintها.

تعریف: پایگاه داده‌ای رابطه‌ای (Relational) داده را به‌شکل رابطه (جدول) با نوع و constraint اعلام‌شده نگه می‌دارد و SQL اعلانی را با optimizer هزینه‌محور و تراکنش ACID جواب می‌دهد. قوت‌ها: join، constraint و foreign key، تراکنش چندردیفی، کوئری ad-hoc، ابزار پخته (backup، PITR، migration، ORM، observability). جایی که کم می‌آورد: throughput نوشتن فراتر از یک primary، جدول‌های تکی خیلی بزرگ بدون partitioning، نوشتن چند region جهانی، و جست‌وجوی متنی یا برداری در مقیاس بالا.

text
     Request                             PostgreSQL work
1    POST /orders (AP1)                  BEGIN; INSERT orders; INSERT order_lines (unnest); INSERT outbox; COMMIT
2    GET /orders/01J9A (AP2)             index scan on orders_pkey, then order_lines_pkey
3    GET /customers/42/orders (AP3)      index scan on (customer_id, id DESC) LIMIT 20
4    warehouse feed (AP4)                partial index WHERE status = 'PLACED'
5    finance report (AP5)                runs on a replica or in ClickHouse via CDC, not on the primary

سناریوی واقعی: مدیریت سفارش، صورت‌حساب، موجودی، مجوزها، دادهٔ مستأجرهای SaaS (Multi-Tenancy)، هر چیزی که پول در آن هست؛ کاتالوگ با ویژگی‌های JSONB؛ صف job با FOR UPDATE SKIP LOCKED؛ جست‌وجوی کوچک با tsvector؛ embedding با pgvector.

هر محصول چه می‌دهد:

قابلیتPostgreSQLMySQL InnoDBSQL ServerOracleSQLite
Foreign key و CHECKبلهبلهبلهبلهبله (اجرای FK با pragma)
JSONjsonb با GINJSON با ایندکس روی ستون generatedنوع jsonJSONتابع‌های JSON
ایندکس partial و expressionبلهایندکس functional؛ partial نداردایندکس filteredfunction-basedبله
افزونهpgvector، TimescaleDB، PostGIS، Cituspluginمحدودoptionافزونهٔ بارگذاری‌شدنی
خطای کلید تکراریSQLSTATE 23505 unique_violationError 10622627 / 2601ORA-00001SQLITE_CONSTRAINT

راه درست: با PostgreSQL شروع کنید مگر نیازی آن را رد کند؛ با فرم‌های نرمال مدل کنید و با شاهد denormalize کنید. schema کانتکست Ordering این فصل، با foreign key، CHECK، ایندکس partial و جدولی با JSONB و ستون generated:

sql
-- PostgreSQL 16+ schema for the Ordering context (adapter: orders/postgres.go).
-- Relational strengths in one file: foreign keys, CHECK constraints,
-- a transaction across two tables, and indexes that serve AP2-AP4.

CREATE TABLE orders (
    id           text        PRIMARY KEY,                -- time-sortable ID (ULID-style)
    customer_id  text        NOT NULL,
    status       text        NOT NULL CHECK (status IN ('PLACED', 'PAID', 'SHIPPED')),
    total_cents  bigint      NOT NULL CHECK (total_cents >= 0),
    created_at   timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE order_lines (
    order_id     text   NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
    line_no      int    NOT NULL,
    sku          text   NOT NULL,
    quantity     int    NOT NULL CHECK (quantity > 0),
    price_cents  bigint NOT NULL CHECK (price_cents >= 0),
    PRIMARY KEY (order_id, line_no)
);

-- AP3: a customer's latest orders is a range scan on one index.
CREATE INDEX orders_customer_recent ON orders (customer_id, id DESC);
-- AP4: the warehouse feed reads only PLACED orders; a partial index stays small.
CREATE INDEX orders_placed ON orders (id DESC) WHERE status = 'PLACED';

-- JSONB with a contract, not instead of one: typed columns for what you
-- filter and join on, JSONB for the long tail of product attributes.
CREATE TABLE products (
    sku          text   PRIMARY KEY,
    name         text   NOT NULL,
    price_cents  bigint NOT NULL CHECK (price_cents >= 0),
    attributes   jsonb  NOT NULL DEFAULT '{}'::jsonb
                 CHECK (jsonb_typeof(attributes) = 'object'),
    -- a promoted, indexed attribute once a query needs it often
    brand        text GENERATED ALWAYS AS (attributes ->> 'brand') STORED
);
CREATE INDEX products_attributes ON products USING gin (attributes jsonb_path_ops);
CREATE INDEX products_brand ON products (brand);

-- Outbox: the change that other stores (search index, analytics, cache)
-- must see is written in the same transaction as the order.
CREATE TABLE outbox (
    id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    aggregate_id text        NOT NULL,
    event_type   text        NOT NULL,
    payload      jsonb       NOT NULL,
    created_at   timestamptz NOT NULL DEFAULT now()
);

پایگاه‌های سندی: MongoDB، embedding در برابر referencing حیاتی ​

به زبان ساده: هر aggregate (محصول با variantهایش، سفارش با سطرهایش) را یک سند شبه‌JSON ذخیره کنید تا یک خواندن هر چه یک صفحه لازم دارد برگرداند.

بدفهمی رایج: «در MongoDB همه‌چیز را embed می‌کنید.» راهنمای خود MongoDB می‌گوید وقتی "The child side of the relationship has high cardinality"، وقتی "Your embedded data grows without bounds" یا وقتی "Your data is written at different times in a write-heavy workload"، از reference استفاده کنید.

تعریف: پایگاه داده سندی (Document database) سندهای خودتوصیف (در MongoDB، BSON) را در collectionها نگه می‌دارد. Embedding دادهٔ مرتبط را داخل والد می‌گذارد ("These denormalized data models allow applications to retrieve related data in a single database operation")؛ Referencing یک شناسه نگه می‌دارد و با کوئری دوم یا $lookup حلش می‌کند ("References result in normalized data models"). اتمی بودن در سطح سند است: "a write operation is atomic on the level of a single document". Aggregation pipeline زبان کوئری مرحله‌ای MongoDB است ($match، $group، $sort، $lookup). محدودیت‌های سخت: "The maximum BSON document size is 16 mebibytes" و حداکثر ۱۰۰ سطح تودرتویی.

text
     Decision          Product document                          Why
1    variants          embedded array (bounded, read with it)    "has-a", read together, updated together
2    attributes        embedded object (differs per type)        schema volatility, no cross-product invariant
3    reviews           separate collection, product_id ref        unbounded, written by other users at other times
4    price history     separate collection or time-series coll.  grows forever
5    stock             separate store with transactions           invariant across orders; usually relational

سناریوی واقعی: کاتالوگ محصول؛ مدیریت محتوا (مقاله با بلوک‌ها)؛ پروفایل کاربر با ترجیحات؛ backend اپ موبایل که کل شیء را همگام می‌کند؛ بایگانی payload رویدادها. کمتر مناسب: دفتر کل، دادهٔ back-office به‌شدت رابطه‌ای، گزارش‌های بین collectionها.

هر محصول چه می‌دهد:

قابلیتMongoDBjsonb در PostgreSQLآیتم DynamoDB
حداکثر اندازه16 MiB برای هر سند1 GB برای هر مقدار فیلد (TOAST)400 KB برای هر آیتم
کوئری تودرتوdot notation، عملگرهای آرایه->، ->>، @>، jsonpathفقط projection؛ فیلتر بعد از خواندن
ایندکس ثانویه روی فیلد تودرتوبلهGIN یا ایندکس expressionفقط از طریق attributeهای کلید GSI
Join$lookupSQL کاملندارد
تراکنش چندرکوردیreplica set یا sharded clusterبومیTransactWriteItems

راه درست: آنچه محدود است و با هم خوانده می‌شود embed کنید، آنچه بی‌حد است یا مستقل نوشته می‌شود reference کنید، و aggregation pipeline سنگین گزارش‌ها را روی secondary یا store تحلیلی اجرا کنید. مدل Laravel MongoDB و یک کوئری با aggregation builder در Laravel است؛ کل موتور در MongoDB in Depth.

Key-value و wide-column: DynamoDB، Cassandra و single-table design حیاتی ​

به زبان ساده: هر خواندن یا «آیتم با این کلید را بده» است یا «آیتم‌های زیر این partition key را به ترتیب sort key بده»؛ کلیدها را طوری شکل می‌دهید که هر صفحه یکی از همین درخواست‌ها باشد.

بدفهمی رایج: «یک جدول برای هر موجودیت، مثل SQL.» راهنمای DynamoDB برعکس می‌گوید: "You should maintain as few tables as possible" و "A single table with inverted indexes can usually enable simple queries to create and retrieve the complex hierarchical data structures required by your application." گذاشتن سفارش‌ها و مشتری‌ها در جدول‌های جدا یعنی چیدمان SQL بدون join‌های SQL.

تعریف: store کلید-مقدار (Key-value) آیتم‌ها را با partition key (که hash می‌شود تا partition انتخاب شود) و در DynamoDB و Cassandra با sort key اختیاری (clustering key) که آیتم‌های داخل partition را مرتب می‌کند، آدرس‌دهی می‌کند. Global secondary index (GSI) همان آیتم‌ها را با attributeهای دیگر دوباره کلیدگذاری می‌کند؛ GSIهای DynamoDB فقط "support eventually consistent reads". Join وجود ندارد (no joins): دادهٔ مرتبط یا زیر یک partition key کنار هم گذاشته می‌شود (یک item collection) یا تکرار می‌شود. Single-table design چند نوع موجودیت را در یک جدول با نام‌های کلید عمومی (PK، SK، GSI1PK، GSI1SK) و پیشوندهای نوع‌دار (CUST#، ORDER#) نگه می‌دارد. راهنمای DynamoDB سه ویژگی را که باید اول دانست فهرست می‌کند: اندازهٔ داده، شکل داده ("a NoSQL database organizes data so that its shape in the database corresponds with what will be queried") و سرعت داده.

Table "ordering" (base table, strong reads allowed)GSI1 (eventually consistent)PKSKattributesGSI1PK / GSI1SKCUST#c-42PROFILEname, email, tier-CUST#c-42ORDER#01J9Astatus, total, Lines[ ]STATUS#PLACED#1CUST#c-42ORDER#01J9Bstatus, total, Lines[ ]STATUS#PAID#3CUST#c-7ORDER#01J8Zstatus, total, Lines[ ]STATUS#PLACED#0GSI1PKGSI1SKSTATUS#PLACED#001J8ZSTATUS#PLACED#101J9ASTATUS#PAID#301J9BAP2 get one orderGetItem PK=CUST#c-42SK=ORDER#01J9A, ConsistentReadone item, lines embeddedcost: ceil(size/4 KB) RCUAP3 latest orders of a customerQuery PK=CUST#c-42 ANDbegins_with(SK, "ORDER#")ScanIndexForward=false, Limit=20one partition, sorted by ULIDAP4 warehouse feed by statusQuery GSI1 GSI1PK=STATUS#PLACED#nfor n in 0..3, merge newest firstshard suffix avoids one hotpartition for a 3-value attribute

تصویر چیدمان جدول ordering را نشان می‌دهد: آیتم پروفایل مشتری و آیتم‌های سفارش زیر یک partition key با CUST#، سطرهای سفارش داخل خود آیتم embed شده‌اند، و GSI1 همان سفارش‌ها را با STATUS#...#shard دوباره کلیدگذاری می‌کند. سه کادر پایین نشان می‌دهند هر الگو دقیقاً چه درخواستی است.

text
     Access pattern                     DynamoDB request                                      Items read
1    AP1 place order                    PutItem, ConditionExpression attribute_not_exists(PK) 1 write (+1 GSI write)
2    AP2 get order                      GetItem PK=CUST#c-42, SK=ORDER#01J9A, ConsistentRead  1
3    AP3 latest 20 orders               Query PK=CUST#c-42 AND begins_with(SK,"ORDER#"),      up to 20, one partition
                                        ScanIndexForward=false, Limit=20
4    AP4 PLACED feed                    Query GSI1 GSI1PK=STATUS#PLACED#0..3, merge           4 small queries
5    AP5 revenue report                 not served: stream to S3/ClickHouse via DynamoDB Streams

سناریوی واقعی: سبد خرید و session در مقیاس خرده‌فروشی؛ پروفایل و تنظیمات کاربر؛ رجیستری دستگاه‌ها؛ leaderboard با sort key؛ پیام‌های چت (Cassandra: partition به‌ازای کانال و سطل زمانی)؛ feature flag؛ جدول‌های کلید idempotency (API Idempotency).

هر محصول چه می‌دهد:

مفهومDynamoDBCassandra / ScyllaDBBigtable
Partition keypartition key (hash)partition keyپیشوند row key
ترتیب داخل partitionsort keyclustering columnsrow key واژه‌نامه‌ای
مسیر دسترسی ثانویهGSI (eventual)، LSI (همان partition key، ۵ تا در هر جدول)materialized view، ایندکس SAI یا جدول دومجدول دوم
محدودیت هر partition۳۰۰۰ واحد خواندن و ۱۰۰۰ واحد نوشتن در ثانیهراهنمای اندازهٔ partition (partitionها را محدود نگه دارید)اندازهٔ row، hotspot
نوشتن شرطیConditionExpressionlightweight transaction (IF NOT EXISTS)check-and-mutate
مدل ظرفیتon-demand (پیش‌فرض) یا provisionedگره‌هایی که خودتان اجرا می‌کنید یا سرویس managedگره

راه درست: جدول الگوهای دسترسی را بنویسید، چیدمان آیتم‌ها را با پیشوند کلید بکشید، هر الگو را GetItem یا Query کنید، برای هر مسیر اضافه یک GSI بگذارید، کلیدهای GSI کم‌تنوع را shard کنید و هرگز Scan را روی مسیر درخواست نفرستید. adapter در Go است؛ موتورها در Wide-Column & Key-Value at Scale؛ طراحی partition key در سطح سیستم در Sharding at System Level.

Redis: store اصلی یا cache حیاتی ​

به زبان ساده: Redis همهٔ داده را در حافظه نگه می‌دارد، ساختار داده (hash، sorted set، stream) با دستورهای خیلی سریع می‌دهد و فقط به همان اندازه‌ای که تنظیم کنید روی دیسک می‌نویسد.

بدفهمی رایج: «Redis یک cache است و هرگز نمی‌تواند store اصلی باشد»، یا برعکس، «Redis روی دیسک persist می‌کند، پس به اندازهٔ PostgreSQL امن است». صفحهٔ persistence خود Redis می‌گوید هر دو RDB و AOF را به کار ببرید "if you want a degree of data safety comparable to what PostgreSQL can provide you"، و با پیش‌فرض appendfsync everysec "you may lose 1 second of data if there is a disaster".

تعریف: Redis در نقش cache نسخه‌هایی از داده‌ای را نگه می‌دارد که منبع حقیقتش جای دیگری است، با TTL و سیاست بیرون‌اندازی (maxmemory-policy مثلاً allkeys-lru؛ ببینید Caching). در نقش store اصلی Redis (Redis primary store) تنها نسخه را نگه می‌دارد، که persistence (snapshotهای RDB و/یا AOF)، replication، maxmemory-policy noeviction (تا هیچ کلیدی بی‌صدا حذف نشود؛ با noeviction "the server will return an error when you try to execute commands that cache new data") و کسب‌وکاری که پنجرهٔ از دست رفتن باقی‌مانده را می‌پذیرد لازم دارد. هزینهٔ حافظه (Memory cost) عامل تعیین‌کننده است: هر بایت داده، به‌علاوهٔ سربار هر کلید و فضای copy-on-write هنگام fork در بازنویسی RDB/AOF، در RAM زندگی می‌کند.

text
     t       Event                                              appendfsync everysec   RDB only (save every 5 min)
1    09:00:00  SET cart:{42} ...                               in AOF buffer           in memory
2    09:00:01  background fsync                                 on disk                 in memory
3    09:00:01.6 HINCRBY cart:{42} sku-9 1                       in AOF buffer           in memory
4    09:00:01.9 power loss
5    restart   replay AOF                                       lost: the last ~1 s     lost: up to 5 minutes

سناریوی واقعی: خوب به‌عنوان store اصلی: سبد خرید، session، شمارندهٔ rate limit (Rate Limiting)، leaderboard، presence، کدهای OTP کوتاه‌عمر، feature flag با fallback. بد به‌عنوان تنها store: موجودی حساب، سفارش، پرداخت، هر چیزی که باید برای حسابرسی بازتولیدش کنید.

Redis در برابر DynamoDB برای workloadهای کلید-مقدار:

سؤالRedis (ElastiCache، MemoryDB، خودمیزبان)DynamoDB
تأخیرزیر میلی‌ثانیه، در حافظهچند میلی‌ثانیهٔ تک‌رقمی
پایداریقابل تنظیم؛ AOF با everysec تا حدود ۱ ثانیه از دست می‌دهد؛ MemoryDB یک log پایدار اضافه می‌کندپایدار، هنگام نوشتن بین AZها replicate می‌شود
محرک هزینهRAM برای کل دادهدرخواست‌ها و GB ذخیره‌شده
ساختار دادهhash، list، set، sorted set، stream، HyperLogLogآیتم با attribute؛ list و map داخل آیتم
اندازهٔ هر مقدارتا 512 MB برای هر string400 KB برای هر آیتم
شکل کوئریکلید، بازه روی sorted set، اسکریپتکلید، بازه روی sort key، GSI
مقیاس افقیRedis Cluster با ۱۶۳۸۴ hash slotpartition خودکار
بهترین وقتیداغ، کوچک، کوتاه‌عمر، حساس به تأخیررکوردهای پایدار در هر اندازه با کلید معلوم

راه درست: برای هر keyspace تصمیم بگیرید Redis cache است (بیرون‌اندازی مجاز) یا store (noeviction، AOF روشن، replica، هشدار حافظه)؛ هرگز پول را فقط در Redis نگه ندارید. persistence و ساختارها در Redis in Depth است.

به زبان ساده: موتور جست‌وجو یک inverted index (کلمه → سندها) می‌سازد تا سندها را با ارتباط متنی و facet سریع پیدا و رتبه‌بندی کند.

بدفهمی رایج: «Elasticsearch می‌تواند پایگاه داده اصلی ما باشد.» این یک ایندکس مشتق‌شده است: near-real-time (سند بعد از refresh بعدی ایندکس قابل جست‌وجو می‌شود)، بدون تراکنش چندسندی؛ باید بتوانید آن را از منبع حقیقت دوباره بسازید.

تعریف: Elasticsearch و OpenSearch (fork متن‌باز Elasticsearch) موتورهای توزیع‌شدهٔ جست‌وجو و تحلیل روی Apache Lucene‌اند و full-text search با امتیازدهی BM25، aggregation، typeahead و جست‌وجوی برداری می‌دهند. کنار منبع حقیقت می‌نشینند و با CDC یا outbox تغذیه می‌شوند.

text
     Step   Event                                   Where
1    1      Product updated in MongoDB / order in PostgreSQL       source of truth
2    2      Change stream / Debezium emits change event           CDC
3    3      Indexer upserts document by product_id (idempotent)  OpenSearch
4    4      Search request reads the index after refresh          user sees new price
5    5      Index mapping changes: build new index, alias swap      zero downtime reindex

سناریوی واقعی: جست‌وجوی محصول با facet؛ جست‌وجوی log؛ typeahead؛ جست‌وجوی آگهی در marketplace؛ جست‌وجوی مرکز راهنما. وقتی پیکره کوچک است (ده‌ها هزار ردیف) و رتبه‌بندی ساده، full-text search در PostgreSQL از یک store دوم بی‌نیازتان می‌کند؛ مقایسه در Full-Text Search و خود سیستم در Search Systems است.

نیازFTS در PostgreSQLElasticsearch / OpenSearchMongoDB Atlas Search
رتبه‌بندیts_rank، سادهBM25، function score، learning to rankمبتنی بر Lucene
Facet و aggregationGROUP BY در SQLبومی، سریعfacet
تازگیتراکنشیnear-real-timenear-real-time
store اضافه برای اجرانهبلهمدیریت‌شده داخل Atlas

راه درست: یک ایندکس برای هر aggregate قابل جست‌وجو، یک indexer idempotent با کلید شناسهٔ منبع، و یک job بازسازی کامل که آزموده‌اید.

storeهای time series و ستونی: TimescaleDB، InfluxDB، ClickHouse مهم ​

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

بدفهمی رایج: «metricها فقط ردیف‌اند؛ PostgreSQL عملیاتی ما کافی است.» کافی است، تا روزی که یک داشبورد ساعت ۹ صبح ۵۰۰ میلیون ردیف را روی primary تجمیع کند. partition زمانی (hypertableهای TimescaleDB) یا ذخیره‌سازی ستونی (ClickHouse) هزینه را چند مرتبه عوض می‌کند.

تعریف: workload از نوع time series پرنوشتن، مرتب بر اساس زمان، به‌ندرت به‌روزشونده است و با بازهٔ زمانی، تجمیع و downsampling کوئری می‌شود. hypertableهای TimescaleDB "PostgreSQL tables that automatically partition your time-series data by time" هستند؛ InfluxDB 3 Core "a database built to collect, process, transform, and store event and time series data" است؛ ClickHouse "a column-oriented SQL database management system (DBMS) for online analytical processing (OLAP)" است. ذخیره‌سازی ستونی (Columnar) هر ستون را کنار هم نگه می‌دارد، پس یک تجمیع فقط ستون‌های لازم را می‌خواند و خوب فشرده‌شان می‌کند (ببینید OLTP vs OLAP & Columnar Storage).

text
     Query: average temperature per device per hour, last 7 days, 50,000 devices
1    row store, one table      reads every column of every row in range; index on (device, ts) helps filters, not the scan
2    TimescaleDB hypertable    prunes to 7 daily chunks; compressed chunks; continuous aggregate precomputes hourly
3    ClickHouse MergeTree      reads 3 columns (device, ts, temp), compressed; vectorised aggregation

سناریوی واقعی: telemetry در IoT، metricهای برنامه، tickهای مالی، تحلیل clickstream، impressionهای تبلیغات، backend سامانه‌های observability.

محصولمدلSQLبهترین وقتی
TimescaleDBافزونهٔ PostgreSQL، hypertable، فشرده‌سازی، continuous aggregatePostgreSQL کاملtime series را کنار دادهٔ رابطه‌ای و با join می‌خواهید
InfluxDB 3پایگاه داده اختصاصی time seriesSQL و InfluxQLدریافت metric و رویداد با کوئری بلادرنگ
ClickHouseOLAP ستونی، موتورهای MergeTreeSQL مخصوص ClickHouseپیمایش و تجمیع تحلیلی بزرگ، time series هم
Cassandrapartition به‌ازای دستگاه و سطل زمانیCQLنرخ نوشتن عظیم با خواندن بازه‌ای ساده

راه درست: پایگاه عملیاتی را برای state نگه دارید؛ رویدادها را به store سری زمانی یا ستونی stream کنید؛ retention و downsampling را از روز اول تنظیم کنید.

پایگاه‌های گراف: Neo4j تکمیلی ​

به زبان ساده: وقتی سؤال‌ها دربارهٔ مسیر میان رابطه‌هاست («این دو حساب چطور به هم وصل‌اند؟»)، پایگاه داده گراف رابطه‌ها را رکورد درجه‌یک نگه می‌دارد و مستقیم دنبالشان می‌کند.

بدفهمی رایج: «داده‌های ما رابطه دارند، پس پایگاه گراف لازم داریم.» همهٔ داده‌ها رابطه دارند. store گرافی وقتی می‌ارزد که کوئری‌ها چندین گام با عمق متغیر پیمایش کنند؛ یکی دو join همان چیزی است که رابطه‌ای خوب انجامش می‌دهد.

تعریف: مستندات Neo4j: "A Neo4j graph database stores data as nodes, relationships, and properties instead of in tables or documents." کوئری‌ها با Cypher (یا استاندارد ISO GQL) نوشته می‌شوند. PostgreSQL موارد کم‌عمق را با CTE بازگشتی پوشش می‌دهد؛ ببینید Graph Databases.

text
     Query: accounts within 4 hops of a flagged account through shared devices or cards
1    PostgreSQL   WITH RECURSIVE over an edges table; cost grows quickly with hops and fan-out
2    Neo4j        MATCH (a:Account {flagged:true})-[:USES*1..4]-(b:Account) RETURN DISTINCT b

سناریوی واقعی: حلقه‌های تقلب، پیشنهاد بر اساس خرید مشترک، گراف کنترل دسترسی (ReBAC؛ ببینید Authorization Models)، توپولوژی شبکه، گراف دانش.

گام‌هاPostgreSQLNeo4j
۱ تا ۲join ایندکس‌دار، خوبخوب
۳ تا ۶، متغیرCTE بازگشتی، سریع بزرگ می‌شودبرای همین ساخته شده
تجمیع انبوه روی همهٔ گره‌هاخوبضعیف‌تر

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

پایگاه‌های برداری و pgvector تکمیلی ​

به زبان ساده: embeddingها (فهرست‌هایی از عدد که معنا را نشان می‌دهند) را ذخیره کنید و نزدیک‌ترین‌ها به embedding یک کوئری را پیدا کنید.

بدفهمی رایج: «retrieval-augmented generation یک پایگاه برداری اختصاصی لازم دارد.» pgvector ("Open-source vector similarity search for Postgres") بردارها را کنار همان ردیف‌هایی که توصیف می‌کنند نگه می‌دارد، با ایندکس HNSW و IVFFlat و فیلتر و join در همان کوئری. storeهای اختصاصی (Qdrant، Milvus، Pinecone) در تعداد خیلی زیاد بردار یا با نیازهای خاص فیلتر و multi-tenancy می‌ارزند.

تعریف: پایگاه داده برداری (Vector database) بردارهای پرابعاد را برای جست‌وجوی تقریبی نزدیک‌ترین همسایه (ANN) ایندکس می‌کند و recall را با تأخیر معامله می‌کند. جزئیات در Vector Search & pgvector و ML Systems.

text
     Query: 10 products most similar to an image, only in stock, only category 'shoes'
1    pgvector     SELECT ... FROM products WHERE in_stock AND category = 'shoes'
                  ORDER BY embedding <=> $1 LIMIT 10   -- HNSW index, filters in SQL
2    dedicated    filter by payload in the vector store; stock from a second call or a synced copy

سناریوی واقعی: جست‌وجوی معنایی، RAG روی اسناد، شباهت تصویر، حذف موارد تکراری، پیشنهاد.

مقیاسانتخاب
تا ده‌ها میلیون بردار، فیلتر روی دادهٔ رابطه‌ایpgvector
صدها میلیون تا میلیاردها، فیلتر تخصصیپایگاه برداری اختصاصی

راه درست: با pgvector شروع کنید؛ recall و p99 را اندازه بگیرید؛ وقتی عددها گفتند جابه‌جا شوید.

NewSQL و distributed SQL: Spanner، CockroachDB، YugabyteDB، Vitess مهم ​

به زبان ساده: SQL و تراکنش، اما داده به rangeهایی روی گره‌های زیاد تقسیم و با اجماع replicate شده، پس نوشتن افقی مقیاس می‌گیرد و از دست رفتن گره یا zone را تحمل می‌کند.

بدفهمی رایج: «distributed SQL همان PostgreSQL است که مجانی مقیاس می‌گیرد.» هر نوشتن یک دور اجماع بین replicaهاست (و اگر چنین بچینید، بین regionها)؛ تأخیر نوشتن تک‌ردیف از primary محلی بیشتر است، برخی قابلیت‌ها و افزونه‌های PostgreSQL نیستند، و جای‌گذاری داده مسئلهٔ طراحی شما می‌شود.

تعریف: پایگاه‌های NewSQL (که امروز معمولاً distributed SQL خوانده می‌شوند) SQL رابطه‌ای با تراکنش ACID روی خوشه‌ای shared-nothing می‌دهند. معرفی Spanner در Google Cloud: "A distributed clock called TrueTime guarantees transactions are strongly consistent even across regions. Data is automatically 'split' for scalability and replicated using a synchronous, Paxos-based scheme for availability." CockroachDB rangeها را با Raft replicate می‌کند و تراکنش‌های بین‌range را با "a distributed, atomic commit protocol called Parallel Commits" commit می‌کند. YugabyteDB یک API سازگار با PostgreSQL (YSQL) روی لایهٔ ذخیره‌سازی توزیع‌شده می‌دهد. Vitess از جنس دیگری است: "an open-source database clustering system for horizontal scaling of MySQL" که کوئری‌ها را به شاردهایی از MySQL معمولی می‌فرستد؛ PlanetScale روی آن ساخته شده.

text
     Write: UPDATE accounts SET balance = balance - 100 WHERE id = 7   (3 replicas, 3 zones)
1    gateway node finds the range for id=7 and its leaseholder / leader
2    leader proposes the write intent through Raft (Paxos in Spanner)
3    majority (2 of 3) acknowledges -> committed; latency = one round trip to the nearest quorum
4    multi-region placement: quorum across regions adds tens of milliseconds per write

سناریوی واقعی: دفتر کل یا موجودی جهانی که باید بین regionها سازگار بماند (معرفی Spanner از دفتر کل معاملات و دفتر موجودی خرده‌فروشی نام می‌برد)؛ SaaSی که از یک primary از PostgreSQL بزرگ‌تر شده اما نمی‌تواند SQL را رها کند؛ مجموعه‌ای از MySQL که sharding لازم دارد (Vitess).

محصولAPIاجماعنکته
Google Cloud SpannerGoogleSQL و گویش PostgreSQLPaxos + TrueTimeفقط مدیریت‌شده؛ external consistency
CockroachDBپروتکل wire در PostgreSQLRaft برای هر rangeپیش‌فرض serializable؛ READ COMMITTED هم هست
YugabyteDBYSQL (PostgreSQL)، YCQLRaft برای هر tabletلایهٔ کوئری PostgreSQL را دوباره به کار می‌برد
Vitess / PlanetScaleپروتکل MySQLreplication در MySQL برای هر شاردلایهٔ sharding، نه یک پایگاه اجماعی واحد
TiDBپروتکل MySQLRaft (TiKV)HTAP با TiFlash

راه درست: distributed SQL را وقتی انتخاب کنید که invariantهای SQL و یکی از این دو را لازم دارید: مقیاس نوشتن فراتر از یک primary یا نوشتن چند region؛ locality را صریح طراحی کنید (جدول‌های partitionشده بر اساس region، follower read). سازوکار در Distributed SQL, Consensus & 2PC.

پایگاه‌های serverless: Aurora Serverless، Neon، PlanetScale، DynamoDB on-demand تکمیلی ​

به زبان ساده: به اندازهٔ مصرف پول می‌دهید و ظرفیت دنبال بار می‌رود، گاهی تا صفر.

بدفهمی رایج: «serverless یعنی کشسانی بی‌نهایت و همیشه ارزان‌تر.» مقیاس‌گیری پله و حد دارد، شروع از صفر تأخیر cold start می‌آورد، و بار ثابتِ بالا اغلب روی ظرفیت provisioned ارزان‌تر است.

تعریف: پایگاه داده serverless (Serverless database) صورت‌حساب (و اغلب compute) را از instanceهای ثابت جدا می‌کند. DynamoDB on-demand "offers pay-per-request pricing for read and write requests" و "the default and recommended throughput option for most DynamoDB workloads" است. Aurora Serverless v2 با واحد ظرفیت Aurora (ACU) مقیاس می‌گیرد، می‌تواند "add half an ACU when only a little more capacity is needed" و از کوچک شدن تا صفر ACU با توقف و ادامهٔ خودکار پشتیبانی می‌کند. Neon ذخیره‌سازی را از compute جدا می‌کند تا "compute endpoints can automatically scale up and down according to load, or scale to zero entirely". PlanetScale سرویس مدیریت‌شدهٔ Vitess (MySQL) و Postgres می‌دهد.

text
     Hour    Load       Provisioned (fixed)       Serverless (per use)
1    02:00   ~0         paying for idle            near zero (or paused; first request waits)
2    09:00   10x        throttled or over-sized    scales up in steps
3    13:00   steady     cheaper per unit           more expensive per unit at constant load

سناریوی واقعی: محیط‌های توسعه و preview (branchهای Neon)، ابزارهای داخلی پرنوسان، محصولات تازه با بار نامعلوم، پایگاه داده برای هر مستأجر، backendهای رویدادمحور (Serverless & Event-Driven Compute).

محصولواحد صورت‌حسابرسیدن به صفرموتور
DynamoDB on-demandبه‌ازای درخواست + فضای ذخیرهبله (compute بیکار ندارد)DynamoDB
Aurora Serverless v2ACU-ساعت + I/O + فضای ذخیرهبله، با توقف خودکارسازگار با MySQL / PostgreSQL
Neoncompute-ساعت + فضای ذخیرهبلهPostgreSQL
PlanetScaleبر اساس plan یا clusterبسته به planVitess (MySQL)، Postgres

راه درست: serverless برای بار پرنوسان یا نامعلوم و محیط‌های غیرتولیدی؛ ظرفیت provisioned یا رزروشده وقتی بار ثابت و اندازه‌گیری‌شده است.

Polyglot persistence: یک store برای هر bounded context حیاتی ​

به زبان ساده: بخش‌های مختلف سیستم داده‌شان را در پایگاه‌های مختلف نگه می‌دارند، هرکدام بر اساس اینکه آن بخش چطور از داده استفاده می‌کند انتخاب شده و هرکدام دقیقاً یک مالک (سرویس یا ماژول) دارد.

بدفهمی رایج: «polyglot persistence یعنی هر سرویس پایگاه محبوبش را برمی‌دارد.» یعنی workload انتخاب می‌کند، store یک مالک دارد، و هر store اضافه باید هزینهٔ عملیاتی‌اش را توجیه کند. فاولر: "This will come at a cost in complexity. Each data storage mechanism introduces a new interface to be learned."

تعریف: polyglot persistence یعنی به کار بردن چند فناوری ذخیره‌سازی در یک سیستم، هرکدام پشت یک مرز (یک bounded context، یک ماژول یا یک سرویس). داده‌ای که کانتکست دیگری لازم دارد به‌صورت رویداد (outbox) منتشر یا از log گرفته می‌شود (CDC) و آنجا به‌عنوان read model ذخیره می‌شود؛ store مالک منبع حقیقت می‌ماند. ببینید Data Ownership in Microservices و Data Patterns.

Cart / sessions: Redishash per customer, TTL 7 daysAOF everysec; loss = stale cartno money, no historycheckout reads cart, prices from CatalogCatalog: MongoDBproduct document, variants embeddedattributes differ per product typechange streams outOrdering: PostgreSQLorders + lines + outbox, one transactionFKs, CHECKs, ad-hoc SQLsystem of record for moneyCDC / outbox relayDebezium, change streamsinto Kafka topicsat-least-once, idempotent sinksSearch: OpenSearchfull-text, facets, typeaheadderived, rebuildable indexseconds behind the sourceAnalytics: ClickHousecolumnar, aggregationsrevenue per region per hournever on the OLTP primaryCache invalidationRedis cache keys for productand order pages deleted onchange events

تصویر سه کانتکست مالک (Cart روی Redis، Catalog روی MongoDB، Ordering روی PostgreSQL با جدول outbox) را در چپ نشان می‌دهد؛ تغییرات از مسیر CDC به Kafka می‌روند و از آنجا ایندکس OpenSearch، store تحلیلی ClickHouse و ابطال cache را تغذیه می‌کنند. هیچ سرویسی store دیگری را مستقیم نمی‌خواند.

text
     Step   Event                                                   Store
1    1      Customer adds sku-9 to cart                              Redis (Cart)
2    2      Checkout reads cart, prices each sku                      MongoDB (Catalog)
3    3      Order, lines and outbox row in one transaction            PostgreSQL (Ordering)
4    4      Debezium reads the WAL, publishes OrderPlaced             Kafka
5    5      Indexer updates order search; ETL updates revenue tables  OpenSearch, ClickHouse
6    6      Cache invalidator deletes order-page cache keys           Redis (cache)

سناریوی واقعی: تجارت الکترونیک (در ادامه کار شده)؛ بانکی با دفتر کل روی Oracle، log رویداد روی Kafka و جست‌وجوی مشتری روی Elasticsearch؛ اپ درخواست خودرو با store رابطه‌ای سفرها، ایندکس مکانی و تاریخچهٔ موقعیت به‌صورت time series (Uber case study).

هزینهٔ هر store اضافهیعنی چه
عملیاتbackup، تمرین بازگردانی، ارتقا، پایش، runbook برای on-call
امنیتcredential، قواعد شبکه، رمزنگاری و audit برای هر store
سازگارییک pipeline (CDC/outbox) با lag، بازپخش و reconciliation
مهارتکسی که حالت‌های خرابی‌اش را بشناسد
توسعهٔ محلییک container دیگر در محیط هر توسعه‌دهنده

راه درست: یک مالک برای هر store، هیچ جدول مشترکی بین کانتکست‌ها، همگام‌سازی فقط با رویداد یا CDC، و یک دلیل نوشته‌شده برای هر store. فایل config/database.php در Laravel با یک connection برای هر کانتکست در Laravel است.

مهاجرت بین storeها: dual write، backfill، shadow read مهم ​

به زبان ساده: یک کانتکست را با گام‌های برگشت‌پذیر از یک پایگاه داده به دیگری ببرید، در حالی که ترافیک تولید جریان دارد، و پیش از اعتماد به store تازه ثابت کنید همان جواب‌ها را می‌دهد.

بدفهمی رایج: «dual write امن است اگر در همان درخواست به هر دو بنویسیم.» بدون تراکنشی که هر دو store را بپوشاند، یک نوشتن ممکن است موفق شود و دیگری شکست بخورد؛ dual write باید قابل ترمیم باشد (صف pending، job reconciliation) یا جایش را CDC از store قدیمی بگیرد.

تعریف: Dual write هر نوشتن را اول به primary و بعد به store دیگر می‌فرستد؛ Backfill دادهٔ تاریخی را idempotent کپی می‌کند؛ Shadow read از store قدیمی جواب می‌دهد و هم‌زمان store تازه را هم می‌خواند و تفاوت‌ها را ثبت می‌کند؛ flip store تازه را primary می‌کند در حالی که قدیمی برای بازگشت نگه داشته می‌شود. این روش سمت دادهٔ الگوی Strangler Fig است.

Every arrow is a config flip; every dashed arrow is the rollback0 Old onlyreads: oldwrites: oldport + contract tests1 Dual writereads: oldwrites: old, then newfailed new write queued2 Backfill + shadowcopy history, idempotentread old, also read newlog mismatches to zero3 New primaryreads: newwrites: new, then oldold kept warm4 New onlyold store retiredafter a full cycle(month-end, peaks)Prefer CDC from the primary over application dual writes when the new store can consume a change stream

هر پیکان در تصویر یک تغییر پیکربندی است و هر پیکان خط‌چین مسیر بازگشت؛ یعنی در هیچ مرحله‌ای پل پشت سر خراب نمی‌شود.

text
     Phase          Reads     Writes              Exit criterion
1    0 Old only     old       old                 port in place, contract suite green on both adapters
2    1 Dual write   old       old, then new       failed new writes queued and drained
3    2 Backfill     old       old, then new       history copied; duplicates skipped
4    3 Shadow read  old (+new compared)           mismatch rate 0 for a full business cycle
5    4 New primary  new       new, then old       latency and error SLOs met; rollback rehearsed
6    5 New only     new       new                 old store archived, then removed

سناریوی واقعی: MongoDB به PostgreSQL بعد از رشد نیازهای گزارش‌گیری؛ MySQL شاردشده به Vitess؛ DynamoDB به Aurora بعد از اینکه الگوهای دسترسی دیگر پایدار نماندند؛ Cassandra خودمیزبان به یک سرویس managed.

تکنیکمزیتریسک
Dual write در برنامهساده، بدون زیرساختواگرایی در خرابی جزئی؛ باید صف و ترمیم داشته باشد
CDC از store قدیمییک مسیر نوشتن؛ مرتب بر اساس logابزار CDC لازم است (Debezium، DynamoDB Streams، change streams)
Backfillتاریخچه را می‌آوردبار روی store قدیمی؛ باید idempotent و کنترل‌شده باشد
Shadow readهم‌ارزی را روی ترافیک واقعی ثابت می‌کندبار خواندن دوبرابر؛ مقایسه را بیرون از مسیر داغ انجام دهید
Flip با feature flagبازگشت فوریهر دو store تا بازنشستگی باید همگام بمانند

راه درست: بستهٔ migrate در Go پایین‌تر دو adapter را پشت همان port می‌پیچد، با فاز، صف pending و ثبت mismatch؛ گام‌های سطح schema داخل یک پایگاه داده در Zero-Downtime Schema Migrations است.

سازوکار ​

واحدها، محدودیت‌ها و سقف هر partition در DynamoDB ​

راهنمای partition key در DynamoDB: "Every partition in a DynamoDB table is designed to deliver a maximum capacity of 3,000 read units per second and 1,000 write units per second. One read unit represents one strongly consistent read operation per second, or two eventually consistent read operations per second, for an item up to 4 KB in size. One write unit represents one write operation per second for an item up to 1 KB in size."

تنظیم یا محدودیتمقدارصفحهٔ منبعپیامد طراحی
واحد خواندن (Read unit)یک خواندن قوی 4 KB یا دو خواندن eventualPartition key best practicesآیتم 20 KB برای هر خواندن قوی ۵ واحد می‌خورد
واحد نوشتن (Write unit)نوشتن 1 KBPartition key best practicesهر GSI که آیتم را project می‌کند یک نوشتن دیگر است
throughput هر partition۳۰۰۰ RCU و ۱۰۰۰ WCU در ثانیهPartition key best practicesیک کلید داغ هر قدر جدول بزرگ باشد سقف دارد
اندازهٔ آیتمحداکثر 400 KBLarge items best practicesblobهای بزرگ با یک اشاره‌گر به S3 می‌روند
تراکنشتا ۱۰۰ action، مجموع 4 MB، یک حساب و یک RegionTransactions APIinvariantها را در ۱۰۰ آیتم نگه دارید
GSI در هر جدول۲۰ (قابل افزایش)Service quotasهر مسیر دسترسی یکی خرج دارد
LSI در هر جدول۵، هنگام ساخت جدولService quotasهمان partition key، و محدودیت 10 GB برای item collection
خواندن از GSIفقط eventualGSI pageread-your-writes جدول پایه را لازم دارد
حالت ظرفیتon-demand (پیش‌فرض) یا provisionedCapacity mode pageprovisioned با auto scaling برای بار ثابت

اجرای برنامهٔ اندازه‌گیری آزمایشگاه برای الگوهای Ordering این خروجی را چاپ می‌کند:

text
access pattern                                 units/op    units/s
AP1 place order (2 KB item + 2 KB GSI copy)         4.0        800
AP2 get order, strong                               1.0       1500
AP3 latest 20 orders, eventual                      5.0       2000
AP4 PLACED feed on GSI, eventual                   12.5        250
total: 3750 RCU/s, 800 WCU/s
partitions needed for throughput alone: 2
max strong 2 KB reads/s on ONE key: 3000
max 2 KB writes/s on ONE key: 500
orders storage per year: 139 GB

دو درس از این عددها: کل workload کانتکست Ordering در چند partition (و روی یک primary از PostgreSQL) جا می‌شود، و خطر واقعی یک کلید است. GSIِ وضعیتی که روی PLACED کلید بخورد همهٔ سفارش‌های تازه را روی یک partition از GSI می‌گذارد با سقف ۱۰۰۰ WCU؛ پسوند shard (STATUS#PLACED#0..3) همان چیزی است که این سقف را برمی‌دارد.

محدودیت‌ها و تنظیم‌های مدل‌سازی در MongoDB ​

تنظیم یا محدودیتمقدارپیامد
اندازهٔ سند16 MiB در BSONآرایه‌های بی‌حد باید collection شوند
عمق تودرتویی۱۰۰ سطحبه‌ندرت می‌رسید؛ تودرتویی عمیق خودش بوی بد است
اتمی بودنیک سند، با آرایه‌های تودرتوآنچه باید با هم عوض شود embed کنید
تراکنش چندسندیreplica set یا sharded cluster لازم است؛ مستندات Laravel MongoDB: "your deployment must be a multiple node replica set or sharded cluster"روی سرور مستقل توسعه در دسترس نیست
اعتبارسنجی schemavalidator از نوع $jsonSchema برای هر collectionبه کارش ببرید؛ بی‌schema بودن انتخاب است نه پیش‌فرض
Write concernw: "majority" برای پایداری در failoverمقدارهای پایین‌تر پایداری را با تأخیر معامله می‌کنند

تنظیم‌های persistence و حافظه در Redis ​

text
# redis.conf for a keyspace used as a primary store (carts)
appendonly yes
appendfsync everysec          # "fsync every second ... you may lose 1 second of data"
save 3600 1 300 100 60 10000  # RDB snapshots as well, for backups and faster restarts
maxmemory 4gb
maxmemory-policy noeviction   # never drop a key silently; writes get an error instead
# for a pure cache instance instead:
# appendonly no
# maxmemory-policy allkeys-lru
تنظیممقدارهااثر
appendfsyncalways، everysec (پیش‌فرض)، noمستندات Redis: always "Very very slow, very safe" است؛ no flush را به سیستم‌عامل می‌سپارد ("Normally Linux will flush data every 30 seconds with this configuration")
saveنقطه‌های snapshot (ثانیه، تعداد تغییر)RDB؛ "you should be prepared to lose the latest minutes of data"
قالب AOFmulti part AOF از Redis 7.0.0یک فایل base و فایل‌های incremental که یک manifest ردشان را دارد
maxmemory-policynoeviction، allkeys-lru، allkeys-lfu، volatile-lru، volatile-ttl، ...allkeys-lru برای cache "is a good default option"؛ noeviction برای store
هزینهٔ forkRDB و بازنویسی AOF یک فرزند fork می‌کنندمستندات Redis: ممکن است سرویس‌دهی را "for some milliseconds or even for one second if the dataset is very big" متوقف کند
Cluster۱۶۳۸۴ hash slotدستورهای چندکلیدی باید کلیدها را در یک slot داشته باشند: hash tag مثل cart:{42}

تنظیم‌های PostgreSQL برای دادهٔ منعطف ​

تنظیماثرنکته
json در برابر jsonbjson متن را نگه می‌دارد و دوباره parse می‌کند؛ jsonb "a decomposed binary format" ذخیره می‌کندمستندات PostgreSQL: "most applications should prefer to store JSON data as jsonb"
GIN با jsonb_ops یا jsonb_path_opsjsonb_path_ops کوچک‌تر و سریع‌تر است ولی فقط برای containment با @>پیش‌فرض jsonb_ops عملگرهای وجود کلید را هم پشتیبانی می‌کند
ستون generatedGENERATED ALWAYS AS (attributes ->> 'brand') STOREDیک فیلد داغ JSON را به ستون ایندکس‌دار تبدیل می‌کند
CHECK (jsonb_typeof(...) = 'object')آرایه یا مقدار ساده را جایی که باید object باشد رد می‌کنداعتبارسنجی بدون JSON Schema کامل
ایندکس partialWHERE status = 'PLACED'ایندکس کوچک برای زیرمجموعهٔ داغ (AP4)

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

محصولکد / exceptionپیام (عین متن هر جا مستند شده)retry؟علت معمول در این فصل
PostgreSQLSQLSTATE 23505unique_violationنه؛ ردیف موجود را برگردانیدسفارش retryشده با همان شناسه
PostgreSQLSQLSTATE 23503foreign_key_violationنهسطر برای سفارشی که وجود ندارد
PostgreSQLSQLSTATE 23514check_violationنهتعداد صفر، وضعیت ناشناخته، JSONB غیر object
PostgreSQLSQLSTATE 40001serialization_failureبله، کل تراکنشبه‌روزرسانی هم‌زمان موجودی زیر SERIALIZABLE
DynamoDBConditionalCheckFailedException"The conditional request failed."نهattribute_not_exists(PK) روی سفارش تکراری
DynamoDBProvisionedThroughputExceededException"You exceeded your maximum allowed provisioned throughput for a table or for one or more global secondary indexes."بله، با backoffpartition داغ یا GSI کم‌ظرفیت
DynamoDBItemCollectionSizeLimitExceededException"Collection size exceeded."بله (بعد از تغییر طراحی)جدولی با LSI که یک partition key آن از 10 GB گذشته
DynamoDBTransactionCanceledExceptionدلیل لغو به‌ازای هر actionبسته به دلیلیک شرط در TransactWriteItems شکست خورد
LaravelIlluminate\Database\UniqueConstraintViolationExceptionخطای کلید تکراری driver را می‌پیچدنههمان 23505
Redisپاسخ خطای OOMروی نوشتن‌ها زیر noeviction وقتی به maxmemory رسیدهبعد از آزاد کردن حافظهstore از RAM بزرگ‌تر شده

Go ​

ماژول Go (academy/sql-vs-nosql-decision) یک port و سه adapter دارد. port قرارداد است: یک مجموعه تست رفتاری روی fake درون‌حافظه، روی adapter DynamoDB (با کلاینت fakeی که همان شرط‌های کلید را می‌فهمد) و، وقتی ORDERS_PG_DSN تنظیم شده، روی PostgreSQL اجرا می‌شود. pgx نسخهٔ v5.13.0 به Go 1.25 نیاز دارد و همین directive مربوط به go در ماژول را تعیین می‌کند.

Before ​

store اول انتخاب شده («NoSQL برای مقیاس»)، handler مستقیم با API در DynamoDB حرف می‌زند، جمع مبلغ float است، retry رونویسی می‌کند و تنها راه جواب دادن به «سفارش‌های یک مشتری» یک Scan با فیلتر است که کل جدول را می‌خواند و هزینه‌اش را حساب می‌کند.

go
// Package before shows the shape this chapter argues against: the store
// was chosen first ("we need scale, so NoSQL"), the use case speaks the
// store's API directly, and every new question becomes a table scan.
package before

import (
	"context"
	"strconv"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

type OrderHandler struct {
	DB *dynamodb.Client
}

// PlaceOrder writes a float total, no condition (a retry overwrites), and
// a key that cannot answer "latest orders of a customer".
func (h OrderHandler) PlaceOrder(ctx context.Context, orderID, customerID string, total float64) error {
	_, err := h.DB.PutItem(ctx, &dynamodb.PutItemInput{
		TableName: aws.String("orders"),
		Item: map[string]types.AttributeValue{
			"order_id":    &types.AttributeValueMemberS{Value: orderID},
			"customer_id": &types.AttributeValueMemberS{Value: customerID},
			"total":       &types.AttributeValueMemberN{Value: strconv.FormatFloat(total, 'f', -1, 64)},
		},
	})
	return err
}

// OrdersOfCustomer is the query nobody modelled: a Scan with a filter
// reads (and bills) the whole table, then throws most of it away.
func (h OrderHandler) OrdersOfCustomer(ctx context.Context, customerID string) ([]map[string]types.AttributeValue, error) {
	var out []map[string]types.AttributeValue
	p := dynamodb.NewScanPaginator(h.DB, &dynamodb.ScanInput{
		TableName:        aws.String("orders"),
		FilterExpression: aws.String("customer_id = :c"),
		ExpressionAttributeValues: map[string]types.AttributeValue{
			":c": &types.AttributeValueMemberS{Value: customerID},
		},
	})
	for p.HasMorePages() {
		page, err := p.NextPage(ctx)
		if err != nil {
			return nil, err
		}
		out = append(out, page.Items...)
	}
	return out, nil
}

After ​

port، با الگوهای دسترسی که بالایش نوشته شده. دامنه invariantهای خودش را اعتبارسنجی می‌کند چون storeهای key-value نمی‌توانند CHECK اجرا کنند:

go
// Package orders is the Ordering bounded context. The domain and the use
// cases depend only on the OrderRepository port; PostgreSQL (pgx) and
// DynamoDB (AWS SDK for Go v2) are adapters behind it.
package orders

import (
	"context"
	"errors"
	"time"
)

// The access patterns this context must serve. They were written down
// before any schema, because they decide which store fits.
//
//	AP1 Place an order (one write, idempotent on order ID)       ~200 writes/s peak
//	AP2 Get one order with its lines by customer + order ID      point lookup
//	AP3 List a customer's latest N orders, newest first          range scan on one key
//	AP4 List orders in a status (PLACED) for the warehouse feed  secondary access path
//
// Anything else (ad-hoc reports, revenue per region) goes to the analytics
// store through CDC, not to this repository.

// Status is the lifecycle state of an order.
type Status string

const (
	StatusPlaced  Status = "PLACED"
	StatusPaid    Status = "PAID"
	StatusShipped Status = "SHIPPED"
)

// Line is one product in an order. Lines are owned by the order and are
// always read with it, so document and key-value adapters embed them.
type Line struct {
	SKU        string
	Quantity   int
	PriceCents int64
}

// Order is the aggregate. Money is integer cents, never float.
type Order struct {
	ID         string // time-sortable ID (ULID-style), so IDs sort by creation
	CustomerID string
	Status     Status
	Lines      []Line
	TotalCents int64
	CreatedAt  time.Time
}

// ErrNotFound and ErrDuplicate are the only errors callers branch on.
var (
	ErrNotFound  = errors.New("orders: not found")
	ErrDuplicate = errors.New("orders: duplicate order id")
	ErrInvalid   = errors.New("orders: invalid order")
)

// OrderRepository is the port. Each method maps to one access pattern.
type OrderRepository interface {
	Save(ctx context.Context, o Order) error                                           // AP1
	Get(ctx context.Context, customerID, orderID string) (Order, error)                // AP2
	ListByCustomer(ctx context.Context, customerID string, limit int) ([]Order, error) // AP3
	ListByStatus(ctx context.Context, status Status, limit int) ([]Order, error)       // AP4
}

// Validate enforces the invariants every adapter relies on. A relational
// store would also enforce them with CHECK constraints; key-value stores
// cannot, so the domain must.
func (o Order) Validate() error {
	if o.ID == "" || o.CustomerID == "" || len(o.Lines) == 0 {
		return ErrInvalid
	}
	var total int64
	for _, l := range o.Lines {
		if l.Quantity <= 0 || l.PriceCents < 0 {
			return ErrInvalid
		}
		total += int64(l.Quantity) * l.PriceCents
	}
	if total != o.TotalCents {
		return ErrInvalid
	}
	return nil
}
go
package orders

import (
	"context"
	"errors"
	"time"
)

// Service holds the use cases. It never imports a driver.
type Service struct {
	Repo  OrderRepository
	Clock func() time.Time
}

// PlaceOrder computes the total, validates and saves. A retried request
// with the same order ID returns the stored order instead of a second one.
func (s Service) PlaceOrder(ctx context.Context, id, customerID string, lines []Line) (Order, error) {
	o := Order{ID: id, CustomerID: customerID, Status: StatusPlaced, Lines: lines, CreatedAt: s.Clock().UTC()}
	for _, l := range lines {
		o.TotalCents += int64(l.Quantity) * l.PriceCents
	}
	if err := o.Validate(); err != nil {
		return Order{}, err
	}
	err := s.Repo.Save(ctx, o)
	if errors.Is(err, ErrDuplicate) {
		return s.Repo.Get(ctx, customerID, id)
	}
	return o, err
}

adapter برای PostgreSQL با pgx. pgx.BeginFunc سفارش، سطرهایش (با یک insert از نوع unnest) و ردیف outbox را در یک تراکنش می‌پیچد؛ SQLSTATE 23505 به ErrDuplicate تبدیل می‌شود؛ فهرست‌ها سطرها را با = ANY($1) بار می‌کنند و نه با N+1 کوئری:

go
package orders

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
)

// PGDB is the subset of *pgxpool.Pool the adapter needs; *pgxpool.Pool
// and pgx.Tx both satisfy it.
type PGDB interface {
	Begin(ctx context.Context) (pgx.Tx, error)
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
}

// Postgres implements OrderRepository on the schema in sql/schema.sql.
type Postgres struct{ DB PGDB }

const uniqueViolation = "23505" // SQLSTATE unique_violation

func (p Postgres) Save(ctx context.Context, o Order) error {
	if err := o.Validate(); err != nil {
		return err
	}
	err := pgx.BeginFunc(ctx, p.DB, func(tx pgx.Tx) error {
		if _, err := tx.Exec(ctx,
			`INSERT INTO orders (id, customer_id, status, total_cents, created_at)
			 VALUES ($1, $2, $3, $4, $5)`,
			o.ID, o.CustomerID, string(o.Status), o.TotalCents, o.CreatedAt); err != nil {
			return err
		}
		skus, qty, price, nos := make([]string, 0, len(o.Lines)), make([]int32, 0, len(o.Lines)),
			make([]int64, 0, len(o.Lines)), make([]int32, 0, len(o.Lines))
		for i, l := range o.Lines {
			skus, qty, price, nos = append(skus, l.SKU), append(qty, int32(l.Quantity)),
				append(price, l.PriceCents), append(nos, int32(i+1))
		}
		// One statement for all lines: unnest the arrays into rows.
		if _, err := tx.Exec(ctx,
			`INSERT INTO order_lines (order_id, line_no, sku, quantity, price_cents)
			 SELECT $1::text, * FROM unnest($2::int[], $3::text[], $4::int[], $5::bigint[])`,
			o.ID, nos, skus, qty, price); err != nil {
			return err
		}
		// Same transaction: the event other stores consume (see migrate/ and CDC).
		_, err := tx.Exec(ctx,
			`INSERT INTO outbox (aggregate_id, event_type, payload)
			 VALUES ($1, 'OrderPlaced', jsonb_build_object('order_id', $1::text, 'customer_id', $2::text, 'total_cents', $3::bigint))`,
			o.ID, o.CustomerID, o.TotalCents)
		return err
	})
	var pgErr *pgconn.PgError
	if errors.As(err, &pgErr) && pgErr.Code == uniqueViolation {
		return ErrDuplicate
	}
	return err
}

func (p Postgres) Get(ctx context.Context, customerID, orderID string) (Order, error) {
	list, err := p.queryOrders(ctx,
		`SELECT id, customer_id, status, total_cents, created_at FROM orders
		 WHERE customer_id = $1 AND id = $2`, customerID, orderID)
	if err != nil {
		return Order{}, err
	}
	if len(list) == 0 {
		return Order{}, ErrNotFound
	}
	return list[0], nil
}

func (p Postgres) ListByCustomer(ctx context.Context, customerID string, limit int) ([]Order, error) {
	return p.queryOrders(ctx,
		`SELECT id, customer_id, status, total_cents, created_at FROM orders
		 WHERE customer_id = $1 ORDER BY id DESC LIMIT $2`, customerID, limit)
}

func (p Postgres) ListByStatus(ctx context.Context, status Status, limit int) ([]Order, error) {
	return p.queryOrders(ctx,
		`SELECT id, customer_id, status, total_cents, created_at FROM orders
		 WHERE status = $1 ORDER BY id DESC LIMIT $2`, string(status), limit)
}

// queryOrders loads headers, then all their lines in one round trip
// (WHERE order_id = ANY($1)), avoiding N+1 queries.
func (p Postgres) queryOrders(ctx context.Context, sql string, args ...any) ([]Order, error) {
	rows, err := p.DB.Query(ctx, sql, args...)
	if err != nil {
		return nil, err
	}
	list, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Order, error) {
		var o Order
		var st string
		err := r.Scan(&o.ID, &o.CustomerID, &st, &o.TotalCents, &o.CreatedAt)
		o.Status = Status(st)
		return o, err
	})
	if err != nil || len(list) == 0 {
		return list, err
	}
	ids := make([]string, len(list))
	pos := make(map[string]int, len(list))
	for i, o := range list {
		ids[i], pos[o.ID] = o.ID, i
	}
	lrows, err := p.DB.Query(ctx,
		`SELECT order_id, sku, quantity, price_cents FROM order_lines
		 WHERE order_id = ANY($1) ORDER BY order_id, line_no`, ids)
	if err != nil {
		return nil, err
	}
	defer lrows.Close()
	for lrows.Next() {
		var id string
		var l Line
		if err := lrows.Scan(&id, &l.SKU, &l.Quantity, &l.PriceCents); err != nil {
			return nil, err
		}
		list[pos[id]].Lines = append(list[pos[id]].Lines, l)
	}
	return list, lrows.Err()
}

adapter برای DynamoDB با AWS SDK for Go v2، با single-table design. PutItem با attribute_not_exists(PK) ساختن را idempotent می‌کند، GetItem از ConsistentRead استفاده می‌کند، AP3 یک Query با begins_with و ترتیب نزولی است و AP4 یک scatter-gather روی چهار shard از GSI:

go
package orders

import (
	"context"
	"errors"
	"fmt"
	"hash/fnv"
	"sort"
	"strconv"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// DynamoAPI is the subset of *dynamodb.Client the adapter uses, so tests
// can pass a fake. The method signatures are the SDK's own.
type DynamoAPI interface {
	PutItem(ctx context.Context, in *dynamodb.PutItemInput, opts ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error)
	GetItem(ctx context.Context, in *dynamodb.GetItemInput, opts ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error)
	Query(ctx context.Context, in *dynamodb.QueryInput, opts ...func(*dynamodb.Options)) (*dynamodb.QueryOutput, error)
}

// Single-table design: every entity of the Ordering context lives in one
// table; the key layout, not the table name, separates them.
//
//	Entity    PK            SK              GSI1PK                 GSI1SK
//	Customer  CUST#c-42     PROFILE         -                      -
//	Order     CUST#c-42     ORDER#01J..     STATUS#PLACED#3        01J..
//
// AP2 = GetItem(PK, SK). AP3 = Query(PK, begins_with(SK, "ORDER#")) newest
// first. AP4 = Query on GSI1 per shard, merged. Lines are embedded in the
// order item (read together, written together, bounded in number).
type Dynamo struct {
	Client DynamoAPI
	Table  string
	// StatusShards spreads one status over N GSI partition keys; a GSI on a
	// three-value attribute would otherwise be a hot partition.
	StatusShards int
}

type orderItem struct {
	PK, SK         string
	Type           string
	GSI1PK, GSI1SK string
	OrderID        string
	CustomerID     string
	Status         string
	TotalCents     int64
	CreatedAt      string
	Lines          []lineItem
}

type lineItem struct {
	SKU        string `dynamodbav:"sku"`
	Quantity   int    `dynamodbav:"qty"`
	PriceCents int64  `dynamodbav:"price"`
}

func customerPK(id string) string { return "CUST#" + id }
func orderSK(id string) string    { return "ORDER#" + id }

func (d Dynamo) shards() int {
	if d.StatusShards < 1 {
		return 1
	}
	return d.StatusShards
}

func (d Dynamo) statusPK(s Status, orderID string) string {
	h := fnv.New32a()
	h.Write([]byte(orderID))
	return fmt.Sprintf("STATUS#%s#%d", s, int(h.Sum32())%d.shards())
}

func (d Dynamo) toItem(o Order) orderItem {
	it := orderItem{
		PK: customerPK(o.CustomerID), SK: orderSK(o.ID), Type: "ORDER",
		GSI1PK: d.statusPK(o.Status, o.ID), GSI1SK: o.ID,
		OrderID: o.ID, CustomerID: o.CustomerID, Status: string(o.Status),
		TotalCents: o.TotalCents, CreatedAt: o.CreatedAt.UTC().Format(time.RFC3339Nano),
	}
	for _, l := range o.Lines {
		it.Lines = append(it.Lines, lineItem(l))
	}
	return it
}

func fromItem(it orderItem) (Order, error) {
	t, err := time.Parse(time.RFC3339Nano, it.CreatedAt)
	o := Order{ID: it.OrderID, CustomerID: it.CustomerID, Status: Status(it.Status), TotalCents: it.TotalCents, CreatedAt: t}
	for _, l := range it.Lines {
		o.Lines = append(o.Lines, Line(l))
	}
	return o, err
}

func (d Dynamo) Save(ctx context.Context, o Order) error {
	if err := o.Validate(); err != nil {
		return err
	}
	av, err := attributevalue.MarshalMap(d.toItem(o))
	if err != nil {
		return err
	}
	_, err = d.Client.PutItem(ctx, &dynamodb.PutItemInput{
		TableName: aws.String(d.Table),
		Item:      av,
		// Idempotent create: refuse to overwrite an existing order.
		ConditionExpression: aws.String("attribute_not_exists(PK)"),
	})
	var ccf *types.ConditionalCheckFailedException
	if errors.As(err, &ccf) {
		return ErrDuplicate
	}
	return err
}

func (d Dynamo) Get(ctx context.Context, customerID, orderID string) (Order, error) {
	out, err := d.Client.GetItem(ctx, &dynamodb.GetItemInput{
		TableName: aws.String(d.Table),
		Key: map[string]types.AttributeValue{
			"PK": &types.AttributeValueMemberS{Value: customerPK(customerID)},
			"SK": &types.AttributeValueMemberS{Value: orderSK(orderID)},
		},
		ConsistentRead: aws.Bool(true), // base table only; GSIs are eventually consistent
	})
	if err != nil {
		return Order{}, err
	}
	if len(out.Item) == 0 {
		return Order{}, ErrNotFound
	}
	var it orderItem
	if err := attributevalue.UnmarshalMap(out.Item, &it); err != nil {
		return Order{}, err
	}
	return fromItem(it)
}

func (d Dynamo) ListByCustomer(ctx context.Context, customerID string, limit int) ([]Order, error) {
	return d.query(ctx, &dynamodb.QueryInput{
		TableName:              aws.String(d.Table),
		KeyConditionExpression: aws.String("PK = :pk AND begins_with(SK, :prefix)"),
		ExpressionAttributeValues: map[string]types.AttributeValue{
			":pk":     &types.AttributeValueMemberS{Value: customerPK(customerID)},
			":prefix": &types.AttributeValueMemberS{Value: "ORDER#"},
		},
		ScanIndexForward: aws.Bool(false), // newest first: sort key descending
		Limit:            aws.Int32(int32(limit)),
	})
}

// ListByStatus is a scatter-gather over the write shards of GSI1.
func (d Dynamo) ListByStatus(ctx context.Context, status Status, limit int) ([]Order, error) {
	var all []Order
	for s := 0; s < d.shards(); s++ {
		part, err := d.query(ctx, &dynamodb.QueryInput{
			TableName:              aws.String(d.Table),
			IndexName:              aws.String("GSI1"),
			KeyConditionExpression: aws.String("GSI1PK = :pk"),
			ExpressionAttributeValues: map[string]types.AttributeValue{
				":pk": &types.AttributeValueMemberS{Value: "STATUS#" + string(status) + "#" + strconv.Itoa(s)},
			},
			ScanIndexForward: aws.Bool(false),
			Limit:            aws.Int32(int32(limit)),
		})
		if err != nil {
			return nil, err
		}
		all = append(all, part...)
	}
	sort.Slice(all, func(i, j int) bool { return all[i].ID > all[j].ID })
	if len(all) > limit {
		all = all[:limit]
	}
	return all, nil
}

func (d Dynamo) query(ctx context.Context, in *dynamodb.QueryInput) ([]Order, error) {
	out, err := d.Client.Query(ctx, in)
	if err != nil {
		return nil, err
	}
	var items []orderItem
	if err := attributevalue.UnmarshalListOfMaps(out.Items, &items); err != nil {
		return nil, err
	}
	list := make([]Order, 0, len(items))
	for _, it := range items {
		o, err := fromItem(it)
		if err != nil {
			return nil, err
		}
		list = append(list, o)
	}
	return list, nil
}

fake درون‌حافظه و مجموعهٔ قرارداد. همان چهار تست روی همهٔ adapterها اجرا می‌شود؛ storeی که نتواند از آن‌ها رد شود نمی‌تواند به این کانتکست خدمت کند:

go
package orders

import (
	"context"
	"sort"
	"sync"
)

// Memory is the in-process fake used by use-case tests and as the
// reference behaviour every real adapter must match.
type Memory struct {
	mu   sync.Mutex
	rows map[string]Order // key: customerID + "/" + orderID
}

func NewMemory() *Memory { return &Memory{rows: map[string]Order{}} }

func (m *Memory) Save(_ context.Context, o Order) error {
	if err := o.Validate(); err != nil {
		return err
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	k := o.CustomerID + "/" + o.ID
	if _, ok := m.rows[k]; ok {
		return ErrDuplicate
	}
	o.Lines = append([]Line(nil), o.Lines...)
	m.rows[k] = o
	return nil
}

func (m *Memory) Get(_ context.Context, customerID, orderID string) (Order, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	o, ok := m.rows[customerID+"/"+orderID]
	if !ok {
		return Order{}, ErrNotFound
	}
	return o, nil
}

func (m *Memory) ListByCustomer(_ context.Context, customerID string, limit int) ([]Order, error) {
	return m.list(func(o Order) bool { return o.CustomerID == customerID }, limit), nil
}

func (m *Memory) ListByStatus(_ context.Context, status Status, limit int) ([]Order, error) {
	return m.list(func(o Order) bool { return o.Status == status }, limit), nil
}

func (m *Memory) list(keep func(Order) bool, limit int) []Order {
	m.mu.Lock()
	defer m.mu.Unlock()
	var out []Order
	for _, o := range m.rows {
		if keep(o) {
			out = append(out, o)
		}
	}
	// Newest first; IDs are time-sortable so ID order equals creation order.
	sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
	if limit > 0 && len(out) > limit {
		out = out[:limit]
	}
	return out
}
go
package orders

import (
	"context"
	"sort"
	"strings"
	"sync"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// fakeDynamo understands exactly the key conditions the adapter sends:
// PK = :pk [AND begins_with(SK, :prefix)] on the table, GSI1PK = :pk on GSI1.
type fakeDynamo struct {
	mu    sync.Mutex
	items map[string]map[string]types.AttributeValue
}

func newFakeDynamo() *fakeDynamo {
	return &fakeDynamo{items: map[string]map[string]types.AttributeValue{}}
}

func s(av types.AttributeValue) string {
	if v, ok := av.(*types.AttributeValueMemberS); ok {
		return v.Value
	}
	return ""
}

func (f *fakeDynamo) PutItem(_ context.Context, in *dynamodb.PutItemInput, _ ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	k := s(in.Item["PK"]) + "|" + s(in.Item["SK"])
	if _, exists := f.items[k]; exists && aws.ToString(in.ConditionExpression) == "attribute_not_exists(PK)" {
		return nil, &types.ConditionalCheckFailedException{Message: aws.String("The conditional request failed")}
	}
	f.items[k] = in.Item
	return &dynamodb.PutItemOutput{}, nil
}

func (f *fakeDynamo) GetItem(_ context.Context, in *dynamodb.GetItemInput, _ ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	return &dynamodb.GetItemOutput{Item: f.items[s(in.Key["PK"])+"|"+s(in.Key["SK"])]}, nil
}

func (f *fakeDynamo) Query(_ context.Context, in *dynamodb.QueryInput, _ ...func(*dynamodb.Options)) (*dynamodb.QueryOutput, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	pk := s(in.ExpressionAttributeValues[":pk"])
	prefix := s(in.ExpressionAttributeValues[":prefix"])
	pkAttr, skAttr := "PK", "SK"
	if aws.ToString(in.IndexName) == "GSI1" {
		pkAttr, skAttr = "GSI1PK", "GSI1SK"
	}
	var out []map[string]types.AttributeValue
	for _, it := range f.items {
		if s(it[pkAttr]) == pk && strings.HasPrefix(s(it[skAttr]), prefix) {
			out = append(out, it)
		}
	}
	desc := in.ScanIndexForward != nil && !*in.ScanIndexForward
	sort.Slice(out, func(i, j int) bool {
		if desc {
			return s(out[i][skAttr]) > s(out[j][skAttr])
		}
		return s(out[i][skAttr]) < s(out[j][skAttr])
	})
	if in.Limit != nil && int(*in.Limit) < len(out) {
		out = out[:*in.Limit]
	}
	return &dynamodb.QueryOutput{Items: out, Count: int32(len(out))}, nil
}
go
package orders

import (
	"context"
	"errors"
	"os"
	"testing"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
)

// One behavioural suite, run against every adapter: the port is the
// contract, and a store is only a candidate if it passes.
func repoContract(t *testing.T, newRepo func(t *testing.T) OrderRepository) {
	ctx := context.Background()
	base := time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC)
	svc := func(r OrderRepository, n int) Service {
		return Service{Repo: r, Clock: func() time.Time { return base.Add(time.Duration(n) * time.Minute) }}
	}
	lines := []Line{{SKU: "book-1", Quantity: 2, PriceCents: 1500}, {SKU: "pen-7", Quantity: 1, PriceCents: 250}}

	t.Run("AP1 place is idempotent on order id", func(t *testing.T) {
		r := newRepo(t)
		a, err := svc(r, 0).PlaceOrder(ctx, "01J0000001", "c-42", lines)
		if err != nil {
			t.Fatal(err)
		}
		b, err := svc(r, 5).PlaceOrder(ctx, "01J0000001", "c-42", lines)
		if err != nil {
			t.Fatal(err)
		}
		if a.TotalCents != 3250 || !b.CreatedAt.Equal(a.CreatedAt) {
			t.Fatalf("retry must return the first order: %+v vs %+v", a, b)
		}
		if err := r.Save(ctx, a); !errors.Is(err, ErrDuplicate) {
			t.Fatalf("want ErrDuplicate, got %v", err)
		}
	})

	t.Run("AP2 get returns lines; missing is ErrNotFound", func(t *testing.T) {
		r := newRepo(t)
		if _, err := svc(r, 0).PlaceOrder(ctx, "01J0000002", "c-42", lines); err != nil {
			t.Fatal(err)
		}
		o, err := r.Get(ctx, "c-42", "01J0000002")
		if err != nil || len(o.Lines) != 2 || o.Lines[0].SKU != "book-1" {
			t.Fatalf("get: %+v %v", o, err)
		}
		if _, err := r.Get(ctx, "c-42", "nope"); !errors.Is(err, ErrNotFound) {
			t.Fatalf("want ErrNotFound, got %v", err)
		}
	})

	t.Run("AP3 and AP4 newest first with limit", func(t *testing.T) {
		r := newRepo(t)
		for i, id := range []string{"01J0000010", "01J0000011", "01J0000012"} {
			if _, err := svc(r, i).PlaceOrder(ctx, id, "c-7", lines); err != nil {
				t.Fatal(err)
			}
		}
		if _, err := svc(r, 9).PlaceOrder(ctx, "01J0000013", "c-8", lines); err != nil {
			t.Fatal(err)
		}
		got, err := r.ListByCustomer(ctx, "c-7", 2)
		if err != nil || len(got) != 2 || got[0].ID != "01J0000012" || got[1].ID != "01J0000011" {
			t.Fatalf("by customer: %+v %v", got, err)
		}
		placed, err := r.ListByStatus(ctx, StatusPlaced, 3)
		if err != nil || len(placed) != 3 || placed[0].ID != "01J0000013" {
			t.Fatalf("by status: %+v %v", placed, err)
		}
	})

	t.Run("invalid order never reaches the store", func(t *testing.T) {
		r := newRepo(t)
		bad := Order{ID: "x", CustomerID: "c", Lines: []Line{{SKU: "a", Quantity: 0, PriceCents: 1}}}
		if err := r.Save(ctx, bad); !errors.Is(err, ErrInvalid) {
			t.Fatalf("want ErrInvalid, got %v", err)
		}
	})
}

func TestMemoryContract(t *testing.T) {
	repoContract(t, func(*testing.T) OrderRepository { return NewMemory() })
}

func TestDynamoContract(t *testing.T) {
	repoContract(t, func(*testing.T) OrderRepository {
		return Dynamo{Client: newFakeDynamo(), Table: "ordering", StatusShards: 4}
	})
}

// TestPostgresContract runs only when ORDERS_PG_DSN points at a scratch
// database that already has sql/schema.sql applied, for example
// ORDERS_PG_DSN=postgres://app:app@localhost:5432/orders_test
func TestPostgresContract(t *testing.T) {
	dsn := os.Getenv("ORDERS_PG_DSN")
	if dsn == "" {
		t.Skip("ORDERS_PG_DSN not set")
	}
	repoContract(t, func(t *testing.T) OrderRepository {
		pool, err := pgxpool.New(context.Background(), dsn)
		if err != nil {
			t.Fatal(err)
		}
		t.Cleanup(pool.Close)
		if _, err := pool.Exec(context.Background(), "TRUNCATE orders, order_lines, outbox"); err != nil {
			t.Fatal(err)
		}
		return Postgres{DB: pool}
	})
}

func TestStatusKeySpreadsOverShards(t *testing.T) {
	d := Dynamo{StatusShards: 4}
	seen := map[string]bool{}
	for _, id := range []string{"01J1", "01J2", "01J3", "01J4", "01J5", "01J6", "01J7", "01J8"} {
		seen[d.statusPK(StatusPlaced, id)] = true
	}
	if len(seen) < 2 {
		t.Fatalf("all orders landed on one GSI partition: %v", seen)
	}
}

پوستهٔ مهاجرت: dual write، backfill، shadow read، flip. هر فاز یک مقدار از Phase است؛ نوشتن‌های ناموفق در store دوم برای backfill صف می‌شوند؛ shadow read بدون اثر روی پاسخ، mismatchها را ثبت می‌کند:

go
// Package migrate moves the Ordering context from one store to another
// without a big-bang cutover: dual write, backfill, shadow read, then flip.
package migrate

import (
	"context"
	"errors"
	"reflect"
	"sync"

	"academy/sql-vs-nosql-decision/orders"
)

// Phase is where the migration stands. Each phase is a config flip, and
// each can be rolled back to the previous one.
type Phase int

const (
	OldOnly    Phase = iota // reads and writes on the old store
	DualWrite               // writes to both, reads from old
	ShadowRead              // writes to both, reads from old, new compared in the background
	NewPrimary              // writes to both, reads from new (old kept for rollback)
	NewOnly                 // old store retired
)

// Mismatch is recorded when the shadow read disagrees with the primary.
type Mismatch struct {
	CustomerID, OrderID string
	Reason              string
}

// Repo wraps two adapters behind the same port.
type Repo struct {
	Old, New orders.OrderRepository
	Phase    Phase

	mu         sync.Mutex
	Mismatches []Mismatch
	Pending    []orders.Order // secondary writes that failed; the backfill job retries them
}

var _ orders.OrderRepository = (*Repo)(nil)

func (r *Repo) primary() orders.OrderRepository {
	if r.Phase >= NewPrimary {
		return r.New
	}
	return r.Old
}

func (r *Repo) secondary() orders.OrderRepository {
	switch {
	case r.Phase == OldOnly || r.Phase == NewOnly:
		return nil
	case r.Phase >= NewPrimary:
		return r.Old
	default:
		return r.New
	}
}

// Save writes the primary first; only its result decides success. A failed
// secondary write is queued, never surfaced: dual write without a
// transaction across stores cannot be atomic, so it must be repairable.
func (r *Repo) Save(ctx context.Context, o orders.Order) error {
	if err := r.primary().Save(ctx, o); err != nil {
		return err
	}
	if sec := r.secondary(); sec != nil {
		if err := sec.Save(ctx, o); err != nil && !errors.Is(err, orders.ErrDuplicate) {
			r.mu.Lock()
			r.Pending = append(r.Pending, o)
			r.mu.Unlock()
		}
	}
	return nil
}

// Get serves from the primary; in ShadowRead it also reads the new store
// and records any difference. The caller never sees the shadow result.
func (r *Repo) Get(ctx context.Context, customerID, orderID string) (orders.Order, error) {
	o, err := r.primary().Get(ctx, customerID, orderID)
	if r.Phase == ShadowRead {
		so, serr := r.New.Get(ctx, customerID, orderID)
		switch {
		case errors.Is(err, orders.ErrNotFound) != errors.Is(serr, orders.ErrNotFound):
			r.record(customerID, orderID, "presence differs")
		case err == nil && serr == nil && !sameOrder(o, so):
			r.record(customerID, orderID, "content differs")
		}
	}
	return o, err
}

func (r *Repo) ListByCustomer(ctx context.Context, customerID string, limit int) ([]orders.Order, error) {
	return r.primary().ListByCustomer(ctx, customerID, limit)
}

func (r *Repo) ListByStatus(ctx context.Context, status orders.Status, limit int) ([]orders.Order, error) {
	return r.primary().ListByStatus(ctx, status, limit)
}

func (r *Repo) record(c, o, reason string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.Mismatches = append(r.Mismatches, Mismatch{CustomerID: c, OrderID: o, Reason: reason})
}

func sameOrder(a, b orders.Order) bool {
	return a.ID == b.ID && a.CustomerID == b.CustomerID && a.Status == b.Status &&
		a.TotalCents == b.TotalCents && a.CreatedAt.Equal(b.CreatedAt) && reflect.DeepEqual(a.Lines, b.Lines)
}

// Backfill copies historical orders (from a snapshot or an export of the
// old store) into the new one. It is idempotent: ErrDuplicate means the
// dual write already copied that order.
func Backfill(ctx context.Context, history []orders.Order, dst orders.OrderRepository) (copied, skipped int, err error) {
	for _, o := range history {
		switch e := dst.Save(ctx, o); {
		case e == nil:
			copied++
		case errors.Is(e, orders.ErrDuplicate):
			skipped++
		default:
			return copied, skipped, e
		}
	}
	return copied, skipped, nil
}
go
package migrate

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/sql-vs-nosql-decision/orders"
)

type flaky struct {
	orders.OrderRepository
	fail bool
}

func (f *flaky) Save(ctx context.Context, o orders.Order) error {
	if f.fail {
		return errors.New("new store unavailable")
	}
	return f.OrderRepository.Save(ctx, o)
}

func order(id string) orders.Order {
	return orders.Order{ID: id, CustomerID: "c-1", Status: orders.StatusPlaced,
		Lines: []orders.Line{{SKU: "a", Quantity: 1, PriceCents: 100}}, TotalCents: 100,
		CreatedAt: time.Date(2026, 11, 26, 0, 0, 0, 0, time.UTC)}
}

func TestMigrationPhases(t *testing.T) {
	ctx := context.Background()
	oldRepo, newMem := orders.NewMemory(), orders.NewMemory()
	newRepo := &flaky{OrderRepository: newMem}
	r := &Repo{Old: oldRepo, New: newRepo, Phase: OldOnly}

	// History written before the migration exists only in the old store.
	_ = r.Save(ctx, order("01A"))

	r.Phase = DualWrite
	_ = r.Save(ctx, order("01B"))
	newRepo.fail = true
	if err := r.Save(ctx, order("01C")); err != nil {
		t.Fatalf("a failed secondary write must not fail the request: %v", err)
	}
	newRepo.fail = false
	if len(r.Pending) != 1 {
		t.Fatalf("want 1 pending repair, got %d", len(r.Pending))
	}

	// Backfill the history plus the pending repairs; 01B is skipped as a duplicate.
	copied, skipped, err := Backfill(ctx, append([]orders.Order{order("01A"), order("01B")}, r.Pending...), newRepo)
	if err != nil || copied != 2 || skipped != 1 {
		t.Fatalf("backfill copied=%d skipped=%d err=%v", copied, skipped, err)
	}

	r.Phase = ShadowRead
	for _, id := range []string{"01A", "01B", "01C"} {
		if _, err := r.Get(ctx, "c-1", id); err != nil {
			t.Fatal(err)
		}
	}
	if len(r.Mismatches) != 0 {
		t.Fatalf("stores should agree after backfill: %+v", r.Mismatches)
	}

	// A write that reached only the old store is caught by the shadow read.
	_ = oldRepo.Save(ctx, order("01D"))
	if _, err := r.Get(ctx, "c-1", "01D"); err != nil {
		t.Fatal(err)
	}
	if len(r.Mismatches) != 1 || r.Mismatches[0].Reason != "presence differs" {
		t.Fatalf("want one presence mismatch, got %+v", r.Mismatches)
	}

	r.Phase = NewPrimary
	if _, err := r.Get(ctx, "c-1", "01D"); !errors.Is(err, orders.ErrNotFound) {
		t.Fatalf("after the flip reads come from the new store: %v", err)
	}
}

اندازه‌گیری از روی جدول الگوهای دسترسی (خروجی در سازوکار):

go
// Command sizing turns an access-pattern table into DynamoDB capacity
// units and a per-key ceiling, using the unit sizes and per-partition
// limits from the DynamoDB Developer Guide (4 KB read unit, 1 KB write
// unit, 3,000 RCU and 1,000 WCU per partition). Run: go run ./sizing
package main

import (
	"fmt"
	"math"
)

type pattern struct {
	name      string
	perSecond float64 // peak operations per second
	itemKB    float64 // bytes touched per operation, in KB
	write     bool
	strong    bool // strongly consistent read (base table only)
	items     float64
}

const (
	readUnitKB, writeUnitKB = 4.0, 1.0
	partitionRCU            = 3000.0
	partitionWCU            = 1000.0
)

func units(p pattern) float64 {
	if p.write {
		return math.Ceil(p.itemKB/writeUnitKB) * p.items
	}
	u := math.Ceil(p.itemKB/readUnitKB) * p.items
	if !p.strong {
		u /= 2 // eventually consistent reads cost half
	}
	return u
}

func main() {
	ps := []pattern{
		{name: "AP1 place order (2 KB item + 2 KB GSI copy)", perSecond: 200, itemKB: 2, write: true, items: 2},
		{name: "AP2 get order, strong", perSecond: 1500, itemKB: 2, strong: true, items: 1},
		{name: "AP3 latest 20 orders, eventual", perSecond: 400, itemKB: 40, items: 1},
		{name: "AP4 PLACED feed on GSI, eventual", perSecond: 20, itemKB: 100, items: 1},
	}
	var rcu, wcu float64
	fmt.Printf("%-46s %8s %10s\n", "access pattern", "units/op", "units/s")
	for _, p := range ps {
		u := units(p)
		fmt.Printf("%-46s %8.1f %10.0f\n", p.name, u, u*p.perSecond)
		if p.write {
			wcu += u * p.perSecond
		} else {
			rcu += u * p.perSecond
		}
	}
	fmt.Printf("total: %.0f RCU/s, %.0f WCU/s\n", rcu, wcu)
	fmt.Printf("partitions needed for throughput alone: %.0f\n", math.Ceil(math.Max(rcu/partitionRCU, wcu/partitionWCU)))
	// One hot key (a celebrity customer, one status value) is capped by a
	// single partition no matter how big the table is.
	fmt.Printf("max strong 2 KB reads/s on ONE key: %.0f\n", partitionRCU/math.Ceil(2/readUnitKB))
	fmt.Printf("max 2 KB writes/s on ONE key: %.0f\n", partitionWCU/math.Ceil(2/writeUnitKB))
	// Storage, for the relational-vs-NoSQL "scale ceiling" question.
	ordersPerDay, kb := 200000.0, 2.0
	fmt.Printf("orders storage per year: %.0f GB\n", ordersPerDay*365*kb/1024/1024)
}

نگاه Go ​

بستهٔ Goکاربرد اینجانکته
github.com/jackc/pgx/v5pgx.BeginFunc، pgx.CollectRows، پارامتر آرایه‌ایپروتکل بومی PostgreSQL؛ pgx.Tx و *pgxpool.Pool متدهای Begin/Query لازم adapter را دارند
github.com/jackc/pgx/v5/pgxpoolpgxpool.New(ctx, dsn)یک pool برای هر process؛ ببینید Connection Pooling
github.com/jackc/pgx/v5/pgconn*pgconn.PgError و .Codeبر اساس SQLSTATE شاخه بزنید، هرگز بر اساس متن پیام
github.com/aws/aws-sdk-go-v2/service/dynamodbPutItem، GetItem، Query، NewScanPaginatorبرای تست، interfaceی با امضای متدهای خود SDK بپذیرید
github.com/aws/aws-sdk-go-v2/service/dynamodb/typesAttributeValueMemberS، ConditionalCheckFailedExceptionخطای تایپ‌دار با errors.As
github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalueMarshalMap، UnmarshalMap، UnmarshalListOfMapsstruct tag از نوع dynamodbav
go.mongodb.org/mongo-driver/v2adapter برای MongoDB می‌شدهمان port، همان مجموعهٔ قرارداد
github.com/redis/go-redis/v9adapter سبد خرید در GoTxPipelined برای MULTI/EXEC
hash/fnvwrite sharding در GSIhash پایدار و ارزان برای پسوند shard

Laravel ​

Before ​

Redis به‌عنوان «پایگاه داده سریع» انتخاب شده و تنها store سفارش‌ها شده. جمع مبلغ یک float در hash است، هیچ چیز تراکنشی نیست و یک restart بین snapshotها سفارش‌ها را از بین می‌برد.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

// Before: Redis was chosen as "the fast database" and became the only
// store. The order total is a float in a hash, there is no transaction
// with stock, no constraint, and no history if the instance restarts
// between snapshots.
class CheckoutBeforeController
{
    public function __invoke(Request $request)
    {
        $customerId = (string) $request->user()->id;
        $cart = Redis::hgetall("cart:{$customerId}");

        $total = 0.0;
        foreach ($cart as $sku => $qty) {
            $total += (float) Redis::get("price:{$sku}") * (int) $qty; // float money
        }

        $orderId = (string) Redis::incr('order:seq');
        Redis::hmset("order:{$orderId}", [
            'customer' => $customerId,
            'total' => $total,          // the only copy of what the customer owes
            'status' => 'PLACED',
        ]);
        Redis::del("cart:{$customerId}");

        return response()->json(['order_id' => $orderId, 'total' => $total], 201);
    }
}

After ​

یک connection برای هر bounded context. Ordering روی PostgreSQL، Catalog روی MongoDB از طریق mongodb/laravel-mongodb (بستهٔ رسمی؛ نسخهٔ 5.12.2 در Packagist به illuminate/support با ^12|^13.0 نیاز دارد، پس Laravel 13 را پشتیبانی می‌کند)، و سبدهای خرید روی پایگاه Redis جداگانه:

php
<?php

use Illuminate\Support\Str;

// config/database.php (excerpt): one connection per bounded context and
// workload. Ordering owns PostgreSQL, Catalog owns MongoDB, the cart and
// sessions use a Redis connection that is allowed to lose data.
return [

    'default' => env('DB_CONNECTION', 'orders'),

    'connections' => [

        // System of record for money: constraints, transactions, ad-hoc SQL.
        'orders' => [
            'driver' => 'pgsql',
            'url' => env('ORDERS_DB_URL'),
            'host' => env('ORDERS_DB_HOST', '127.0.0.1'),
            'port' => env('ORDERS_DB_PORT', '5432'),
            'database' => env('ORDERS_DB_DATABASE', 'orders'),
            'username' => env('ORDERS_DB_USERNAME', 'orders_app'),
            'password' => env('ORDERS_DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'search_path' => 'public',
            'sslmode' => env('ORDERS_DB_SSLMODE', 'prefer'),
        ],

        // Catalog documents: variable attributes per product type, read whole.
        // Driver provided by mongodb/laravel-mongodb (MongoDB\Laravel\MongoDBServiceProvider).
        'mongodb' => [
            'driver' => 'mongodb',
            'dsn' => env('CATALOG_MONGODB_URI', 'mongodb://127.0.0.1:27017'),
            'database' => env('CATALOG_MONGODB_DATABASE', 'catalog'),
        ],
    ],

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],

        // Carts: a separate logical database so a FLUSHDB on the cache
        // connection cannot take carts with it.
        'cart' => [
            'url' => env('REDIS_CART_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CART_DB', '2'),
        ],
    ],
];

schema کانتکست Ordering روی connection خودش ($connection = 'orders' روی migration)، با constraintهایی که schema builder بیانشان نمی‌کند به‌صورت SQL:

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    // Runs on the Ordering context's own connection.
    protected $connection = 'orders';

    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->string('id', 26)->primary();          // ULID: time-sortable
            $table->string('customer_id');
            $table->string('status', 16);
            $table->bigInteger('total_cents');
            $table->timestampTz('created_at')->useCurrent();
            $table->index(['customer_id', 'id']);          // AP3
        });

        Schema::create('order_lines', function (Blueprint $table) {
            $table->string('order_id', 26);
            $table->integer('line_no');
            $table->string('sku');
            $table->integer('quantity');
            $table->bigInteger('price_cents');
            $table->primary(['order_id', 'line_no']);
            $table->foreign('order_id')->references('id')->on('orders')->cascadeOnDelete();
        });

        Schema::create('outbox', function (Blueprint $table) {
            $table->id();
            $table->string('aggregate_id');
            $table->string('event_type');
            $table->jsonb('payload');
            $table->timestampTz('created_at')->useCurrent();
        });

        // Constraints the schema builder does not express are plain SQL.
        DB::connection($this->connection)->statement(
            "ALTER TABLE orders ADD CONSTRAINT orders_status_chk CHECK (status IN ('PLACED','PAID','SHIPPED'))"
        );
        DB::connection($this->connection)->statement(
            'ALTER TABLE order_lines ADD CONSTRAINT order_lines_qty_chk CHECK (quantity > 0)'
        );
        DB::connection($this->connection)->statement(
            "CREATE INDEX orders_placed ON orders (id DESC) WHERE status = 'PLACED'"   // AP4
        );
    }

    public function down(): void
    {
        Schema::dropIfExists('outbox');
        Schema::dropIfExists('order_lines');
        Schema::dropIfExists('orders');
    }
};

مدل‌های Eloquent و repository port. DB::connection('orders')->transaction() سفارش، سطرها و ردیف outbox را با هم نگه می‌دارد؛ UniqueConstraintViolationException یک retry را به یک خواندن تبدیل می‌کند:

php
<?php

namespace App\Ordering;

use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Order extends Model
{
    use HasUlids;

    // The Ordering context's own PostgreSQL connection.
    protected $connection = 'orders';

    public $timestamps = false;

    protected $fillable = ['id', 'customer_id', 'status', 'total_cents', 'created_at'];

    protected function casts(): array
    {
        return [
            'total_cents' => 'integer',
            'created_at' => 'immutable_datetime',
        ];
    }

    public function lines(): HasMany
    {
        return $this->hasMany(OrderLine::class, 'order_id')->orderBy('line_no');
    }
}
php
<?php

namespace App\Ordering;

use Illuminate\Database\Eloquent\Model;

class OrderLine extends Model
{
    protected $connection = 'orders';

    protected $table = 'order_lines';

    public $incrementing = false;

    public $timestamps = false;

    protected $primaryKey = null;

    protected $fillable = ['order_id', 'line_no', 'sku', 'quantity', 'price_cents'];
}
php
<?php

namespace App\Ordering;

use Illuminate\Support\Collection;

// The port. Each method is one access pattern (AP1-AP4 in the chapter);
// controllers and jobs depend on this interface, never on a connection.
interface OrderRepository
{
    /** @param list<array{sku: string, quantity: int, price_cents: int}> $lines */
    public function place(string $orderId, string $customerId, array $lines): Order;

    public function find(string $customerId, string $orderId): ?Order;

    /** @return Collection<int, Order> */
    public function latestForCustomer(string $customerId, int $limit = 20): Collection;

    /** @return Collection<int, Order> */
    public function placedFeed(int $limit = 100): Collection;
}
php
<?php

namespace App\Ordering;

use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class EloquentOrderRepository implements OrderRepository
{
    public function place(string $orderId, string $customerId, array $lines): Order
    {
        try {
            return DB::connection('orders')->transaction(function () use ($orderId, $customerId, $lines) {
                $total = array_sum(array_map(fn (array $l) => $l['quantity'] * $l['price_cents'], $lines));

                $order = Order::create([
                    'id' => $orderId,
                    'customer_id' => $customerId,
                    'status' => 'PLACED',
                    'total_cents' => $total,
                    'created_at' => now(),
                ]);

                foreach (array_values($lines) as $i => $line) {
                    $order->lines()->create($line + ['line_no' => $i + 1]);
                }

                // Same transaction as the order: the relay publishes it to
                // search, analytics and cache invalidation (see the outbox chapter).
                DB::connection('orders')->table('outbox')->insert([
                    'aggregate_id' => $orderId,
                    'event_type' => 'OrderPlaced',
                    'payload' => json_encode(['order_id' => $orderId, 'customer_id' => $customerId, 'total_cents' => $total]),
                ]);

                return $order->load('lines');
            });
        } catch (UniqueConstraintViolationException) {
            // A retried request with the same order ID: return the first result.
            return $this->find($customerId, $orderId) ?? throw new \RuntimeException("order {$orderId} belongs to another customer");
        }
    }

    public function find(string $customerId, string $orderId): ?Order
    {
        return Order::with('lines')->where('customer_id', $customerId)->find($orderId);
    }

    public function latestForCustomer(string $customerId, int $limit = 20): Collection
    {
        return Order::with('lines')
            ->where('customer_id', $customerId)
            ->orderByDesc('id')
            ->limit($limit)
            ->get();
    }

    public function placedFeed(int $limit = 100): Collection
    {
        return Order::where('status', 'PLACED')->orderByDesc('id')->limit($limit)->get();
    }
}

Catalog روی MongoDB. MongoDB\Laravel\Eloquent\Model با variantها و ویژگی‌های embed شده، یک فیلتر dot-notation و aggregation builder (Product::aggregate()->match()->group()):

php
<?php

namespace App\Catalog;

use MongoDB\Laravel\Eloquent\Model;

// Catalog context: one document per product, variants and attributes
// embedded because they are read with the product, change with it and
// are bounded (tens, not millions). Reviews are NOT embedded: unbounded,
// written at different times, so they live in their own collection.
class Product extends Model
{
    protected $connection = 'mongodb';

    protected $table = 'products';

    protected $fillable = ['sku', 'name', 'type', 'price_cents', 'attributes', 'variants'];

    protected function casts(): array
    {
        return [
            'price_cents' => 'integer',
            'attributes' => 'array',
            'variants' => 'array',
        ];
    }
}
php
<?php

namespace App\Catalog;

use Illuminate\Support\Collection;
use MongoDB\Builder\Accumulator;
use MongoDB\Builder\Expression;
use MongoDB\Builder\Query;

class CatalogQueries
{
    // A point lookup by SKU and a filter on an embedded attribute (dot notation).
    public function bySku(string $sku): ?Product
    {
        return Product::where('sku', $sku)->first();
    }

    /** @return Collection<int, Product> */
    public function laptopsWithRam(int $minGb): Collection
    {
        return Product::where('type', 'laptop')
            ->where('attributes.ram_gb', '>=', $minGb)
            ->orderBy('price_cents')
            ->limit(50)
            ->get();
    }

    // Aggregation pipeline through the Laravel MongoDB aggregation builder:
    // product count and average price per type.
    public function pricePerType(): Collection
    {
        return Product::aggregate()
            ->match(price_cents: Query::gte(1))
            ->group(
                _id: Expression::fieldPath('type'),
                products: Accumulator::sum(1),
                avg_price_cents: Accumulator::avg(Expression::numberFieldPath('price_cents')),
            )
            ->get();
    }
}

سبد خرید روی Redis با Redis::connection('cart')->transaction() (MULTI/EXEC) و یک hash tag برای Redis Cluster:

php
<?php

namespace App\Cart;

use Illuminate\Support\Facades\Redis;

// Cart context: Redis as the primary store for data the business accepts
// losing (a few seconds with appendfsync everysec). Money never lives here:
// at checkout the prices come from the Catalog and the total is written
// to the Ordering database.
class RedisCartStore
{
    private const TTL_SECONDS = 7 * 24 * 3600;

    public function add(string $customerId, string $sku, int $quantity): void
    {
        $key = $this->key($customerId);

        // MULTI/EXEC: the increment and the TTL refresh apply together.
        Redis::connection('cart')->transaction(function ($redis) use ($key, $sku, $quantity) {
            $redis->hincrby($key, $sku, $quantity);
            $redis->expire($key, self::TTL_SECONDS);
        });
    }

    /** @return array<string, int> sku => quantity */
    public function items(string $customerId): array
    {
        $raw = Redis::connection('cart')->hgetall($this->key($customerId));

        return array_filter(array_map('intval', $raw), fn (int $q) => $q > 0);
    }

    public function clear(string $customerId): void
    {
        Redis::connection('cart')->del($this->key($customerId));
    }

    private function key(string $customerId): string
    {
        // Hash tag keeps one customer's keys on one Redis Cluster slot.
        return "cart:{{$customerId}}";
    }
}

سیم‌کشی و جریان checkout روی سه store:

php
<?php

namespace App\Providers;

use App\Ordering\EloquentOrderRepository;
use App\Ordering\OrderRepository;
use Illuminate\Support\ServiceProvider;

// Register in bootstrap/providers.php next to
// MongoDB\Laravel\MongoDBServiceProvider::class.
class PersistenceServiceProvider extends ServiceProvider
{
    public array $singletons = [
        OrderRepository::class => EloquentOrderRepository::class,
    ];
}
php
<?php

namespace App\Http\Controllers;

use App\Cart\RedisCartStore;
use App\Catalog\CatalogQueries;
use App\Ordering\OrderRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

// After: three stores, three owners, one flow. Redis holds the cart,
// MongoDB prices it, PostgreSQL records the order (and its outbox event)
// in one transaction. The client sends an order ID so a retry is safe.
class CheckoutController
{
    public function __construct(
        private RedisCartStore $cart,
        private CatalogQueries $catalog,
        private OrderRepository $orders,
    ) {}

    public function __invoke(Request $request): JsonResponse
    {
        $customerId = (string) $request->user()->id;
        $orderId = (string) $request->input('order_id', (string) Str::ulid());

        $lines = [];
        foreach ($this->cart->items($customerId) as $sku => $quantity) {
            $product = $this->catalog->bySku($sku) ?? abort(422, "unknown sku {$sku}");
            $lines[] = ['sku' => $sku, 'quantity' => $quantity, 'price_cents' => $product->price_cents];
        }
        abort_if($lines === [], 422, 'empty cart');

        $order = $this->orders->place($orderId, $customerId, $lines);
        $this->cart->clear($customerId);   // losing this step only leaves a stale cart

        return response()->json([
            'order_id' => $order->id,
            'total_cents' => $order->total_cents,
        ], 201);
    }
}

نگاه Laravel ​

قابلیت Laravel 13کاربردنکته
connectionها در config/database.phpیک connection نام‌دار برای هر کانتکست (orders، mongodb)مدل‌ها protected $connection را تنظیم می‌کنند
DB::connection('orders')->transaction()سفارش + سطرها + outbox به‌صورت اتمیتراکنش هرگز چند connection را نمی‌پوشاند
Schema در migration با $connectionmigration برای هر کانتکستدر CI برای هر پایگاه داده اجرا شود
HasUlidsکلیدهای رشته‌ای مرتب بر اساس زمانبا شناسه‌های ULID-مانند Go و ایندکس id DESC جور است
Illuminate\Database\UniqueConstraintViolationExceptionساختن idempotentبگیریدش و ردیف موجود را بخوانید
Redis::connection('cart')یک پایگاه منطقی اختصاصی برای سبدهاجدا از connection مربوط به cache
Redis::transaction(fn ($redis) => ...)بلوک MULTI/EXECتراکنش قابل rollback نیست
mongodb/laravel-mongodbdriver => 'mongodb'، MongoDB\Laravel\Eloquent\Model، embedsMany، aggregation builderMongoDB\Laravel\MongoDBServiceProvider را ثبت کنید؛ تراکنش replica set می‌خواهد
$singletons روی service providerbind کردن port به adapter مربوط به Eloquentهنگام مهاجرت adapter را عوض کنید
driverهای cache و sessionredis، database، dynamodbDynamoDB برای cache و session پشتیبانی می‌شود، نه به‌عنوان connection برای Eloquent

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

«NoSQL را برای مقیاس انتخاب کردیم» و حالا گزارش لازم داریم ​

text
     Month   Event
1    0       Team picks DynamoDB "because it scales"; designs keys for 4 access patterns
2    4       Product asks for "orders by region and promo code, last quarter"
3    4       Only answer on the request path: Scan + FilterExpression -> reads the whole table, slow, billed per item
4    5       Fix: DynamoDB Streams / export to S3 -> analytics store; or move Ordering to PostgreSQL
راه‌حلچطورمزیتهزینه
stream به store تحلیلیDynamoDB Streams یا export به S3، بعد ClickHouse / Athenaطراحی عملیاتی دست نمی‌خوردstore دوم، lag
یک GSI تازه برای هر الگوی تازهافزودن GSI و backfill attributeهادر DynamoDB می‌ماندهزینهٔ نوشتن برای هر GSI؛ ۲۰ تا در هر جدول
انتقال کانتکست به PostgreSQLفازهای مهاجرت بالاSQL ad-hoc برای همیشهیک پروژهٔ مهاجرت
دفعهٔ بعد پیشگیری کنیدالگوهای دسترسی را بنویسید؛ اگر ناپایدارند با رابطه‌ای شروع کنیدارزان‌تریناز ابتدا انضباط می‌خواهد
sql
-- What the report is in the relational design: one query, on a replica.
SELECT c.region, o.promo_code, count(*) AS orders, sum(o.total_cents) / 100.0 AS revenue
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= date_trunc('quarter', now()) - interval '3 months'
  AND o.created_at <  date_trunc('quarter', now())
GROUP BY c.region, o.promo_code
ORDER BY revenue DESC;

Redis به‌عنوان تنها store برای پول ​

راه‌حلچطورمزیتهزینه
منبع حقیقت در PostgreSQLسفارش و موجودی حساب در SQL با constraint؛ Redis فقط cacheپایدار، قابل حسابرسیاگر فقط Redis داشتید، یک store دیگر
Redis به‌عنوان write bufferدر Redis بپذیرید و دسته‌ای به SQL flush کنیدجهش‌ها را جذب می‌کندپنجرهٔ از دست رفتن = فاصلهٔ flush به‌علاوهٔ fsync
سرویس پایدار سازگار با RedisAmazon MemoryDB یک transaction log چند-AZ نگه می‌داردAPI در Redis با پایداریتأخیر نوشتن و هزینهٔ بیشتر
الگوی دفتر کلورودی‌های فقط-افزودنی، موجودی مشتق‌شدهقابل بازسازیردیف بیشتر

کد After در Laravel همین راه‌حل است: سبد خرید در Redis می‌ماند (از دست رفتنش یعنی دوباره افزودن)، قیمت از Catalog می‌آید، و جمع مبلغ در PostgreSQL در همان تراکنش رویداد outbox حساب و ذخیره می‌شود.

JSONB به بهانهٔ بی‌schema بودن ​

sql
-- Smell: everything in one document, nothing enforced, every query a JSON path.
CREATE TABLE orders_blob (id bigserial PRIMARY KEY, doc jsonb);
SELECT doc FROM orders_blob WHERE doc ->> 'customer' = '42';  -- no index, no type, no FK

-- Fix: typed columns for what you filter, join, sum or constrain; JSONB for the long tail.
ALTER TABLE products
  ADD CONSTRAINT products_attributes_shape
  CHECK (jsonb_path_exists(attributes, '$.brand') OR attributes = '{}'::jsonb);

-- Containment query served by the jsonb_path_ops GIN index:
SELECT sku, name FROM products WHERE attributes @> '{"color": "red", "size": 42}';

-- A field queried on every listing page becomes a generated, indexed column:
SELECT sku, name FROM products WHERE brand = 'Acme' ORDER BY price_cents LIMIT 20;
راه‌حلچه وقت
ستون تایپ‌دار + FK + CHECKهر چیزی که در join، جمع، قاعدهٔ یکتایی یا گزارش هست
JSONB با CHECK (jsonb_typeof(...) = 'object')ویژگی‌های متغیر، payloadهای طرف سوم
ستون generated + ایندکس B-treeیک فیلد JSON که زیاد کوئری می‌شود
GIN با jsonb_path_opsفیلترهای containment (@>) روی کلیدهای زیاد

partition داغ در DynamoDB ​

راه‌حلچطورمزیتهزینه
Write shardingپسوند #0..N-1 روی کلید کم‌تنوعنوشتن روی N partition پخش می‌شودخواندن N شاخه می‌شود
کلید با تنوع بیشترکلید بر اساس شناسهٔ سفارش، نه وضعیتبدون fan-outبرای مسیر دیگر GSI لازم است
cache جلوی خواندن‌های داغDAX یا Redis برای یک آیتم پرطرفدارجهش خواندن را جذب می‌کندکهنگی
دسته یا buffer کردنافزایش‌ها را پیش از نوشتن جمع کنیدنوشتن کمترتأخیر (Write Buffering)

statusPK و ListByStatus در adapter همان راه‌حل write sharding‌اند؛ TestStatusKeySpreadsOverShards بررسی می‌کند که هشت سفارش روی یک کلید نیفتند.

راه‌حلچطورمزیتهزینه
FTS در PostgreSQL + GINستون tsvector، websearch_to_tsqueryبدون store تازهرتبه‌بندی ساده
OpenSearch از طریق outbox/CDCردیف outbox در تراکنش سفارش، Debezium به Kafka، indexer idempotentارتباط، facetstore دوم، lag، job بازسازی
جست‌وجوی مدیریت‌شده روی store سندیMongoDB Atlas Searchیک فروشندهlock-in

storeهای بیش از حد ​

راه‌حلچطورمزیتهزینه
سیاههٔ storeها با مالکیک ردیف برای هر store: مالک، هدف، الگوهای دسترسی، on-callدیده شدنیک ساعت کار
ادغام در PostgreSQLJSONB، pgvector، TimescaleDB و FTS جای storeهای کوچک را می‌گیرندقطعه‌های متحرک کمترفضای رشد کمتر برای هر قابلیت
بازنشستگی با مهاجرتفازهای بالا، برعکسامنزمان

انتخاب ​

جدول تصمیم بر اساس workload ​

Workloadstore پیشنهادیتکنیک اضافهدلیل
سفارش، پرداخت، دفتر کل، موجودیPostgreSQL (یا MySQL)constraint، outbox، کلید idempotencyinvariantهای چندموجودیتی و حسابرسی
همان، با نوشتن چند region یا فراتر از یک primarySpanner، CockroachDB، YugabyteDBpartitioning آگاه از regioninvariantهای SQL به‌علاوهٔ نوشتن افقی
کاتالوگ محصول با ویژگی‌های متغیرJSONB در PostgreSQL، یا MongoDB اگر aggregateها یک‌جا خوانده می‌شوند و یک تیم مالکشان استستون generated یا $jsonSchemaنوسان schema
سبد خرید، session، شمارندهٔ rate limitRedis (حالت store) یا DynamoDBTTL، noeviction برای storeکوچک، داغ، تحمل‌پذیر در برابر از دست رفتن یا کلیدمحور
پروفایل کاربر در مقیاس خیلی بزرگ با الگوهای معلومDynamoDB یا Cassandrasingle-table design، GSIتأخیر قابل‌پیش‌بینی در هر اندازه
پیام‌های چت، فید فعالیتCassandra / ScyllaDB یا DynamoDBpartition برای هر کانال و سطل زمانیrange scan روی یک کلید، نرخ نوشتن بالا (Feeds)
جست‌وجوی محصول یا محتواElasticsearch / OpenSearchتغذیه با CDC، reindex با aliasارتباط و facet
metric، telemetry در IoTTimescaleDB، InfluxDB، ClickHouseretention، downsamplingپرافزودن، تجمیع روی پنجرهٔ زمانی
تحلیل و BIClickHouse، یک انبار دادهCDC از OLTPپیمایش ستونی
حلقهٔ تقلب، پیشنهاد بر اساس مسیرNeo4j (مشتق‌شده)تغذیه از OLTPپیمایش با عمق متغیر
جست‌وجوی معنایی، RAGاول pgvectorایندکس HNSW، فیلتر در SQLبردار کنار فیلترهای رابطه‌ای
بار نامعلوم، preview، branch توسعهNeon، Aurora Serverless، DynamoDB on-demandبودجه و هشدارپرداخت به‌اندازهٔ مصرف
cache جلوی هر چیزیRediscache-aside، TTL، allkeys-lru (Caching)تأخیر و کم کردن بار

SQL در برابر NoSQL در یک جدول ​

رابطه‌ای را انتخاب کنید وقتییک خانوادهٔ NoSQL را انتخاب کنید وقتی
الگوهای دسترسی زیاد، در حال تغییر یا نامعلوم‌اندالگوهای دسترسی کم، پایدار و معلوم‌اند
invariantها چند موجودیت را درگیر می‌کنند (پول، موجودی، رزرو)هر عملیات یک aggregate یا یک کلید را لمس می‌کند
کوئری ad-hoc و گزارش روی دادهٔ زنده لازم داریدگزارش‌ها به هر حال به store تحلیلی می‌روند
یک primary نوشتن‌های ۲ تا ۳ سال آینده را می‌کشدنرخ نوشتن یا حجم داده فراتر از یک primary بزرگ است، یا regionهای زیاد لازم است
تیم SQL و ORM را می‌شناسدتیم روش مدل‌سازی NoSQL را می‌شناسد (single-table، قواعد embedding)
lock-in کم می‌خواهیدAPI فروشنده را در ازای عملیاتی که خودتان اجرا نمی‌کنید می‌پذیرید

مثال کارشده ۱: تجارت الکترونیک (کاتالوگ، سفارش، سبد، جست‌وجو) ​

text
     Context    Patterns (peak)                                   Store                 Why
1    Ordering   place 200 w/s; get 1,500 r/s; list 400 r/s        PostgreSQL            money, FKs, ad-hoc, 139 GB/year
2    Catalog    get product 5,000 r/s; edit 5 w/s; attrs vary     MongoDB or PG JSONB   aggregate read whole; volatile attributes
3    Cart       add item 300 w/s; read cart 1,000 r/s; TTL 7 d     Redis (AOF everysec)  hot, small, loss of 1 s acceptable
4    Search     queries 800 r/s; facets; typeahead               OpenSearch            relevance; fed by CDC from Catalog
5    Analytics  hourly revenue, funnels                           ClickHouse            columnar; fed by CDC from Ordering

یک مالک برای هر store، هیچ کانتکستی جدول‌های دیگری را نمی‌خواند، و CDC/outbox برای هر چیز مشتق‌شده. با تیمی دونفره، Catalog به JSONB در PostgreSQL و Search به FTS در PostgreSQL می‌رود تا وقتی عددها چیز دیگری بگویند: دو store (PostgreSQL و Redis) به جای پنج.

مثال کارشده ۲: telemetry در IoT ​

text
     Fact                                   Estimate (back-of-envelope)
1    50,000 devices x 1 reading / 2 s        25,000 writes/s, all day
2    100 bytes per reading                   ~2.2 GB/day raw, ~0.8 TB/year before compression
3    Queries                                 last hour per device (range on one key); hourly averages per site (aggregate)
4    Device registry                         50,000 rows, relational, joins with customers and sites

telemetry به TimescaleDB می‌رود (hypertable، فشرده‌سازی، continuous aggregate، join با رجیستری در همان PostgreSQL) یا اگر پیمایش تحلیلی غالب است به ClickHouse؛ و اگر تیم یک store اختصاصی metric می‌خواهد به InfluxDB. رجیستری دستگاه‌ها و صورت‌حساب رابطه‌ای می‌مانند. Redis آخرین خوانش هر دستگاه را برای داشبوردها نگه می‌دارد.

مثال کارشده ۳: گراف اجتماعی ​

text
     Pattern                                         Shape                    Store
1    Follow / unfollow, 2,000 w/s                     write to two adjacency lists   Cassandra or DynamoDB (followers, following)
2    "Do I follow X?" 50,000 r/s                       point lookup             same table, or Redis set
3    Home timeline                                     range on one key         precomputed feed per user ([Feeds](/system-design/feeds-fanout-fanin))
4    "People you may know" (2 to 3 hops)               graph traversal          Neo4j or an offline job, derived
5    Profiles, settings, billing                       relational                PostgreSQL

فهرست‌های مجاورت برای سؤال‌های یک‌گامی به store کلید-مقدار یا wide-column تعلق دارند؛ پیشنهادهای چندگامی روی یک گراف مشتق‌شده یا به‌صورت job دسته‌ای اجرا می‌شوند؛ سیستم حساب کاربری رابطه‌ای می‌ماند.

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

Monolith: یک process، یک پایگاه داده ​

یک برنامهٔ Laravel یا Go و یک PostgreSQL. تصمیم پایگاه داده اینجا بیشتر این است: «PostgreSQL، و کدام قابلیت‌هایش»: JSONB برای ویژگی‌های کاتالوگ، FTS برای جست‌وجو، جدول jobs یا Redis برای صف، Redis برای cache و session. با این حال جدول الگوهای دسترسی را بنویسید و در مخزن نگه دارید؛ ورودی همهٔ تصمیم‌های بعدی است. حتی در monolith دسترسی به داده را پشت repository بگذارید تا انتقال بعدی فقط عوض کردن adapter باشد.

Modular monolith: مرز بدون شبکه ​

هر ماژول مالک جدول‌های خودش است (schemaهای ordering، catalog و cart در یک PostgreSQL) و ماژول‌ها هرگز بین هم join نمی‌زنند؛ interface همدیگر را صدا می‌زنند یا رویدادهای منتشرشدهٔ همدیگر را می‌خوانند. اینجاست که polyglot persistence ممکن می‌شود بی‌آنکه لازم باشد: ماژول Catalog بعداً می‌تواند به MongoDB برود چون کس دیگری به جدول‌هایش دست نمی‌زند. Laravel این را با یک نام connection برای هر ماژول ملموس می‌کند، حتی وقتی همه به یک سرور اشاره می‌کنند (Modular Monolith).

Microservices: یک مالک برای هر store ​

هر سرویس مالک پایگاه دادهٔ خودش است و بقیه دادهٔ آن را از API یا رویداد می‌گیرند (Database per Service). جریان checkout این می‌شود: سرویس Cart (Redis) ← سرویس Catalog (MongoDB) برای قیمت ← سرویس Ordering (PostgreSQL) سفارش و ردیف outbox را در یک تراکنش می‌نویسد ← relay رویداد OrderPlaced را به Kafka منتشر می‌کند ← مصرف‌کننده‌های Search و Analytics storeهای خودشان را idempotent به‌روز می‌کنند (Idempotent Consumers). چیزی که از مرز رد نمی‌شود: join، foreign key و تراکنش بین سرویس‌ها. invariantهایی که چند سرویس را درگیر می‌کنند saga می‌شوند (Saga).

دادهٔ توزیع‌شده: replica، cache، region ​

replicaهای خواندنی عقب‌اند، پس الگوهای read-your-writes (AP2 درست بعد از AP1) به primary می‌روند یا از توکن session استفاده می‌کنند (Replication Topologies). GSIهای DynamoDB، ایندکس‌های جست‌وجو و cacheها همه نسخه‌های eventual‌اند؛ UI روی این مسیرها باید چند ثانیه کهنگی را تحمل کند. نوشتن چند region شما را مجبور به انتخاب می‌کند: یک region نویسنده با replica در جاهای دیگر، طراحی multi-leader یا leaderless با حل تعارض (DynamoDB global tables، Cassandra)، یا distributed SQL با اجماع بین regionها و تأخیرش برای هر نوشتن (CAP & PACELC).

مسیر مقیاس: ۱ برابر، ۱۰ برابر، ۱۰۰ برابر ​

بارطراحی معمول
1xprimary و replica از PostgreSQL؛ Redis برای cache و session؛ بقیه به‌صورت قابلیت‌های PostgreSQL
10xprimary بزرگ‌تر، replicaهای بیشتر، connection pooling، partitioning بزرگ‌ترین جدول‌ها؛ جست‌وجو و تحلیل با CDC بیرون می‌روند
100xکانتکست پرنوشتن را shard کنید (Citus، Vitess) یا به distributed SQL یا store کلید-مقدار با single-table design ببرید؛ بازبینی کلیدهای داغ؛ store برای هر کانتکست

آزمایشگاه: کوئری‌ها را مدل کنید، اندازه بگیرید، port را ثابت کنید ​

۱. اندازه‌گیری الگوهای دسترسی (روی همین ماشین اجرا شد؛ یک برنامهٔ کوچک تک‌process در Go):

bash
cd docs/snippets/system-design/sql-vs-nosql-decision/go
go run ./sizing
# access pattern                                 units/op    units/s
# AP1 place order (2 KB item + 2 KB GSI copy)         4.0        800
# AP2 get order, strong                               1.0       1500
# AP3 latest 20 orders, eventual                      5.0       2000
# AP4 PLACED feed on GSI, eventual                   12.5        250
# total: 3750 RCU/s, 800 WCU/s
# partitions needed for throughput alone: 2
# max strong 2 KB reads/s on ONE key: 3000
# max 2 KB writes/s on ONE key: 500
# orders storage per year: 139 GB

۲. اجرای مجموعهٔ قرارداد روی DynamoDB جعلی و adapter درون‌حافظه (روی همین ماشین اجرا شد):

bash
go test ./... 
# ok   academy/sql-vs-nosql-decision/migrate
# ok   academy/sql-vs-nosql-decision/orders
# TestPostgresContract is skipped unless ORDERS_PG_DSN is set

۳. اجرای همان مجموعه روی PostgreSQL (خروجی موردانتظار؛ اجرا نشده):

bash
createdb orders_test
psql orders_test -f ../sql/schema.sql
ORDERS_PG_DSN=postgres://app:app@localhost:5432/orders_test go test ./orders -run Postgres -v
# --- PASS: TestPostgresContract (0.05s)
#     --- PASS: TestPostgresContract/AP1_place_is_idempotent_on_order_id
#     --- PASS: TestPostgresContract/AP2_get_returns_lines;_missing_is_ErrNotFound
#     --- PASS: TestPostgresContract/AP3_and_AP4_newest_first_with_limit
#     --- PASS: TestPostgresContract/invalid_order_never_reaches_the_store

۴. ببینید کدام ایندکس به کدام الگو خدمت می‌کند (خروجی موردانتظار؛ اجرا نشده):

sql
EXPLAIN SELECT id FROM orders WHERE customer_id = 'c-42' ORDER BY id DESC LIMIT 20;
-- Limit -> Index Only Scan using orders_customer_recent on orders
EXPLAIN SELECT id FROM orders WHERE status = 'PLACED' ORDER BY id DESC LIMIT 100;
-- Limit -> Index Scan using orders_placed on orders
INSERT INTO products (sku, name, price_cents, attributes) VALUES ('p1', 'Lamp', 1999, '[1,2]');
-- ERROR:  new row for relation "products" violates check constraint "products_attributes_check"

۵. ببینید Redis یک ثانیه نوشتن را از دست می‌دهد یا نه (خروجی موردانتظار؛ اجرا نشده، روی یک Redis آزمایشی):

bash
redis-cli CONFIG SET appendonly yes
redis-cli CONFIG SET appendfsync everysec
redis-cli CONFIG GET maxmemory-policy
# 1) "maxmemory-policy"
# 2) "noeviction"
redis-cli HINCRBY "cart:{42}" sku-9 1
redis-cli INFO persistence | grep -E "aof_enabled|aof_last_write_status"
# aof_enabled:1
# aof_last_write_status:ok

۶. هزینهٔ یک کوئری مدل‌نشده را روی DynamoDB حس کنید (خروجی موردانتظار؛ اجرا نشده، روی DynamoDB Local یا یک حساب sandbox):

bash
aws dynamodb scan --table-name orders --filter-expression "customer_id = :c" \
  --expression-attribute-values '{":c":{"S":"c-42"}}' --return-consumed-capacity TOTAL
# "Count": 3, "ScannedCount": 120000, "ConsumedCapacity": {"CapacityUnits": 1450.5}
aws dynamodb query --table-name ordering --key-condition-expression "PK = :pk AND begins_with(SK, :p)" \
  --expression-attribute-values '{":pk":{"S":"CUST#c-42"},":p":{"S":"ORDER#"}}' --no-scan-index-forward \
  --return-consumed-capacity TOTAL
# "Count": 3, "ScannedCount": 3, "ConsumedCapacity": {"CapacityUnits": 0.5}

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

باورواقعیت
NoSQL مقیاس می‌گیرد، SQL نهیک primary از PostgreSQL بیشتر workloadها را می‌کشد؛ distributed SQL خود SQL را افقی می‌کند؛ NoSQL کارایی قابل‌پیش‌بینی برای کوئری‌های طراحی‌شده می‌دهد
بدون schema یعنی schema نداریمschema به داخل هر خواننده می‌رود؛ مستندات MongoDB و PostgreSQL هر دو ساختار قابل‌پیش‌بینی را توصیه می‌کنند
MongoDB یعنی همه‌چیز را embed کنفرزندانِ بی‌حد، مستقل‌نوشته‌شده یا پرتعداد را reference کنید
DynamoDB برای هر موجودیت یک جدول می‌خواهدراهنما تا حد ممکن جدول کمتر را توصیه می‌کند؛ single-table design موجودیت‌ها را کنار هم می‌گذارد
GSI خواندن قوی می‌دهدGSIهای DynamoDB فقط خواندن eventual را پشتیبانی می‌کنند
persistence در Redis آن را به امنی PostgreSQL می‌کندeverysec ممکن است حدود یک ثانیه از دست بدهد؛ RDB به‌تنهایی ممکن است چند دقیقه
JSONB یعنی ستون لازم نداریمفیلتر، join، جمع و constraint را روی ستون تایپ‌دار؛ JSONB برای دنبالهٔ بلند
distributed SQL مقیاس مجانی استهر نوشتن یک دور اجماع است؛ regionها تأخیر اضافه می‌کنند
polyglot persistence یعنی پایگاه‌های داده زیادیعنی store درست برای هر workload، هرکدام با یک مالک، و تا حد ممکن کم
dual write در درخواست برای مهاجرت کافی استخرابی جزئی storeها را واگرا می‌کند؛ صف، reconciliation یا CDC لازم است
serverless همیشه ارزان‌تر استبار ثابت بالا اغلب روی provisioned ارزان‌تر است؛ شروع از صفر cold start دارد
موتور جست‌وجو می‌تواند منبع حقیقت باشدایندکسی مشتق‌شده و near-real-time است که باید بتوانید بازسازی‌اش کنید
دادهٔ گرافی پایگاه گراف لازم داردیکی دو گام همان join است؛ store گرافی برای پیمایش عمیق با عمق متغیر می‌ارزد

چکیده ​

موضوعبه خاطر بسپارید
گام اولجدول الگوهای دسترسی: نام، شکل، QPS، سازگاری، SLO
پیش‌فرضPostgreSQL مگر نیازی آن را رد کند
قوت رابطه‌ایjoin، constraint، foreign key، تراکنش، کوئری ad-hoc، ابزار
قاعدهٔ سندیدادهٔ محدود و هم‌خوان را embed، دادهٔ بی‌حد را reference کنید؛ سقف 16 MiB
قاعدهٔ DynamoDBاول سؤال‌ها را بدانید؛ جدول کم؛ PK + SK + GSI؛ Scan هرگز روی مسیر درخواست
عددهای DynamoDBواحد خواندن 4 KB، واحد نوشتن 1 KB، ۳۰۰۰ RCU / ۱۰۰۰ WCU برای هر partition، آیتم 400 KB، تراکنش ۱۰۰ آیتمی
Redis به‌عنوان storeAOF با everysec (حدود ۱ ثانیه از دست رفتن)، snapshot با RDB، noeviction، replica؛ هرگز تنها نسخهٔ پول
Redis در برابر DynamoDBRedis برای داغ، کوچک، زیر میلی‌ثانیه؛ DynamoDB برای رکوردهای پایدار کلیدمحور در هر اندازه
جست‌وجوElasticsearch/OpenSearch به‌عنوان ایندکس مشتق‌شده با تغذیهٔ CDC
Time seriesTimescaleDB، InfluxDB، ClickHouse؛ retention و downsampling
برداراول pgvector
Distributed SQLSpanner، CockroachDB، YugabyteDB؛ Vitess، MySQL را shard می‌کند
ServerlessNeon، Aurora Serverless v2، DynamoDB on-demand، PlanetScale
Polyglotیک مالک برای هر store؛ همگام‌سازی با outbox/CDC؛ هزینهٔ عملیاتی را بشمارید
مهاجرتdual write → backfill → shadow read → flip → بازنشستگی، هر گام برگشت‌پذیر

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

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

۱ — چرا راهنمای DynamoDB می‌گوید تا سؤال‌ها را ندانید schema را طراحی نکنید؟ حیاتی ​

پاسخ

پاسخ: چون کوئری‌های DynamoDB فقط برای شرط‌های کلیدی که طراحی کرده‌اید کارآمدند (partition key، sort key، GSI). هر چیز دیگری Scan است. کلیدها همان plan کوئری‌اند، پس باید از الگوهای دسترسی پیروی کنند.

۲ — شکل کوئری هرکدام را بگویید: «سفارش 01J9A»، «۲۰ سفارش آخر مشتری ۴۲»، «درآمد هر منطقه در فصل گذشته»، «کفش قرمز سایز ۴۲»، «دوستانِ دوستان». حیاتی ​

پاسخ

پاسخ: point lookup؛ range scan روی یک کلید؛ aggregation (ad-hoc، با join)؛ full-text search؛ graph traversal.

۳ — تیمی می‌گوید «ویژگی‌ها در هر محصول فرق دارد، پس MongoDB لازم داریم». چه می‌پرسید؟ حیاتی ​

پاسخ

پاسخ: آیا محصول یک‌جا توسط یک مالک خوانده و نوشته می‌شود؟ invariant بین محصولات یا گزارش با join هست؟ تجربهٔ تیم با PostgreSQL چقدر است؟ ویژگی‌های متغیر به‌تنهایی با JSONB در PostgreSQL و ستون generated جواب می‌گیرند؛ MongoDB وقتی جور است که شکل aggregate و مالکیت هم به آن سمت اشاره کنند.

۴ — چه وقت فرزند در MongoDB باید reference شود نه embed؟ حیاتی ​

پاسخ

پاسخ: وقتی سمت فرزند پرتعداد است، بی‌حد رشد می‌کند، در workload پرنوشتن در زمان‌های متفاوت نوشته می‌شود، بدون والد هم معنا دارد، یا سند را بیش از حد بزرگ (سقف 16 MiB) یا انتقالش را پرهزینه می‌کند.

۵ — چرا GSIِ کلیدخورده روی وضعیت سفارش partition داغ می‌سازد و adapter چطور درستش می‌کند؟ مهم ​

پاسخ

پاسخ: attributeی با سه مقدار همهٔ سفارش‌های PLACED را روی یک partition key از GSI می‌گذارد که سقفش ۱۰۰۰ واحد نوشتن در ثانیه است. adapter یک پسوند shard مبتنی بر hash اضافه می‌کند (STATUS#PLACED#0..3) و همهٔ shardها را کوئری و نتیجه‌ها را ادغام می‌کند.

۶ — store اصلی Redis با appendfsync everysec چه چیزی را ممکن است از دست بدهد و کدام تنظیم‌ها آن را store می‌کنند نه cache؟ مهم ​

پاسخ

پاسخ: حدود یک ثانیه نوشتن هنگام crash. تنظیم‌های store: AOF روشن، snapshotهای RDB برای backup، maxmemory-policy برابر noeviction، replica و هشدار حافظه.

۷ — Redis یا DynamoDB برای (الف) session با TTL سی‌دقیقه‌ای، (ب) پروفایل ۲۰۰ میلیون کاربر، (ج) leaderboardی که ۱۰ هزار بار در ثانیه به‌روز می‌شود؟ حیاتی ​

پاسخ

پاسخ: (الف) Redis (یا DynamoDB با TTL اگر سرور نمی‌خواهید)؛ (ب) DynamoDB (پایدار، کلیدمحور، حجم)؛ (ج) sorted set در Redis با snapshot دوره‌ای به یک store پایدار.

۸ — distributed SQL چه چیزی می‌دهد که PostgreSQL نمی‌دهد و هزینه‌اش چیست؟ مهم ​

پاسخ

پاسخ: نوشتن و فضای ذخیره روی چند گره مقیاس می‌گیرد و از دست رفتن گره یا zone را تحمل می‌کند، با حفظ SQL و تراکنش serializable. هزینه: تأخیر اجماع برای هر نوشتن (بین regionها بیشتر)، هزینهٔ عملیاتی و مالی، و قابلیت‌ها و افزونه‌های کمتر PostgreSQL.

۹ — چرا dual write در برنامه پرریسک است و بستهٔ migrate چطور ریسک را مهار می‌کند؟ حیاتی ​

پاسخ

پاسخ: بدون تراکنشی که هر دو store را بپوشاند، یک نوشتن ممکن است موفق و دیگری ناموفق شود و storeها واگرا شوند. بسته اول به primary می‌نویسد و نتیجهٔ آن را برمی‌گرداند، نوشتن‌های ناموفق store دوم را برای backfill idempotent صف می‌کند و با shadow read تفاوت‌های باقی‌مانده را پیش از flip پیدا می‌کند.

۱۰ — برای یک سیستم تجارت الکترونیک که دو توسعه‌دهنده اداره‌اش می‌کنند چه storeهایی انتخاب می‌کنید و چرا؟ حیاتی ​

پاسخ

پاسخ: PostgreSQL برای سفارش، کاتالوگ (JSONB) و جست‌وجو (FTS)، و Redis برای سبد خرید، session و cache. دو store که تیم می‌تواند اداره کند؛ Catalog یا Search را فقط وقتی بیرون ببرید که الگوهای اندازه‌گیری‌شده لازمش کنند.

واژه‌نامه ​

اصطلاحمعنا
الگوی دسترسی (Access pattern)عملیات نام‌دار و تکرارشونده روی داده با ورودی، نتیجه، نرخ و نیاز سازگاری
شکل کوئری (Query shape)نوع کار: point lookup، range scan، join، full-text search، aggregation، graph traversal، شباهت
جست‌وجوی نقطه‌ای (Point lookup)آوردن یک رکورد با کلیدش
پیمایش بازه (Range scan)خواندن برشی مرتب از یک کلید یا ایندکس
جست‌وجوی متنی (Full-text search)پیدا کردن و رتبه‌بندی سندها با کلمه، از طریق inverted index
تجمیع (Aggregation)جمع، شمارش، میانگین یا صدک روی رکوردهای زیاد
پیمایش گراف (Graph traversal)دنبال کردن رابطه‌ها در یک یا چند گام
نسبت خواندن به نوشتن (Read/write ratio)نسبت خواندن‌ها به نوشتن‌ها در یک workload
نیاز سازگاری (Consistency requirement)اینکه یک خواندن در یک الگو چقدر می‌تواند کهنه باشد
نیاز تراکنش (Transaction requirement)کدام invariantها باید بین رکوردها اتمی عوض شوند
نوسان schema (Schema volatility)مجموعهٔ فیلدها هر چند وقت عوض می‌شود و چه کسی کنترلش می‌کند
سقف مقیاس (Scale ceiling)باری که طراحی فعلی در آن تغییر ساختاری لازم دارد
SLO تأخیر (Latency SLO)صدک تأخیر هدف برای هر الگوی دسترسی
بلوغ عملیاتی (Operational maturity)توانایی اثبات‌شده در اجرا، backup، بازگردانی و تنظیم یک store
سرویس مدیریت‌شده (Managed service)پایگاه داده‌ای که فروشنده اداره‌اش می‌کند (RDS، Atlas، DynamoDB، Neon)
Lock-inهزینهٔ رفتن از یک محصول یا فروشنده
رابطه‌ای (Relational)جدول‌هایی با نوع و constraint اعلام‌شده که با SQL کوئری می‌شوند
Joinترکیب ردیف‌های جدول‌ها با تطبیق کلیدها
قید (Constraint)قاعده‌ای که پایگاه داده اجرا می‌کند: NOT NULL، UNIQUE، CHECK، FOREIGN KEY
کلید خارجی (Foreign key)ستونی که مقدارش باید به‌عنوان کلید در جدول دیگری وجود داشته باشد
کوئری ad-hoc (Ad-hoc query)سؤالی که کسی ذخیره‌سازی را برایش طراحی نکرده
PostgreSQL به‌عنوان پیش‌فرض (PostgreSQL by default)شروع با PostgreSQL مگر نیازی آن را رد کند
JSONBنوع JSON دودویی و ایندکس‌پذیر در PostgreSQL
پایگاه داده سندی (Document database)store سندهای خودتوصیف (MongoDB)
Embeddingنگه داشتن دادهٔ مرتبط داخل سند والد
Referencingنگه داشتن یک شناسه و حل کردنش جداگانه
Aggregation pipelineزبان کوئری مرحله‌ای MongoDB ($match، $group، $lookup)
کلید-مقدار (Key-value)storeی که با کلید آدرس‌دهی می‌شود و مقدارش مبهم یا نیمه‌ساختاریافته است
Wide-columnردیف‌های partitionشده با clustering column (Cassandra، Bigtable)
Partition keyکلیدی که hash می‌شود تا partition انتخاب شود
Sort keyکلیدی که آیتم‌های داخل یک partition را مرتب می‌کند (در Cassandra، clustering key)
GSIglobal secondary index در DynamoDB: همان آیتم‌ها با attributeهای دیگر، eventual
Single-table designچند نوع موجودیت در یک جدول DynamoDB با کلیدهای عمومی و پیشوند
بدون join (No joins)storeهای کلید-مقدار رکوردها را ترکیب نمی‌کنند؛ کنار هم بگذارید یا تکرار کنید
Item collectionهمهٔ آیتم‌هایی که یک partition key مشترک دارند
Partition داغ (Hot partition)partitionی که ترافیکی بیش از سقف خودش می‌گیرد
Write shardingافزودن پسوند به یک کلید برای پخش نوشتن‌هایش
store اصلی Redis (Redis primary store)Redis که تنها نسخهٔ یک keyspace را با persistence و noeviction نگه می‌دارد
Persistence AOF RDBappend-only file در Redis (log عملیات) و snapshotهای نقطه‌ای
هزینهٔ حافظه (Memory cost)RAM لازم برای کل داده به‌علاوهٔ سربار و فضای fork
Elasticsearch / OpenSearchموتورهای توزیع‌شدهٔ جست‌وجو و تحلیل مبتنی بر Lucene
سری زمانی (Time series)دادهٔ زمان‌دار پرافزودن که با پنجرهٔ زمانی کوئری می‌شود
TimescaleDBافزونهٔ PostgreSQL با hypertableهایی که بر اساس زمان partition می‌شوند
InfluxDBپایگاه داده اختصاصی time series
ClickHouseپایگاه داده SQL ستونی برای OLAP
ستونی (Columnar)نگه داشتن هر ستون کنار هم برای پیمایش و فشرده‌سازی سریع
پایگاه داده گراف (Graph database)store گره‌ها و رابطه‌ها با property (Neo4j)
Neo4jپایگاه داده گراف که با Cypher کوئری می‌شود
پایگاه داده برداری (Vector database)storeی که برای جست‌وجوی تقریبی نزدیک‌ترین همسایه ایندکس شده
pgvectorافزونهٔ PostgreSQL برای جست‌وجوی شباهت برداری
NewSQL / distributed SQLSQL و تراکنش ACID روی خوشه‌ای shared-nothing
Spannerپایگاه داده SQL توزیع‌شدهٔ جهانی Google Cloud با TrueTime
CockroachDBdistributed SQL سازگار با PostgreSQL با Raft برای هر range
YugabyteDBdistributed SQL با API سازگار با PostgreSQL به نام YSQL
Vitessلایهٔ sharding و clustering برای MySQL
پایگاه داده serverless (Serverless database)صورت‌حساب و ظرفیتی که دنبال مصرف می‌رود، گاهی تا صفر
Aurora ServerlessAurora با ظرفیت بر حسب ACU که خودکار مقیاس می‌گیرد
NeonPostgreSQL بی‌سرور با جداسازی storage و compute
PlanetScaleسرویس مدیریت‌شدهٔ Vitess (MySQL) و Postgres
DynamoDB on-demandحالت ظرفیت پرداخت به‌ازای درخواست، پیش‌فرض
Polyglot persistenceچند فناوری ذخیره‌سازی، هرکدام بر اساس workload انتخاب‌شده و در مالکیت یک مرز
Bounded contextمرز یک مدل که مالک داده و زبان خودش است
CDCchange data capture: خواندن log پایگاه داده برای انتشار تغییرات
Outboxجدولی که در تراکنش کسب‌وکار نوشته و به‌صورت رویداد relay می‌شود
Dual writeنوشتن هر تغییر در دو store هنگام مهاجرت
Backfillکپی idempotent دادهٔ تاریخی به store تازه
Shadow readخواندن store تازه کنار قدیمی و مقایسه، بی‌آنکه جوابش به کاربر برسد

منابع ​

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