# Deploy and operate pgs3

> Run pgs3 persistently on PostgreSQL startup, build from source or Docker, terminate TLS in Nginx, route primary/standby traffic, and handle backups, monitoring, and upgrades.

---

LLMS index: [llms.txt](/llms.txt)

---

Each `pgs3` endpoint serves one PostgreSQL database on Linux and speaks plain HTTP on a local `SO_REUSEPORT` listener. Treat `pgs3` as a database-resident service: terminate TLS at a reverse proxy, budget background workers and WAL headroom, and recover objects with PostgreSQL physical backups.

For throughput benchmarks and workload boundaries, see [Performance and limits](/docs/pgs3/performance/).

## 1. Persistent automatic startup {#automatic}

<a id="preflight"></a>

While `SELECT pgs3.start()` is convenient for quick experiments, production instances should register the static launcher through `shared_preload_libraries` so the HTTP pool starts automatically with PostgreSQL.

1. Add `pgs3` to `postgresql.conf` (append to any existing preload entries):

   ```conf
   shared_preload_libraries = 'pgs3'
   pgs3.enabled = on
   pgs3.target_database = 'appdb'
   pgs3.listen_addr = '127.0.0.1'
   pgs3.port = 9000
   pgs3.workers = 4
   max_worker_processes = 16
   ```

2. Size `max_worker_processes` to cover the launcher (1), the GC worker (1), `pgs3.workers`, parallel query workers, and any other preloaded extensions.
3. Run `CREATE EXTENSION IF NOT EXISTS pgs3;` in `pgs3.target_database` (if provisioning in two stages, leave `pgs3.enabled = off` until the extension is created, then enable and restart).
4. Restart PostgreSQL and confirm the pool is running before opening traffic:

   ```sql
   SELECT worker_kind, desired, status, count(*)
   FROM pgs3.worker_state
   GROUP BY 1, 2, 3
   ORDER BY 1, 2, 3;
   ```
{.steps}

## 2. Terminate TLS in Nginx {#proxy}

`pgs3` does not terminate TLS. Bind `pgs3.listen_addr` to `127.0.0.1` and place Nginx in front of it.

Three proxy rules are essential for SigV4 verification:
- Forward the exact client `Host` header including any non-default port (`$http_host`).
- Omit any trailing path or slash on `proxy_pass` so Nginx preserves the raw signed URI verbatim.
- Disable request and response buffering so large streaming PUTs and Range GETs do not stall on proxy disk.

```nginx
upstream pgs3_backend {
    server 127.0.0.1:9000;
    keepalive 64;
}

server {
    listen 443 ssl;
    server_name s3.example.internal;

    ssl_certificate     /etc/nginx/tls/s3.crt;
    ssl_certificate_key /etc/nginx/tls/s3.key;

    # Cap upload size to match your tested memory and WAL budget
    client_max_body_size 100m;
    client_body_timeout 300s;

    location / {
        # No URI component on proxy_pass: preserves the signed raw path
        proxy_pass http://pgs3_backend;
        proxy_http_version 1.1;
        proxy_set_header Host $http_host;
        proxy_set_header Connection "";
        proxy_request_buffering off;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }
}
```

## 3. Primary and standby routing {#routing}

<a id="standby"></a>

- **Route all writes and read-after-write traffic to the primary**. A hot standby rejects write operations with `503 ServiceUnavailable`.
- **Standby reads are eventually consistent**: Streaming replication lag can return slightly older versions, and recovery conflicts may cancel long reads. Request metrics backed by writable tables are unavailable during recovery.
- **Health checks**: Probe `SELECT NOT pg_is_in_recovery()`, confirm desired HTTP workers are `running` in `pgs3.worker_state`, and run a lightweight signed read (such as `HeadBucket`).
- **Safe retries**: Before retrying an interrupted version-sensitive write, check whether it already committed or guard it with `If-None-Match: *` or `If-Match: "<etag>"`. Fence the old primary during failover before reopening writes.

## 4. Backup, PITR, and recovery {#backup}

Use PostgreSQL **physical base backups** (including all tablespaces) plus **WAL archiving / PITR** to recover relational tables, object payloads, versions, and credentials to one consistent point in time.

> [!CAUTION]
> SigV4 verification requires recoverable signing secrets stored in `pgs3.credential`. Always encrypt physical backups and WAL archives and restrict access to them. Logical `pg_dump` / `pg_restore` and logical replication are not supported recovery paths for `pgs3` object state.

Keep client traffic blocked after a restore until you complete this checklist:

1. Verify `pgs3.extension_version()` matches the installed shared library.
2. Check pending uploads and reference counts; sample inline and chunked objects to verify content hashes.
3. Run an end-to-end signed read/write smoke test and confirm cross-tenant isolation.
4. Disable or rotate any credentials that PITR resurrected from before an earlier revocation.
{.steps}

## 5. Monitor and troubleshoot {#monitor}

<a id="changes"></a>
<a id="incidents"></a>

Inspect live worker status and aggregated S3 request counters from SQL:

```sql
SELECT worker_kind, desired, status, count(*)
FROM pgs3.worker_state
GROUP BY 1, 2, 3;

TABLE pgs3.stats;
```

Track desired vs. running workers, error counts, latency buckets, in-flight requests, transferred bytes, pending upload age, and GC backlog (counters flush periodically). At the PostgreSQL layer, monitor dead tuples, `pgs3.chunk` partitions, TOAST bloat, checkpoints, WAL generation, and replication lag. Keep `autovacuum` active and run `ANALYZE` after bulk loads or large bucket forks.

> [!NOTE]
> `LISTEN pgs3` emits operation classes only (not full payloads or replayable streams). Consumers that need durable event replay should record events in a separate table or queue.

### Safe configuration changes

Change one GUC at a time, reload (`SELECT pg_reload_conf()`), and verify both `pgs3.worker_state` and a real signed request on the updated listener. A failed port bind can leave the previous listener active. Drain client traffic before calling `pgs3.stop()` or restarting PostgreSQL. See [Reload vs. restart](/docs/pgs3/reference/#reload).

### Common issues

| Symptom | What to check |
| --- | --- |
| TCP connects, but HTTP returns `403` / `500` | Check `pgs3.worker_state`, `pgs3.target_database`, and whether `pgs3.server_role` attributes or grants drifted (launcher stops HTTP listeners on drift). |
| `SignatureDoesNotMatch` behind Nginx | Confirm `Host` (with port), raw request URI (no URI suffix on `proxy_pass`), clock skew (≤ 15 min), path-style addressing, and `us-east-1` region. |
| Pending uploads stay in `pgs3.upload` | Check lease expiry (5 min) and pending retention (24 h), and verify the `gc` worker is `running` in `pgs3.worker_state`. |
| Writes return `503 ServiceUnavailable` | Traffic is hitting a read-only standby; route writes to the primary. |
| Requests return `503 SlowDown` | Queries hit `pgs3.statement_timeout_ms`; inspect lock contention or slow disk/WAL checkpoints. |

## 6. Upgrade and rollback {#upgrade}

Versions `0.1.0` and `0.1.1` support in-place SQL upgrades to `0.1.2`.

1. Take a verified physical backup and drain S3 traffic.
2. Install the updated `pgs3` package (matching the PostgreSQL major/minor) and restart PostgreSQL.
3. Update the extension catalog in each database using `pgs3`:

   ```sql
   ALTER EXTENSION pgs3 UPDATE TO '0.1.2';
   SELECT pgs3.extension_version();
   ```

4. Re-verify bucket listing, object reads/writes, and tenant isolation before reopening traffic. If rollback is needed, restore the physical backup from step 1.
{.steps}

## 7. Build from source or Docker {#source}

When packages are not available for your environment—or when testing locally in Docker—build directly from the release tag:

```bash
git clone --branch v0.1.2 --depth 1 https://github.com/pgsty/pgs3.git
cd pgs3
make image PG_MAJOR=17
```

This creates a local `pgs3-test:pg17` container image. Run a disposable instance exposing PostgreSQL on `55432` and the S3 endpoint on `9000`:

```bash
docker run -d --name pgs3-demo \
  -e POSTGRES_PASSWORD=postgres \
  -p 127.0.0.1:55432:5432 \
  -p 127.0.0.1:9000:9000 \
  pgs3-test:pg17 \
  postgres -c max_worker_processes=16 -c pgs3.listen_addr=0.0.0.0 -c pgs3.workers=2
```

For a native Linux build, install Rust ≥ 1.99.1, PostgreSQL server headers, and `cargo-pgrx` 0.20.1, then run `make package PG_MAJOR=17` and copy the staged shared library, control file, and SQL scripts into your PostgreSQL directories. Packages built against PG17.12 or PG18.7 headers require at least that server minor version.

---

Backlinks:

- [Getting started](/docs/pgs3/getting-started/)
