Skip to content

[model-gateway] fix graceful shutdown for TLS/Non-TLS server#15491

Merged
slin1237 merged 1 commit intomainfrom
graceful-shutdown-fix
Dec 19, 2025
Merged

[model-gateway] fix graceful shutdown for TLS/Non-TLS server#15491
slin1237 merged 1 commit intomainfrom
graceful-shutdown-fix

Conversation

@slin1237
Copy link
Copy Markdown
Collaborator

The fix: Use axum_server for both TLS and non-TLS paths with graceful_shutdown(Some(duration)) to wait up to the configured grace period for existing connections (including streaming) to close.

Changes:

  • Use axum_server::bind for non-TLS (instead of axum::serve)
  • Use axum_server::bind_rustls for TLS
  • Both paths now use graceful_shutdown(Some(grace_period))
  • Add --shutdown-grace-period-secs CLI flag (default: 180s)
  • Python CLI: Added --shutdown-grace-period-secs argument
  • Python bindings: Added shutdown_grace_period_secs parameter

K8s users: Ensure terminationGracePeriodSeconds >= shutdown_grace_period_secs

Checklist

The issue: axum_server::Handle::graceful_shutdown(None) doesn't wait for
connections - it initiates shutdown immediately.

The fix: Use axum_server for both TLS and non-TLS paths with
graceful_shutdown(Some(duration)) to wait up to the configured grace period
for existing connections (including streaming) to close.

Changes:
- Use axum_server::bind for non-TLS (instead of axum::serve)
- Use axum_server::bind_rustls for TLS
- Both paths now use graceful_shutdown(Some(grace_period))
- Add --shutdown-grace-period-secs CLI flag (default: 180s)
- Python CLI: Added --shutdown-grace-period-secs argument
- Python bindings: Added shutdown_grace_period_secs parameter

K8s users: Ensure terminationGracePeriodSeconds >= shutdown_grace_period_secs
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @slin1237, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the robustness of the model gateway's shutdown process. By adopting axum_server and introducing a configurable grace period, the server can now gracefully handle termination signals, allowing ongoing requests, especially streaming ones, to finish processing. This prevents abrupt disconnections and potential data loss, leading to a more reliable and user-friendly service operation.

Highlights

  • Graceful Shutdown Implementation: The server now uses axum_server for both TLS and non-TLS paths, enabling a configurable graceful shutdown period to ensure in-flight requests complete before the server fully terminates.
  • Configurable Grace Period: A new --shutdown-grace-period-secs CLI flag has been introduced, allowing users to specify how long the server should wait for active connections to close during shutdown, with a default of 180 seconds.
  • Python Bindings Update: The Python CLI and bindings have been updated to expose the new shutdown_grace_period_secs parameter, making the graceful shutdown configuration accessible from Python.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request correctly implements graceful shutdown for both TLS and non-TLS servers by switching to axum_server and using its graceful_shutdown feature with a configurable grace period. The changes are well-implemented across the Python bindings and the Rust core. I've added a couple of suggestions to improve code clarity and maintainability: one to fix an incorrect comment about the default grace period, and another to refactor duplicated code for setting up the graceful shutdown logic.

pub request_timeout_secs: u64,
pub request_id_headers: Option<Vec<String>>,
/// Grace period in seconds to wait for in-flight requests during shutdown.
/// Default is 30 seconds.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The default value for shutdown_grace_period_secs is 180 seconds across the codebase, but this comment states it is 30 seconds. Please update the comment to reflect the correct default value to avoid confusion.

Suggested change
/// Default is 30 seconds.
/// Default is 180 seconds.

Comment on lines +1022 to +1032
let addr: std::net::SocketAddr = bind_addr
.parse()
.map_err(|e| format!("Invalid address: {}", e))?;

let handle = axum_server::Handle::new();
let handle_clone = handle.clone();
let grace_period = Duration::from_secs(config.shutdown_grace_period_secs);
spawn(async move {
shutdown_signal().await;
handle_clone.graceful_shutdown(Some(grace_period));
});
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This logic for parsing the address and setting up the graceful shutdown is duplicated from the TLS branch. To improve maintainability and reduce redundancy, consider extracting this common code to before the if/else block.

For example, you could refactor the if/else block to look like this:

    let addr: std::net::SocketAddr = bind_addr
        .parse()
        .map_err(|e| format!("Invalid address: {}", e))?;

    let handle = axum_server::Handle::new();
    let grace_period = Duration::from_secs(config.shutdown_grace_period_secs);

    // Spawn a task to gracefully shutdown the server.
    let handle_clone = handle.clone();
    spawn(async move {
        shutdown_signal().await;
        handle_clone.graceful_shutdown(Some(grace_period));
    });

    if let (Some(cert), Some(key)) = (
        &config.router_config.server_cert,
        &config.router_config.server_key,
    ) {
        info!("TLS enabled");
        ring::default_provider()
            .install_default()
            .map_err(|e| format!("Failed to install rustls ring provider: {:?}", e))?;

        let tls_config = axum_server::tls_rustls::RustlsConfig::from_pem(cert.clone(), key.clone())
            .await
            .map_err(|e| format!("Failed to create TLS config: {}", e))?;

        axum_server::bind_rustls(addr, tls_config)
            .handle(handle)
            .serve(app.into_make_service())
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
    } else {
        axum_server::bind(addr)
            .handle(handle)
            .serve(app.into_make_service())
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
    }

@slin1237 slin1237 merged commit 50cad01 into main Dec 19, 2025
69 of 70 checks passed
@slin1237 slin1237 deleted the graceful-shutdown-fix branch December 19, 2025 20:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant