Skip to content

Add graceful shutdown support to listener #58

@coolguy1771

Description

@coolguy1771

Proposal

The listener currently exits immediately upon context cancellation, which can orphan sessions and interrupt in-flight message processing. I propose adding a configurable ShutdownTimeout to ensure the listener has a dedicated window to close the session and clean up resources before the process terminates.

Proposed Changes

  1. Update Config: Add a ShutdownTimeout field (defaulting to 30s) to govern the cleanup phase.
  2. Instrument Run: Use a defer block with a background context to ensure the Close signal is sent even after the main context is cancelled.
type Config struct {
    ScaleSetID      int
    MaxRunners      int
    ShutdownTimeout time.Duration // Added
    Logger          *slog.Logger
}

func (l *Listener) Run(ctx context.Context, scaler Scaler) error {
    timeout := l.config.ShutdownTimeout
    if timeout == 0 {
        timeout = 30 * time.Second
    }
    
    defer func() {
        // Use background context because the parent ctx is already cancelled
        cleanupCtx, cancel := context.WithTimeout(context.Background(), timeout)
        defer cancel()
        
        l.logger.Info("shutting down; cleaning up session")
        if err := l.client.Close(cleanupCtx); err != nil {
            l.logger.Error("session cleanup failed", "error", err)
        } else {
            l.logger.Info("session closed successfully")
        }
    }()
    
    // ... main loop ...
}

Key Benefits

  • Reliability: Prevents "zombie" sessions from accumulating on the server side during deployments or restarts.
  • Visibility: Adds logging to the shutdown sequence to help debug hung listeners.
  • Safety: The use of a background context with a hard timeout ensures that the listener won't block indefinitely if the API is unresponsive during shutdown.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions