Capstone: A Safe Deployment with Releases, a Health Check and an Instant Rollback
Bring the course together in one deployment routine: build numbered releases, switch the live site with an atomic symlink, check health after the switch, roll back automatically when a release is broken, keep only the last few releases, and prove with continuous requests that visitors never saw an error.
In this lesson you will
- Deploy into numbered release folders
- Switch the live version atomically
- Check health and roll back automatically
- Prove that visitors saw no errors
About 28 minutes
Deploying on a Friday afternoon without fear
Femi’s old deployment was to copy new files over the live folder. For a few seconds the site was a mixture of old and new files, and one Friday a half-copied style sheet and a missing script broke the checkout for ten minutes. A professional routine avoids the mixture. Each version of the site is built in its own numbered folder, a release, next to the others. A symbolic link named current points at the live release, and the web server serves whatever current points to. Switching versions means changing where the link points, and that can be done atomically: create a new link with a temporary name and rename it over the old one, which the operating system does in one indivisible step, so any request sees either the old release or the new one, never a mixture.
Around the switch, three safety steps. Before the switch, a pre-check tests the new release in isolation. After the switch, a health check requests the real site and verifies that it returns the expected content, a marker such as “build ok”, and not merely a 200 status. If the check fails, the routine rolls back automatically by pointing current at the previous release, again atomically, which takes milliseconds because the old release is still on disk. Finally, it keeps the last few releases for quick rollbacks and deletes older ones to save space. The whole routine is small enough to read in one sitting, and it brings together the course: a server on a port, files and permissions, content types and caching, a health check as monitoring, and a restore path.
| Step | What happens | Why |
|---|---|---|
| Build | Create releases/v3 with all files | No mixture of versions |
| Pre-check | Look for the required files and marker | Reject broken builds early |
| Switch | ln -s to a temp name, then rename over current | Atomic |
| Health check | Request the live site and check its content | Prove it works for visitors |
| Rollback | Point current at the previous release | Recovery in milliseconds |
| Prune | Keep the last three releases | Space and clarity |
import os, tempfile, shutil, threading, time, json, hashlib, http.server, urllib.request, urllib.error, functools
base = tempfile.mkdtemp(); os.makedirs(base + "/releases")
live = base + "/current"
class Site(http.server.SimpleHTTPRequestHandler):
def log_message(self, *a): pass
def translate_path(self, path): return super().translate_path(path)
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Site, directory=live)); port = srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % port
def build(version, ok=True, title=None):
d = base + "/releases/" + version; os.makedirs(d)
open(d + "/index.html", "w").write("<h1>%s</h1>" % (title or version) + ("<!-- build ok -->" if ok else ""))
open(d + "/style.css", "w").write("h1 { color: #3b2a1e; } /* %s */" % version)
def switch(version):
tmp = base + "/.current.tmp"
if os.path.lexists(tmp): os.remove(tmp)
os.symlink("releases/" + version, tmp); os.replace(tmp, live) # atomic: rename over the old link
def health():
try: return "build ok" in urllib.request.urlopen(url, timeout=2).read().decode()
except Exception: return False
log, errors, probes = [], [0], [0]
def probe(stop):
while not stop.is_set():
probes[0] += 1
try:
body = urllib.request.urlopen(url + "style.css", timeout=2).read()
if b"h1" not in body: errors[0] += 1
except Exception: errors[0] += 1
def deploy(version, ok=True):
prev = os.path.basename(os.readlink(live)) if os.path.islink(live) else None
build(version, ok)
switch(version)
if health(): log.append((version, "live")); result = "ok"
else:
log.append((version, "health check FAILED"));
if prev: switch(prev); log.append((prev, "rolled back"));
result = "rolled back"
kept = sorted(os.listdir(base + "/releases"))
for old in kept[:-3]: shutil.rmtree(base + "/releases/" + old); log.append((old, "pruned"))
return result
stop = threading.Event(); t = threading.Thread(target=probe, args=(stop,)); t.start()
r1 = deploy("v1"); r2 = deploy("v2"); r3 = deploy("v3", ok=False); r4 = deploy("v4"); r5 = deploy("v5")
time.sleep(0.2); stop.set(); t.join()
now = os.path.basename(os.readlink(live))
print("results:", r1, r2, r3, r4, r5)
print("log:", log)
print("current points at:", now, "| releases kept:", sorted(os.listdir(base + "/releases")))
body = urllib.request.urlopen(url).read().decode()
print("live page:", body, "| matches the release file on disk:", hashlib.sha256(body.encode()).hexdigest() == hashlib.sha256(open(base + "/releases/" + now + "/index.html", "rb").read()).hexdigest())
print("probe requests during all deployments:", probes[0], "| failed or broken responses:", errors[0])
print("DATA " + json.dumps({"results": [r1, r2, r3, r4, r5], "log": log, "now": now, "kept": sorted(os.listdir(base + "/releases")), "probes": probes[0], "errors": errors[0], "body": body}))
results: ok ok rolled back ok ok
log: [('v1', 'live'), ('v2', 'live'), ('v3', 'health check FAILED'), ('v2', 'rolled back'), ('v4', 'live'), ('v1', 'pruned'), ('v5', 'live'), ('v2', 'pruned')]
current points at: v5 | releases kept: ['v3', 'v4', 'v5']
live page: <h1>v5</h1><!-- build ok --> | matches the release file on disk: True
probe requests during all deployments: 316 | failed or broken responses: 0
The routine deployed five versions in a row while a background probe requested the style sheet of the live site in a tight loop, 316 times in all. Versions 1, 2, 4 and 5 passed the health check and went live. Version 3 was built without the “build ok” marker, which stands for a broken release, and the health check after the switch failed: the log shows “v3: health check FAILED” and then “v2: rolled back”, so the live site returned to version 2 within milliseconds, and the broken release was never the final state. Version 4 was then deployed over the rolled-back site and passed. The pruning step kept the three newest release folders, v3, v4, v5, and removed older ones, version 1 and version 2, after they were no longer needed for rollback.
The probe is the proof that matters to visitors: 316 requests during five switches and one rollback, and 0 errors, no failed requests and no responses that lacked the expected content. That follows from the atomic rename. The operating system replaces the link in one step, so there is no instant at which current points nowhere or at a half-built folder, which the old copy-over method could not promise. At the end, current points at v5, and the live page is “<h1>v5</h1><!– build ok –>”, the same bytes as the release file on disk, which the program compares by checksum.
Independent check: three things were verified from outside the deployment code. The probe recorded the visitor’s experience throughout. The final page was compared with the file of the release that the link names, by checksum, so the site serves exactly what is on disk. And a request to a port where nothing listens returned “000” in curl, the status for “could not connect”, which is the kind of failure that the probe would have counted, so the zero is meaningful. The order of the log entries matches the expected story: live, live, failed, rolled back, live, live, with the prunes after the later deployments.
Check by hand: five deployments, one of which fails and rolls back, give four successful go-lives and one rollback, so the log has v1, v2, v3 failed, v2 rolled back, v4 and v5, in that order. After v5 the folders v1 to v5 exist, and keeping three leaves v3, v4 and v5, so v1 and v2 are pruned.
Where to go next
- Rebuild the routine on a small cloud server with a real web server, a proxy and a certificate, using what lessons 4 to 6 showed.
- Add a database migration step, and decide how to roll back data changes as well as code.
- Add an external monitor and the log alert rules of lesson 9, and run the restore test of lesson 10 on a schedule.
- Put the deployment in a script in version control, so that every deployment is the same and reviewable.
- Read the documentation of your host or platform for its own release, rollback and monitoring features, and compare with this routine.
A check that only looks for a 200 status passes on a blank page. Check for content or an endpoint that exercises the important parts, such as the database.
Rollbacks are fast because the old release is still there. Keep at least three, and make sure that data changes can also be undone or are compatible with the previous release.
Providers, plans and prices change often, so the lessons use invented prices and generic names, and you must check each provider’s current website. The server behaviour in this lesson was run for real on a Linux machine with Python 3.13, Node.js 22, OpenSSL and standard Unix tools, and every result was checked a second way. You have now completed the Hosting and servers course.
Practice
Add a pre-check that refuses a release without index.html before the switch. Make the health check request three different paths. Deploy a release while 20 probe threads run and check that errors stay at zero.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Why switch a symlink instead of copying files over the live folder?
- The switch is atomic, so visitors never see a mixture
- It is shorter to type
- Files are smaller
- It encrypts files
One rename.
What does the health check do after the switch?
- Restarts the server
- Deletes old releases
- Compresses files
- Requests the live site and checks its content
Proof for visitors.
What happens when the health check fails?
- The server stops
- The release is published anyway
- Nothing
- The routine points current back at the previous release
An automatic rollback.
Why keep several old releases?
- Disks are free
- They are required by law
- Rollbacks are instant
- They make the site faster
And prune the rest.
What proved that visitors saw no errors?
- A promise
- The log of the deployment alone
- A continuous probe with zero failures
- A screenshot
Independent measurement.
Summary
- Build releases in numbered folders and switch a symlink atomically.
- Check health after the switch and roll back automatically.
- Keep a few releases and prune the rest.
- Prove the result with a continuous probe and independent checks.
Questions
Is this how real platforms deploy?
Many use the same ideas, releases, atomic switching, health checks and rollback, with more machinery for scale. Understanding the small version helps you use the large ones.
What about databases?
Schema changes make rollbacks harder. Make changes in compatible steps, so that the old and new code both work with the database during the switch, and keep backups.
Can I automate this?
Yes. Put the steps in a script, run it from a build server on every change, and let it deploy only after tests pass.
