# Graceful Shutdown (/sdks/elixir/how-to/error-handling/graceful-shutdown)



## Overview [#overview]

A **graceful shutdown** stops a KubeMQ client without dropping in-flight messages or leaking server-side subscription state. Killing a process outright, or closing the client while a subscription is still active, can truncate a handler or leave the server thinking a consumer is still there. In a container platform that sends `SIGTERM` before force-killing a pod, an orderly shutdown sequence turns a rolling deploy into a clean handoff instead of a burst of errors.

The pattern has a fixed order: stop new work by cancelling every active subscription, then close the client so its connection and remaining resources are released. `KubeMQ.Subscription.cancel/1` stops one subscription at a time, and only once all of them return `:ok` does `KubeMQ.Client.close/1` tear down the connection.

**Gotchas:** closing the client before every subscription is cancelled can leave orphaned subscriptions consuming server resources. `cancel/1` returning `:ok` confirms the request was accepted, not that an in-flight callback has finished running.

## Prerequisites [#prerequisites]

* KubeMQ server running on `localhost:50000`
* Elixir SDK installed (`{:kubemq, "~> 1.0"}` in mix.exs)

## Code [#code]

```elixir title="main.exs"
channel = "elixir-error-handling.graceful-shutdown"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "elixir-shutdown")

{:ok, sub1} =
  KubeMQ.Client.subscribe_to_events(client, channel,
    on_event: fn _event -> :ok end
  )

{:ok, sub2} =
  KubeMQ.Client.subscribe_to_events(client, "#{channel}.other",
    on_event: fn _event -> :ok end
  )

IO.puts("Active subscriptions: sub1=#{KubeMQ.Subscription.active?(sub1)}, sub2=#{KubeMQ.Subscription.active?(sub2)}")

IO.puts("Starting graceful shutdown...")

:ok = KubeMQ.Subscription.cancel(sub1)
IO.puts("  Sub1 cancelled")

:ok = KubeMQ.Subscription.cancel(sub2)
IO.puts("  Sub2 cancelled")

KubeMQ.Client.close(client)
IO.puts("  Client closed")

IO.puts("Shutdown complete. All resources cleaned up.")
```

## How It Works [#how-it-works]

* Cancel each subscription individually with `Subscription.cancel/1`
* Close the client connection after all subscriptions are cancelled
* This prevents orphaned subscriptions from consuming server resources

## Related [#related]

* [Close](/sdks/elixir/how-to/connection/close)
* [Connection Error](/sdks/elixir/how-to/error-handling/connection-error)
