InkdownInkdown
Start writing

Arpit Bhayani Blogs

336 files·168 subfolders

Shared Workspace

Arpit Bhayani Blogs
001 Ai Topological Sort

022-heartbeats-in-distributed-systems

Shared from "Arpit Bhayani Blogs" on Inkdown

Heartbeats in Distributed Systems

Source: https://arpitbhayani.me/blogs/heartbeats-in-distributed-systems Date: 2025-11-12

In distributed systems, one of the fundamental challenges is knowing whether a node or service is alive and functioning properly. Unlike monolithic applications, where everything runs in a single process, distributed systems span multiple machines, networks, and data centers. This becomes even glaring when the nodes are geographically separated. This is where heartbeat mechanisms come into play.


In distributed systems, one of the fundamental challenges is knowing whether a node or service is alive and functioning properly. Unlike monolithic applications, where everything runs in a single process, distributed systems span multiple machines, networks, and data centers. This becomes even glaring when the nodes are geographically separated. This is where heartbeat mechanisms come into play.

Imagine a cluster of servers working together to process millions of requests per day. If one server silently crashes, how quickly can the system detect this failure and react? How do we distinguish between a truly dead server and one that is just temporarily slow due to network congestion? These questions form the core of why heartbeat mechanisms matter.

001-ai-topological-sort.md
tldr.md
002 Temporal Primer
002-temporal-primer.md
tldr.md
003 Rag Production
003-rag-production.md
tldr.md
004 Structure Of Llm Chat
004-structure-of-llm-chat.md
tldr.md
005 How Llms Work
005-how-llms-work.md
tldr.md
006 Monolith Is Distributed System
006-monolith-is-distributed-system.md
tldr.md
007 Defensive Databases
007-defensive-databases.md
tldr.md
008 Bm25
008-bm25.md
tldr.md
009 Join Algorithms
009-join-algorithms.md
tldr.md
010 Venting At Work
010-venting-at-work.md
tldr.md
011 Half Life
011-half-life.md
tldr.md
012 Multi Paxos
012-multi-paxos.md
tldr.md
013 Mysql Replication Internals
013-mysql-replication-internals.md
tldr.md
014 Bloom Filters
014-bloom-filters.md
tldr.md
015 Clock Sync Nightmare
015-clock-sync-nightmare.md
tldr.md
016 Kafka Partitions
016-kafka-partitions.md
tldr.md
017 Product Quantization
017-product-quantization.md
tldr.md
018 Qkv Matrices
018-qkv-matrices.md
tldr.md
019 Deleted Production
019-deleted-production.md
tldr.md
020 How Llm Inference Works
020-how-llm-inference-works.md
tldr.md
021 Blocking Queues
021-blocking-queues.md
tldr.md
022 Heartbeats In Distributed Systems
022-heartbeats-in-distributed-systems.md
tldr.md
023 Cassandra Writes
023-cassandra-writes.md
tldr.md
024 Redis Replication
024-redis-replication.md
tldr.md
025 Arrogant People At Work
025-arrogant-people-at-work.md
tldr.md
026 Cdn Content Replication
026-cdn-content-replication.md
tldr.md
027 Cant Fix Everything Day One
027-cant-fix-everything-day-one.md
tldr.md
028 Emotions At Work
028-emotions-at-work.md
tldr.md
029 Grpc Http2
029-grpc-http2.md
tldr.md
030 Meetings With No Agenda Are A Waste Of Time
030-meetings-with-no-agenda-are-a-waste-of-time.md
tldr.md
031 Growth Is Not About Doing Everything
031-growth-is-not-about-doing-everything.md
tldr.md
032 Career Longevity Vs Job Hopping
032-career-longevity-vs-job-hopping.md
tldr.md
033 Stay Relevant At Higher Salary Levels
033-stay-relevant-at-higher-salary-levels.md
tldr.md
034 Why Consensus
034-why-consensus.md
tldr.md
035 Database Deadlocks
035-database-deadlocks.md
tldr.md
036 Cpu Cache Locality
036-cpu-cache-locality.md
tldr.md
037 Eventual Consistency
037-eventual-consistency.md
tldr.md
038 Dns Udp Tcp
038-dns-udp-tcp.md
tldr.md
039 Masters
039-masters.md
tldr.md
040 Empathy Makes Great Engineers Unstoppable
040-empathy-makes-great-engineers-unstoppable.md
tldr.md
041 Good Mentors Build People
041-good-mentors-build-people.md
tldr.md
042 Always Have Back Burner Projects
042-always-have-back-burner-projects.md
tldr.md
043 Before You Push Back Know What Youre Standing On
043-before-you-push-back-know-what-youre-standing-on.md
tldr.md
044 Be The One They Can Count On
044-be-the-one-they-can-count-on.md
tldr.md
045 How Much People Bet On You
045-how-much-people-bet-on-you.md
tldr.md
046 How To Get Leadership To Say Yes To Your Project
046-how-to-get-leadership-to-say-yes-to-your-project.md
tldr.md
047 Dont Let Your Best Ideas Die In Silence
047-dont-let-your-best-ideas-die-in-silence.md
tldr.md
048 Be Someone Others Want To Work With
048-be-someone-others-want-to-work-with.md
tldr.md
049 Dont Fall For Xy Problem Ask Right Questions
049-dont-fall-for-xy-problem-ask-right-questions.md
tldr.md
050 Biggest Lie Startups Tell Engineers
050-biggest-lie-startups-tell-engineers.md
tldr.md
051 Promotions Are Proactive Not Reactive
051-promotions-are-proactive-not-reactive.md
tldr.md
052 Not Enough To Be Right Learn To Be Heard
052-not-enough-to-be-right-learn-to-be-heard.md
tldr.md
053 No One Ships Alone
053-no-one-ships-alone.md
tldr.md
054 Not Every Mistake Needs A Correction
054-not-every-mistake-needs-a-correction.md
tldr.md
055 Build Influence At Work
055-build-influence-at-work.md
tldr.md
056 Your Soft Skills Arent Soft At All
056-your-soft-skills-arent-soft-at-all.md
tldr.md
057 Experience Before Forming Opinion
057-experience-before-forming-opinion.md
tldr.md
058 Curiosity And High Bias For Action
058-curiosity-and-high-bias-for-action.md
tldr.md
059 Worklog
059-worklog.md
tldr.md
060 Mistakes And Growth
060-mistakes-and-growth.md
tldr.md
061 Own It Instead Of Sweeping It Aside
061-own-it-instead-of-sweeping-it-aside.md
tldr.md
062 Dont Wait Step Up
062-dont-wait-step-up.md
tldr.md
063 Temporary Fix Is Permanent
063-temporary-fix-is-permanent.md
tldr.md
064 Interview Bias And What Sets You Apart
064-interview-bias-and-what-sets-you-apart.md
tldr.md
065 Saying This Isnt My Problem Is A Problem
065-saying-this-isnt-my-problem-is-a-problem.md
tldr.md
066 Okr
066-okr.md
tldr.md
067 Miscommunication
067-miscommunication.md
tldr.md
068 When In Doubt Code It Out
068-when-in-doubt-code-it-out.md
tldr.md
069 Follow Up Without Annoying People
069-follow-up-without-annoying-people.md
tldr.md
070 Lead Projects That Land
070-lead-projects-that-land.md
tldr.md
071 Abstract Thinking Skill Next Decade
071-abstract-thinking-skill-next-decade.md
tldr.md
072 We Engineers Suck At Task Estimation
072-we-engineers-suck-at-task-estimation.md
tldr.md
073 Shiny Object Syndrome In Tech
073-shiny-object-syndrome-in-tech.md
tldr.md
074 3p
074-3p.md
tldr.md
075 Leverage The Equilibrium
075-leverage-the-equilibrium.md
tldr.md
076 On Demand Container Loading In Aws Lambda
076-on-demand-container-loading-in-aws-lambda.md
tldr.md
077 Sql Has Problems We Can Fix Them Pipe Syntax In Sql
077-sql-has-problems-we-can-fix-them-pipe-syntax-in-sql.md
tldr.md
078 Nanolog A Nanosecond Scale Logging System
078-nanolog-a-nanosecond-scale-logging-system.md
tldr.md
079 Best Resource Is Mythical
079-best-resource-is-mythical.md
tldr.md
080 Wtf The Who To Follow Service At Twitter
080-wtf-the-who-to-follow-service-at-twitter.md
tldr.md
081 Know A Lot
081-know-a-lot.md
tldr.md
082 Out Of Syllabus
082-out-of-syllabus.md
tldr.md
083 Negotiate The Offer
083-negotiate-the-offer.md
tldr.md
084 Never Bad Mouth Your Ex Exployer
084-never-bad-mouth-your-ex-exployer.md
tldr.md
085 Culture Fit
085-culture-fit.md
tldr.md
086 Quantification In Resume
086-quantification-in-resume.md
tldr.md
087 Hiring Is Unfair
087-hiring-is-unfair.md
tldr.md
088 Questions For Interviewers
088-questions-for-interviewers.md
tldr.md
089 Collaboration Communication
089-collaboration-communication.md
tldr.md
090 Out Of Vicious Interview Cycle
090-out-of-vicious-interview-cycle.md
tldr.md
091 Pitch Projects Not Ideas
091-pitch-projects-not-ideas.md
tldr.md
092 Read Design Docs
092-read-design-docs.md
tldr.md
093 Read Rca Docs
093-read-rca-docs.md
tldr.md
094 Start Generalist
094-start-generalist.md
tldr.md
095 Do Not Rely On Summaries
095-do-not-rely-on-summaries.md
tldr.md
096 Structure Your Design Interviews
096-structure-your-design-interviews.md
tldr.md
097 Title Inflation
097-title-inflation.md
tldr.md
098 Find Your Own Project
098-find-your-own-project.md
tldr.md
099 Six Pointers To Crack Coding And Design Interviews
099-six-pointers-to-crack-coding-and-design-interviews.md
tldr.md
100 Keep Yourself Unblocked
100-keep-yourself-unblocked.md
tldr.md
101 Genetic Knapsack
101-genetic-knapsack.md
tldr.md
102 Pseudorandom Number Generation Lfsr
102-pseudorandom-number-generation-lfsr.md
tldr.md
103 How Indexes Work On Partitioned And Sharded Data
103-how-indexes-work-on-partitioned-and-sharded-data.md
tldr.md
104 Some Data Partitioning Strategies For Distributed Data Stores
104-some-data-partitioning-strategies-for-distributed-data-stores.md
tldr.md
105 Data Partitioning
105-data-partitioning.md
tldr.md
106 Leaderless Replication
106-leaderless-replication.md
tldr.md
107 Conflict Resolution
107-conflict-resolution.md
tldr.md
108 Conflict Detection
108-conflict-detection.md
tldr.md
109 Multi Master Replication
109-multi-master-replication.md
tldr.md
110 Monotonic Reads
110-monotonic-reads.md
tldr.md
111 Read Your Write Consistency
111-read-your-write-consistency.md
tldr.md
112 Handling Outages Master Replica
112-handling-outages-master-replica.md
tldr.md
113 Replication Formats
113-replication-formats.md
tldr.md
114 Replication Strategies
114-replication-strategies.md
tldr.md
115 Master Replica Replication
115-master-replica-replication.md
tldr.md
116 Durability
116-durability.md
tldr.md
117 Isolation
117-isolation.md
tldr.md
118 Atomicity
118-atomicity.md
tldr.md
119 Consistency
119-consistency.md
tldr.md
120 Architectures In Distributed Systems
120-architectures-in-distributed-systems.md
tldr.md
121 Mistaken Beliefs Of Distributed Systems
121-mistaken-beliefs-of-distributed-systems.md
tldr.md
122 Fork Bomb
122-fork-bomb.md
tldr.md
123 Chained Operators Python
123-chained-operators-python.md
tldr.md
124 Taxonomy On Sql
124-taxonomy-on-sql.md
tldr.md
125 The Weird Walrus
125-the-weird-walrus.md
tldr.md
126 Fully Persistent Arrays
126-fully-persistent-arrays.md
tldr.md
127 Persistent Data Structures Introduction
127-persistent-data-structures-introduction.md
tldr.md
128 Constant Folding Python
128-constant-folding-python.md
tldr.md
129 String Interning Python
129-string-interning-python.md
tldr.md
130 Recursion Visualizer Python
130-recursion-visualizer-python.md
tldr.md
131 Flajolet Martin
131-flajolet-martin.md
tldr.md
132 2q Cache
132-2q-cache.md
tldr.md
133 Israeli Queues
133-israeli-queues.md
tldr.md
134 1d Terrain
134-1d-terrain.md
tldr.md
135 Jaccard Minhash
135-jaccard-minhash.md
tldr.md
136 Ts Smoothing
136-ts-smoothing.md
tldr.md
137 Lfu
137-lfu.md
tldr.md
138 Morris Counter
138-morris-counter.md
tldr.md
139 Slowsort
139-slowsort.md
tldr.md
140 Bitcask
140-bitcask.md
tldr.md
141 Phi Accrual
141-phi-accrual.md
tldr.md
142 10x Engineer
142-10x-engineer.md
tldr.md
143 Decipher Repeated Key Xor
143-decipher-repeated-key-xor.md
tldr.md
144 Decipher Single Xor
144-decipher-single-xor.md
tldr.md
145 Python Iterable Integers
145-python-iterable-integers.md
tldr.md
146 Inheritance C
146-inheritance-c.md
tldr.md
147 Rum
147-rum.md
tldr.md
148 Consistent Hashing
148-consistent-hashing.md
tldr.md
149 Python Caches Integers
149-python-caches-integers.md
tldr.md
150 Fractional Cascading
150-fractional-cascading.md
tldr.md
151 Copy On Write
151-copy-on-write.md
tldr.md
152 Midpoint Insertion Caching Strategy
152-midpoint-insertion-caching-strategy.md
tldr.md
153 Fsm Python
153-fsm-python.md
tldr.md
154 Bayesian Average
154-bayesian-average.md
tldr.md
155 Sliding Window Ratelimiter
155-sliding-window-ratelimiter.md
tldr.md
156 Idf
156-idf.md
tldr.md
157 Better Programmer
157-better-programmer.md
tldr.md
158 Python Prompts
158-python-prompts.md
tldr.md
159 Rule 30 Cellular Automata
159-rule-30-cellular-automata.md
tldr.md
160 Function Overloading
160-function-overloading.md
tldr.md
161 Isolation Forest
161-isolation-forest.md
tldr.md
162 Image Steganography
162-image-steganography.md
tldr.md
163 Long Integers Python
163-long-integers-python.md
tldr.md
164 I Changed My Python
164-i-changed-my-python.md
tldr.md
165 Benchmark And Compare Pagination Approach In Mongodb
165-benchmark-and-compare-pagination-approach-in-mongodb.md
tldr.md
166 Mongodb Cursor Skip Is Slow
166-mongodb-cursor-skip-is-slow.md
tldr.md
167 Fast And Efficient Pagination In Mongodb
167-fast-and-efficient-pagination-in-mongodb.md
tldr.md
168 Making Http Requests Using Netcat
168-making-http-requests-using-netcat.md
tldr.md

What are Heartbeat Messages

At its most basic level, a heartbeat is a periodic signal sent from one component in a distributed system to another to indicate that the sender is still alive and functioning. Think of it as a simple message that says “I am alive!”

Heartbeat messages are typically small and lightweight, often containing just a timestamp, a sequence number, or an identifier. The key characteristic is that they are sent regularly at fixed intervals, creating a predictable pattern that other components can monitor.

The mechanism works through a simple contract between two parties: the sender and the receiver. The sender commits to broadcasting its heartbeat at regular intervals, say every 2 seconds. The receiver monitors these incoming heartbeats and maintains a record of when the last heartbeat was received. If the receiver does not hear from the sender within an expected timeframe, it can reasonably assume something has gone wrong.

Plain text

When a node crashes, stops responding, or becomes isolated due to network partitions, the heartbeats stop arriving. The monitoring system can then take appropriate action, such as removing the failed node from a load balancer pool, redirecting traffic to healthy nodes, or triggering failover procedures.

Core Components of Heartbeat Systems

The first component is the heartbeat sender. This is the node or service that periodically generates and transmits heartbeat signals. In most implementations, the sender runs on a separate thread or as a background task to avoid interfering with the primary application logic.

The second component is the heartbeat receiver or monitor. This component listens for incoming heartbeats and tracks when each heartbeat was received. The monitor maintains state about all the nodes it is tracking, typically storing the timestamp of the last received heartbeat for each node. When evaluating node health, the monitor compares the current time against the last received heartbeat to determine if a node should be considered failed.

Plain text

The third parameter is the heartbeat interval, which determines how frequently heartbeats are sent. This interval represents a fundamental trade-off in distributed systems. Sending heartbeats too frequently, we waste network bandwidth and CPU cycles. Send them too infrequently, and we will be slow to detect failures. Most systems use intervals ranging from 1 to 10 seconds, depending on the application requirements and network characteristics.

The fourth one is the timeout or failure threshold. This defines how long the monitor will wait without receiving a heartbeat before declaring a node as failed.

Note, the timeout must be carefully chosen to balance two competing concerns: fast failure detection versus tolerance for temporary network delays or processing pauses. A typical rule of thumb is to set the timeout to at least 2 to 3 times the heartbeat interval, allowing for some missed heartbeats before declaring failure.

Deciding Heartbeat Intervals and Timeouts

When a system uses very short intervals, such as sending heartbeats every 500 milliseconds, it can detect failures quickly. However, this comes at a cost. Each heartbeat consumes network bandwidth, and in a large cluster with hundreds or thousands of nodes, the cumulative traffic can become significant. Additionally, very short intervals make the system more sensitive to transient issues like brief network congestion or garbage collection pauses.

Consider a system with 1000 nodes where each node sends heartbeats to a central monitor every 500 milliseconds. This results in 2000 heartbeat messages per second just for health monitoring. In a busy production environment, this overhead can interfere with actual application traffic.

Conversely, if the heartbeat interval is too long, say 30 seconds, the system becomes sluggish in detecting failures. A node could crash, but the system would not notice for 30 seconds or more. During this window, requests might continue to be routed to the failed node, resulting in user-facing errors.

Similarly, the timeout value must also account for network characteristics. In a distributed system spanning multiple data centers, network latency varies. A heartbeat sent from a node in California to a monitor in Virginia might take 80 milliseconds under normal conditions, but could spike to 200 milliseconds during periods of congestion.

Hence, if the timeout is set too aggressively, these transient delays trigger false alarms.

A practical approach is to measure the actual round-trip time in the network and use that as a baseline. Many systems follow the rule that the timeout should be at least 10 times the round-trip time. For example, if the average round-trip time is 10 milliseconds, the timeout should be at least 100 milliseconds to account for variance.

Plain text

Another important consideration is the concept of multiple missed heartbeats before declaring failure. Rather than marking a node as dead after a single missed heartbeat, systems wait until several consecutive heartbeats are missed. This approach reduces false positives caused by packet loss or momentary delays.

For instance, if we send heartbeats every 2 seconds and require 3 missed heartbeats before declaring failure, a node would need to be unresponsive for at least 6 seconds before being marked as failed. This provides a good balance between quick failure detection and tolerance for transient issues.

Push vs Pull Heartbeat Models

Heartbeat mechanisms can be implemented using two different communication models: push and pull.

In a push model, the monitored node actively sends heartbeat messages to the monitoring system at regular intervals. The node takes responsibility for broadcasting its own health status. The monitored service simply runs a background thread that periodically sends a heartbeat message.

Plain text

The push model works well in many scenarios, but it has limitations. If the node itself becomes completely unresponsive or crashes, it obviously cannot send heartbeats. Additionally, in networks with strict firewall rules, the monitored nodes might not be able to initiate outbound connections to the monitoring system.

  • Kubernetes Node Heartbeats
  • Hadoop YARN NodeManagers push heartbeats to the ResourceManager
  • Celery and Airflow workers push heartbeats to the schedule

In a pull model, the monitoring system actively queries the nodes at regular intervals to check their health. Instead of waiting for heartbeats to arrive, the monitor reaches out and asks, “Are you alive?” The monitored services expose a health endpoint that responds to these queries.

Plain text

The pull model provides more control to the monitoring system and can be more reliable in some scenarios. Since the monitor initiates the connection, it works better in environments with asymmetric network configurations. However, it also introduces additional load on the monitor, especially in large clusters where hundreds or thousands of nodes need to be polled regularly.

  • Load balancers actively probe backend servers
  • Prometheus pulls metrics endpoints on each target
  • Redis Sentinel monitors and polls Redis instances with PING

By the way, many real-world systems use a hybrid approach that combines elements of both models. For example, nodes might send heartbeats proactively (push), but the monitoring system also periodically polls critical nodes (pull) as a backup mechanism. This redundancy improves overall reliability.

Failure Detection Algorithms

While basic heartbeat mechanisms are effective, they struggle with the challenge of distinguishing between actual failures and temporary slowdowns. This is where more sophisticated failure detection algorithms come into play.

The simplest failure detection algorithm uses a fixed timeout. If no heartbeat is received within the specified timeout period, the node is declared failed. While easy to implement, this binary approach is inflexible and prone to false positives in networks with variable latency.

Plain text
Phi Accrual Failure Detection

A more sophisticated approach is the phi accrual failure detector, originally developed for the Cassandra database. Instead of providing a binary output (alive or dead), the phi accrual detector calculates a suspicion level on a continuous scale. The higher the suspicion value, the more likely it is that the node has failed.

The phi value is calculated using statistical analysis of historical heartbeat arrival times. The algorithm maintains a sliding window of recent inter-arrival times and uses this data to estimate the probability distribution of when the next heartbeat should arrive. If a heartbeat is late, the phi value increases gradually rather than jumping immediately to a failure state.

The phi value represents the confidence level that a node has failed. For example, a phi value of 1 corresponds to approximately 90% confidence, a phi of 2 corresponds to 99% confidence, and a phi of 3 corresponds to 99.9% confidence.

Gossip Protocols for Heartbeats

As distributed systems grow in size, centralized heartbeat monitoring becomes a bottleneck. A single monitoring node responsible for tracking thousands of servers creates a single point of failure and does not scale well. This is where gossip protocols come into play.

Gossip protocols distribute the responsibility of failure detection across all nodes in the cluster. Instead of reporting to a central authority, each node periodically exchanges heartbeat information with a randomly selected subset of peers. Over time, information about the health of every node spreads throughout the entire cluster, much like gossip spreads in a social network.

The basic gossip algorithm: each node maintains a local membership list containing information about all known nodes in the cluster, including their heartbeat counters. Periodically, the node selects one or more random peers and exchanges its entire membership list with them. When receiving a membership list from a peer, the node merges it with its own list, keeping the most recent information for each node.

Plain text

The gossip protocol eliminates single points of failure since every node participates in failure detection. It scales well because the number of messages each node sends remains constant regardless of cluster size. It is also resilient to node failures since information continues to spread as long as some nodes remain connected.

However, gossip protocols also introduce complexity. Because information spreads gradually, there can be a delay before all nodes learn about a failure. This eventual consistency model means that different nodes might temporarily have different views of the cluster state. The protocol also generates more total network traffic since information is duplicated across many gossip exchanges, though this is usually acceptable since gossip messages are small.

Many production systems use gossip-based failure detection. Cassandra, for example, uses a gossip protocol where each node gossips with up to three other nodes every second. Nodes track both heartbeat generation numbers and version numbers to handle various failure scenarios. The protocol also includes mechanisms to handle network partitions and prevent split-brain scenarios.

Implementation Considerations

One important implementation consideration is the transport protocol.

Should heartbeats use TCP or UDP? TCP provides reliable delivery and guarantees that messages arrive in order, but it also introduces overhead and can be slower due to connection establishment and acknowledgment mechanisms.

UDP is faster and more lightweight, but packets can be lost or arrive out of order. Many systems use UDP for heartbeat messages because occasional packet loss is acceptable, the receiver can tolerate missing a few heartbeats without declaring a node dead.

However, TCP is often preferred when heartbeat messages carry critical state information that must not be lost.

Another consideration is network topology. In systems spanning multiple data centers, network latency and reliability vary significantly between different paths. A heartbeat between two nodes in the same data center might have a round-trip time of 1 millisecond, while a heartbeat crossing continents might take 100 milliseconds or more. Systems should account for these differences, potentially using different timeout values for local versus remote nodes.

Plain text

Another important implementation consideration is to ensure that we do not have blocking operations in the heartbeat processing path. Heartbeat handlers should execute quickly and defer any expensive operations to separate worker threads.

Resource management is also critical. In a system with thousands of nodes, maintaining separate threads or timers for each node can exhaust system resources. We should prefer event-driven architectures or thread pools to efficiently manage concurrent heartbeat processing. Connection pooling would also reduce the overhead of establishing new connections for each heartbeat message.

Network Partitions and Split-brain

A network partition occurs when network connectivity is disrupted, splitting a cluster into two or more isolated groups. Nodes within each partition can communicate with each other but cannot reach nodes in other partitions.

During a partition, nodes on each side will stop receiving heartbeats from nodes on the other side. This creates an ambiguous situation where both sides might believe the other has failed. If not handled carefully, this can lead to split-brain scenarios where both sides continue operating independently, potentially leading to data inconsistency or resource conflicts.

Consider a database cluster with three nodes spread across two data centers. If the network connection between data centers fails, the nodes in each data center will form separate partitions. Without proper safeguards, both partitions might elect their own leader, accept writes, and diverge from each other.

To handle network partitions correctly, systems often use quorum-based approaches. A quorum is the minimum number of nodes that must agree before taking certain actions. For example, a cluster of five nodes might require a quorum of three nodes to elect a leader or accept writes.

During a partition, only the partition containing at least three nodes can continue operating normally. The minority partition recognizes it has lost quorum and stops accepting writes.

Plain text

Real-world Applications

Each node in a Kubernetes cluster runs a kubelet agent that periodically sends node status updates to the API server. By default, kubelets send updates every 10 seconds. If the API server does not receive an update within 40 seconds, it marks the node as NotReady.

Kubernetes also implements liveness and readiness probes at the pod level. A liveness probe checks whether a container is running properly, and if the probe fails repeatedly, Kubernetes restarts the container. A readiness probe determines whether a container is ready to accept traffic, and failing readiness probes cause the pod to be removed from service endpoints.

Plain text

Cassandra, a distributed NoSQL database, uses gossip-based heartbeats to maintain cluster membership. Each Cassandra node gossip with up to three other random nodes every second. The gossip messages include heartbeat generation numbers that increment whenever a node restarts and heartbeat version numbers that increment with each gossip round.

Cassandra uses the phi accrual failure detector to determine when nodes are down. The default phi threshold is 8, meaning a node is considered down when the algorithm is about 99.9999% confident it has failed. This adaptive approach allows Cassandra to work reliably across diverse network environments.

etcd, a distributed key-value store used by Kubernetes, implements heartbeats as part of its Raft consensus protocol. The Raft leader sends heartbeat messages to followers every 100 milliseconds by default. If a follower does not receive a heartbeat within the election timeout (typically 1000 milliseconds), it initiates a new leader election.

Footnotes

Heartbeats are essential to distributed systems. From simple periodic messages to sophisticated adaptive algorithms, heartbeats enable systems to maintain awareness of component health and respond to failures quickly.

The key to effective heartbeat design lies in balancing competing concerns. Fast failure detection requires frequent heartbeats and aggressive timeouts, but this increases network overhead and sensitivity to transient issues. Slow detection reduces resource consumption and false positives but leaves the system vulnerable to longer outages.

As we design distributed systems, consider heartbeat mechanisms early in the architecture process. The choice of heartbeat intervals, timeout values, and failure detection algorithms significantly impacts system behavior under failure conditions.

No matter what we are building, heartbeats remain an essential tool for maintaining reliability.