# Connecting to SurrealDB

The Kotlin SDK connects to SurrealDB over WebSocket or HTTP, with automatic transport selection and reconnection.

The first step towards interacting with [SurrealDB](/docs) is to create a connection to a database instance. This involves constructing a [`SurrealClient`](/docs/reference/kotlin/api/core/surreal-client.md) with a [`SurrealClientConfig`](/docs/reference/kotlin/api/core/client-config.md), then selecting a namespace and database. The SDK supports remote connections over WebSocket and HTTP.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#constructor"><code>SurrealClient(config)</code></a></td>
			<td scope="row" data-label="Description">Creates a new client from a configuration</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#connect"><code>client.connect()</code></a></td>
			<td scope="row" data-label="Description">Establishes the connection explicitly</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#close"><code>client.close()</code></a></td>
			<td scope="row" data-label="Description">Closes the connection and releases resources</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#use"><code>client.use(ns, db)</code></a></td>
			<td scope="row" data-label="Description">Selects a namespace and database</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#version"><code>client.version()</code></a></td>
			<td scope="row" data-label="Description">Returns the server version</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#ping"><code>client.ping()</code></a></td>
			<td scope="row" data-label="Description">Pings the server</td>
		</tr>
	</tbody>
</table>

## Opening a connection

Construct a [`SurrealClient`](/docs/reference/kotlin/api/core/surreal-client.md) with a [`SurrealClientConfig`](/docs/reference/kotlin/api/core/client-config.md) whose `url` points at your SurrealDB instance. By default (`autoConnect = true`) the client connects lazily on the first request, so you rarely need to call [`.connect()`](/docs/reference/kotlin/api/core/surreal-client.md#connect) yourself.

```kotlin
import com.surrealdb.kotlin.SurrealClient
import com.surrealdb.kotlin.SurrealClientConfig

val client = SurrealClient(SurrealClientConfig(url = "ws://localhost:8000"))
```

## Connection string protocols

The URL scheme determines the transport. For more on server configuration, see the [start command](/docs/reference/cli/surrealdb-cli/commands/start.md) documentation.

| Protocol | Description |
|---|---|
| `ws://` | Plain WebSocket connection |
| `wss://` | Secure WebSocket connection (TLS) |
| `http://` | Plain HTTP connection |
| `https://` | Secure HTTP connection (TLS) |

The WebSocket engine maintains a single long-lived connection, while the HTTP engine issues a request per call.

## Feature support by protocol

Not all features are available on every transport. You can check support at runtime with [`.supports()`](/docs/reference/kotlin/api/core/surreal-client.md#supports); unsupported calls throw [`SurrealFeatureNotSupportedException`](/docs/reference/kotlin/api/errors.md).

| Feature | WebSocket | HTTP |
|---|---|---|
| Authentication | Yes | Yes |
| Queries | Yes | Yes |
| CRUD operations | Yes | Yes |
| Live queries | Yes | No |
| Transactions | Yes | No |
| Multiple sessions | Yes | No |
| Refresh tokens | Yes | No |
| Export / Import | Yes | Yes |
| SurrealML | Yes | Yes |

See [Features and events](/docs/reference/kotlin/api/features.md) for the full [`SurrealFeature`](/docs/reference/kotlin/api/features.md#feature) enum.

## Selecting a namespace and database

After connecting, select a [namespace](/docs/reference/query-language/statements/define/namespace.md) and [database](/docs/reference/query-language/statements/define/database.md) with [`.use()`](/docs/reference/kotlin/api/core/surreal-client.md#use).

```kotlin
client.use("surrealdb", "docs")
```

## Reconnection

The WebSocket engine automatically reconnects with exponential backoff. Tune this through the [`ReconnectConfig`](/docs/reference/kotlin/api/core/client-config.md#reconnect-config) on your [`SurrealClientConfig`](/docs/reference/kotlin/api/core/client-config.md).

```kotlin
import com.surrealdb.kotlin.SurrealClientConfig
import com.surrealdb.kotlin.engine.ReconnectConfig

val client = SurrealClient(
    SurrealClientConfig(
        url = "wss://example.com",
        reconnect = ReconnectConfig(
            enabled = true,
            initialDelayMillis = 250,
            maxDelayMillis = 30_000,
            multiplier = 1.5,
            maxAttempts = null, // null means retry indefinitely
        ),
    ),
)
```

## Observing connection events

The client exposes a [`connectionEvents`](/docs/reference/kotlin/api/features.md#connection-events) [`SharedFlow`](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flow/) you can collect to react to lifecycle changes.

```kotlin
import com.surrealdb.kotlin.engine.SurrealConnectionEvent
import kotlinx.coroutines.launch

scope.launch {
    client.connectionEvents.collect { event ->
        when (event) {
            is SurrealConnectionEvent.Connected -> println("connected")
            is SurrealConnectionEvent.Reconnecting -> println("reconnecting, attempt ${event.attempt}")
            is SurrealConnectionEvent.Disconnected -> println("disconnected")
            is SurrealConnectionEvent.Error -> println("error: ${event.cause.message}")
            else -> {}
        }
    }
}
```

## Closing a connection

Call [`.close()`](/docs/reference/kotlin/api/core/surreal-client.md#close) to release all resources associated with the connection.

```kotlin
client.close()
```

## Learn more

- [SurrealClient API reference](/docs/reference/kotlin/api/core/surreal-client.md) for complete method signatures
- [Client configuration](/docs/reference/kotlin/api/core/client-config.md) for all configuration options
- [Authentication](/docs/reference/kotlin/concepts/authentication.md) for signing in and managing sessions
- [Error handling](/docs/reference/kotlin/concepts/error-handling.md) for handling connection errors
