Golang Kafka 101: Extract and Calculate our Consumer Lag
Second part of our series in managing our Golang Kafka consumers with the custom metric that matters the most: consumer lag. Here we will explain and show the code section to calculate and expose our consumer lag from our services

TL;DR
Essentially the code works as a local calculator for the specific consumer instance that is running and its specific partition assigned. We calculate the difference between the highest offset (last message produced) and the current offset of the consumer, the difference is what we call consumer lag or backlog. This info then it is exposed through an endpoint to be accessed dynamically.
Introduction
In this article I will explain technically the different methods and code snippets used to calculate and exposed our consumer lag for our future steps.
- Intro: Managing Golang Kafka Consumer Lag
- Extract and Calculate our Consumer Lag
- Building and Using our Custom HPA
- Deep Dive Into Our Kubernetes Controller
The Problem with the Golang Kafka Consumer
After working more than a couple of years with Golang and its Confluence Kafka package, I can affirm that after all the amazing things it provides and how fast and easy can be to implement; it lacks of one of the essential things that the Java Kafka Consumer provides out of the box, in this case: metrics.
Even though there are several ways to aggregate and export these metrics, you do need to have an extensive knowledge of the package to target the specifics. Which I did my research for my use case and that’s the reason I am sharing it with you. We engineers help each other to make ours life easier.
First Step
As a rule of thumb every time I code, I organize my preliminary models and create the structs. We will have two simple struct that will represent all our consumer lag information.





