Skip to content

Commit 15ee52c

Browse files
authored
fix(den-api): finish in-flight requests on deploy instead of cutting them at 3s (#6386)
Render sends SIGTERM 60s after moving traffic and SIGKILLs after maxShutdownDelaySeconds (300s on api-private). cloudflared keeps pooled connections to the old instance, so requests still land there after the switch. The old handler force-closed every connection 3s after SIGTERM and gave background loops the same 3s, killing work mid-way. - Drain in-flight requests and background loops together for a fixed 240s. - Send Connection: close while draining so keep-alive callers reconnect to the new instance; sweep idle sockets. - Close long-lived GET event streams at drain start; their clients resume on the new instance. POST event streams (MCP tool calls) drain normally. - /ready answers 503 with draining: true; /health is unchanged.
1 parent 102afd8 commit 15ee52c

9 files changed

Lines changed: 493 additions & 82 deletions

File tree

‎ee/apps/den-api/src/app.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ import { preclaimScopeMiddleware } from "./middleware/preclaim-scope.js"
6161
import { auditRequestMiddleware } from "./audit/request-capture.js"
6262
import { isOperationalErrorPath, normalizeOperationalErrorResponse, operationalErrorResponse } from "./operational-errors.js"
6363
import { sanitizePublicResponseHeaders } from "./public-response-headers.js"
64+
import { isDraining } from "./drain-state.js"
6465
import { AUTOMATION_MODEL_ATTENTION_CAPABILITY_HEADER } from "@openwork/types/automations"
6566

6667
type AppVariables = RequestIdVariables & AuthContextVariables & Partial<UserOrganizationsContext> & Partial<OrganizationContextVariables> & Partial<MemberTeamsContext>
@@ -77,6 +78,7 @@ const readinessResponseSchema = z.object({
7778
checks: z.object({
7879
database: z.enum(["ok", "error"]),
7980
}),
81+
draining: z.boolean().optional().meta({ description: "True while this instance shuts down and finishes its in-flight requests." }),
8082
}).meta({ ref: "DenApiReadinessResponse" })
8183

8284
const openApiDocumentSchema = z.object({
@@ -262,21 +264,26 @@ app.get(
262264
tags: ["System"],
263265
security: [],
264266
summary: "Check den-api readiness",
265-
description: "Verifies den-api can reach its database dependency.",
267+
description: "Verifies den-api can reach its database dependency and is not shutting down.",
266268
responses: {
267269
200: jsonResponse("den-api is ready to serve traffic.", readinessResponseSchema),
268270
503: jsonResponse("den-api is not ready to serve traffic.", readinessResponseSchema),
269271
},
270272
}),
271273
publicRoute,
272274
async (c) => {
275+
let database: "ok" | "error" = "ok"
273276
try {
274277
await db.execute(sql`select 1`)
275-
return c.json({ ok: true, service: "den-api", checks: { database: "ok" } })
276278
} catch (error) {
277279
appLogger.error("readiness database check failed", { component: "readiness", error })
278-
return c.json({ ok: false, service: "den-api", checks: { database: "error" } }, 503)
280+
database = "error"
279281
}
282+
// A draining instance still finishes in-flight work but must not look
283+
// ready for new traffic.
284+
if (isDraining()) return c.json({ ok: false, service: "den-api", checks: { database }, draining: true }, 503)
285+
if (database === "error") return c.json({ ok: false, service: "den-api", checks: { database } }, 503)
286+
return c.json({ ok: true, service: "den-api", checks: { database } })
280287
},
281288
)
282289

‎ee/apps/den-api/src/drain-state.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// Set once when this process starts its graceful shutdown. `/ready` reads it
2+
// so nothing treats a draining instance as ready for new traffic.
3+
let draining = false
4+
5+
export function markDraining(): void {
6+
draining = true
7+
}
8+
9+
export function isDraining(): boolean {
10+
return draining
11+
}
Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
import { ServerResponse, type IncomingMessage, type Server } from "node:http"
2+
import type { Http2Bindings, HttpBindings } from "@hono/node-server"
3+
4+
/**
5+
* Graceful shutdown for den-api.
6+
*
7+
* Render runs zero-downtime deploys: it moves traffic to the new instance,
8+
* waits 60s, sends SIGTERM to the old one, then SIGKILLs it after the
9+
* service's shutdown delay (`maxShutdownDelaySeconds`, 300s for den-api,
10+
* Render's maximum). Requests can still reach the old instance after the
11+
* switch because cloudflared keeps its pooled connections to it, so the old
12+
* instance must finish what it is already doing instead of cutting it off.
13+
*
14+
* On the first signal we:
15+
* - report draining (`/ready` answers 503),
16+
* - stop accepting connections and ask keep-alive callers to reconnect,
17+
* which lands their next request on the new instance,
18+
* - close long-lived GET event streams at once: they never finish on their
19+
* own, and their clients resume on the new instance with Last-Event-ID,
20+
* - stop background loops alongside the request drain,
21+
* - wait for both, bounded by one fixed drain deadline, then exit.
22+
* A second signal exits immediately.
23+
*/
24+
25+
/**
26+
* Fixed request and background-work drain. With the after-stop work and the
27+
* final socket close it stays inside Render's 300s shutdown delay.
28+
*/
29+
export const DEN_SHUTDOWN_DRAIN_MS = 240_000
30+
31+
export type GracefulShutdownOptions = {
32+
/** Max time to wait for in-flight requests and background work after the first signal. */
33+
drainTimeoutMs: number
34+
/** Called once when draining starts, before anything else. */
35+
onDrainStart?: () => void
36+
/** Stops background loops. Runs alongside the request drain and shares its deadline. */
37+
stopBackgroundWork?: () => Promise<void>
38+
/** Work to finish after requests and background work stop (telemetry flush). */
39+
afterStop?: () => Promise<void>
40+
afterStopTimeoutMs?: number
41+
/** How often idle keep-alive sockets and event streams are closed while draining. */
42+
sweepMs?: number
43+
exit?: (code: number) => void
44+
log?: (message: string, details?: Record<string, unknown>) => void
45+
signals?: NodeJS.Signals[]
46+
processTarget?: Pick<NodeJS.Process, "on" | "off">
47+
}
48+
49+
export type GracefulShutdown = {
50+
isDraining: () => boolean
51+
activeRequests: () => number
52+
shutdown: (reason: string) => Promise<void>
53+
dispose: () => void
54+
}
55+
56+
type DenFetch = (request: Request, env: HttpBindings | Http2Bindings) => Response | Promise<Response>
57+
58+
// Responses that are long-lived GET event streams. Filled by trackEventStreams
59+
// before @hono/node-server writes the response, read when draining.
60+
const eventStreams = new WeakSet<ServerResponse>()
61+
62+
function isEventStream(request: Request, response: Response) {
63+
return request.method === "GET"
64+
&& (response.headers.get("content-type") ?? "").toLowerCase().startsWith("text/event-stream")
65+
}
66+
67+
/**
68+
* Wraps the app's fetch so shutdown can tell which responses are long-lived
69+
* GET event streams. Only GET streams are closed early: a POST that answers
70+
* with an event stream (an MCP tool call) is real work and drains normally.
71+
*/
72+
export function trackEventStreams(fetch: DenFetch): DenFetch {
73+
return async (request, env) => {
74+
const response = await fetch(request, env)
75+
if (env.outgoing instanceof ServerResponse && isEventStream(request, response)) eventStreams.add(env.outgoing)
76+
return response
77+
}
78+
}
79+
80+
async function withTimeout<T>(work: Promise<T>, ms: number): Promise<"done" | "timeout"> {
81+
let timer: ReturnType<typeof setTimeout> | undefined
82+
const timeout = new Promise<"timeout">((resolve) => {
83+
timer = setTimeout(() => resolve("timeout"), ms)
84+
timer.unref()
85+
})
86+
try {
87+
return await Promise.race([work.then(() => "done" as const), timeout])
88+
} finally {
89+
clearTimeout(timer)
90+
}
91+
}
92+
93+
function describeError(error: unknown) {
94+
return error instanceof Error ? error.message : String(error)
95+
}
96+
97+
export function installGracefulShutdown(server: Server, options: GracefulShutdownOptions): GracefulShutdown {
98+
const exit = options.exit ?? ((code: number) => process.exit(code))
99+
const log = options.log ?? ((message, details) => console.log(`[shutdown] ${message}`, details ?? ""))
100+
const target = options.processTarget ?? process
101+
const signals = options.signals ?? ["SIGTERM", "SIGINT"]
102+
const sweepMs = options.sweepMs ?? 1_000
103+
const afterStopTimeoutMs = options.afterStopTimeoutMs ?? 5_000
104+
105+
let draining = false
106+
let shutdownPromise: Promise<void> | undefined
107+
const responses = new Set<ServerResponse>()
108+
const idleWaiters = new Set<() => void>()
109+
110+
// Keep-alive callers (cloudflared) pool connections to this instance. Ask
111+
// them to open a fresh connection for their next request, which reaches a
112+
// live instance, instead of closing the socket under them.
113+
function askToReconnect(response: ServerResponse) {
114+
if (!response.headersSent) response.setHeader("Connection", "close")
115+
}
116+
117+
function closeEventStreams() {
118+
for (const response of responses) {
119+
if (eventStreams.has(response)) response.destroy()
120+
}
121+
}
122+
123+
const onRequest = (_request: IncomingMessage, response: ServerResponse) => {
124+
responses.add(response)
125+
if (draining) askToReconnect(response)
126+
response.on("close", () => {
127+
responses.delete(response)
128+
if (responses.size === 0) for (const resolve of idleWaiters) resolve()
129+
})
130+
}
131+
server.on("request", onRequest)
132+
133+
function waitForRequests() {
134+
if (responses.size === 0) return Promise.resolve()
135+
return new Promise<void>((resolve) => {
136+
const done = () => {
137+
idleWaiters.delete(done)
138+
resolve()
139+
}
140+
idleWaiters.add(done)
141+
})
142+
}
143+
144+
function stopBackgroundWork() {
145+
if (!options.stopBackgroundWork) return Promise.resolve()
146+
return options.stopBackgroundWork().catch((error: unknown) => {
147+
log("background work shutdown failed", { error: describeError(error) })
148+
})
149+
}
150+
151+
async function run(reason: string) {
152+
draining = true
153+
options.onDrainStart?.()
154+
for (const response of responses) askToReconnect(response)
155+
const startedAt = Date.now()
156+
log("draining", { reason, activeRequests: responses.size, drainTimeoutMs: options.drainTimeoutMs })
157+
158+
const closed = new Promise<void>((resolve) => server.close(() => resolve()))
159+
closeEventStreams()
160+
server.closeIdleConnections()
161+
const sweep = setInterval(() => {
162+
closeEventStreams()
163+
server.closeIdleConnections()
164+
}, sweepMs)
165+
sweep.unref()
166+
167+
let requestsDone = false
168+
let backgroundDone = false
169+
const requests = waitForRequests().then(() => { requestsDone = true })
170+
const background = stopBackgroundWork().then(() => { backgroundDone = true })
171+
const drained = await withTimeout(Promise.all([requests, background]), options.drainTimeoutMs)
172+
clearInterval(sweep)
173+
174+
if (!requestsDone) {
175+
log("request drain timed out, closing remaining connections", { activeRequests: responses.size })
176+
server.closeAllConnections()
177+
} else {
178+
server.closeIdleConnections()
179+
}
180+
if (!backgroundDone) log("background work did not stop before the drain deadline")
181+
await withTimeout(closed, 1_000)
182+
183+
if (options.afterStop) {
184+
const flushed = await withTimeout(options.afterStop().catch((error: unknown) => {
185+
log("after-stop work failed", { error: describeError(error) })
186+
}), afterStopTimeoutMs)
187+
if (flushed === "timeout") log("after-stop work timed out", { afterStopTimeoutMs })
188+
}
189+
190+
log("stopped", { reason, drained: drained === "done", elapsedMs: Date.now() - startedAt })
191+
}
192+
193+
function shutdown(reason: string) {
194+
shutdownPromise ??= run(reason)
195+
return shutdownPromise
196+
}
197+
198+
const handlers = new Map<NodeJS.Signals, () => void>()
199+
for (const signal of signals) {
200+
const handler = () => {
201+
if (shutdownPromise) {
202+
log("second signal, exiting now", { signal, activeRequests: responses.size })
203+
exit(1)
204+
return
205+
}
206+
void shutdown(signal).then(
207+
() => exit(0),
208+
(error: unknown) => {
209+
log("shutdown failed", { error: describeError(error) })
210+
exit(1)
211+
},
212+
)
213+
}
214+
handlers.set(signal, handler)
215+
target.on(signal, handler)
216+
}
217+
218+
return {
219+
isDraining: () => draining,
220+
activeRequests: () => responses.size,
221+
shutdown,
222+
dispose() {
223+
server.off("request", onRequest)
224+
for (const [signal, handler] of handlers) target.off(signal, handler)
225+
},
226+
}
227+
}

‎ee/apps/den-api/src/server.ts‎

Lines changed: 13 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
import { Server } from "node:http"
12
import { DEN_HTTP_KEEP_ALIVE_TIMEOUT_MS, serveDenHttp } from "./http-server.js"
3+
import { DEN_SHUTDOWN_DRAIN_MS, installGracefulShutdown, trackEventStreams } from "./graceful-shutdown.js"
4+
import { markDraining } from "./drain-state.js"
25
import app from "./app.js"
36
import { startSlackAssistantWorker } from "./slack-assistant/worker.js"
47
import { startSlackDesktopHandoffWorker } from "./slack-assistant/desktop-handoff.js"
@@ -33,55 +36,14 @@ appLogger.info("external mcp implementation selected", { component: "server", ru
3336
// dev outbox) and must not be reachable from the LAN; production/default
3437
// behavior (all interfaces) is unchanged when DEN_BIND_HOST is unset.
3538
const bindHost = process.env.DEN_BIND_HOST?.trim()
36-
const server = serveDenHttp({ fetch: app.fetch, port: env.port, ...(bindHost ? { hostname: bindHost } : {}) }, (info) => {
39+
const server = serveDenHttp({ fetch: trackEventStreams(app.fetch), port: env.port, ...(bindHost ? { hostname: bindHost } : {}) }, (info) => {
3740
markServerListening()
3841
appLogger.info("server listening", { component: "server", port: info.port, keep_alive_timeout_ms: DEN_HTTP_KEEP_ALIVE_TIMEOUT_MS })
3942
})
4043

41-
let shuttingDown = false
42-
const SERVER_CLOSE_TIMEOUT_MS = 3_000
43-
const BACKGROUND_STOP_TIMEOUT_MS = 3_000
44-
const OBSERVABILITY_SHUTDOWN_TIMEOUT_MS = 2_500
45-
46-
type CloseAllConnectionsServer = {
47-
closeAllConnections: () => void
48-
}
49-
50-
function canCloseAllConnections(value: object): value is CloseAllConnectionsServer {
51-
return "closeAllConnections" in value && typeof value.closeAllConnections === "function"
52-
}
53-
54-
function withTimeout<T>(label: string, promise: Promise<T>, timeoutMs: number): Promise<T> {
55-
let timer: ReturnType<typeof setTimeout> | undefined
56-
const timeout = new Promise<T>((_resolve, reject) => {
57-
timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs)
58-
timer.unref()
59-
})
60-
61-
return Promise.race([promise, timeout]).finally(() => {
62-
if (timer) {
63-
clearTimeout(timer)
64-
}
65-
})
66-
}
67-
68-
async function closeServer() {
69-
const closePromise = new Promise<void>((resolve) => {
70-
server.close(() => resolve())
71-
})
44+
if (!(server instanceof Server)) throw new Error("den-api expects an HTTP/1.1 server")
7245

73-
try {
74-
await withTimeout("server close", closePromise, SERVER_CLOSE_TIMEOUT_MS)
75-
} catch (error) {
76-
appLogger.warn("server close did not finish before timeout", { component: "server", error })
77-
if (canCloseAllConnections(server)) {
78-
server.closeAllConnections()
79-
}
80-
await withTimeout("server force close", closePromise, 1_000).catch((forceError) => {
81-
appLogger.error("server force close did not finish", { component: "server", error: forceError })
82-
})
83-
}
84-
}
46+
const OBSERVABILITY_SHUTDOWN_TIMEOUT_MS = 2_500
8547

8648
async function stopBackgroundLoops() {
8749
stopModelsAnalyticsExportLoop()
@@ -104,37 +66,11 @@ async function stopBackgroundLoops() {
10466
}
10567
}
10668

107-
async function shutdown(signal: "SIGTERM" | "SIGINT") {
108-
if (shuttingDown) {
109-
appLogger.warn("second shutdown signal received", { component: "server", signal })
110-
process.exit(1)
111-
return
112-
}
113-
shuttingDown = true
114-
115-
appLogger.info("shutdown requested", { component: "server", signal })
116-
await withTimeout("background loop shutdown", stopBackgroundLoops(), BACKGROUND_STOP_TIMEOUT_MS).catch((error) => {
117-
appLogger.error("background loop shutdown timed out", { component: "server", error })
118-
})
119-
await closeServer()
120-
await withTimeout("observability shutdown", shutdownObservability(), OBSERVABILITY_SHUTDOWN_TIMEOUT_MS).catch((error) => {
121-
appLogger.error("observability shutdown failed", { component: "server", error })
122-
})
123-
}
124-
125-
process.on("SIGTERM", () => {
126-
void shutdown("SIGTERM")
127-
.then(() => process.exit(0))
128-
.catch((error) => {
129-
appLogger.error("shutdown failed", { component: "server", error })
130-
process.exit(1)
131-
})
132-
})
133-
process.on("SIGINT", () => {
134-
void shutdown("SIGINT")
135-
.then(() => process.exit(0))
136-
.catch((error) => {
137-
appLogger.error("shutdown failed", { component: "server", error })
138-
process.exit(1)
139-
})
69+
installGracefulShutdown(server, {
70+
drainTimeoutMs: DEN_SHUTDOWN_DRAIN_MS,
71+
onDrainStart: markDraining,
72+
stopBackgroundWork: stopBackgroundLoops,
73+
afterStop: shutdownObservability,
74+
afterStopTimeoutMs: OBSERVABILITY_SHUTDOWN_TIMEOUT_MS,
75+
log: (message, details) => appLogger.info(`shutdown: ${message}`, { component: "server", ...details }),
14076
})

0 commit comments

Comments
 (0)