# Connect (/sdks/elixir/tutorials/connect)



## Overview [#overview]

Every KubeMQ application starts the same way: open a connection to the broker and prove it actually works before building anything on top of it. This tutorial is that first lesson — start a client process, give it a stable identity, and confirm connectivity with a state check, so the pattern is muscle memory before you move on to real messaging.

`KubeMQ.Client.start_link/1` takes an `address` and a `client_id` — the ID tags this connection in broker logs, subscriptions, and management views — and starts a supervised GenServer process that opens the gRPC connection. `connection_state/1` and `connected?/1` verify the connection cheaply, reflecting the process's live state rather than just whether it was created. `close/1` shuts the GenServer down and releases the underlying gRPC resources.

**Gotchas:** `{:ok, client}` from `start_link/1` doesn't always mean the broker is reachable — the GenServer can start before the connection settles, so checking `connected?/1` is the only reliable proof; reusing the same client ID across running instances causes routing confusion on the broker; and forgetting to call `close/1` in quick scripts is a common source of leaked processes and connections under load.

## Prerequisites [#prerequisites]

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

## Code [#code]

```elixir title="main.exs"
IO.puts("Connecting to KubeMQ server...")

case KubeMQ.Client.start_link(address: "localhost:50000", client_id: "elixir-connect-example") do
  {:ok, client} ->
    IO.puts("Connected successfully!")
    IO.puts("Connection state: #{KubeMQ.Client.connection_state(client)}")
    IO.puts("Connected? #{KubeMQ.Client.connected?(client)}")
    KubeMQ.Client.close(client)
    IO.puts("Done.")

  {:error, reason} ->
    IO.puts("Connection failed: #{inspect(reason)}")
end
```

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

* `KubeMQ.Client.start_link/1` starts a GenServer and establishes a gRPC connection
* `connection_state/1` returns the current connection state atom
* `connected?/1` returns a boolean indicating active connectivity
* `close/1` gracefully shuts down the GenServer and releases resources

## Related [#related]

* [Elixir SDK Reference](/sdks/elixir/reference)
* [Close](/sdks/elixir/how-to/connection/close)
* [Ping](/sdks/elixir/how-to/connection/ping)
