Skip to content
ImagineWorld

Observability – Getting Visibility into GenAI on K8s

node_idnode-book_kubernetes-for-generative-ai-solutions_chapter-12-observability-getting-visibility-into-genai-on-k8s
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleObservability – Getting Visibility into GenAI on K8s
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Observability – Getting Visibility into GenAI on K8s

Section titled “Chapter 12 — Observability – Getting Visibility into GenAI on K8s”

In this chapter, we will cover key observability concepts for monitoring GenAI applications in Kubernetes (K8s). We’ll dive into why monitoring is critical for optimizing GenAI workloads, examining both system-level metrics and application-specific signals. By integrating tools such as Prometheus for metrics collection and Grafana for visualization, and leveraging the debugging capabilities of LangChain, you’ll learn how to construct a comprehensive monitoring framework that provides real-time and actionable insights.

In this chapter, we’re going to cover the following main topics:

  • Observability key concepts
  • Monitoring tools in K8s
  • Visualization and debugging

Observability is the foundational framework for identifying, investigating, and remediating issues in a system, as shown in Figure 12*.1*. It provides a holistic view of system behavior and performance. Observability is built on three core pillars: logs, metrics, and traces. Logs capture detailed event information, metrics quantify system performance, and traces provide an end-to-end view of request flows. Together, these components enable efficient monitoring and troubleshooting of complex distributed systems. This integration ensures actionable insights for maintaining system reliability and performance.

Figure 12.1 – Observability framework

System logs cover events such as transactions, system errors, and user actions. K8s generates logs at different layers, such as container logs, node logs, and cluster-level logs. You can use the following command to see logs for a Pod:

$ kubectl logs <pod-name>

If the Pod has multiple containers, a specific container log can be observed with the following:

$ kubectl logs <pod-name> -c <container-name>

By default, logs in K8s are ephemeral and are lost when Pods restart. To persist logs, one can use sidecar containers or logging agents that forward logs to a centralized storage backend such as Amazon CloudWatch Logs, Elasticsearch, or Loki.

K8s does not provide cluster-wide logging by default. To implement logging at the cluster level, one can use solutions such as Loki or managed services such as Datadog, Splunk, Amazon CloudWatch, and New Relic.

Standard logs provide great insights into pod-level events and errors; however, they don’t cover a complete trace of an API response. That’s where K8s audit logs come in, offering a more granular view of API interactions for security and compliance purposes. We will cover K8s audit logs in the next section.

K8s provides audit log capabilities to track all API requests made to the K8s API server. This provides a detailed record of actions performed by users, service accounts, and controllers and can help with security, compliance, and troubleshooting.

To enable audit logs, modify the K8s API server configuration by adding the following:

--audit-log-path=/var/log/kubernetes/kube-apiserver-audit.log
--audit-policy-file=/etc/kubernetes/audit-policy.yaml

The following YAML shows a sample audit policy that will log the request metadata without the request body:

apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Metadata

In managed K8s offerings such as Amazon EKS, control plane audit logs can be configured to stream to Amazon CloudWatch Logs. Refer to the EKS documentation at https://docs.aws.amazon.com/eks/latest/userguide/control-plane-logs.html for instructions on how to set up the audit logs.

While logs provide a detailed view of discrete events, such as errors, system activity, and user actions, metrics offer a complementary perspective by capturing continuous performance data over time. In the next section, we shift our focus from event-based insights to performance monitoring using metrics.

Metrics involve time-series data that tracks system performance indicators such as memory usage and latency. In K8s, metrics provide real-time performance data about the cluster, nodes, Pods, and containers. These metrics help with monitoring, scaling, and troubleshooting workloads running inside a K8s cluster.

Metrics in K8s are collected at different layers:

  • Node metrics, such as CPU, memory, disk, and network usage at the node level
  • Pod and container metrics, such as resource consumption of each Pod and container
  • Cluster-level metrics, such as the overall health and performance of the cluster
  • Application-level metrics, which are custom application metrics such as request latency and error rates

In Chapter 6, we covered the key metrics that are critical for application scaling and end user experiences. We covered both conventional metrics, such as CPU and memory usage, and custom metrics, such as queue length and HTTP request rates. Prometheus is a common way of collecting metrics in the K8s environment; we will discuss this in a later section.

Traces provide a visual representation of how a single request flows through a distributed system, tracking its interactions with various services, APIs, databases, and components. Tracing in K8s helps track requests as they propagate through different services, containers, and nodes within a distributed system. Traces provide end-to-end visibility into the lifecycle of a request, allowing developers and operators to understand latency issues, failures, and dependencies in microservices architectures.

In K8s, tracing is crucial because applications often consist of multiple microservices communicating over the network. Unlike logs and metrics, which provide snapshots of system behavior, tracing provides contextual insights into request flows.

OpenTelemetry (OTel) (https://opentelemetry.io/) is a common framework used for collecting traces. Once collected, OTel can export the traces to Zipkin (https://zipkin.io/), Jaeger (https://www.jaegertracing.io/), and AWS X-Ray (https://aws.amazon.com/xray/). We will cover OTel in detail in later sections.

In this section, we explored the fundamentals of observability in K8s and the three core pillars – logs, metrics, and traces. In the next section, we will explore various tools in the K8s landscape to monitor GenAI workloads.

Achieving true observability in K8s requires a holistic approach that integrates logs, metrics, and traces. Each pillar offers unique strengths and is suited for specific use cases. By adopting the best practices for combining logs, metrics, and traces, one can optimize monitoring strategies and achieve better system reliability and resilience, ultimately enhancing the user experience.

The following is a sample stack for observability, as depicted in Figure 12*.2*:

  • Fluentd and Fluent Bit collect logs from Kubernetes nodes, Pods, and applications and forwards them to Amazon CloudWatch/Loki/OpenSearch for storage.
  • OTel collects traces and application-specific metrics, exporting them to Prometheus (for metrics) and Jaeger/AWS X-Ray/Zipkin (for traces).
  • Grafana provides a single interface to visualize logs (from Loki), metrics (from Prometheus), and traces (from AWS X-Ray). Developers and operators use Grafana dashboards to analyze performance, debug issues, and set up alerts based on logs, metrics, and traces.

Figure 12.2 – Observability stack in K8s

We will discuss each of these tools in the following sections.

Fluentd (https://www.fluentd.org/) is a lightweight and scalable log aggregator that is widely used in K8s for collecting, processing, and forwarding logs to various backends. In a K8s cluster, Fluentd is typically deployed as a DaemonSet, ensuring that each node has an agent responsible for collecting logs from all running Pods and containers. Fluentd can gather logs from multiple sources, including container logs from /var/log/containers, K8s API server events, and system logs. It then parses, filters, and routes these logs to destinations such as Elasticsearch, Loki, Splunk, Amazon S3, and cloud-based logging solutions such as Amazon CloudWatch.

Fluentd is highly configurable through a plugin-based architecture. There are 100+ plugins available to support different log formats and backends (https://www.fluentd.org/plugins). It uses a structured logging approach, allowing logs to be processed in JSON format for better searchability and indexing. Fluentd supports log enrichment by attaching K8s metadata, such as the namespace or Pod/container name, before sending logs to a storage system. It also supports log filtering, buffering, and compression, which helps in optimizing resource usage in large-scale K8s environments. In K8s logging pipelines, Fluentd is often used alongside Loki (for efficient log storage) or Elasticsearch (for full-text log searching).

Fluent Bit (https://fluentbit.io/) is a lightweight version of Fluentd, optimized for low-resource environments and edge computing with much smaller memory footprint requirements. The following table provides a high-level comparison of Fluentd and Fluent Bit, highlighting their key differences and typical use cases:

FeaturesFluentdFluent Bit
Resource usageSignificant CPU and memory usageLightweight; minimal CPU and memory usage
ArchitectureWritten in Ruby and CWritten in C
Plugin ecosystemLarge plugin library with more than 1,000 external pluginsOver 100 built-in plugins
Deployment modelDeployed as a K8s DaemonSet or sidecar with multiple pluginsDeployed as a K8s DaemonSet or sidecar with multiple plugins
ScalabilityRequires more resources at scaleVery scalable in environments with constrained resources
Use casesContainers/serversEmbedded Linux/containers/servers

Loki (https://github.com/grafana/loki) is a lightweight, scalable log aggregation system designed for the K8s environment. Unlike traditional log management systems such as Elasticsearch, Loki indexes only metadata (labels) instead of the full log content, making it efficient and cost-effective for large-scale deployments. Loki integrates with Prometheus and Grafana, allowing users to correlate logs with metrics for better troubleshooting and observability.

Loki collects logs from K8s Pods using agents such as Fluentd or Fluent Bit, which run as DaemonSets to forward logs to Loki for storage and querying, as shown in Figure 12*.3*. This enables developers and operators to search logs efficiently using log query language (LogQL) (https://grafana.com/docs/loki/latest/query/), filter logs by namespace, Pod, or container, and visualize them in Grafana.

Figure 12.3 – Fluent Bit/Loki deployment in K8s

OTel is a collection of APIs, SDKs, and tools that you can use to instrument, generate, collect, and export telemetry data (metrics, logs, and traces). It is commonly used for collecting and exporting telemetry data to various backend services, such as Prometheus, Jaeger, Datadog, and AWS X-Ray.

In K8s, OTel enables unified observability by collecting metrics, traces, and logs, which can be collected from Pods, containers, or nodes. It supports multiple backends for data storage and works with auto-instrumentation for programming languages such as Go, Java, Python, and Node.js. Refer to the OTel documentation at https://opentelemetry.io/docs/platforms/kubernetes/operator/automatic/ for a detailed walkthrough of auto-instrumentation.

OTel collectors (https://opentelemetry.io/docs/collector/) act as central agents that receive, process, and export telemetry data. These collectors support all three telemetry signals (metrics, traces, and logs), making it a powerful unified observability solution. OTel exporters (https://opentelemetry.io/docs/languages/go/exporters/) are used to send collected data to backend systems such as Prometheus, Jaeger, and Datadog.

To deploy OTel in K8s, one can start by installing OTel collectors using a Helm chart and configure the collectors to define the receivers, processors, and exporters for telemetry data. Please visit the documentation at https://opentelemetry.io/docs/demo/kubernetes-deployment/ for OTel deployment in K8s. Alternatively, you can use the AWS distribution of the OTel project – AWS Distro for OpenTelemetry (ADOT) (https://aws-otel.github.io/) – for a secure, production-ready, open source distribution with predictable performance. To deploy ADOT on Amazon EKS, install the ADOT-managed add-on and configure collectors to forward observability data to your preferred destinations. Refer to the ADOT documentation at https://aws-otel.github.io/docs/getting-started/adot-eks-add-on for detailed installation instructions.

Prometheus (https://prometheus.io/) is an open source monitoring and alerting tool designed for collecting and querying time-series metrics. It was originally built by SoundCloud (https://soundcloud.com/) in 2012, to address the challenges of dynamic and distributed systems, and later joined the Cloud Native Computing Foundation (CNCF) in 2016 as the second hosted project after K8s. Prometheus collects and stores metrics as time-series data, where each data point is recorded with a timestamp and key-value pairs known as labels. It is widely used in K8s environments to provide real-time insights into system performance and resource utilization. In Chapter 10, we briefly discussed the Prometheus agent and adapters; let’s take a deeper look now.

The following diagram illustrates the high-level architecture of Prometheus and some of the key components in its ecosystem:

Figure 12.4 – Prometheus architecture

The following are the key components of the Prometheus architecture:

  • Prometheus server (https://github.com/prometheus/prometheus): The Prometheus server is a central component that scrapes metrics from configured endpoints, such as nodes, Pods, or services. It stores these metrics in a time-series database, which can be queried using Prometheus Query Language (PromQL). Prometheus performs automatic target discovery in K8s to simplify monitoring in dynamic, containerized environments. Instead of manually specifying the endpoints for monitoring, Prometheus uses K8s APIs to dynamically discover targets such as Pods, Endpoints, and Services. This ensures that as workloads scale or shift within the cluster, Prometheus automatically adjusts to continue monitoring them without requiring configuration changes.
  • Prometheus exporters (https://prometheus.io/docs/instrumenting/exporters/): Prometheus exporters are libraries that expose metrics in a format compatible with Prometheus. Exporters are essential for integrating Prometheus with systems or applications that do not natively expose metrics in the Prometheus format. They act as intermediaries, collecting data from the target system and exposing it on an HTTP endpoint for Prometheus to scrape. In K8s, exporters are widely used to monitor various components of the cluster, including nodes, applications, and external systems. For GenAI workloads, exporters are especially critical for monitoring GPUs, inference latency, and resource utilization. NVIDIA DCGM exporter exposes GPU metrics such as utilization, memory usage, temperature, and power consumption, critical for monitoring GPU workloads. We deployed this add-on on our EKS cluster setup in Chapter 10.
  • Prometheus Alertmanager (https://prometheus.io/docs/alerting/latest/overview/): Prometheus Alertmanager handles alerts generated by Prometheus, sending notifications to different channels such as Slack (https://slack.com/), email, or PagerDuty (https://www.pagerduty.com/). It can be configured for GenAI use cases such as resource saturation alerts or higher inference latency. Prometheus Alertmanager supports deduplication, which consolidates duplicate alerts generated by multiple Prometheus instances to prevent notification flooding, and alert grouping, which groups similar alerts into a single notification for better readability.
  • Prometheus Pushgateway (https://prometheus.io/docs/instrumenting/pushing/): This is a component of the Prometheus ecosystem that lets short-lived jobs push their metrics to Prometheus. This is especially useful for ephemeral workloads, such as short GenAI tasks, that cannot be directly scraped by Prometheus. In K8s environments, the Pushgateway acts as an intermediary, allowing batch jobs, cron jobs, and other transient workloads to publish metrics to a persistent endpoint. Prometheus then scrapes this endpoint at regular intervals.
  • PromQL (https://prometheus.io/docs/prometheus/latest/querying/basics/): PromQL is a powerful and flexible query language used to extract and analyze time-series data stored in the Prometheus ecosystem, such as the Prometheus server itself or tools that rely on Prometheus as a backend, such as Grafana. It allows users to perform computations on metrics, filter and aggregate them based on labels, and derive insights through queries.

Now that we have covered the key components of the Prometheus stack, let’s discuss how to deploy it within the K8s environment.

In K8s, it is recommended to deploy the Prometheus server as a StatefulSet. A StatefulSet is a K8s controller used to manage stateful applications that require stable identities and persistent storage. Unlike Deployments, which treat Pods as interchangeable, StatefulSets assign each Pod a unique, stable hostname and ensure that storage volumes persist across Pod restarts. This ensures consistency and reliability for workloads that rely on maintaining state across restarts or rescheduling. Deploying the Prometheus server as a StatefulSet ensures that it has persistent storage access for metrics, using a PersistentVolumeClaim (PVC).

To streamline the K8s setup, the Prometheus community has developed Helm charts to deploy all essential components, which are available at https://github.com/prometheus-community/helm-charts. In our setup, we will deploy kube-prometheus-stack using the Terraform Helm provider. This Helm chart deploys Prometheus and Grafana instances in our EKS cluster, as shown in Figure 12*.5*. After deployment, we will configure Prometheus to scrape metrics from various components within the cluster, such as the NVIDIA DCGM exporter, Qdrant vector database, Ray Serve deployments, and so on. Prometheus automatically discovers the relevant target endpoints and collects metrics at regular intervals. Using the Grafana web console, we can then visualize and query these metrics, build and import interactive dashboards, and define alerting rules.

Figure 12.5 – Prometheus and Grafana setup in EKS cluster

To get started, download the addons.tf and kube-prometheus.yaml files from the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Gen-AI-Models/tree/main/ch12/. The kube-prometheus-stack Helm chart, along with prometheus-adapter, will be deployed in the monitoring namespace, as shown in the following code snippet:

module "eks_blueprints_addons" {
source = "aws-ia/eks-blueprints-addons/aws"
...
enable_kube_prometheus_stack = true
kube_prometheus_stack = {
namespace = "monitoring"
values = [
templatefile("${path.module}/kube-prometheus.yaml", {
storage_class_type = kubernetes_storage_class.default_gp3.id
})]
...
helm_releases = {
"prometheus-adapter" = {
repository = "https://prometheus-community.github.io/helm-charts"
chart = "prometheus-adapter"
namespace = module.eks_blueprints_addons.kube_prometheus_stack.namespace
...

The Prometheus setup is customized using the kube-prometheus.yaml Helm values file. It does the following things:

  • Prometheus configuration:
    • Configures the scrape interval and evaluation interval to 30 seconds
      • Specifies a scrape timeout of 10 seconds for targets
      • Sets a data retention of 5 hours and provisions 50Gi of PVC of the gp3 storage class
  • Alertmanager configuration:
    • Disables the Alertmanager component in this deployment; you can enable it by setting the alertmanager.enabled value to true
  • Grafana configuration:
    • Deploys Grafana and enables the default monitoring dashboards

Execute the following terraform commands to deploy the kube-prometheus-stack and prometheus-adapter Helm charts in the EKS cluster:

$ terraform init
$ terraform plan
$ terraform apply -auto-approve

Verify the installation using the following kubectl command. The output should confirm that the Prometheus StatefulSet, node exporter DaemonSet, Grafana, kube-state-metrics, prometheus-adapter, and prometheus-operator deployments are in a READY status:

$ kubectl get ds -n monitoring
NAME READY
kube-prometheus-stack-prometheus-node-exporter 6
$ kubectl get deploy -n monitoring
NAME READY
kube-prometheus-stack-grafana 1/1
kube-prometheus-stack-kube-state-metrics 1/1
kube-prometheus-stack-operator 1/1
prometheus-adapter 1/1
$ kubectl get sts -n monitoring
NAME READY
prometheus-kube-prometheus-stack-prometheus 1/1

In larger environments, it is recommended to assign sufficient CPU and memory resources and use appropriate scrape intervals for different metrics to optimize resource usage. For example, for critical metrics such as CPU or memory utilization, it is recommended to use intervals of 10 to 15 seconds, whereas for less critical metrics, this interval could be in minutes.

In this section, we covered how to deploy the Prometheus stack in an EKS cluster. However, to gain deeper insights into GPU performance (critical for AI/ML workloads), we need to enable metric scraping for GPUs. In the next section, we’ll cover integrating NVIDIA’s DCGM exporter with Prometheus by configuring Service monitors.

In Chapter 10, we deployed the NVIDIA DCGM Exporter add-on to gain visibility into GPU utilization metrics. During the setup, we disabled the service monitors that enable Prometheus to scrape the metrics at regular intervals. Prometheus Service Monitors (https://prometheus-operator.dev/docs/developer/getting-started/#using-servicemonitors) and Pod Monitors (https://prometheus-operator.dev/docs/developer/getting-started/#using-podmonitors) are CustomResourceDefinitions (CRDs) that allow the Prometheus Operator to automatically discover and configure monitoring targets within a K8s cluster. By leveraging label selectors on K8s services and Pods, these monitors streamline the process of collecting metrics.

Let’s update the Terraform code to enable the scraping of dcgm-exporter metrics using Service Monitors. Begin by downloading aiml-addons.tf from the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch12/aiml-addons.tf:

resource "helm_release" "dcgm_exporter" {
name = "dcgm-exporter"
...
values = [
<<-EOT
serviceMonitor:
enabled: true

Execute the following terraform commands to update the NVIDIA DCGM exporter Helm chart in the EKS cluster:

$ terraform init
$ terraform plan
$ terraform apply -auto-approve

We can verify the scraping status by launching the Prometheus dashboard and checking the scraping target’s health. By default, the Prometheus service is internal and not exposed outside of the cluster, so let’s use the kubectl port-forward mechanism to connect to it from the local machine. Run the following command to initiate a port-forward connection from local port 9090 to Prometheus service port 9090 in the monitoring namespace:

$ kubectl port-forward svc/kube-prometheus-stack-prometheus -n monitoring 9090:9090
Forwarding from 127.0.0.1:9090 -> 9090
Forwarding from [::1]:9090 -> 9090

Now, launch the http://localhost:9090/targets?search=dcgm-exporter URL in your browser to check the health of the DCGM exporter targets. Figure 12*.6* shows that all three dcgm-exporter endpoints are in the UP state, with each corresponding to a GPU worker node in the cluster:

Figure 12.6 – Prometheus target health status

Next, we can query the dcgm-exporter metrics using PromQL. For example, Figure 12*.7* shows the average GPU utilization across multiple GPUs over the past minute grouped by the K8s Pod, where DCGM_FI_DEV_GPU_UTIL is the metric exposed by dcgm-exporter.

Figure 12.7 – Querying GPU metrics using PromQL

Similarly, we will create additional Service Monitors to collect metrics from both the Ray Serve cluster deployed in Chapter 11 and various e-commerce chatbot application components. You can download the corresponding K8s manifest files from the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/tree/main/ch12/monitoring and apply each file using the kubectl apply -f command to deploy them to the EKS cluster:

$ kubectl apply -f <replace with service monitor file name>

After applying the files, navigate to the Prometheus dashboard and verify the status of the newly discovered scraping targets. You will notice both ray-workers and ray-head Pod targets in the dashboard, as shown in Figure 12*.8*.

Figure 12.8 – Prometheus target health status

In this section, we explored various tools to monitor GenAI applications in K8s, such as Fluentd, Fluent Bit, Loki, OTel, and Prometheus. We also deployed kube-prometheus-stack in the EKS cluster and set up the Service/Pod monitors to collect metrics from dcgm-exporter and other application components in our EKS cluster. In the next section, we will dive into visualization tools such as Grafana to view these metrics.

In this section, we will explore key practices for enhancing the observability of GenAI applications deployed on K8s. We will begin by demonstrating how Grafana can be used to visualize essential metrics such as GPU utilization, system performance, and the status of GenAI applications, to provide real-time operational insights. Additionally, we will dive into debugging strategies for Gen AI workloads by examining tools such as Langfuse (https://github.com/langfuse/langfuse), an open source LLM engineering platform designed to aid in debugging and the analysis of LLM applications.

Grafana (https://grafana.com/) is an open source visualization and analytics platform widely used for monitoring K8s environments. It provides a centralized interface for querying, visualizing, and alerting on metrics collected from various data sources, such as Prometheus, Amazon CloudWatch, and Azure Monitor.

Grafana provides prebuilt and customizable dashboards to monitor K8s components such as API servers, etcd databases, nodes, Pods, and namespaces. These dashboards help visualize metrics such as CPU and memory utilization, network activity, and application-specific metrics. Grafana allows users to configure alerts with notifications sent to channels such as Slack, email, PagerDuty, or Microsoft Teams. Alerts are typically based on threshold conditions, though you can also implement anomaly detection through custom queries or external integrations.

Grafana provides the ability to define roles and permissions using role-based access control (RBAC), allowing fine-grained control over who can view or edit dashboards and alerts. Grafana supports a wide range of community-contributed plugins (https://grafana.com/grafana/plugins/), custom visualization panels (https://grafana.com/grafana/plugins/panel-plugins/), and dashboards (https://grafana.com/grafana/dashboards/), enabling users to extend its functionality and adapt it to specific use cases.

The following lists some Grafana best practices:

  • Ensure Grafana dashboards and settings persist across Pod restarts by using a Persistent Volume (PV) and a PVC. This helps maintain the state even when Grafana Pods are rescheduled.
  • Automate dashboard provisioning using ConfigMaps or infrastructure as code (IaC) tools, such as Terraform, to maintain consistent observability setups across environments.
  • Enable robust authentication mechanisms (https://grafana.com/docs/grafana/latest/setup-grafana/configure-security/configure-authentication/) such as OAuth, SAML, and LDAP, to control user access. Use RBAC to manage user permissions effectively.
  • When exposing the Grafana dashboard outside the cluster, use an Ingress controller with TLS termination to secure network communications.
  • Leverage Grafana’s rich plugin ecosystem to integrate with external data sources and specialized visualizations.
  • Enhance observability by combining metrics, logs, and traces. Integrate Grafana with Loki for centralized K8s logging alongside metrics visualization.
  • Monitor Grafana’s resource usage and performance within the K8s cluster. This includes setting up alerts for abnormal behavior, which helps maintain optimal performance and availability.
  • Use managed Grafana offerings such as Amazon Managed Grafana (https://aws.amazon.com/grafana/), Grafana Cloud (https://grafana.com/products/cloud/), and Azure Managed Grafana (https://azure.microsoft.com/en-us/products/managed-grafana) to offload operational tasks such as scaling, patching, and security management. This enables us to focus on creating dashboards and analyzing data. These services also provide seamless cloud-native integrations, auto-scaling capabilities, and cost efficiencies.

In our setup, we deployed Grafana as part of the kube-prometheus-stack installation earlier in this chapter. Alternatively, Grafana Helm charts can be leveraged to deploy as a standalone option in K8s; refer to https://grafana.com/docs/grafana/latest/setup-grafana/installation/helm/ for step-by-step instructions. By default, the Grafana service is accessible within the cluster unless it is exposed outside via the K8s LoadBalancer service type or an Ingress resource. So, let’s use the kubectl port-forward mechanism to connect to the Grafana console:

$ kubectl port-forward svc/kube-prometheus-stack-grafana -n monitoring 8080:80
Forwarding from 127.0.0.1:8080 -> 80
Forwarding from [::1]:8080 -> 80

Now, open http://localhost:8080/ in your browser to access the Grafana console. When prompted for credentials, note that a default admin user is automatically created during the Helm chart installation. You can retrieve the credentials from the K8s secret named kube-prometheus-stack-grafana in the monitoring namespace by running the following command:

$ kubectl get secret kube-prometheus-stack-grafana -n monitoring -o go-template='{{printf "Username: %s\nPassword: %s\n" (index .data "admin-user" | base64decode) (index .data "admin-password" | base64decode)}}'

Once logged in to the Grafana console, navigate to Connections | Data sources in the left side menu bar to view and manage the connected data sources. You will notice the local Prometheus server is already added to the data sources, as shown in Figure 12*.9*.

Figure 12.9 – Grafana connected data sources

As Grafana has access to Prometheus metrics, let’s start exploring the Grafana dashboards. Navigate to Dashboards in the left side menu bar to view and manage the Grafana dashboards. You will notice a list of pre-existing dashboards that were already created by our kube-prometheus-stack installation, as shown in Figure 12*.10*.

Figure 12.10 – Grafana dashboards list

These Grafana dashboards provide preconfigured monitoring views tailored for various K8s components, such as CoreDNS, API server, Namespace, Pod, Workload, Node, Scheduler, Controller Manager, and kubelet. You can select and explore these dashboards to gain insights into the performance, resource usage, and health of the K8s environments. For example, select the Kubernetes | Compute Resources | Cluster dashboard to view an overview of resource utilization, including CPU, memory, and storage metrics across the entire K8s cluster, helping you monitor and optimize cluster performance, as shown in Figure 12*.11*.

Figure 12.11 – Kubernetes Compute Resources dashboard

In this dashboard, we can see the CPU, memory quota, and usage metrics aggregated by each K8s namespace at the cluster level.

While the default dashboards offer comprehensive insights into core K8s components, you may also need visibility into specialized resources, depending on your workload. Now, let’s take a look at how to visualize GPU metrics using the NVIDIA DCGM exporter dashboard.

Earlier in this chapter, we enabled metrics collection from the NVIDIA DCGM exporter add-on using Prometheus Service Monitor resources. Now, we will visualize these metrics using Grafana dashboards. NVIDIA published a Grafana dashboard at https://grafana.com/grafana/dashboards/12239-nvidia-dcgm-exporter-dashboard/ to monitor GPU utilization metrics.

You can import this dashboard to your Grafana instance using the instructions at https://grafana.com/docs/grafana/latest/dashboards/build-dashboards/import-dashboards/. Once the import is successful, you will be able to visualize the GPU metrics, as shown in Figure 12*.12*.

Figure 12.12 – DCGM exporter Grafana dashboard

This dashboard provides real-time visibility into key GPU performance metrics such as temperature, power usage, clock speeds, and utilization. With this information, you can quickly identify performance bottlenecks, detect potential issues, and optimize resource usage.

In addition to dashboards, we can also define Prometheus alerting rules to monitor GPU health and performance. For example, we can create a Prometheus rule (https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) to trigger alerts based on various conditions such as high and low GPU utilization, elevated GPU temperature, or critical GPU errors. To create these rules, download gpu-rules.yaml from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch12/monitoring/gpu-rules.yaml and run the following command to configure them in our setup:

$ kubectl apply -f gpu-rules.yaml

Once deployed, we can visualize the rules in the Prometheus or Grafana console. In the Grafana console, navigate to Alerting | Alert rules in the left side menu bar to view the status of the alert rules, as shown in Figure 12*.13*.

Figure 12.13 – NVIDIA GPU alert rules in the Grafana console

As shown in Figure 12*.13*, one of the GPU alerting rules is in a Firing state due to low GPU utilization on one of our worker nodes. To investigate further, we can expand the alert rule to view detailed information such as the worker node, GPU identifier, and the associated K8s Pod, as illustrated in Figure 12*.14*.

Figure 12.14 – GPU alert rule details in the Grafana console

While the DCGM dashboard provides deep visibility into GPU performance, it’s also important to monitor the higher-level services that rely on these resources, especially in GenAI workloads. One such example is Ray Serve, which plays a key role in serving models such as Llama 3 in our deployment. Let’s now set up a dedicated Grafana dashboard to monitor the performance and resource usage of Ray Serve components.

In Chapter 11, we deployed a Ray cluster in our EKS cluster and used the Ray Serve framework to expose the Llama 3 model. Earlier in this chapter, we also created Prometheus Service and Pod Monitor resources to gather metrics from both the Ray cluster and Ray Serve deployments. Now, we will create a Ray monitoring dashboard to visualize key metrics such as request throughput, latency, ongoing HTTP connections, and resource utilization. To do this, download the Grafana dashboard JSON file (ray-serve-dashboard.json) from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/tree/main/ch12/dashboards.

Open the Grafana console, navigate to the Dashboards page, and choose the New | Import option. Upload the ray-serve-dashboard.json file from your local filesystem and click the Import button. Once imported, select Ray Serve Dashboard from the dashboards list to view real-time information about your Ray Serve deployments, helping you identify bottlenecks and optimize performance, as shown in Figure 12*.15*.

Figure 12.15 – Ray Serve Grafana dashboard

Just like GPU alerting rules in the previous section, we can also define Prometheus alerting rules to monitor the health and performance of Ray Serve deployments. For example, we can configure a Prometheus rule to trigger alerts based on conditions such as high error rates, increased latency, Ray worker node failures, response latency spikes, or low throughput. To create these rules, download the ray-serve-rules.yaml file from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch12/monitoring/ray-serve-rules.yaml and run the following command to configure them in our setup:

$ kubectl apply -f ray-serve-rules.yaml

Once deployed, we can visualize the rules in the Prometheus or Grafana console. In the Grafana console, navigate to Alerting | Alert rules in the left side menu bar to view the status of the alert rules, as shown in Figure 12*.16*.

Figure 12.16 – Ray Serve alert rules in Grafana

As we have covered the different observability tools for monitoring GenAI workloads in K8s, let’s now explore how to extend these concepts for GenAI frameworks, such as LangChain.

LangChain (https://github.com/langchain-ai/langchain) is a framework for building applications with LLMs, which we covered in Chapter 4. It integrates with various tools to enable observability and debugging.

LangChain provides built-in capabilities to log and trace the execution of chains, agents, and tools. These features allow developers and operators to understand how prompts, responses, and workflows behave during execution. The verbose mode in LangChain enables detailed logs of intermediate steps, such as input prompts, output responses, and tool invocations, by setting verbose=True in chains, agents, or tools.

LangChain can integrate with LangChainTracer to collect execution data, including steps, timing information, errors, and retries. The tracer can be used via LangSmith (https://www.langchain.com/langsmith) or deployed as a self-hosted server in K8s.

The following code snippet defines a custom debugging and observability callback handler for LangChain, which helps track the execution flow of a chain. It logs when a chain starts, when it completes, and the time taken for execution, and handles errors gracefully:

import time
from langchain.callbacks.base import BaseCallbackHandler
from langchain.chains import LLMChain
from langchain_openai import OpenAI
from langchain.prompts import PromptTemplate
class DebugCallbackHandler(BaseCallbackHandler):
def __init__(self):
self.start_time = None
def on_chain_start(self, inputs, **kwargs):
"""Triggered when the chain starts execution."""
self.start_time = time.time()
print("\n[DEBUG] Chain started...")
print(f" Inputs: {inputs}")
def on_chain_end(self, outputs, **kwargs):
"""Triggered when the chain successfully completes execution."""
elapsed_time = time.time() - self.start_time
print(f"\n[DEBUG] Chain finished in {elapsed_time:.2f} seconds")
print(f"Outputs: {outputs}")
def on_chain_error(self, error, **kwargs):
print("\n [ERROR] Chain encountered an error!")
print(f" Error Message: {error}")
debug_handler = DebugCallbackHandler()

The DebugCallbackHandler class extends BaseCallbackHandler, making it compatible with LangChain’s callback system. The constructor initializes a self.start_time variable, which is used to track the execution duration.

The on_chain_error method is called when an error occurs during chain execution. It prints an error message along with details about the encountered exception.

This callback handler is useful for debugging and performance monitoring in LangChain applications by providing real-time logs for execution tracking, timing analysis, and error handling.

While LangChain’s built-in logging and tracing capabilities provide a solid foundation for understanding the internal workings of LLM chains and agents, there are scenarios where more advanced observability tools are needed, especially for production-grade applications. This is where platforms such as LangFuse come into play, offering richer insights, distributed tracing, and powerful dashboards tailored for LLM workflows. Let’s take a closer look at how LangFuse enhances observability for GenAI applications in the next section.

LangFuse (https://langfuse.com/) is an open source observability and monitoring platform tailored for LLM applications. It provides deep insights into the execution of AI workflows by tracking user interactions, prompts, responses, and application performance. LangFuse supports key observability features such as logging, tracing, metrics collection, and visualization, making it invaluable for debugging and optimizing LLM-based applications.

LangFuse benefits from K8s-native capabilities such as scalability, auto-healing, and seamless integration with managed services. LangFuse collects and visualizes critical metrics and traces related to prompts, model latency, response accuracy, and system health. It supports distributed tracing, allowing developers to trace user interactions across multiple components, such as API gateways, vector databases, and LLM endpoints, to diagnose performance bottlenecks or errors.

Key features of LangFuse include the following:

  • It logs detailed information about requests, including the input prompt, LLM-generated responses, and associated metadata such as token usage and model-specific parameters
  • It captures the end-to-end lifecycle of interactions, enabling you to monitor every step in workflows, from user input to database queries and LLM outputs
  • It provides interactive dashboards to visualize system performance, latency trends, error rates, and other key performance indicators (KPIs)
  • It links errors or delays in AI pipelines to specific users, prompts, or workflows for faster debugging and resolution
  • It easily integrates with Prometheus, Grafana, OTel, and other K8s monitoring tools to enhance existing observability stacks

For K8s deployments, LangFuse offers flexibility in deployment configurations, enabling you to run the observability stack alongside your AI workloads. It is compatible with Helm charts, ensuring smooth deployment and configuration in cloud-native environments. Detailed deployment instructions and configurations for K8s and EKS are available in the LangFuse documentation at https://langfuse.com/self-hosting/kubernetes-helm.

In this section, we explored various visualization and debugging tools for monitoring GenAI applications in K8s, including Grafana, LangChain, and LangFuse. We deployed Grafana in our EKS cluster and imported prebuilt dashboards to view the key performance metrics of various components, such as the API server, Ray Serve deployments, and so on. Additionally, LangChain and LangFuse provide advanced debugging and observability features for GenAI workloads, enabling you to trace LLM calls, monitor model outputs, and optimize prompt configurations.

In this chapter, we covered key observability concepts for monitoring GenAI applications in K8s. We understood why monitoring is critical for optimizing GenAI workloads, examining both system-level metrics and application-specific signals. We explored a comprehensive monitoring framework using tools such as Prometheus for metrics collection, Grafana for visualization, and LangFuse and LangChain for debugging.

In K8s, various tools cater to different facets of the observability framework. Prometheus excels at collecting and querying time-series metrics, offering built-in alerting capabilities and seamless integration with K8s. Fluentd and Fluent Bit serve as a unified logging layer, collecting data from diverse sources and routing it to multiple destinations. OpenTelemetry provides a vendor-neutral set of APIs and libraries for generating and processing telemetry data, spanning metrics, logs, and traces.

Grafana provides an intuitive interface to view and analyze metrics, logs, and traces, making it easy to detect anomalies and investigate performance bottlenecks. LangFuse specializes in detailed logging and observability of LLM-based requests, capturing prompts, responses, and metadata to facilitate faster debugging. LangChain offers a framework for orchestrating and experimenting with LLM workflows, helping us better understand and refine prompt engineering, chaining logic, and model responses.

In the next chapter, we will explore how to set up high availability and disaster recovery for GenAI applications on K8s.

Get This Book's PDF Version and Exclusive Extras