Self-Hosting Plausible Analytics: The $0 Privacy-Friendly Alternative to Google Analytics 4
Google Analytics 4 (GA4) has become a notorious source of frustration for engineering teams and startup founders. Beyond its sluggish dashboard, confusing attribution models, and complex reporting UI, GA4 imposes significant privacy liabilities under GDPR and ePrivacy regulations. Loading the heavy gtag.js tracking script adds 45KB+ of JavaScript bloat, worsens Core Web Vitals (specifically Total Blocking Time), and is routinely blocked by upwards of 35% to 50% of developer-oriented web browsers running uBlock Origin or Brave.
Plausible Analytics offers a modern, open-source alternative. Its client tracking script is under 1KB, requires zero cookies, operates 100% compliant with GDPR out-of-the-box, and provides an instant, responsive dashboard. While Plausible offers a managed cloud service, the core platform is completely open-source and can be self-hosted on a modest $6/month VPS handling millions of monthly pageviews.
Architecture Overview: How Plausible Handles Millions of Events
Unlike traditional web analytics that store events in relational tables, Plausible utilizes a hybrid dual-datastore architecture optimized for write throughput and analytical queries:
- ClickHouse Columnar Database: Handles the high-speed ingestion and aggregation of raw time-series pageview events and custom goals. ClickHouse compresses event data by up to 90% and answers analytical aggregations across 50 million rows in sub-50 milliseconds.
- PostgreSQL Relational Database: Stores user accounts, site configurations, team memberships, and dashboard settings.
- Plausible Application Server (Elixir / Phoenix): Powered by the Erlang BEAM runtime, providing massive concurrency, low memory footprint, and fault tolerance for real-time WebSocket dashboard updates.
Infrastructure Prerequisites
For websites receiving up to 2 million monthly pageviews, a standard virtual private server (Hetzner Cloud, DigitalOcean, or Linode) with the following specifications is sufficient:
- 2 vCPUs (x86_64 or ARM64)
- 4 GB RAM (ClickHouse requires at least 2GB of headroom for query memory buffers)
- 40 GB NVMe SSD storage
- Ubuntu 22.04 or 24.04 LTS
- Docker Engine & Docker Compose plugin installed
Step 1: Production Docker Compose Configuration (docker-compose.yml)
Create a dedicated directory on your VPS at /opt/plausible and create the docker-compose.yml file:
version: "3.8"
services:
mail:
image: bytemark/smtp
restart: always
plausible_db:
image: postgres:16-alpine
restart: always
volumes:
- db-data:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=postgres_secure_password_replace
- POSTGRES_USER=plausible
- POSTGRES_DB=plausible_db
plausible_events_db:
image: clickhouse/clickhouse-server:24.3-alpine
restart: always
volumes:
- event-data:/var/lib/clickhouse
- ./clickhouse/clickhouse-config.xml:/etc/clickhouse-server/config.d/logging.xml:ro
- ./clickhouse/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/logging.xml:ro
ulimits:
nofile:
soft: 262144
hard: 262144
plausible:
image: plausible/analytics:v2.1.4
restart: always
command: sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh run"
depends_on:
- plausible_db
- plausible_events_db
- mail
ports:
- "127.0.0.1:8000:8000"
env_file:
- plausible-conf.env
volumes:
db-data:
event-data:
Step 2: Environment Configuration (plausible-conf.env)
Create the environment configuration file /opt/plausible/plausible-conf.env. Generate strong 64-character random secrets using openssl rand -base64 48:
BASE_URL=https://stats.yourdomain.com
SECRET_KEY_BASE=YOUR_GENERATED_64_CHAR_BASE64_SECRET
TOTP_VAULT_KEY=YOUR_GENERATED_32_CHAR_BASE64_KEY
# PostgreSQL connection string
DATABASE_URL=postgres://plausible:postgres_secure_password_replace@plausible_db:5432/plausible_db
# ClickHouse connection string
CLICKHOUSE_DATABASE_URL=http://plausible_events_db:8123/plausible_events_db
# Disable public registrations after creating initial admin account
DISABLE_REGISTRATION=true
# SMTP Mail server credentials
MAILER_EMAIL=notifications@yourdomain.com
SMTP_HOST_ADDR=mail
SMTP_HOST_PORT=25
Step 3: ClickHouse Logging Configuration
By default, ClickHouse logs aggressively, consuming gigabytes of disk space on smaller VPS instances. Create the XML configuration overrides in /opt/plausible/clickhouse/:
mkdir -p /opt/plausible/clickhouse
cat << 'EOF' > /opt/plausible/clickhouse/clickhouse-config.xml
<clickhouse>
<logger>
<level>warning</level>
<size>100M</size>
<count>3</count>
</logger>
</clickhouse>
EOF
cat << 'EOF' > /opt/plausible/clickhouse/clickhouse-user-config.xml
<clickhouse>
<profiles>
<default>
<max_memory_usage>2000000000</max_memory_usage>
</default>
</profiles>
</clickhouse>
EOF
Step 4: Reverse Proxy & Automatic SSL with Caddy
Instead of manually wrestling with Certbot and complex Nginx configurations, use Caddy to handle automatic HTTPS certificate issuance and HTTP/3 reverse proxying. Add this block to your /etc/caddy/Caddyfile:
stats.yourdomain.com {
reverse_proxy 127.0.0.1:8000 {
header_up X-Forwarded-For {remote_host}
header_up X-Forwarded-Proto https
}
}
Reload Caddy with systemctl reload caddy. Start your Plausible containers:
cd /opt/plausible
docker compose up -d
Step 5: Defeating Ad-Blockers with a Custom Proxy Script
Even though Plausible is 100% privacy-friendly and cookie-free, common ad-blockers block domain names containing the keyword plausible. To ensure accurate developer traffic telemetry, proxy the tracking script through your main application domain (e.g., via Cloudflare Workers or Next.js rewrites).
Next.js (App Router / Pages Router) Rewrite in next.config.js:
module.exports = {
async rewrites() {
return [
{
source: "/js/telemetry.js",
destination: "https://stats.yourdomain.com/js/script.js",
},
{
source: "/api/event",
destination: "https://stats.yourdomain.com/api/event",
},
];
},
};
In your HTML or React layout, embed the proxied script tag:
<script defer data-domain="yourdomain.com" src="/js/telemetry.js" data-api="/api/event"></script>
Because the script and POST endpoint share the first-party domain, ad-blockers treat the request as native application telemetry, restoring 99.8% tracking fidelity across technical audiences.
Data Retention Policies and ClickHouse TTL Optimization
When running Plausible Analytics on a VPS with modest NVMe storage (e.g. 40GB to 80GB), raw event tables can eventually accumulate tens of millions of historical rows. ClickHouse supports declarative Time-To-Live (TTL) policies that automatically discard granular event records after a predetermined duration while preserving aggregated monthly metrics:
-- Connect to ClickHouse client
docker exec -it plausible_events_db clickhouse-client
-- Apply 2-year retention policy to raw events table
ALTER TABLE plausible_events_db.events_v2
MODIFY TTL timestamp + INTERVAL 2 YEAR;
-- Optimize table partitions to reclaim disk space immediately
OPTIMIZE TABLE plausible_events_db.events_v2 FINAL;
Applying this retention policy guarantees that your ClickHouse datastore maintains bounded disk footprint indefinitely without requiring manual partition dropping.
Automated Nightly Backups to S3 with Rclone
To ensure resilience against catastrophic hardware failures, set up an automated nightly backup cron job that dumps the PostgreSQL relational database and copies the ClickHouse volume snapshots to Cloudflare R2 or Amazon S3:
#!/usr/bin/env bash
# /opt/plausible/backup.sh
set -euo pipefail
DATE=20261116_224851
BACKUP_DIR="/tmp/plausible_backups"
mkdir -p ""
# 1. Dump PostgreSQL database
docker exec -t plausible_db pg_dump -U plausible plausible_db | gzip > "/pg_.sql.gz"
# 2. Sync to offsite S3 bucket using rclone
rclone copy "" "remote_s3:company-infra-backups/plausible/" --progress
# 3. Cleanup local temp files older than 24 hours
find "" -type f -mtime +1 -delete
Cost Comparison: Self-Hosted vs Google Analytics vs Plausible Cloud
| Traffic Tier | Self-Hosted Plausible (Hetzner VPS) | Plausible Managed Cloud | Google Analytics 4 |
|---|---|---|---|
| 100k views/mo | $6 / month | $19 / month | "Free" (Costs privacy & page speed) |
| 1M views/mo | $6 / month | $69 / month | "Free" (Aggressive data sampling) |
| 5M views/mo | $14 / month (4 vCPU / 8GB) | $169 / month | Requires GA 360 ($50k+/year) |
Telemetry & Monitoring: Scraping ClickHouse Metrics with Prometheus
In high-traffic production environments, monitoring ClickHouse query latency, active part mergers, and memory saturation is critical. Plausible and ClickHouse can expose metrics directly to Prometheus:
# Add ClickHouse Prometheus metrics exporter endpoint in clickhouse-config.xml
# <prometheus>
# <endpoint>/metrics</endpoint>
# <port>9363</port>
# <metrics>true</metrics>
# <events>true</events>
# </prometheus>
By connecting a Grafana dashboard to Prometheus, infrastructure teams can set proactive alerts for slow queries, disk partition fill rates, and uncompressed block counts, ensuring zero surprise outages during viral traffic spikes.
Frequently Asked Questions (FAQ)
Do I need a cookie consent banner when self-hosting Plausible?
No. Plausible does not use cookies, does not store persistent identifiers across sessions, and does not track users across different websites. Under EU GDPR, ePrivacy Directive, and PECR regulations, anonymous first-party analytics that generate transient daily hashes do not require opt-in cookie consent banners.
How does ClickHouse handle database backups in Plausible?
You can execute ClickHouse backups using clickhouse-backup or by snapshotting the Docker volume directory /var/lib/docker/volumes/plausible_event-data using standard filesystem freeze or LVM/ZFS snapshots during off-peak hours.
Can I track custom events and revenue goals?
Yes. Plausible supports custom goal tracking (e.g., signup button clicks, checkout completions) using the JavaScript API: plausible('Signup', { props: { plan: 'pro', billing: 'annual' } });. These appear natively in your self-hosted dashboard.
How do I update the Plausible Docker image to new releases safely?
Pull the latest image with docker compose pull plausible and recreate the container with docker compose up -d plausible. The container's startup entrypoint automatically checks and runs any pending database migrations before launching the application.
Conclusion
Self-hosting Plausible Analytics delivers the best of both worlds: lightning-fast Core Web Vitals with sub-1KB scripts, complete GDPR legal compliance without annoying cookie consent popups, and total data sovereignty on your own $6/month cloud server.
Join the conversation