id: redis-client-output-buffer-guard
namespace: company.team
description: |
Find the Redis clients whose reply buffer is growing inside the server. Redis queues every reply
for a client that reads slower than the server writes. That queue lives in the server's own
memory. It pushes the instance toward maxmemory. Once it crosses client-output-buffer-limit
Redis closes the client: a pub/sub subscriber loses every message it had not read, a replica has
to run a full resync. CLIENT LIST attributes that memory to a named client and a command, which a
plain memory graph cannot. Report it, alert Slack, then behind an approval kill the one offender
with CLIENT KILL, read CLIENT LIST again and fail if its buffer is still there.
inputs:
- id: instances
type: JSON
displayName: Redis hosts to inspect
description: >-
Hostnames reachable from the containers the RedisCLI tasks start. Example
["redis-pubsub-1", "redis-cache-1"].
defaults: '["redis-pubsub-1", "redis-cache-1"]'
- id: port
type: INT
displayName: Port
defaults: 6379
- id: near_limit_pct
type: INT
displayName: Share of the hard limit that counts as near
description: >-
A client whose output buffer reaches this share of its class hard limit is
reported as NEAR_LIMIT. Redis kills it at 100 percent.
defaults: 50
- id: min_omem_mb
type: FLOAT
displayName: Smallest output buffer worth reporting (MiB)
description: Buffers under this are normal and are not reported.
defaults: 1
- id: growth_mb
type: FLOAT
displayName: Growth since the last run that counts as growing (MiB)
defaults: 1
- id: protected_names
type: STRING
displayName: Client names that must never be killed
description: >-
Comma separated CLIENT SETNAME values. Replica links are already excluded,
whatever their name.
defaults: ""
- id: network
type: STRING
displayName: Docker network for redis-cli
defaults: ""
- id: kestra_url
type: STRING
displayName: Kestra URL used in the approval message
defaults: http://localhost:8080
- id: auto_remediate
type: BOOL
displayName: Auto remediate
description: Allows CLIENT KILL, which still waits for an approval.
defaults: false
- id: dry_run
type: BOOL
displayName: Dry run
description: Must be false, together with auto_remediate, for CLIENT KILL to run.
defaults: true
variables:
state_key: redis_obuf_baseline
tasks:
- id: read
type: io.kestra.plugin.core.flow.Loop
description: >-
Read-only. CLIENT LIST for the per-client output buffer, CONFIG GET for
the class limits, INFO clients and INFO stats for the instance totals. An
unreachable host does not stop the others.
values: "{{ inputs.instances | toJson }}"
outputs:
- id: state
type: STRING
value: >-
{{ {'host': item.value, 'clients': outputs.clients.vars.command_1 ??
'', 'limits': outputs.limits.vars.command_1 ?? '', 'info_clients':
outputs.info_clients.vars.command_1 ?? '', 'info_stats':
outputs.info_stats.vars.command_1 ?? ''} | toJson }}
tasks:
- id: one
type: io.kestra.plugin.core.flow.Sequential
allowFailure: true
tasks:
- id: clients
type: io.kestra.plugin.redis.cli.RedisCLI
host: "{{ item.value }}"
port: "{{ inputs.port }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.network }}"
commands:
- CLIENT LIST
- id: limits
type: io.kestra.plugin.redis.cli.RedisCLI
host: "{{ item.value }}"
port: "{{ inputs.port }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.network }}"
commands:
- CONFIG GET client-output-buffer-limit
- id: info_clients
type: io.kestra.plugin.redis.cli.RedisCLI
host: "{{ item.value }}"
port: "{{ inputs.port }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.network }}"
commands:
- INFO clients
- id: info_stats
type: io.kestra.plugin.redis.cli.RedisCLI
host: "{{ item.value }}"
port: "{{ inputs.port }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.network }}"
commands:
- INFO stats
- id: assess
type: io.kestra.plugin.core.output.OutputValues
description: >-
Parse CLIENT LIST into one record per client, put each client in its Redis
class (normal, pubsub or replica), compare its omem with that class hard
limit and with the KV baseline. The obuf disconnection counter is compared
with the baseline too.
values:
r: >-
{{ ('{"r":' ~ (outputs.read.outputs | jq('map(.outputs.state |
fromjson)') | first | toJson)
~ ',"base":' ~ ((kv(vars.state_key, errorOnMissing=false) ?? '{"hosts":{}}') | toJson)
~ ',"pct":' ~ inputs.near_limit_pct
~ ',"minmb":' ~ inputs.min_omem_mb
~ ',"growmb":' ~ inputs.growth_mb
~ ',"prot":' ~ (inputs.protected_names | toJson) ~ '}')
| jq('
(.base | if type == "string" then (fromjson | .hosts // {}) else (.hosts // {}) end) as $base
| .pct as $pct
| (.minmb * 1048576) as $minom
| (.growmb * 1048576) as $grow
| (.prot | split(",") | map(gsub(" "; "")) | map(select(. != ""))) as $prot
| [ .r[] | . as $x
| ($x.limits | split("\\n")) as $ll
| (if ($ll | length) > 1 then $ll[1] else "" end) as $limline
| ($limline | split(" ")) as $lt
| (if ($lt | length) >= 12
then ([0, 4, 8]
| map({($lt[.]):
{hard: ($lt[(. + 1)] | tonumber),
soft: ($lt[(. + 2)] | tonumber),
secs: ($lt[(. + 3)] | tonumber)}
}
)
| add)
else {}
end) as $lim
| ($x.info_clients | split("\\n") | map(select(contains(":")) | gsub("\\r"; "") | split(":")) | map({(.[0]): (.[1] // "")}) | add // {}) as $ic
| ($x.info_stats | split("\\n") | map(select(contains(":")) | gsub("\\r"; "") | split(":")) | map({(.[0]): (.[1] // "")}) | add // {}) as $is
| (($is.client_output_buffer_limit_disconnections // "0") | tonumber) as $disc
| (($ic.client_recent_max_output_buffer // "0") | tonumber) as $recent
| ($base[$x.host] // {}) as $bh
| (($bh.disconnections // 0)) as $bdisc
| ($bh.clients // {}) as $bcl
| [ $x.clients | split("\\n") | .[] | select(startswith("id="))
| (split(" ") | map(select(contains("=")) | split("=") | {(.[0]): (.[1:] | join("="))}) | add) ] as $cls
| [ $cls[]
| ((.omem // "0") | tonumber) as $om
| ((.oll // "0") | tonumber) as $ol
| ((.obl // "0") | tonumber) as $ob
| (if (.name // "") == "" then "addr:" + (.addr // "?") else .name end) as $key
| (if (.name // "") == "" then "(unnamed)" else .name end) as $cname
| (if ((.flags // "") | contains("S")) then "slave"
elif ((((.sub // "0") | tonumber) + ((.psub // "0") | tonumber) + ((.ssub // "0") | tonumber)) > 0 or ((.flags // "") | contains("P"))) then "pubsub"
else "normal" end) as $class
| ($lim[$class].hard // 0) as $hard
| ($bcl[$key] // 0) as $prev
| ($om - $prev) as $delta
| (if $hard > 0 then (($om * 100) / $hard) else 0 end) as $share
| (($om / 1048576) | floor | tostring | sub("[.]0$"; "")) as $ommib
| (if $hard > 0 then ($share | floor | tostring | sub("[.]0$"; "")) else "-" end) as $sharetxt
| (if $hard > 0 then (($hard / 1048576) | floor | tostring | sub("[.]0$"; "")) else "0" end) as $hardmib
| (if $hard > 0 then "\($sharetxt) percent of the \($class) hard limit of \($hardmib) MiB"
else "the \($class) class has no hard limit, so Redis never closes this client and the buffer counts toward maxmemory" end) as $limtxt
| (if ($prev > 0 and $delta > 0) then ", up \((($delta / 1048576) | floor | tostring | sub("[.]0$"; ""))) MiB since the last run"
elif $prev > 0 then ", flat or smaller than the last run"
else "" end) as $growtxt
| (if ($om >= $minom and $class == "slave") then "REPLICA_BUFFER"
elif ($om >= $minom and $hard > 0 and $share >= $pct) then "NEAR_LIMIT"
elif ($om >= $minom and $prev > 0 and $delta >= $grow) then "GROWING"
elif ($om >= $minom and $hard == 0) then "UNCAPPED_BUFFER"
else "OK" end) as $code
| (.name // "") as $nm
| (if ($class != "slave" and (((.cmd // "") | startswith("client|")) | not) and (($prot | index($nm)) == null)) then true else false end) as $killable
| if $code == "OK" then empty
else {host: ($x.host), scope: "client", code: $code,
severity: (if $code == "NEAR_LIMIT" then "CRITICAL" elif $code == "UNCAPPED_BUFFER" then "MEDIUM" else "HIGH" end),
id: (.id // ""), addr: (.addr // ""), laddr: (.laddr // ""), name: $cname,
cmd: (.cmd // ""), class: $class, omem: $om, omem_mib: $ommib, oll: $ol, obl: $ob,
hard_limit: $hard, share_pct: $sharetxt, grew_by: $delta,
age: ((.age // "0") | tonumber), idle: ((.idle // "0") | tonumber),
killable: $killable,
fix: "CLIENT KILL ID \(.id // "") ADDR \(.addr // "")",
detail: "\($class) client \($cname) at \(.addr) running \(.cmd): output buffer \($ommib) MiB (\($om) bytes), \($ol) replies queued, \($limtxt)\($growtxt). Age \(.age)s, idle \(.idle)s."}
end ] as $cf
| [ (if $limline == ""
then {host: $x.host, scope: "instance", code: "UNREACHABLE", severity: "HIGH",
id: "", addr: "-", laddr: "", name: "-", cmd: "-", class: "-", omem: 0, omem_mib: "0",
oll: 0, obl: 0, hard_limit: 0, share_pct: "-", grew_by: 0, age: 0, idle: 0,
killable: false, fix: "",
detail: "No CLIENT LIST or CONFIG reply from \($x.host). Check the host, the port and whether CLIENT and CONFIG are allowed for this user."}
else empty end),
(if ($disc > $bdisc and $base[$x.host] != null)
then {host: $x.host, scope: "instance", code: "KILLED_ALREADY", severity: "CRITICAL",
id: "", addr: "-", laddr: "", name: "-", cmd: "-", class: "-", omem: 0, omem_mib: "0",
oll: 0, obl: 0, hard_limit: 0, share_pct: "-", grew_by: 0, age: 0, idle: 0,
killable: false, fix: "",
detail: "Redis closed \($disc - $bdisc) client(s) on \($x.host) for crossing client-output-buffer-limit since the last run (counter \($bdisc) to \($disc)). A pub/sub subscriber closed this way silently lost every message it had not read. A replica closed this way needs a full resync."}
else empty end) ] as $inst
| ([ $cls[] | {k: (if (.name // "") == "" then "addr:" + (.addr // "?") else .name end), v: ((.omem // "0") | tonumber)} ]
| group_by(.k) | map({(.[0].k): (map(.v) | max)}) | add // {}) as $snap
| {host: $x.host,
findings: ($inst + $cf),
info: {connected_clients: (($ic.connected_clients // "0") | tonumber),
pubsub_clients: (($ic.pubsub_clients // "0") | tonumber),
recent_max_output_buffer: $recent,
disconnections: $disc, disconnections_before: $bdisc,
limits: $lim},
snapshot: (if $limline == "" then $base[$x.host] else {disconnections: $disc, recent_max_output_buffer: $recent, clients: $snap} end)
}
] as $per
| {findings: ($per | map(.findings) | add // []),
hosts: ($per | map({host: .host, info: .info})),
targets: ($per | map(.findings) | add // [] | map(select(.scope == "client" and .killable == true) | {host: (.host), addr: (.addr), name: (.name), id: (.id), omem: (.omem), cmd: (.fix)})),
snapshot: {hosts: ($per | map({(.host): .snapshot}) | add // {})}
}') | first | toJson }}
- id: summary
type: io.kestra.plugin.core.log.Log
message: >-
Redis client output buffers on {{ inputs.instances | length }}
instance(s): {{ fromJson(outputs.assess.values.r).findings | length }}
finding(s). {{ fromJson(outputs.assess.values.r) | jq('.hosts |
map("\(.host): \(.info.connected_clients) clients, \(.info.pubsub_clients)
in the pubsub class, client_recent_max_output_buffer
\(.info.recent_max_output_buffer) bytes, obuf disconnections
\(.info.disconnections) (was \(.info.disconnections_before))") | join(";
")') | first }}. {{ fromJson(outputs.assess.values.r) | jq('.findings |
map("\(.severity) \(.code) \(.host) \(.name): \(.detail)") | join(" | ")')
| first }}
- id: save_baseline
type: io.kestra.plugin.core.kv.Set
description: >-
The next run compares each client's output buffer and the obuf
disconnection counter with this snapshot. No TTL: an expired KV key throws
instead of reading as missing.
key: "{{ vars.state_key }}"
kvType: JSON
value: "{{ fromJson(outputs.assess.values.r).snapshot | toJson }}"
- id: route
type: io.kestra.plugin.core.flow.If
condition: "{{ fromJson(outputs.assess.values.r).findings | length > 0 }}"
then:
- id: alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': 'Redis client output buffers: ' ~ (fromJson(outputs.assess.values.r) | jq('.findings | map("\(.severity) \(.code) \(.host) \(.name) (\(.cmd)): \(.omem_mib) MiB, \(.share_pct) percent of its class hard limit") | join("; ")') | first) ~ '.' ~ (inputs.auto_remediate and not inputs.dry_run ? ' Asking for approval to run CLIENT KILL.' : ' No change applied (auto_remediate=' ~ inputs.auto_remediate ~ ', dry_run=' ~ inputs.dry_run ~ ').')} | toJson }}
- id: remediate_gate
type: io.kestra.plugin.core.flow.If
description: >-
CLIENT KILL disconnects a live client, so it needs auto_remediate,
dry_run false and an approval. Replica links and protected names are
never offered.
condition: "{{ inputs.auto_remediate and not inputs.dry_run and
(fromJson(outputs.assess.values.r).targets | length) > 0 }}"
then:
- id: ask_approval
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': 'These Redis clients hold a large reply buffer inside the server and can be disconnected to free it now: ' ~ (fromJson(outputs.assess.values.r) | jq('.targets | map("\(.addr) name \(.name), \(.omem) bytes queued, fix \(.cmd)") | join("; ")') | first) ~ '. Killing a client drops the replies it had not read, so a pub/sub subscriber loses those messages. It does not fix the consumer that is reading too slowly. To disconnect, enter the addresses in the resume form within 2 hours: ' ~ inputs.kestra_url ~ '/ui/main/executions/' ~ flow.namespace ~ '/' ~ flow.id ~ '/' ~ execution.id ~ '. Leave it empty to keep every client connected.'} | toJson }}
- id: wait_for_decision
type: io.kestra.plugin.core.flow.Pause
description: No answer within 2 hours means no client is disconnected.
pauseDuration: PT2H
behavior: RESUME
onResume:
- id: kill_addrs
type: STRING
required: false
description: Comma separated addr values from the message. Empty keeps every
client.
- id: note
type: STRING
required: false
description: Optional reason, logged with the result.
- id: kill_requested
type: io.kestra.plugin.core.flow.If
condition: "{{ ((outputs.wait_for_decision.onResume.kill_addrs ?? '') | trim) !=
'' }}"
then:
- id: remediate
type: io.kestra.plugin.core.flow.Loop
description: >-
One CLIENT KILL per approved client, one at a time. The ID and
ADDR filters are combined, which Redis treats as AND, so a
client that reconnected since the report is not killed by
mistake.
concurrencyLimit: 1
values: >-
{{ ('{"t":' ~ (fromJson(outputs.assess.values.r).targets |
toJson)
~ ',"a":' ~ ((outputs.wait_for_decision.onResume.kill_addrs ?? '') | toJson) ~ '}')
| jq('(.a | split(",") | map(gsub(" "; "")) | map(select(. != ""))) as $a
| [.t[] | (.addr) as $ad | select(($a | index($ad)) != null)]') | first | toJson }}
outputs:
- id: killed
type: STRING
value: >-
{{ {'host': fromJson(item.value).host, 'addr':
fromJson(item.value).addr, 'name':
fromJson(item.value).name, 'omem_before':
fromJson(item.value).omem, 'reply':
outputs.kill.vars.command_1 ?? ''} | toJson }}
tasks:
- id: kill
type: io.kestra.plugin.redis.cli.RedisCLI
host: "{{ fromJson(item.value).host }}"
port: "{{ inputs.port }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.network }}"
commands:
- "{{ fromJson(item.value).cmd }}"
- id: reread
type: io.kestra.plugin.core.flow.Loop
description: Read CLIENT LIST and INFO clients again on every host that was
changed.
values: >-
{{ ('{"t":' ~ (fromJson(outputs.assess.values.r).targets |
toJson)
~ ',"a":' ~ ((outputs.wait_for_decision.onResume.kill_addrs ?? '') | toJson) ~ '}')
| jq('(.a | split(",") | map(gsub(" "; "")) | map(select(. != ""))) as $a
| [.t[] | (.addr) as $ad | select(($a | index($ad)) != null) | .host] | unique') | first | toJson }}
outputs:
- id: after
type: STRING
value: >-
{{ {'host': item.value, 'clients':
outputs.clients2.vars.command_1 ?? '', 'info':
outputs.ic2.vars.command_1 ?? ''} | toJson }}
tasks:
- id: clients2
type: io.kestra.plugin.redis.cli.RedisCLI
host: "{{ item.value }}"
port: "{{ inputs.port }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.network }}"
commands:
- CLIENT LIST
- id: ic2
type: io.kestra.plugin.redis.cli.RedisCLI
host: "{{ item.value }}"
port: "{{ inputs.port }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.network }}"
commands:
- INFO clients
- id: verify_result
type: io.kestra.plugin.core.flow.If
description: An approved client still holding a reportable buffer means the kill
did not land.
condition: >-
{{ ('{"t":' ~ (fromJson(outputs.assess.values.r).targets |
toJson)
~ ',"a":' ~ ((outputs.wait_for_decision.onResume.kill_addrs ?? '') | toJson)
~ ',"r":' ~ (outputs.reread.outputs | jq('map(.outputs.after | fromjson)') | first | toJson)
~ ',"min":' ~ (inputs.min_omem_mb * 1048576) ~ '}')
| jq('(.a | split(",") | map(gsub(" "; "")) | map(select(. != ""))) as $a
| (.min) as $m
| [.t[] | (.addr) as $ad | select(($a | index($ad)) != null) | .addr] as $t
| [ .r[] | . as $h
| ($h.clients | split("\\n") | .[] | select(startswith("id="))
| (split(" ") | map(select(contains("=")) | split("=") | {(.[0]): (.[1:] | join("="))}) | add))
| (.addr) as $ad | select((($t | index($ad)) != null) and (((.omem // "0") | tonumber) >= $m)) | .addr ] | length') | first > 0 }}
then:
- id: remediation_failed
type: io.kestra.plugin.core.execution.Fail
errorMessage: >-
CLIENT KILL ran, but these clients are still connected
with a reportable output buffer: {{ ('{"t":' ~
(fromJson(outputs.assess.values.r).targets | toJson)
~ ',"a":' ~ ((outputs.wait_for_decision.onResume.kill_addrs ?? '') | toJson)
~ ',"r":' ~ (outputs.reread.outputs | jq('map(.outputs.after | fromjson)') | first | toJson)
~ ',"min":' ~ (inputs.min_omem_mb * 1048576) ~ '}')
| jq('(.a | split(",") | map(gsub(" "; "")) | map(select(. != ""))) as $a
| (.min) as $m
| [.t[] | (.addr) as $ad | select(($a | index($ad)) != null) | .addr] as $t
| [ .r[] | . as $h
| ($h.clients | split("\\n") | .[] | select(startswith("id="))
| (split(" ") | map(select(contains("=")) | split("=") | {(.[0]): (.[1:] | join("="))}) | add))
| (.addr) as $ad2 | select((($t | index($ad2)) != null) and (((.omem // "0") | tonumber) >= $m))
| "\($h.host) \($ad2) name=\(.name) omem=\(.omem) oll=\(.oll)" ] | join("; ")') | first }}.
else:
- id: remediated
type: io.kestra.plugin.core.log.Log
message: >-
Disconnected and verified. Before: {{
outputs.remediate.outputs | jq('map(.outputs.killed |
fromjson) | map("\(.name) at \(.addr) on \(.host) held
\(.omem_before) bytes, CLIENT KILL replied \(.reply)") |
join("; ")') | first }}. After: {{ ('{"r":' ~
(outputs.reread.outputs | jq('map(.outputs.after |
fromjson)') | first | toJson) ~ '}') | jq('
[ .r[] | . as $h
| ($h.info | split("\\n") | map(select(contains(":")) | gsub("\\r"; "") | split(":")) | map({(.[0]): (.[1] // "")}) | add // {}) as $ic
| ($h.clients | split("\\n") | map(select(startswith("id="))) | length) as $n
| "\($h.host): \($n) clients, client_recent_max_output_buffer \($ic.client_recent_max_output_buffer // "?") bytes" ] | join("; ")') | first }}.
Note: {{ (outputs.wait_for_decision.onResume.note ?? '')
== '' ? 'none given' :
outputs.wait_for_decision.onResume.note }}. The buffer is
gone, the cause is not. Fix the consumer that was not
reading. Raise client-output-buffer-limit for its class
instead if the burst is expected.
else:
- id: kill_declined
type: io.kestra.plugin.core.log.Log
message: Approval returned no address, so every client is still connected.
else:
- id: clean
type: io.kestra.plugin.core.log.Log
message: >-
Every client's output buffer is small, no client was closed for
crossing client-output-buffer-limit since the last run.
errors:
- id: alert_flow_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': 'Redis client output buffer guard failed (execution ' ~ execution.id ~ '). Check the logs.'} | toJson }}
triggers:
- id: every_ten_minutes
type: io.kestra.plugin.core.trigger.Schedule
description: >-
Shipped disabled and always in safe mode. Output buffers grow in minutes,
so this runs often enough to catch one before Redis closes the client.
cron: "*/10 * * * *"
disabled: true
inputs:
auto_remediate: false
dry_run: true