⚡ TechVani: AI, Technology, Apps, Coding & Digital World
TechVaniAI • Technology • Apps • Coding • Digital World
HomeAI & TechAppsCodingFree AI ToolsStudent TechSecurityAboutContactPrivacy
TECHVANI // LEARN. BUILD. TEST.

Learn the tech. Build the idea.

Clear study notes, tested lab files and practical guides for coding, AI and digital safety.

Explore Latest →
šŸ¤– AI & TechAI news, tools & guides šŸ“± Apps & ToolsUseful apps & websites šŸ’» CodingProgramming & web development šŸŽ“ Student TechStudy & career technology šŸ” Cyber SecuritySafety & awareness

Latest Posts

Circuit Notebook theme

Exam Notes

šŸ“š BTech CSE Exam Notes

Find Semester 1-8 subjects in one place. Choose a semester and open the notes you need. This is a general study guide, not an official syllabus.

Open Exam Notes →🧪 Open Lab Files →

Exam Numericals & Study Series

Practice CPU scheduling and explore OS and DBMS topics in separate, easy-to-follow parts. New topics will appear in the hub as they are published.

Open Numericals Hub →

Start here and stay in touch

New to TechVani? Start with our free AI tools guide for students. It covers which tools to try and what to check before relying on an answer.

For step-by-step videos, visit SiteSudhar on YouTube.

Join TechVani on WhatsApp

Get new AI tools and coding guides in your WhatsApp Updates tab.

Browse Topics

Popular Posts

TechVani

Distributed Algorithms | Semester 8 BTech CSE Core Notes

Semester 8 - Page 1: Distributed Algorithms. 25 numbered topics, highlighted rules, worked cases, answered exam questions, diagrams, comparison tables and three complete Python demos. General common-core guide, not an official syllabus. Confirm exact protocol variants and required proofs with your course outline.

Run each Python block separately: Python 3, standard library only. Finite clock traces and all 45 distinct majority-quorum pairs are checked. These are not a cluster, Raft implementation, real-network failure test or proof of every execution. Fault/timing/membership assumptions govern actual guarantees.

Topic map

  1. Distributed model and local knowledge
  2. Synchrony, asynchrony and partial synchrony
  3. Failure models and channels
  4. Safety, liveness and invariants
  5. Happened-before and causal relation
  6. Lamport scalar clocks
  7. Vector clocks and concurrency
  8. Physical clocks and synchronization limits
  9. Consistent cuts and global snapshots
  10. FIFO, causal and total-order broadcast
  11. Leader election goals and assumptions
  12. Ring-election teaching trace
  13. Bully election and timeout caveats
  14. Centralized mutual exclusion
  15. Permission-based and token mutual exclusion
  16. Deadlock and distributed waits
  17. Consensus agreement, validity and termination
  18. FLP impossibility and its scope
  19. Quorums and intersection
  20. Raft terms, leaders and replicated logs
  21. Consistency and operation histories
  22. Network partitions and availability tradeoffs
  23. Retries, idempotence and durable recovery
  24. Simulation, testing and failure injection
  25. Exam synthesis and protocol checklist

1. Distributed model and local knowledge

Distributed processes coordinate through messages under stated channel, timing, identity and fault assumptions. No process automatically sees one perfect global state.

Worked example: A node receiving no reply must consider delay, loss and crash under its actual model.
Exam question: Can a local observation establish every other node's current state?
Answer: No. Message delay and failures limit knowledge.

2. Synchrony, asynchrony and partial synchrony

Synchronous models assume known timing bounds; asynchronous models do not. Partial synchrony introduces bounds that hold under stated conditions without assuming perfect timing always.

Worked example: A timeout is useful operational evidence but is not a proof of crash in an unbounded-delay model.
Exam question: Does timeout expiration always distinguish crash from slowness?
Answer: No. Its interpretation depends on assumptions.

3. Failure models and channels

Crash-stop, crash-recovery, omission and Byzantine faults differ. State durable state, message reliability/order and identity/authentication assumptions.

Worked example: A crash-recovering node may restart with old durable data; a Byzantine node can send inconsistent false messages.
Exam question: Can crash-fault reasoning automatically tolerate Byzantine behavior?
Answer: No. The fault model changes the requirements.

4. Safety, liveness and invariants

Safety excludes bad states; liveness promises eventual progress under assumptions. An invariant should hold across every modeled transition.

Worked example: Two simultaneous critical-section entrants violate safety; a request waiting forever violates progress under its promised conditions.
Exam question: Does preserving safety guarantee timely completion?
Answer: No. A safe system may stop making progress.

5. Happened-before and causal relation

Happened-before includes local process order, send-before-corresponding-receive and transitivity. Events with neither causal direction are concurrent.

Worked example: Independent first events at two processes are concurrent until a connecting causal message/order exists.
Exam question: Does wall-clock ordering alone prove causality?
Answer: No. Timestamps are not causal evidence by themselves.

6. Lamport scalar clocks

Increment for each event; receive updates to max(local, received)+1. Happened-before implies increasing Lamport values, but increasing values do not prove happened-before.

Worked example: A message stamped 5 received with local 9 advances the receiver to 10.
Exam question: Does L(a)<L(b) imply a caused b?
Answer: No. The implication is only the other direction.
P1: local1 -> send2
                 | message m1
P2:          receive3 -> local4 -> send5
                                    | m2
P3:                             receive6
Clock values rise on this causal chain. The converse scalar-clock implication does not hold.

Fixed Lamport send/receive trace

clock = {"P1":0,"P2":0,"P3":0}
def local(process):
    clock[process] += 1
    return clock[process]
def receive(process, stamp):
    clock[process] = max(clock[process], stamp)+1
    return clock[process]
trace = [local("P1")]
m1 = local("P1"); trace.append(m1)
trace.append(receive("P2", m1))
trace.append(local("P2"))
m2 = local("P2"); trace.append(m2)
trace.append(receive("P3", m2))
assert trace == [1,2,3,4,5,6]
print("fixed causal trace:", trace)
print("receive stamp5/local9:", max(9,5)+1)
print("Finite trace only; a smaller scalar clock does not establish causality.")

Checked output:

fixed causal trace: [1, 2, 3, 4, 5, 6]
receive stamp5/local9: 10
Finite trace only; a smaller scalar clock does not establish causality.

7. Vector clocks and concurrency

Under the stated fixed-process vector model, increment own component and merge componentwise maxima on receive before incrementing. Component comparison records causal knowledge.

Worked example: [1, 0, 0] and[0, 1, 0] are incomparable; [2, 2, 0] is after [2, 0, 0] under this model.
Exam question: Do vector clocks remove all metadata/scaling concerns?
Answer: No. They grow with modeled process identities and assumptions.

Vector comparison and one merge under a fixed process model

def before(a,b):
    return all(x<=y for x,y in zip(a,b)) and any(x<y for x,y in zip(a,b))
a,b = [1,0,0],[0,1,0]
send = [2,0,0]
received = [max(x,y) for x,y in zip(send,b)]
received[1] += 1
assert not before(a,b) and not before(b,a)
assert received == [2,2,0] and before(send,received)
print("independent a/b concurrent:", not before(a,b) and not before(b,a))
print("receive vector:", received)
print("send before receive:", before(send,received))
print("Fixed equal-length vectors; no dynamic-membership or network protocol implementation.")

Checked output:

independent a/b concurrent: True
receive vector: [2, 2, 0]
send before receive: True
Fixed equal-length vectors; no dynamic-membership or network protocol implementation.

8. Physical clocks and synchronization limits

Physical-clock synchronization has uncertainty and drift; timestamps need bound/context before driving ordering guarantees. Logical clocks solve a different task.

Worked example: Two machines reporting close times can still disagree within clock error; deadlines need actual synchronization assumptions.
Exam question: Can a clock service provide perfect causality automatically?
Answer: No. Clock accuracy and causal order differ.

9. Consistent cuts and global snapshots

A consistent cut cannot include receipt of a message while excluding its send. Snapshot algorithms need channel/process assumptions and in-transit-message handling.

Worked example: A cut with receive(m) but not send(m) is inconsistent, even if local logs look individually plausible.
Exam question: Does reading each node at different times always form one valid global state?
Answer: No. The combined cut can violate causality.

10. FIFO, causal and total-order broadcast

FIFO preserves one sender's order; causal order preserves causal dependencies; total order agrees on delivery sequence under its defined guarantees..

Worked example: A tie-broken Lamport sort in a local array is not by itself a fault-tolerant total-order broadcast protocol.
Exam question: Can sorting timestamps alone guarantee distributed delivery agreement?
Answer: No. Communication, membership and failure handling are needed.

11. Leader election goals and assumptions

Election chooses a coordinator under a membership/identity/failure model. Unique leader safety and eventual leader progress need separate reasoning.

Worked example: Choosing max ID in a static list illustrates an intended selection rule, not a live failure-tolerant election.
Exam question: Does an ID maximum alone implement leader election?
Answer: No. Nodes must coordinate and handle failures/messages.
Election: choose coordinator
Mutual exclusion: at most one entrant
Consensus: agree on valid value
Each needs its own model and protocol.
These tasks are related but not interchangeable.

12. Ring-election teaching trace

A directed reliable ring with unique participating IDs can forward higher candidates and discard lower ones under a specified max-ID variant. Precise message cost depends on the algorithm.

Worked example: For IDs 3, 7, 2, 5 the maximum is 7, but participation and reliable progression must hold for its candidate to return.
Exam question: Can every ring variant share one complexity formula?
Answer: No. Specify the actual algorithm and assumptions.

13. Bully election and timeout caveats

A bully-style election uses higher-ID requests/replies and timeout assumptions to favor the highest live eligible process. Delays/recovery require careful handling.

Worked example: If 5 crashed and 4 is highest live, 4 can become coordinator under supported timing/membership conditions.
Exam question: Does one missed reply prove the highest ID is permanently dead?
Answer: No. Failure suspicion can be wrong.

14. Centralized mutual exclusion

A lock coordinator can serialize grants but introduces availability/recovery concerns. Requests, releases and duplicate handling must be defined.

Worked example: A lost release may block progress; coordinator crash/restart needs a safe ownership recovery rule.
Exam question: Does a central lock eliminate every distributed failure problem?
Answer: No. It relocates coordination and recovery concerns.

15. Permission-based and token mutual exclusion

Permission protocols collect ordered approvals; token protocols rely on controlled token ownership. Message loss, duplicate tokens and membership changes affect guarantees.

Worked example: Two token copies can violate mutual exclusion; a lost sole token can stop progress until safe recovery.
Exam question: Can a token be regenerated casually after any delay?
Answer: No. A delayed existing token could create duplicates.

16. Deadlock and distributed waits

A wait-for cycle may indicate deadlock under the modeled resource/request assumptions. Delayed observations can produce stale or phantom conclusions.

Worked example: P waits for Q while Q waits for P forms a cycle if those current waits and exclusive dependencies actually hold.
Exam question: Does a cycle in stale logs necessarily prove current deadlock?
Answer: No. Verify the model and current state.

17. Consensus agreement, validity and termination

Consensus requires agreement, suitable validity and termination under a named model. A one-round majority preference count is not a complete consensus protocol.

Worked example: Nodes must agree on a valid proposed value despite permitted failures and messages, not merely report local votes.
Exam question: Are election, consensus and mutual exclusion identical?
Answer: No. They solve different coordination tasks.

18. FLP impossibility and its scope

In a fully asynchronous message-passing model with even one possible crash, deterministic consensus cannot guarantee termination in all executions. This does not say no practical system can ever decide.

Worked example: Protocols add timing assumptions/randomization/failure detectors or may preserve safety while waiting during adverse runs.
Exam question: Does FLP forbid consensus in every model?
Answer: No. Its assumptions and guaranteed-termination scope matter.

19. Quorums and intersection

Majority quorums intersect in a fixed membership, supporting particular coordination proofs. Intersection alone does not implement consensus or every consistency property.

Worked example: For five nodes a strict majority is three; every pair of such three-node sets intersects.
Exam question: Does any overlapping set system automatically produce a correct log?
Answer: No. Protocol rules, durable state and membership matter.

All majority quorum pairs in five-node fixed membership

from itertools import combinations
nodes = range(5)
quorums = [set(q) for q in combinations(nodes,3)]
pairs = list(combinations(quorums,2))
assert all(a & b for a,b in pairs)
print("three-node quorums:", len(quorums))
print("distinct pairs checked:", len(pairs))
print("minimum intersection:", min(len(a&b) for a,b in pairs))
print("Set intersection check only, not a consensus/Raft implementation or liveness proof.")

Checked output:

three-node quorums: 10
distinct pairs checked: 45
minimum intersection: 1
Set intersection check only, not a consensus/Raft implementation or liveness proof.

20. Raft terms, leaders and replicated logs

Raft separates leader election, log replication and safety with terms and durable state rules. Study actual election/commit restrictions, not only majority counting.

Worked example: A stale leader/term must not overwrite accepted newer-term behavior; committed-log safety depends on the precise protocol.
Exam question: Is a toy quorum script a Raft implementation?
Answer: No. It verifies only set arithmetic.

21. Consistency and operation histories

Linearizability respects a single-operation order consistent with real-time precedence; eventual convergence is a different guarantee. State the actual operation/model.

Worked example: A read after a completed write has a stronger expectation under linearizability than under a merely eventual replica model.
Exam question: Does eventual consistency mean every read immediately returns latest value?
Answer: No. Its convergence assumptions and timing differ.

22. Network partitions and availability tradeoffs

Partition-tolerance discussions concern lost/delayed communication. CAP-style availability and consistency have formal scopes, not generic marketing meanings.

Worked example: A system may reject some operations to preserve a specified consistency guarantee during a partition.
Exam question: Does CAP mean every system freely picks any two properties forever?
Answer: No. The partition scenario and definitions matter.

23. Retries, idempotence and durable recovery

An uncertain response does not prove an operation failed. Stable request IDs and durable deduplication/reconciliation can prevent repeated effects under scoped assumptions.

Worked example: After a lost payment response, re-read authoritative state before another effect; a local-memory ID set does not survive restart.
Exam question: Does a timeout authorize retrying an irreversible write blindly?
Answer: No. Reconcile outcome and apply an idempotency policy.
Request -> possible effect -> response lost
         -> authoritative reconciliation
         -> scoped duplicate/idempotency rule
A timeout is an uncertain outcome, not proof of no write.

24. Simulation, testing and failure injection

A local trace can verify a rule, not real network fault tolerance. Test permitted runtime failures and invariants with reproducible schedules/limitations.

Worked example: Clock and quorum demos below show exact finite examples, not a cluster or proof of all executions.
Exam question: Does one successful run prove distributed safety for every schedule?
Answer: No. Invariants/model reasoning and broader tests are needed.

25. Exam synthesis and protocol checklist

For each algorithm state nodes/channels/faults/timing, transition rules, invariant, progress assumptions and complexity for that variant. Keep selection/counting separate from live protocol evidence.

Worked example: Explain why Lamport ordering is one-way causal evidence and why quorum intersection is necessary but not sufficient in a consensus design.
Exam question: What makes a strong distributed-algorithms answer?
Answer: A precise model, correct trace, safety/liveness distinction and explicit limits.

Timing and fault assumptions

ModelImportant distinction
SynchronousKnown bounds support timeout reasoning
AsynchronousUnbounded delay prevents perfect crash inference
Crash-stop/recoveryRecovery and durable state differ
ByzantineArbitrary/inconsistent behavior, not only crashes
Fixed/dynamic membershipQuorum/identity assumptions change

Order and coordination

ConceptClaimLimit
Lamport clockCausality implies increasing scalarReverse implication false
Vector clockComponent comparison under modelMetadata/membership assumptions
FIFOPer-sender orderNot all causal/total order
Quorum intersectionAny two strict majorities overlapNot a protocol by itself
RaftNamed replicated-log protocolPrecise durable/election/commit rules needed

Safety versus progress

TaskSafety exampleProgress caveat
Mutual exclusionAt most one entrantToken/coordinator/permission recovery
ElectionNo conflicting eligible leader under specificationTiming/membership/fault assumptions
ConsensusAgreement and suitable validityFLP scope or added assumptions
RetriesAvoid repeated unwanted effectsUnknown outcomes require reconciliation

Revision checklist

Write model, faults, channel order and timing first. Trace scalar/vector rules exactly. Distinguish election, mutual exclusion and consensus; state FLP scope and quorum limits. Do not mistake a local sort/count/simulation for a fault-tolerant distributed protocol.

Resources and sources

Original hub link is preserved. Primary protocol and university sources support causal clocks, impossibility scope and actual consensus study.

Comments