惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
S
Secure Thoughts
月光博客
月光博客
美团技术团队
雷峰网
雷峰网
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Forbes - Security
Forbes - Security
W
WeLiveSecurity
P
Proofpoint News Feed
阮一峰的网络日志
阮一峰的网络日志
爱范儿
爱范儿
G
GRAHAM CLULEY
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
AI
AI
Last Week in AI
Last Week in AI
Google Online Security Blog
Google Online Security Blog
Schneier on Security
Schneier on Security
云风的 BLOG
云风的 BLOG
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Recent Announcements
Recent Announcements
Webroot Blog
Webroot Blog
T
Tor Project blog
Cisco Talos Blog
Cisco Talos Blog
N
News and Events Feed by Topic
罗磊的独立博客
The Register - Security
The Register - Security
Blog — PlanetScale
Blog — PlanetScale
T
Threat Research - Cisco Blogs
博客园 - 【当耐特】
Apple Machine Learning Research
Apple Machine Learning Research
人人都是产品经理
人人都是产品经理
T
The Exploit Database - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
B
Blog
腾讯CDC
Microsoft Azure Blog
Microsoft Azure Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Engineering at Meta
Engineering at Meta
Latest news
Latest news
IT之家
IT之家
D
DataBreaches.Net
博客园 - 司徒正美
N
Netflix TechBlog - Medium
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

Datadog | The Monitor blog

Introducing our open source AI-native SAST Instrument and monitor Boomi integration flows with OpenTelemetry and Datadog Not all index scans are equal: How we cut query latency by over 99% Platform engineering metrics: What to measure and what to ignore Integrate Recorded Future threat intelligence with Datadog Cloud SIEM CI/CD security: threat modeling using a MITRE-style threat matrix CI/CD security: How to secure your GitHub ecosystem Ingress NGINX is EOL: A practical guide for migrating to Kubernetes Gateway API Operating agentic AI with Amazon Bedrock AgentCore and Datadog LLM Observability: Lessons from NTT DATA Introducing the Datadog Code Security MCP Capture and analyze custom heatmaps in Session Replay Understand session replays faster with AI summaries and smart chapters Monitor ClickHouse query performance with Datadog Database Monitoring How we designed empathetic alert sounds for on-call engineers Search and act across Datadog to resolve issues faster with Bits Assistant Measure the business impact of every product change with Datadog Experiments Analyzing round trip query latency Configuring JavaScript caches for better performance Introducing Bits AI Dev Agent for Code Security Datadog achieves ISO 42001 certification for responsible AI Monitor Nutanix clusters, hosts, and VMs with Datadog Monitor Juniper Mist in Datadog A new Host Map for modern infrastructure Annotate traces to improve LLM quality with Datadog LLM Observability What’s new in Cloud SIEM: AI-powered investigations, enhanced threat intelligence, and scalable security operations Explore Kubernetes with native OpenTelemetry data Monitor Oracle Fusion Cloud Applications with Datadog Announcing the Datadog Terraform provider v4.0.0 Scaling Kubernetes workloads on custom metrics How to design cloud environments for AI-powered threat analysis Monitor Aruba Central in Datadog How we centralize and remediate risks with Datadog Case Management Accelerate incident response with Datadog and ServiceNow Monitor your application and network load balancer logs Understanding Karpenter architecture for Kubernetes autoscaling Tools for collecting metrics and logs from Karpenter Monitor Karpenter with Datadog What your product data is actually saying Key metrics for monitoring Karpenter Securing Datadog’s platform in the AI age: The role of observability data Four ways engineering teams use the Datadog MCP Server to power AI agents Approaching your observability migration with the right mindset Meet the new Bits AI SRE: Deeper reasoning, twice as fast Key learnings from the 2026 State of DevSecOps study Use plain English to query your multi-cloud infrastructure in Resource Catalog Simplifying troubleshooting across the user journey with Datadog Synthetic Monitoring Protect your OCI resources with Datadog Cloud Security This Month in Datadog - February 2026 Amazon EC2 security: How misconfigured and public AMIs expand your cloud attack surface Enable end-to-end visibility into your Java apps with a single command Measure and improve mobile app startup performance with Datadog RUM Evaluating our AI Guard application to improve quality and control cost Identify untested code across every level of your codebase Make use of guardrail metrics and stop babysitting your releases Monitor Versa Networks SD-WAN performance in Datadog Improve performance and reliability with APM Recommendations Remediate transitive vulnerabilities faster with Datadog Software Composition Analysis Generate audit-ready vulnerability and compliance reports with Datadog Sheets Monitor Fortinet FortiManager performance in Datadog Improve test coverage across codebases with Datadog Code Coverage Move fast, don’t break things: Consistent testing standards at scale Enrich logs with ServiceNow CMDB context before routing to any SIEM or logging tool Monitor Lustre with Datadog Make faster, better product decisions with Datadog Product Analytics Surface and remediate runtime posture issues with Workload Protection Findings Protect agentic AI applications with Datadog AI Guard How to optimize JavaScript code with CSS Trace Google Pub/Sub workloads in Cloud Run with Datadog Detect human names in logs with ML in Sensitive Data Scanner How we cut our NLQ agent debugging time from hours to minutes with LLM Observability Debug PostgreSQL query latency faster with EXPLAIN ANALYZE in Datadog Database Monitoring Datadog acquires Propolis Unify and correlate frontend and backend data with retention filters Scale compliance across global frameworks with Datadog Cloud Security Monitor Arista VeloCloud SD-WAN performance with Datadog Building reliable dashboard agents with Datadog LLM Observability Simplify log collection and aggregation for MSSPs with Datadog Observability Pipelines Mitigation for Node.js denial-of-service vulnerability affecting Datadog APM Automate flaky test fixes with the Bits AI Dev Agent and Test Optimization How we built an AI SRE agent that investigates like a team of engineers Datadog integrations 2025 recap: Observability for AI, security, and hybrid cloud Design effective executive dashboards with Datadog Implement dbt data quality checks with dbt-expectations Bring faster visibility into AWS Lambda functions with remote instrumentation Troubleshoot faster with the GitLab Source Code integration in Datadog How Cambia Health Solutions saved $30,000 monthly with Cloud Cost Management and the Datadog Resource Catalog Normalize any logs for Cloud SIEM with Datadog's OCSF processor Optimizing Datadog at scale: Cost-efficient observability at Zendesk Detect, diagnose, and resolve network issues easily with CNM Network Health Connect engineering errors to user impact in early-stage products Cilium configuration for Kubernetes operations at scale Designing feedback loops for progressive delivery Ship features faster and safer with Datadog Feature Flags Choosing the right OpenTelemetry Collector distribution Route your monitor alerts with Datadog monitor notification rules Automate Cloud SIEM investigations with Bits AI Security Analyst Cloud threat detection: How to identify risky activity across control and data planes Collecting Kafka performance metrics Monitoring Kafka with Datadog Monitoring Kafka performance metrics
Go memory metrics demystified
Felix Geisendörfer · 2024-01-26 · via Datadog | The Monitor blog

For engineers in charge of supporting Go applications, diagnosing and resolving memory issues such as OOM kills or memory leaks can be a daunting task. Practical and easy-to-understand information about Go memory metrics is hard to come by, so it’s often challenging to reconcile your system metrics—such as process resident set size (RSS)—with the metrics provided by the old runtime.MemStats, with the newer runtime/metrics, or with profiling data.

If you’ve been looking for this kind of information, then you’re in luck. This blog post aspires to be the missing “Go memory metrics primer” that can help you in your troubleshooting efforts. It will cover the following:

  • An overview of Go application memory

  • How to analyze Go memory usage

  • New APM runtime metrics dashboards

An overview of Go application memory

A Go program’s memory usage can be broken down into process memory and kernel memory. Process memory consists of both Go memory (managed by the Go runtime) and non-Go memory (allocated using either cgo or syscalls like mmap, loaded binaries, etc.). The kernel memory breaks down into unreclaimable memory as well as reclaimable memory (e.g., caches) that can be freed up under memory pressure.

In this article we’ll focus specifically on memory that is managed by the Go runtime. However, it’s important to keep the bigger picture of memory usage in mind because the OOM killer in the Linux kernel also takes non-Go memory and kernel memory into consideration.

Memory usage of a Go application

Physical Go memory

Let’s start with an important nugget of information that’s found in the documentation for the runtime/debug package (with credit to Michael Knyszek at Google for pointing this out):

[T]he following expression accurately reflects the value the runtime attempts to maintain as the limit: `runtime.MemStats.Sys − runtime.MemStats.HeapReleased` or in terms of the runtime/metrics package: `/memory/classes/total:bytes − /memory/classes/heap/released:bytes`

What might not be obvious here is that this value is also the runtime’s best estimate for the amount of physical Go memory that it is managing. And though this last statement is a bit imprecise (see the next section to find out why), for now, you should take away the following: If this estimate is close to the process RSS number reported by your OS, then your program’s memory usage is probably dominated by Go memory. This would be good news for you: it would mean that you should be able to use runtime metrics, profiling, and garbage collector (GC) tuning to address any issues you might have. (Note that the topic of GC tuning is generally beyond the scope of this article, but you can consult the Go documentation for in-depth information about this topic.)

When you see a number that is much higher than the RSS reported by the OS, continue to the next section below, “Virtual Go memory.” There might still be hope that you can estimate Go memory usage accurately enough to diagnose the memory issues with your application.

However, if you find that this number is much lower than the RSS reported by the OS, your program is probably using a lot of non-Go memory, typically from using cgo or mmap. You can estimate how much of this memory you need to hunt down by taking your process RSS usage and subtracting the Go memory value from above. That being said, debugging non-Go memory problems is tricky and unfortunately out of scope for this article.

Virtual Go memory

Now let’s talk about the technical imprecision alluded to in the previous section. The physical Go memory estimate above is actually calculated out of virtual memory metrics. For example, let’s say you include these lines in your program:

const GiB = 1024*1024*1024

data := make([]byte,10*GiB)

You might assume that this code will use 10 GiBs of physical memory. However, in reality, it will only increase your virtual memory usage (MemStats.Sys or /memory/classes/total:bytes). Physical memory will only be used when you fill the slice with data.

Unfortunately, in other words, the Go runtime tracks only virtual memory. So from this perspective, you can’t completely trust any runtime metrics when it comes to understanding physical memory usage. But despite this caveat, the lack of any direct reporting on physical memory from the Go runtime is usually not a problem in practice. Unless you’re using some old GC hacks (as opposed to setting a soft memory limit, which is preferable in most situations today), you can assume that essentially all of your Go memory is backed by physical memory.

How to analyze Go memory usage

Now that you can estimate your physical Go memory usage, let’s explore the options for breaking it down. This will allow you to diagnose the memory problems you might be facing.

The runtime/metrics package that was introduced in Go 1.16 makes it easy to get started on this task. We basically only need to stack all /memory/classes/ metrics except heap/released:bytes and total:bytes on a graph.

However, these metrics provide so much detail that it could overwhelm busy practitioners. In the table below we have simplified these metrics into a few categories that are easier to understand. Relying on information in the Go source code, we have also mapped the newer metrics to the older MemStats metrics (if you are still collecting them for legacy reasons).


Note: This list is accurate as of Go 1.21. New memory metrics might be added in the future.


runtime/metricsMemStatsCategory
/memory/classes/heap/objects:bytesHeapAllocHeap Live & Dead Objects
/memory/classes/heap/free:bytesHeapIdle - HeapReleasedHeap Reserve
/memory/classes/heap/unused:bytesHeapInuse - HeapAllocHeap Reserve
/memory/classes/heap/stacks:bytesStackInuseGoroutine Stacks
/memory/classes/os-stacks:bytesStackSys - StackInuseOS Thread Stacks
/memory/classes/metadata/other:bytesGCSysGC Overhead
/memory/classes/metadata/mspan/inuse:bytesMSpanInuseAllocator Overhead
/memory/classes/metadata/mspan/free:bytesMSpanSys - MSpanInuseAllocator Overhead
/memory/classes/metadata/mcache/inuse:bytesMCacheInuseAllocator Overhead
/memory/classes/metadata/mcache/free:bytesMCacheSys - MCacheInuseAllocator Overhead
/memory/classes/other:bytesOtherSysRuntime Overhead
/memory/classes/profiling/buckets:bytesBuckHashSysProfiler Overhead

In the image below, you can see how this might look on a graph for a real-world application. The dotted line on top, representing Go Total, is revealing the Go memory value calculated by using the arithmetic expression in the quoted section above. The lower dotted line, representing Heap Total, is computed by adding the Heap Live & Dead Objects and Heap Reserve values. The sawtooth pattern of the line representing Heap Live & Dead Objects is caused by the GC, but it might look different for you depending on how your metric aggregation windows line up with your GC cycles. For your own applications you’ll probably also see less memory usage in Goroutine Stacks than you do in this example because this particular program happens to use a lot of goroutines.

Graph of Go memory metrics

Now let’s talk about how you can use this breakdown. If you see the Heap Total number trending up under steady load, you probably have a memory leak. If you also see Goroutine Stacks trending up, this might be caused by a goroutine leak. In both cases, continue with profiling. If instead those numbers are merely spiky—but occasionally enough to cause OOMs—you might also be interested in GC tuning (especially by setting a soft memory limit).

Heap profiling

The best way to break down your heap usage is to use Go’s built-in heap profiler. (See a description of the heap profile and other predefined profiles here.) If you’re using go tool pprof, select the inuse_space sample type, as shown below. This will show you the allocations made by your application that were reachable during the most recent GC cycle. (Note also that the official GC guide refers to this inuse_space as “live heap memory.”)

A flame graph showing memory usage

If you’re using Go’s heap profiler for the first time, it might surprise you to discover that it reports less than half of your process’s actual memory usage. The reason for this is that the profiler measures the heap’s low watermark right after a GC cycle (a.k.a. /gc/heap/live:bytes since Go 1.21). The GC uses this value to calculate the heap target, which dictates when the next GC cycle will occur. This calculation depends on GOGC, and the default of 100% allows the heap to double in size before the next GC cycle. For this reason, you should multiply the numbers you see in heap profiles by two to roughly estimate true memory usage.

If you’re dealing with a memory leak, you should try to diff two heap profiles that were taken some time apart. You can do this by using pprof with the -diff_base or -base flag. Or, as a Datadog customer, you can use our comparison view as shown in the following image:

Comparison view of Heap Live Size in different time periods

This comparison view will help reveal the allocation origin of the memory you are leaking. It will also often allow you to identify the goroutines or global data structures that keep the memory alive.

Goroutine profiling

If you see a high amount of memory usage in the Goroutine Stacks metric, the goroutine profile can help you by letting you break down your goroutines by stack trace. Through this functionality, you can also identify oversized goroutine pools and similar issues.

In case of a goroutine leak, you can also diff your goroutine profiles to determine which goroutines are leaking, and why. For example, the comparison view below reveals that about 16 thousand BarHandler.func1 goroutines have leaked because they are stuck on a channel receive operation in main.go on line 70.

Comparison view of goroutine profiles taken at different times

New APM runtime metrics dashboards

To help you with application monitoring and diagnostics, we at Datadog have recently revamped our APM runtime metrics dashboards—including those for Go applications. So if you’re a customer and have Go runtime metrics enabled, you will now get a Go Runtime Metrics built-in dashboard with a memory usage breakdown and many other helpful metrics:

A dashboard of Go Runtime Metrics

Summary

Go’s runtime metrics can give you great visibility into the Go memory usage of your program. Here are the main tips for using these metrics to help you resolve memory issues:

  • Estimate your Go memory usage arithmetically by using the expression “/memory/classes/total:bytes/memory/classes/heap/released:bytes,” and then break it down as described in this article.

  • Estimate your non-Go memory usage (e.g., cgo) arithmetically by using the formula “Process RSS − Go memory,” but be aware that it’s tricky to break this non-Go memory usage down any further.

  • Use profiling to break down your heap memory usage. Multiply the numbers by two in your head to align with process RSS.

  • Don’t forget to also look at kernel memory usage when diagnosing memory issues.

Armed with this knowledge, you should be able to reconcile the numbers reported by your OS with the metrics provided by the runtime.

For more information about Go garbage collection and memory optimization, see the official documentation. And to get started with Datadog, you can sign up for our 14-day free trial.