graceful-shutdown
Skill này làm gì
Công cụ này giúp các chương trình máy tính kết thúc công việc một cách có tổ chức. Nó đảm bảo mọi việc đang làm được hoàn tất trước khi tắt, tránh mất dữ liệu hoặc bị gián đoạn đột ngột.
Khi nào nên dùng
- ✓Khi cập nhật một chương trình mà không cần nó dừng hoạt động đột ngột.
- ✓Khi một chương trình xử lý tác vụ cần kết thúc an toàn.
- ✓Khi dùng các hệ thống gửi tín hiệu yêu cầu chương trình tắt một cách lịch sự.
Liên kết skill
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/graceful-shutdown/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Làm thế nào để chương trình của tôi tắt an toàn khi nhận được tín hiệu tắt máy?”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Chương trình lắng nghe các tín hiệu tắt (như Ctrl+C). Khi nhận được tín hiệu, nó ngừng nhận tác vụ mới, chờ các tác vụ hiện tại hoàn thành và giải phóng tài nguyên trước khi thoát.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
Graceful Shutdown
Overview
A skill for implementing graceful shutdown in servers, workers, and long-running processes. Ensures in-flight requests complete, background jobs finish or checkpoint, database connections close cleanly, and the process exits with a proper status code. Essential for zero-downtime deployments in container orchestrators (Kubernetes, ECS, Docker Compose) and bare-metal process managers (systemd, PM2).
When to Use This Skill
- Use when building an HTTP server that must not drop active connections during deploys
- Use when writing a background worker that processes jobs from a queue
- Use when deploying to Kubernetes, Docker, or any environment that sends SIGTERM before killing
- Use when the user says "graceful shutdown", "drain connections", "handle SIGTERM", "zero downtime", or "don't kill active requests"
- Use when implementing health check endpoints (
/healthz,/readyz) for orchestrators
How It Works
Step 1: Register signal handlers early
Trap SIGTERM (orchestrator shutdown) and SIGINT (Ctrl+C) at process startup. Set a flag so the application knows it is shutting down.
let isShuttingDown = false;
function onShutdownSignal(signal: string): void {
if (isShuttingDown) return; // prevent double-shutdown
isShuttingDown = true;
console.log(`Received ${signal}, starting graceful shutdown...`);
shutdown();
}
process.on("SIGTERM", () => onShutdownSignal("SIGTERM"));
process.on("SIGINT", () => onShutdownSignal("SIGINT"));
Step 2: Stop accepting new work
Immediately stop the server from accepting new connections. For HTTP servers, call server.close(). For queue workers, stop polling for new jobs.
async function shutdown(): Promise<void> {
// 1. Stop accepting new connections
server.close(() => {
console.log("Server closed — no new connections accepted");
});
// 2. Mark health check as not-ready so load balancers stop routing
// (readiness probe returns 503 from this point)
}
Step 3: Drain in-flight work with a deadline
Wait for active requests and background tasks to finish, but enforce a hard deadline so the process never hangs indefinitely.
const DRAIN_TIMEOUT_MS = 25_000; // must be less than orchestrator's terminationGracePeriodSeconds
async function drainAndExit(): Promise<void> {
const deadline = setTimeout(() => {
console.error("Drain timeout reached — forcing exit");
process.exit(1);
}, DRAIN_TIMEOUT_MS);
deadline.unref(); // don't keep the event loop alive just for the timer
try {
// Wait for active connections to finish
await waitForActiveConnections();
// Flush buffered data (logs, metrics, queues)
await flushBuffers();
// Close external resource handles
await closeResources();
console.log("Graceful shutdown complete");
process.exit(0);
} catch (err) {
console.error("Error during shutdown:", err);
process.exit(1);
}
}
Step 4: Implement readiness and liveness probes
Orchestrators use these to decide whether to route traffic and whether to restart the container. Liveness proves the process is alive; readiness controls whether traffic is routed. While the listener is still available during a drain, keep liveness healthy and return 503 only from readiness. After the listener closes, new probes cannot connect, so do not promise that HTTP liveness remains reachable for the entire termination window.
import { createServer, IncomingMessage, ServerResponse } from "node:http";
function handleHealthCheck(req: IncomingMessage, res: ServerResponse): void {
if (req.url === "/healthz") {
// Keep liveness distinct from readiness while the listener is available.
// Drain-rejection middleware must not turn this endpoint into a 503.
res.writeHead(200).end("ok");
return;
}
if (req.url === "/readyz") {
// Readiness: 503 during shutdown so the load balancer stops routing.
if (isShuttingDown) {
res.writeHead(503).end("shutting down");
} else {
res.writeHead(200).end("ready");
}
return;
}
}
Step 5: Track active connections
Maintain a count of in-flight requests so you know when draining is complete. Use a once guard covering both finish and close events so that client disconnects (aborted requests) correctly decrement the counter.
let activeConnections = 0;
let drainResolve: (() => void) | null = null;
…
Câu hỏi thường gặp
Tại sao 'tắt an toàn' lại quan trọng?
Để tránh mất dữ liệu, hỏng tệp hoặc làm gián đoạn người dùng giữa chừng một thao tác. Nó đảm bảo quá trình chuyển đổi suôn sẻ, nhất là trong các hệ thống tự động.
Điều gì xảy ra nếu tôi không dùng công cụ này?
Chương trình có thể bị dừng đột ngột, làm đứt kết nối và để lại các tác vụ chưa xong. Điều này có thể gây lỗi, mất dữ liệu và ảnh hưởng đến các hệ thống phụ thuộc vào nó.
Công cụ này có dùng được cho mọi loại chương trình không?
Có, nó được thiết kế cho máy chủ, tiến trình chạy nền (worker) và bất kỳ chương trình nào cần kết thúc có kiểm soát và an toàn.
Chi tiết
Mô tả gốc của tác giả
Implement graceful shutdown for servers and workers: drain connections, finish in-flight work, release resources, and exit cleanly on SIGTERM/SIGINT.
Độ phổ biến
- Sao GitHub
- 48k
- Vị trí xếp hạng
- #4780
- Giấy phép
- MIT
- Cập nhật
- 15/10/2026
Bình luận
- …
Thêm skill từ kho mã này
00-andruia-consultant
48kGiúp agent của bạn bắt đầu hoặc cải thiện các dự án AI. Phân tích mã, gợi ý công cụ và lập kế hoạch hành động bằng tiếng Tây Ban Nha.
007
48kCho phép agent của bạn thực hiện kiểm toán bảo mật và mô hình hóa mối đe dọa. Hữu ích để bảo vệ dự án khỏi các cuộc tấn công và lỗ hổng.
10-andruia-skill-smith
48kGiúp agent của bạn tạo hoặc cải thiện các công cụ AI. Xác định cách công cụ hoạt động, viết tài liệu và kiểm tra cấu trúc.
20-andruia-niche-intelligence
48kGiúp agent của bạn tạo bản tóm tắt về một ngành cụ thể. Hữu ích để hiểu bối cảnh, quy tắc, cách người dùng tương tác và rủi ro của dự án.
Skill tương tự
openclaw-update
394kGiúp agent của bạn cập nhật OpenClaw Gateway đang có, chọn cách cập nhật phù hợp với cách cài đặt và giữ phiên làm việc của bạn hoạt động.
diagnose-gateway
394kGiúp agent của bạn tìm hiểu vì sao OpenClaw Gateway bị lỗi bằng cách kiểm tra cài đặt, kênh và cổng mà không thay đổi gì.
crabbox-apps
394kGiúp agent của bạn mở và chạy một app trên máy đám mây tạm thời, rồi hiển thị giao diện của nó trong thanh bên của chat.