DEV Community

Alex Georgiev
Alex Georgiev

Posted on AI-assisted

What happens to MongoDB writes when the primary dies

Graceful stepdowns beat hard crashes

I expected killing a MongoDB primary to cause a short gap in writes while the replica set sorted itself out. What I didn't expect was that whether there was a gap at all would depend almost entirely on how the primary left, not on how long an election takes. A hard crash and a polite request to step down produced completely different outcomes for the exact same three-node set, and I only found that out because I tested both rather than stopping at the first result.

I ran this locally: three mongo:8.0 containers (v8.0.38) on a plain Docker bridge network, formed into a replica set with default settings, no cloud, no managed service. A Python 3.13 script using pymongo 4.20.2 wrote one document roughly every 100ms against the replica set, and I disrupted the primary in various ways while it ran. Everything below is from this machine, this morning.

Killing the primary outright

First test: let the write loop run for eight seconds, then docker kill the primary — a SIGKILL, the same as a crashed process or a host that vanished, with no chance for the primary to tell anyone it was leaving.

trial killed last write before gap first write after gap outage
1 mongo1 7.86s 17.89s 10.03s
2 mongo3 7.93s 18.64s 10.71s
3 mongo1 7.83s 18.44s 10.61s

Three trials, average outage 10.45 seconds, fastest 10.03 seconds. rs.config().settings on this set shows both electionTimeoutMillis and heartbeatTimeoutSecs at ten seconds, which is suspiciously close to what I measured — but with both defaults sitting at the same value, this run can't tell which one is actually setting the pace, only that something in that ten-second neighbourhood is.

Every failed write during that window raised the same thing, over and over, roughly every two seconds (my client's own serverSelectionTimeoutMS was set to 2000):

pymongo.errors.ServerSelectionTimeoutError: No primary available for writes,
Timeout: 2.0s, Topology Description: <TopologyDescription ...
topology_type: ReplicaSetNoPrimary, servers: [...
error=AutoReconnect('mongo1:27017: [Errno 111] Connection refused ...')>]>
Enter fullscreen mode Exit fullscreen mode

Four or five of these per trial, never anything else — a flat refusal to accept anything until a new primary existed. I didn't check the collection for partial or corrupted documents afterwards, so I can't say anything about that beyond what the error itself shows.

Asking it to leave instead of killing it

Then I tried the version any real maintenance window would actually use: rs.stepDown(60) on the primary, while the same write loop was running.

Two trials, 391 and 389 write attempts, zero errors in either one. Not fewer errors — none. The slowest single write across the second trial took 12.3 milliseconds, against a normal 2–3 milliseconds. I checked separately that the stepdown call actually did something rather than silently failing: every time I ran it and then queried rs.status(), a different node really had taken over as primary.

I didn't log the exact moment the rs.stepDown() call landed relative to the write stream, so I can't rule out some lucky gap by eye — but writes were going out roughly ten times a second for the full run in both trials, and zero failures across 780 combined attempts is a lot of luck to ask for by chance. The likelier explanation is structural: a primary that's stepping down can tell the rest of the set immediately, and the election starts at once, instead of everyone waiting out a silence first to even suspect something is wrong. The roughly ten-second number from the crash tests isn't really "how long MongoDB elections take" — it looks more like how long it takes to notice the primary is gone when nobody said anything.

retryWrites didn't save me, and the reason is worth knowing

I expected retryWrites=true — the pymongo default — to paper over at least part of the crash scenario. It didn't look like it did: trial 1 (retryWrites=true) and trial 2 (retryWrites=false) show the same error and roughly the same cadence and outage length. I'll be honest about how thin that comparison is — it's one trial per setting, and the spread between my two retryWrites=true trials (10.03s and 10.61s, same node killed both times) is already bigger than the 0.68s gap I'm using to say retryWrites made no difference. This isn't a settled result on its own.

What does make the point more solidly is a different test: I ran a single insert_one with no overrides — the driver's real defaults, including a 30-second serverSelectionTimeoutMS — straight after killing the primary. It returned successfully after 8.30 seconds, with no exception at any point. That's somewhat faster than the ~10 second outages measured elsewhere, which is more likely slack in exactly when I fired the write relative to the kill than a different underlying outage — but the headline fact stands regardless of the exact number: a write with a generous timeout just waited it out and succeeded, invisibly. The only thing that changed between this and the failing trials was how long my own code was willing to wait before giving up. "Retryable writes make failover transparent" is true only if your timeouts are generous enough to sit through the wait; mine, set the way a latency-sensitive service actually would be, were not.

It gets worse per client, not for the whole system

I ran five of these writers at once against a single kill. Every one of them hit exactly 5 errors independently — 25 failed calls total across five clients from one ten-second outage, not some shared budget of failures the replica set absorbs on everyone's behalf. Each connection pool discovers the gone primary and times out on its own schedule. A service with more concurrent writers doesn't get a shorter outage; it just generates more failed requests during the same one.

Reads kept working the entire time

While the writers above were failing, I ran a separate reader against the secondaries with read_preference=SECONDARY through a hard kill: 100 reads attempted, zero failures. The outage number above is specifically a write-availability number. If a feature can tolerate reading slightly stale data from a secondary during that window, it doesn't need to care about this at all.

Watching it happen

rs.status() is the plain way to see this live — no special tooling, works the moment you suspect something. A few seconds into a kill, querying it from a surviving secondary gave me:

mongo1:27017 (not reachable/healthy) health=0
mongo2:27017 SECONDARY               health=1
mongo3:27017 SECONDARY               health=1
Enter fullscreen mode Exit fullscreen mode

No primary yet, and the dead member's health already at 0. Checking again once the election had settled showed one of the two survivors had become PRIMARY, while the killed node stayed at health=0 until I brought it back. That's enough to build an alert on without reading a single log line.

What I got wrong on the way

My first attempt to connect a host-side Python script to the containers failed outright, with pymongo unable to resolve mongo1 at all. I'd tried to pull each container's IP with docker inspect -f '{{.NetworkSettings.Networks.mongo-net.IPAddress}}', and the hyphen in mongo-net broke Go's template parser rather than the lookup itself — it failed silently enough that I wrote three empty strings into /etc/hosts and didn't notice until pymongo's own error told me plainly that the names didn't resolve. The fix was {{(index .NetworkSettings.Networks "mongo-net").IPAddress}}. A smaller, less interesting bug than anything above, but it's the kind of thing that wastes twenty minutes if you don't read the actual error message.

Run it yourself

docker network create mongo-net
for i in 1 2 3; do
  docker run -d --name mongo$i --network mongo-net --hostname mongo$i \
    -v mongo$i-data:/data/db mongo:8.0 --replSet rs0 --bind_ip_all
done
docker exec mongo1 mongosh --quiet --eval '
  rs.initiate({_id:"rs0", members:[
    {_id:0,host:"mongo1:27017"},{_id:1,host:"mongo2:27017"},{_id:2,host:"mongo3:27017"}]})'
# after it settles, find the primary, then either:
docker kill mongo1                                   # hard crash
docker exec mongo1 mongosh --quiet --eval 'rs.stepDown(60)'   # graceful
Enter fullscreen mode Exit fullscreen mode

The writer I used was a plain pymongo loop (insert_one every 100ms, printing elapsed time and any exception); nothing fancier than that produced the numbers above.

My own take

On this three-node set, with these defaults, planned maintenance going through rs.stepDown() rather than just stopping the process looked like a clear win every time I tried it: the gap between those two wasn't a few milliseconds, it was all of it, ten seconds of failed writes versus none. I'd want to see it hold up on a bigger set or under real load before calling it a rule rather than a strong result from five trials. For the crash case I can't avoid, the more useful lever isn't retryWrites, it's deciding on purpose how long my application is willing to block on a write before it gives up and tells the user something is wrong — the replica set took about ten seconds to recover in every crash trial here, and the only question left is whether my own code waits that out quietly or surfaces it immediately. I'd rather it waited, for anything that isn't on a latency budget tighter than that.

Top comments (4)

Collapse
 
kashif_manzer profile image
Kashif Manzer •

Useful distinction between waiting for a server and retrying a write. Server selection is the driver looking for a suitable primary, while a retryable write only helps once an operation has started and hits a retryable error, so a short selection timeout can fail before any retry has a chance. One more check worth adding is rollback. A write acknowledged by the old primary but not yet replicated to a majority can disappear after the election, so the collection check after the kill matters as much as the error count during it.

Collapse
 
smtahosin profile image
S M Tahosin •

Alex, that 8.30s insert still landing surprised me lol. I set that timeout to 3s once and a normal restart started failing. One setting for everything on your side? thanks :D

Collapse
 
alexgeorgiev17 profile image
Alex Georgiev •

Ha, it surprised me too. And 3s failing makes sense to me. The crash outage was about 10 seconds every time here, so anything shorter than that just runs out before a new primary exists.

Not one setting, no. Even in the post it was two. The write loop had serverSelectionTimeoutMS at 2s on purpose so I could see the failures, and the 8.30s insert was the driver default of 30s, which is why it just quietly waited it out.

If I were picking, I'd split it by who's waiting. Background jobs and anything with no user staring at it get a timeout comfortably above that ~10s window, so they ride through a failover. User-facing writes get a short one and a proper error, because a request hanging for 10 seconds isn't really better than failing. And for planned restarts, rs.stepDown() first was the thing that made the gap go away completely in my tests, whatever the timeout was.

Collapse
 
smtahosin profile image
S M Tahosin •

Alex, 'who's waiting' is a clean way to split it. mine failed on a planned restart, friday evening of all times lol. i never ran stepDown, just restarted the node and watched writes error. doing it your way next deploy. thanks :D