SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Challenges of Distribution
  • Failure Types: Crash vs Byzantine
  • Network Partitions
  • Split Brain Problem
  • Heartbeats
  • Failure Detectors
  • Handling Failures
  • Consistency Models
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Distributed System Fundamentals

Heartbeats

Small regular 'I am alive' signals that let others notice when a machine stops.

⏱ 11 min readBeginnerMust KnowHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A heartbeat is a tiny message that a machine sends again and again to say "I am alive". If the messages stop, the others know something is wrong.

  • In a distributed system you cannot see whether another machine is up. You can only listen for signs of life.
  • The receiver keeps a timer. Each heartbeat resets it. If the timer runs out, the machine is suspected to be dead.
  • The timeout is a trade-off: short means fast detection but more false alarms; long means fewer false alarms but a slow reaction.

02Concept: What is it?

When two machines talk over a network, silence is confusing. If a server does not answer, was it crashed, overloaded, or is the network just slow? From the outside these look the same. So systems use a simple habit: every machine regularly sends a small message, and everyone else watches the clock.

A heartbeat usually carries very little: the sender's name, a counter or timestamp, and sometimes a bit of health information such as load. It is sent at a fixed interval (for example every 1 second). The monitor decides a machine is dead after it has missed several beats in a row, called the timeout.

A heartbeat and a timeout
Worker is healthy
πŸ–₯️Worker
→↓beat, beat, beat
πŸ‘€Monitortimer reset each time
Time since last beatalways below the timeout
Worker crashes
πŸ’₯Workersilent
⇒⇣nothing
πŸ‘€Monitortimer runs out
Time since last beatover the timeout: suspect it
Each arriving beat resets the timer. When beats stop, the timer runs out and the monitor reacts.
🧠A heartbeat never proves death
Missing beats only make a machine suspect. It may be alive but slow, or cut off by the network. A failure detector can be wrong, and good designs expect this.

03Real-Life Example

🍡The Night Watchman and the Radios
A building has 10 night guards, each far from the others. Every minute each guard presses a button on their radio. In the control room a light blinks for each guard. If one light does not blink for three minutes, the control room sends someone to check. A guard in a basement may have weak signal and miss a few blinks without any problem, so the control room waits a little before raising the alarm. Wait too little and the team runs to false alarms. Wait too long and a guard who fell ill lies there for a long time.
Night guards
Heartbeats
Pressing the radio button
Sending a heartbeat message
Every minute
The heartbeat interval
The blinking light in the control room
The monitor receiving a beat
Waiting three minutes before alarm
The failure timeout (missed beats allowed)
A guard in a weak-signal basement
A slow or jittery network
Running to check a healthy guard
A false alarm (false positive)
Sending someone to take over the post
Failover to a replacement
Timeline of a crash
  1. 1
    Beats arrive every 2 seconds
    Monitor timer is reset each time
  2. πŸ’₯
    The worker crashes
    No more beats are sent
  3. 3
    Timer keeps counting
    Missed beat 1, missed beat 2
  4. 4
    Timeout reached
    Monitor marks the worker as suspected dead
  5. 5
    Recovery action
    Elect a new leader, move its work, alert a human

04Why Do We Need It?

πŸ”Notice failures
A crashed machine sends nothing, so silence is the only clue we have.
πŸ”Trigger failover
When the leader goes quiet, the followers start choosing a new one.
🚦Stop sending traffic to dead nodes
Load balancers and registries remove unhealthy instances from rotation.
🧹Free up resources
Locks, leases and work held by a dead machine can be given to someone else.
πŸ“ŠKnow cluster health
A list of who is alive is the starting point for dashboards and alerts.
πŸͺΆCheap to do
A few bytes every second per machine. Almost no cost, a lot of safety.
You cannot ask a dead machine if it is dead. So let every machine keep saying it is alive, and treat silence as a warning.

05Where Do We Use It?

πŸ‘‘Leader election
Followers expect heartbeats from the leader. When they stop, an election starts (Raft does exactly this).
πŸ—‚οΈService registries
Services send heartbeats to Consul or Eureka. No beat means the instance is removed.
βš–οΈLoad balancer health checks
The load balancer pings each server and stops sending traffic to those that do not answer.
🐘Hadoop HDFS
DataNodes send heartbeats to the NameNode. A silent node has its blocks copied elsewhere.
☸️Kubernetes
Nodes report to the control plane, and liveness and readiness probes check each container.
πŸ“‘Databases and queues
Kafka brokers and consumers, Redis Sentinel and replicas all use heartbeats to know who is up.

06Types / Parts / How It Works

Who starts the message?

Push or pull
Push (I am alive)
πŸ–₯️Worker
→↓sends beat
πŸ‘€Monitor

The worker decides when. Silence means trouble.

Pull (are you alive?)
πŸ‘€Monitor
↔ping / reply
πŸ–₯️Worker

The monitor asks. A missing reply means trouble.

Both patterns are common. Push is cheaper for the monitor. Pull lets the monitor check from the outside.

Who watches whom?

PatternHow it worksGood and bad
Central monitorEveryone sends beats to one monitor or leaderSimple. The monitor is a single point of failure and may be overloaded.
Leader to followersThe leader sends beats, followers watch the leader (Raft)Fast failover. Followers only watch one machine.
All to allEvery node pings every other nodeNo single point. Traffic grows with the square of the number of nodes.
Ring or random peersEach node watches a few neighbours, or random ones (gossip)Scales to thousands of nodes. Detection is slower and more complex.

What counts as alive?

CheckWhat it provesWhat it misses
Process is runningThe program has not crashedIt may be stuck or deadlocked
Network ping answersThe machine and network workThe app itself may be broken
Application health endpointThe app can answer a requestA deeper dependency (database) may be down
Deep check (touches the database)The whole path worksHeavy, and one shared dependency failing marks every server dead at once
VisualizerHeartbeat timer: detection speed vs false alarmsCrash the worker at 20 s and watch how long the monitor takes to notice. Then switch to the jittery network and shorten the timeout until false alarms appear.
What happens to the worker?
Truth: is the worker really up?
Heartbeats reaching the monitor (cyan dot = one arrived)
Monitor says: green = trusts it, amber = gave up (correct), red = gave up (wrong, false alarm)
0 s20 s40 s
Heartbeats received
10
network cost
False alarms
0
healthy but declared dead
Crash found after
2 s
detection time
Good balance for this network: no false alarms, and the crash at 20 s was noticed after 2 s. Rule of thumb: detection time is about the timeout (4 s) minus the time since the last beat.

A simplified model with a fixed delay pattern (no random numbers). The monitor gives up when no heartbeat has arrived for the whole timeout. Real detectors (for example phi accrual) use the history of arrival times instead of one fixed number.

07How to Use It / Steps / Implementation

Designing a heartbeat check

  1. 1
    Pick the interval
    How often to send. A common start is 1 to 5 seconds. Faster gives quicker detection but costs more network and CPU, especially with many nodes.
  2. 2
    Allow several misses
    Declare a node dead only after several missed beats (often 3 to 5), not one. A single dropped or delayed message is normal.
  3. 3
    Timeout is longer than the worst normal delay
    Look at your real network delays, including garbage collection pauses and busy CPUs, and set the timeout above them.
  4. 4
    Send beats from a separate path
    Do not let a busy worker thread skip a beat because it is processing a big job. Use a dedicated thread, or a separate port.
  5. 5
    Check the right thing
    A beat from a thread that is alive does not prove the app can serve users. Add a real health check where it matters.
  6. 6
    Decide what happens next
    Remove from the load balancer, start an election, or alert. Make the action safe if the node was actually alive.
  7. 7
    Watch the detector itself
    Track false alarms and detection time. If healthy nodes keep getting removed, your timeout is too aggressive.
πŸ’‘Adaptive detectors
Instead of one fixed timeout, systems like Cassandra and Akka use the phi accrual detector. It learns the normal rhythm of beats and gives a suspicion level. A node on a slow link is judged by its own history, not by a number someone guessed.
⚠️Fencing is still needed
A node declared dead may wake up and keep acting as the leader. Combine heartbeats with leases and fencing tokens, so an old leader's writes are rejected.

08Key Terms to Know

TermMeaning in easy words
HeartbeatA small, regular message that says the sender is alive
IntervalHow often a heartbeat is sent
TimeoutHow long the monitor waits without a beat before it suspects failure
Failure detectorThe part of a system that decides which nodes are alive or suspected dead
False positiveA healthy node wrongly declared dead
False negativeA dead node not noticed yet (it is still believed alive)
Liveness probeA check that asks if a process is running and should be restarted if not (Kubernetes)
Readiness probeA check that asks if a process is ready to receive traffic
Phi accrual detectorA detector that outputs a suspicion level learned from past beat timing
LeaseA permission that lasts for a set time and must be renewed, like a heartbeat with authority
Fencing tokenAn increasing number that lets storage reject writes from an old, wrongly trusted leader

09Pros, Cons and Trade-offs

βœ… Pros
  • Very simple idea and easy to build
  • Tiny network cost
  • Works for any kind of machine or service
  • Detects crashes without any guessing about the cause
  • Foundation for failover, election and load balancing
⚠️ Cons
  • Cannot tell a crash from a slow network
  • A wrong timeout causes false alarms or slow detection
  • A heartbeat thread can be alive while the app is stuck
  • All-to-all beats do not scale
  • A false alarm can cause two leaders (split brain)

Trade-offs

ChoiceWe gainWe lose
Short intervalFaster detectionMore traffic and CPU, and more chances for jitter to look like failure
Long intervalCheap and quietSlow to notice a crash
Few misses allowedQuick failoverMore false alarms during hiccups
Many misses allowedStable, few false alarmsUsers wait longer during a real failure
Fixed timeoutSimple to explain and debugOne number must fit every network condition
Adaptive detectorFits each link, fewer mistakesMore complex to build and tune

10Common Problems and Mistakes

Common mistakes

  1. Timeout too tight. A garbage collection pause or a busy network makes healthy nodes look dead.
  2. Declaring death after one miss. One lost packet should not remove a server.
  3. Heartbeat from an idle thread. The thread is fine but the real work is deadlocked, so nobody notices.
  4. Deep health checks on shared dependencies. If the database is down, every server fails its check and the load balancer removes them all.
  5. No safe action on false alarm. The "dead" leader is alive and keeps writing, causing a split brain.
  6. All nodes restart together. After an outage everyone sends beats and re-registers at once, creating a flood.

Things to watch

🐒Slow, not dead
A node under heavy load answers late. Removing it adds more load to the others.
πŸ”ŒOne-way network fault
A can hear B, but B cannot hear A. Each side has a different idea of who is alive.
πŸ•°οΈClock changes
Use a monotonic clock for timers, so a clock adjustment does not look like silence.
🧠Split brain
When a partition hides a live leader, a second leader can appear. See the Split Brain Problem.

11Real-World Examples

πŸ›ΆRaft
The leader sends heartbeats to followers. A follower that hears nothing for a random 150 to 300 ms starts an election.
🐘HDFS
DataNodes send a heartbeat to the NameNode every 3 seconds by default. After about 10 minutes of silence the node is declared dead and its blocks are copied.
☸️Kubernetes
Kubelets report node status, and liveness and readiness probes decide when to restart a container or stop sending it traffic.
πŸ“¨Kafka
Consumers send heartbeats to the group coordinator. If they stop, the group rebalances and gives their partitions to others.
πŸ””Redis Sentinel
Sentinels ping the primary. If enough of them agree it is down, one replica is promoted.
πŸ—‚οΈConsul and Eureka
Services renew their registration. A missed renewal removes them from lookups.
πŸ“Note
Default intervals and timeouts change between products and versions. Check the docs of the tool you use before you rely on a number.
Mini case: a leader that goes quiet
πŸ‘‘Leaderbeats every 150 ms
→↓beats
πŸ§‘β€πŸ€β€πŸ§‘Followerstimer 150-300 ms
⇒⇣silence
πŸ—³οΈElectionnew leader
Leader Watchers Recovery
The followers wait for the timeout, then elect a new leader. A long pause on the old leader can make this happen even if it is alive.

12Related Topics to Read Next

Challenges of Distribution→

Why you cannot see if another machine is up in the first place.

Network Partitions→

A cut network makes healthy nodes look dead.

Split Brain Problem→

What goes wrong when a false alarm creates two leaders.

Leader Election→

The main thing that heartbeats trigger.

Gossip Protocol→

A way to share who is alive without asking everyone.

Service Discovery→

Registries use heartbeats to remove dead instances.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a small regular message that says "I am alive".
  • βœ”Detect: no beat for the timeout (several intervals) means the node is suspected.
  • βœ”Cannot know: crash, slow node and broken network look the same.
  • βœ”Short timeout: fast detection, more false alarms. Long: fewer false alarms, slow reaction.
  • βœ”Patterns: push or pull; central, leader-to-followers, all-to-all, gossip.
  • βœ”Smart: phi accrual learns the normal rhythm of each link.
  • βœ”Danger: a false alarm plus a live old leader can cause split brain. Use leases and fencing.
  • βœ”One line: β€œKeep saying you are alive, and treat silence as a warning, not proof.”
← Previous
Split Brain Problem
Next β†’
Failure Detectors