Rolling back a bad release
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A new ShopLite release goes live and orders start failing within minutes. Customers are affected right now, so the question is not who to blame but how to bring the last good version back safely.
Spotting a bad release
A rollback puts the previous, known-good version back into production while you find out what went wrong with the new one. With SHA-tagged images it takes about a minute.
A bad release shows within minutes of a deploy: more 5xx errors, a slower p95, or a key action such as placing an order failing. The program below compares error counts before and after.
Example 1 · Did the release make it worse?
public class BadReleaseDemo { static double average(int[] values, int from, int to) { double sum = 0; for (int i = from; i < to; i++) { sum += values[i]; } return sum / (to - from); }
public static void main(String[] args) { // 5xx errors per minute; the deploy finished after minute 5 (index 4) int[] errorsPerMinute = {1, 0, 2, 1, 1, 14, 19, 22, 18, 21}; int deployIndex = 5;
double before = average(errorsPerMinute, 0, deployIndex); double after = average(errorsPerMinute, deployIndex, errorsPerMinute.length); System.out.printf("Before deploy: %.1f errors/min%n", before); System.out.printf("After deploy: %.1f errors/min%n", after); if (after > 3 * before && after >= 5) { System.out.println("Errors rose sharply right after the deploy: roll back, then investigate."); } else { System.out.println("No clear change after the deploy: look elsewhere."); } }}Before deploy: 1.0 errors/min After deploy: 18.8 errors/min Errors rose sharply right after the deploy: roll back, then investigate.
What this code does
- Comparing the same metric just before and just after the deploy separates "the release did this" from "errors happen anyway".
- The rule needs both a big ratio and a real number (at least 5 a minute), so one extra error on a quiet night does not trigger a rollback.
Compare the same metric for the minutes before and after the deploy finished, and check the logs for a new error type. If the release is the likely cause and users are affected, roll back first and investigate afterwards. Fixing forward under pressure, while customers keep failing, usually takes longer than you expect.
Rollback options
Fix forward means solving the problem with a new release instead of going back to the old one. It is faster only when the fix is tiny, certain and already tested.
All the ways back redeploy an image that already exists. The first example finds the previous tag; the second rolls back on the VM and then reverts the commit in Git.
Example 2 · Finding the previous version in deployed-tags.log
import java.util.List;
public class RollbackTargetDemo { public static void main(String[] args) { // /opt/shoplite/deployed-tags.log, written by deploy.sh (newest last) List<String> log = List.of( "2026-10-14T10:02:11Z 91d2a7c4e0b13f5a6c8d9e0f1a2b3c4d5e6f7a8b", "2026-10-15T16:40:09Z 3f9c2e1b7d4a5c6e8f90a1b2c3d4e5f6a7b8c9d0", "2026-10-16T08:31:40Z 8b41d07a2c9e4f6b8d0a1c3e5f7a9b1d3f5a7c9e");
String current = log.get(log.size() - 1).split(" ")[1]; String previous = log.get(log.size() - 2).split(" ")[1]; System.out.println("Running now: " + current.substring(0, 7)); System.out.println("Roll back to: " + previous.substring(0, 7)); System.out.println("Command: ssh deploy@<vm> \"/opt/shoplite/deploy.sh " + previous + "\""); }}Running now: 8b41d07 Roll back to: 3f9c2e1 Command: ssh deploy@<vm> "/opt/shoplite/deploy.sh 3f9c2e1b7d4a5c6e8f90a1b2c3d4e5f6a7b8c9d0"
What this code does
- Each deploy appends a line with the time and the full SHA, so the second-to-last line is always the version that ran before the current one.
- The rollback uses the same
deploy.shas every deploy, which is why it is fast and safe: no new build, just an image that already passed tests and ran in production.
Example 3 · Rolling back on the VM, then reverting in Git
Runs in: a terminal on your laptop, with SSH access to the VM and the shoplite-api repository
ssh deploy@203.0.113.25 "tail -n 3 /opt/shoplite/deployed-tags.log"ssh deploy@203.0.113.25 "/opt/shoplite/deploy.sh 3f9c2e1b7d4a5c6e8f90a1b2c3d4e5f6a7b8c9d0"curl -s https://api.shoplite.example/actuator/health# Then make main match production againgit revert --no-edit 8b41d07git push origin main2026-10-14T10:02:11Z 91d2a7c4e0b13f5a6c8d9e0f1a2b3c4d5e6f7a8b
2026-10-15T16:40:09Z 3f9c2e1b7d4a5c6e8f90a1b2c3d4e5f6a7b8c9d0
2026-10-16T08:31:40Z 8b41d07a2c9e4f6b8d0a1c3e5f7a9b1d3f5a7c9e
[+] Pulling 1/1
✔ api Pulled 1.2s
[+] Running 2/2
✔ Container shoplite-api-1 Healthy 39.8s
✔ Container shoplite-caddy-1 Running 0.0s
Deployed 3f9c2e1b7d4a5c6e8f90a1b2c3d4e5f6a7b8c9d0
{"groups":["liveness","readiness"],"status":"UP"}
[main c52e8a1] Revert "Add gift notes to orders"
4 files changed, 3 insertions(+), 41 deletions(-)What this code does
- The pull takes about a second because the older image's layers are still on the VM. Health is UP again about 40 seconds later.
git revertadds a new commit that undoes8b41d07without rewriting history, and the push runs the normal pipeline. If production branch rules require pull requests, push the revert on a branch and merge it the usual way.
There are three common ways back:
- Redeploy the previous SHA: take the tag from
deployed-tags.logand rundeploy.shwith it; the image is still in GHCR. - The platform's rollback button: container platforms keep a list of earlier deploys.
git revert: a new commit that undoes the bad one, tested and deployed by the pipeline. It is slower, but run it after a quick redeploy so the next push does not bring the bug back.
Order of execution
Roll back ShopLite
Tap the steps in the order you would take them.
Database changes: Flyway only moves forward
Expand and contract changes a database in safe steps: first expand (add a nullable or defaulted column that old and new code both accept), and later contract (make it NOT NULL or drop the old one) when no running version needs the old shape.
Rolling back the code does not roll back the database, and Flyway's free edition only moves forward. The program below checks whether the old code can still insert orders after a migration.
Example 4 · Will the old code still work with the new schema?
import java.util.LinkedHashMap;import java.util.Map;import java.util.Set;
record Column(boolean nullable, String defaultValue) {}
public class RollbackSafetyDemo { static String insertCheck(Map<String, Column> table, Set<String> codeWrites) { for (Map.Entry<String, Column> c : table.entrySet()) { Column col = c.getValue(); if (!codeWrites.contains(c.getKey()) && !col.nullable() && col.defaultValue() == null) { return "ERROR 1364: Field '" + c.getKey() + "' doesn't have a default value"; } } return "INSERT works"; }
static Map<String, Column> orders(Column giftNote) { Map<String, Column> t = new LinkedHashMap<>(); t.put("customer_id", new Column(false, null)); t.put("address_id", new Column(false, null)); t.put("status", new Column(false, "PLACED")); t.put("gift_note", giftNote); return t; }
public static void main(String[] args) { Set<String> oldCode = Set.of("customer_id", "address_id", "status");
System.out.println("V6 NOT NULL, no default: " + insertCheck(orders(new Column(false, null)), oldCode)); System.out.println("V6 nullable (expand): " + insertCheck(orders(new Column(true, null)), oldCode)); System.out.println("V6 NOT NULL DEFAULT '': " + insertCheck(orders(new Column(false, "")), oldCode)); }}V6 NOT NULL, no default: ERROR 1364: Field 'gift_note' doesn't have a default value V6 nullable (expand): INSERT works V6 NOT NULL DEFAULT '': INSERT works
What this code does
- A simplified model of MySQL's strict-mode rule: a column the
INSERTleaves out must be nullable or have a default. The old code was written beforegift_noteexisted, so it never sends it. - Expanding with a nullable column (or a default) keeps the old version working, which is exactly what makes a rollback safe. Making it NOT NULL waits for a later release.
Example 5 · Expand and contract as Flyway migrations
Runs in: src/main/resources/db/migration in the shoplite-api project, applied by Flyway on start-up
-- Release A (expand): V6__add_gift_note.sql-- Old and new code both work: the column may be empty.ALTER TABLE orders ADD COLUMN gift_note VARCHAR(200) NULL;
-- Release B: the code now always writes gift_note (empty text when there is none).
-- Release C (contract), only after release B has run safely for a while:-- V7__gift_note_not_null.sqlUPDATE orders SET gift_note = '' WHERE gift_note IS NULL;ALTER TABLE orders MODIFY gift_note VARCHAR(200) NOT NULL DEFAULT '';INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "6 - add gift note" INFO o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `shoplite`, now at version v6 (execution time 00:00.188s) ... INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "7 - gift note not null" INFO o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `shoplite`, now at version v7 (execution time 00:00.412s)
What this code does
- Each release can be rolled back to the one before it: A's schema works for the old code, and C only runs when every running version writes the column.
- The same idea works for renames and removals: add the new column, write both, move readers, then drop the old one in a later release. Never rename or drop in the same release that stops using a column.
Flyway ignores a newer V6 it does not know, and Hibernate's validate ignores extra columns, so the old app starts. The danger is in the data rules: with gift_note NOT NULL and no default, the old INSERT fails with Field 'gift_note' doesn't have a default value, and the rollback breaks ordering again.
Predict the output
Can the old code still insert?
The old code does not know the new column. Pick what happens.
Round 1 of 3
The migration adds the column as NOT NULL without a default.
Graceful shutdown and rolling deploys
Graceful shutdown lets requests that are already running finish when the app is told to stop, instead of cutting them off. Spring Boot enables it with server.shutdown: graceful, and readiness turns to OUT_OF_SERVICE at once.
Docker gives a container only 10 seconds after SIGTERM before SIGKILL, but Spring may wait up to 30 seconds. The program below shows a request cut off when the grace period is too short.
Example 6 · Why the grace period must cover in-flight requests
public class GracefulShutdownDemo { static void stop(String how, int[] remainingSeconds, int allowedSeconds) { int finished = 0; int cut = 0; for (int r : remainingSeconds) { if (r <= allowedSeconds) { finished++; } else { cut++; } } System.out.printf("%-42s finished %d, cut off %d%n", how, finished, cut); }
public static void main(String[] args) { // seconds each in-flight request still needs when SIGTERM arrives int[] inFlight = {1, 2, 4, 8, 15, 25}; stop("Immediate stop (no graceful shutdown)", inFlight, 0); stop("Graceful, but Docker kills after 10 s", inFlight, 10); stop("Graceful 30 s + stop_grace_period 40s", inFlight, 30); }}Immediate stop (no graceful shutdown) finished 0, cut off 6 Graceful, but Docker kills after 10 s finished 4, cut off 2 Graceful 30 s + stop_grace_period 40s finished 6, cut off 0
What this code does
- Each number is how long a request still needs when the stop signal arrives. A request finishes only if it fits inside the time the process is allowed to keep running.
- Spring's 30-second graceful phase helps only if Docker waits at least that long; with Docker's default 10 seconds, the two slowest requests are still killed.
Spring waits up to spring.lifecycle.timeout-per-shutdown-phase (30 s by default). Set stop_grace_period: 40s in Compose (or --stop-timeout) so the JVM gets all of it. Write server.shutdown: graceful out even though it is the default since Boot 3.4, so readers see it.
A rolling deploy starts the new version, waits until its readiness is UP and only then stops the old one, so there is no gap. Platforms do this; ShopLite's single-VM Compose stops the old container first, so expect a short gap there.
Fix the error
Give requests time to finish
Pick the line that lets in-flight requests finish.
Round 1 of 2
Orders in flight are cut off when ShopLite stops.
Error
POST /api/v1/me/orders interrupted: Connection reset by peer
A short incident write-up
An incident write-up is a short, blameless page written after an incident: what happened with times, the impact, the fix that stopped it and the prevention steps. It turns one bad day into a lesson.
Write it within a day, while the logs still exist. This is the write-up for the gift note release.
Incident 2026-10-16: orders failed after release 8b41d07What happened 08:31 UTC deploy of 8b41d07 (gift notes). 08:32 POST /api/v1/me/orders started returning 500. 08:39 rolled back to 3f9c2e1; orders failed again (gift_note NOT NULL). 08:47 hotfix V7 made it nullable.Impact 16 minutes; 61 orders failed; no data lost.Fix Redeployed 3f9c2e1, then V7__make_gift_note_nullable.sql.Prevention Expand-and-contract for new columns; a smoke test that places an order; backup before risky migrations.Keep it blameless (about the system, not a person) and under a page, and link it in the repository. In an interview, one incident you handled well is worth more than any list of tools.
Next step
Check your understanding
12 quick questions