graceful-shutdown

graceful-shutdown is a skill for Claude Code, Codex from cass-2003/local-workflow-skill. It costs 132 tokens per session (2,848 once invoked), scanned A, original, MIT.

A guide to stopping a service carefully after it receives a shutdown signal. It explains how to stop new traffic, finish active requests, and close connections and workers.

In plain words
What is it for?
Use it to implement shutdown handling for HTTP, WebSocket, streaming, database, cache, and message-queue services, including Kubernetes deployments.
Why use it?
It helps prevent failed requests, lost queue messages, incomplete work, and leaked database or cache connections during deployments or restarts.

Skill for Claude CodeCodex

Written for no agent in particular: nothing here depends on one.

Good fit Use it to implement shutdown handling for HTTP, WebSocket, streaming, database, cache, and message-queue services, including Kubernetes deployments.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/cass-2003/local-workflow-skill/graceful-shutdown
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add cass-2003/local-workflow-skill --skill graceful-shutdown
Clone the repo
git clone --depth 1 https://github.com/cass-2003/local-workflow-skill

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for graceful-shutdown

README.md
[![agentmods](https://agentmods.dev/badge/skills/cass-2003/local-workflow-skill/graceful-shutdown/github.svg)](https://agentmods.dev/skills/cass-2003/local-workflow-skill/graceful-shutdown)
Your own site
<a href="https://agentmods.dev/skills/cass-2003/local-workflow-skill/graceful-shutdown"><img src="https://agentmods.dev/badge/skills/cass-2003/local-workflow-skill/graceful-shutdown/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for graceful-shutdown

Your own site · 80×15
<a href="https://agentmods.dev/skills/cass-2003/local-workflow-skill/graceful-shutdown"><img src="https://agentmods.dev/badge/skills/cass-2003/local-workflow-skill/graceful-shutdown.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 132 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,848 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00132 $0.02848
Opus 5 $0.00066 $0.01424
Sonnet 5 $0.00026 $0.00570
Haiku 4.5 $0.00013 $0.00285

Measured 7d ago against content hash 0e547ed3aea3, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-10, from the pricing page.

Security

Grade A, and why

graceful-shutdown scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 7d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/engineering-core/ours/graceful-shutdown/SKILL.md · 324 lines

How it starts

The opening of the file, as written. The whole thing — 324 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Graceful Shutdown Skill — 优雅停机

何时使用

  • 部署滚动更新时用户看到 502 / 连接重置
  • 排查"deploy 后丢了几条请求 / 队列消息"
  • 设计长连接服务(WebSocket / SSE / gRPC streaming)的发布
  • 数据库 / 缓存连接没正确关闭,连接数堆积
  • Kubernetes 滚动 deploy 配 preStop / terminationGracePeriodSeconds

一、为什么需要优雅停机

[时刻 T]   K8s 收到 deploy 命令
[T+0ms]    新 Pod 创建
[T+xms]    新 Pod ready → Service endpoint 加入新 IP
[T+xms]    Service endpoint 移除旧 IP(异步!可能延迟)
[T+xms]    旧 Pod 收到 SIGTERM
[T+30s]    grace period 默认 30s 后 SIGKILL

两个并发问题

  1. endpoint 摘流延迟:旧 Pod 收到 SIGTERM 但 LB 还在发流量进来 → 502 / 连接重置
  2. in-flight 请求:旧 Pod 处理中的请求还没完成就被 kill → 数据不一致 / 客户端 retry

二、停机六步标准流程

1. 收到 SIGTERM
2. 标记 health check 为 unhealthy → LB / Service 摘流
3. 等若干秒(让 LB / DNS / kube-proxy 真正生效)
4. 关闭 HTTP listener(不接新连接)
5. 等待所有 in-flight 请求完成(带 timeout)
6. 关闭依赖(DB pool / Redis / message queue / OTel exporter flush)
7. 进程退出

三、Go 标准实现

func main() {
    srv := &http.Server{Addr: ":8080", Handler: router}
    go srv.ListenAndServe()

    // 1. 等信号
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
    <-quit
    log.Info("shutdown signal received")

    // 2. 标记 unhealthy(让 LB 摘流)
    healthState.Store(false)
    time.Sleep(5 * time.Second)   // 等 LB 摘流(K8s readiness 周期 + 误差)

    // 3-4-5. 关闭 HTTP(带超时;server.Shutdown 等 in-flight 完成)
    ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
    defer cancel()
    if err := srv.Shutdown(ctx); err != nil {
        log.Error("forced shutdown", "err", err)
    }

    // 6. 关依赖
    db.Close()
    redis.Close()
    tracerProvider.Shutdown(context.Background())   // flush spans
    log.Info("shutdown complete")
}

四、Node.js (Express / Fastify)

const server = app.listen(8080)
let shuttingDown = false

// healthcheck 路由
app.get('/healthz', (req, res) => {
  res.status(shuttingDown ? 503 : 200).json({ ok: !shuttingDown })
})

async function shutdown() {
  if (shuttingDown) return
  shuttingDown = true
  console.log('SIGTERM received, shutting down')

  // 1. 等 LB 摘流
  await sleep(5000)

  // 2. 关 listener
  await new Promise<void>((resolve) => {
    server.close((err) => err ? console.error(err) : resolve())
    // server.close 等所有 keep-alive 连接关闭
    // 强制关 keep-alive:server.closeIdleConnections()  (Node 18+)
    server.closeIdleConnections?.()
  })

  // 3. 等 in-flight(自家计数器或外部 inflight 中间件)
  await waitForInflightToFinish(20_000)

  // 4. 关依赖
  await db.end()
  await redis.quit()
  await otelSdk.shutdown()

  process.exit(0)
}

process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)

Read the full file on GitHub · 324 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 7d ago First seen · 324 lines · 132 tokens per session scan A 0e547ed3aea3

Subscribe to this mod's changes

graceful-shutdown is a skill published in the GitHub repository cass-2003/local-workflow-skill (12 stars, last pushed 2mo ago), licensed MIT. It adds 132 tokens to every session and 2,848 once invoked, about $0.0007 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-03.

Related

Other skills, from other repositories

systematic-debugging

Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes.

obra/superpowers · 21 tokens

local-ai-agents

Build local-first AI agents that run entirely on a developer workstation with Microsoft Foundry Local and Qwen function-calling models. Covers Small Language Models (SLMs), the OpenAI-compatible local endpoint, sandboxed local tools, local RAG with Chroma, local MCP servers, hybrid cloud/local routing, and the…

microsoft/ai-agents-for-beginners · 200 tokens

next-cache-components-adoption

Turn on Cache Components in a Next.js app and resolve the blocking routes it surfaces. Use when the user wants to enable, adopt, or migrate to Cache Components, flip the cacheComponents flag, work through a flood of blocking-prerender / instant validation errors, run the cache-components-instant-false codemod, or…

vercel/next.js · 95 tokens

insight-error-page

Write or audit an insight-kind error page for the Next.js dev overlay. Use when creating a new errors/ .mdx page, auditing an existing one, or checking that a page matches the framework fix cards. Covers page structure, title alignment, FixCard cards with Copy prompt button, code snippets, terminology verification…

vercel/next.js · 83 tokens

next-cache-components-optimizer

Drive a Next.js route to instant navigation by setting up an agentic loop, under Cache Components / PPR, on initial load (hard navigation) and client-side navigation (soft navigation). Encode the goal as a failing @next/playwright instant() e2e and work it to green, one verified route at a time; the shipped test then…

vercel/next.js · 170 tokens

next-partial-prefetching-adoption

Turn on Partial Prefetching in a Next.js app and work through the insights it surfaces. Use when the user wants to enable or adopt Partial Prefetching, flip the partialPrefetching flag, opt routes in with export const prefetch = 'partial', audit Link prefetch={true} behavior, preserve existing prefetched UI with…

vercel/next.js · 103 tokens