# Close a KubeMQ Ruby Client (/sdks/ruby/how-to/connection/close)



## Overview [#overview]

Closing a client isn't an afterthought — it tells the broker and your own process that this connection is done, so both sides release what they were holding for it. A KubeMQ client is more than a socket: it's a gRPC channel plus whatever subscriptions and buffered messages it's servicing. Skip the close and those linger — subscriptions keep streaming, the channel stays open — and in short-lived scripts or test suites you leak connections until the process exits.

Calling `close` cancels active subscriptions, flushes the message buffer, and closes the underlying gRPC channel. Once it returns, `closed?` flips to `true` for the rest of the client's lifetime.

**Gotchas:** the drain window is bounded, not unlimited, so a slow consumer can still lose the tail of a burst if you close mid-stream; a closed client is dead forever — no reconnect on the same instance, build a new one; and `close` is idempotent, so calling it a second time is safe, but any other method call after closing raises `ClientClosedError`.

## Prerequisites [#prerequisites]

* KubeMQ server running on `localhost:50000`
* Ruby SDK installed (`gem install kubemq`)

## Code [#code]

```ruby title="main.rb"
require 'kubemq'

address = ENV.fetch('KUBEMQ_ADDRESS', 'localhost:50000')

begin
  client = KubeMQ::PubSubClient.new(address: address, client_id: 'close-example')
  puts "Connected to #{address}"

  info = client.ping
  puts "Ping OK: host=#{info.host}, version=#{info.version}"

  client.close
  puts "Client closed (closed?=#{client.closed?})"

  client.close
  puts 'Second close is safe (idempotent)'
rescue KubeMQ::Error => e
  puts "KubeMQ error: #{e.message}"
end
```

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

* `close` cancels active subscriptions, flushes the message buffer, and closes the gRPC channel.
* Calling `close` multiple times is safe — the method is idempotent.
* After closing, `closed?` returns `true` and further operations raise `ClientClosedError`.

## Related [#related]

* [Ruby SDK Reference](/sdks/ruby/reference)
* [Connect](/sdks/ruby/tutorials/connect)
* [Graceful Shutdown](/sdks/ruby/how-to/error-handling/graceful-shutdown)
