TuBrief
구독 채널
비디오
커뮤니티

Technical Steps to Ditch Firebase and Switch to $5/mo Self-Hosting

TuBrief 편집팀
2026년 7월 14일
0
Computing/Software

원본 영상을 바탕으로 AI의 도움을 받아 작성했습니다. 원본 영상이 기준입니다.

English한국어Español中文العربيةहिन्दीDeutschFrançaisPortuguêsРусскийBahasa Indonesia日本語

관련 영상

This Free Go Alternative to Firebase is Just One File7:49

This Free Go Alternative to Firebase is Just One File

Better Stack

커뮤니티의 다른 글

사내 시스템에 llm api 붙일 때 마주하는 현실적인 한계와 대응법

2026년 9월 13일

레거시 백엔드에 GPT-6 Astra 붙일 때 예산 승인과 보안 통과를 먼저 끝내는 법이 있습니다

2026년 9월 13일

에이전트끼리 대화하다 6천만 원 청구서가 나오는 이유

2026년 9월 13일

사내 RAG 벡터 검색에 Okta 권한 필터를 직접 거는 방법

2026년 9월 13일

브라우저 에이전트에게 내 구글 계정을 통째로 넘기면 안 되는 이유

2026년 9월 12일

Apple Won the AI Race

2026년 9월 12일

댓글 (0)

Log in to leave a comment

아직 작성된 글이 없습니다

© 2026 . All rights reserved.

TuBrief
구독 채널
비디오
커뮤니티
로그인

Technical Steps to Ditch Firebase and Switch to $5/mo Self-Hosting

Firebase is sweet at the beginning. You can just focus on implementing features without worrying about infrastructure. However, even with just a little bit of growth, the numbers on your bill start to climb. But the thought of moving to self-hosting is daunting. What if data gets lost? What if the service stops every time I deploy?

These are valid concerns. But there is a way. I have compiled the specific steps to safely migrate your Firestore data to PocketBase—an all-in-one SQLite-based backend—and build a zero-downtime deployment environment using GitHub Actions and Nginx.


Pipeline for Migrating Firestore Data to PocketBase

The first wall you hit when moving unstructured data from Firestore to a relational model-based PocketBase schema is the identifier length. Firestore uses 20-character document IDs, while PocketBase imposes a 15-character alphanumeric constraint by default. If you ignore this and push them through, you will see a validation_length_invalid error.

To avoid this, you need to shorten the length while maintaining uniqueness. The most reliable method is to hash the Firestore ID with SHA256 and use the first 15 characters. You don't need to worry about collisions; the probability of a 15-character hash colliding, even in large datasets, is negligibly low.

The structure of a Node.js migration script to handle this looks like this. It uses the firebase-admin and axios packages to fetch data in batches of 100.

`javascript
// migration.js
const admin = require('firebase-admin');
const axios = require('axios');
const crypto = require('crypto');

admin.initializeApp({
credential: admin.credential.applicationDefault()
});

const db = admin.firestore();
const PB_URL = 'http://127.0.0.1:8090/api/collections/posts/records';

async function migrate() {
let lastDoc = null;
let hasMore = true;

while (hasMore) {
let query = db.collection('posts').orderBy('name').limit(100);
if (lastDoc) {
query = query.startAfter(lastDoc);
}

const snapshot = await query.get();
if (snapshot.empty) {
  hasMore = false;
  break;
}

for (const doc of snapshot.docs) {
  const data = doc.data();
  // Convert 20-char Firestore ID to 15-char alphanumeric
  const newId = crypto.createHash('sha256').update(doc.id).digest('hex').substring(0, 15);
  
  try {
    await axios.post(PB_URL, {
      id: newId,
      firestore_id: doc.id, // Record original ID for potential verification
      title: data.title,
      content: data.content
    });
  } catch (err) {
    console.error(`Migration failed: ${doc.id}`, err.response?.data);
  }
}
lastDoc = snapshot.docs[snapshot.docs.length - 1];

}
}

migrate();

`

To do this without downtime, you need a transition period. First, use this script to migrate over 90% of your existing data in the background. Then, deploy "Dual-Write" code in your client application that writes to both Firebase and PocketBase simultaneously. Once you verify that data matches in both, change your read endpoints to PocketBase and remove the Firebase code. From the user's perspective, the server never stops for even a second.


Setting Up a 24/7 PocketBase Server

PocketBase is a lightweight backend that runs as a single binary. However, if you just run it on a Linux server, there is no way to recover the service if the process shuts down due to an unexpected Out-of-Memory (OOM) error.

You need to configure systemd to make the process self-healing. Create an /etc/systemd/system/pocketbase.service file and register the following content:

`ini
[Unit]
Description=PocketBase Service
After=network.target

[Service]
Type=simple
User=pocketbase
Group=pocketbase
LimitNOFILE=65535
ExecStart=/opt/pocketbase/pocketbase serve --http="127.0.0.1:8090"
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

`

The LimitNOFILE=65535 setting is crucial here. When using PocketBase's real-time subscription (WebSocket) feature, this prevents disconnections caused by hitting the default Linux file descriptor limit during traffic spikes.

Place Nginx in front to handle SSL certificates and proxying. You need to add options to your /etc/nginx/sites-available/pocketbase config to ensure real-time stream connections aren't delayed.

`nginx
upstream pocketbase {
server 127.0.0.1:8090;
}

server {
server_name api.yourdomain.com;

location / {
    proxy_pass http://pocketbase;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;

    # Support for WebSockets and SSE real-time streaming
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_buffering off;
}

}

`

Now, just apply an HTTPS certificate with the certbot --nginx command, and the basic infrastructure is ready.

In my experience, even on the cheapest VPS tier with 512MB of RAM, if you tweak the SQLite settings, it easily handles over 1,000 light requests per second. To maximize SQLite performance when running PocketBase, you should use WAL (Write-Ahead Log) mode. PocketBase enables WAL mode by default, but if you ever handle SQLite directly, check the PRAGMA journal_mode=WAL; and PRAGMA synchronous=NORMAL; settings. This eliminates almost all bottlenecks where requests wait for disk writes.


Real-time Backups with Cloudflare R2 and Litestream

The most common mistake indie hackers make is copying the active SQLite database file (data.db) directly from a running server for backups. This method carries a high risk of data corruption during the backup process.

We use Litestream. It is a tool that intercepts SQLite's WAL frames in real-time and pushes only the changed parts to cloud storage. I recommend Cloudflare R2 as the backup storage because outbound transfer fees are free, meaning you incur almost no costs regardless of how many backups you take.

Write the /etc/litestream.yml configuration file as follows:

`yaml
dbs:

  • path: /opt/pocketbase/pb_data/data.db
    replicas:
    • type: s3
      bucket: your-r2-bucket-name
      endpoint: https://.r2.cloudflarestorage.com
      access-key-id:
      secret-access-key:

`

With this setup, even if the original db file is lost, you can restore it to within 1 second of its last state with a single command:

`bash
litestream restore -if-replica-exists /opt/pocketbase/pb_data/data.db

`

If you accidentally wipe data during development and need to restore to a specific point in time, you can also specify the timestamp:

`bash

1. Temporarily stop PocketBase

sudo systemctl stop pocketbase.service

2. Generate restoration file for a specific time

litestream restore -timestamp "2026-07-14T15:00:00Z" -o /tmp/recovered.db /opt/pocketbase/pb_data/data.db

3. Check data integrity and replace file

sqlite3 /tmp/recovered.db "PRAGMA integrity_check;"
mv /tmp/recovered.db /opt/pocketbase/pb_data/data.db
chown -R pocketbase:pocketbase /opt/pocketbase/pb_data/

4. Resume service

sudo systemctl start pocketbase.service

`

Cloudflare R2 provides 10GB of free storage every month. It also includes free credits for 1 million write requests and 10 million read requests, making the backup cost effectively zero for a solo service.


Zero-Downtime Deployment Using GitHub Actions and Nginx

Deploying with Docker is convenient, but on small VPS instances with 512MB or 1GB of RAM, even the memory used by the Docker daemon itself is significant. We can implement zero-downtime deployment (Blue-Green) by alternating ports in Linux systemd without using Docker.

This takes advantage of SQLite's nature, which allows multiple processes to read and write to a single SQLite file. We register a systemd service template so that the PocketBase binary can be run on port 9011 (Blue) and port 9012 (Green), respectively.

First, here is an example workflow for transferring the binary built by GitHub Actions to the server:

`yaml

.github/workflows/deploy.yml

name: Deploy
on:
push:
branches: [ main ]

jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.22'
- name: Build
run: |
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o pocketbase main.go
- name: Transfer Binary to VPS
uses: appleboy/scp-action@master
with:
host: ${{ secrets.VPS_HOST }}
username: ${{ secrets.VPS_USER }}
key: ${{ secrets.VPS_KEY }}
source: "pocketbase"
target: "/srv/pocketbase/next_release"

`

Once the binary arrives on the server, a deployment script runs. It checks whether the currently active port is 9011 or 9012 and runs the new version of the binary on the idle port.

`bash
#!/bin/bash

deploy_swap.sh

CURRENT_PORT=$(curl -s http://127.0.0.1:8090/api/health | jq -r '.port' 2>/dev/null || echo "9011")

if [ "$CURRENT_PORT" = "9011" ]; then
TARGET_PORT="9012"
else
TARGET_PORT="9011"
fi

Run new version binary on the target port in the background

sudo systemctl start pocketbase@$TARGET_PORT.service

Wait 3 seconds for health check

sleep 3
HEALTH_CHECK=(curl−shttp://127.0.0.1:(curl -s http://127.0.0.1:(curl−shttp://127.0.0.1:TARGET_PORT/api/health | jq -r '.status')

if [ "HEALTH_CHECK" = "OK" ]; then # Update Nginx upstream config to the new port and reload echo "upstream pocketbase { server 127.0.0.1:TARGET_PORT; }" | sudo tee /etc/nginx/conf.d/upstream.conf
sudo systemctl reload nginx

# Stop old version process
sudo systemctl stop pocketbase@$CURRENT_PORT.service
echo "Deployment complete. Port $TARGET_PORT successfully switched."

else
echo "Deployment failed. New version health check failed."
sudo systemctl stop pocketbase@$TARGET_PORT.service
exit 1
fi

`

Using this method, zero-downtime deployment works perfectly without expensive container orchestration tools. Because Nginx buffers requests for the fraction of a second (in milliseconds) it takes to reload during deployment, it safely passes requests to the new port without the user noticing.

Self-hosting requires some effort during the initial setup, but once configured, it becomes an excellent foundation that allows you to focus solely on your product without worrying about monthly infrastructure costs.