Skip to content
  • Home
  • YouTube
  • About
  • Contact
Learn to Code and Code to Learn

Learn to Code and Code to Learn

Your Journey to Code Mastery

  • Interview Prep Sheet
    • TCP DSA 75
    • TCP DSA 150
    • TCP DSA 351
    • TCP HLD 50
    • TCP HLD 101
  • General
    • Setup
    • Mastering in C programming (Crash Course)
  • DSA Patterns
    • Fast and Slow Pointer
    • sliding window
      • fixed size sliding window
      • Variable size sliding window
  • Coding Prep
    • Leetcode Problems
      • Leetcode Practice
      • Leetcode PTOD
      • TCP DSA 150
    • GFG
      • GFG Practice
      • GFG PTOD
    • Company wise Interview Questions
      • Google
      • Microsoft
  • Programming
    • C Programming
    • C++
      • C++-11
      • c++-14
      • STL
    • Python
  • HLD
    • TCP HLD 50
    • TCP HLD 101
  • LLD
    • SOLID Principle
    • Design Pattern
      • Creational Design Patterns
        • Singleton
  • Toggle search form

CAP THEOREM

Posted on May 24, 2026May 24, 2026 By thecodepathshala No Comments on CAP THEOREM

What is CAP Theorem?

Consistency (C) — Every read receives the most recent write, or an error. All nodes see the same data at the same time. After updating data, every future read returns updated value.
Example : If user changes password, Any server/node immediately returns new password.

Availability (A) — Every request to a non-failed node receives a response (success or failure), but that response may not be the most recent write. The system stays up and responsive. Even if some nodes fail, system continues responding.
Example : Amazon shopping cart still works even if few servers die.

Partition Tolerance (P) — The system continues to operate even when messages between nodes are dropped or delayed due to a network split.
Network Partition : Some nodes cannot communicate with others.

Node A ----X---- Node B

Both nodes are alive but disconnected.
In distributed systems : partitions are unavoidable. Therefore P is practically mandatory.

Details Explanation:

CAP theorem states that during a network partition, a distributed system must choose between consistency and availability. CP systems prioritize correctness and may reject requests, while AP systems prioritize uptime and may return stale data temporarily.

In Short : CAP Theorem states that a distributed system can guarantee at most two of the three properties simultaneously: Consistency, Availability, and Partition Tolerance introduced by Eric Brewer.
Since network partitions are a reality in any distributed system, the real-world choice almost always comes down to CP vs AP.

CAP theorem proof

Consider a distributed system with two nodes:

        Node A   <----X---->   Node B

Both nodes store the same data:

X = 10

Now suppose a network partition happens.

This means:

  • Node A and Node B are alive
  • But they cannot communicate with each other

Step-by-Step Scenario

Step 1: User Sends a Write Request

A user updates:

X = 20

The write reaches Node A.

Now:

Node A: X = 20
Node B: X = 10

But because of the partition:

  • Node A cannot send the updated value to Node B.

Step 2: Another User Sends a Read Request

Now a read request goes to Node B.

Node B only knows:

X = 10

because it never received the latest update.


The System Has Only Two Choices


Option 1 — Return Old Value

Node B responds with:

X = 10

The system remains available because it answered the request.

BUT:

The answer is stale and incorrect.

So:

  • Availability = maintained
  • Consistency = broken

This is an AP system behavior.


Option 2 — Reject the Read Request

Node B refuses to answer because it is unsure whether its data is latest.

Example:

ERROR: Cannot guarantee latest value

Now:

  • Consistency = maintained
  • Availability = broken

This is a CP system behavior.


Why Can’t We Have Both?

To guarantee consistency:

  • Node B must know about the latest write.

But due to the network partition:

  • communication between nodes is impossible.

So the system must choose:

ChoiceResult
Answer requestMay return stale data
Reject requestSystem becomes unavailable

It cannot do both simultaneously.

Conclusion

During a network partition, a distributed system cannot guarantee both:

  • Consistency (latest data)
  • Availability (every request gets response)

Therefore:

In the presence of a Partition, the system must choose either Consistency or Availability.

This is the essence of the CAP theorem.

CP vs AP vs CA

CAP Theorem

CP Systems

Choose : Consistency & Partition Tolerance
Sacrifice : Availability
Behavior During Partition :
If nodes cannot agree:
system rejects requests
or becomes temporarily unavailable
Goal :
avoid stale/incorrect data
Example:
Bank account balance. Wrong balance is unacceptable.
Expectation :
reject transaction than show incorrect money

CP Database Examples
  • MongoDB (with majority write concern)
  • HBase
  • Redis Sentinel/Cluster modes
  • Zookeeper
  • etcd
  • Cockroach Labs / CockroachDB
CP Timeline Example
Client -> Node A writes x=10
Partition happens
Client reads from Node B
Node B cannot verify latest state
=> reject request

AP Systems

Choose : Availability & Partition Tolerance
Sacrifice : Strong Consistency
Behavior During Partition :
System continues serving requests even if:
data may be stale/older
replicas diverge temporarily
Goal :
Should return response (success/falure) even with incorrect data
Example:
Social media likes count.

Seeing 100 likes instead of 101 likes for few seconds is acceptable.

Expectation :
Should return response even with stale data till sync happens.

AP Database Examples
  • Cassandra
  • Amazon DynamoDB
  • Riak
  • Couchbase
AP Timeline Example
Node A receives x=10
Partition occurs
Node B still serves old x=5

System available but inconsistent temporarily. Later synchronization happens.

CA Systems

Choose : Consistency & Availability
Sacrifice : Partition Tolerance
Reality :
True CA systems do not exist in distributed environments because network failures always possible.

CA Database Examples
  • Single-node MySQL
  • Single-node PostgreSQL

Why you always need P in practice

Network partitions are not optional failures — they happen in any distributed system due to packet loss, hardware failure, or datacenter outages. The theorem’s real implication is:

You must choose between CP and AP. CA is only possible in a single-node system.

Single-node relational DBs (Postgres, MySQL deployed on one machine) are CA — but the moment you replicate them, you must handle partitions.

Interview Understanding

Most systems are:
->. tunable
->. configurable.
Example:
Cassandra allows tuning:
consistency levels
quorum reads/writes

Consistency models (interview depth)

CAP’s “C” is strong (linearizable) consistency. But in practice there’s a spectrum:

Strong consistency — All nodes see the same data simultaneously. Reads always return the latest write. Slowest. Used in: banking, inventory management, leader election.

Eventual consistency — Nodes will eventually converge to the same state, but reads may be stale in the interim. Fastest. Used in: shopping carts, DNS, social media likes.

Eventual consistency — Nodes will eventually converge to the same state, but reads may be stale in the interim. Fastest. Used in: shopping carts, DNS, social media likes.
Example :
not immediately synchronized globally
eventually becomes correct

Causal consistency — Operations with a causal relationship are seen by all nodes in that order. Middle ground. Used in: comment threads (reply must appear after the parent post).

Read-your-writes consistency — After you write, you’ll always read that write. Other users might still see stale data. Used in: user profile updates.

Strong Consistency vs Eventual Consistency

FeatureStrong ConsistencyEventual Consistency
ReadsLatest dataPossibly stale
LatencyHigherLower
AvailabilityLowerHigher
ComplexityHighModerate
Use CasesBankingSocial media

PACELC — the extension interviewers love

CAP only talks about behaviour during a partition. But partitions are rare.
PACELC extends it to normal operations:

If Partition → choose between Availability and Consistency.
Else → choose between Latency and Consistency.

Even without a partition, replicating data to achieve consistency adds latency. Cassandra for example is AP/EL — it prefers availability during partitions and low latency during normal operation.

Real-World Examples

1. Banking System → CP

Requirements:

  • no double spending
  • accurate balances

Tradeoff:

  • temporary unavailability acceptable

2. WhatsApp → AP leaning

Requirements:

  • messages should send quickly

Temporary inconsistency acceptable:

  • message sync later

3. DNS → AP

DNS must always respond.

Stale records acceptable briefly.

4. Google Docs

Hybrid:

  • availability prioritized
  • operational transforms reconcile conflicts

Real-world system mapping

CAP Interview Answer Structure

If interviewer asks:

“Explain CAP theorem”

Answer:

CAP theorem says a distributed system can provide at most two of:
Consistency, Availability, and Partition Tolerance.

Since partitions are unavoidable in distributed systems, the real tradeoff is between Consistency and Availability during network failures.

CP systems sacrifice availability to maintain correctness, while AP systems sacrifice immediate consistency to remain available.

When asked “what database would you use?”, walk through this reasoning:

  1. What’s the consequence of stale data? — Money/inventory → CP. Social feed → AP is fine.
  2. What’s the consequence of downtime? — Payments need to respond with an error. A product listing can serve a cached (stale) result.
  3. What’s your write pattern? — Heavy writes across regions → AP (Cassandra, DynamoDB). Single region with strong reads → CP (Postgres replicated, or Spanner).
  4. Can you tune it? — Cassandra lets you set QUORUM read/write levels per query, giving you CP behaviour when you need it on critical paths.

A strong answer names the tradeoff explicitly: “I’d use Cassandra here because downtime is more damaging than briefly stale product counts. If a user adds to cart during a partition, I’d rather accept the write and reconcile later than show an error.”

Common Interview Follow-Ups


Q1: Why is partition tolerance mandatory?

Because:

  • network failures are inevitable
  • distributed nodes can become unreachable

Q2: Is NoSQL always AP?

No.

Examples:

  • Cassandra → AP
  • HBase → CP

Q3: Can a system switch dynamically?

Yes.

Many modern databases allow:

  • tunable consistency
  • quorum configuration

Q4: Why do companies prefer eventual consistency?

Because:

  • lower latency
  • better scalability
  • higher availability

Quick Comparison Table

PropertyCPAP
PriorityCorrectnessAvailability
During PartitionReject requestsServe stale data
LatencyHigherLower
Use CasesBankingSocial feeds
ExampleetcdCassandra

Golden Interview Lines

Line 1

In distributed systems, partition tolerance is non-negotiable.

Line 2

CAP tradeoff matters only during network partitions.

Line 3

Most modern systems are neither purely CP nor AP; they provide tunable consistency.


HLD, hld101, System Design, TCP HLD50 Tags:HLD, TCP HLD101, TCP HLD50

Post navigation

Previous Post: TCP DSA 351

More Related Articles

Single Responsibility Principle C++
Dependency Inversion Principle C++
Interface Segregation Principle(ISP) C++
Liskov Substitution Principle C++
TCP HLD 50 HLD
Open-Closed Principle C++

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Archives

  • May 2026
  • August 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • August 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • September 2023
  • February 2023
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021

Categories

  • Algo
  • Array in C
  • C Programming
  • C++
  • C++
  • Company Wise
  • Competitive Programming
  • Design Pattern
  • DS
  • DS & Algo
  • Fast and Slow Pointer
  • fixed size sliding window
  • General
  • GFG
  • GFG PTOD
  • HLD
  • hld101
  • Interview Prep Sheet
  • Interview Questions
  • Leetcode Problems
  • Leetcode PTOD
  • LLD
  • Low-level design
  • Mastering in C programming (Crash Course)
  • Neetcode 150
  • Programming
  • Roadmap
  • Setup
  • Setup
  • sliding window
  • SOLID Principle
  • STL
  • string in c
  • System Design
  • TCP DSA 150
  • TCP DSA 351
  • TCP DSA 75
  • TCP HLD50
  • Top X
  • Variable size sliding window

Tags

algorithm array basic c++ coding interview C Programming Crash Course data structure and algorithm design pattern dsa easy Fixed size sliding window fubctions GFD gfg GFG PTOD hard HLD jump game LC PTOD leetcode Leetcode PTOD Leetcode Top Interview 150 LLD loop loops Low-level design Mastering C Programming in 15 Days matrix medium rotate array searching&sorting sliding window solid STL string string in c sunction in c system design TCP HLD50 TCP HLD101 Template in C++ Top Top 20 coding patterns to master MAANG Interview Top interview 150

Is DSA required for FAANG interview 🇮🇳♥️
Bug free code | prod ready #google #leetcode #codeprep #codeadventure #codeeveryday
2 sum in O(n) #google #microsoft
Design a system for 10 million users #Design #google #microsoft #interview
System design basic #systemdesign #apple #google
LeetCode #1 – Two Sum | Under 3 Minutes #leetcode #viral #codeeveryday #codelife
🚀 LeetCode #1 – Two Sum Explained in Under 2 Minutes!
Learn the most asked coding interview problem using the Hash Map approach and understand why it runs in O(n) time instead of O(n²).
In this Short, you'll learn:
✅ Problem statement
✅ Optimized Hash Map approach
✅ Step-by-step dry run
✅ Time & Space Complexity
✅ Interview tips
If you're preparing for FAANG, Microsoft, Amazon, Google, or any software engineering interview, this series is for you.
👍 Like the video if it helped.
💬 Comment which LeetCode problem I should explain next.
🔔 Subscribe for daily DSA, Golang, System Design, and Coding Interview content.
#leetcode #twosum #dsa #coding #programming #cpp #golang #interview #softwareengineer #shorts #codinginterview #algorithms #datastructures
🚀 LeetCode #1 – Two Sum Explained in Under 3 Minutes! #leetcode #viral #codeeveryday #codelife
Queue #codinginterview #education #databaseconcepts #algorithmanalysis #spacecomplexity #dsa
Want to clearly understand Time Complexity and Space Complexity of Queue for DSA and coding interviews? 🤔
In this video, we explain Queue Data Structure Complexity using simple examples, Big-O notation, and interview-focused concepts.

🚀 What You’ll Learn in This Video:

What is a Queue in Data Structures?

Queue Principle: FIFO (First In First Out)

Types of Queue (Simple, Circular, Priority, Deque)

Time Complexity of Queue Operations

Enqueue → O(1)

Dequeue → O(1)

Front / Peek → O(1)

Rear → O(1)

Search → O(n)

Space Complexity of Queue

Queue Implementation (Array vs Linked List)

Real-World Applications of Queue

Most Asked Queue Interview Questions

🎯 Why Watch This Video?
✔ Easy explanation of Big O Notation
✔ Important for Coding Interviews & Exams
✔ Useful for C, C++, Java, Python learners
✔ Beginner-friendly & exam-oriented

📌 Who Should Watch?

DSA Beginners

Computer Science Students

Coding Interview Aspirants

Competitive Programmers

📈 Master DSA Concepts Step-by-Step!

👍 Like | 💬 Comment | 🔔 Subscribe for more Data Structures & Algorithms content


🔖 Tags:
time complexity of queue
space complexity of queue
queue data structure
queue operations time complexity
big o notation queue
queue using array
queue using linked list
circular queue time complexity
queue interview questions
dsa queue tutorial
time and space complexity of queue,
time and space complexity problems,
time and space complexity python,
time and space complexity in ds,
time and space complexity of algorithm,
time and space complexity data structure,
calculating time and space complexity,
time and space complexity examples,
time and space complexity of dfs,
time and space complexity of an algorithm,
time and space complexity in c,
time and space complexity in c++,
finding time complexity and space complexity,
data structures time and space complexity,
data structure time and space complexity,
time and space complexity in dsa,
time and space complexity explained,
calculate space and time complexity,
space and time complexity in dsa,
time and space complexity of algorithms,
space and time complexity dsa,
time and space complexity algorithm,
calculate time and space complexity,
how to find time and space complexity of algorithms


🔖 Hashtags:

#QueueDataStructure
#TimeComplexity
#SpaceComplexity
#BigONotation
#DSA
#CodingInterview
#LearnDSA
#Programming
#ComputerScience
🔥 Time & Space Complexity of Queue | Queue Data Structure | Big-O Explained
Load More... Subscribe

TCP DSA

75
150
351

TCP HLD

50
101

Recent Posts

  • CAP THEOREM
  • TCP DSA 351
  • TCP HLD 101
  • TCP HLD 50
  • TCP DSA-150

    Recent Comments

    1. Odell Volner on C program to print multiplication table of a given number
    2. Crista Diegidio on C program to print multiplication table of a given number
    3. Daniel Pauling on C program to print multiplication table of a given number
    4. Tonisha Hepp on C program to print multiplication table of a given number
    5. Jorge Layng on C program to print multiplication table of a given number

    Copyright © 2026 Learn to Code and Code to Learn.

    Powered by PressBook Blog WordPress theme