Skip to content
Source
Sign inSign up

Fail over when the primary stops

Site administration

Fail over when the primary stops

The primary git server stopped, and the team got the Sentry alert git-failover. The forge failed over by itself: a replica is the primary now, and pushes work again. Make sure that git works, then bring the old server back as a replica.

16 min read

The web Worker checks the primary each minute. When the primary does not answer 3 checks in a row, 10 seconds apart, the Worker fails over:

  1. It picks the replica that has the newest version of the most repositories. A replica that lost the heartbeats of the primary more than a minute before the checks comes last. In a tie, it picks us, then eu, then asia.
  2. It makes that replica the primary of a new term. The other servers follow it.
  3. It moves git_primary of every repository in the database to the new primary.
  4. It sends the alert git-failover to the team.
  5. In the next minutes, it moves the copy of the refs of each repository (in Postgres) to the refs of the new primary.

The Worker does not fail over when a replica still gets the heartbeats of the primary. Then the primary is up, and only the Worker cannot reach it. See When the Worker cannot reach the primary.

Pushes stop for 1 to 2 minutes: up to 1 minute until the next check, 20 seconds of checks, and a few seconds for the failover. Clones, fetches and pages go on for the first minute, as Reads while the primary is down says.

You need:

  • The setup of Set up the git servers: the shared secret in ~/gitd-secret, and your SSH key.

  • GITD_IP_US, GITD_IP_EU and GITD_IP_ASIA set to the addresses of the servers, as in step 2 of the setup.

  • psql, and neonctl signed in to the Neon organization of the forge. The rows of the forge are in Postgres on Neon (README.md, "Database"). Put the URL of its database in PG_URL. The URL holds a password, so keep it in this shell only:

    PG_URL="$(neonctl connection-string main --project-id tiny-unit-38538247 --role-name app --database-name source)"

The steps below use us as the old primary and eu as the new one. Use your regions in their place.

1. Find out what the forge did

  1. Open the alert git-failover in Sentry. Its breadcrumbs hold one line with the details:

    {"alert":"git-failover","details":{"from":"us","to":"eu","term":1764100000000,"behind":0,"unreached":"us"}}
    • from is the old primary, and to is the new one.
    • term is the number of this failover: a time in milliseconds.
    • behind counts the repositories where the new primary is older than another replica, or than a version that a replica knew was coming. If it is more than 0, read What a failover can lose.
    • unreached names the servers that did not take the new term from the Worker, or says none. The old primary is one of them while it is down. A server that is up takes the term from the first heartbeat of the new primary.
  2. Ask each server for its role:

    for ip in "$GITD_IP_US" "$GITD_IP_EU" "$GITD_IP_ASIA"; do
      ssh -i ~/.ssh/source_git_ed25519 root@"$ip" curl -fsS 127.0.0.1:8420/healthz; echo
    done

    The new primary answers with "role":"primary" and the new term. A replica answers with "role":"replica", the same term, and "primary":"eu". The old primary does not answer.

  3. Make sure that each repository on the git servers names the new primary:

    psql "$PG_URL" -c "SELECT git_primary, count(*) FROM repos WHERE git_primary IS NOT NULL GROUP BY git_primary"

2. Make sure that git works

  1. Push a commit to a branch of a repository on the git servers.

  2. Clone that repository.

  3. On the analytics server, read the times of the failover. checksMs is the time of the checks, and promotedMs is the time until the database named the new primary:

    clickhouse-client --password "$(cat /root/.clickhouse-admin)" --query "SELECT timestamp, properties FROM analytics.events WHERE event = 'gitd.failover' ORDER BY timestamp DESC LIMIT 1"

3. Bring the old primary back

When the old server works again, start gitd and its tunnel. It needs no new install:

ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_US" systemctl start gitd.service cloudflared.service

gitd starts with its old role. At its first heartbeat, the other servers answer with the newer term. Then it becomes a replica of eu, and keeps that role in its role file (/srv/git/repos/gitd-role). The new primary then sends it each repository that it lacks, in a few minutes. Until then, the Worker reads those repositories from another server.

Make sure that it is a replica now. It answers with "role":"replica" and the new term:

ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_US" curl -fsS 127.0.0.1:8420/healthz

If the old primary has pushes that no other server got, the new primary does not overwrite them. Then the alert git-copy-kept comes each minute. Do Save the pushes that only one server has.

If you rebuilt the server, install it as Add a replica server says.

4. Move the primary back, if you want to

eu can stay the primary. Reads go to the nearest server, and only pushes and writes cross the ocean to eu. To make us the primary again, do this at a quiet time. Pushes stop for about a minute.

  1. Make a header file with the secret, so that the secret is not on the command line:

    (umask 077 && printf 'x-gitd-secret: %s\n' "$(tr -d '\r\n' < ~/gitd-secret)" > ~/gitd-header)
  2. Stop gitd on the current primary. It ends its open requests and its copies to the replicas first:

    ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_EU" systemctl stop gitd.service
  3. Fail over to us at once:

    curl -sS -X POST -H @"$HOME/gitd-header" -H 'content-type: application/json' -d '{"to":"us"}' https://source.tanstack.com/_gitsrv/failover

    The answer looks like {"ok":true,"from":"eu","to":"us","term":1764100060000,"behind":0}.

    If the answer is 409 with behind, us lacks the newest version of some repositories. No server sends them while gitd is stopped on eu, so a wait does not help:

    1. Start gitd on eu again, as in step 4.

    2. Wait until us has each version that eu sends it. The role of us then has no coming part:

      ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_US" 'curl -fsS -H @<(printf "x-gitd-secret: %s\n" "$(cat /etc/gitd/secret)") 127.0.0.1:8420/role'
    3. Do steps 2 and 3 again.

    If the answer is 409 with claimed, another failover holds the claim. A failover keeps its claim for 2 minutes, so you get this answer when you run this step less than 2 minutes after the last failover, for example in a drill. You also get it when the cron fails over at that moment. Keep gitd stopped on eu, wait 1 minute, and run the command again:

    • If it answers {"ok":true,...}, go on with step 4.
    • If it answers 409 with healthy and the primary in us answers, the cron failed over to us. Go on with step 4.
    • If it names another region, the cron failed over to that region. Do steps 2 and 3 again for that region.
  4. Start gitd on eu again. It becomes a replica of us by itself:

    ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_EU" systemctl start gitd.service
  5. Delete the header file: rm ~/gitd-header.

If you do not run step 3, the cron of the Worker fails over by itself within 2 minutes. It picks the newest replica, and us in a tie.

When the Worker cannot reach the primary

The alert git-primary-unreachable comes each minute while the primary does not answer the Worker, but a replica still gets its heartbeats. Its details name the primary, and the replicas that hear it (heardBy). The primary is up, and it can still take pushes and writes through a slow tunnel. So the Worker does not fail over: a write that the old primary takes after the failover is lost.

  1. Look for the cause on the way from the Worker to the primary: its tunnel (systemctl status cloudflared on the server), and the load of the server.
  2. If gitd is slow or stuck, restart it on the primary: systemctl restart gitd.service. A restart is no failover: gitd answers /healthz while it drains.
  3. If you cannot repair the way to the primary, fail over by hand, as When the Worker cannot fail over says. The old primary steps down at the first heartbeat of the new one. A write that ends on it after that gets not-primary, and the Worker or the person tries it again.

When the Worker cannot fail over

The alert git-failover-stuck comes each minute while the primary is down and the Worker cannot fail over. Its details name the reason:

  • no-candidate: no server can be the primary. Each one is down, runs a gitd from before roles, or missed the last failover. Install gitd on a server that runs an older gitd.
  • stale: each server that can be the primary lost the heartbeats of the primary more than 15 seconds before the last time that the Worker found the primary up, or a replica heard it. Such a server can lack the pushes of that time, with no sign of them. Bring the primary back if you can. If you cannot, fail over by hand, and name the server that lost the heartbeats last (its beatAgeMs in GET /role is the smallest).
  • promote-failed: no server took the role. The Worker asks each server that can be the primary, each time with a newer term. Read journalctl -u gitd -n 50 on each server. The next run tries again, as a run that does not fail over gives its claim back.
  • no-binding: this Worker has no Workers VPC binding for the region that the database names as the primary. Add the binding (GITD_US, GITD_EU or GITD_ASIA) to apps/web/wrangler.jsonc, and deploy.

A server that missed the last failover can lack the pushes of the primary of that term. If you can, bring that primary back instead.

To fail over by hand, call the Worker with the header file of step 4. With no to, it picks the newest replica. A failover by hand also runs while a replica still hears the primary, and to a stale server: the Worker trusts your call.

curl -sS -X POST -H @"$HOME/gitd-header" -H 'content-type: application/json' -d '{}' https://source.tanstack.com/_gitsrv/failover
  • 409 with healthy: the primary answers the Worker. Look for the cause on the way to it, for example its tunnel (systemctl status cloudflared on the server).
  • 409 with behind: the region that you named is older than another replica. Name another region, or send no to.

When a server has the wrong term

The alert git-role-drift comes each minute while a server has a term or a primary that is not the one of the last failover. Its details name the region, its term and primary, and the term of the last failover (recordTerm).

A server that was down during the failover takes the term from the first heartbeat of the new primary, and then the alert stops. If the alert goes on:

  1. Read the last failover. Its term and primary are the role that each server must have:

    psql "$PG_URL" -c "SELECT value FROM site_settings WHERE key = 'gitd_primary'"
  2. Give that role to the server. Put the term and the primary of step 1 in the command:

    ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_ASIA" 'curl -fsS -X POST -H @<(printf "x-gitd-secret: %s\n" "$(cat /etc/gitd/secret)") -H "content-type: application/json" -d "{\"term\":<term>,\"primary\":\"<region>\"}" 127.0.0.1:8420/role'

    If the server answers 409 with stale-term, it has a newer term than the last failover. Some other failover gave it that term. Read the role of each server (step 1 of Find out what the forge did) before you change more.

Save the pushes that only one server has

The new primary does not overwrite a copy of a repository on a replica when that copy has a version that the new primary never had. Such a copy holds pushes that reached only that server before the failover. The replica refuses reads of that repository, and the other servers serve them. The alert git-copy-kept comes each minute, with the number of kept copies of each primary (kept).

The new primary also keeps the copy of a repository that it does not have at all: the old primary made it in its last seconds, and no copy reached another server. Then do the steps of When the primary does not have the repository after step 3.

  1. Find the repositories. The kept part of the role of the primary names each one, with the server and the version that it has:

    ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_EU" 'curl -fsS -H @<(printf "x-gitd-secret: %s\n" "$(cat /etc/gitd/secret)") 127.0.0.1:8420/role'

    For example, "kept":{"<repo id>":{"us":42}} says that us keeps the copy of <repo id> at version 42.

  2. On that server, save the copy as a git bundle, as the user git that owns it:

    ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_US" runuser -u git -- env HOME=/srv/git git -C /srv/git/repos/<repo id>.git bundle create /tmp/<repo id>-kept.bundle --all
  3. Copy the bundle to your computer:

    scp -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_US":/tmp/<repo id>-kept.bundle .
  4. Give the commits to the people of the repository. In a clone of the repository, fetch the branches of the bundle, and push the commits that they want to keep to a new branch:

    git fetch <repo id>-kept.bundle 'refs/heads/*:refs/remotes/kept/*'
  5. Delete the copy on that server. The next push to the repository sends the whole repository to that server again:

    ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_US" 'curl -fsS -X DELETE -H @<(printf "x-gitd-secret: %s\n" "$(cat /etc/gitd/secret)") 127.0.0.1:8420/api/<repo id>'

The alert stops at the next push to the repository. To stop it at once, restart gitd on the primary (systemctl restart gitd.service): at its start, it brings each replica level again.

When the primary does not have the repository

If /srv/git/repos/<repo id>.git does not exist on the primary, the forge cannot serve the repository. The bundle of step 3 is its only copy. Put it on the primary:

  1. Copy the bundle to the primary, make the repository from it, and restart gitd there. At its start, gitd writes the hooks of the repository:

    scp -i ~/.ssh/source_git_ed25519 <repo id>-kept.bundle root@"$GITD_IP_EU":/tmp/
    ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_EU" 'chown git:git /tmp/<repo id>-kept.bundle && runuser -u git -- env HOME=/srv/git git clone -q --mirror /tmp/<repo id>-kept.bundle /srv/git/repos/<repo id>.git && runuser -u git -- env HOME=/srv/git git -C /srv/git/repos/<repo id>.git config --remove-section remote.origin && systemctl restart gitd.service'
  2. Delete the copy on the server that kept it, as step 5 says.

  3. Send the repository to the replicas. The command waits until each replica has it:

    apps/gitd/deploy/install.sh replicate <repo id>

When the forge names commits that the primary does not have

The alert git-refs-lost comes once for a repository after a failover. Its details name the repository (repoId), the number of refs (refs) and the term. A branch or a tag of the forge names a commit that the new primary does not have: a push that reached the forge, but no replica. The forge keeps that ref as it is, and pages and merges that need the commit fail.

  1. The old primary keeps those commits, with the alert git-copy-kept. Do Save the pushes that only one server has, so that the people of the repository get them.
  2. The next push to such a branch moves the ref of the forge to the commit of the push. A branch that gets no push keeps the lost commit on the forge: push a new commit to it, or delete it.

When gitd does not start

gitd reads its role file (/srv/git/repos/gitd-role) at each start. If the file is not a role, gitd stops at once, and its log (journalctl -u gitd -n 20) names the file. gitd writes this file whole and syncs it to the disk, so this occurs only after a fault of the disk or an edit by hand.

  1. Read the term and the primary of the last failover:

    psql "$PG_URL" -c "SELECT value FROM site_settings WHERE key = 'gitd_primary'"
  2. Write the role file again with them. Put the term and the primary of step 1 in the command:

    ssh -i ~/.ssh/source_git_ed25519 root@"$GITD_IP_US" 'printf "{\"term\":<term>,\"primary\":\"<region>\"}\n" > /srv/git/repos/gitd-role && chown git:git /srv/git/repos/gitd-role && systemctl start gitd.service'

If the query of step 1 gives no row, no failover occurred yet. Then delete the file instead: the server starts with the role of its config (GITD_ROLE).

Reads while the primary is down

A replica refuses ref reads 10 seconds after the last heartbeat of the primary: it cannot know if a push came after it. While the primary does not answer the Worker, the Worker asks such a replica again for a stale answer, the replica with the newest version first. It does this only for clones, fetches and the git reads of pages. The replica answers when both are true:

  • Its last heartbeat is at most 60 seconds old.
  • It knows of no newer version of the repository. The heartbeats name each version that the primary sends.

So clones, fetches and code pages go on during the first minute. If the failover takes longer, they stop until it ends. The gitd.call and git.request events of such a read say stale.

A stale read can lack the pushes that the primary took after its last heartbeat to that replica. Usually that is the last 2 seconds. If the link between the primary and the replica broke before the primary stopped, it is up to 60 seconds. A read that decides an action never takes a stale answer: CI, a merge, the compare before a write, and the catch-up of a rollback. Writes and pushes go to the primary only.

What a failover can lose

  • A push waits until one replica has it, for 10 seconds at most. If no replica got a push of the old primary in that time, the new primary does not have it. When the old primary comes back, it keeps that push, as Save the pushes that only one server has says.
  • When each replica has the newest version of a different repository, the new primary does not have the last push of some of them (behind). The replica that has such a push keeps its copy of that repository, with the same alert.
  • A write or a push that ends on the old primary after it lost its role does not count. Its refs go back on the old primary, so it never serves them. A write, such as a merge, fails with not-primary, and the Worker or the person tries it again. After a push, git prints a warning to push again. git prints the same warning when the Worker refuses a push because the database names another primary now.
  • A copy of a whole repository that the old primary started before the failover can come after it. The copy names its term, and the server that gets it refuses a term that is not its own. So such a copy moves no ref, also on the new primary.
  • The old primary keeps the calls to the Worker that it still owed (the refs that moved, for CI and webhooks). The Worker refuses them, because the database names another primary now. Instead, in the minutes after the failover, the Worker moves the copy of the refs of each repository to the branches and tags of the new primary, 50 repositories each minute. This move is no push: it starts no CI, sends no webhooks, and moves no pull request head. A branch that only the old primary had goes from the copy when the new primary has its commit. A ref of the copy whose commit the new primary does not have stays as it is: see When the forge names commits that the primary does not have.
  • When a server becomes the primary again, the pushes that it still owed the Worker from an older term do not go to the Worker. gitd moves their records to the folder gitd-owed-<term> of the repository, where an operator can read them.

Done

The new primary takes every push and write, and the replicas serve reads again. The old primary is a replica of the new one. To test all of this on the production servers, run a failover drill.