# Prepare the Source

Source: https://docs.formance.com/v4.0/modules/ledger/migration/prepare-source

Stack: v4.0

Prepare each Ledger v2 ledger as an independent migration unit. The output of this page is a source worksheet and a tested, least-privilege read path from the target environment.

These checks do not change Ledger v2.

## Inventory the ledger

Record the following before granting access:

| Area       | Record                                                                                          |
| ---------- | ----------------------------------------------------------------------------------------------- |
| Identity   | Ledger name, bucket, environment, owner, and expected target name.                              |
| History    | Current highest log ID, transaction count, oldest retained log, and known gaps or deleted data. |
| Accounting | Assets, material account prefixes, balance invariants, backdated transactions, and reversions.  |
| Metadata   | Account and transaction keys, values with inconsistent formats, and deleted keys.               |
| Uniqueness | Transaction references and application-generated idempotency keys.                              |
| Clients    | Every writer, reader, scheduled job, reconciliation, SDK, and API path.                         |
| Events     | Exporters, pipelines, consumers, ordering assumptions, and deduplication keys.                  |
| Queries    | Filters, pagination, reports, and indexes required on the target.                               |
| Operations | Peak write rate, maintenance window, source-load budget, and escalation owner.                  |

Select representative fixtures now: high-value accounts, zero-balance accounts, each asset, boundary amounts, reverted transactions, backdated transactions, and metadata edge cases. You will use the same fixtures during rehearsal and production validation.

## Preflight an HTTP source

Run the request from the same network boundary as the target cluster. Use a client credential that can read source logs and nothing more.

```bash
set -euo pipefail

export V2_URL="https://ledger-v2.example.com"
export SOURCE_LEDGER="main-v2"
export V2_TOKEN="<short-lived-access-token>"

: "${V2_URL:?set V2_URL}"
: "${SOURCE_LEDGER:?set SOURCE_LEDGER}"
: "${V2_TOKEN:?set V2_TOKEN}"
command -v curl >/dev/null

curl --fail --silent --show-error \
  --header "Authorization: Bearer $V2_TOKEN" \
  "$V2_URL/v2/$SOURCE_LEDGER/logs?pageSize=1"
```

The response must contain either an empty `cursor.data` array or the newest source log. Record the returned log ID as the initial source head.

When Ledger v2 uses OAuth2 client credentials, test both the token endpoint and the log request. Provision the scope required by your Ledger v2 authorization policy; `ledger:read` is an example, not a universal scope name.

```bash
set -euo pipefail

export V2_TOKEN_ENDPOINT="https://auth.example.com/oauth/token"
export V2_CLIENT_ID="ledger-mirror"
export V2_CLIENT_SECRET="<client-secret>"
export V2_SCOPES="ledger:read"

: "${V2_TOKEN_ENDPOINT:?set V2_TOKEN_ENDPOINT}"
: "${V2_CLIENT_ID:?set V2_CLIENT_ID}"
: "${V2_CLIENT_SECRET:?set V2_CLIENT_SECRET}"
: "${V2_SCOPES:?set V2_SCOPES}"
command -v curl >/dev/null

curl --fail --silent --show-error \
  --user "$V2_CLIENT_ID:$V2_CLIENT_SECRET" \
  --data "grant_type=client_credentials" \
  --data-urlencode "scope=$V2_SCOPES" \
  "$V2_TOKEN_ENDPOINT"
```

Do not save the token or client secret in the migration record. Save the secret-manager entry name, field, owner, and rotation date.

## Preflight a PostgreSQL source

Run the following queries through the same hostname, TLS policy, database user, and network path that the target will use.

```sql
\set source_ledger 'main-v2'

SELECT name, bucket AS source_bucket
FROM _system.ledgers
WHERE name = :'source_ledger'
\gset
```

The query must return exactly one row. `\gset` stores the returned bucket as `source_bucket`; psql quotes it as an identifier in the next query:

```sql
SELECT COALESCE(MAX(id), 0) AS source_log_id
FROM :"source_bucket".logs
WHERE ledger = :'source_ledger';
```

The PostgreSQL identity needs `CONNECT` on the database, `USAGE` on `_system` and the selected bucket schema, `SELECT` on `_system.ledgers`, and `SELECT` on the selected bucket's `logs` table. Grant access only to the bucket returned for this ledger. The mirror does not need permission to create or modify Ledger v2 tables or schemas.

For PostgreSQL password authentication:

- store the password in the target deployment's secret manager;
- require TLS according to your database policy;
- test certificate and hostname verification when using `verify-ca` or `verify-full`.

For Amazon RDS IAM authentication:

- enable IAM database authentication for the source;
- grant the database user `rds_iam` as required by your RDS setup;
- grant the target Ledger runtime identity `rds-db:connect` for the exact database-user ARN;
- set the libpq DSN parameter to `sslmode=require`, `sslmode=verify-ca`, or `sslmode=verify-full`;
- if you assume a role, test `sts:AssumeRole` from the target runtime identity first.
- for rehearsal and cutover reads, generate a fresh IAM token for every psql process and pass it through that process's `PGPASSWORD`; do not store it in the DSN, command arguments, or evidence.

## Measure source capacity

The mirror reads logs in ascending order and continues polling after catch-up. A production rehearsal should establish:

- how many logs the mirror processes per minute;
- the added API or database load;
- how long a full replay takes;
- whether the mirror catches up after peak write periods;
- the target disk headroom during replay and index building.

Keep the default batch size for the first rehearsal. Increase it only after measuring source latency, target apply latency, and operational headroom.

## Define stop conditions

Stop the rehearsal or production replay when:

- source request latency or database load crosses the agreed limit;
- source credentials expose more access than approved;
- the target cannot read the earliest retained source log;
- a malformed source entry blocks the cursor;
- a transformation produces an unexplained balance or metadata difference;
- target disk pressure or write stalls prevent steady progress.

The mirror does not repair missing source history and does not compare source and target balances. Source access is a prerequisite, not proof that the migration is correct.

## Source-ready checklist

- [ ] Every source ledger has a worksheet and owner.
- [ ] The target network can reach the selected source transport.
- [ ] The credential has the minimum required read access.
- [ ] TLS and hostname validation match the production policy.
- [ ] The initial source log ID is recorded.
- [ ] Representative validation fixtures are recorded.
- [ ] Source load and stop thresholds are approved.
- [ ] All Ledger v2 writers can be identified and frozen during cutover.

Continue with [Update Ledger Clients](https://docs.formance.com/v4.0/modules/ledger/migration/update-clients).
