Back to the academy

Reversible atomic deployments and idempotency in critical systems

How to guarantee an order never runs twice, how to migrate a database without losing data and how to automate the rollback when a deployment fails.

Advanced · Prisma · MySQL · Bash · nginx

Never run the same order twice (exactly-once)

In a system that sends orders, retries are unavoidable: a timeout does not tell you whether the order arrived. The solution is to reserve the execution in the database before running it, with a unique constraint on its key: the first attempt inserts the reservation and carries on; any repetition hits the constraint and stops instead of sending a second order.

❌ Antipattern

async function execute(signal: Signal) {
  await exchange.placeOrder(signal); // a retry places a second order
  await db.order.create({ data: { signalId: signal.id } });
}

✅ Stoic pattern

async function execute(signal: Signal, botId: string) {
  try {
    // a unique index on (signalId, botId) reserves the execution first
    await db.execution.create({ data: { signalId: signal.id, botId, status: 'RESERVED' } });
  } catch (error) {
    if (isUniqueViolation(error)) return; // already executed or in flight
    throw error;
  }
  await exchange.placeOrder(signal);
}

Key takeaways

  • A timeout does not mean failure: design assuming every operation may be repeated.
  • Reserve before executing, with a unique constraint that makes a duplicate impossible.
  • Idempotency is guaranteed by the database, not by an in-memory `if`.

Database migrations without losing data

A migration that drops and recreates a table works locally and destroys production. Schema changes are made in backward-compatible steps: add the new column, backfill it, deploy the code that uses it and only then drop the old one. And when the migration history and the database disagree, you never reset: you reconcile the history with `migrate resolve` without touching the data.

❌ Antipattern

# "fixes" the drift... and wipes every table
npx prisma migrate reset --force

✅ Stoic pattern

# reconcile the migration history without touching the data
npx prisma migrate resolve --applied 20261028_add_course_progress
npx prisma migrate deploy

Key takeaways

  • Expand, then contract: add first, migrate the data, remove last.
  • Every migration must be able to coexist with the previous version of the code.
  • A reset is never the fix for migration drift, not even locally.

Automatic rollback when a deployment fails

An atomic deployment prepares the new version in its own directory and activates it by switching a single symbolic link: there is never an intermediate state with mixed files. If the healthcheck that follows fails, the script points the link back at the previous version and reloads the service. Rolling back becomes a matter of seconds that, on top of that, is rehearsed on every deployment.

Example

release="/srv/app/releases/$(date +%Y%m%d%H%M%S)"
previous="$(readlink /srv/app/current)"

cp -r dist "$release"
ln -sfn "$release" /srv/app/current && systemctl reload nginx

if ! curl --fail --retry 5 --retry-delay 3 https://example.com/health; then
  ln -sfn "$previous" /srv/app/current && systemctl reload nginx
  exit 1
fi

Key takeaways

  • Activating a version must be a single atomic change, such as a symbolic link.
  • Keep the previous version untouched until the new one proves it is healthy.
  • A rollback that only runs in emergencies is untested: automate it.