Backing up app server Postgres instance

In a perfectly scalable system, you usually put your DB instance on a separate server, and other servers will connect to it remotely. DB servers have functionalities like backup/restore, auto-upgrade, and many more. This makes you think less about managing the DB — you just write your application, connect to the DB, and that's it.

Storing the DB instance on a separate server enables you to build a scalable system. You could have multiple instances of the application server (which are load balanced), and they might remotely connect to a single DB instance (as a single source of truth).

If, on the other hand, you store your DB instance within the same application server, you cannot scale it to multiple application servers.

Although storing the DB instance within the application server is not a best practice, I did it in production. The main reason is that storing the DB instance within the application server cuts around $20–$30 in monthly costs for us. Also, in the city where we launched the startup, there might be a maximum of around 5-10k monthly users in the first year, optimistically. So a single server with a DB instance is more than enough for our current load. As a startup, we want maximum results with minimum resources.

You could argue: what happens if your application server crashes, gets hacked, etc.? First of all, I tried to apply all possible best practices to keep my server secure. Secondly, as a backup plan, I created a unique way to back up my database daily.

The idea is that every day at 3 AM (midnight), my server does an important thing :). It backs up the database and uploads the backup to Google Cloud Storage. With this implementation, I can restore my data even if my database gets deleted. For our startup, a 1-day interval is enough for backups. If it is not, I can configure the interval as I want. Also, from time to time, I manually delete obsolete backup files from Cloud Storage.

Below, I am providing the code examples on how I did it in Ktor. Sensitive data is, of course, hidden.

Here is the scheduleMidnightJobs function that executes multiple jobs exactly at 3 AM based on Uzbekistan time:

fun Application.scheduleMidnightJobs() {
    launch(Dispatchers.IO) {
        while (true) {
            val delayMillis = millisUntilMidnight()
            delay(delayMillis)

             // .... hidden

            runCatching {
                println("🚀 Starting daily backup at ${ZonedDateTime.now(uzbekistanTimeZone)}")
                performBackupAndUpload(
                    bucketName = STORAGE_BUCKET,
                    storage = GoogleCloudStorage.googleCloudStorage
                )
                println("✅ Backup completed successfully at ${ZonedDateTime.now(uzbekistanTimeZone)}")
            }.onFailure { e ->
                println("❌ Backup failed: ${e.message}")
            }

            // .... hidden
        }
    }
}

private fun millisUntilMidnight(): Long {
    val now = ZonedDateTime.now(uzbekistanTimeZone)
    val nextRun = now.withHour(3).withMinute(0).withSecond(0).withNano(0)
        .let { if (it.isBefore(now)) it.plusDays(1) else it }

    return Duration.between(now, nextRun).toMillis()
}

This is a function that executes a backup script that is stored within the project’s root directory and uploads the backup to Google Cloud Storage:

suspend fun performBackupAndUpload(
    bucketName: String,
    storage: Storage
) = withContext(Dispatchers.IO) {
    val projectRoot = "{hidden}"
    val backupScript = "$projectRoot/backup/backup.sh"
    val backupDir = "$projectRoot/backup/backups"

    val backupFileName = "{db_name_hidden}_backup_${LocalDateTime.now()}.dump"
    val process = ProcessBuilder("bash", backupScript, backupFileName)
        .directory(File(projectRoot))
        .redirectErrorStream(true)
        .start()

    val output = process.inputStream.bufferedReader().readText()
    val exitCode = process.waitFor()

    if (exitCode != 0) {
        throw RuntimeException("Backup script failed (exit code $exitCode): $output")
    }
    println("Backup script output $output")

    // Get generated .gz file
    val gzFile = File("$backupDir/$backupFileName.gz")
    if (!gzFile.exists()) {
        throw RuntimeException("Backup file not found: ${gzFile.absolutePath}")
    }

    // Upload to Google Cloud Storage (private)
    val blobName = "db_backups/${gzFile.name}"
    storage.create(
        BlobInfo.newBuilder(bucketName, blobName)
            .setContentType("application/gzip")
            .build(),
        gzFile.readBytes()
    )

    // Clean up local backup
    gzFile.delete()
    println("Backup uploaded to GCS: $blobName")
}

This is actual backup script:

#!/bin/bash

# === PostgreSQL Backup Script ===
set -euo pipefail

# Database connection settings
DB_NAME="{hidden}"
DB_USER="{hidden}"
DB_HOST="{hidden}"
DB_PORT="{hidden}"
DB_PASSWORD="{hidden}" 

FILENAME="${1:-}"

BACKUP_DIR="$(pwd)/backup/backups"
mkdir -p "$BACKUP_DIR"

if [ -z "$FILENAME" ]; then
    DATE=$(date +"%Y%m%d_%H%M%S")
    FILENAME="${DB_NAME}_${DATE}.dump"
fi

BACKUP_PATH="${BACKUP_DIR}/${FILENAME}"
LOG_FILE="${BACKUP_DIR}/backup.log"

echo "[$(date)] Starting PostgreSQL backup..." | tee -a "$LOG_FILE"
echo "Backup file will be saved to: $BACKUP_PATH" | tee -a "$LOG_FILE"

PGPASSWORD="$DB_PASSWORD" pg_dump -U "$DB_USER" -h "$DB_HOST" -p "$DB_PORT" -d "$DB_NAME" -F c -f "$BACKUP_PATH"

gzip "$BACKUP_PATH"

SIZE=$(du -h "${BACKUP_PATH}.gz" | cut -f1)
echo "[$(date)] ✅ Backup successful: ${BACKUP_PATH}.gz ($SIZE)" | tee -a "$LOG_FILE"

echo "[$(date)] Backup process completed." | tee -a "$LOG_FILE"
echo "===============================================" | tee -a "$LOG_FILE"