본문으로 건너뛰기
Skillpedia
배포 및 클라우드 (DevOps)48k · #4780

graceful-shutdown

하는 일

이 도구는 컴퓨터 프로그램이 작업을 체계적으로 마치도록 돕습니다. 종료하기 전에 진행 중인 모든 작업이 완료되도록 하여 데이터 손실이나 갑작스러운 중단을 막습니다.

사용하는 경우

  • ✓프로그램이 갑자기 멈추지 않도록 업데이트할 때.
  • ✓작업을 처리하는 프로그램이 안전하게 끝나야 할 때.
  • ✓프로그램에 정중하게 종료하라는 신호를 보내는 시스템을 사용할 때.

스킬 링크

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/graceful-shutdown/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/graceful-shutdown/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“종료 신호를 받으면 제 프로그램이 안전하게 종료되도록 하려면 어떻게 해야 하나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

프로그램은 종료 신호(예: Ctrl+C)를 듣습니다. 신호를 받으면 새 작업을 받지 않고, 현재 작업이 끝나기를 기다린 뒤 자원을 해제하고 종료합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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;


…
자주 묻는 질문

「우아한 종료」가 왜 중요한가요?

작업 도중 데이터 손실, 파일 손상, 사용자 중단을 막기 위해서입니다. 특히 자동화 시스템에서 원활한 전환을 보장합니다.

이 도구를 사용하지 않으면 어떻게 되나요?

프로그램이 갑자기 종료되어 연결이 끊기고 작업이 완료되지 않을 수 있습니다. 이로 인해 오류, 데이터 손실, 그것에 의존하는 시스템의 문제가 생길 수 있습니다.

이 도구가 모든 종류의 프로그램에 작동하나요?

네. 서버, 백그라운드 프로세스(워커), 제어된 안전한 종료가 필요한 모든 프로그램을 위해 설계되었습니다.

상세 정보

작성자의 원본 설명

Implement graceful shutdown for servers and workers: drain connections, finish in-flight work, release resources, and exit cleanly on SIGTERM/SIGINT.

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#4780
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬