Repository navigation
Add per-command CPU time to SLOWLOG - #15907
Conversation
…low commands Slow commands are often blamed on CPU starvation without evidence. For every slowlog-worthy command, record how much of its time it actually ran on-CPU, and log/count commands that were off-CPU for long enough to be slow on that alone, classified as starvation (preempted) or blocked. CPU time is sampled once per event-loop wakeup and once per slow command, so fast commands pay no extra syscall. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mands) Fast commands are too short to be preempted mid-command, so starvation between them never reaches the slowlog. Check each event-loop cycle as a whole: if the cycle reaches slowlog-log-slower-than, sample once more and report it when its off-CPU time alone reaches the threshold, classified as starvation or blocked like slow commands. The cycle uses its own sample from afterSleep(), never moved by commands, so duration, off-CPU time and command count describe the same window. New INFO stats: eventloop_cpu_starvation_events, eventloop_off_cpu_blocked_events. The one-per-second log limit is shared with the per-command line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## unstable #15907 +/- ##
============================================
+ Coverage 77.28% 78.11% +0.83%
============================================
Files 146 156 +10
Lines 87988 95245 +7257
============================================
+ Hits 67998 74404 +6406
- Misses 19990 20841 +851
🚀 New features to boost your workflow:
|
A slow command called from a script or a module (RM_Call) moved the CPU checkpoint before the outer command was logged, so the outer command's window started after it and it was stored as mostly on-CPU. Only top-level commands move the checkpoint now; the off_min bound already keeps each command from being blamed for time outside it. Also note at the cycle check that it isn't reached while nested. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
This change touches performance-sensitive code paths. Adding the |
|
there are quite a few things i don't understand when reading the PR description, maybe it can be improved instead of explaining it to me.
|
…ore AOF flush Move the off-CPU code (sampling, per-command estimate, classification, rate-limited log, cycle check) from server.c into slowlog.c; server.c keeps only the calls. No behavior change. Run the event-loop cycle check before the AOF write/fsync in beforeSleep(), so disk waits are no longer counted as off-CPU time of the cycle. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
i'm not sure this is good, in theory there could be many short voluntary, and one long involuntary or the other way around. the only way to know for sure is if one is 0 and we attribute all the lost time to the other.
i'm not certain what it means? that we'll record slowlog for every command, but won't measure CPU usage for them? and still keep measuring CPU usage for the event loop? |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 6c76665. Configure here.
CE Performance Automation : step 1 of 2 (build) DONE.This comment was automatically generated given a benchmark was triggered.
You can check a comparison in detail via the grafana link |
CE Performance Automation : step 2 of 2 (benchmark) RUNNING...This comment was automatically generated given a benchmark was triggered. Started benchmark suite at 2026-10-14 08:33:08.359556 and took 131.983365 seconds up until now. In total will run 357 benchmarks. |
@fcostaoliveira do we have results ? |
@StavRLevi is this addressed? @oranagra did you mean we should have config about the command duration |
|
Hi, yes, addressed with a hard-coded 10ms minimum rather than a config, Oran's suggestion. On the main thread, a command is measured only when it's inserted into the slowlog and took ≥10ms, and a cycle only when it took ≥ max(slowlog-log-slower-than, 10ms). So a 0 or 1ms threshold doesn't make short commands pay for getrusage. The only per cycle cost left is the single sample at wakeup, and off-cpu-tracking no disables everything. slowlog-max-len 0 disables only the per command check (no entries), not the cycle check.
|
|
Benchmark results for this PR: head
AWS m7i.metal-24xl (x86) and m8g.metal-24xl (ARM). No measurable impact. The x86 leans from the single-run results (HELLO, SET, SETNX) did not hold with more runs; the remaining deltas are within run-to-run range (SETNX x86: 4.2% base, 2.9% head). |
…e.CpuTime The 8th entry field (redis/redis#15907, 8.12 RC3) is the duration minus the provable off-CPU time, distinguishing a command that ran slowly from one starved of CPU. Parsed positionally past the client address/name and argument count, so every historical entry length still parses: null when the server did not send the field, zero (per the server) when it was not measured. Gated SER011 with the rest of the 8.12 surface.
…011) (#3343) * Redis 8.12 BITRANGEINTARRAY (bit enumeration): IDatabase.StringBitPositions (#3315) * Plan: StringBitPositions (BITRANGEINTARRAY, Redis 8.12) * Plan: record the behaviour observed against a local unstable build * Redis 8.12 BITRANGEINTARRAY: IDatabase.StringBitPositions Enumerates the set (or, with bit: false, the clear) bit positions in a byte or bit range of a string or native bitmap, ascending, with an optional LIMIT; the sibling of StringBitPosition (BITPOS). Reuses ResultProcessor.Int64Array; the argument tail fits Message.Create, with the default BYTE omitted as BITCOUNT/BITPOS do. Negative limit throws client-side. Gated [Experimental(Experiments.Server_8_12)] (SER011), with RedisFeatures.v8_12_0 and RedisFeatures.StringBitPositions, matching the BLESS branch so the two merge textually. Tests: exact wire bytes for every option combination (BitPositionsRoundTrip), and live tests in BitTests gated on v8_12_0, observed green against a local build of unstable (6a5fee67) on RESP2 and RESP3. Removes the BITRANGEINTARRAY row from the command coverage ledger. * 8.12 RC2: pin the real pre-release version and run CI against the RC2 image - RedisFeatures.v8_12_0 is now 8.11.241, which is what 8.12 RC2 reports (the earlier 8.12.0 placeholder made the gated tests skip on RC2) - the test topology image defaults to redislabs/client-libs-test:8.12-rc2 - the cluster configs opt out of the new cluster-bus-port-protected-mode check, which otherwise refuses to start a plaintext cluster node on RC2 Validated locally against the RC2 topology: StringBitPositions live tests and BitPositionsRoundTrip all pass, and the cluster forms cleanly. * SortedSetScanLarge: count distinct members, tolerating ZSCAN duplicates The 8.12 btree zset encoding can return duplicate members even for an unmodified key (redis/redis#16158; the SCAN contract allows it), so the test now asserts the distinct member count instead of the raw count. All 8 cases pass against the RC2 topology. * Set-member expiration (Redis 8.12): SADDEX / SEXPIRE / SPTTL / SPERSIST on IDatabase (#3340) * Initial support for Redis 8.12 set-member expiration The hash-field-TTL idea (7.4's HEXPIRE) brought to sets (redis/redis#15938, 8.12-rc2), mirroring the HashField* family: - SetAddAndSetExpiry (SADDEX): add members and/or (re)set their expiration in one atomic call; When.NotExists/Exists map to MNX/MXX, which are all-or-nothing across the batch, exactly as HSETEX's FNX/FXX; the bare form discards an existing TTL, KEEPTTL keeps it - SetMemberExpire (SEXPIRE/SPEXPIRE/SEXPIREAT/SPEXPIREAT by precision) -> ExpireResult[], per member - SetMemberGetTimeToLive (SPTTL) and SetMemberGetExpireDateTime (SPEXPIRETIME) -> long[] - SetMemberPersist (SPERSIST) -> PersistResult[] - KeyNotificationType.SExpired ('sexpired', side-effect block), so the 8.12 notification - including on the subkey channels, whose payload names the lapsed member - parses as a known type; GetSubKeys() already handles the payload Gated [Experimental] behind SER011/Experiments.Server_8_12 and RedisFeatures.v8_12_0 (8.11.241), both shared with #3261/#3315; the test docker image moves to client-libs-test:8.12-rc2 as in those PRs. Round-trip tests pin the exact wire bytes; the live tests (HashFieldTests mirror) pass against the 8.12-rc2 topology on both protocols. Plan document in notes/set-member-expiry/. * SADDEX rides SetAdd: two Expiration overloads replace the four-per-arity SetAddAndSetExpiry surface Review feedback (see the PR): Expiration already encodes EX/PX/EXAT/PXAT/KEEPTTL - exactly SADDEX's expiration block - so the TimeSpan?/DateTime/keepTtl splits collapse and the surface is SetAdd(key, value, Expiration, When, flags) and SetAdd(key, values, Expiration, When, flags), both bool (+async): 8 members become 4, with no new method name. A required Expiration keeps overload resolution away from the existing SetAdd members. - Expiration.Persist is rejected (SADDEX has no PERSIST; SetMemberPersist is the way to remove member expirations) - previously it would have been sent as a bogus token. - The overloads always send SADDEX: plain SADD is not an equivalent fallback for the no-expiry form, because bare SADDEX discards an existing member's TTL where SADD leaves existing members untouched; the XML docs call this out, and that the multi-value form reports only whether anything changed, not a count. - The SetMemberExpire/GetTimeToLive/GetExpireDateTime/Persist family is unchanged (ExpireWhen's GT/LT cannot ride Expiration, and it mirrors the HashField shape). - plan.md carries a revision note; SER011.md updated; all 50 SetMemberExpiry tests pass live against 8.12-rc2, 525 KeyPrefixed tests pass. * Each set-member-expiry test deletes its key up front: SADDEX's changed-anything reply and the MNX/NX conditions make residue from a previous run (or the other protocol) look like a failure * Redis 8.12 BLESS (eviction protection) support (#3261) Adds KeyBless/KeyUnbless/KeyBlessFlags (+async) on IDatabase and IServer.BlessedKeys (+async) over BLESS SCAN, with the BlessFlags enum, gated behind SER011 (Server_8_12). SET/CLEAR are raised to primary-only; GET stays replica-eligible. Adds bless/unbless keyspace notification types. * CommandCoverage: the BLESS rows retire with #3261 (the ledger lists only unexposed commands) * Redis 8.12 atomic sorted-set moves: ZMOVE / ZMOVEMEMBER on IDatabase (#3351) redis/redis#16135 (8.12-rc3) adds ZMOVE, BZMOVE and ZMOVEMEMBER: - SortedSetMove (ZMOVE MIN|MAX [COUNT]) - from the low or high end - SortedSetMoveByScore (ZMOVE BYSCORE min max [COUNT]) - a score range - SortedSetMoveMembers (ZMOVEMEMBER [NX|XX] MEMBERS n ...) - named members, with When as the per-member condition on the destination Each returns SortedSetEntry[]?, null when nothing moved (the server's null reply is never folded into an empty array). COUNT is sent if and only if the caller gives one: for BYSCORE, no COUNT means the whole range, so the SortedSetPop habit of eliding COUNT 1 is not copied. The reply is nested [member, score] pairs in RESP2 as well as RESP3, unlike ZPOPMIN, so SortedSetWithScores does not fit; NullableSortedSetEntryArray is a strict nested-pair processor. BZMOVE is not exposed (blocking; policy row in CommandCoverage.md). Gated [Experimental] behind SER011 and the new RedisFeatures.v8_12_0_rc3 (8.11.242: rc2 does not have the commands); the test docker image moves to client-libs-test:8.12-rc3. * SLOWLOG GET: surface the 8.12 estimated-CPU-time field as CommandTrace.CpuTime The 8th entry field (redis/redis#15907, 8.12 RC3) is the duration minus the provable off-CPU time, distinguishing a command that ran slowly from one starved of CPU. Parsed positionally past the client address/name and argument count, so every historical entry length still parses: null when the server did not send the field, zero (per the server) when it was not measured. Gated SER011 with the rest of the 8.12 surface. * Redis 8.12 GA: test against client-libs-test:8.12.0; SER011 stays while the library API settles 8.12.0 went GA on 2026-11-22. The docker test image moves from 8.12-rc3 to 8.12.0, and docs/exp/SER011.md now says the server is generally available while the library API remains experimental.

Problem
Slow commands are often blamed on CPU starvation without evidence. The slowlog
records how long a command took, not whether the thread was actually running
during that time.
SLOWLOG GET field 8: CPU time (µs)
An upper bound on the thread's CPU time for the command:
min(duration, CPU used in the command's window). Close to the duration meansthe command was running; much lower means it mostly was not.
0means not measured: commands shorter than 10ms,off-cpu-tracking no,the unblock path (e.g. a timed-out
BLPOP), and a command re-executed afterblocking.
The reply grows from 7 to 8 elements.
How one cycle is split across commands
Sampling around every command costs ~0.3µs/command (−30% pipelined
throughput), so instead:
context-switch counts). It's the checkpoint.
at least 10ms. That sample becomes the checkpoint for whatever comes next.
Shorter commands take no sample.
For that command:
Example: wakeup, fast command A (5ms), a 200ms context switch, then B (100ms).
At B's end: window = 305ms, window_cpu = 105ms, so B's cpu = min(100, 105) =
100 and off_min = 0. The 200ms happened before B, so it's not charged to B;
the cycle check reports it.
Detections: log lines and INFO counters
Two checks, one rule: reported when the guaranteed off-CPU time is at least
10ms.
Per command: only commands inserted into the slowlog are checked. Counted
in
slow_command_off_cpu_events.Per event-loop cycle: checked when the cycle took at least
max(
slowlog-log-slower-than, 10ms). Counted ineventloop_off_cpu_events.This exists because preemption between fast commands never produces a
slowlog entry.
Both share a limit of one log line per second; the next printed line reports
how many were suppressed. INFO counts every detection, including suppressed
ones. A slow command and its cycle can both count: one asks whether that
command was off-CPU, the other whether that wakeup was.
CONFIG RESETSTATclears both counters.
Label
The context-switch counts tell how many switches happened, not how long each
lasted, so a label is printed only when it's certain:
ru_nivcsw: the kernel took the CPU awaywhile the thread was runnable) →
(starvation)ru_nvcsw: the thread waited, e.g. a blockingsyscall, disk, a lock, a major page fault) →
(blocked)Cycle measurement
The wakeup sample is also kept as the cycle start, and commands never move it.
The cycle is measured at the end of
beforeSleep(), after commands handedover by IO threads, so they are inside the window. The AOF write/fsync
duration (already measured) is subtracted from the off-CPU time, so disk waits
aren't counted. Nested event processing (
processEventsWhileBlocked) returnsbefore this check.
Config
off-cpu-tracking yes|no(defaultyes, changeable withCONFIG SET).yes: one CPU sample per event-loop wakeup, plus one per slow command/cycle.no: no sampling at all, so no cost. SLOWLOG field 8 is0, there are nooff-CPU log lines, and the counters stay
0.as off-CPU. Commands that started while it was off aren't measured.
Otherwise it follows the slowlog: a command is checked only when it's inserted
into the slowlog, and a cycle only when it takes at least
slowlog-log-slower-than. A hard-coded 10ms minimum applies on top: shorterstalls are normal scheduling, and a low threshold shouldn't make commands pay
for
getrusage(). Reports depend only on the measured off-CPU time (≥ 10ms).Limitations
epoll_waitisn't measured,because the window starts once the thread runs.
be labeled
blocked.(their duration isn't known in advance), so on that path the 10ms minimum
only skips the report, not the sampling.
RUSAGE_THREAD(e.g. macOS), the fallbackRUSAGE_SELFincludesother threads' CPU and switches, so off-CPU time reads lower, detections can
be missed, and labels are rare.
Testing
tests/unit/slowlog.tcl:DEBUG SLEEPDEBUG SLEEP→ off-CPU log line and counterEVAL(above the 10ms minimum) gets a non-zero estimateEVALalone,then after 75ms of sleeps, reports about the same CPU time
EVALthenDEBUG SLEEPinsideEXEC)off-cpu-tracking no→ field 8 is0and nothing is reported; turning itback on after an idle period reports nothing false, and measuring resumes
CONFIG RESETSTATclears both countersnice 19,Linux only): a Lua loop is reported per command, and 10×1000 pipelined SETs
per cycle
tests/unit/moduleapi/misc.tcl: module commands that runDEBUG SLEEPviaRM_Call, one and two levels deep, keep the off-CPU time of the inner command.Performance
CE Performance Automation, n=3, pinned bare-metal (m7i.metal-24xl /
m8g.metal-24xl), against the PR's merge-base (
b78a80bd):| test (worst case: one request per wakeup)
|---|---|---|
| zrank-100K-pipeline-1 | −1.7% |
| zrevrank-1M-pipeline-1 | −1.5% |
The cost is one sample per event-loop wakeup, so it shows only when each
request is its own wakeup; the broader string/hash/sorted-set/list regression
gate showed no consistent regression.
off-cpu-tracking noremoves it.A variant reading
run_delayfrom/proc/thread-self/schedstat(exact timewaiting for a CPU vs blocked) was also benchmarked: same cost on amd64,
1–1.5% worse on arm64, so it's left for a possible follow-up.
Note
Medium Risk
Changes the hot path (event loop and
call()/slowlogPushCurrentCommand) and extends the SLOWLOG wire format; default-on sampling can reduce throughput on non-pipelined workloads thoughoff-cpu-tracking nodisables it.Overview
Adds off-CPU tracking so slow commands and long event-loop cycles can be distinguished from true CPU work.
SLOWLOG GETreplies grow from 7 to 8 elements: field 8 is an upper-bound CPU time (µs) for the command (0 when not measured).Sampling is cheap on the main thread: one
getrusagecheckpoint per event-loop wakeup, with an extra sample only when a command is actually written to the slowlog and ran ≥10ms.call()copies that checkpoint per command;slowlogMeasureCpu()derives CPU vs off-CPU bounds and may emit rate-limitedSlow command off-CPUwarnings plusslow_command_off_cpu_eventsinINFO stats.offCpuCheckEventLoopCycle()at the end ofbeforeSleep()reports starvation between fast commands (AOF flush time excluded) viaEvent loop cycle off-CPUlines andeventloop_off_cpu_events.New modifiable config
off-cpu-tracking(defaultyes, documented inredis.conf) resets the CPU window when re-enabled. Client timing resets go throughresetClientCommandDuration()(wall + CPU fields). Module-threadRM_Callpaths sample per command and nested slow calls attribute off-CPU to outer commands; tests cover slowlog shape,DEBUG SLEEP,EXEC, config toggle, and Linux CPU-pinning starvation.Reviewed by Cursor Bugbot for commit 733c0f7. Bugbot is set up for automated code reviews on this repo. Configure here.