Interview Handbook by Sayed Elmahdy English

المحور 11 · الداتا وقواعد البيانات

NoSQL وتصميم الداتا

Document و Key-Value و Wide-column و Graph، و MongoDB و Redis و Cassandra و Cosmos DB، و Sharding، و Replication، وإمتى SQL وإمتى NoSQL.

20 سؤالJunior · 6Mid · 9Senior · 510 اختيارات

المفاهيم

هنفهم إيه؟ هنقرر شكل تخزين مناسب لما التطبيق يكبر أو يحتاج قراءات متوقعة أو بيانات مترابطة بطريقة مختلفة. هتقارن document وkey-value وgraph وغيرها، وتربط التصميم بنمط الوصول والتوزيع والـ consistency. الهدف اختيار مبرر، مش افتراض إن أسرع أو بلا .

قبل ما تبدأ: في قواعد relational، البيانات جداول وروابط بينها؛ في NoSQL النماذج مختلفة حسب المحرك. access pattern هو السؤال المتكرر الذي يطلبه التطبيق، مثل جلب طلبات عميل. ابدأ من هذا السؤال، ومعرفة من محور 10 تساعدك على المقارنة.

المصطلحات اللي تحتها خط منقّط تقدر تضغط عليها لمعرفة معناها، وترجع تكمل من نفس مكانك.

#ليه NoSQL موجودة؟ والعائلات المختلفةWhy NoSQL exists and its main families

بعض workloads محتاجة reads محددة على بيانات ضخمة موزعة، أو document مرنة، أو graph traversal بدل joins عامة. عائلات مختلفة، مش product واحد ولا وعد إن كل حاجة -free أو أسرع من .

العائلةأمثلةالمشكلة المناسبة والتكلفة
DocumentMongoDB، و Cosmos for NoSQLaggregates متقاربة في document؛ التكرار والـ document growth محتاجين تصميم
Key-valueRedis، و DynamoDBlookup بنمط key معروف؛ queries العشوائية مش نقطة قوتها. DynamoDB كمان بيدعم document values
Wide-columnCassandrapartitioned rows و writes كبيرة؛ query-driven tables وحدود partition
GraphNeo4jعلاقات متعددة القفزات زي product recommendations؛ مش بديل لكل reporting
SearchElasticsearch، و OpenSearchfull-text و relevance و aggregations؛ indexing lag وتكلفة shards
Time-seriesInfluxDBقياسات بالوقت و retention و downsampling؛ series مهمة
Vectorpgvector، و vector capabilities في محركات متعددةsimilarity للـ ؛ approximate recall و filtering و embedding versions

العائلات متداخلة. pgvector extension في PostgreSQL relational، مش دليل إن كل vector search لازم NoSQL. Cassandra wide-column مش نفس columnstore analytics. ابدأ بالمطلوب من queries والـ consistency والـ operations، مش باسم الموضة.

#Model by access patterns: order و customerModel by access patterns: orders and customers

لو الشاشة دايماً بتعرض order مع lines، تحميل document واحدة مفيد. لكن كل orders جوه customer يعمل document بلا حدود ونقطة contention.

اعتبر order مظروف فيه فاتورة الشراء وقتها. رقم العميل reference لملفه الحالي؛ عنوان الشحن المكتوب على الفاتورة snapshot مش بيتغير لما العميل ينقل بيته.

{
  "id": "order-42",
  "tenantId": "store-7",
  "customerId": "customer-9",
  "customerSnapshot": { "name": "Ali", "shippingCity": "Cairo" },
  "status": "pending",
  "lines": [
    { "productId": "product-3", "nameAtSale": "Mug", "qty": 2,
      "unitPriceMinor": 12000, "currency": "EGP" }
  ],
  "schemaVersion": 1
}
  1. اكتب queries: point lookup لـ order، وقائمة customer orders حسب الوقت، وتحديث status. اختار indexes والـ partition key لكل واحدة.
  2. embed lines لأنها bounded ومملوكة للـ order وبتتقري وتتعدل معاه. productId و customerId references لكيانات ليها عمر مستقل.
  3. snapshot للسعر والاسم والعنوان عند البيع؛ current customer data تتجاب من ملفه لو مطلوبة.
  4. لو نسخت current data في أكتر من مكان، حدد update owner وآلية sync و acceptable staleness.

الفلوس هنا minor units من غير floating-point ambiguity؛ currencies ليها scales مختلفة، فحدد السياسة. schemaVersion مع validation و readers تقبل النسخ القديمة؛ flexibility مش غياب schema. limits لحجم document والـ arrays والـ write contention لازم تتراجع حسب المنتج.

#Partition و shard keys والـ hot partitionsPartition keys, sharding and hot partitions

مثال خطوة بخطوة
  1. عندك طلبات ملايين العملاء وعايز توزعها على أكثر من عقدة تخزين. مفتاح التقسيم يحدد الطلب يذهب لأنهي جزء؛ مثل CustomerId.
  2. لو أغلب الاستعلامات تعرض طلبات عميل واحد، المفتاح ده يجمعها في مكان معروف. لكن عميلًا ضخمًا قد يحمل جزءًا واحدًا فوق طاقته؛ ده hot partition.
  3. قبل اختيار المفتاح اكتب أهم قراءاتك وكتاباتك وتوزيع العملاء. توزيع البيانات وحده لا يعني إن الحمل اتوزع بالتساوي، والاستعلام عبر أجزاء كثيرة له تكلفة.

جهاز واحد ليه حدود storage و . يقسم data بين عقد؛ partition key بيحدد مين يستقبل read و write. اختيار غلط يخلي cluster كبير شغال كأنه جهاز واحد.

Access pattern                  Candidate key           Risk
Orders for one ordinary tenant  tenantId                One huge tenant becomes hot
Order point lookups             orderId                 Customer history fans out
Customer history                tenantId + customerId   One celebrity customer can be hot
Write-heavy event archive       tenantId + time bucket  Active bucket can still be hot
Extreme write skew              key + hash bucket       Reads must query several buckets

high مهمة، لكن مش كفاية: key ممكن ليها مليون قيمة ومعظم traffic على قيمة واحدة. قيم متزايدة في range sharding ممكن تركز writes في آخر shard. hash يوزع writes بس يضر range locality. compound أو hierarchical keys حسب دعم database ممكن توازن احتياجات مختلفة.

  1. قيس أكبر partition مش المتوسط، والـ RU أو والـ throttling.
  2. راجع reads: query من غير partition key قد تحتاج scatter-gather لكل shards.
  3. راجع boundary والـ uniqueness scope والـ resharding قبل القرار.
  4. لو قسمت tenant على buckets، احتفظ بطريقة routing و merge للـ results وخطة migration.
مش sharding: الأولى نسخ لنفس الداتا، والتانية توزيع أجزاء مختلفة. الاتنين ممكن يشتغلوا مع بعض.

#Replication و quorum reads و writesReplication and quorum reads and writes

نسخة واحدة نقطة فشل. تزود availability والـ read locality، لكن تحديث النسخ وترتيب الكتابات ليهم تكلفة.

النمطالسلوكالمقايضة
Leader/followerالكتابة من leader وتتنسخ للـ followersasync follower ممكن يرجّع stale data؛ failover محتاج fencing و durability policy
Multi-leaderكتابات في مناطق متعددةconflict detection و resolution؛ last-write-wins ممكن يضيّع تحديثات
Leaderlessالـ coordinator يتعامل مع replicas متعددةquorums و versions و read repair و anti-entropy؛ التفاصيل تختلف
N = 3 replicas: A, B, C
W = 2: a successful write is acknowledged by A and B
R = 2: a read waits for responses from B and C
R + W = 4 > N: the read and write sets intersect at B
But: concurrent writes, version choice and failed writes still need rules.

R عدد ردود القراءة المطلوبة، W عدد acknowledgements للكتابة، N replication factor. R + W > N يضمن intersection لـ quorums على نفس replica set ثابتة. مش ضمان linearizability لوحده. لازم version ordering صح، ومعالجة concurrent و partial writes و membership changes. sloppy ممكن تستخدم replicas بديلة فـ intersection المقصود مايبقاش موجود. write quorum intersection نفسها تحتاج 2W > N لو مطلوبة؛ consensus له بروتوكول أوسع من مجرد المعادلة.

W=1 يقلل انتظار الكتابة لكنه قد يخسر acknowledged data مع failure قبل النسخ. زيادة R أو W ترفع التنسيق وتقلل عدد failures اللي تقدر تتحملها للـ operation دي. ماتستخدمش إعداد منتج لإثبات ضمان مش موثق فيه.

#CAP و PACELC من غير شعاراتCAP and PACELC without slogans

لو network فصلت مجموعتين من replicas، هل الاتنين يقبلوا operations ولا واحدة تستنى؟ بيحدد trade-off أثناء partition، مش قائمة تختار منها اتنين طول الوقت.

During a partition:
  C: preserve one-copy linearizable behavior, possibly reject or delay requests
  A: every request to a non-failing node completes, possibly with stale results
PACELC:
  If Partition: Availability versus Consistency
  Else:        Latency versus Consistency

C هنا linearizability، مش consistency اللي معناها valid constraints. A هي formal availability لكل request لعقدة غير فاشلة، مش uptime عادي. في نظام موزع network partitions احتمال لازم تتعامل معاه؛ مش اختيار نلغي P. product واحد ممكن يختار بشكل مختلف لكل operation أو configuration.

فرعين لمحل والاتصال بينهم قاطع: لو كل واحد يبيع آخر قطعة من غير تنسيق ممكن الاتنين يوعدوا بيها. لو واحد يرفض البيع لحد التأكد، correctness اتحفظت بس availability للعملية قلت.

بيفكرك إن حتى وقت الشبكة السليمة، انتظار replica بعيدة يزود . ماتحطش label ثابت AP أو CP على كل features المنتج من غير تحديد scope وإعداداته.

#Consistency levels: مثال Cosmos DBConsistency levels through Cosmos DB

العميل عدّل عنوانه وبعدها قراه قديم؛ مجرد كلمة eventual مش بتقول تجربة المستخدم هتبقى إيه. اختار guarantee واضحة وحدد نطاقها.

المستوىالوعدمناسب لإيه
Stronglinearizable reads لأحدث committed write وفق ترتيب النظامقرار محتاج أحدث قيمة؛ تنسيق وتكلفة availability/
Bounded stalenessالتأخر محدود بعدد versions أو وقت مضبوطينقراءة قديمة بحد معروف بدل تأخر مفتوح
Sessionداخل session: read-your-writes و monotonic reads مع مناسبالمستخدم يشوف تعديلاته؛ مش global latest لكل users
Consistent prefixترتيب الكتابات محفوظ من غير gaps ظاهرة في prefix المرئيرؤية قديمة لكن بالترتيب
Eventualالتقارب مع توقف الكتابات ووصول التحديثات؛ من غير حد تأخر مضمونread models تتحمل stale data

ده نموذج Cosmos for ؛ راجع mappings للـ التانية و scope ضمانات partition والـ . session tokens لازم تنتقل لو نفس user بيتنقل بين app instances؛ singleton client يساعد إدارة tokens لكن مش بيغطي كل distributed flow. account default يحدد أقصى قوة request consistency المعتادة؛ ماتطلبش strong من account مضبوط على eventual وتتوقع upgrade سحري.

#BASE و ACID و transactions في NoSQLBASE, ACID and NoSQL transactions

عدم استخدام جداول مش معناه ممنوع . الفرق في scope والتكلفة. وصف شائع: Basically Available، و Soft state، و ؛ مش معيار يحدد كل behavior.

// MongoDB.Driver; reuse client. Replica set or supported sharded deployment required.
using var session = await client.StartSessionAsync(cancellationToken: ct);
await session.WithTransactionAsync(async (s, token) =>    // (1)
{
    var filter = Builders<StockDocument>.Filter.And(
        Builders<StockDocument>.Filter.Eq(p => p.Id, productId),
        Builders<StockDocument>.Filter.Gte(p => p.Available, quantity));
    var update = Builders<StockDocument>.Update.Inc(p => p.Available, -quantity);
    var result = await stock.UpdateOneAsync(s, filter, update,
        cancellationToken: token);                        // (2)
    if (result.ModifiedCount != 1)
        throw new InvalidOperationException("Insufficient stock");
    await orders.InsertOneAsync(s, order, cancellationToken: token);
    return order.Id;                                      // (3)
}, cancellationToken: ct);
🧾 شرح الكود
  1. (1) session واحدة لكل العمليات؛ helper ممكن يعيد callback للأخطاء المؤقتة، فممنوع external side effects أو swallow exceptions.
  2. (2) quantity موجبة ومتحقق منها قبل الكود؛ atomic predicate مع transaction يربط stock والـ order. لازم تمرر session لكل call.
  3. (3) order ID ثابت خارج callback يساعد outcome handling؛ ماتعملش parallel operations جوه نفس transaction. المقتطف يفترض StockDocument و OrderDocument models و collections متجهزين.
المنتجحدود مهمة
MongoDBsingle-document writes atomic؛ multi-document transactions على deployments مدعومة مع read/write concerns مناسبة وتكلفة تنسيق
DynamoDBTransactWriteItems all-or-nothing لحد 100 distinct items في نفس account و Region، ضمن حجم وحدود الخدمة؛ مش BatchWriteItem
Cosmos for transactional batch لنفس logical partition في نفس container؛ مش cross-partition transaction عامة

transaction ممكن توجد داخل database بتوفر eventual replica reads. الفلوس والـ stock غالباً تحتاج conditional writes و version checks أو transaction واضحة، مش last-write-wins. ماتنقلش توقعات relational لكل NoSQL transaction من غير توثيق.

#MongoDB indexing و query plansMongoDB indexing and query plans

document model مش بتمنع collection scans. index لازم يدعم filter والـ sort الفعليين، وإلا الـ flexible هتخبي bottleneck بس.

using MongoDB.Driver;

var keys = Builders<OrderDocument>.IndexKeys
    .Ascending(o => o.TenantId)
    .Ascending(o => o.CustomerId)
    .Descending(o => o.CreatedAt);                        // (1)
await orders.Indexes.CreateOneAsync(
    new CreateIndexModel<OrderDocument>(keys),
    cancellationToken: ct);                              // (2)
🧾 شرح الكود
  1. (1) query بتساوي tenant و customer وبعدها sort بالوقت. لو فيه pagination، ضيف unique tie-breaker للـ sort والـ index حسب الحاجة.
  2. (2) index تتدار كتغيير deployment متراجع؛ مش كل request تعمل create. راجع plan بـ explain و executionStats: keysExamined و docsExamined مقارنة بالـ nReturned.

MongoDB عندها compound و unique و multikey للـ arrays و partial و indexes. multikey ليها قيود على compound arrays والـ covered queries؛ ماتعتمدش على mapping ذهني لجدول . TTL expiration asynchronous، فمش ضمان مسح لحظي وقت expiry؛ query أو authorization لازم يتحققوا من صلاحية record. unique indexes على sharded collections ليها shard-key restrictions. كل index تكلف storage و writes و memory.

#Redis data structures: أكتر من cacheRedis data structures beyond caching

أحياناً المطلوب membership أو ranking أو event log، مش مجرد تحت key. Redis عندها operations جاهزة تقلل read-modify-write في التطبيق.

Structureمثالالتفصيلة المهمة
Stringcounter أو أو cached valueINCR atomic؛ وسياسة eviction مهمين
Hashحقول cartتعديل field من غير إعادة لكل object
Setunique user IDs لمنتجmembership و intersection
Sorted setترتيب products بالـ popularitymember فريد و score؛ مش decimal ledger للفلوس
Listqueue بسيطةpop لوحدها مش processing acknowledgement protocol
Streamorder events مع consumer groupspending entries و و replay و retention محتاجين إدارة
Bitmap / HyperLogLog / Geodaily activity، و approximate unique counts، و nearby storesكل واحدة ليها semantics ودقة وتكلفة مختلفة
HSET cart:{customer-9} product-3 2
SADD product:3:interested customer-9
ZINCRBY products:popular 1 product-3
XADD orders:events * orderId order-42 status paid
XGROUP CREATE orders:events fulfilment 0 MKSTREAM
XREADGROUP GROUP fulfilment worker-1 COUNT 10 STREAMS orders:events >
# After durable processing: XACK orders:events fulfilment <message-id>

دي redis-cli commands توضيحية؛ XGROUP CREATE تتعمل مرة وتتعامل مع group موجودة. Streams ممكن تعيد pending message بعد crash، فـ consumer ويعمل claim للمتروك. Pub/Sub مختلف: messages مش متخزنة للمشترك الغايب. Lua أو تجمع operations atomically على السيرفر ضمن قيود cluster keys؛ Redis مش بتعمل relational rollback لكل runtime error. persistence و و failover configuration يحددوا durability؛ in-memory مش معناها مفيش تخزين ولا معناها durable افتراضياً.

#MongoDB و Cosmos DB من .NETUsing MongoDB and Cosmos DB from .NET

اختار driver لما محتاج native operations وتحكم واضح، أو provider لو abstraction وحدود الترجمة مناسبين. تغيير provider مش بيحوّل document database لـ relational.

// MongoDB.Driver; register and reuse MongoClient for its connection pools.
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;

var client = new MongoClient(mongoConnectionString);
var orders = client.GetDatabase("store")
    .GetCollection<OrderDocument>("orders");
var filter = Builders<OrderDocument>.Filter.And(
    Builders<OrderDocument>.Filter.Eq(o => o.TenantId, tenantId),
    Builders<OrderDocument>.Filter.Eq(o => o.Id, orderId)); // (1)
var order = await orders.Find(filter).FirstOrDefaultAsync(ct);

public sealed class OrderDocument
{
    [BsonId] public string Id { get; set; } = "";
    public string TenantId { get; set; } = "";
    public string CustomerId { get; set; } = "";
    public DateTime CreatedAt { get; set; }
}
🧾 شرح الكود
  1. (1) tenant ID يطلع من trusted authorization context، والـ filter يجمعه مع order ID. BsonId يخزن Id كـ _id؛ مش استعلام مشروط على string مركبة.
// Microsoft.Azure.Cosmos; reuse CosmosClient. Existing /tenantId container assumed.
using Microsoft.Azure.Cosmos;

var cosmos = new CosmosClient(cosmosConnectionString);
var container = cosmos.GetContainer("store", "orders");
try
{
    var response = await container.ReadItemAsync<CosmosOrder>(
        id: orderId, partitionKey: new PartitionKey(tenantId),
        cancellationToken: ct);                          // (2)
    Console.WriteLine(response.RequestCharge);
}
catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
    Console.WriteLine("Order not found in the authorized partition");
}
public sealed record CosmosOrder(string id, string tenantId, string status);
🧾 شرح الكود
  1. (2) point read محتاجة id و partition key، والهوية فريدة جوه logical partition. track RU و diagnostics؛ 429 ليها retry policy بحدود، مش loop لا نهائية. للـ updates استخدم ETag مع IfMatchEtag لو مطلوب .
الطريقالحدود اللي تراجعها
Microsoft.EntityFrameworkCore.Cosmosmapping للـ container و partition key و translation؛ مش relational migrations و joins عامة
MongoDB.EntityFrameworkCoreprovider رسمي من MongoDB؛ راجع version compatibility و unsupported EF features
Native SDKsتحكم أوضح في sessions و batches و diagnostics؛ mapping و abstraction مسؤوليتك

استخدم secret store أو managed identity حيث متاحة بدل credentials في source. المقتطفات بتفترض provisioned databases و collections و 10 مع package versions متوافقة. ماتعملش client جديد لكل request.

#Polyglot persistence و SQL vs NoSQL decisionPolyglot persistence and SQL versus NoSQL decisions

أداة مختلفة لكل query ممكن تحسن الأداء، لكنها تزود backups والـ monitoring والـ skills والـ consistency work. polyglot persistence قرار cost مش هدف لوحده.

الاحتياجبداية مناسبةالسؤال الحاسم
orders و payments بعلاقات و constraintsrelational database غالباًإيه boundary والـ reporting المطلوبين؟
bounded documents و access patterns معروفةdocument store أو PostgreSQL embed ولا reference؟ ومين صاحب التكرار؟
key lookups و و atomic structuresRedis أو DynamoDB حسب durability والتشغيلهل data دي authoritative ولا مشتقة؟
full-text relevance و facetingsearch index أو relational search حسب الحجمتتحمل indexing lag قد إيه؟
علاقات traversal كتيرgraph engine أو relational recursive queriesعمق traversal وحجم graph يبرروا أداة تانية؟
semantic similaritypgvector أو vector-capable enginerecall والـ filters والـ والـ access control؟
-- PostgreSQL: stable relational facts plus variable product attributes.
CREATE TABLE products (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL,
    price numeric(18,2) NOT NULL CHECK (price >= 0),
    attributes jsonb NOT NULL DEFAULT '{}'::jsonb         -- (1)
);
CREATE INDEX ix_products_attributes ON products USING gin (attributes);
SELECT id, name FROM products
WHERE attributes @> '{"color":"blue"}'::jsonb;           -- (2)
🧾 شرح الكود
  1. (1) JSONB مرونة للـ sparse attributes، مع و constraints و transactions relational.
  2. (2) containment query ممكن تستفيد من GIN؛ equality أو range على field محددة ممكن يناسبها expression B-tree بدل index شامل.

JSONB مش automatic ، والتحديثات الكبيرة والـ indexing ليهم تكلفة. لو عندك مصدر الحقيقة و search نسخة مشتقة، استخدم أو و consumers و reconciliation؛ ماتعملش dual write ساذجة. اعرف تعيد بناء index وتتعامل مع deleted records و versions. query result لازم يلتزم authorization حتى لو search index قديم.

مراجع للمراجعة: Cosmos DB consistency، و MongoDB .NET transactions، و DynamoDB transactions، و Redis data types، و PostgreSQL JSONB، و ورقة PACELC. الأمثلة مقتطفات مستقلة؛ transaction example بتفترض collections و models فيها الحقول المستخدمة، والـ package versions تتراجع مع provider compatibility.

أسئلة الانترفيو

راجع فهمك

ليه الاختيار ده مناسب؟ إمتى ممكن ماينفعش؟ وإيه اللي هيتغير لو الحمل زاد أو ظهر فشل؟

11.1Why would you choose a NoSQL database?Junior

لـ workload محددة: document أو key access أو graph أو search. مش لأن قديمة أو بلا .

الإجابة النموذجية (English)

I choose a database when its data model and operational guarantees fit a concrete access pattern better than a relational design. Examples include bounded document aggregates, predictable key-based access, graph traversal or search relevance. I compare consistency, boundaries, query flexibility and operational cost. I do not assume NoSQL means no , automatic scalability or no transactions. If relational constraints and changing reports dominate, a relational database may remain the simpler choice.

11.2What are the main NoSQL families?Junior

document و key-value و wide-column و graph و search و time-series و vector capabilities؛ الحدود متداخلة.

الإجابة النموذجية (English)

I distinguish document stores for aggregates, key-value stores for known-key access, wide-column stores for partition-oriented workloads and graph databases for traversals. Search engines specialize in relevance, time-series engines in timestamped measurements, and vector capabilities in similarity search. The boundaries overlap: DynamoDB supports document values, and PostgreSQL can provide vector search through pgvector. I use the categories to understand access patterns, not as rigid labels that determine every guarantee of a product.

11.3Does a document database have no schema?Junior

موجودة في شكل documents والـ readers حتى لو مش rigid table. validation و versioning لازمين.

الإجابة النموذجية (English)

I consider a document database -flexible rather than schema-free. Documents still have field names, types and assumptions that application readers depend on. I define validation rules for important , version evolving document shapes and support older documents during rollout. I also choose stable money and date representations. Without that discipline, flexibility simply moves schema errors from deployment time to runtime and makes migrations and analytics harder to reason about.

11.4When should you embed data instead of referencing it?Junior

embed bounded owned data بتتقري مع parent؛ references للكيانات المستقلة و arrays غير المحدودة.

الإجابة النموذجية (English)

I embed data when it is bounded, owned by the parent and commonly read or changed with it, such as order lines. I reference independently changing entities such as customers and products, and avoid unbounded arrays such as every order inside one customer. I may retain purchase-time snapshots separately from current records. The decision considers document size, write contention and consistency, not just reducing one join or one network call.

11.5How do sharding and replication differ?Junior

أجزاء مختلفة موزعة؛ نسخ من نفس الأجزاء. واحدة scaling والتانية resilience/locality، وممكن الاتنين.

الإجابة النموذجية (English)

I use to distribute different portions of a dataset across nodes, increasing capacity and spreading workload when the key is suitable. keeps multiple copies of the same portion for resilience and read locality. A sharded cluster can replicate every shard. Neither removes design work: sharding needs routing and balance, while replication needs consistency and failover policies. I would not expect adding replicas alone to solve a single hot write partition.

11.6What is eventual consistency?Junior

لو writes وقفت والتحديثات وصلت النسخ تتقارب؛ مفيش lag bound من الكلمة لوحدها، ولا read-your-writes مضمون.

الإجابة النموذجية (English)

I understand as convergence when writes stop and updates can propagate. It does not by itself guarantee a maximum delay or that an immediate read sees my write. I use it for workloads that tolerate stale results, such as a derived product search index, and define how that staleness appears to users. For decisions like reserving the last item, I need a stronger operation or an authoritative conditional write.

11.7How would you model orders and customers in a document database?Mid

order مستقلة فيها bounded lines و snapshot للبيع؛ customerId reference؛ history query محتاجة index و partition مناسبين.

الإجابة النموذجية (English)

I start from queries: point-reading an order, listing a customer's history and changing order state. I store each order separately with bounded lines and purchase-time snapshots, while CustomerId references the current customer. I do not append unlimited orders to one customer document. I then choose partitioning and indexes for those queries and define how copied current facts would be synchronized. Historical prices and shipping details should not change when the catalog or customer record changes.

11.8What makes a good partition key?Mid

distribution وحجم partitions و query locality و boundary. high مش كفاية لو traffic منحازة.

الإجابة النموذجية (English)

I look for enough distinct values, balanced data and traffic, and routing that matches the main queries. I evaluate the busiest tenant or customer, not just average size, and consider and uniqueness scope. A high- key can still be hot if one value receives most requests. Bucketing may spread writes but makes reads and ordering harder. I also review key-change and resharding costs because a convenient initial key can become expensive to replace.

11.9How would you diagnose a hot partition?Mid

per-partition metrics و throttling و أكبر keys. replicas مش بتقسم hot key؛ bucketing له read fan-out.

الإجابة النموذجية (English)

I inspect per-partition , and throttling, then identify which logical keys dominate traffic or storage. I check whether range growth concentrates writes or one tenant overwhelms an otherwise balanced design. Possible remedies include a different compound key, bounded time buckets or hash buckets, but each changes routing and read fan-out. I test the largest cases and plan data migration. Adding replicas may improve some reads without fixing a single overloaded write key.

11.10What are leader-follower, multi-leader and leaderless replication?Mid

الأول leader واحد للكتابة؛ multi-leader conflict resolution؛ leaderless quorums و repair حسب المنتج.

الإجابة النموذجية (English)

I distinguish a leader accepting writes and replicating to followers from multiple leaders accepting writes in different locations. The latter needs explicit conflict handling. Leaderless systems coordinate reads and writes across replicas with configurable acknowledgements, versions and repair mechanisms. Each model has trade-offs around , stale reads, failover and concurrent updates. I check the actual implementation and settings rather than assuming a model name proves durability or strong consistency.

11.11What does R + W > N mean in quorum replication?Mid

read/write sets تتقاطع على replica set ثابتة؛ مش linearizability theorem لوحده.

الإجابة النموذجية (English)

I use N for replica count, W for required write acknowledgements and R for required read responses. If R plus W exceeds N over the same fixed replica set, successful read and write quorums intersect. That helps a read encounter an acknowledged write, but does not alone guarantee linearizability. Correct version selection, concurrent and failed writes, membership changes and sloppy- behavior still matter. I rely on the database's documented protocol rather than treating the inequality as a complete proof.

11.12How does session consistency improve user experience in Cosmos DB?Mid

read-your-writes و monotonic reads داخل session؛ session تتنقل بين app instances لو محتاج.

الإجابة النموذجية (English)

I use session consistency when a user should see their own changes without requiring every user to observe the globally latest value. Session help maintain read-your-writes and monotonic reads within the relevant session scope. Reusing a client helps manage tokens, but a user moving between application instances may require explicit propagation. I still distinguish this from an atomic business and verify the and partition scope of the guarantees I depend on.

11.13How do you index a MongoDB order-history query?Mid

tenant و customer equality وبعدهم createdAt sort؛ pagination tie-breaker. راجع docsExamined والـ nReturned.

الإجابة النموذجية (English)

I begin with the query shape, for example tenant and customer equality followed by creation-time ordering. A compound index in that order is a candidate, with a unique tie-breaker if pagination needs deterministic order. I inspect explain statistics to compare examined keys and documents with returned rows, and verify that sorting is supported. I account for index storage and write cost and review array, partial and unique-index restrictions rather than indexing every field.

11.14What can Redis do beyond caching?Mid

hashes و sets و sorted sets و lists و streams و counters. data structure مش كفاية لdelivery أو durability guarantee.

الإجابة النموذجية (English)

I use Redis structures for specific operations: hashes for cart fields, sets for membership, sorted sets for popularity rankings and atomic counters for usage. Streams support retained events and consumer groups, while lists support simpler queues. I distinguish Streams from Pub/Sub, which does not retain messages for disconnected consumers. Durability, eviction, and recovery policies still need design. An atomic command also does not automatically make an entire business workflow exactly-once.

11.15How do you access MongoDB and Cosmos DB efficiently from .NET?Mid

reuse clients؛ typed Mongo filters؛ Cosmos point read بـ id و partition key؛ diagnostics و bounded retries.

الإجابة النموذجية (English)

I reuse MongoClient and CosmosClient so their connection management and session behavior are effective. For MongoDB I use typed filters and appropriate indexes. For Cosmos point reads I supply both id and partition key and monitor request charges and diagnostics. I handle not-found and throttling deliberately, propagate cancellation and protect credentials. providers are available, but I verify their translation and feature limitations instead of expecting relational joins and migrations from every provider.

11.16Explain CAP precisely and how PACELC extends the discussion.Senior

وقت partition في trade-off بين linearizability والـ formal availability. تضيف /consistency وقت الاتصال السليم.

الإجابة النموذجية (English)

I explain as a limitation during a network partition: a system cannot guarantee both linearizable behavior and completion of every request to every non-failing node. It is not a blanket choose-two slogan, and consistency here differs from validity. adds the healthy-network trade-off between and consistency, because coordination still takes time without a failure. I discuss the guarantee for a particular operation and configuration rather than labeling an entire product permanently.

11.17Can NoSQL databases provide ACID transactions?Senior

أيوه؛ Mongo multi-document، و DynamoDB TransactWriteItems، و Cosmos batch داخل partition. boundaries مختلفة.

الإجابة النموذجية (English)

Yes. I check the supported scope rather than assuming the data model excludes . MongoDB supports multi-document transactions on suitable deployments, DynamoDB offers TransactWriteItems, and Cosmos for has transactional batches within one logical partition and container. Their limits, , retry behavior and costs differ. I model aggregates to keep important local where possible and use conditional writes when sufficient, rather than assuming every distributed operation can join one unlimited transaction.

11.18What can go wrong when a transaction callback is retried?Senior

email أو payment ممكن يتكرر؛ session لكل call و stable IDs و . unknown commit محتاج verification.

الإجابة النموذجية (English)

I assume a retryable callback may execute more than once. Sending email or charging a remote provider inside it can duplicate side effects even if the database changes roll back. I keep the callback limited to database work, pass its session to every operation and use stable identifiers and an where needed. I do not swallow failures or run unsupported parallel operations. I also plan for ambiguous commit outcomes and reconciliation instead of treating a timeout as proof of failure.

11.19How would you keep SQL and a search index consistent?Senior

source of truth واحدة، أو ، versioned consumers و replay و reconciliation؛ stale index مش authorization source.

الإجابة النموذجية (English)

I make one store authoritative and treat the search index as rebuildable derived data. I publish changes through an or rather than independently writing both stores in a request. Consumers handle duplicates, ordering and document versions, including deletions. I monitor lag, support replay and reconcile drift. The product defines acceptable search staleness, and sensitive access checks do not trust a stale index alone. A rebuild procedure is part of the design, not an emergency improvisation.

11.20When is PostgreSQL JSONB enough, and when would you add another store?Senior

للمرونة مع relational constraints؛ store تانية لو pattern أو scale مثبتة تبرر التشغيل والـ consistency cost.

الإجابة النموذجية (English)

I consider when variable attributes belong alongside relational facts and I still need joins, constraints and familiar . Targeted expression indexes or GIN may support the access patterns without another service. I add a specialized store only when measured search, graph, partitioning or requirements justify its operational and consistency costs. JSONB is not automatic , but document flexibility alone is also not a sufficient reason to operate multiple databases.

اختبر نفسك

إجابات الاختبار وعلامات إكمال المحاور بتتحفظ على المتصفح ده، ومش بتتنقل لأجهزة تانية.

النتيجة: 0 / 0

Which data is usually best embedded inside an order?

lines مملوكة للـ order ومحدودة؛ arrays غير المحدودة خطر.

A partition key has many values but one receives most writes. What follows?

توزيع traffic مهم زي عدد values.

What does R + W > N guarantee under fixed replica-set assumptions?

intersection شرط مفيد، بس protocol والـ versions والـ concurrency لسه مهمين.

CAP consistency refers to...

مختلفة عن Consistency في .

Which Cosmos DB level is commonly chosen for read-your-writes within a session?

session guarantee مش global latest لكل العملاء.

Cosmos DB for NoSQL transactional batches normally require...

partition key بتأثر على atomicity boundary.

MongoDB TTL indexing means an expired record...

الـ cleanup مش expiry authorization mechanism.

Which Redis facility retains entries and supports consumer groups?

Streams فيها pending و ؛ consumers لسه محتاجة .

What does a Cosmos DB point read need besides an item id?

id و partition key بيوجهوا القراءة مباشرة.

Which design avoids naïve SQL-plus-search dual writes?

derived index محتاجة lag monitoring و replay و reconciliation.