Skip to content

feat(api): fail readiness before an API server stops serving - #2343

Merged
Quick104 merged 4 commits into
mainfrom
feat/api-shutdown-readiness
Oct 12, 2026
Merged

Quick104 merged 4 commits into
mainfrom
feat/api-shutdown-readiness

Conversation

@Quick104

@Quick104 Quick104 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #2320
Validation tasks: none

An API server that is told to stop closes its listeners within milliseconds, while GET /api/v1/ready keeps answering 200 until the very end. A load balancer or Kubernetes therefore has no moment to route new requests to another replica first, and requests that arrive during a rolling restart fail. This change makes a stopping API server fail readiness first and keep serving for a few seconds before it shuts down.

Approach

On SIGTERM or SIGINT the API process marks itself as shutting down. /api/v1/ready then answers 503 with {"status":"shutting_down","postgres":…,"s3":…,"artwork":…}, the same shape as its other non-ok answers. The booleans report the last dependency probe, so the answer does not wait on a slow storage probe. The LAN discovery advertisement is withdrawn. The server keeps serving everything for SILO_SHUTDOWN_DELAY (a duration or whole seconds, default 5s, 0 skips the wait), then runs the existing graceful shutdown. A second signal ends the wait. /api/v1/health, the liveness probe, does not change, so nothing restarts the process while it waits.

The application context is now cancelled after the wait instead of at the signal, so background work keeps running while the server still answers requests. A restart request still stops at once, and ends the wait if it arrives during it: an administrator's restart has already told players the server is restarting, and the loss of storage admission sends one after it has stopped storage writers. A failed listener also stops the process at once, during the wait or not.

The example compose silo service and proxy get stop_grace_period: 2m, since Docker's default 10-second kill already cut the existing 30-second graceful shutdown short. The development compose file and make dev-backend set the delay to 0, because air kills the process half a second after interrupting it. docs/architecture/api-shutdown.md describes the sequence and the Docker and Kubernetes settings, and the retained probe contract in api-contract.md records shutting_down as an additive status, like degraded.

No client calls /api/v1/ready; the Apple and Android reachability checks read /api/v1/health, which does not change. The Jellyfin-compatible and Audiobookshelf-compatible listeners have no readiness probe and close as before. Transcode nodes drain separately in #2340.

Validation

  • Before, on a sandbox, polling every 100 ms through a SIGTERM to the API: readiness answered 200 ok until the listener closed 5 ms after the signal, then connections were refused.
  • After: readiness answered 503 shutting_down within 100 ms of the signal while health stayed 200, and the graceful shutdown began 5.0 s later. A second SIGTERM one second after the first started the shutdown at once.
  • Unit tests cover the readiness answer while shutting down (without waiting on a new probe) and without a signal, the delay parsing, and the wait ending after its delay, at a second signal, a restart request or a listener error.
  • go build, go vet and make lint-changed (0 issues) pass, as do the tests of internal/api, internal/api/handlers, internal/scenariocatalog, internal/contractledger and cmd/silo. No web or generated contract changes.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/api-shutdown-readiness/

Risks

  • Every stop of an API server by signal now takes SILO_SHUTDOWN_DELAY longer, 5 seconds by default. A single server with no load balancer can set it to 0.
  • Background work (schedulers, scans, the node health sweep) keeps running for those seconds instead of stopping at the signal, and work it starts then is cut when the shutdown begins, as it would be a moment later anyway.
  • nodeDrainTimeout in feat(nodes): drain transcode nodes before they stop #2340 parses its variable the same way; whichever pull request merges second can share one helper.
  • A monitor that treats any non-200 readiness as an outage alerts for the seconds a server spends stopping.

Follow-ups

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code, running in T3 Code
  • Tool(s): Claude Code subagents; Codex CLI through T3 Code task delegation
  • Model(s): claude-opus-5-5 (implementation and review), claude-sonnet-5-5 (review finder), gpt-6.1-sol (adversarial review)
  • Involvement: Fully AI-generated; maintainer review pending
  • Adversarial review: a multi-agent Claude review (two finders, one on correctness and contracts, one on cleanup and conventions) checked the diff. It found that a restart request after lost storage admission would have kept serving with storage writers stopped, that air would kill the dev server mid-wait, that LAN discovery kept advertising during the wait, an overflow in the seconds form, an unbounded test wait, and stale docs (grace-period sizing, blob-storage.md, listener scope). All were fixed. A background Codex (gpt-6.1-sol) review then found that a restart request, storage admission loss or listener failure arriving during the wait stayed queued until the delay ended. The wait now stops at once for each. A Kody review then found that readiness probed its dependencies before checking for shutdown, so a hung storage probe could delay the shutting_down answer by the whole default delay; it now reports the last probe.

🤖 Generated with Claude Code

An API server that is told to stop now answers /api/v1/ready with 503
shutting_down and keeps serving for SILO_SHUTDOWN_DELAY (default 5s) before
its listeners close, so load balancers and Kubernetes route new requests away
first. A second signal skips the wait. Liveness is unchanged.

Refs #2320

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 9 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4bb31d64-b117-4ea2-bd8a-732a01991122

📥 Commits

Reviewing files that changed from the base of the PR and between f5c2aff and 3d59e95.


📒 Files selected for processing (4)
  • docs/architecture/api-contract.md
  • docs/architecture/api-shutdown.md
  • internal/api/handlers/health.go
  • internal/api/handlers/ready_shutdown_test.go

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 85775f91-1c7e-4bd1-aaa2-cdaa758bff48






📥 Commits

Reviewing files that changed from the base of the PR and between a8bb5e0 and f5c2aff.







📒 Files selected for processing (4)
  • cmd/silo/api_shutdown.go
  • cmd/silo/api_shutdown_test.go
  • cmd/silo/main.go
  • docs/architecture/api-shutdown.md






🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/architecture/api-shutdown.md






Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.








📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The API readiness endpoint now reports when shutdown begins. Signal-triggered shutdown withdraws LAN discovery, waits for a configurable delay or a second signal, then cancels the application context. Development and deployment configuration and documentation describe the delay.

Changes

API Shutdown

Layer / File(s) Summary
Shutdown-aware readiness
internal/api/router.go, internal/api/handlers/health.go, cmd/silo/main.go, internal/api/handlers/ready_shutdown_test.go, docs/architecture/api-contract.md, docs/architecture/blob-storage.md
The readiness handler receives a shutdown callback. When it reports shutdown, readiness returns HTTP 503 with status shutting_down and dependency health fields. Tests cover the shutdown response and the unset callback.
Signal-triggered shutdown
cmd/silo/api_shutdown.go, cmd/silo/main.go, cmd/silo/api_shutdown_test.go
Signal-triggered shutdown stops LAN discovery, marks readiness as shutting down, and waits for the configured delay or a second signal before canceling the application context. Restart requests and listener failures remain immediate shutdown paths. Tests cover delay parsing and stop coordination.
Shutdown configuration and deployment guidance
Makefile, docker-compose.dev.yml, docker-compose.yml, docs/architecture/api-shutdown.md
Development settings use a zero delay. Compose examples set a two-minute stop grace period. The guide describes readiness and liveness probes, termination grace periods, and load-balancer polling.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Signal
  participant main
  participant LANDiscovery
  participant waitForAPIStop
  participant ReadyHandler
  participant ApplicationContext
  Signal->>main: SIGTERM or SIGINT
  main->>waitForAPIStop: Pass delay, signal, restart, and server-error channels
  waitForAPIStop->>ReadyHandler: Mark readiness as shutting down
  waitForAPIStop->>LANDiscovery: Cancel lanCtx
  ReadyHandler->>ReadyHandler: Return 503 with status shutting_down
  waitForAPIStop->>waitForAPIStop: Wait for delay or an early stop event
  waitForAPIStop->>main: Return
  main->>ApplicationContext: Cancel app context
Loading
















Merge Risk: ⚪ Minimal · up to f5c2a

The shutdown-readiness change is mergeable after normal checks. No actionable issue is established by the supplied evidence.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 6 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check Passed The description clearly explains the shutdown-readiness change, affected endpoints, configuration, validation, risks, and follow-ups.
Linked Issues check Passed The description links the change to issue #2320 and identifies related follow-up work, including #2340.
Out of Scope Changes check Passed The implementation, configuration, tests, and documentation changes directly support the shutdown-readiness objective.
Title check Passed The title concisely and accurately describes the main change: failing API readiness before the server stops serving.


Full details: Docstring Coverage

Explanation

Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 6 files. (1 skipped: 1 unsupported.)




✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR









🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR











  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adversarial review (gpt-6.1-sol, reviewed a8bb5e0)

One verified finding below. Focused package suites passed with -race: cmd/silo, internal/api, internal/api/handlers, internal/scenariocatalog, and internal/contractledger. A concurrent readiness check also passed. The finding was reproduced with the production delay helper and the shutdown select extracted from main.go; storage-admission loss was simulated. Live storage transitions and Kubernetes propagation were not exercised.

AI disclosure: gpt-6.1-sol; Codex via T3 Code.

Comment thread cmd/silo/main.go Resolved
A restart request, storage admission loss or listener failure that arrived
during SILO_SHUTDOWN_DELAY stayed queued until the delay ended, so the
listeners kept serving after storage writers had stopped. The wait now
watches all of them and stops at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread cmd/silo/main.go Resolved
Comment thread internal/api/handlers/health.go Resolved
Readiness probed PostgreSQL, S3 and artwork storage before it checked for
shutdown, so a hung storage probe could hold back the shutting_down answer
for up to five seconds, the whole default delay. While shutting down it now
reports the last probe results instead of probing again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Comment thread internal/api/handlers/health.go Resolved
Readiness read the shutdown flag before probing, so a request whose probes
spanned the signal still answered 200. It reads the flag again after
probing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104
Quick104 merged commit 812aca4 into main Oct 12, 2026
28 checks passed
@Quick104
Quick104 deleted the feat/api-shutdown-readiness branch October 12, 2026 13:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant