ရိုးရိုးလေး ရှင်းပြမယ်
Graceful shutdown ကို ရိုးရိုးလေး ပြောရရင်
Version အသစ် deploy လုပ်တိုင်း platform က process အဟောင်းကို 'ရပ်တော့' လို့ signal တစ်ခု ပို့ပါတယ်၊ များသောအားဖြင့် SIGTERM ပါ။ Graceful shutdown ဆိုတာ အဲဒီ signal ကို ရတဲ့အခါ ချက်ချင်း မသေဘဲ လက်ထဲမှာ ရှိနေတဲ့ အလုပ်ကို ပြီးအောင် လုပ်၊ connection တွေကို သေသေချာချာ ပိတ်ပြီးမှ ထွက်တာပါ။
ဆိုင်ပိတ်ချိန်လိုပါပဲ: တံခါးပေါ်မှာ 'ပိတ်ပါပြီ' ဆိုင်းဘုတ် ချိတ်၊ ဆိုင်ထဲ ရှိနေတဲ့ customer တွေကို ငွေရှင်းပြီးအောင် စောင့်၊ ပြီးမှ မီးပိတ်ပြီး သော့ခတ်ပါတယ်။ ဒါပေမဲ့ customer တစ်ယောက်က နာရီဝက် ကြာနေရင်တောင် အချိန်တစ်ခုမှာ တံခါးပိတ်ရပါမယ်။
Problem → Why → Solution
ပြဿနာ: deploy တိုင်း 502 error တွေ
Team တစ်ခုက တစ်နေ့ ဆယ်ခါလောက် deploy လုပ်ပြီး deploy တိုင်း user အချို့ 502 Bad Gateway ရပါတယ်၊ payment request တစ်ဝက်တစ်ပျက်တွေလည်း ကျန်ခဲ့ပါတယ်။ Code ကို ကြည့်လိုက်တော့ SIGTERM ရတာနဲ့ process.exit(0) ကို ချက်ချင်း ခေါ်ထားပါတယ်။ အခြား service တစ်ခုမှာတော့ signal handler လုံးဝ မရှိလို့ container က timeout ပြည့်တဲ့အထိ ရပ်နေပြီး SIGKILL နဲ့ အတင်းသတ်ခံရပါတယ်။
const server = app.listen(3000);
process.on('SIGTERM', () => {
// In-flight responses are cut off, buffered logs may be lost,
// and the database never hears that the connections are gone.
process.exit(0);
});ဘာကြောင့် exit ချက်ချင်း ခေါ်တာ မှားလဲ
Signal ရောက်လာတဲ့ အချိန်မှာ request တချို့က database ကို စောင့်နေတုန်း ဖြစ်နိုင်ပြီး load balancer ကလည်း ဒီ process ဆီ request အသစ်တွေ ဆက်ပို့နေနိုင်ပါသေးတယ်။ process.exit() က ဒါတွေ အားလုံးကို ဖြတ်ချပြီး pipe ထဲက log line တွေကိုလည်း ဆုံးရှုံးစေနိုင်ပါတယ်။ Handler လုံးဝ မရှိတာကလည်း ပြဿနာပါ: container ထဲမှာ PID 1 ဖြစ်နေတဲ့ process က handler မရှိရင် SIGTERM ကို လျစ်လျူရှုပြီး platform က SIGKILL ပို့တဲ့အထိ စောင့်နေရပါတယ်။
Core concept: shutdown ဆိုတာ အဆင့်လိုက် state machine တစ်ခု
Signal နှစ်မျိုးကို ကိုင်တွယ်ပါ: SIGTERM ကို Docker၊ Kubernetes နဲ့ process manager တွေက ပို့ပြီး SIGINT ကတော့ terminal မှာ Ctrl+C နှိပ်ရင် ရောက်လာပါတယ်။ Kubernetes က SIGTERM ပို့ပြီးနောက် terminationGracePeriodSeconds (default 30 စက္ကန့်) စောင့်ပြီး docker stop က default 10 စက္ကန့် စောင့်ပါတယ်၊ ပြီးရင် SIGKILL နဲ့ အတင်းသတ်ပါတယ်။ SIGKILL ကို ဖမ်းလို့ မရလို့ shutdown တစ်ခုလုံး အဲဒီ deadline အတွင်း ပြီးရပါမယ်။
အဆင့်တွေကို အစဉ်လိုက် လုပ်ပါ။ (1) shuttingDown flag ကို set လုပ်ပြီး readiness endpoint က 503 ပြန်ပါစေ၊ load balancer က ဒီ instance ဆီ traffic ပို့တာ ရပ်ဖို့ စက္ကန့်အနည်းငယ် စောင့်ပါ။ (2) server.close() ကို ခေါ်ပါ: listening socket ကို ပိတ်လို့ connection အသစ် မဝင်တော့ဘဲ in-flight request တွေ ပြီးမှ callback ပြန်ပါတယ်။ Node 19 ကစပြီး close() က idle keep-alive connection တွေကိုပါ ပိတ်ပေးပေမဲ့ drain လုပ်နေတုန်း ပြီးသွားတဲ့ response တွေမှာ Connection: close ထည့်ရင် socket တွေ မြန်မြန် ပိတ်ပါတယ်။ (3) Database pool၊ queue consumer၊ log buffer လို dependency တွေကို request တွေ ပြီးမှ ပိတ်ပါ၊ သူတို့ကို request တွေက သုံးနေနိုင်လို့ပါ။ (4) Exit code ကို သတ်မှတ်ပြီး Node ကို ကိုယ့်ဘာသာ ထွက်ခိုင်းပါ။
Shutdown function ကို idempotent ဖြစ်အောင် ရေးပါ: SIGTERM ပြီးနောက် SIGINT ထပ်ရောက်လာရင် cleanup ကို ဒုတိယအကြိမ် မစရပါဘူး။ Force-exit timer ကိုလည်း ထည့်ပါ၊ stuck ဖြစ်နေတဲ့ connection တစ်ခုက deploy တစ်ခုလုံးကို ဆွဲမထားစေဖို့ပါ။ အဲဒီ timer ကို unref() လုပ်ထားရင် cleanup အချိန်မီ ပြီးတဲ့အခါ process ကို ဆွဲမထားပါဘူး။
Shutdown ကို test လုပ်ဖို့ တကယ့် signal ပို့စရာ မလိုပါဘူး။ process.emit('SIGTERM', 'SIGTERM') က register လုပ်ထားတဲ့ listener တွေကို signal အစစ် ရောက်လာသလို ခေါ်ပေးပါတယ်။ Windows မှာ SIGTERM ကို listen လုပ်လို့ ရပေမဲ့ kill က အဲဒီ listener ကို ဘယ်တော့မှ မခေါ်ဘဲ process ကို တိုက်ရိုက် ရပ်ပစ်တဲ့အတွက် ဒီနည်းက OS တိုင်းမှာ တူညီတဲ့ ရလဒ် ပေးပါတယ်။ Test တွေမှာ handler ကို တိုက်ရိုက် ခေါ်ပြီး ပြန်ပေးတဲ့ promise ကို await လုပ်တာလည်း အဆင်ပြေပါတယ်။
- Signal: readiness 503 + deadline
- LB ရပ်ဖို့ ခဏစောင့်
- server.close(): in-flight drain
- DB/queue ကို ပိတ်
- exitCode သတ်မှတ်ပြီး ထွက်
Deadline ပြည့်သွားရင် အဆင့်တွေကို ကျော်ပြီး exit code 1 နဲ့ ထွက်ပါ၊ platform က SIGKILL နဲ့ သတ်တာထက် ကိုယ်တိုင် ထွက်တာ ပိုကောင်းပါတယ်။
အထွေထွေ ပုံစံ
let shuttingDown = false;
async function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true; // readiness now reports 503
setTimeout(() => process.exit(1), DEADLINE_MS).unref();
await waitForLoadBalancer();
await new Promise((resolve) => server.close(resolve));
await closeDependencies();
process.exitCode = 0;
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);Guard က တစ်ကြိမ်တည်း run အောင် လုပ်ပြီး unref လုပ်ထားတဲ့ timer က deadline ကို ကာကွယ်ပါတယ်။ Step တစ်ခုစီကို await လုပ်လို့ အစဉ်က ရှင်းလင်းပါတယ်။
Worked example: in-flight request ကို ပြီးအောင် drain လုပ်ခြင်း
ဒီ demo က server ကို port 0 ပေါ်မှာ ဖွင့်ပြီး 400 ms ကြာတဲ့ report request တစ်ခုကို စပါတယ်။ Request စပြီးတာနဲ့ process.emit('SIGTERM', 'SIGTERM') နဲ့ signal ကို simulate လုပ်ပါတယ် — Windows မှာ kill က SIGTERM handler ကို မခေါ်ပေးလို့ OS တိုင်းမှာ အတူတူ ဖြစ်အောင် ဒီနည်းကို သုံးတာပါ။ Grace period အတွင်း /ready က 503 ပြန်ပြီး report က ပြီးဆုံးကာ server ပိတ်ပြီးနောက် request အသစ်က ECONNREFUSED ရပါတယ်။ Client ဘက် ရလဒ်တွေကို shutdown ပြီးမှ print ထုတ်လို့ output အစဉ် မပြောင်းပါဘူး။
import { createServer } from 'node:http';
import { setTimeout as sleep } from 'node:timers/promises';
const READINESS_GRACE_MS = 250; // several seconds in production; short for the demo
const database = {
async close() {
await sleep(20);
console.log('database pool closed');
},
};
let shuttingDown = false;
let reportStarted;
let shutdownFinished;
const started = new Promise((resolve) => (reportStarted = resolve));
const finished = new Promise((resolve) => (shutdownFinished = resolve));
function send(res, status, body) {
if (shuttingDown) res.setHeader('Connection', 'close'); // no keep-alive while draining
res.statusCode = status;
res.end(body);
}
const server = createServer(async (req, res) => {
if (req.url === '/ready') {
return send(res, shuttingDown ? 503 : 200, shuttingDown ? 'draining' : 'ready');
}
console.log('slow report started');
reportStarted();
await sleep(400); // work that is already in flight when the signal arrives
send(res, 200, 'report done');
});
function closeServer() {
return new Promise((resolve, reject) => {
// close() stops new connections and calls back once in-flight requests end
server.close((err) => (err ? reject(err) : resolve()));
});
}
async function shutdown(signal) {
if (shuttingDown) return; // a second signal must not start a second cleanup
shuttingDown = true;
console.log(`${signal} received: readiness is now 503`);
const forceExit = setTimeout(() => {
console.error('drain deadline passed, forcing exit');
server.closeAllConnections();
process.exit(1);
}, 10_000);
forceExit.unref(); // this timer alone must not keep the process alive
await sleep(READINESS_GRACE_MS); // give the load balancer time to stop routing here
await closeServer();
console.log('http server closed: in-flight requests finished');
await database.close();
clearTimeout(forceExit);
process.exitCode = 0; // let Node exit on its own instead of calling process.exit()
shutdownFinished();
}
process.on('SIGTERM', shutdown); // container stop, kill <pid>
process.on('SIGINT', shutdown); // Ctrl+C in a terminal
// ---- simulate a deployment stopping this process ----
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const report = fetch(`${base}/report`).then((res) => res.text());
await started;
// Simulate the signal so the demo behaves the same on every OS:
process.emit('SIGTERM', 'SIGTERM');
const ready = await fetch(`${base}/ready`);
const readyText = `${ready.status} ${await ready.text()}`;
const reportText = await report;
await finished;
const late = await fetch(`${base}/ready`).catch((error) => error.cause?.code);
console.log(`client: /ready during grace -> ${readyText}`);
console.log(`client: in-flight report -> ${reportText}`);
console.log(`client: new request after close -> ${late}`);Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Idempotent guard
if (shuttingDown) return; // a second signal must not start a second cleanupSIGTERM ပြီးနောက် Ctrl+C ထပ်နှိပ်လည်း server.close() နဲ့ database.close() ကို ဒုတိယအကြိမ် မခေါ်ပါဘူး။
- Deadline that does not hold the process
forceExit.unref(); // this timer alone must not keep the process aliveCleanup 10 စက္ကန့်အတွင်း မပြီးရင် closeAllConnections() နဲ့ socket တွေကို ဖြတ်ပြီး exit code 1 နဲ့ ထွက်ပါတယ်။ unref ကြောင့် cleanup စောစော ပြီးရင် timer က process ကို 10 စက္ကန့် ဆွဲမထားပါဘူး။
- Stop keep-alive while draining
if (shuttingDown) res.setHeader('Connection', 'close'); // no keep-alive while drainingDrain လုပ်နေတုန်း ပြီးသွားတဲ့ response က keep-alive socket ကို ဖွင့်မထားလို့ server.close() ရဲ့ callback က client ရဲ့ idle timeout ကို စောင့်စရာ မလိုတော့ပါဘူး။
- Drain, then dependencies
await closeServer();Report request ပြီးမှ ဒီ await က ဆက်သွားလို့ database ကို request တစ်ခုခု သုံးနေတုန်း မပိတ်မိပါဘူး။
- Exit without process.exit()
process.exitCode = 0; // let Node exit on its own instead of calling process.exit()Server နဲ့ database ပိတ်ပြီးတဲ့အခါ event loop မှာ အလုပ် မကျန်တော့လို့ Node က ကိုယ့်ဘာသာ ထွက်ပြီး stdout ထဲက ကျန်နေတဲ့ log တွေကိုလည်း flush လုပ်ခွင့် ရပါတယ်။
slow report started
SIGTERM received: readiness is now 503
http server closed: in-flight requests finished
database pool closed
client: /ready during grace -> 503 draining
client: in-flight report -> report done
client: new request after close -> ECONNREFUSEDContainer ထဲမှာ signal က node ဆီ တကယ် ရောက်ရဲ့လား
Shutdown code ကောင်းကောင်း ရေးထားပေမဲ့ signal က node process ဆီ မရောက်ရင် အလကားပါ။ Dockerfile မှာ shell form (CMD node server.js) ကို သုံးရင် container ရဲ့ PID 1 က /bin/sh ဖြစ်ပြီး shell က signal ကို node ဆီ မပို့ပေးတတ်ပါဘူး။ npm start လို wrapper တွေကလည်း signal နဲ့ node ကြားမှာ process တစ်ခု ထပ်ထည့်ပါတယ်။ Exec form နဲ့ node ကို တိုက်ရိုက် run ပြီး PID 1 ပြဿနာအတွက် docker run --init ဒါမှမဟုတ် tini လို init process ကို သုံးပါ။
FROM node:22-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
USER node
# Exec form: node itself receives SIGTERM (no shell in between).
CMD ["node", "src/server.js"]| Platform | Stop ဖြစ်ပုံ |
|---|---|
| docker stop | SIGTERM၊ default 10 စက္ကန့် စောင့်၊ ပြီးရင် SIGKILL |
| Kubernetes | SIGTERM၊ terminationGracePeriodSeconds (default 30 s)၊ ပြီးရင် SIGKILL |
| Terminal | Ctrl+C က SIGINT ပို့ |
လက်တွေ့ project တွေမှာ
Production deploy တစ်ခုမှာ
Kubernetes rolling update တစ်ခုမှာ pod အသစ်တွေ ready ဖြစ်မှ pod အဟောင်းတွေကို SIGTERM ပို့ပါတယ်။ Service endpoint ကနေ pod ကို ဖယ်တာနဲ့ SIGTERM ပို့တာ တစ်ပြိုင်နက် ဖြစ်လို့ readiness grace period (ဒါမှမဟုတ် preStop sleep) မထားရင် signal ရပြီးနောက်မှာတောင် request အသစ်တွေ ဝင်လာနိုင်ပါတယ်။
- Grace period + drain + dependency ပိတ်ချိန် စုစုပေါင်းက terminationGracePeriodSeconds ထက် နည်းရပါမယ်၊ ဥပမာ 5 s grace၊ 15 s drain deadline၊ 30 s platform limit။
- Queue consumer တွေမှာ message အသစ် ယူတာ ရပ်ပြီး လက်ရှိ message ကို ack လုပ်ပြီးမှ ပိတ်ပါ၊ မဟုတ်ရင် message တွေ ထပ်ခါ process ဖြစ်ပါတယ်။
- WebSocket ဒါမှမဟုတ် server-sent events လို ရှည်လျားတဲ့ connection တွေက drain ကို အမြဲ ဆွဲထားနိုင်လို့ client တွေကို reconnect လုပ်ခိုင်းတဲ့ message ပို့ပြီး ပိတ်ပါ။
အမှားများ
Shutdown မှာ ဖြစ်လေ့ရှိတဲ့ အမှားများ
Signal handler ထဲမှာ process.exit() ကို ချက်ချင်း ခေါ်ခြင်း
In-flight response တွေ ဖြတ်ချခံရပြီး client တွေ 502 ရပါတယ်၊ transaction တွေ တစ်ဝက်တစ်ပျက် ကျန်ပြီး pipe ထဲက log line တွေ ပျောက်နိုင်ပါတယ်။ Server ကို drain လုပ်ပြီး dependency တွေ ပိတ်ကာ process.exitCode ကို သတ်မှတ်ပါ၊ process.exit() ကို deadline ပြည့်တဲ့ fallback အတွက်ပဲ ချန်ထားပါ။
Deadline မထားခြင်း
Hang ဖြစ်နေတဲ့ database query တစ်ခု ဒါမှမဟုတ် ပိတ်မသွားတဲ့ WebSocket တစ်ခုက server.close() ရဲ့ callback ကို အမြဲ ဆွဲထားနိုင်ပါတယ်။ Platform က SIGKILL နဲ့ သတ်တဲ့အထိ deploy တစ်ခုလုံး ကြာပြီး cleanup log တစ်ကြောင်းမှ မကျန်ပါဘူး။ unref လုပ်ထားတဲ့ force-exit timer ကို ထည့်ပါ။
Dependency ကို server မတိုင်ခင် ပိတ်ခြင်း
Database pool ကို အရင်ပိတ်ပြီးမှ server ကို drain လုပ်ရင် in-flight request တွေက 'pool is closed' error နဲ့ fail ဖြစ်ပါတယ်။ အစဉ်က အမြဲ: traffic ရပ်၊ request တွေ ပြီး၊ ပြီးမှ သူတို့ သုံးတဲ့ dependency တွေ ပိတ်ပါ။
Mini challenge
Mini challenge: idempotent shutdown + deadline
createShutdown(steps, { deadlineMs }) ကို ရေးပါ။ ပြန်ပေးတဲ့ shutdown(reason) function ကို ဘယ်နှခါ ခေါ်ခေါ် cleanup steps တွေ တစ်ကြိမ်တည်း run ရမယ်၊ ခေါ်သူတိုင်းက promise တစ်ခုတည်းကို ရရမယ်။ Step တွေကို အစဉ်လိုက် ပိတ်ပြီး deadline ကျော်ရင် exit code 1 နဲ့ resolve လုပ်ပါ။ SIGTERM နဲ့ SIGINT ကို process.emit နဲ့ ဆက်တိုက် simulate လုပ်ပြီး hang ဖြစ်နေတဲ့ step တစ်ခုနဲ့လည်း စမ်းပါ။
- ဒုတိယ ခေါ်ဆိုမှုက promise အသစ် မဖန်တီးဘဲ ပထမ promise ကို ပြန်ပေးရမယ်
- Step တွေကို for...of နဲ့ အစဉ်လိုက် await လုပ်ပါ
- Deadline ကို Promise.race နဲ့ ထည့်ပြီး ပြီးတာနဲ့ timer ကို clearTimeout လုပ်ပါ
- အောင်မြင်ရင် 0၊ deadline ကျော်ရင် 1 ကို resolve လုပ်ပါ
import { setTimeout as sleep } from 'node:timers/promises';
function createShutdown(steps, { deadlineMs }) {
let pending = null;
async function runSteps(reason) {
// TODO: log who started it, then await each [name, close] step in order
}
return function shutdown(reason) {
// TODO: if pending exists, return it
// TODO: race runSteps(reason) against a timer that resolves to 1
// TODO: clear the timer, log the outcome, return the exit code
};
}
// TODO: scenario 1 - three quick steps; emit SIGTERM then SIGINT,
// check that two calls return the very same promise
// TODO: scenario 2 - one step that never resolves, deadlineMs: 200ရလဒ်: Scenario 1 မှာ 'shutdown started by SIGTERM' တစ်ကြောင်းတည်း ထွက်ပြီး step သုံးခု အစဉ်လိုက် ပိတ်ကာ exit code 0 ရပါတယ်။ Scenario 2 မှာ http server ပိတ်ပြီးနောက် deadline of 200 ms hit (1) ပြပါတယ်။
အရိပ်အမြွက် ကြည့်ရန်
pending ကို promise chain တစ်ခုလုံး (race + then) နဲ့ assign လုပ်ပါ။ Deadline promise ကို setTimeout နဲ့ ကိုယ်တိုင် ဆောက်ပြီး cancel function ကို ထိန်းထားရင် step တွေ မြန်မြန်ပြီးတဲ့အခါ timer က process ကို ဆွဲမထားပါဘူး။
အဖြေ ကြည့်ရန်
import { setTimeout as sleep } from 'node:timers/promises';
function createShutdown(steps, { deadlineMs }) {
let pending = null;
async function runSteps(reason) {
console.log(`shutdown started by ${reason}`);
for (const [name, close] of steps) {
await close();
console.log(` closed ${name}`);
}
return 0;
}
function deadline() {
let timer;
const promise = new Promise((resolve) => {
timer = setTimeout(() => resolve(1), deadlineMs);
});
return { promise, cancel: () => clearTimeout(timer) };
}
return function shutdown(reason) {
if (pending) return pending; // later callers share the first run
const limit = deadline();
pending = Promise.race([runSteps(reason), limit.promise]).then((code) => {
limit.cancel();
console.log(code === 0 ? 'clean exit (0)' : `deadline of ${deadlineMs} ms hit (1)`);
return code;
});
return pending;
};
}
// Scenario 1: SIGTERM, then an impatient SIGINT while cleanup is still running.
const healthy = createShutdown([
['http server', () => sleep(30)],
['job queue', () => sleep(20)],
['database pool', () => sleep(10)],
], { deadlineMs: 1_000 });
process.once('SIGTERM', healthy);
process.once('SIGINT', healthy);
process.emit('SIGTERM', 'SIGTERM');
process.emit('SIGINT', 'SIGINT');
console.log('one shared promise:', healthy('again') === healthy('and again'));
console.log('exit code:', await healthy('final check'));
// Scenario 2: a dependency that never finishes closing.
const stuck = createShutdown([
['http server', () => sleep(10)],
['message broker', () => new Promise(() => {})], // hangs forever
], { deadlineMs: 200 });
const code = await stuck('SIGTERM');
console.log('a real process would now call process.exit(' + code + ')');Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Platform တွေက SIGTERM ပို့ပြီး deadline (docker 10 s၊ Kubernetes 30 s default) ပြည့်ရင် SIGKILL နဲ့ သတ်ပါတယ်။
- အစဉ်က: readiness 503 → LB ကို ခဏစောင့် → server.close() နဲ့ drain → dependency ပိတ် → exitCode သတ်မှတ်ပါ။
- Shutdown ကို guard နဲ့ idempotent ဖြစ်အောင် လုပ်ပြီး unref လုပ်ထားတဲ့ force-exit timer ထည့်ပါ။
- process.emit('SIGTERM', 'SIGTERM') က shutdown ကို OS မရွေး deterministic စမ်းသပ်နိုင်စေပါတယ်။
- Container ထဲမှာ exec form CMD နဲ့ node ကို တိုက်ရိုက် run ပြီး signal ရောက်ကြောင်း သေချာပါစေ။
Process — Node.js