Designing Reliable Automation Pipelines for Persistent Game Worlds

A practical exploration of reasoning, architecture and stable backup mechanisms

DevOps
Automation
Infrastructure
Systems Design
Reliability Engineering
This post presents the reasoning process and technical decisions that led to the creation of a reliable backup and automation workflow for persistent game servers, including a real use case related to maintaining stable Minecraft sessions at home.
Author
Published

December 4, 2025

Modified

November 5, 2026

NoteUpdated on November 5, 2026

The reference implementation now also runs Horizon, the community rewrite of Minecraft 26.3 in Rust, next to the official Java server (PR #2, PR #3). This post now covers the new server layer, the Horizon image and how a stop from inside the game is handled.

The previous update (October 22, 2026) was a reliability and security release: most importantly, the GitHub token is no longer embedded in the remote URL, where the original version wrote it to the repository config and to the logs. See the revision history.


Reference Implementation

The complete implementation described throughout this post is publicly available in the following repository:

GitHub Repository
danieltorquatof/minecraft-backup · project page (status and updates)

The project contains the full set of scripts, Docker definitions and utility functions that support the automation flow presented below. The excerpts in this post come from commit 80236c9; reviewing the code directly in the repository can help contextualise the behaviour of each component and illustrate how the pieces integrate in practice.


Key Code Excerpts

Although the full implementation is available in the repository, a few excerpts help illustrate the mechanics behind the automation layer. The example below shows how the autosave routine guards against overlapping runs and then delegates world persistence to a dedicated function that commits the updated data to Git. That function talks to the game through a small server layer, so it works the same with the Java server and with Horizon.

scripts/autosave.sh

View on GitHub

#!/bin/bash
# Periodic backup, run every PERIODIC_INTERVAL minutes while the server is up.
# Can also be run by hand: docker compose exec minecraft /opt/minecraft-backup/scripts/autosave.sh

source /opt/minecraft-backup/utils/saveWorld.sh

LOG_FILE="$LOG_DIR/autosave.log"

exec 9>"$LOCK_FILE"

if ! flock -n 9; then
  log "AUTOSAVE" "Another backup is still running. Skipping."
  exit 0
fi

if ! server_online; then
  log "AUTOSAVE" "Server is not accepting commands yet. Skipping."
  exit 0
fi

log "AUTOSAVE" "Starting execution..."

if ! saveWorld "AUTOSAVE"; then
  log "AUTOSAVE" "Execution failed."
  exit 1
fi

log "AUTOSAVE" "Execution completed."

utils/saveWorld.sh

View on GitHub

# Flushes the world to disk (when the server is running), commits every change and pushes it.
saveWorld() {
  local prefix="$1"
  local online=false

  # ... ensure_repo prepares the repository (omitted)

  if server_online; then
    online=true

    server_cmd 'tellraw @a {"text":"📂 Backup started!","color":"gold"}' >/dev/null

    # Pause automatic saving so region files are not rewritten while they are staged.
    server_cmd save-off >/dev/null
    server_cmd save-all flush >/dev/null
  fi

  local add_status=0
  repo_git add -A || add_status=$?

  if [ "$online" = true ]; then
    server_cmd save-on >/dev/null || log "$prefix" "WARNING: could not re-enable automatic saving."
  fi

  if [ "$add_status" -ne 0 ]; then
    log "$prefix" "ERROR: git add failed."
    return 1
  fi

  if repo_git diff --cached --quiet; then
    log "$prefix" "No changes since the last backup."
  else
    local commit_msg
    commit_msg="$(date -u +"%Y-%m-%dT%H:%M:%SZ") - $prefix"

    repo_git commit -q -m "$commit_msg" || return 1
  fi

  # Also sends commits left behind by previous failed pushes.
  if ! repo_git push -q -u origin HEAD; then
    log "$prefix" "ERROR: git push failed."
    # ... warns the players in game (omitted)
    return 1
  fi

  log "$prefix" "Backup successfully pushed."
}

utils/server.sh: one interface, two servers

View on GitHub

SERVER_FLAVOR is set by each Dockerfile. The Java image sends console commands through RCON; Horizon has a local control API (horizon-server cmd), so it needs no RCON at all. Everything above this layer only calls server_cmd and server_online:

# Runs one console command (e.g. `server_cmd save-all flush`). Fails if the server can't be reached.
server_cmd() {
  if is_horizon; then
    horizon cmd "$@"
  else
    rcon "$@"
  fi
}

server_online() {
  if is_horizon; then
    horizon status --json 2>/dev/null | grep -q '"phase":"running"'
  else
    rcon list >/dev/null 2>&1
  fi
}

utils/common.sh: credentials

View on GitHub

The token is handed to Git through an inline credential helper defined in environment variables, so it never reaches the remote URL, a config file or the logs:

export GIT_TERMINAL_PROMPT=0
export GIT_CONFIG_COUNT=3
export GIT_CONFIG_KEY_0="safe.directory"
export GIT_CONFIG_VALUE_0="$REPO_DIR"
export GIT_CONFIG_KEY_1="init.defaultBranch"
export GIT_CONFIG_VALUE_1="$GIT_BRANCH"
export GIT_CONFIG_KEY_2="credential.helper"
export GIT_CONFIG_VALUE_2='!f() { test "$1" = get && test -n "$GITHUB_TOKEN" && echo "username=${GITHUB_USER:-x-access-token}" && echo "password=$GITHUB_TOKEN"; }; f'

These sections illustrate the predictable structure that supports periodic and manual world preservation. The underlying model is intentionally minimalistic so the logic remains transparent and easy to debug, while every step reports failures instead of assuming success.


Persistent digital environments demand predictable behaviour. Whether managing corporate infrastructure or personal projects, stability depends on systems that continue to operate even when attention shifts elsewhere. Over time I realised that reliable automation is not only relevant in professional settings. It can also solve surprisingly ordinary problems.

A practical example emerged in my own home. My partner and I often play Minecraft together and our sessions sometimes last several hours. Anyone who has hosted a local or containerised server knows that crashes or unexpected shutdowns can corrupt the world or erase progress. After losing entire builds on more than one occasion I started thinking seriously about how to design a stable and automatic backup mechanism that would remove the risk altogether.

This line of thinking eventually led to a full architecture that integrates Docker, Git and GitHub for continuous world versioning. Although this post uses that implementation as a reference, the focus here is the reasoning that guides the creation of automation pipelines that are reliable, observable and resilient.


Designing the Automation Flow

Before exploring each script it is useful to visualise how the overall workflow operates. The intention was to create a loop that could run indefinitely, independent of the user’s attention.

flowchart TB;
  A[Container starts]
  B[Validate configuration]
  Z[Horizon only: prepare server.toml and game files]
  C[Initialisation script]
  D{Remote has backups?}
  E[Clone or fast-forward repository]
  F[Prepare empty repository]
  G[Start Minecraft server: Java or Horizon]
  H[Periodic loop starts]
  I[Autosave script executes every N minutes]
  J[saveWorld.sh]
  K[Pause saving and flush world]
  L[Git add, resume saving, commit if changed]
  M[Push to GitHub]
  N[Container receives stop signal]
  O[Stop server gracefully]
  P[Shutdown script]

  A --> B
  B --> Z
  Z --> C
  C --> D

  D -- Yes --> E
  D -- No --> F

  E --> G
  F --> G

  G --> H
  H --> I

  I --> J
  J --> K
  K --> L
  L --> M

  G --> N
  N --> O
  O --> P
  P --> J

This diagram reflects the core concept. Every event leads to a deterministic and observable action. World data is always saved, always committed and always pushed, and any step that fails is logged and reported instead of silently ignored.


Understanding the File Structure

The project uses a modular structure that separates concerns and creates predictable behaviours. Each file contributes uniquely to the automation pipeline.

.
├── .github/workflows/ci.yml   # ShellCheck, Hadolint, compose validation, image builds and a Horizon smoke test
├── docker-compose.yml         # Java server (itzg/minecraft-server)
├── docker-compose.horizon.yml # Horizon server (Rust)
├── Dockerfile                 # Java image
├── Dockerfile.horizon         # Horizon image
├── entrypoint.sh              # Startup → periodic loop → graceful shutdown
├── .env.example               # Java settings
├── .env.horizon.example       # Horizon settings
├── scripts
│   ├── autosave.sh            # Periodic backup (can also be run by hand)
│   ├── healthcheck.sh         # Docker health check of the Horizon image
│   ├── init.sh                # Restores/clones the world before the server starts
│   └── shutdown.sh            # Final backup after the server stops
└── utils
    ├── common.sh              # Shared configuration and git helpers
    ├── horizon.sh             # Horizon setup: server.toml, world name, game files
    ├── log.sh                 # Logging to stdout and ./logs
    ├── saveWorld.sh           # Flush → commit → push
    └── server.sh              # Server backend: start, console commands, online check (Java or Horizon)

Each one will be explained individually so the full picture becomes clear.


Container and Image Definitions

docker-compose.yml

Defines how the server is launched. It handles:

  • Port exposure for gameplay only (MC_HOST_PORT, 25565 by default). RCON stays inside the container, since backups are the only thing that uses it;
  • Environment variable loading;
  • Persistence of the Minecraft world and logs;
  • Building the custom image from the local Dockerfile;
  • A three minute stop_grace_period, so Docker does not kill the container while the final backup is being pushed.

Its purpose is to maintain stability across restarts and ensure that all automation scripts remain present inside the container.

docker-compose.horizon.yml does the same for Horizon. It mounts the Minecraft 26.3 game files read-only (Horizon needs files prepared from your own copy of the game, which are never shipped in the image) and allows four minutes to stop, since Horizon may take up to three to save. Both files share ./data, so the same world can move between the two servers, one at a time.


Dockerfile

The Dockerfile extends the “official” image itzg/minecraft-server:java25 (configurable through MC_IMAGE_TAG for older Minecraft versions) then installs all custom scripts under /opt/minecraft-backup. This combination provides the reliability of a well maintained base image while enabling custom behaviour controlled entirely by our own entrypoint.

flowchart LR;
  A[""Official" Minecraft Server Image"]
  B[Import custom scripts]
  C[Add entrypoint logic]
  D[Build customised backup capable image]

  A --> B
  B --> C
  C --> D

This duality of stability and customisation supports the idea of predictable infrastructure that can also adapt to specific needs.

Dockerfile.horizon

Horizon publishes an official Dockerfile but no image, so Dockerfile.horizon downloads a pinned, dated nightly release and verifies it against the published SHA256SUMS before installing the same scripts. Pinning matters here: Horizon changes daily, so a new version is tested on a copy of the world before the pin moves. The image runs as UID 1000, like the Java one, and adds a Docker health check.


Core Execution Orchestrator

entrypoint.sh

This script coordinates the lifecycle of the server and backup system.

It performs:

  1. Configuration validation (repository name, token, interval and, for Horizon, the EULA);
  2. Horizon setup, when that image is used (utils/horizon.sh);
  3. Initialisation and startup synchronisation;
  4. Launch of the periodic autosave loop;
  5. Server start through server_start: the itzg start script or horizon-server run;
  6. Graceful shutdown: the server is stopped first, then the final backup runs.

A second diagram helps illustrate this behaviour.

flowchart TB;
  A[entrypoint.sh starts]
  V{Configuration valid?}
  X[Exit with a clear error]
  B[Run init.sh]
  C[Configure and sync repository]
  D[Start autosave loop in background]
  E[Begin Minecraft server]
  F{Stop signal received?}
  S[Stop server and wait for it to save]
  G[Run shutdown.sh]
  H[Final commit and push]

  A --> V
  V -- No --> X
  V -- Yes --> HZ{Horizon?}
  HZ -- Yes --> HS[Prepare server.toml and game files]
  HZ -- No --> B
  HS --> B
  B --> C
  C --> D
  D --> E
  E --> F
  F -- Yes --> S
  S --> G
  G --> H
  F -- No --> E

This flow ensures that no world data is lost, regardless of how the container stops. The same final backup also runs when the server stops on its own, for example after /stop in game.

Horizon needed one extra piece here. When the game is stopped from inside (/stop, RCON or horizon-server cmd stop), its supervisor stays up on purpose, waiting for a start that never comes in a container: the container would stay up, autosaves would skip every run and no final backup would be taken. A small watcher (server_watch_stop) ends the supervisor once the game reports stopped twice in a row, after having been up, so the usual shutdown path takes over. Checking twice skips the brief stopped phase a horizon-server restart passes through.


Utility Layers

utils/common.sh

Shared configuration used by every script: the Git identity (commits fail without a committer), the credential helper shown above and a function that runs Git as the same user as the server, so no world file ends up owned by root.


utils/server.sh

The server backend shown in the excerpts: how to start the server, send it console commands and tell whether it is up, for either flavour. It also holds the Horizon stop watcher.


utils/horizon.sh

Runs only on the Horizon image, before the world is restored. It writes server.toml on the first start, always sets the world name to the backup repository name, turns off Horizon’s own zip backups (they also pause saving and would collide with the Git ones) and checks that the prepared game files are present, stopping the container with a clear message when they are not.


utils/log.sh

A lightweight logger that standardises how each script communicates events. Every log entry includes a timestamp and prefix and goes both to docker compose logs and to persistent storage, so it survives container recreation. This improves verification and troubleshooting.


utils/saveWorld.sh

The most responsibilities in the automation pipeline concentrate here. It performs:

  • In game world flush through the server layer (RCON on Java, the control API on Horizon), with automatic saving paused while files are staged
  • Git staging and committing (only when something changed)
  • Push synchronisation with GitHub, including commits left behind by earlier failed pushes
  • Messaging for both users and logs

It represents the core reliability mechanism. If this script functions correctly, every world state becomes recoverable.


Lifecycle Scripts

scripts/init.sh

Executed only during startup. It validates the remote repository, checks whether it exists and whether it is empty. It clones the repository, fast-forwards an existing clone or prepares a new one so the world directory becomes fully managed by Git. A local world without history is moved aside instead of being overwritten. This step prevents drift between the running server and the stored history.


scripts/autosave.sh

Runs periodically based on the interval defined in the environment variables. It skips the run when another backup is still in progress or the server is not ready yet, and otherwise calls saveWorld.sh. These periodic commits create a complete backup timeline.


scripts/shutdown.sh

Triggered after the server has stopped, whether by docker compose stop, by the game itself or, on Horizon, by the stop watcher. It waits for any backup still in progress and calls saveWorld.sh so the final server state is stored safely. Because the server has already flushed the world to disk, this prevents data corruption and makes the server restart friendly regardless of how the container was stopped.


Environment Templates and Management

.env.example and .env.horizon.example

Guide the user in defining:

  • GitHub repository credentials (a fine-grained token limited to the backup repository is enough)
  • Minecraft server settings and the base image tag
  • Backup intervals and an optional Git remote other than GitHub
  • Metadata for commits
  • For Horizon: the EULA, where the prepared game files are and first-start settings such as the seed and whitelist

This separation of configuration strengthens clarity and reduces accidental misconfiguration, and the entrypoint refuses to start with an invalid one.


Why This Matters

Although the technical implementation is interesting, the motivation emerged from a real problem. Playing Minecraft with my partner is one of our favourite activities and losing progress due to corruption or abrupt shutdowns was frustrating. Manual backups were easy to forget and relying on memory alone was not sustainable.

Creating an infrastructure that handles backups automatically removed the cognitive load entirely. It also ensured that every session became safe. The system evolved from a personal inconvenience into an elegant example of how automation thinking can improve both professional and personal digital environments.

This project demonstrates that reliable systems do not appear spontaneously. They are built through reasoning, testing and iteration. The first version already worked for everyday use, yet running it for months revealed failures that only appear over time: commits that failed without a committer identity, a token that leaked into the logs, a final backup racing against the server’s own shutdown. Adding a second server later was mostly a matter of putting a small interface where the code used to call RCON directly, and testing it against the real thing exposed the one behaviour no documentation mentioned: a game that stops while its supervisor keeps running. Whether used for game worlds, business processes or experimental environments, the principles remain consistent: predictable automation, clear observability and robust fallback mechanisms.


Final Considerations

Constructing automation flows like this establishes a foundation for trust in any persistent system. Once the structure works without supervision, users are free to focus on the experience rather than maintenance. In my case it allowed long sessions of building and exploration with my partner to continue without disruption.

I hope this explanation clarifies not only what the system does, but also how it was structured and why the reasoning behind it led to a reliable design.


Revision history

  • November 5, 2026: Added Horizon (Rust) support to the reference implementation (PR #2, PR #3): server layer (utils/server.sh) in the excerpts, Horizon image and compose file, Horizon setup and the in-game stop watcher.
  • October 22, 2026: Updated for the reliability and security release of the reference implementation (PR #1): new code excerpts, credential handling, graceful shutdown, consistent snapshots, Java 25 image and CI.
  • December 4, 2025: First published.