# The cutover was a connection string

> Moving a self-managed MongoDB replica set onto Atlas without a maintenance window. The private network went in first and Terraform owned it; mongomirror did the rest from the one box that could see both sides.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2023-10-19
- Tags: MongoDB, MongoDB Atlas, AWS, Terraform, PrivateLink, EC2, Migration
- URL: https://deyanpeev.com/posts/the-cutover-was-a-connection-string

We were running MongoDB ourselves, a replica set on EC2 instances, built by
people who had moved on and patched by people who hadn't volunteered. It
worked. The argument for moving it onto Atlas was that the on-call rotation
included a database that no one currently on the team had chosen, and every
upgrade was a small project.

The constraint was that we couldn't stop. The platform is used across time
zones, and there is no hour of the week where a maintenance window is free. So
the migration had to happen underneath a running application, and the
application had to keep writing throughout.

Two things made that possible. `mongomirror` does this job and does it well,
and all of the risk had moved into the network long before any data did. Most
of this post is about the second.

# The network came first

The default way to let something reach an Atlas cluster is the IP access list.
You tell Atlas which public addresses may connect, and traffic goes over the
internet with TLS on top. It isn't insecure and I'm not going to pretend it
is. It was still wrong for us, because the list is a list. It needs an entry
per NAT address, it drifts when the network changes, and "can this thing reach
the database" becomes a question about a text field in a web console when it
should be a question about the VPC.

VPC peering is the obvious next step and we skipped it too. Peering joins two
networks, and we didn't want to join anything, we wanted one directional door.
It also means caring about CIDR overlap forever, and it exposes rather more of
Atlas's network to ours than the job required.

AWS PrivateLink gives you the door. Atlas publishes an endpoint service, you
create an interface endpoint in your own VPC, and the cluster becomes reachable
at a private address inside your subnets. Nothing traverses the internet, there
is no route between the two VPCs, and the security question collapses into a
security group, and Terraform already owns those.

In Terraform it's a three-step chain, and the order is forced by which side
knows what:

```hcl
resource "mongodbatlas_privatelink_endpoint" "atlas" {
  project_id    = var.atlas_project_id
  provider_name = "AWS"
  region        = "EU_CENTRAL_1"
}

resource "aws_vpc_endpoint" "atlas" {
  vpc_id             = module.vpc.vpc_id
  service_name       = mongodbatlas_privatelink_endpoint.atlas.endpoint_service_name
  vpc_endpoint_type  = "Interface"
  subnet_ids         = module.vpc.private_subnets
  security_group_ids = [aws_security_group.atlas_endpoint.id]
}

resource "mongodbatlas_privatelink_endpoint_service" "atlas" {
  project_id          = mongodbatlas_privatelink_endpoint.atlas.project_id
  private_link_id     = mongodbatlas_privatelink_endpoint.atlas.private_link_id
  endpoint_service_id = aws_vpc_endpoint.atlas.id
  provider_name       = "AWS"
}
```

Atlas has to create the endpoint service before AWS can be told what to connect
to, and AWS has to create the interface endpoint before Atlas can be told to
accept it. Terraform resolves that through the references without any help,
and for me that's the main reason to do it in Terraform and not by hand in two
browser tabs.

Two details cost me time, and neither is guessable.

The port range is not 27017. Behind a private endpoint, Atlas puts a load
balancer in front of the replica set and gives every node in the region its own
port on it (1024, 1025, 1026 and upward), because all the nodes now answer on
one hostname. So the security group can't be a tidy `27017` rule. Clients need
egress to the endpoint across 1024-65535, and the endpoint's own group needs
matching ingress. The first time you write the sensible-looking rule, DNS
resolves, the TCP connection to the first node succeeds, and then the driver
fails to complete topology discovery because it cannot reach the other two. It
looks like an Atlas problem. It's a security group problem.

The connection string is a different string. A cluster behind a private endpoint
has its own `mongodb+srv://` URI, and it's not the one on the cluster's
overview page. In Terraform it comes off the cluster resource under
`connection_strings.private_endpoint`, and it doesn't exist until the endpoint
service is established. So the cluster resource needs an explicit
`depends_on` pointing at `mongodbatlas_privatelink_endpoint_service`, or the
first apply will hand you an empty list and the second will fix it silently.
Implicit dependency is not enough here because nothing in the cluster's
arguments refers to the endpoint.

By the time any data moved, the network had been applied, destroyed and
re-applied several times against a throwaway project, so on migration day "can
we reach Atlas" was already answered.

# Where mongomirror has to run

`mongomirror` connects to both databases at once. It does an initial sync of
every collection, then tails the source oplog and applies the changes to the
destination until you tell it to stop. So it needs to run somewhere that can
see the source replica set *and* the Atlas cluster.

After PrivateLink there is one kind of place like that, an instance inside
the VPC, in a subnet the interface endpoint lives in, with a security group
allowed through it. That rules out a laptop, a bastion outside the private
subnets, or a CI runner on hosted infrastructure. The network decision in the
previous section had decided this one too.

So it ran on a plain EC2 instance in the same VPC and the same private subnets
as the endpoint. Three things about that box mattered.

Network mattered more than CPU. The initial sync is bounded by how fast you can
pull documents out of one side and push them into the other. We gave it a
network-optimised instance and never saw the CPU become the constraint.

Disk mattered because of the oplog. `mongomirror` needs the source's oplog
window to still cover the whole of the initial sync when the sync finishes. If
the sync takes longer than the oplog holds, the tail has nothing to resume from
and you start again. `--oplogPath` buffers oplog entries to local disk while the
sync runs, so "is our oplog big enough" turns into "is this volume big enough",
and that one is much easier to answer. The sizing rule is unglamorous. If the
source oplog holds a day and the sync takes two, you want roughly two days'
worth of oplog in free space.

And it has to survive your SSH session, because this runs for hours. Ours ran
under `systemd` with its output to the journal. The first thing that goes wrong
with a long-running foreground process is a laptop lid.

Permissions are two users, and they aren't symmetric. On the source, the user
needs the built-in `backup` role, which is read any database plus read `local`,
where the oplog is. On the Atlas side it needs `Atlas admin`, because it's
recreating collections and indexes and not just writing documents.

# The command

```bash
mongomirror \
  --host "rs0/mongo-a.internal:27017,mongo-b.internal:27017,mongo-c.internal:27017" \
  --username migrator \
  --password "$SOURCE_PASSWORD" \
  --authenticationDatabase admin \
  --ssl \
  --sslCAFile /etc/ssl/internal-ca.pem \
  --destination "atlas-prod-shard-0/pl-0-eu-central-1.abcde.mongodb.net:1024,..." \
  --destinationUsername migrator \
  --destinationPassword "$ATLAS_PASSWORD" \
  --numParallelCollections 8 \
  --oplogPath /mnt/oplog \
  --bookmarkFile /mnt/state/mongomirror.bookmark \
  --httpStatusPort 8000
```

`--host` wants the replica set name and its members, not a URI. `--destination`
wants the same format for Atlas, and here the private endpoint shows up
concretely. Those are per-node ports on one load-balanced hostname, the
port-range business from earlier.

The flags I would argue about:

`--numParallelCollections` defaults to 4. Raising it helps when you have many
collections of similar size and does nothing when one collection is most of your
data, which is more common and was our case. Eight was a guess. It made the
small collections finish sooner and left the big one as slow as it was going
to be anyway.

`--bookmarkFile` is what makes the run resumable. It records how far the oplog
tail has got. Put it somewhere that outlives the process - the point of it is to
be there after a crash, and the default lands next to wherever you happened to
be standing.

`--drop` we didn't use. It drops user collections on the destination before
copying, which is right for a target you're sure about and a loaded gun on a
target you are not. Ours was a fresh cluster with nothing to drop, so the flag
would only have been there to save us from a mistake we would rather not have
made in the first place.

`--noIndexRestore` we also did not use, but I'd use it on a much larger
dataset. Index builds on the destination are a real part of the wall-clock
time, and skipping them and building afterwards lets you control when that cost
lands. It also means the destination isn't ready when `mongomirror` says the
sync is done, and that's a footgun if anyone else is watching the same status
endpoint and drawing conclusions.

# Watching it on a port

`--httpStatusPort` is the flag that turned this from an anxious afternoon into a
boring one. It exposes a small HTTP endpoint on the instance that reports what
phase the process is in and how far behind the oplog tail is.

That's enough to build the two things people wanted:

```bash
curl -s localhost:8000/status | jq '{phase, lag: .details.lagTimeSeconds}'
```

A one-line poll into Slack every few minutes during the initial sync, so that
people didn't have to ask. And an alert on the lag going up instead of down
once the tail started, because a lag that grows means the source is writing
faster than the mirror can apply, and that's the one failure where waiting
longer does not help.

The cutover plan is also built around the lag number, so get a feel for it
well before you need it. Ours settled at a couple of seconds and stayed there,
and from that we knew the cutover would be short.

# The cutover

The sequence was written down, rehearsed against a copy, and executed in about
four minutes.

1. Confirm the mirror is in oplog-tail phase and the lag has been in the low
   seconds for hours, not minutes.
2. Stop writes. For us that meant putting the API into a mode where write
   endpoints return a retryable error and the background workers stop consuming.
   Reads carried on being served from the old replica set the entire time.
3. Watch the lag go to zero. The design exists for this step. With writes
   stopped, the tail has a finite amount of work left, and you can see it
   finish instead of assuming it has.
4. Stop `mongomirror`.
5. Roll the application onto the new connection string and let the deployment
   replace the instances.
6. Turn writes back on.

Step 5 is the title of this post, and it's meant to be an anticlimax. The
connection string lived in one place, a parameter the deployment reads (not a
value baked into an image or repeated across services), so the last act of the
migration was changing one string and letting the normal deployment mechanism
do the normal thing. If that value had been in eleven places this would have
been a different and much worse story. The work to consolidate it happened
weeks earlier, for this reason.

The old replica set stayed running for a week, untouched and still receiving
nothing. Rolling back would have meant reversing steps 5 and 6 and accepting the
loss of whatever had been written to Atlas in the meantime. So the rollback was
real for about the first ten minutes and theatre after that. I still think the
ten real minutes were worth the week of instance cost.

# The write pause inside "no downtime"

The application never stopped serving. There was no maintenance page and no
scheduled window, and we didn't tell anyone to avoid the product that evening.
That's what we meant when we said no downtime, and I think it is the meaning
that matters.

There was still a window of under a minute where writes were refused with a
retryable status and the clients retried into it. A user who submitted a form at
the wrong moment saw a spinner for a few seconds. A background job that would
have run then ran slightly later. If your definition of zero downtime doesn't
permit a brief write pause, then this was not zero downtime, and I'd rather say
so here than hide it behind a good headline number.

The alternative is a fully pauseless cutover, with dual writes or a proxy in
front of both databases. It's possible and it is a substantially larger
project. For a sub-minute write pause absorbed by retries that already existed,
it wasn't close to being justified.

# What I would tell myself in September

Do the network as its own piece of work, with its own apply and its own destroy.
Everything I got wrong about PrivateLink, I got wrong in a scratch project
against a cluster with no data in it, and there is no cheaper place to discover
the port range.

Consolidate the connection string before you need to change it. The migration
was easy because there was one place to edit, and getting it to one place was
work done weeks in advance.

Rehearse against a restored copy, timed. We ran the full sequence against a
cluster restored from a backup, including the write-pause, and it's the only
reason anyone was willing to say "about four minutes" out loud. The rehearsal
also caught that our write-pause mode didn't stop one background consumer. That
would have been an unpleasant thing to learn live.

Watch the lag, not the clock. Every version of this plan that goes wrong goes
wrong because someone decided enough time had probably passed. With the status
port you don't have to decide that.

The database is now somebody else's operational problem (that was the reason
for the move), and the network in front of it is a hundred lines of Terraform
that the next person can read.

---

*`mongomirror` has since been retired. MongoDB's current paths for this are the
Atlas Live Migration service and `mongosync`. The mechanics of the cutover (a
sync, a tail, a lag you watch to zero) are the same, and so are the PrivateLink
and connection-string parts, and those are most of this post.*
