Home > Article > Backend Development > Using the Heartbeats pattern in Golang
During my adventures in balancing Data & Software Engineer, I always look for something a little different in GoLang to study, understand how it works and apply it to more complex things than some basic traditional courses and articles that I find on the internet. In this short article, I will report and demonstrate how I implemented through Go Routines, the time package using Ticker to simulate the heartbeat ("I'm alive") of the application, in addition to the use of channels, etc.
It is not news to many that it is extremely important to ensure that whoever calls a certain function knows whether the function is taking time, processing, or in lock. That said, several other terminologies have emerged such as Trace, Metrics, connectivity, etc., which have been introduced in monitoring applications that in most cases use agents installed on the application servers that collect metrics and send them to interfaces that visualize all (or almost) the status of your application. Among these tools we have DataDog, NewRelic, Slack, Grafana, Jaeger, etc.
As I study and thinking about creating something quick and simple that addresses some more advanced Go concepts, I created a relatively simple application that makes use of the heartbeats pattern. Whoever is calling me receives the result and, at the same time, information whether I am still active or not. In a more advanced scenario, this may be interesting to customize what is actually an active application in terms of some business particularity, since a simple implementation of a Prometheus solves this case (is the application active? CPU, Memory, open goroutines ), but not with simultaneous and customizable feedback.
In terms of structure, I only created three files within my package with go mod:
This part of the Go code is defining a variable called “dictionary” which is a map that associates rune-type characters with strings.
Each map entry is a key (rune) and a value (string). In the example below, the keys are lowercase letters of the alphabet and the values are names associated with each letter. For example, the letter ‘a’ is associated with the name “airton”, the letter ‘b’ is associated with the name “bruno”, and so on:
package heartbeat var dicionario = map[rune]string{ 'a': "airton", 'b': "bruno", 'c': "carlos", 'd': "daniel", 'e': "eduardo", 'f': "felipe", 'g': "gustavo", }
I explain better below after the complete code each part of the code:
package heartbeat import ( "context" "fmt" "time" ) func ProcessingTask( ctx context.Context, letras chan rune, interval time.Duration, ) (<-chan struct{}, <-chan string) { heartbeats := make(chan struct{}, 1) names := make(chan string) go func() { defer close(heartbeats) defer close(names) beat := time.NewTicker(interval) defer beat.Stop() for letra := range letras { select { case <-ctx.Done(): return case <-beat.C: select { case heartbeats <- struct{}{}: default: } case names <- dicionario[letra]: lether := dicionario[letra] fmt.Printf("Letra: %s \n", lether) time.Sleep(3 * time.Second) // Simula um tempo de espera para vermos o hearbeats } } }() return heartbeats, names }
package heartbeat import ( "context" "fmt" "time" )
Here I have my heartbeat package that will be responsible for implementing a functionality that sends “heartbeats” at a specific time interval, while processing tasks. For this, I need context (Context Management), fmt (for string formatting) and time for time control.
func ProcessingTask ( ctx context.Context, letras chan rune, interval time.Duration, ) (<-chan struct{}, <-chan string) {
This is the definition of the ProcessingTask function that takes a ctx context, a letter channel (a channel that receives Unicode characters) and a time interval as arguments. The function returns two channels: a heartbeats channel that sends an empty struct for each “heartbeat” and a names channel that sends the name of the letter corresponding to each character received.
heartbeats := make(chan struct{}, 1) names := make(chan string)
These two lines create two channels: heartbeats is a buffer channel with capacity of one element and names is an unbuffered channel.
go func() defer close(heartbeats) defer close(names) beat := time.NewTicker(interval) defer beat.Stop() for letra := range letras { select { case <-ctx.Done(): return case <-beat.C: select { case heartbeats <- struct{}{}: default: } case names <- dicionario[letra]: lether := dicionario[letra] fmt.Printf("Letra: %s \n", lether) time.Sleep(3 * time.Second) // Simula um tempo de espera para vermos o hearbeats } } }() return heartbeats, names
This is an anonymous goroutine (or anonymous function that runs in a new thread) that executes the main logic of the ProcessingTask function. It uses a for-range loop to read characters from the letters channel. Inside the loop, use a select to choose an action to be performed from the available options:
Finally, the function returns the heartbeats and names channels.
task_test.go
package heartbeat var dicionario = map[rune]string{ 'a': "airton", 'b': "bruno", 'c': "carlos", 'd': "daniel", 'e': "eduardo", 'f': "felipe", 'g': "gustavo", }
Here I created a Go unit test for the ProcessingTask function that was explained previously. The TestProcessingTask test function creates a context with a timeout of 20 seconds and a channel of Unicode characters (letters). The anonymous goroutine then sends lyrics to the lyrics channel. The ProcessingTask function is then called with the context, Unicode character channel, and a time interval. It returns two channels, a heartbeat channel and a word channel.
The test function then runs an infinite loop with a select, which reads from three channels: the context, the heartbeat channel, and the word channel.
If the context is cancelled, the test loop is terminated. If a heartbeat is received, an “Application Up!” is printed to standard output. If a word is received, the test checks whether the word is present in the letter dictionary. If it is not present, the test fails and an error message is displayed.
Therefore, this unit test tests our ProcessingTask function, which receives characters from one channel, sends letter names to another channel and emits the “heartbeats” while running in a context in which I used a time limit. Ahhh... and it also checks if the names of the letters sent to the word channel are present in the dictionary.
This Go code illustrates some important concepts of the Go language and unit tests:
Full project on my GitHub: https://github.com/AirtonLira/heartbeatsGolang
LinkedIn - Airton Lira Junior
The above is the detailed content of Using the Heartbeats pattern in Golang. For more information, please follow other related articles on the PHP Chinese website!