-
Notifications
You must be signed in to change notification settings - Fork 17.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: runtime: add per-goroutine CPU stats #41554
Comments
A possible solution to showing high level usage of different query paths can be achieved by setting profiling labels on the goroutine: And doing background profiling on the job: Overall Go program usage can be queried from the enclosing container or process stats from the Operating system directly. |
Yes, this is exactly what labels are for. A nice thing about labels is that they let you measure CPU or heap performance across a range of goroutines all cooperating on some shared task. https://golang.org/pkg/runtime/pprof/#Labels Please let us know if you need something that is not addressed by labels. |
Thanks for the suggestion. My main concern with profiling is that there is a non-negligible performance overhead. For example, running a quick workload (95% reads and 5% writes against a CockroachDB SQL table) shows that throughput drops by at least 8% when profiling with a one second interval. I'm hoping that this information can be gathered by the scheduler in a much cheaper way since the question to answer is not "where has this goroutine spent most of its time" but "how much CPU time has this goroutine used". Would this even be feasible? |
Ah, I see. I would think that always collecting CPU statistics would be unreasonably expensive. But it does seem possible to collect them upon request in some way, at least when running on GNU/Linux. Every time a thread switched to a different goroutine it would call I don't know how useful this would be for most programs. In Go it is very easy to start a new goroutine, and it is very easy to ask an existing goroutine to do work on your behalf. That means that it's very easy for goroutine based stats to accidentally become very misleading, for example when the program forgets to collect the stats of some newly created goroutine. That is why runtime/pprof uses the labels mechanism. Perhaps it would also be possible for this mechanism to use the labels mechanism. But then it is hard to see where the data should be stored or how it should be retrieved. |
I'm curious what the internal experience with this mechanism is and how it is used exactly. I suppose some goroutine will be tasked with continuously reading the background profiling stream, but what does it do with it? Is there any code I can look at for how to get to "here's a stream of timestamped label maps" to "this label used X CPU resources"? Do we "just" create a profile every X seconds from the stream? And if that is the idea, how is that different from doing "regular" profiling at a lower sample rate (you might miss a beat every time you restart the sample, but let's assume this is ok)? I feel like I'm missing the bigger picture here. For the record, I did get the background tracing PR linked above working on the go1.16 branch: cockroachdb/cockroach#60795 |
With the The most lightweight variant I have seen is based on https://github.com/golang/go/compare/master...cockroachdb:taskgroup?expand=1 I understand that this basic approach has caveats (if threads get preempted, the duration of the preemption will be counted towards the goroutine's CPU time, and there's probably something about cgo calls too) but it seems workable and cheap enough to at least be able to opt into globally.
The PR above avoids (if I understand you correctly) this by using propagation rules very similar to labels. A small initial set of goroutines (ideally just one, at the top of the "logical task") is explicitly labelled via the task group (identified by, say, an int64) to which the app holds a handle (for querying). The ID is inherited by child goroutines. Statistics are accrued at the level of the task group, not at the individual goroutine level (though goroutine level is possible, just create unique task group IDs). I recall that the Go team is averse to giving users goroutine-local storage by accident, which this approach would not (there would not need to be a way to retrieve the current task group from a goroutine) - given the task group ID, one can ask for its stats. But one can not ask a goroutine about its task group ID.
I agree that getting labels and either of the new mechanisms proposed to play together would be nice, but it doesn't seem straightforward. You could assign to each label pair ( One difficulty is that we lose the simple identification of a task group with a memory address which we had before, because two maps with identical contents identify the same task group. On the plus side, any labelled approach would avoid the clobbering of counters that could naively result if libraries did their own grouping (similar to how one should not call You mention above that
but profiler labels are not used for heap profiles yet, and I think it's because of a somewhat similar problem - a goroutine's allocations in general outlive the goroutine, so the current mechanism (where the labels hang off the |
The implementation using nanotime() is in fact ready already here: cockroachdb@b089033
Done here: cockroachdb@9020a4b
One elephant in the room is that looking up labels and traversing a Go map in the allocation hot path is a performance killer.
This is the other elephant in the room: partitioning the heap allocator by profiler labels would run amok of the small heap optimization. (plus, it would be CPU-expensive to group the profiling data by labels) |
In case it wasn't clear from the latest comments from @tbg and myself: we believe that doing things at the granularity of goroutines is too fine grained, and raises painful questions about where to accumulate the metrics when goroutines terminate. While @tbg is trying to salvage pprof labels as the entity that defines a grouping of goroutines, I am promoting a separate "task group" abstraction which yields a simpler implementation and a lower run-time overhead. I don't know which one is going to win yet—we need to run further experiments—but in any case we don't want a solution that does stats per individual goroutines. |
@knz I really like the feature in https://github.com/cockroachdb/go/commits/crdb-fixes. Could you create a pull request to go official? |
thank you for your interest! |
Fixes github.com/golang/issues/41554. This commit introduces a /sched/goroutine/running:nanoseconds metric, defined as the total time spent by a goroutine in the running state. This measurement is useful for systems that would benefit from fine-grained CPU attribution for. An alternative for scheduler-backed CPU attribution would be the use of profiler labels. Given it's common to spawn multiple goroutines for the same task, goroutine-backed statistics can easily become misleading. Profiler labels instead let you measure CPU performance across a set of cooperating goroutines. That said, it comes with overhead that makes it unfeasible to always enable. For high-performance systems that care about fine-grained CPU attribution (databases for e.g. that want to measure total CPU time spent processing each request), profiler labels are too cost-prohibitive, especially given the Go runtime has a much cheaper view of the data needed. It's worth noting that we already export /sched/latencies:seconds to track scheduling latencies, i.e. time spent by a goroutine in the runnable state. This commit does effectively the same, except for the running state. Users are free to use this metric to power histograms or tracking on-CPU time across a set of goroutines. Change-Id: Id21ae4fcee0cd5f983604d61dad373098a0966bc
Fixes github.com/golang/issues/41554. This commit introduces a /sched/goroutine/running:nanoseconds metric, defined as the total time spent by a goroutine in the running state. This measurement is useful for systems that would benefit from fine-grained CPU attribution. An alternative for scheduler-backed CPU attribution would be the use of profiler labels. Given it's common to spawn multiple goroutines for the same task, goroutine-backed statistics can easily become misleading. Profiler labels instead let you measure CPU performance across a set of cooperating goroutines. That said, it comes with overhead that makes it unfeasible to always enable. For high-performance systems that care about fine-grained CPU attribution (databases for e.g. that want to measure total CPU time spent processing each request), profiler labels are too cost-prohibitive, especially given the Go runtime has a much cheaper view of the data needed. It's worth noting that we already export /sched/latencies:seconds to track scheduling latencies, i.e. time spent by a goroutine in the runnable state. This commit does effectively the same, except for the running state. Users are free to use this metric to power histograms or tracking on-CPU time across a set of goroutines. Change-Id: Id21ae4fcee0cd5f983604d61dad373098a0966bc
Change https://go.dev/cl/387874 mentions this issue: |
Fixes golang#41554. This commit introduces a /sched/goroutine/running:nanoseconds metric, defined as the total time spent by a goroutine in the running state. This measurement is useful for systems that would benefit from fine-grained CPU attribution. An alternative for scheduler-backed CPU attribution would be the use of profiler labels. Given it's common to spawn multiple goroutines for the same task, goroutine-backed statistics can easily become misleading. Profiler labels instead let you measure CPU performance across a set of cooperating goroutines. That said, it comes with overhead that makes it unfeasible to always enable. For high-performance systems that care about fine-grained CPU attribution (databases for e.g. that want to measure total CPU time spent processing each request), profiler labels are too cost-prohibitive, especially given the Go runtime has a much cheaper view of the data needed. It's worth noting that we already export /sched/latencies:seconds to track scheduling latencies, i.e. time spent by a goroutine in the runnable state (go-review.googlesource.com/c/go/+/308933). This commit does effectively the same, except for the running state. Users are free to use this metric to power histograms or tracking on-CPU time across a set of goroutines. Change-Id: Id21ae4fcee0cd5f983604d61dad373098a0966bc
Fixes golang#41554. This commit introduces a /sched/goroutine/running:nanoseconds metric, defined as the total time spent by a goroutine in the running state. This measurement is useful for systems that would benefit from fine-grained CPU attribution. An alternative to scheduler-backed CPU attribution would be the use of profiler labels. Given it's common to spawn multiple goroutines for the same task, goroutine-backed statistics can easily become misleading. Profiler labels instead let you measure CPU performance across a set of cooperating goroutines. That said, it comes with overhead that makes it unfeasible to always enable. For high-performance systems that care about fine-grained CPU attribution (databases for e.g. that want to measure total CPU time spent processing each request), profiler labels are too cost-prohibitive, especially given the Go runtime has a much cheaper view of the data needed. It's worth noting that we already export /sched/latencies:seconds to track scheduling latencies, i.e. time spent by a goroutine in the runnable state (go-review.googlesource.com/c/go/+/308933). This commit does effectively the same except for the running state. Users are free to use this metric to power histograms or tracking on-CPU time across a set of goroutines. Change-Id: Ie78336a3ddeca0521ae29cce57bc7a5ea67da297
@irfansharif sent https://go.dev/cl/387874 today which adds a FWIW, I don't think this API is a good fit for [1] We also expect some monitoring systems to discover and export all metrics. This metric would be meaningless to export directly, as it would only report on a single reporter goroutine. cc @golang/runtime @mknyszek |
Thanks for the quick turnaround. I'm happy to go the route of ReadGoroutineCPUStats or a more direct GoroutineRunningNanos like API; I only went with runtime/metrics given the flexibility of the API and because direct APIs have commentary faboring the runtime/metrics variants. I would also be happy with the adding just the private grunningnanos() helper for external dependants like CRDB to go:linkname directly against, but I can see why that's unsatisfying in to include in the stdlib. If the nanos was just tracked in
Great point. When documenting that the metric is scoped only to the calling goroutine, I hoped that'd be sufficient for monitoring systems to know and filter out explicitly. |
Fixes golang#41554. This commit introduces a /sched/goroutine/running:nanoseconds metric, defined as the total time spent by a goroutine in the running state. This measurement is useful for systems that would benefit from fine-grained CPU attribution. An alternative to scheduler-backed CPU attribution would be the use of profiler labels. Given it's common to spawn multiple goroutines for the same task, goroutine-backed statistics can easily become misleading. Profiler labels instead let you measure CPU performance across a set of cooperating goroutines. That said, it comes with overhead that makes it unfeasible to always enable. For high-performance systems that care about fine-grained CPU attribution (databases for e.g. that want to measure total CPU time spent processing each request), profiler labels are too cost-prohibitive, especially given the Go runtime has a much cheaper view of the data needed. It's worth noting that we already export /sched/latencies:seconds to track scheduling latencies, i.e. time spent by a goroutine in the runnable state (go-review.googlesource.com/c/go/+/308933). This commit does effectively the same except for the running state. Users are free to use this metric to power histograms or tracking on-CPU time across a set of goroutines. Change-Id: Ie78336a3ddeca0521ae29cce57bc7a5ea67da297
Fixes golang#41554. This commit introduces a /sched/goroutine/running:nanoseconds metric, defined as the total time spent by a goroutine in the running state. This measurement is useful for systems that would benefit from fine-grained CPU attribution. An alternative to scheduler-backed CPU attribution would be the use of profiler labels. Given it's common to spawn multiple goroutines for the same task, goroutine-backed statistics can easily become misleading. Profiler labels instead let you measure CPU performance across a set of cooperating goroutines. That said, it comes with overhead that makes it unfeasible to always enable. For high-performance systems that care about fine-grained CPU attribution (databases for e.g. that want to measure total CPU time spent processing each request), profiler labels are too cost-prohibitive, especially given the Go runtime has a much cheaper view of the data needed. It's worth noting that we already export /sched/latencies:seconds to track scheduling latencies, i.e. time spent by a goroutine in the runnable state (go-review.googlesource.com/c/go/+/308933). This commit does effectively the same except for the running state. Users are free to use this metric to power histograms or tracking on-CPU time across a set of goroutines. Change-Id: Ie78336a3ddeca0521ae29cce57bc7a5ea67da297
Fixes golang#41554. This commit introduces a /sched/goroutine/running:nanoseconds metric, defined as the total time spent by a goroutine in the running state. This measurement is useful for systems that would benefit from fine-grained CPU attribution. An alternative to scheduler-backed CPU attribution would be the use of profiler labels. Given it's common to spawn multiple goroutines for the same task, goroutine-backed statistics can easily become misleading. Profiler labels instead let you measure CPU performance across a set of cooperating goroutines. That said, it comes with overhead that makes it unfeasible to always enable. For high-performance systems that care about fine-grained CPU attribution (databases for e.g. that want to measure total CPU time spent processing each request), profiler labels are too cost-prohibitive, especially given the Go runtime has a much cheaper view of the data needed. It's worth noting that we already export /sched/latencies:seconds to track scheduling latencies, i.e. time spent by a goroutine in the runnable state (go-review.googlesource.com/c/go/+/308933). This commit does effectively the same except for the running state. Users are free to use this metric to power histograms or tracking on-CPU time across a set of goroutines. Change-Id: Ie78336a3ddeca0521ae29cce57bc7a5ea67da297
The report in #36821 reflects bugs in / shortcomings of Go's CPU profiling on Linux as of early 2020. @irfansharif , have you found that it is still inaccurate on Linux as of Go 1.18, or is it possible that the runtime/pprof sampling profiler could give acceptable results for on-CPU time? Some of the earlier comments here pointed to map-based goroutine labels adding unacceptable computation overhead. If those were more efficient, would goroutine labels plus the sampling profiler work well enough? There's also the question from @andy-kimball of granularity, in particular for billing customers for their CPU time. I don't fully understand why sampling isn't an option, even for (repeated) operations that take only a few hundred microseconds each. It seems like the work of repeated operations would show up in over 1000 samples (at 100 Hz) well before it's consumed $0.01 of CPU time (at current cloud prices). Overall it seems to me that the current tools we have are close, so I'm interested in how we can improve them enough to be useful here. |
Fixes golang#41554. This commit introduces a /sched/goroutine/running:nanoseconds metric, defined as the total time spent by a goroutine in the running state. This measurement is useful for systems that would benefit from fine-grained CPU attribution. An alternative to scheduler-backed CPU attribution would be the use of profiler labels. Given it's common to spawn multiple goroutines for the same task, goroutine-backed statistics can easily become misleading. Profiler labels instead let you measure CPU performance across a set of cooperating goroutines. That said, it has two downsides: - performance overhead; for high-performance systems that care about fine-grained CPU attribution (databases for e.g. that want to measure total CPU time spent processing each request), profiler labels are too cost-prohibitive, especially given the Go runtime has a much cheaper and more granular view of the data needed - inaccuracy and imprecision, as evaluated in golang#36821 It's worth noting that we already export /sched/latencies:seconds to track scheduling latencies, i.e. time spent by a goroutine in the runnable state (go-review.googlesource.com/c/go/+/308933). This commit does effectively the same except for the running state on the requesting goroutine. Users are free to use this metric to power histograms or tracking on-CPU time across a set of goroutines. Change-Id: Ie78336a3ddeca0521ae29cce57bc7a5ea67da297
We would like to get to the point where a user can run an Similarly, we'd like to be able to show a list of all recent SQL statements that have been run and show the CPU consumed by each. While some statements may have thousands of iterations and show an accurate number, there's often a "long tail" of other SQL statements that have only a few iterations. Those would often show 0, since we didn't happen to get a "hit". While it's perhaps better than nothing, we're trying to enable a better customer experience than that. |
Collecting a timestamp every time the scheduler starts or stops a goroutine, tracking goroutines' running time to sub-microsecond levels, sounds close to key features of the execution tracer (runtime/trace). That data stream also describes when goroutines interact with each other, which allows tracking which parts of the work each goroutine does are for particular inbound requests. Rather than build up additional ways to see data that's already available via runtime/trace, are there ways to pare down or modify the execution tracer's view to something with lower complexity and overhead? I have guesses (below), but I'm curious for your view on how the execution tracer falls short today for your needs. Is it:
|
@rhysh I am currently having similar thoughts, and I think a low-enough overhead, user-parseable trace (with some way of inserting markers at the user level) sounds like it could potentially resolve this situation, assuming it's OK to stream this data out and analyze it programmatically out-of-band. For this to work, though, the trace format itself has to be more scalable and robust, too. On scalability, the traces come out to be pretty large, and they unfortunately basically need to be read fully into memory. On robustness, you really always need a perfect trace to get any useful information out (or at least, the tools back out if it's not perfect). For instance, partial traces don't exist as a concept because there's no enforcement that, say, a block of really old events actually appears early in the trace, forcing you to always deal with the whole trace (from I'm currently thinking a bit about tracing going forward, and this has been on my mind. No promises of course, but Go's tracing story in general could use some improvements. |
What would it take to get this proposal moved into the Active column of the Proposals board? |
Anyone interested in tracing, I can't recommend highly enough Dick Sites's new book Understanding Software Dynamics. For an intro see his Stanford talk. It seems to me that really good tracing along these lines would help a lot more than scattered per-goroutine CPU stats. |
I agree that really good tracing would help, but for the environments we're hoping to use per-goroutine CPU stats, and the contexts we're hoping to use it under (CPU controllers), we're not running with the kinds of kernel patches (https://github.com/dicksites/KUtrace) Dick's tracing techniques seem to be predicated on. I've not evaluated how the more mainstream kernel tracing techniques (ftrace, strace) or use of bpf probes fare performance wise. I also recently learned about how Go's own GC is able to bound it's CPU use to 25% (https://github.com/golang/proposal/blob/master/design/44167-gc-pacer-redesign.md#a-note-about-cpu-utilization, authored by participants in this thread), which effectively uses a similar idea: by capturing the grunning time for time spent in GC assists. This kind of CPU control is similar to what we could do if per-goroutine CPU stats were exposed by the runtime, it would let us hard-cap a certain tenant on a given machine to some fixed % of CPU (with the usual caveats around how accurate this measure is). |
@irfansharif I think there's an interesting question how much we could learn with a Go-runtime-run version of the tracers (GUTrace, say) and no kernel help. I think quite a lot. The point was inspiration, not direct adoption. The setting where tracing would not help is if you want the program to observe itself and respond, like the pacer does. The tracing I am thinking of has a workflow more like the Go profiler, where you collect the profile/trace and then interact with it outside the program. |
Ack. This is precisely the class of problems I'm hoping to push on with per-goroutine CPU stats (or at least just the grunning time). |
For posterity, running the reproductions from https://github.com/chabbimilind/GoPprofDemo#serial-program:
Still somewhat inaccurate + imprecise (we observe variances across multiple runs) for small total running time (controllable by |
Goroutine stats are useful in serving infrastructure where users are
charged on how much resource (in this case CPU) is used and the program
must measure and accumulate that. Being able to do goroutine CPU stats in
a goroutine-per-request model maps nicely to per-user accounting. Also
when isolation decisions are made--i.e. throttling requests for users who
are doing a lot of high-CPU work. This isn't just about measuring CPU for
debugging. Different examples than Irfan's, but it's really the same thing
-- the program observing itself and making decisions.
P.S. I like the Sites book too.
…On Wed, Jun 22, 2022 at 3:34 PM irfan sharif ***@***.***> wrote:
The setting where tracing would not help is if you want the program to
observe itself and respond, like the pacer does.
Ack. This is precisely the class of problems I'm hoping to push on with
per-goroutine CPU stats (or at least just the grunning time).
—
Reply to this email directly, view it on GitHub
<#41554 (comment)>, or
unsubscribe
<https://github.com/notifications/unsubscribe-auth/AQ2F67ZGQ53PNBLUY3LQB2LVQNTFLANCNFSM4RVY5BXA>
.
You are receiving this because you commented.Message ID:
***@***.***>
|
CockroachDB's latest release (v22.2) builds with a patched Go runtime, using effectively the diff from #51347. In the comments above we talked about the "kind of CPU control [..] we could do if per-goroutine CPU stats were exposed by the runtime" and how "it would let us hard-cap a certain tenant on a given machine to some fixed % of CPU". We did this exact thing for bulky, scan-heavy, CPU work in the system (think backups or range feed catch up scans) where we've found them to be disruptive to foreground traffic due to elevated scheduling latencies. https://www.cockroachlabs.com/blog/rubbing-control-theory/ is a wordy write up of the simple idea: dynamically adjust what % of CPU is used for elastic work by measuring at high frequency what the Go scheduling latency p99 is, and then use per-goroutine CPU time to enforce the prescribed %. It's been effective. @mknyszek: Could we move this further along the proposals board? I believe this issue was also referenced in #57175 (comment) ("There's an issue about measure CPU time on-line"). |
@irfansharif nice article. I like the idea of per-goroutine scheduler stats in general (even if it's a niche use case). A few thoughts.
Sounds like Little's Law?
Why do you need to enforce a prescribed % instead of just deciding if you want more or less elastic work to happen? Specifically, wouldn't it be enough to have a P(ID) controller that outputs a throttle (sleep) value for elastic work based on the error of (actual scheduler latency - desired scheduler latency)? Sorry if I'm missing something mentioned in the article or that's otherwise obvious. |
Enforcing a CPU utilization % for elastic work is the same as introducing tiny sleeps everywhere. Elastic work synchronously acquires CPU tokens before/while processing, tokens that get generated at some prescribed rate. When tokens are unavailable, work is blocked. |
Off topic for this issue, but related to your blog post, @irfansharif : You might be interested in #56060 (comment) . |
RE: https://www.cockroachlabs.com/blog/rubbing-control-theory/, nice! I think this demonstrates an interesting use-case for wanting to ingest metrics produced by the Go runtime on-line. By any chance have you measured whether there's any additional overhead incurred to tracking per-goroutine CPU times for every goroutine?
I don't think we can should move forward with exactly what #51347 does, since I think something like this probably needs a new API, though I'm not sure what that looks like.
Slightly off-topic, but this is exactly how the Go runtime's background scavenger goroutine works. There's a PI controller that controls sleep time to achieve a desired CPU utilization. It seems to work reasonably well. |
Since my colleagues at Datadog have at least two UCs (EXPLAIN ANALYZE and Resource Isolation) for this feature that are not well served by CPU profiling with pprof labels, I decided to give this a shot. It's similar to @asubiotto's original proposal, but with a few differences:
package debug // runtime/debug
// GStats collect information about a single goroutine.
type GStats struct {
// Running is the time this goroutine was in running state. This should usually
// be similar to the CPU time used by the goroutine.
Running time.Duration
// could be extended in the future, e.g. with cumulative scheduler latency
// or time spend in different wait states.
}
// SetGStats enables the tracking of goroutine statistics for the current
// goroutine. It returns the previous setting.
func SetGStats(enabled bool) bool {}
// ReadGStats reads statistics about the calling goroutine into stats. Calling this
// from a goroutine that has not previously called SetGStats(true) may panic.
func ReadGStats(stats *GStats) I haven't checked with @irfansharif, but I suspect this API would be compatible with CRDBs use cases. |
I'm happy to wholly adopt any alternative, sticking this into As for keeping this opt-{in,out}/non-optional, there too I'll happily defer to folks with better intuition about the performance overhead. Some microbenchmarks against
I did want to learn from the Go team what would be a better way to evaluate the overhead. We didn't observe anything at the CRDB-level {micro,benchmarks}. We didn't bother with keeping it opt-{in,out}. |
Thanks @irfansharif. I'll try to reproduce the bench results with a bare metal amd64/linux box tomorrow. I'm okay if we decide the |
If we're reasonably certain that it doesn't make a difference on microbenchmarks, I'm not all that concerned about bigger systems. On the API side, I think it'd be nice to have something less committal than
As long as the metrics are scalars, I expect this to be only slightly less efficient than the struct-based API. One thing that might be interesting also is including a dump of this information in the goroutine profile. |
@irfansharif I just tried on a big AWS linux machine with 128 vCPUs and I still see a significant performance regression on
@mknyszek how do you feel about making this opt-in if the results above are true? I believe these micro benchmarks will not translate to noticable regression for most Go programs, but I'm still a little worried about the numbers. The API you proposed sounds nice as well, I'd be okay with that 👍.
As a new sample type? How would one interpret the resulting profile? For most programs the stack traces in a goroutine profile will be biased towards Off-CPU time, but then the flame graph would be scaled by On-CPU (executing) time? I'd imagine this to lead to confusing results. |
Was there any conclusion in the end? What happened to this? |
Per-process CPU stats can currently be obtained via third-party packages like https://github.com/elastic/gosigar. However, I believe that there exists a need for a certain type of applications to be able to understand CPU usage at a finer granularity.
Example
At a high level in CockroachDB, whenever an application sends a query to the database, we spawn one or more goroutines to handle the request. If more queries are sent to the database, they each get an independent set of goroutines. Currently, we have no way of showing the database operator how much CPU is used per query. This is useful for operators in order to understand which queries are using more CPU and measure that against their expectations in order to do things like cancel a query that's using too many resources (e.g. an accidental overly intensive analytical query). If we had per-goroutine CPU stats, we could implement this by aggregating CPU usage across all goroutines that were spawned for that query.
Fundamentally, I think this is similar to bringing up a task manager when you feel like your computer is slow, figuring out which process on your computer is using more resources than expected, and killing that process.
Proposal
Add a function to the
runtime
package that does something like:Alternatives
From a correctness level, an alternative to offering these stats is to
LockOSThread
the active goroutine for exclusive thread access and then get coarser-grained thread-level cpu usage by callingGetrusage
for the current thread. The performance impact is unclear.Additional notes
Obtaining execution statistics during runtime at a fine-grained goroutine level is essential for an application like a database. I'd like to focus this conversation on CPU usage specifically, but the same idea applies to goroutine memory usage. We'd like to be able to tell how much live memory a single goroutine has allocated to be able to decide whether this goroutine should spill a memory-intensive computation to disk, for example. This is reminiscent of #29696 but at a finer-grained level without a feedback mechanism.
I think that offering per-goroutine stats like this is useful even if it's just from an obervability standpoint. Any application that divides work into independent sets of goroutines and would like to track resource usage of a single group should benefit.
The text was updated successfully, but these errors were encountered: