How Eureka’s Heartbeat Keeps Microservices Alive: A Deep Dive
This article explores how Eureka’s heartbeat mechanism works in microservice architectures, comparing it to the Tang dynasty tribute system, and details who sends the heartbeat, its interval, the sending process, server handling, and the actions performed after receipt, with code examples and thread‑pool configuration.
The Tang dynasty’s tribute system, where surrounding states regularly reported their allegiance, is likened to the heartbeat mechanism in microservice architectures. In this analogy, each microservice periodically sends a heartbeat to the Eureka server to confirm its liveliness.
Key concepts covered:
Who sends the heartbeat request?
How often is it sent?
How is it sent?
How does the server receive it?
What actions are taken after receipt?
Who Sends the Heartbeat Request
Eureka uses client instances to send heartbeat requests to the Eureka server. The diagram below shows three microservices—order, product, and coupon—registered with the Eureka server, each sending its own heartbeat.
How Often the Heartbeat Is Sent
When the DiscoveryClient initializes, it schedules periodic tasks using a thread pool named heartbeatExecutor . This pool creates a HeartbeatThread that sends heartbeats every 30 seconds after an initial 30‑second delay.
The thread pool has core parameters such as maximumPoolSize , corePoolSize , keepAliveTime , and runnableTaskQueue . The scheduled task starts after a 30‑second delay and then repeats every 30 seconds.
How the Heartbeat Is Sent
The HeartbeatThread implements Runnable and its run method invokes the renew() logic, which ultimately calls:
<code>eurekaTransport.registrationClient.sendHeartBeat(
instanceInfo.getAppName(),
instanceInfo.getId(),
instanceInfo,
null);
</code>This sends a PUT request to a URL such as http://localhost:8080/v2/apps/order/i-000000-1 , delivering the instance information to the server.
How the Server Receives the Heartbeat
The server side is handled by ApplicationsResource , which routes the PUT request to InstanceResource.renewLease() .
<code>ApplicationsResource->ApplicationResource->InstanceResource</code>What Happens After Reception
The core action updates the instance’s lastUpdateTimestamp field, marking the latest heartbeat time:
<code>public void renew() {
lastUpdateTimestamp = System.currentTimeMillis() + duration;
}
</code>The instance information resides in the server’s in‑memory registry (a ConcurrentHashMap ) as a Lease object with a volatile lastUpdateTimestamp . If this timestamp becomes stale, the server triggers a service deregistration.
Sanyou's Java Diary
Passionate about technology, though not great at solving problems; eager to share, never tire of learning!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.