Databases & System Design•Part 3: NoSQL & Document Databases (MongoDB, DynamoDB) (26 - 40)
CAP Theorem:
In Simple Words: A distributed system can guarantee at most two of three:
- Consistency: Every read gets latest write.
- Availability: Every request gets a non-error response.
- Partition Tolerance: System keeps running despite network splits.
- RDBMS focuses on CA or CP; NoSQL typically focuses on CP (MongoDB) or AP (Cassandra, DynamoDB).
typescript
// Demonstrating Eventual Consistency (AP) handling in client code:
// Retry read with backoff if recent write is not yet visible on replica:
async function getWithRetry(id: string, attempts = 3): Promise<Document | null> {
for (let i = 0; i < attempts; i++) {
const doc = await db.collection('orders').findOne({ _id: id });
if (doc) return doc;
await new Promise(r => setTimeout(r, 100 * (i + 1))); // Backoff
}
return null;
}