Skip to main content
This guide covers deploying SnackBase in development and production environments.

Prerequisites

Required Software

  • Python: 3.12 or higher
  • uv: Package manager (installation guide)
  • Database: SQLite (development) or PostgreSQL (production recommended)

Optional

  • Docker: For containerized deployment (coming soon)
  • Nginx: For reverse proxy in production
  • systemd: For service management on Linux

Development Deployment

Quick Start

1. Clone the repository:
2. Install dependencies:
3. Create environment file:
4. Start the development server:
5. Access the application:

Development Configuration

Create a .env file in the project root:

Development Server Options

Initialize Database

The database is automatically initialized on first run. To manually initialize:

Development Tools

Production Deployment

Deployment Checklist

  • Set strong SNACKBASE_SECRET_KEY, SNACKBASE_TOKEN_SECRET and SNACKBASE_ENCRYPTION_KEY
  • Use PostgreSQL database
  • Set SNACKBASE_ENVIRONMENT=production
  • Set SNACKBASE_DEBUG=false
  • Configure proper CORS origins
  • Set up reverse proxy (Nginx)
  • Enable HTTPS/TLS
  • Configure log aggregation
  • Set up monitoring and alerts
  • Configure automated backups
  • Test health check endpoints

Option 1: Direct Deployment (systemd)

1. Prepare the Server

2. Deploy Application

3. Production Environment Configuration

Generate a strong secret key:

4. Set Up PostgreSQL

5. Create systemd Service

Create /etc/systemd/system/snackbase.service:

6. Start and Enable Service

Option 2: Nginx Reverse Proxy

1. Install Nginx

2. Configure Nginx

Create /etc/nginx/sites-available/snackbase:

3. Enable Site and Restart Nginx

4. Set Up SSL with Let’s Encrypt

Option 3: Docker Deployment

You can deploy SnackBase using the included Dockerfile and docker-compose.yml (optional).

1. Build the Image

2. Run the Container

3. Access Application

The application will be available at http://localhost:8000.

Database Configuration

SQLite (Development Only)

Pros:
  • Zero configuration
  • Perfect for development
  • File-based, easy to backup
Cons:
  • Not suitable for production
  • Limited concurrency
  • No network access
Setup:
Connection Pooling: SnackBase uses SQLAlchemy’s async connection pooling. Configure in .env:

Environment Variables

Complete Reference

Health Checks

SnackBase provides three health check endpoints:

/health - Basic Health Check

Returns 200 if the service is running.
Response:

/ready - Readiness Check

Returns 200 if the service is ready to accept requests (includes database connectivity).
Response:

/live - Liveness Check

Returns 200 if the service is alive (simple ping).
Response:

Using Health Checks

systemd:
Kubernetes (future):

Troubleshooting

Service Won’t Start

Check logs:
Common issues:
  • Database connection failure
  • Port already in use
  • Missing environment variables
  • File permission issues

Database Connection Errors

PostgreSQL:
SQLite:

Permission Denied Errors

High Memory Usage

Reduce worker count:
Configure connection pool:

Slow API Responses

Check database:
Enable query logging:

CORS Errors

Update CORS origins:
Check Nginx configuration:

Monitoring and Maintenance

Log Management

View logs:
Log rotation (if using file-based logging): Create /etc/logrotate.d/snackbase:

Performance Monitoring

System resources:
Application metrics (future):
  • Prometheus integration
  • Grafana dashboards
  • Custom metrics endpoint

Backup Strategy

Database backup (PostgreSQL):
File storage backup:
Automated backup/restore commands will be added in Phase 5 (F5.10)

Security Best Practices

  1. Use strong secret keys: Generate with secrets.token_urlsafe(64)
  2. Enable HTTPS: Use Let’s Encrypt for free SSL certificates
  3. Restrict CORS: Only allow trusted domains
  4. Use PostgreSQL: SQLite is not suitable for production
  5. Regular updates: Keep dependencies up to date
  6. Monitor logs: Set up log aggregation and alerts
  7. Firewall: Only expose necessary ports (80, 443)
  8. Database security: Use strong passwords, restrict network access
  9. File permissions: Ensure proper ownership and permissions
  10. Rate limiting: On by default — see Rate Limiting below, and configure SNACKBASE_TRUSTED_PROXIES if you run behind a proxy

Rate Limiting

Rate limiting is on by default (SNACKBASE_RATE_LIMIT_ENABLED=true). Raise the limits rather than turning it off — it is the only bound on request-rate abuse on a publicly reachable instance. Only paths under /api/v1 are metered. The admin SPA, its JavaScript and CSS bundles, and the /health, /ready and /live probes are never rate limited, so a page load cannot rate-limit itself into a blank screen and a busy API cannot fail your uptime checks. Static assets ship with cache-control: max-age=14400 and are meant to be absorbed by a CDN or reverse proxy. Responses carry X-RateLimit-Limit (the per-minute rate), X-RateLimit-Burst (the computed capacity), X-RateLimit-Remaining and X-RateLimit-Reset. A rejected request returns 429 with Retry-After. The limiter is per-process and in-memory, so N replicas enforce N times the configured limit.

Login throttling

Password guessing is bounded separately and is not affected by the settings above: Keep SNACKBASE_LOGIN_RATE_LIMIT_PER_MINUTE below SNACKBASE_LOGIN_LOCKOUT_THRESHOLD. An attacker hammering one victim then exhausts their own address budget before the victim’s account locks, which keeps the lockout from becoming a denial-of-service primitive against arbitrary users.

Trusted proxies — configure this before you deploy behind anything

Both limits above are keyed on the client’s IP address. Behind a reverse proxy the socket peer is the proxy, so unless SnackBase is told which peers to believe, every visitor collapses into one rate-limit bucket and one login-failure budget. One attacker then locks out every user, and any user’s successful login refunds the attacker’s accumulated failures. SNACKBASE_TRUSTED_PROXIES names the peers whose forwarding headers may be believed. Each entry is one of:
  • a bare address — 127.0.0.1
  • a CIDR network — 10.0.0.0/8, fd00::/8
  • the literal * — trust whatever peer connects
From a trusted peer, CF-Connecting-IP is used first, then the rightmost entry of X-Forwarded-For, then the peer itself. From an untrusted peer both headers are ignored and a warning naming the peer is logged once per process. An unparseable entry fails at startup naming the entry.
Leaving SNACKBASE_TRUSTED_PROXIES at its loopback default behind a proxy collapses every visitor into one rate-limit bucket and one login-failure budget.
Behind Cloudflare, with your own Nginx or Traefik terminating TLS on the same host:
If the proxy runs on another host in a private network, name that network instead:
On a managed platform — Railway, Fly, Render — the edge peer address is neither stable nor published, so no address or range is correct:
* is safe there only because the container is reachable solely through the platform’s edge. Never use * on an instance clients can connect to without passing your proxy: any client could then forge X-Forwarded-For, mint an unlimited number of rate-limit buckets, and escape the login throttle entirely.

Security Headers

SnackBase automatically sets security headers on all HTTP responses to protect against common web vulnerabilities:
  • X-Content-Type-Options: Prevents MIME type sniffing
  • X-Frame-Options: Prevents clickjacking attacks
  • X-XSS-Protection: Enables browser XSS protection
  • Strict-Transport-Security (production only): Enforces HTTPS
  • Content-Security-Policy: Prevents XSS and injection attacks
  • Permissions-Policy: Restricts browser features
  • Referrer-Policy: Controls referrer information

Customizing Security Headers

You can customize security headers via environment variables:
Note: The default CSP policy is designed to work with the SnackBase Admin UI, which loads every asset from its own origin. FastAPI’s interactive API docs (/docs and /redoc, served in development only) are the one exception: they load Swagger UI and ReDoc from cdn.jsdelivr.net, so SnackBase adds those origins to the docs responses only. Every other response keeps the configured policy, and you do not need to loosen it to use the API docs. If you’re using a custom frontend with external CDNs or inline scripts, you may need to adjust the CSP policy.

Troubleshooting CSP Issues

If your frontend is blocked by CSP:
  1. Check browser console: Look for CSP violation errors
  2. Identify blocked resources: Note the source and type (script, style, image, etc.)
  3. Update CSP policy: Add the necessary sources to the appropriate directive
  4. Test thoroughly: Ensure all functionality works after CSP changes
Example CSP for frontend with external CDN:

Single-Tenant Mode

SnackBase supports a “Single-Tenant Mode” where the entire instance behaves as a dedicated application for a single account.

How it works

When enabled:
  1. All new users automatically join the specified SNACKBASE_SINGLE_TENANT_ACCOUNT.
  2. Login and Registration endpoints no longer require an account identifier (though it’s still accepted).
  3. The first user to register becomes the admin of that account.

Configuration

Authentication Flow

In single-tenant mode, the account is resolved server-side:

Next Steps

After deployment:
  1. Create first account: Use the /api/v1/auth/register endpoint
  2. Test API: Use Swagger UI at /docs
  3. Create collections: Use the /api/v1/collections endpoint
  4. Set up monitoring: Configure log aggregation and alerts
  5. Configure backups: Set up automated database backups
  6. Review security: Follow security best practices checklist