> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Replica

A replica reads a database's own change log through a SQL change receiver
(`@bijectionhq/app-sql`) or a Debezium envelope receiver. A SQL replica lands
each complete source commit and its position in one Bijection transaction.
A source transaction too large for one Bijection transaction stops the replica
before publishing any of that commit
([large source transactions](https://docs.bijection.com/integrations/replica/lag-and-hold.md#large-source-transactions)).

See [dialects](https://docs.bijection.com/integrations/replica/dialects.md) for declared source protocols.
For Oracle, see the
[Oracle Database relation source](https://docs.bijection.com/integrations/native-oracle.md).

```mermaid theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
flowchart LR
  DB[Source log] --> R[Change receiver]
  R --> L[Sources landing mutation]
  L --> P[Commit rows, status and position in one transaction]
  P --> Q[Reactive queries]
```

## Declare and place the replica

`replica(dialect, { tables, groups? })` from `@bijectionhq/library-replicas`
declares each replicated table, its source table, its key and its projected
columns. Calling the declaration with `{ provider, allow, label?, lag? }`
returns a subtree you place directly in `app(...)` — its tree path
in the app tree is its name:

```ts bijection/warehouse.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { label, role, secret, t } from "@bijectionhq/bijection";
import { postgresLogical } from "@bijectionhq/app-sql";
import { replica } from "@bijectionhq/library-replicas";

export const rows = label();
export const operator = role({ clear: [rows] });
export const reader = role({ clear: [rows] });

// The private login, placed at `login` in the app tree.
export const login = secret();

// The SQL change receiver, placed at `source` in the app tree.
export const source = postgresLogical({
  endpoint: "db.example.com:5432", label: rows, credential: login,
  requests: { retain: { days: 1 }, message: "Configured request-log retention for this receiver." },
  isolation: "Publication bijection lists the replicated tables only; the role reads every published row.",
  hold: "8GiB",
});

// Each PostgreSQL commit touching these tables publishes as one transaction.
// An order and its lines stop together if a breaking change reaches either.
const declaration = replica("postgres", {
  tables: {
    orders: {
      source: "public.orders",
      key: ["id"],
      label: rows,
      fields: {
        description: t.maybe(t.string),
        id: t.int,
        payload: t.bytes,
        total: t.decimal,
      },
    },
    lines: {
      source: "public.lines",
      key: ["id"],
      label: rows,
      fields: { id: t.int, order_id: t.int },
      index: [["order_id"]],
    },
  },
  groups: [["orders", "lines"]],
});

export const warehouse = declaration({
  provider: source,
  allow: { operators: [operator], readers: [reader] },
  lag: "live",
});
```

* `source` is `schema.name`; for `envelope` it is the Kafka topic carrying the
  table's change envelopes.
* `key` is the primary key, or the columns of a unique not-null index, in
  order. A keyless table cannot be replicated: read it with a periodic
  [`poll`](https://docs.bijection.com/reference/connectors/sql) instead.
* `fields` maps each projected source column to its value type. Key columns
  are never `t.maybe`. Unlisted columns are not read.
* `label` (optional) is the label every replicated row carries.
* `index` (optional) declares field orders beside `key`; the key is always a
  point.
* `groups` lists tables that [stop together](https://docs.bijection.com/integrations/replica/groups.md).

| Mount option | Default | Meaning |
| - | - | - |
| `provider` | required | A SQL change receiver (`postgresLogical`, `mysqlBinlog`, `sqlServerCdc`, `oracleLogMiner`) or Debezium stream receiver |
| `allow` | required | Operator roles, as an array or `{ operators, readers }`. Readers can call `status` and the SQL read queries. |
| `label` | the label every declared table shares | Label for the replica's sync and status fact tables and its functions. Required when the tables share no label |
| `lag` | `"live"` | [Polling cadence](https://docs.bijection.com/integrations/replica/lag-and-hold.md): `"live"` (1 s) or a duration |

Set the SQL replica's [retention budget](https://docs.bijection.com/integrations/replica/lag-and-hold.md)
with `hold` on its receiver. Envelope replicas take `hold` and `onHold`
on the mount.

## Read the tables

In an application query, call `warehouse.read(ctx)` to read SQL tables at one
published source position in the query's frame. Use `get` with the full
declared key, `where(...).first(n)` with equality on a declared index, or
`first(n)` for a bounded scan in fact-ID order.

```ts bijection/app.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app, query, t } from "@bijectionhq/bijection";
import { SQL_REPLICA_READ_REFUSES } from "@bijectionhq/library-replicas";
import { login, operator, reader, rows, source, warehouse } from "./warehouse";

const orderDetails = query({
  under: rows, allow: [reader], refuses: SQL_REPLICA_READ_REFUSES, args: { id: t.int },
}, async (ctx, { id }) => {
  const { position, orders, lines } = await warehouse.read(ctx);
  return {
    position,
    order: await orders.get({ id }),
    lines: await lines.where({ order_id: id }).first(50),
  };
});

export default app({ rows, operator, reader, login, source, warehouse, orderDetails });
```

SQL reads return `ReplicaUnavailable` during initial baselining or any
rebuild, after a source gap, or at a replica-wide stop. Reading an individual
stopped table also returns `ReplicaUnavailable`. Every read enforces the
declared row label. The private tables are written through `sync.writes`,
so application queries and direct operator writes cannot bypass selection.

Envelope replicas expose ordinary keyed tables through `table.readOnly(...)`.
Read those with `ctx.get` and `ctx.list`. Keep application-owned annotations in
separate tables.

## Credentials and source setup

No bindings entry is required. Store the receiver's login secret
at its tree path:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection secret set login --from-file login.json
```

After deploying, run `bijection mutate warehouse.inspect` to submit a
read-only probe against the source. `bijection query warehouse.status` then
shows its result: any missing settings, privileges or setup SQL, and the keys
and fields the source catalog declares for each table. Bijection never runs
that SQL and never creates tables, triggers or schemas in your database. Run it
as the source administrator.

## What happens next

The SQL replica builds its [baseline](https://docs.bijection.com/integrations/replica/status.md#baselines)
in bounded key ranges and replays the source log before selecting a cut.
[`bijection query warehouse.status`](https://docs.bijection.com/integrations/replica/status) reads the
mounted `warehouse.status` query: its state, lag, hold and table states.

## PostgreSQL capture through Debezium

`exactReplica` follows a dedicated PostgreSQL capture enrollment. The
worker takes an exported snapshot, seals committed changes and its restart
offset together, and answers the installation's signed replication target.
The replica prepares immutable row and index pages in bounded batches.
It publishes a snapshot or complete source transaction by selecting its
manifest and cut together in one local transaction. Readers keep using
the previous manifest until selection commits. Unchanged pages are
shared by the two manifests.
[Worker and gateway setup](../../../external/provider_gateways/debezium-gateway/README.md)

Each exact replica defaults to 1 GiB of charged live page storage and
4,000,000 page, reference and cleanup obligations. Set `storage.bytes` and
`storage.obligations` on `exactReplica` to size the mount. Allow room for the
selected snapshot, its replacement and any pages still awaiting collection.
`shop.status` reports the charge and limits. When collection can make room,
capture pauses with `ReplicaStorageCapacity` and retries the same page as
capacity frees up. If the candidate still cannot fit, capture blocks with
that reason and keeps serving the selected cut.

The replica credits page capacity when it deletes the unreachable pages
and releases their child references. A reader admitted to a held Store
version still sees its original manifest and pages. Store history and
physical erasure follow their own retention and custody rules.

The provider can pack consecutive small commits into one page. A truncate
clears the affected table's roots within the same publication. The
other tables keep their roots. An expired transaction candidate can
retry from the selected cut while the source journal retains its pages.
If the provider reports a retention gap, the replica keeps serving its
last published cut. An explicit rebaseline can select a new snapshot.

```ts bijection/app.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app, label, query, role, t } from "@bijectionhq/bijection";
import { exactReplica } from "@bijectionhq/library-replicas/exact";

const data = label();
const operator = role({ clear: [data] });
const reader = role({ clear: [data] });
export const shop = exactReplica({
  label: data,
  allow: { operators: [operator], readers: [reader] },
  tables: {
    orders: { from: "orders", key: ["id"], fields: { id: t.int, status: t.string } },
    lines: {
      from: "order_lines",
      key: ["id"],
      fields: { id: t.int, orderId: t.int, quantity: t.int },
      index: [["orderId"]],
    },
  },
});

const orderDetails = query(
  { under: data, allow: [reader], args: { id: t.int } },
  async (ctx, { id }) => {
    const { cut, orders, lines } = await shop.read(ctx);
    const order = await orders.get({ id });
    const items = await lines.where({ orderId: id }).first(100);
    return { cut, order, lines: items };
  },
);

export default app({ data, operator, reader, shop, orderDetails });
```

Select the enrolled source in the installation's bindings file, the file you
pass to `bijection deploy --bindings <file>`. The source is a resource entry: it
chooses which database the replica reads, and each installation's file can
name its own.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { placement } from "@bijectionhq/bijection";
import { bind } from "@bijectionhq/library-replicas/exact";
import { shop } from "./bijection/app";

export default placement.bindings([
  bind(shop, { source: "inventory" }),
]);
```

Before deploying, approve the source and its recipient grant with
`bijection capture enroll`. The grant names the installation, source alias,
receiver, label and typed projection. Approval is authority to read the
source; it does not choose who operates capture.

Who runs the capture worker is [placement](https://docs.bijection.com/operate/placement.md). The replica's
`capture` slot (`exact-capture@1`), here `shop.capture`, is managed unless you
bind it: the cell creates a managed worker when an installed release requests
the source.

Deployment checks and records the approved source revision. The app can
serve its other functions while capture is taking its first snapshot. Replica reads return
`ReplicaUnready` until its first snapshot is selected. A dry run checks
the declaration and the capture slot's placement. Each live delivery checks the
enrollment again, and the worker verifies the projection independently.

Set `observeHead: true` on the replica to sample the source WAL head. A query
can then use `shop.read(ctx, { freshWithin: { seconds: 10 } })`. It receives
`ReplicaStale` if the published cut falls behind the observation or the
observation has expired. The mounted `shop.cut` query takes `freshWithin`
as a Temporal duration. Freshness is measured from when Bijection started
the capture request that supplied the latest observed head. The evidence
expires at that time plus the specified duration. Specify whole milliseconds
from 1 millisecond through 24 hours, with a day counting as 24 hours. An
unreachable source supplies no new freshness evidence.

The two local reads share the query's frame. The mounted operator functions
are `shop.status`, `shop.inspect`, `shop.pause`, `shop.resume` and `shop.rebaseline`. Pass
`acceptNewHistory=false` to rebaseline against the same source history.
A manual pause discards unfinished staging and leaves the selected cut
readable. Resume restarts an unfinished snapshot with a new generation
or requests changes from the selected cut.
A replacement provider or source with a different history needs a reviewed
`acceptNewHistory=true` call.

To first deploy with your own Debezium provider, enroll the source as
`external`. Put the network and credential references in that enrollment.
Keep the source alias in the resource bindings above. Put the capture
provider in the installation's provider map and pass that file with
`bijection deploy --bindings <file>`.

```ts placement.bindings.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { placement } from "@bijectionhq/bijection";
import { shop } from "./bijection/app";

export default placement.bindings([
  placement.bind(shop.capture, placement.endpoint({
    url: "https://capture.example.com/v1/targets/replication/page",
  })),
]);
```

Choose the operator before the first deployment of the capture slot. Live
handoff between managed and customer providers still requires capture lifecycle
support. `shop.status` includes the published cut and pages staged during a
multi-page transaction. A managed capture placement reports usage per source.
The installation that enrolled a shared source pays for it.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.