
A random boot failure, a lock nobody asked for, and why a broken server should just shut itself down
Imagine starting a new job, and on your first day nobody gives you your laptop password, your access card or even the address of the office. You're hired, you're on the team list, but you can't do a single thing.
Every now and then, one of our new servers had exactly that first day.
How our servers start
We have an auto scaling group that adds servers when we need them. Each new server starts from our own machine image, and then a user data script runs on first boot to finish the setup.
The most important step in that script is getting the app settings. Things like database passwords and API keys don't belong inside a machine image (anyone who can launch the image can read them), so we keep them in AWS Systems Manager Parameter Store. On boot, the script installs the AWS CLI, pulls the settings from Parameter Store, writes them to a .env file, and the app starts with them.
Simple, and it worked. Most of the time.
Most of the time
Every now and then, a new server would come up without its .env file. The server was running and EC2 said it was fine, but the app had no settings, so it failed the load balancer health checks. The unhealthy host alarm went off and someone on call had to jump in.
The funny part is that this server was supposed to be the backup, and now it was the one that needed help.
The fix on call was manual. Log into the broken server, run the ssm get-parameter commands by hand, add the output to .env, restart the app, and wait for the alarm to go back to OK. We even wrote it into our on-call guide as a temporary step until we fixed it. You know how temporary those can be :)
Auto Scaling would have replaced the server eventually, once the health checks failed for long enough. But the alarm doesn't wait for that, and the next server could have the same bad luck.
And that was the annoying part, it wasn't every time. Most servers booted fine. Then one would come up empty, with the same image, the same script, nothing changed. You can't fix what you can't see, and I couldn't make it happen on purpose.
Catching it in the act
Servers in an auto scaling group come and go, and when one is gone, its logs are gone with it. So I made the boot script keep everything it printed in a log file on the server, and pushed those logs to S3 so I could read them later and see what was really going on.
If you want the same thing, this one line at the top of a user data script sends all of its output to a file, as well as the normal boot log:
exec > >(tee -a /var/log/user-data.log) 2>&1
Once I had the logs, the answer was right there. It looked something like this:
E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 1234 (unattended-upgr)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
aws: command not found
Failed to fetch /my-app/env, retrying...
The AWS CLI never got installed, because something else was holding the package manager's lock. No CLI means no settings. And the script didn't stop there, the rest of the setup carried on like nothing happened.
Who was holding the lock?
Ubuntu itself.
Ubuntu has background jobs that refresh the package lists and install security updates on their own (apt-daily and unattended-upgrades). They run on timers with a random delay, and on a fresh server they often kick in soon after boot. That's exactly when your user data script is trying to install things.
Only one process can use apt at a time. If Ubuntu's update job gets the lock first, your apt-get install fails straight away. It doesn't wait, it just gives up. And because of that random delay, sometimes the update job starts before your script and sometimes after. That's why it was random.
This is a known issue, there are Ubuntu bug reports about it going back years. It's one of those defaults that makes total sense on a laptop, and gets in your way on a server that has to be ready in a few minutes. Never trust defaults, again :)
The fix
The fix has three parts. Here's a simplified version of the idea:
#!/bin/bash
exec > >(tee -a /var/log/user-data.log) 2>&1
wait_for_apt() {
while fuser /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock /var/lib/apt/lists/lock >/dev/null 2>&1; do
echo "apt is busy, waiting..."
sleep 5
done
}
fetch_param() {
local name=$1
for attempt in 1 2 3 4 5 6; do
value=$(aws ssm get-parameter --name "$name" --with-decryption \
--query "Parameter.Value" --output text)
if [ $? -eq 0 ] && [ -n "$value" ]; then
echo "$value" >> /app/.env
return 0
fi
echo "Failed to fetch $name, retrying..."
sleep $((2 ** attempt))
done
echo "Could not get $name, shutting down so Auto Scaling replaces this server"
shutdown -h now
exit 1
}
wait_for_apt
apt-get update -y
apt-get install -y awscli
fetch_param "/my-app/env"
Wait for the lock. Before touching apt, the script checks if any process is using the lock files (that's what fuser tells you), and waits until they're free.
Retry the settings fetch. Getting the parameters can fail for other reasons too, like a short network hiccup, or Parameter Store throttling you when a few servers start at once. So it retries with a growing wait between attempts, 2 seconds, then 4, then 8 and so on.
If it still fails, shut down. This is my favourite part, and it wasn't there at first. The first version just called exit when it ran out of retries. Sounds fine, until you notice that exit stops the script, not the server. You end up with the worst kind of server, alive but useless, sitting behind the load balancer failing health checks and setting off alarms.
shutdown -h now turns that confusing problem into a simple one. By default, shutting down from inside an EC2 instance stops it, and Auto Scaling treats an instance that isn't running as unhealthy right away. It doesn't wait for the health check grace period, it just replaces it with a fresh server (docs). The fresh server gets another roll of the dice, and since the lock problem is random, it almost always wins.
The exit 1 after shutdown is worth adding too. Shutdown takes a few seconds, and you don't want the rest of the setup running in the meantime.
The idea behind all of this is that a server that can't start properly should fail fast and loud, not sit there half alive. A dead server gets replaced in minutes. A half alive one waits for a human.
What I'd do differently today
This fix has been running in production and it works. But when I went back to this code to write this article, I found something funny.
Our machine image already has the AWS CLI. It's installed with pip for the app user, but the user data script runs as root, and root can't see it. So on boot, the script installed a second copy with apt, right at the moment Ubuntu was most likely to be holding the lock. We were fighting over a lock to install something that was already on the server.
So if I built this again today:
Don't install anything at boot. Bake the AWS CLI into the image, installed system-wide so every user can find it. If nothing runs apt at boot, there's no lock to fight over. The official installer is three lines:
curl -sSL "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o awscliv2.zip unzip -q awscliv2.zip sudo ./aws/installSame goes for anything else the script installs on boot, like monitoring agents, they all need the same lock. Also newer Ubuntu versions don't even have an
awscliapt package anymore, so that apt line would break on an upgrade anyway.Your image build can hit the same lock too (it starts from a fresh Ubuntu server as well), so wait for the lock there as well. The difference is that a failed build is just a retry, a failed boot is an alarm. That's the real fix, move the risk from boot time to build time.
If you must use apt at boot, let apt do the waiting. My check-then-install loop has a tiny gap, Ubuntu can grab the lock between my check and my
apt-get. Newer apt versions can wait for the lock by themselves:apt-get -o DPkg::Lock::Timeout=300 install -y some-packageNo gap, and less code.
Watch for a replacement loop. Shutting down is great when the problem is random. When it's not random, like a typo in the parameter name or a missing permission on the server's role, every new server will fail the same way, shut down and get replaced, again and again. Add an alert for when the group keeps launching and terminating servers.
Add a bit of jitter. When several servers start together, they all retry on the same schedule and hit Parameter Store at the same moments. A small random delay spreads them out:
sleep $(( 2 ** attempt + RANDOM % 3 ))
What I took from this
- Random failures still have a cause. Most of the time it's timing, two things racing each other.
- Keep logs somewhere that outlives the server. In an auto scaling group, the server you need to debug might already be gone.
- A broken server should die fast. Alive but useless is the worst state. Let Auto Scaling replace it.
- Do the risky work at build time, not boot time. A failed build costs you a retry. A failed boot costs you an alarm.
- Check what your image already has. We were racing for a lock to install a tool that was already there.
In the end, the server didn't need a smarter boot script. It just needed less work to do on its first day.
That's all for now. If you're interested in more advanced content about WSGI, Apache, or other DevOps topics, there are many articles in the DevOps series that you might find interesting.
Mostafa-DE Fayyad
Software Engineer
Comments
Join the discussionThe fail-fast instinct is the real lesson here — an instance that can't load its settings should never sit there looking healthy. One addition I'd make: emit a metric or log line right before the shutdown, so you can tell a single bad boot apart from a fleet-wide churn loop.
The fail-fast idea is what I'd take away from this — a server that can't load its settings shouldn't sit there alive but useless, it should exit and let auto scaling replace it. Baking the CLI into the image, plus turning off unattended-upgrades on first boot, would have removed the race at the source instead of just retrying around it.
The apt lock problem is underrated: on Debian/Ubuntu images, unattended-upgrades can hold the lock right at first boot, which is exactly when cloud-init wants it. The part I like here is that you traced it to timing rather than just retrying — retries hide the root cause until it bites at 3am.
Your native apt timeout addresses the lock race. I would also test the overall bootstrap deadline: keep the lock busy, then separately make the parameter request never complete. The retry count bounds attempts only after a command returns. In both fixtures, assert a visible bootstrap failure and that the host is never admitted to traffic. That keeps the fail-fast rule independent of which dependency is hanging.



