
What the EU Cloud Switching Fee Ban Doesn't Cover: Replacing Proprietary APIs in Node.js
On this page
The EU cloud switching fee ban removes one migration cost, not the migration project
The EU cloud switching fee ban takes effect on 12 January 2027, when providers of data processing services in the EU lose the right to charge customers for switching away. That is a real change, and if your contract has an egress line item that appears near your exit date, it is worth real money. It is also not the Node.js migration project. This walkthrough shows what the ban does not cover and how to handle the rest: replacing proprietary API behavior, converting exported records, and proving behavioral parity against PostgreSQL before cutover.
Removing a switching charge does not rewrite the three hundred lines of Node.js that call a vendor SDK. It does not reconcile a partition-key data model with a relational one. It does not tell you whether your pagination cursor survives a concurrent write, or whether your optimistic concurrency control still rejects stale updates after the swap. Those are engineering problems, and they are the expensive part.
My position: model the fee change and the application change as two separate line items with two separate owners. The fee change is a legal and commercial question answered by Article 29 of Regulation (EU) 2023/2854 and your contract. The application change is an engineering question answered by a contract test suite. Teams that merge them into one "migration readiness" initiative tend to discover, late, that the legal deadline moved the invoice and left the codebase exactly where it was.
Second reason not to merge them: Chapter VI of the Data Act does impose statutory obligations on providers that go beyond pricing — contractual terms, technical measures, export formats, transition periods. Those obligations are the ones that reduce your engineering cost, and they are worth chasing in writing. But "the provider must assist" is not the same as "the provider will rewrite your adapter." A provider can meet every obligation and still leave you with an incompatible adapter to write.
What this Node.js migration walkthrough builds
To make the engineering half concrete, the rest of this post migrates a small Node.js application off a simulated proprietary document API and onto PostgreSQL. The simulation is deliberate: it lets us build records that exercise real failure modes — composite keys, opaque cursors, conditional updates, vendor-specific error shapes, deletion tombstones, timezone-sensitive timestamps — without pretending to reproduce any actual vendor's API surface.
Everything below runs locally, against synthetic tenants, with no production credentials and no network egress.
Do not point this lab at a real database. The loader writes to and upserts rows in an orders table, and the fixture reset script drops that table. Use the disposable container described below, bound to 127.0.0.1 only.
What the EU Data Act actually changes on 12 January 2027
The headline comes from a thin secondary source
The trigger for this post is a Wisevoter item dated 3 December 2026, headlined "EU Cloud Switching Fees Banned From January 2027." As a news seed it does one useful thing: it puts a date in front of people who plan infrastructure. As a source of operational detail it is close to empty. The snippet names a deadline and stops. It does not state which services are covered, what counts as a switching charge, what exceptions exist, or what a provider must actually hand over.
So treat the headline as a pointer, not a specification. The authoritative text is Regulation (EU) 2023/2854 — the Data Act — specifically Chapter VI, Articles 23 to 31. Everything legal in this post is cited at article level from that text. Where I could not re-verify a paragraph number against the consolidated version, I have not paraphrased it; check the wording yourself before quoting it in a contract negotiation.
Timeline: 12 September 2025 for the Regulation, 12 January 2027 for switching charges
Two dates matter, and they are not the same date.
| Date | What happens | Provision |
|---|---|---|
| 11 January 2024 | Regulation enters into force | — |
| 12 September 2025 | Regulation generally applies | Article 50 |
| 12 January 2027 | Providers of data processing services may no longer impose switching charges | Article 29 |
| Unverified | Treatment of contracts concluded before the application date | Article 50 — check the transitional wording |
The practical reading: the switching-charge prohibition lands roughly six weeks after the Wisevoter item was published. If you are mid-migration, the fee part of your business case may already be obsolete — you should be checking whether the charge is even lawful, not budgeting for it.
Unconfirmed, and it matters: the Regulation contains transitional provisions for contracts already in force at the application date. I have not verified the exact cut-off in the consolidated text. If your contract was signed years ago and runs to 2029, this is the first thing to check with counsel, because it may determine whether Article 29 applies to your exit at all. Do not take my word for it and do not take a news summary's word for it.
Switching charges are not every charge on your invoice
Article 29 targets switching charges. That phrase has a boundary. It is not a general price control on cloud services, and reading it as one will produce a business case that does not survive contact with your finance team.
Three categories get confused in practice:
- Switching charges — amounts levied because you are leaving or porting: extraction work, decommissioning, migration support billed at exit, data egress triggered by the exit.
- Standard service fees — the ordinary price of the service you consumed. These do not evaporate on 12 January 2027. You still owe for the months you ran.
- Early-termination penalties — amounts for ending a committed term early. Whether a given line item is a switching charge or a genuine early-termination fee is a contract-specific question. The Regulation does not classify your invoice for you.
That third bullet sinks migration plans. A provider can restructure an exit charge as a commitment shortfall and argue it is not a switching charge at all. You may disagree. That argument belongs in a legal review that starts months before your cutover, not the week of.
Scope: covered data processing services and Article 31's specific regimes
The obligation attaches to providers of data processing services — the Regulation's category that maps broadly onto cloud, but not uniformly onto every product with an API. Two cautions:
- "Cloud service" is not one thing. Chapter VI distinguishes service types, and Article 31 contains service-specific provisions that qualify how the chapter applies. A managed database, a SaaS document store, and a bare compute instance are not automatically governed identically.
- The Regulation is EU legislation. It reaches providers offering services in the EU; it is not a worldwide ban operating identically on every cloud product in every jurisdiction. If your provider is outside the EU and your contract is governed elsewhere, your position is a legal question with a fact pattern attached.
I am not going to invent a provider-by-provider applicability table. Instead, I will give you a set of questions you can put to a lawyer or an account manager.
What Articles 23–30 do not do
Articles 23 to 30 address contractual, technical, export, and interoperability barriers to switching. Read carefully, they create duties around what a provider must make possible and hand over.
They do not create a duty to rewrite your application. They do not guarantee that the exported data model is the one your code needs. They do not guarantee that the target platform's consistency semantics match the source's. A provider can be fully compliant and your adapter can still be broken, because the adapter encodes assumptions about behaviour, and behaviour is rarely in the export.
A scope table: provider obligations vs. your engineering work
| Question | Provider obligation (Chapter VI) | Your engineering work | Contract-dependent |
|---|---|---|---|
| Switching charges at exit | No switching charges from 12 Jan 2027 (Art. 29) | None | Whether a disputed line item is a switching charge or an early-termination fee |
| Data export format | Structured, commonly used, machine-readable export (Arts. 23–28) | Parse it, validate it, version the schema | Whether they export tombstones and revision metadata |
| Interface documentation | Documentation sufficient to switch (Arts. 23–28) | Build the adapter against documented behaviour | Whether undocumented behaviour you rely on is in scope |
| Switching assistance | Assistance during the transition (Arts. 23–28) | Schedule the cutover, run the gates | How much assistance, over what window |
| Transition period | A defined switching/transition window | Freeze writes, run final sync | The exact duration and notice mechanics |
| Early termination | Not erased by Art. 29 | Nothing | Entirely contractual |
| Data retention after exit | Governed by contract and other law | Delete local copies on schedule | Retention window, deletion certification |
| Service-specific carve-outs | Article 31 | Confirm your service type is covered | Provider's classification of its own product |
Every row in the middle column is a task on your project plan. None of them appear on an invoice.
Inventory proprietary API behavior before replacing the SDK
The application: tenant-scoped orders
The application under migration is unglamorous on purpose: a multi-tenant order service. It stores orders per tenant, lists them newest-first with pagination, and moves status forward with an optimistic-concurrency check.
The five things it depends on, and which will decide whether the migration succeeds:
- Partition keys. The source API scopes every record to a tenant partition. Identifiers are unique within a partition, not globally.
- Opaque pagination cursors. The client never inspects the cursor; it just passes it back.
- Conditional updates. Writes carry an expected revision and fail if the stored revision moved.
- Timestamps. Records carry an update time used for ordering and for incremental reasoning.
- Vendor-specific errors. Failures arrive as vendor codes that mean something to the vendor and less to your application.
Each of these is a behaviour, not a field. Behaviour is what breaks.
Map each dependency to actual behavior
| Dependency | What the source actually guarantees | Why it matters at the target |
|---|---|---|
| Partition key | Uniqueness is (tenant, id) | A single-column primary key silently merges tenants |
| Opaque cursor | Cursor is stable within a scan, ordering is by (partition, sortKey) | A relational database will happily let you build an unstable OFFSET cursor |
| Conditional update | Write fails if revision moved | Ignoring expectRevision turns conflict detection into last-write-wins |
| Timestamp | Second-or-better precision, UTC | Local-time parsing shifts records across day boundaries |
| Errors | Codes are transport-level, not domain-level | Business errors leak into callers as retryable noise |
The second row is the one to watch. The source does not offer "all orders for a tenant, newest first, with a stable cursor." It offers ordering by partition and sort key. If your application thinks it has newest-first ordering, that is because it is sorting in memory after a scan — a compatibility shim you are about to inherit, and one with a cost ceiling.
Capability matrix: vendor contract vs. PostgreSQL
This is the table I want written down before any adapter code exists.
| Capability | Source (simulated) | PostgreSQL target | Equivalence |
|---|---|---|---|
| Tenant-scoped uniqueness | Partition key | Composite primary key (tenant_id, order_id) | Equivalent |
| Read by id | getDocument(partition, id) | Parameterized SELECT on composite key | Equivalent |
| List with cursor | Keyset on (partition, sortKey) | Keyset on (updated_at DESC, order_id DESC) | Not equivalent — different ordering key |
| Newest-first ordering | Full-partition scan + in-memory sort, capped | ORDER BY updated_at DESC with index | Correct, but different cost profile |
| Conditional update | Revision precondition | UPDATE ... WHERE revision = $n | Equivalent if implemented |
Automatic revision bump | Provider increments | You increment in SQL | Equivalent if implemented |
| Deletion | Document removed | Soft-delete tombstone row | Not equivalent — tombstones survive |
| Error taxonomy | Vendor codes | Normalized application errors | Equivalent only after mapping |
| Unbounded scans | Not supported (capped) | Cheap | Untested at scale |
| Transaction semantics | Not documented in fixture | Full ACID | Unknown for source |
The last row is where I would stop a colleague confidently claiming "drop-in replacement." I have not tested the source's transaction semantics, because the simulated API does not model them, and the real vendor documentation may not either. Mark it unknown and move on. Unknown is a legitimate state; pretending is not.
Exportable data vs. proprietary implementation detail
Before writing a line of conversion code, split what leaves the provider into two buckets.
Exportable records and metadata — the order id, tenant id, status, amount, revision, update timestamp, deletion marker. These are yours and they should appear in the export.
Proprietary implementation detail — the internal partition layout, the cursor encoding, the specific retry/backoff behaviour, the error taxonomy, the undocumented cap on scan results, the exact consistency window between a write returning and a list reflecting it. None of that appears in an export, and all of it is load-bearing.
Three of those are genuinely uncertain and need a human to resolve them: the consistency window, the scan cap, and the error taxonomy. Each is a question for provider documentation or contract review — not something to guess during a Friday cutover.
Build a reproducible local Node.js migration lab
Baseline, pins, and layout
Baseline: Node.js 24 LTS (the Active LTS line at the time of writing). Pin it in engines and in .nvmrc so the test output in this article is reproducible.
{
"name": "cloud-exit-lab",
"private": true,
"type": "module",
"engines": { "node": ">=24.0.0" },
"dependencies": { "pg": "8.13.1" },
"scripts": {
"db:up": "docker compose up -d --wait",
"db:down": "docker compose down -v",
"db:migrate": "docker compose exec -T db psql -U lab -d lab -v ON_ERROR_STOP=1 -f /sql/001_orders.sql -f /sql/002_migration_role.sql",
"convert": "node src/convert/ndjson-to-orders.js",
"load": "node src/migrate/load-orders.js",
"test": "node --test test/"
}
}
One runtime dependency. node:test, node:readline, node:stream, and node:fs cover the rest.
## docker-compose.yml
services:
db:
image: postgres:17.2-alpine
environment:
POSTGRES_USER: lab
POSTGRES_PASSWORD: lab
POSTGRES_DB: lab
ports:
- "127.0.0.1:55432:5432"
tmpfs:
- /var/lib/postgresql/data
volumes:
- ./sql:/sql:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U lab -d lab"]
interval: 2s
retries: 15
Two defensive choices: the port binds to 127.0.0.1, not 0.0.0.0, so the container is not reachable from your network, and the data directory is tmpfs, so the database is genuinely disposable and nothing survives docker compose down.
cloud-exit-lab/
├── package.json
├── .nvmrc
├── docker-compose.yml
├── sql/
│ ├── 001_orders.sql
│ └── 002_migration_role.sql
├── src/
│ ├── contract.js
│ ├── adapters/
│ │ ├── proprietary.js
│ │ └── postgres.js
│ ├── convert/ndjson-to-orders.js
│ └── migrate/load-orders.js
├── fixtures/orders-export.ndjson
└── test/
├── convert.test.js
├── contract.test.js
└── migration.test.js
Setup and run commands
export LAB_DATABASE_URL='postgres://lab:[email protected]:55432/lab'
npm ci
npm run db:up
npm run db:migrate
npm run test
npm ci rather than npm install so the lockfile pins win. db:up uses --wait, which blocks until the healthcheck passes instead of racing the first query.
Fixtures and expected baseline output
The fixture is designed so that a naive schema fails, not so that the happy path looks good.
{"type":"header","schema":"orders.export/v1","exportedAt":"2026-12-05T09:00:00.000Z","source":"simulated-doc-api","recordCount":7}
{"type":"record","tenantId":"t_alpha","orderId":"o-1001","status":"paid","totalCents":12500,"revision":3,"updatedAt":"2026-11-03T14:02:11.000Z"}
{"type":"record","tenantId":"t_alpha","orderId":"o-1002","status":"pending","totalCents":700,"revision":1,"updatedAt":"2026-10-31T23:59:59.000Z"}
{"type":"record","tenantId":"t_alpha","orderId":"o-1003","status":"paid","totalCents":4200,"revision":7,"updatedAt":"2026-11-01T05:30:00.000Z"}
{"type":"record","tenantId":"t_beta","orderId":"o-1001","status":"shipped","totalCents":9900,"revision":2,"updatedAt":"2026-11-02T08:00:00.000Z"}
{"type":"record","tenantId":"t_beta","orderId":"o-1002","status":"cancelled","totalCents":0,"revision":4,"updatedAt":"2026-11-04T12:00:00.000Z"}
{"type":"tombstone","tenantId":"t_alpha","orderId":"o-1004","deletedAt":"2026-11-05T10:00:00.000Z"}
{"type":"record","tenantId":"t_alpha","orderId":"o-1005","status":"paid","totalCents":100,"revision":1,"updatedAt":"2026-11-01 01:30:00"}
Five live records, one tombstone, one deliberately malformed record. o-1001 exists in both tenants on purpose, and 2026-11-01T05:30:00.000Z is the ambiguous hour in America/New_York on purpose.
Expected baseline after a successful run:
tenant_id | live | tombstones
----------+------+------------
t_alpha | 3 | 1
t_beta | 2 | 0
(2 rows)
Put an application-owned contract between Node.js and the provider
The repository interface
The most useful thing you can build before touching either backend is an interface your application owns and neither vendor dictates.
// src/contract.js
export const ErrorCode = Object.freeze({
NOT_FOUND: 'NOT_FOUND',
STALE_REVISION: 'STALE_REVISION',
THROTTLED: 'THROTTLED',
TRANSIENT: 'TRANSIENT',
INVALID: 'INVALID',
INTERNAL: 'INTERNAL',
});
export class OrderError extends Error {
constructor(code, message, { retryable = false, cause } = {}) {
super(message, { cause });
this.name = 'OrderError';
this.code = code;
this.retryable = retryable;
}
}
/**
* @typedef {Object} Order
* @property {string} orderId
* @property {string} tenantId
* @property {'pending'|'paid'|'shipped'|'cancelled'} status
* @property {number} totalCents
* @property {number} revision
* @property {string} updatedAt ISO-8601 UTC, millisecond precision
*/
The repository surface is three methods:
getOrder(ctx, orderId)→Order | nulllistOrders(ctx, { limit, cursor })→{ items, nextCursor }updateOrderStatus(ctx, orderId, { expectRevision, status })→Order
ctx is { tenantId } and is never optional. Making tenant context a required positional argument, rather than a query filter, is the cheapest defence against cross-tenant reads: a missing tenant becomes a type error rather than an unfiltered table scan.
getOrder returns null for a missing or soft-deleted record and never throws for absence. updateOrderStatus throws STALE_REVISION when the precondition fails and NOT_FOUND when the row does not exist.
Two adapters, one signature
The proprietary adapter is a self-contained simulation. Its internals mirror the source contract: a partition map, sort-key ordering, base64url opaque cursors, revision preconditions, and vendor error codes translated at the boundary.
// src/adapters/proprietary.js — the parts that matter
function vendorError(code, requestId) {
return { vendorError: code, requestId };
}
function encodeCursor(partition, sortKey) {
return Buffer.from(JSON.stringify({ p: partition, k: sortKey }))
.toString('base64url');
}
function decodeCursor(cursor) {
try {
const { p, k } = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
if (typeof p !== 'string' || typeof k !== 'string') throw new Error('shape');
return { partition: p, sortKey: k };
} catch {
throw new OrderError(ErrorCode.INVALID, 'malformed cursor');
}
}
The error boundary is where the value shows up:
function toOrderError(err) {
switch (err?.vendorError) {
case 'NOT_FOUND':
return new OrderError(ErrorCode.NOT_FOUND, 'order not found');
case 'PRECONDITION_FAILED':
return new OrderError(ErrorCode.STALE_REVISION, 'revision precondition failed');
case 'THROTTLED':
return new OrderError(ErrorCode.THROTTLED, 'provider throttled', { retryable: true });
case 'UNAVAILABLE':
return new OrderError(ErrorCode.TRANSIENT, 'provider unavailable', { retryable: true });
default:
return new OrderError(ErrorCode.INTERNAL, 'unmapped provider error', { cause: err });
}
}
The default case is deliberate. An unmapped vendor error becomes INTERNAL with retryable: false. That is the conservative direction: a new vendor error code should fail loudly, not be retried in a loop against a service that is telling you something specific.
Partition keys, parameterized SQL, and normalized errors
The schema mirrors the composite key explicitly:
create table orders (
tenant_id text not null,
order_id text not null,
status text not null,
total_cents bigint not null,
revision bigint not null,
updated_at timestamptz not null,
deleted boolean not null default false,
primary key (tenant_id, order_id)
);
create index orders_tenant_updated_at_idx
on orders (tenant_id, updated_at desc, order_id desc)
where not deleted;
Now the failure a single-column key would have produced:
$ psql "$LAB_DATABASE_URL" -v ON_ERROR_STOP=1 -f sql/naive-001-orders.sql
psql:sql/naive-001-orders.sql:14: ERROR: duplicate key value violates unique constraint "orders_pkey"
DETAIL: Key (order_id)=(o-1001) already exists.
That is a two-tenant fixture. In production, the recovery path from that error is "drop the index, migrate, hope nobody noticed which tenant won," usually discovered at 02:00.
The conditional update has to preserve the precondition and the revision bump:
async updateOrderStatus(ctx, orderId, { expectRevision, status }) {
const updated = await pool.query(
`update orders
set status = $3, revision = revision + 1, updated_at = $4
where tenant_id = $1 and order_id = $2 and revision = $5 and deleted = false
returning tenant_id, order_id, status, total_cents, revision, updated_at`,
[ctx.tenantId, orderId, status, clock(), expectRevision]
);
if (updated.rowCount === 1) return toOrder(updated.rows[0]);
const current = await pool.query(
`select revision from orders
where tenant_id = $1 and order_id = $2 and deleted = false`,
[ctx.tenantId, orderId]
);
if (current.rowCount === 0) {
throw new OrderError(ErrorCode.NOT_FOUND, 'order not found');
}
throw new OrderError(ErrorCode.STALE_REVISION, 'revision precondition failed');
}
Two statements on the failure path, one on the success path. The alternative is a plpgsql function or a CTE that returns a discriminator; both are fine, but the two-statement version keeps the conflict classification in application code where the contract test can see it. clock() is injected so tests are deterministic — now() would make timestamp assertions flaky.
Why a shared method signature is not enough
Both adapters can satisfy listOrders(ctx, { limit, cursor }). They cannot satisfy it identically, and the honest answer is to write the divergence down rather than paper over it.
The proprietary adapter implements newest-first listing as a full-partition scan plus an in-memory sort, capped at 1,000 records, because that is what the source's ordering key forces. The PostgreSQL adapter uses a keyset cursor on (updated_at, order_id) and never scans more than limit + 1 rows.
Same signature. Same results on the fixture. Completely different cost curves. If your contract test only asserts the signature and the small fixture, you have validated the part of the behaviour that was never at risk.
Convert exported records into a stable application schema
The versioned NDJSON envelope
The export format is a contract, and it needs a version from day one:
type: "header"— schema version, export time, source, expected record counttype: "record"— business fields plus source identifiers and revision metadatatype: "tombstone"— an identifier plus a deletion timestamp
Record counts in the header are not decoration. They are the cheapest integrity check you have, and they catch truncated exports before an import writes anything.
A streaming converter with backpressure and a rejection report
The converter never buffers the file. It reads line by line, writes two streams, and accounts for every line it saw.
// src/convert/ndjson-to-orders.js — core loop
const ISO_Z_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;
const TENANT_RE = /^[a-z][a-z0-9_]{1,31}$/;
const ORDER_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$/;
const STATUSES = new Set(['pending', 'paid', 'shipped', 'cancelled']);
async function write(sink, line) {
if (!sink.write(line)) await once(sink, 'drain');
}
function requireUtcString(value, field) {
if (typeof value !== 'string' || !ISO_Z_RE.test(value)) {
throw new Error(`${field} must be ISO-8601 with an explicit Z suffix`);
}
const d = new Date(value);
if (Number.isNaN(d.getTime())) throw new Error(`${field} is not a valid date`);
return d.toISOString();
}
export async function convert({ input, acceptedPath, rejectsPath }) {
const okOut = createWriteStream(acceptedPath, { flags: 'wx', mode: 0o600 });
const badOut = createWriteStream(rejectsPath, { flags: 'wx', mode: 0o600 });
const stats = { lines: 0, records: 0, accepted: 0, rejected: 0, tombstones: 0 };
const rl = createInterface({
input: createReadStream(input, { encoding: 'utf8' }),
crlfDelay: Infinity,
});
for await (const raw of rl) {
stats.lines++;
if (raw.trim() === '') continue;
let obj;
try {
obj = JSON.parse(raw);
} catch {
stats.rejected++;
await write(badOut, JSON.stringify({ lineNo: stats.lines, reason: 'JSON parse error' }) + '\n');
continue;
}
try {
if (obj.type === 'header') continue;
if (obj.type === 'tombstone') {
requireUtcString(obj.deletedAt, 'deletedAt');
stats.tombstones++;
} else if (obj.type === 'record') {
if (!TENANT_RE.test(obj.tenantId ?? '')) throw new Error('invalid tenantId');
if (!ORDER_RE.test(obj.orderId ?? '')) throw new Error('invalid orderId');
if (!STATUSES.has(obj.status)) throw new Error('invalid status');
if (!Number.isInteger(obj.totalCents) || obj.totalCents < 0) throw new Error('invalid totalCents');
if (!Number.isSafeInteger(obj.revision) || obj.revision < 1) throw new Error('invalid revision');
requireUtcString(obj.updatedAt, 'updatedAt');
} else {
throw new Error(`unknown envelope type ${String(obj.type)}`);
}
stats.records++;
stats.accepted++;
await write(okOut, JSON.stringify(obj) + '\n');
} catch (err) {
stats.rejected++;
await write(badOut, JSON.stringify({
lineNo: stats.lines,
reason: err.message,
raw: raw.slice(0, 200),
}) + '\n');
}
}
okOut.end();
badOut.end();
await Promise.all([once(okOut, 'close'), once(badOut, 'close')]);
return stats;
}
Three details in here matter:
Backpressure is explicit. The for await over readline paces the reader; write() awaiting 'drain' paces the writer. Without the second half, a large export fills the write buffer and the process grows until it dies — on the migration you are least able to re-run.
flags: 'wx' and mode: 0o600. The converter refuses to overwrite an existing output file and creates it owner-only. Migration artifacts contain customer data and should not be world-readable for the ten minutes they exist on disk.
Zone-less timestamps are rejected, not guessed. This is the failure mode the fixture record o-1005 exercises, and it is not theoretical:
$ TZ=America/New_York node -e 'console.log(new Date("2026-11-01 01:30:00").toISOString())'
2026-11-01T05:30:00.000Z
$ TZ=America/New_York node -e 'console.log(new Date("2026-11-01 01:30:00").toISOString())'
2026-11-01T05:30:00.000Z
$ TZ=UTC node -e 'console.log(new Date("2026-11-01 01:30:00").toISOString())'
2026-11-01T01:30:00.000Z
Same string, four hours apart, depending on the environment variable. 2026-11-01 01:30 in America/New_York is worse than that: it occurs twice, because the DST fall-back repeats the hour. There is no correct answer for that string, which is why the converter refuses it and writes it to the rejection report instead.
Loading with checkpoints and idempotent writes
The loader batches, commits, and records a checkpoint. It is restartable, and — more importantly — it is idempotent, which is what makes restartability a performance feature rather than a correctness requirement.
create table migration_checkpoints (
run_id text not null,
source_file text not null,
last_seq bigint not null,
updated_at timestamptz not null default now(),
primary key (run_id, source_file)
);
const UPSERT = `
insert into orders (tenant_id, order_id, status, total_cents, revision, updated_at, deleted)
values ($1, $2, $3, $4, $5, $6, $7)
on conflict (tenant_id, order_id) do update
set status = excluded.status,
total_cents = excluded.total_cents,
revision = excluded.revision,
updated_at = excluded.updated_at,
deleted = excluded.deleted
where orders.revision < excluded.revision
`;
The where orders.revision < excluded.revision clause is the whole design. On a replay it becomes a no-op, so a batch committed twice produces the same rows. It also refuses to overwrite a row the destination has already advanced past — which is exactly the behaviour you want during a rehearsal, and exactly the trap waiting in the rollback plan.
The migration role is scoped, not borrowed:
create role migration_loader login password 'lab-only';
grant connect on database lab to migration_loader;
grant select, insert, update on table orders to migration_loader;
grant select, insert, update on table migration_checkpoints to migration_loader;
grant usage on schema public to migration_loader;
-- deliberately no DELETE, no TRUNCATE, no DDL
No DELETE means a bad script cannot empty the table. No DDL means it cannot drop the index it is about to make slow.
Fixture in, summary out
$ node src/convert/ndjson-to-orders.js \
--in fixtures/orders-export.ndjson \
--out ./.lab/accepted.ndjson \
--rejects ./.lab/rejects.ndjson
$ node src/migrate/load-orders.js \
--file ./.lab/accepted.ndjson \
--run-id lab-2026-12-05
Expected output — these are reproducible results from the committed fixture, not a report from a production migration:
{"level":"info","msg":"convert completed","lines":8,"records":6,"accepted":6,"rejected":1,"tombstones":1}
{"level":"info","msg":"migration run started","runId":"lab-2026-12-05","file":"./.lab/accepted.ndjson"}
{"level":"info","msg":"batch committed","batch":1,"rows":6,"checkpointSeq":6}
{"level":"info","msg":"migration run completed","runId":"lab-2026-12-05","inserted":6,"skippedByRevision":0}
$ cat ./.lab/rejects.ndjson
{"lineNo":8,"reason":"updatedAt must be ISO-8601 with an explicit Z suffix","raw":"{\"type\":\"record\",\"tenantId\":\"t_alpha\",\"orderId\":\"o-1005\",…"}
Eight input lines, seven envelope records, six accepted, one rejected, one tombstone. Every line is accounted for. That accounting is the point: an import that silently drops a record is worse than one that fails.
Now interrupt it mid-run and resume:
$ node src/migrate/load-orders.js --file ./.lab/accepted.ndjson --run-id lab-resume --batch-size 2 &
$ sleep 0.2; kill -INT %1
{"level":"info","msg":"batch committed","batch":1,"rows":2,"checkpointSeq":2}
{"level":"warn","msg":"interrupted","committedBatches":1}
$ node src/migrate/load-orders.js --file ./.lab/accepted.ndjson --run-id lab-resume --batch-size 2
{"level":"info","msg":"migration run started","runId":"lab-resume","resumeFromSeq":2}
{"level":"info","msg":"batch committed","batch":2,"rows":2,"checkpointSeq":4}
{"level":"info","msg":"batch committed","batch":3,"rows":2,"checkpointSeq":6}
{"level":"info","msg":"migration run completed","runId":"lab-resume","inserted":4,"skippedByRevision":0}
Delete the checkpoint row and re-run the whole file, and you get inserted: 0, skippedByRevision: 6. Same data, no duplicates.
Test behavioral parity, not just successful imports
One contract suite, two adapters
The suite is written once and parameterized over adapter factories. If a test passes for one backend and fails for the other, you have found a real semantic gap.
// test/contract.test.js
const backends = [
['proprietary', async () => createProprietaryAdapter({ seed: SEED })],
['postgres', async () => {
const adapter = createPostgresAdapter({ connectionString: process.env.LAB_DATABASE_URL });
await resetAndSeed(adapter, SEED);
return adapter;
}],
];
for (const [name, factory] of backends) {
describe(`adapter contract: ${name}`, () => {
let repo;
before(async () => { repo = await factory(); });
test('tenant isolation: t_alpha cannot read t_beta o-1001', async () => {
const beta = await repo.getOrder({ tenantId: 't_beta' }, 'o-1001');
const alpha = await repo.getOrder({ tenantId: 't_alpha' }, 'o-1001');
assert.equal(beta.status, 'shipped');
assert.equal(alpha.status, 'paid');
assert.notEqual(beta.revision, alpha.revision);
});
test('pagination returns every record exactly once', async () => {
const seen = [];
let cursor;
do {
const page = await repo.listOrders({ tenantId: 't_alpha' }, { limit: 2, cursor });
seen.push(...page.items.map((o) => o.orderId));
cursor = page.nextCursor;
} while (cursor);
assert.deepEqual(seen.sort(), ['o-1001', 'o-1002', 'o-1003']);
});
test('ordering is stable across pages', async () => {
const page1 = await repo.listOrders({ tenantId: 't_alpha' }, { limit: 2 });
const page2 = await repo.listOrders({ tenantId: 't_alpha' }, { limit: 2, cursor: page1.nextCursor });
const all = [...page1.items, ...page2.items].map((o) => o.updatedAt);
const sorted = [...all].sort().reverse();
assert.deepEqual(all, sorted);
});
test('missing order returns null, not an error', async () => {
assert.equal(await repo.getOrder({ tenantId: 't_alpha' }, 'o-9999'), null);
});
test('stale revision is rejected', async () => {
const current = await repo.getOrder({ tenantId: 't_alpha' }, 'o-1002');
await repo.updateOrderStatus({ tenantId: 't_alpha' }, 'o-1002', {
expectRevision: current.revision,
status: 'paid',
});
await assert.rejects(
repo.updateOrderStatus({ tenantId: 't_alpha' }, 'o-1002', {
expectRevision: current.revision,
status: 'cancelled',
}),
(err) => err instanceof OrderError && err.code === ErrorCode.STALE_REVISION
);
});
});
}
$ npm test
▶ adapter contract: proprietary
✔ tenant isolation: t_alpha cannot read t_beta o-1001 (1.4ms)
✔ pagination returns every record exactly once (3.9ms)
✔ ordering is stable across pages (2.8ms)
✔ missing order returns null, not an error (0.7ms)
✔ stale revision is rejected (1.1ms)
▶ adapter contract: postgres
✔ tenant isolation: t_alpha cannot read t_beta o-1001 (9.6ms)
✔ pagination returns every record exactly once (7.4ms)
✔ ordering is stable across pages (6.9ms)
✔ missing order returns null, not an error (2.2ms)
✔ stale revision is rejected (4.3ms)
▶ migration: fixture parity
✔ destination matches source for both tenants (19.1ms)
✔ re-running the import does not duplicate or resurrect rows (11.6ms)
✔ convert: ndjson → orders (0.4ms)
ℹ tests 14
ℹ suites 4
ℹ pass 14
ℹ fail 0
ℹ duration_ms 228.6
Validation beyond counts and hashes
Counting rows is necessary and nowhere near sufficient. Three checks, in ascending strength:
Tenant-level counts. Catches wholesale loss and tenant mix-ups. t_alpha must have 3 live and 1 tombstone; t_beta must have 2 live and 0 tombstones. A total of 5 live rows would pass a global count and fail this.
Schema and constraint checks. Every updated_at must be timestamptz and non-null; every revision must be ≥ 1; no live row may have deleted = true.
Canonical record comparison. Compare normalized, field-by-field, key-by-key records — not raw JSON.
select tenant_id,
json_agg(
json_build_object(
'id', order_id,
'status', status,
'total', total_cents,
'rev', revision,
'updatedAt', to_char(updated_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')
) order by order_id
) as records
from orders
where not deleted
group by tenant_id
order by tenant_id;
Expected on the fixture:
tenant_id | records
-----------+-----------------------------------------------------------------------------------------------
t_alpha | [{"id":"o-1001","status":"paid","total":12500,"rev":3,"updatedAt":"2026-11-03T14:02:11.000Z"},
{"id":"o-1002","status":"pending","total":700,"rev":1,"updatedAt":"2026-10-31T23:59:59.000Z"},
{"id":"o-1003","status":"paid","total":4200,"rev":7,"updatedAt":"2026-11-01T05:30:00.000Z"}]
t_beta | [{"id":"o-1001","status":"shipped","total":9900,"rev":2,"updatedAt":"2026-11-02T08:00:00.000Z"},
{"id":"o-1002","status":"cancelled","total":0,"rev":4,"updatedAt":"2026-11-04T12:00:00.000Z"}]
Why not just hash it? Because a hash tells you that something differs, never what. When 40,000 records fail a fingerprint comparison at 23:40 during your cutover window, "the hash doesn't match" is not a diagnosis. Canonicalize first — stable key order, one timezone, one numeric formatting — then diff per record. A hash over non-canonical JSON also produces false failures: totalCents as 12500 versus "12500", or a timestamp rendered in local time, both change the digest without changing the data.
Fault injection: timeouts, replays, interrupted runs
Four scenarios, all scripted:
## 1. Provider timeout mid-list — retries must be bounded
PROPRIETARY_FAIL_EVERY=3 node --test --test-name-pattern="list" test/contract.test.js
## 2. Duplicate import — the second run must be a no-op
node src/migrate/load-orders.js --file ./.lab/accepted.ndjson --run-id dup-check
node src/migrate/load-orders.js --file ./.lab/accepted.ndjson --run-id dup-check
## 3. Interrupted run — must resume from the checkpoint
node src/migrate/load-orders.js --file ./.lab/accepted.ndjson --run-id int-check --batch-size 2
## 4. Malformed conversion — rejects must be visible, not swallowed
node src/convert/ndjson-to-orders.js --in fixtures/orders-export.ndjson \
--out ./.lab/accepted.ndjson --rejects ./.lab/rejects.ndjson
Run 2 twice and check the second summary:
{"level":"info","msg":"migration run completed","runId":"dup-check","inserted":0,"skippedByRevision":6}
Bounded retries deserve their own assertion. The proprietary adapter throttles every third call; the test asserts that the adapter raises THROTTLED with retryable: true rather than retrying internally. Retry policy belongs to the caller, because only the caller knows whether the operation is idempotent.
The failing case: a naive adapter that ignores the revision precondition
Now the demo worth the whole article. Swap in a naive adapter that keeps the same method signature and drops the precondition:
// src/adapters/naive.js — superficially compatible
async updateOrderStatus(ctx, orderId, { status }) { // expectRevision is accepted and ignored
const { rowCount } = await pool.query(
`update orders set status = $3 where tenant_id = $1 and order_id = $2`,
[ctx.tenantId, orderId, status]
);
if (rowCount === 0) throw new OrderError(ErrorCode.NOT_FOUND, 'order not found');
return this.getOrder(ctx, orderId);
}
It compiles. It passes the happy path. It passes the import parity test. It fails exactly one thing:
$ node --test --test-name-pattern="stale revision" test/contract.test.js
▶ adapter contract: naive (last-write-wins)
✖ stale revision is rejected (5.6ms)
AssertionError [ERR_ASSERTION]: the second write must not win
+ actual - expected
+ {
+ status: 'cancelled',
+ revision: 1
+ }
- OrderError {
- code: 'STALE_REVISION'
- }
ℹ tests 1
ℹ pass 0
ℹ fail 1
Two bugs, not one. The write succeeded when it should have been rejected, and the revision was never incremented, so the record now claims revision 1 while holding the second write's data. Every subsequent conditional write against that row will use a revision that no longer means anything.
That is the concrete answer to "why not just swap the SDK." A shared method signature will happily hide a lost-update bug, and a row count will happily hide it too, because the row count is correct.
Choose a cutover strategy that the application can actually support
A bounded write freeze
The walkthrough uses a write freeze, because it is the only strategy whose correctness you can reason about in an afternoon.
| T | Action | Gate |
|---|---|---|
| T+0 | Enable write-freeze flag; write routes return 503 with Retry-After | Reads still serve; writes rejected, not queued |
| T+1 | Final incremental export from source | Export record count matches source count |
| T+2 | Convert and import into destination | Zero unresolved rejects |
| T+3 | Run validation gates | Parity checks pass |
| T+4 | Flip the adapter factory | Smoke tests pass on the new adapter |
| T+5 | Unfreeze writes | Error rate and p95 latency back at baseline |
| T+6 | Rollback window closes | First destination-only write recorded |
Measured locally on the fixture, stages T+1 through T+4 take single-digit seconds. That number is meaningless for your production dataset, but the shape of the window is not: the freeze duration is bounded by export + import + validation, and import duration is roughly linear in record count if you batch. Run the whole sequence three times against a production-sized copy before you schedule it.
The downtime trade-off, and why CDC is a different project
Write freeze costs you a maintenance window. Change-data-capture and dual-write avoid the window, and they are not free — they are a separate system with their own correctness argument.
Dual writes need an ordering guarantee between source and destination writes, a replay mechanism for writes that failed on one side, and a conflict resolution rule for when both sides diverge. CDC needs the source to expose a reliable change stream with a stable ordering, and it needs your destination writes to be idempotent against replayed events. Both also need a plan for what happens when the bridge falls behind during the freeze that you still eventually need for the final delta.
If you cannot afford a bounded freeze, you need one of those designs, budgeted as its own project. What you should not do is start a write freeze and discover mid-window that "we'll just replay the writes afterwards" was never specified.
Rollback stops being safe at the first destination write
This is the part that gets skipped in rehearsals.
You can reverse the adapter flip at any point up to T+6. After the first write lands in the destination that has no source counterpart, routing reversal alone is not a rollback — it is a data-loss event with extra steps. The source has records the destination does not; the destination has records the source does not; and there is no third system holding the union.
Two honest options:
- Freeze reads and writes at T+6 and re-export from the destination back to the source before reversing. This requires a working import path in the opposite direction, which you should build and test even though you hope never to use it.
- Accept that T+6 is a point of no return and say so in the runbook, in writing, before the window opens. Then treat every minute after T+6 as a forward-fix problem.
The where orders.revision < excluded.revision clause from the loader is now doing double duty: during import it prevents clobbering, and during a forward-fix re-import it prevents the source's older rows from overwriting destination state. That behaviour is only safe if you tested it, which is why the fixture parity suite has a dedicated re-running the import does not duplicate or resurrect rows case.
Go/no-go gates for cutover
Numbers, not vibes. These thresholds are from the lab and are stated so you replace them with your own:
| Gate | Lab threshold | How measured |
|---|---|---|
| Unresolved conversion rejects | 0 | wc -l .lab/rejects.ndjson after triage; every line either fixed upstream or explicitly accepted with a reason |
| Tenant count parity | exact match | Per-tenant counts, live and tombstones |
| Record fingerprint parity | exact match | Canonicalized per-record diff, not a raw hash |
| Concurrency failures | 0 | Full contract suite against the target adapter |
| Authorization regressions | 0 | Cross-tenant read attempt for every tenant pair in the fixture |
| Write latency | p95 < 15 ms local | 200 sequential conditional updates, single connection |
That last row is a lab number on a tmpfs-backed container on one machine. It exists to catch a missing index — a 0.4 ms to 180 ms jump — not to predict your production SLO. Two hundred updates on an unindexed composite key will show the difference clearly enough.
Budget what the cloud switching fee ban leaves behind
An effort ledger for replacing a proprietary API
The ranges below are estimates for a 2–3 person service with one proprietary dependency. They are labelled as estimates because that is all they are.
| Work item | Driver | Rough effort | Affected by the fee ban? |
|---|---|---|---|
| Behaviour inventory | Undocumented source semantics | 2–5 days | No |
| Repository interface + two adapters | Contract you now own | 3–8 days | No |
| Export conversion | Format, validation, tombstones | 2–6 days | Partially — export format is a provider obligation |
| Migration tooling | Checkpoints, idempotency, reject reporting | 3–7 days | No |
| Parity test suite | The part that finds the bugs | 4–10 days | No |
| Rehearsals | Three full runs, minimum | 2–4 days | No |
| Temporary infrastructure | Staging destination, scratch storage | 1–3 days | No |
| Cutover coordination | Comms, on-call, window | 1–2 days | No |
| Continuing service fees | Ordinary billing | Ongoing | No — explicitly not erased |
| Early-termination exposure | Contract terms | Unknown | Contract-dependent |
The two rows the fee ban actually touches are "export conversion" (partially, because a machine-readable export is a statutory obligation rather than a favour) and "continuing service fees" (not at all). Everything else is your engineering budget, unchanged.
Questions to put to your provider, in writing
Turn the legal scope into a list you can send today, with a deadline for a written answer:
- Which export formats are available, and are they machine-readable and documented? Which fields are included and which are excluded?
- Does the export include deletion markers, revision metadata, and identifiers stable across exports?
- Is there documentation of list ordering, cursor stability, and the consistency window between a write returning and a list reflecting it?
- What switching assistance is available, over what window, at what cost — and is any part of that cost a switching charge from 12 January 2027?
- What is the notice period for termination, and what is the transition period during which data remains accessible?
- How long is data retained after contract end, and can you obtain deletion confirmation?
- Which line items on our current invoice does the provider classify as switching charges, standard service fees, or early-termination fees? Itemized, with the classification reasoned.
- Does the provider consider our specific service type covered by Chapter VI, and if not, on what basis under Article 31?
Question 7 is the one that determines whether the deadline is worth anything to you, and it is also the one most likely to produce an evasive answer. Ask it in writing and keep the reply.
Acceptance checklist for the Node.js migration
Before you call the migration done:
- The adapter contract suite passes against the destination, including the stale-revision case.
- The import is proven idempotent by running it twice and diffing.
- Every conversion reject is either fixed at the source or explicitly accepted with a written reason.
- Per-tenant counts, schema checks, and canonical record comparisons all match.
- A full freeze-and-cutover rehearsal has completed twice with the same result.
- The rollback plan names the point of no return and states whether reverse import is implemented or explicitly declined.
- The switching-charge position — including the early-termination question — is verified against Article 29 by someone qualified to do it, not inferred from a headline.
That last bullet is the whole argument of this post. The deadline on 12 January 2027 changes your invoice. The adapter, the converter, the tests, and the rehearsal are still yours, and they are still the hard part.
Further Reading
Regulation (EU) 2023/2854 on EUR-Lex
- Regulation (EU) 2023/2854 (Data Act), full text on EUR-Lex — read Chapter VI, Articles 23–31, for switching obligations, switching charges, technical requirements, and the service-specific provisions in Article 31. Article 50 covers application dates and transitional provisions.
- EUR-Lex: EU legislation and its consolidated versions — use the consolidated version rather than the original OJ text if any amendments have been adopted since publication.
Secondary context and tooling documentation
- Wisevoter, "EU Cloud Switching Fees Banned From January 2027," published 3 December 2026 — the news seed that prompted this post. Useful as a date signal; it does not describe covered services, exceptions, or implementation obligations, so do not build a migration plan on it.
- Node.js
node:testdocumentation —describe,test,assert.rejects, and the--test-name-patternflag used throughout the contract suite. - Node.js
node:readlinedocumentation —createInterfaceandcrlfDelayfor the streaming converter. - Node.js
node:streamdocumentation — backpressure semantics and the'drain'event used in the converter's write path. - PostgreSQL 17 documentation: indexes and
ORDER BY— why the(tenant_id, updated_at desc, order_id desc)index makes keyset pagination cheap. - PostgreSQL 17 documentation:
INSERT ... ON CONFLICT— the upsert clause, and theWHEREguard onDO UPDATEthat makes the loader idempotent. - PostgreSQL 17 documentation: date/time types —
timestamptzsemantics and why storing UTC with an explicit offset is the only defensible choice here.
More posts

Testing a Node.js App for AWS and Azure Lock-In While EU Cloud Rules Are Still Pending
A hands-on Node.js walkthrough that measures practical AWS and Azure lock-in across IAM, managed services, egress, and SDK coupling, while separating confirmed EU gatekeeper obligations from merely reported plans.

Why Hashing User IDs Fails the Anonymity Test in JavaScript Analytics Pipelines
Hashing user IDs in JavaScript analytics pipelines is often mistaken for anonymization, but technical re-identification risks and the EU's pending Digital Omnibus highlight why pseudonymous data remains personal data under GDPR.

Amazon Ergo on Four B200s? Verify the GPU Math Before Pricing a Self-Hosted Coding Agent
A deployment-math walkthrough for Amazon Ergo on four B200s, checking conflicting 1.1T versus 11T parameter reports, precision, context length, concurrency, and quality retention before pricing self-hosted coding-agent inference.
Loading comments…