---
title: Connect to Lakebase
description: Write streaming data to Lakebase or an external PostgreSQL database, including authentication, configuration options, and performance tuning.
canonical_url: https://docs.databricks.com/gcp/en/structured-streaming/lakebase
---

# Connect to Lakebase

Use Structured Streaming to write to Lakebase or an external PostgreSQL database with built-in batching, automatic retries, and workspace-managed authentication.

## When to use the Lakebase sink

Use the Lakebase sink for low-latency streaming writes to Lakebase or an external PostgreSQL database. This sink doesn't require you to implement custom `foreach` functions to handle batching, connection management, and error handling.

Common use cases include:

* Update application databases in real-time for operational dashboards or customer-facing features.
* Sync continuously changing data, such as aggregated or filtered streaming results, into a transactional database.
* Write the output of a Structured Streaming query into a Lakebase table with latency in the tens of milliseconds using [real-time mode](https://docs.databricks.com/gcp/en/structured-streaming/real-time/concepts.md) on classic compute.

To sync data from Lakebase to Delta Lake tables in the Lakehouse, the reverse direction, see [Lakebase Change Data Feed](https://docs.databricks.com/gcp/en/oltp/projects/lakebase-cdf.md).

## <a id="reqs" />Requirements

* [Databricks Runtime 18 LTS](https://docs.databricks.com/gcp/en/release-notes/runtime/18.md#unified-format) and above.
  * External PostgreSQL connections require you to use [Databricks Runtime 19](https://docs.databricks.com/gcp/en/release-notes/runtime/19.md) and above and to opt in to the **Custom JDBC on UC Compute** preview.
  * Interval data types require you to use [Databricks Runtime 19](https://docs.databricks.com/gcp/en/release-notes/runtime/19.md) and above.
  * Merge strategies for upserts require you to use [Databricks Runtime 19](https://docs.databricks.com/gcp/en/release-notes/runtime/19.md) and above.
  * Additive schema evolution with `mergeSchema` requires you to use [Databricks Runtime 19](https://docs.databricks.com/gcp/en/release-notes/runtime/19.md) and above.
* Classic compute with dedicated or standard access modes, or serverless compute for notebooks or jobs. On serverless compute, use `Trigger.AvailableNow()`. See [Streaming on serverless compute](https://docs.databricks.com/gcp/en/compute/serverless/streaming.md).
* A Lakebase database, or a Unity Catalog connection to an external PostgreSQL database.

### Identifier requirements

For all targets, Databricks recommends using schema, table, column, and primary-key column names that start with a letter or underscore and contain only letters, numbers, and underscores. The sink enforces these requirements when it automatically creates a Lakebase table. To use identifiers that don't meet these requirements, create the target table before starting the query.

## Connect to a database

The Lakebase sink supports the following connection methods:

### <a id="lakebase-no-uc" />Lakebase tables not registered with Unity Catalog

For Lakebase tables not registered with Unity Catalog, the connector automatically manages the credentials and uses the identity of the user or Databricks service principal running the query. If the table doesn't exist, the connector creates the table.

To write to a Lakebase table, use the `endpoint` and `dbtable` options:

#### Python

```python
(df.writeStream
  .format("postgresql")
  .outputMode("update")
  .option("endpoint", "<project-id>.<branch-id>.<endpoint-id>")
  .option("database", "<database>")  # Optional. Defaults to databricks_postgres.
  .option("dbtable", "<schema>.<table>")
  .option("upsertkey", "<primary-key-columns>")  # Optional
  .option("checkpointLocation", "/Volumes/<catalog>/<schema>/<volume>/<checkpoint-name>")
  .start()
)
```

#### Scala

```scala
df.writeStream
  .format("postgresql")
  .outputMode("update")
  .option("endpoint", "<project-id>.<branch-id>.<endpoint-id>")
  .option("database", "<database>")  // Optional. Defaults to databricks_postgres.
  .option("dbtable", "<schema>.<table>")
  .option("upsertkey", "<primary-key-columns>")  // Optional
  .option("checkpointLocation", "/Volumes/<catalog>/<schema>/<volume>/<checkpoint-name>")
  .start()
```

Replace the following placeholders:

* `<project-id>.<branch-id>.<endpoint-id>`: Your Lakebase endpoint. Find all three values in the **Resource name** on the **Get ID** menu of the **Computes** tab, which has the format `projects/<project-id>/branches/<branch-id>/endpoints/<endpoint-id>`. See [Compute identifiers](https://docs.databricks.com/gcp/en/oltp/projects/manage-computes.md#identifiers).
* `<database>`: Optional. The name of the target PostgreSQL database. Defaults to `databricks_postgres`. See [Manage databases](https://docs.databricks.com/gcp/en/oltp/projects/manage-databases.md).
* `<schema>.<table>`: The target table in `schema.table` format. If you omit the schema, the sink uses the `public` schema. For automatic table creation, use identifiers that start with a letter or underscore and contain only letters, numbers, and underscores.
* `<primary-key-columns>`: Optional. A comma-separated list of all columns in the target table's primary key, for example `id` or `user_id,event_type`. See [Upsert behavior](https://docs.databricks.com/gcp/en/structured-streaming/lakebase.md#upsert).
* `/Volumes/<catalog>/<schema>/<volume>/<checkpoint-name>`: A Unity Catalog volume path where the query stores its checkpoint. You can also use a cloud object storage URI. The location must be storage that you can write to, not local disk, and must be unique to each streaming query. This is independent of the target table. See [Structured Streaming checkpoints](https://docs.databricks.com/gcp/en/structured-streaming/checkpoints.md).

For optional configurations, such as `batchsize` and `batchinterval`, see [the PostgreSQL sink options](https://docs.databricks.com/gcp/en/spark/api-options.md#stream-writer-postgresql).

### <a id="ext-postgres-uc" />External PostgreSQL with Unity Catalog credentials

> [!NOTE]
> **Preview**
>
> This feature is in [Public Preview](https://docs.databricks.com/gcp/en/release-notes/release-types.md). Workspace admins can control access to **Custom JDBC on UC Compute** from the **Previews** page. See [Manage Databricks previews](https://docs.databricks.com/gcp/en/admin/workspace-settings/manage-previews.md).

Use a Unity Catalog connection to authenticate to an external PostgreSQL database without storing credentials in your code. The target table must already exist.

Create a connection of type `POSTGRESQL`. See [Create a connection](https://docs.databricks.com/gcp/en/query-federation/postgresql.md#connection). The user or Databricks service principal running the query must have `USE CONNECTION` on the connection.

To write to the PostgreSQL table, use the `databricks.connection`, `database`, and `dbtable` options:

#### Python

```python
(df.writeStream
  .format("postgresql")
  .outputMode("update")
  .option("databricks.connection", "<connection-name>")
  .option("database", "<database>")
  .option("dbtable", "<schema>.<table>")
  .option("upsertkey", "<primary-key-columns>")  # Optional
  .option("checkpointLocation", "/Volumes/<catalog>/<schema>/<volume>/<checkpoint-name>")
  .start()
)
```

#### Scala

```scala
df.writeStream
  .format("postgresql")
  .outputMode("update")
  .option("databricks.connection", "<connection-name>")
  .option("database", "<database>")
  .option("dbtable", "<schema>.<table>")
  .option("upsertkey", "<primary-key-columns>")  // Optional
  .option("checkpointLocation", "/Volumes/<catalog>/<schema>/<volume>/<checkpoint-name>")
  .start()
```

Replace the following placeholders:

* `<connection-name>`: The name of the Unity Catalog connection.
* `<database>`: The name of the target PostgreSQL database.
* `<schema>.<table>`: The existing target table in `schema.table` format. If you omit the schema, the sink uses the `public` schema.
* `<primary-key-columns>`: Optional. A comma-separated list of all columns in the target table's primary key, for example `id` or `user_id,event_type`. See [Upsert behavior](https://docs.databricks.com/gcp/en/structured-streaming/lakebase.md#upsert).
* `/Volumes/<catalog>/<schema>/<volume>/<checkpoint-name>`: A Unity Catalog volume path where the query stores its checkpoint. You can also use a cloud object storage URI. The location must be storage that you can write to, not local disk, and must be unique to each streaming query. This is independent of the target table. See [Structured Streaming checkpoints](https://docs.databricks.com/gcp/en/structured-streaming/checkpoints.md).

PostgreSQL connections use TLS. Certificate verification follows the settings on the Unity Catalog connection, which you choose when you [create the connection](https://docs.databricks.com/gcp/en/query-federation/postgresql.md#connection):

* **Trust server certificate**: When selected, the connection uses `sslmode=require`, which encrypts the connection without verifying the server certificate.
* **User provided server certificate**: Provide a PEM-encoded server certificate to use `sslmode=verify-full` when **Trust server certificate** isn't selected. If you don't provide a certificate, the connection uses `sslmode=verify-full` with the JVM default trust store.

## <a id="config" />Configuration options

The sink raises an error for unrecognized options, `JDBC_STREAMING_SINK_INVALID_OPTIONS`.&#x20;

For the sink configuration options, including the common options and the options for each connection method, see [the PostgreSQL sink options](https://docs.databricks.com/gcp/en/spark/api-options.md#stream-writer-postgresql).

## <a id="schema-evolution" />Additive schema evolution

In Databricks Runtime 19 and above, set `.option("mergeSchema", "true")` on your streaming writer before `.start()` or `.toTable()` to add DataFrame columns that are missing from an existing Lakebase or external PostgreSQL table. The option defaults to `false`. Without it, a DataFrame with new columns causes the query to fail.

The sink checks for new columns when the query initializes, before writing data. Restart the query with the updated DataFrame schema and `mergeSchema` enabled to add new columns. The sink doesn't check for schema changes at each batch boundary.

New columns are nullable and use the [data type mappings](https://docs.databricks.com/gcp/en/structured-streaming/lakebase.md#data-type-mappings) for automatically created Lakebase tables. Existing rows have null values in the added columns. The database identity used by the sink must have permission to alter the target table. For external PostgreSQL, the target table must already exist.

Schema evolution only adds top-level columns. It doesn't rename or drop columns, change existing column types, or widen types. To make those changes, stop the query, alter the target table yourself, and restart the query with a compatible DataFrame schema.

## <a id="data-type-mappings" />Data type mappings

The sink checks that each DataFrame column is compatible with its corresponding target column before writing to an existing Lakebase or external PostgreSQL table.

The following table contains types supported in Databricks Runtime 18 LTS and above:

| Spark type                                                      | Automatically created Lakebase table type | Compatible types in existing PostgreSQL tables |
| --------------------------------------------------------------- | ----------------------------------------- | ---------------------------------------------- |
| `ByteType`, `ShortType`                                         | `smallint`                                | `smallint`                                     |
| `IntegerType`                                                   | `integer`                                 | `integer`                                      |
| `LongType`                                                      | `bigint`                                  | `bigint`                                       |
| `FloatType`                                                     | `real`                                    | `real`                                         |
| `DoubleType`                                                    | `double precision`                        | `double precision`                             |
| `DecimalType`                                                   | `numeric`                                 | `numeric`                                      |
| `StringType`                                                    | `text`                                    | `varchar`, `text`                              |
| `VarcharType(n)`                                                | `varchar(n)`                              | `varchar`, `text`                              |
| `CharType(n)`                                                   | `char(n)`                                 | `char`                                         |
| `BinaryType`                                                    | `bytea`                                   | `bytea`                                        |
| `BooleanType`                                                   | `boolean`                                 | `boolean`                                      |
| `TimestampType`                                                 | `timestamptz`                             | `timestamptz`                                  |
| `TimestampNTZType`                                              | `timestamp`                               | `timestamp`                                    |
| `DateType`                                                      | `date`                                    | `date`                                         |
| `ArrayType`, `MapType`, `StructType`, `VariantType`, `NullType` | `jsonb`                                   | `json`, `jsonb`                                |

The following table contains types supported in Databricks Runtime 19 and above:

| Spark type                                     | Automatically created Lakebase table type | Compatible types in existing PostgreSQL tables |
| ---------------------------------------------- | ----------------------------------------- | ---------------------------------------------- |
| `DayTimeIntervalType`, `YearMonthIntervalType` | `interval`                                | `interval`                                     |

## <a id="upsert" />Upsert behavior

The `upsertkey` option identifies the target table's primary key columns. For an existing table, the columns in `upsertkey` must match the table's primary key exactly. If you omit the option, the sink reads the primary key from the table. For a Lakebase table that the sink creates, `upsertkey` defines the primary key. If you omit the option, the sink creates the table without a primary key.

When the target table has a primary key, the sink upserts with PostgreSQL's `INSERT INTO ... ON CONFLICT (<primary_key_columns>) DO UPDATE SET ...` syntax. When the target table has no primary key, the sink performs inserts. A query's output mode has no effect on this behavior.

All primary key columns must be present in the DataFrame and use comparable types, such as numeric or string types.

To control how upserts update non-primary-key columns, see [Merge strategies for upserts](https://docs.databricks.com/gcp/en/structured-streaming/lakebase.md#merge-strategies).

## <a id="merge-strategies" />Merge strategies for upserts

In [Databricks Runtime 19](https://docs.databricks.com/gcp/en/release-notes/runtime/19.md) and above, you can use merge strategies to control how the sink updates non-primary-key columns when rows have the same primary key. For example, you can keep the greatest timestamp or update a column only when an incoming event has a newer ordering value.

Merge strategies apply only to upserts. If the target table has no primary key, setting `upsert.mergeStrategies` or `upsert.defaultMergeStrategy` causes an error. You can assign strategies only to non-primary-key columns. Set `upsert.mergeStrategies` to a comma-separated list in `column:strategy` format. Set `upsert.defaultMergeStrategy` to configure a default for columns without explicit strategies. By default, the sink uses the `latest` strategy.

### <a id="supported-merge-strategies" />Supported merge strategies

| Strategy             | Behavior                                                                                                                                                                                                                                           |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `latest`             | Use the latest value by arrival order. This is the default.                                                                                                                                                                                        |
| `earliest`           | Use the earliest value by arrival order.                                                                                                                                                                                                           |
| `latestNonNull`      | Use the latest non-null value by arrival order.                                                                                                                                                                                                    |
| `earliestNonNull`    | Use the earliest non-null value by arrival order.                                                                                                                                                                                                  |
| `greatest`           | Use the greater of the existing and incoming values. Null values are ignored, so a null incoming value doesn't replace an existing value.                                                                                                          |
| `least`              | Use the lesser of the existing and incoming values. Null values are ignored, so a null incoming value doesn't replace an existing value.                                                                                                           |
| `latestBy(column)`   | Use the value from the row with the greatest value in the specified ordering column. See [How `latestBy` and `earliestBy` handle ties and nulls](https://docs.databricks.com/gcp/en/structured-streaming/lakebase.md#ordering-equality-and-nulls). |
| `earliestBy(column)` | Use the value from the row with the least value in the specified ordering column. See [How `latestBy` and `earliestBy` handle ties and nulls](https://docs.databricks.com/gcp/en/structured-streaming/lakebase.md#ordering-equality-and-nulls).    |

### <a id="ordering-equality-and-nulls" />How `latestBy` and `earliestBy` handle ties and nulls

`latestBy(column)` and `earliestBy(column)` choose a value by comparing the incoming ordering value with the one already stored in the table. To keep that stored value accurate, the ordering column must use the matching strategy, either in `upsert.mergeStrategies` or through `upsert.defaultMergeStrategy`:

* For `latestBy(column)`, the ordering column must use `greatest`.
* For `earliestBy(column)`, the ordering column must use `least`.

For example, `is_success:latestBy(last_updated_at)` requires `last_updated_at:greatest`.

When both ordering values are non-null, `latestBy(column)` updates a column only when the incoming ordering value is strictly greater (`>`) than the existing ordering value. For `earliestBy(column)`, it must be strictly less (`<`). For both strategies, when the ordering values are equal, the sink keeps the column's existing value. Within a single batch, if multiple rows have the same primary key and ordering value, the sink keeps the first row it receives.

For example, if `is_success` uses `latestBy(last_updated_at)` and an incoming row has the same `last_updated_at` as the existing row, the sink retains the existing `is_success`, even if the incoming value differs.

For both strategies, non-null ordering values take precedence over null ordering values. An incoming row with a non-null ordering value replaces an existing value whose ordering value is null. An incoming row with a null ordering value doesn't replace an existing value, including when the existing ordering value is also null.

### <a id="merge-strategy-example" />Example: Model custom upsert logic

Consider a table with the columns `id`, `last_updated_at`, `creation_date`, and `is_success`. You might want to express the following logic:

```sql
INSERT INTO events ...
ON CONFLICT (id) DO UPDATE
SET
  -- Keep the most recent timestamp.
  last_updated_at = GREATEST(events.last_updated_at, EXCLUDED.last_updated_at),

  -- Keep the earliest non-null creation date.
  creation_date = COALESCE(events.creation_date, EXCLUDED.creation_date),

  -- Keep the value of is_success from the event with the most recent last_updated_at.
  is_success = CASE
    WHEN EXCLUDED.last_updated_at IS NOT NULL
      AND (events.last_updated_at IS NULL
        OR EXCLUDED.last_updated_at > events.last_updated_at)
    THEN EXCLUDED.is_success
    ELSE events.is_success
  END;
```

To model this logic, use the following merge strategies:

#### Python

```python
(df.writeStream
  .format("postgresql")
  .outputMode("update")
  .option("databricks.connection", "<connection-name>")
  .option("database", "<database>")
  .option("dbtable", "<schema>.<table>")
  .option("upsertkey", "id")
  .option("upsert.mergeStrategies", "last_updated_at:greatest,creation_date:earliestNonNull,is_success:latestBy(last_updated_at)")
  .option("checkpointLocation", "/Volumes/<catalog>/<schema>/<volume>/<checkpoint-name>")
  .start()
)
```

#### Scala

```scala
df.writeStream
  .format("postgresql")
  .outputMode("update")
  .option("databricks.connection", "<connection-name>")
  .option("database", "<database>")
  .option("dbtable", "<schema>.<table>")
  .option("upsertkey", "id")
  .option("upsert.mergeStrategies", "last_updated_at:greatest,creation_date:earliestNonNull,is_success:latestBy(last_updated_at)")
  .option("checkpointLocation", "/Volumes/<catalog>/<schema>/<volume>/<checkpoint-name>")
  .start()
```

### <a id="parameterized-default-merge-strategies" />Parameterized default merge strategies

In [Databricks Runtime 19](https://docs.databricks.com/gcp/en/release-notes/runtime/19.md) and above, `upsert.defaultMergeStrategy` also accepts `latestBy(column)` and `earliestBy(column)`. Use these defaults to apply the same ordering rule to non-primary-key columns without listing each column in `upsert.mergeStrategies`. Explicit per-column strategies override the default, except for the ordering column as described below.

When the default is `latestBy(column)`, the sink automatically applies `greatest` to the ordering column. When the default is `earliestBy(column)`, it automatically applies `least`. If you explicitly assign a strategy to the ordering column, it must match the required `greatest` or `least` strategy.

The following example uses `last_updated_at` to select values for all other non-primary-key columns:

#### Python

```python
(df.writeStream
  .format("postgresql")
  .outputMode("update")
  .option("databricks.connection", "<connection-name>")
  .option("database", "<database>")
  .option("dbtable", "<schema>.<table>")
  .option("upsertkey", "id")
  .option("upsert.defaultMergeStrategy", "latestBy(last_updated_at)")
  .option("checkpointLocation", "/Volumes/<catalog>/<schema>/<volume>/<checkpoint-name>")
  .start()
)
```

#### Scala

```scala
df.writeStream
  .format("postgresql")
  .outputMode("update")
  .option("databricks.connection", "<connection-name>")
  .option("database", "<database>")
  .option("dbtable", "<schema>.<table>")
  .option("upsertkey", "id")
  .option("upsert.defaultMergeStrategy", "latestBy(last_updated_at)")
  .option("checkpointLocation", "/Volumes/<catalog>/<schema>/<volume>/<checkpoint-name>")
  .start()
```

## <a id="perf-tuning" />Performance tuning

### Batching and backpressure

A flush is triggered when either condition is met:

* The buffer reaches `batchsize` rows, which defaults to `1000`.
* The buffer age exceeds `batchinterval`, which defaults to `100 milliseconds`.

When the database cannot keep up with the incoming data rate, the sink propagates backpressure upstream to the source.

Latency and throughput guidance:

* For low-latency workloads with real-time mode, decrease `batchinterval` to guarantee a shorter maximum time before flushing. See [Real-time mode concepts](https://docs.databricks.com/gcp/en/structured-streaming/real-time/concepts.md) for concepts and [Real-time mode examples](https://docs.databricks.com/gcp/en/structured-streaming/real-time/examples.md) for a code example.
* For high-throughput workloads, increase `batchsize` to reduce overhead for each transaction.

### Connection behavior

The sink uses connection pooling on executors. By default, each task uses one database connection.

Databricks recommends that you use the default value of `1` task for each connection. If you increase the number of tasks for each connection, you might cause connection contentions and increase latencies for high throughput connections.

To configure the ratio of tasks to connections, set the `spark.databricks.sql.streaming.jdbc.tasksPerConnection` Spark configuration. If the target database has a low connection limit, reduce the number of shuffle partitions or increase `spark.databricks.sql.streaming.jdbc.tasksPerConnection`.

The sink automatically retries transient JDBC errors, including connection failures, deadlocks, and rate limiting. If the sink exhausts all retries, the query fails.

## Supported triggers and output modes

### Triggers

This table shows support for Structured Streaming trigger types on classic and serverless compute:

| Trigger          | Classic compute                      | Serverless compute (notebooks and jobs) |
| ---------------- | ------------------------------------ | --------------------------------------- |
| `RealTime`       | Yes                                  | No                                      |
| `ProcessingTime` | Yes                                  | No                                      |
| `AvailableNow`   | Yes                                  | Yes                                     |
| `Once`           | Yes. Deprecated. Use `AvailableNow`. | Yes. Deprecated. Use `AvailableNow`.    |

### Output modes

This table shows support for Structured Streaming output modes:

| Output mode | Supported                                                                                                                                                                                                                          |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `update`    | Yes                                                                                                                                                                                                                                |
| `append`    | Yes. Behavior is identical to `update`. The query upserts when the target table has a primary key, otherwise the query inserts. See [Upsert behavior](https://docs.databricks.com/gcp/en/structured-streaming/lakebase.md#upsert). |
| `complete`  | No                                                                                                                                                                                                                                 |

## <a id="limits" />Limitations

* For an external PostgreSQL database connected through a Unity Catalog connection, the target table must already exist. The sink automatically creates missing tables only in Lakebase.
* Lakeflow pipelines are not supported.
