Skip to content

This is the multi-page printable view of this section.

Return to the regular view of this page

pgs3

Turn PostgreSQL into a versioned S3 object endpoint backed by ordinary database tables. Use it when application rows and tenant objects belong in the same transaction, backup, and point-in-time recovery window.

pgs3 embeds an S3-compatible HTTP server directly inside PostgreSQL background workers. S3 clients (mc, rclone, boto3, DuckDB, s3fs) talk to the endpoint over SigV4 path-style HTTP, while SQL sessions read and write the exact same buckets and objects inside normal database transactions.

Note

pgs3 is currently in early alpha (v0.1.2, release acceptance on PostgreSQL 17–19 on Linux). Small-object throughput targets and the 100,000-object bucket fork target are still being optimized. Review the measured performance and limits before sizing production workloads.

Why store objects in PostgreSQL

Running a separate object store alongside PostgreSQL splits state across two systems: a database rollback can leave orphan blobs behind, backups capture two different timestamps, and tenant isolation has to be maintained twice. pgs3 collapses those boundaries into one PostgreSQL database:

  • One transaction boundary: Write application metadata and object bytes in the same SQL transaction—commit together or roll back together.
  • One backup and PITR timeline: Physical base backups and WAL archiving recover relational tables, object payloads, versions, and credentials to the same point in time.
  • Database-native multi-tenancy: Every S3 access key maps to a PostgreSQL NOLOGIN role. Bucket and object visibility is enforced by PostgreSQL Row-Level Security (RLS).
  • Always-on versioning and instant forks: Overwrites append new versions, ordinary deletes insert delete markers, and pgs3.fork_bucket() clones a bucket’s latest state by sharing content-addressed SHA-256 blobs.

When to use pgs3 (and when not to)

WorkloadRecommendationWhy
Application attachments, invoices, configs, or AI agent artifacts that must stay consistent with relational rowsUse pgs3Shared transactions, unified PITR, and zero extra storage cluster to operate
Multi-tenant SaaS workspaces or experiment checkpoints needing cheap bucket forksUse pgs3RLS tenant isolation and copy-on-write pgs3.fork_bucket()
Multi-terabyte media archives, high-fanout public CDN origins, or workloads requiring bucket policies/ACLs/lifecycle rulesUse a dedicated S3 store such as SiloDedicated object stores avoid PostgreSQL WAL amplification, TOAST overhead, and full-GET buffering

How pgs3 works

flowchart LR
    C["S3 Client (mc / rclone / SDK)"] -->|SigV4 Path-Style HTTP| W["pgs3 HTTP Workers"]
    W -->|"SET LOCAL ROLE (RLS)"| SQL["pgs3 SQL API"]
    APP["SQL Session / App"] -->|Direct Transaction| SQL
    SQL --> META["pgs3.bucket & pgs3.object"]
    SQL --> BLOB["pgs3.blob (SHA-256 Dedup)"]
    BLOB -->|"<= 64 KiB"| INLINE["Inline bytea"]
    BLOB -->|"> 64 KiB"| CHUNK["Chunked / Multipart Extents"]
  1. HTTP workers handle the wire protocol: Background workers listen on a shared SO_REUSEPORT TCP port (default 127.0.0.1:9000), verify AWS SigV4 signatures, and map each access key to its PostgreSQL tenant role.
  2. SQL enforces all semantics: Inside short transactions, workers run SET LOCAL ROLE and invoke the same pgs3.* SQL functions that direct SQL callers use. Versioning, preconditions, locking, and RLS isolation live in one place.
  3. Blobs are deduplicated by SHA-256: Every object version points to a canonical content-addressed blob. Small payloads stay inline (pgs3.inline_threshold, default 64 KiB); larger uploads stream into 4 MiB chunks (pgs3.chunk_size) without holding long database transactions.

1 - Getting started with pgs3

Install pgs3, launch a local S3 endpoint inside PostgreSQL, and walk through uploading, overwriting, deleting, and recovering an earlier version with mc (MinIO Client) in three minutes.

1. Install pgs3

Install the pgs3 package on a Linux PostgreSQL 17–19 server (PG16 is best effort; see Downloads for platform availability):

pig repo add pgsql -u
pig ext add pgs3

Need to build from source or spin up a test container instead? See Build from source or Docker.

2. Enable the extension and start the endpoint

Connect to your database as an administrator, create an unprivileged tenant role with an S3 key pair, and start the HTTP worker pool:

CREATE EXTENSION IF NOT EXISTS pgs3;

CREATE ROLE pgs3_demo NOLOGIN NOINHERIT
    NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;

SELECT pgs3.create_credential('PGS3DEMOKEY01', 'change-me-in-production-secret', 'pgs3_demo');
SELECT pgs3.start();

Confirm that the HTTP workers are listening on 127.0.0.1:9000:

SELECT worker_kind, status, listen_addr, port
FROM pgs3.worker_state
ORDER BY worker_kind;
 worker_kind | status  | listen_addr | port
-------------+---------+-------------+------
 gc          | running |             |
 http        | running | 127.0.0.1   | 9000
 http        | running | 127.0.0.1   | 9000
 launcher    | running |             |

pgs3.start() starts a dynamic pool for the current database without editing postgresql.conf. For persistent endpoints that boot with PostgreSQL, see Automatic startup.

3. Upload, version, and recover with mc

Using the MinIO Client (mc, packaged as mcli on some Linux distributions), register the local endpoint with SigV4 and path-style addressing (--path on):

  1. Add the alias and create a bucket:

    mc alias set pgs3 http://127.0.0.1:9000 PGS3DEMOKEY01 change-me-in-production-secret --api S3v4 --path on
    mc mb pgs3/demo
  2. Upload a file and read it back:

    printf 'v1: hello pgs3\n' > hello.txt
    mc cp hello.txt pgs3/demo/notes/hello.txt
    mc cat pgs3/demo/notes/hello.txt
    v1: hello pgs3
  3. Overwrite the object and delete it—pgs3 keeps versioning permanently enabled, so an ordinary delete writes a delete marker instead of losing history:

    printf 'v2: updated\n' > hello.txt
    mc cp hello.txt pgs3/demo/notes/hello.txt
    mc rm pgs3/demo/notes/hello.txt
    mc ls --versions pgs3/demo/notes/hello.txt
    [2026-12-01 04:01:12 UTC]     0B 3 DEL v3 notes/hello.txt
    [2026-12-01 04:01:08 UTC]    12B 2 PUT v2 notes/hello.txt
    [2026-12-01 04:01:02 UTC]    15B 1 PUT v1 notes/hello.txt
  4. Recover the first revision by its version ID (1):

    mc cat --version-id 1 pgs3/demo/notes/hello.txt
    v1: hello pgs3

4. Clean up

When you are done testing, stop the worker pool and remove the local alias:

psql -c 'SELECT pgs3.stop()'
mc alias rm pgs3
rm -f hello.txt

Next steps

2 - Connect S3 clients

Configure mc, rclone, Python boto3, DuckDB httpfs, and s3fs to talk to pgs3. Every client needs three settings: SigV4 signing, path-style addressing, and an explicit endpoint URL.

Any S3 client that speaks AWS Signature Version 4 and path-style URLs (http://host:9000/bucket/key) works against pgs3. Because pgs3 does not implement virtual-host routing (http://bucket.host:9000/key), always disable virtual-host addressing in your client configuration.

All examples below reuse the shell variables from Getting started (or your production HTTPS proxy URL and tenant credentials):

export PGS3_ENDPOINT=http://127.0.0.1:9000
export PGS3_ACCESS_KEY=PGS3DEMOACCESS01
export PGS3_SECRET_KEY='<your-secret-key>'
export PGS3_BUCKET=my-artifacts

mc (MinIO Client)

mc (packaged as mcli on some Linux distributions) is the fastest day-to-day CLI for buckets, objects, directory mirrors, version history, and presigned download links.

Configure an alias

Pass --api S3v4 --path on so mc always signs with SigV4 and sends path-style requests:

mc alias set pgs3 "$PGS3_ENDPOINT" "$PGS3_ACCESS_KEY" "$PGS3_SECRET_KEY" --api S3v4 --path on
mc ls pgs3

Everyday object operations

# Create a bucket and upload with Content-Type and custom metadata
mc mb "pgs3/$PGS3_BUCKET"
printf 'hello pgs3\n' > hello.txt
mc cp --attr "Content-Type=text/plain;owner=docs" hello.txt "pgs3/$PGS3_BUCKET/notes/hello.txt"

# Inspect metadata, read content, and list a prefix
mc stat "pgs3/$PGS3_BUCKET/notes/hello.txt"
mc cat  "pgs3/$PGS3_BUCKET/notes/hello.txt"
mc ls   "pgs3/$PGS3_BUCKET/notes/"

# Server-side copy (reuses the underlying SHA-256 blob without re-uploading)
mc cp "pgs3/$PGS3_BUCKET/notes/hello.txt" "pgs3/$PGS3_BUCKET/archive/hello.txt"

# Mirror a local directory into a dedicated prefix
mc mirror ./reports "pgs3/$PGS3_BUCKET/reports"

Work with object versions

pgs3 keeps versioning permanently enabled on every bucket:

# List every revision and delete marker for a key
mc ls --versions "pgs3/$PGS3_BUCKET/notes/hello.txt"

# Read or download a specific historical version
mc cat --version-id 1 "pgs3/$PGS3_BUCKET/notes/hello.txt"
mc cp  --version-id 1 "pgs3/$PGS3_BUCKET/notes/hello.txt" ./hello-v1.txt

# Ordinary delete (writes a delete marker; earlier versions remain intact)
mc rm "pgs3/$PGS3_BUCKET/notes/hello.txt"

# Permanent delete of a single version
mc rm --version-id 1 "pgs3/$PGS3_BUCKET/notes/hello.txt"

Generate a temporary download URL

mc share download signs a presigned GET URL locally without calling any extra API:

mc share download --expire=10m "pgs3/$PGS3_BUCKET/archive/hello.txt"
Note

MinIO-specific and unsupported S3 subcommands (mc admin, mc anonymous, mc ilm, mc retention, mc tag) are outside the pgs3 API subset and return 501 NotImplemented.

rclone

rclone is part of the pgs3 release acceptance matrix and works well for automated sync jobs, integrity verification, and large multipart transfers.

Configuration file

Add a remote to ~/.config/rclone/rclone.conf:

[pgs3]
type = s3
provider = Other
endpoint = http://127.0.0.1:9000
region = us-east-1
force_path_style = true
access_key_id = PGS3DEMOACCESS01
secret_access_key = <your-secret-key>

To avoid storing secrets in a config file, replace access_key_id and secret_access_key with env_auth = true and export AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY, or configure the remote purely with environment variables (RCLONE_CONFIG_PGS3_TYPE=s3, RCLONE_CONFIG_PGS3_PROVIDER=Other, RCLONE_CONFIG_PGS3_ENDPOINT, RCLONE_CONFIG_PGS3_FORCE_PATH_STYLE=true, RCLONE_CONFIG_PGS3_REGION=us-east-1, plus access/secret keys).

Sync, verify, and restore

# Create a bucket (idempotent if you already own it)
rclone mkdir "pgs3:$PGS3_BUCKET"

# Mirror a local folder into a dedicated prefix
rclone sync ./reports "pgs3:$PGS3_BUCKET/reports" --checkers 4 --transfers 4

# Verify byte-for-byte integrity by downloading and comparing hashes
rclone check --download ./reports "pgs3:$PGS3_BUCKET/reports"

# Download back to a local directory
rclone copy "pgs3:$PGS3_BUCKET/reports" ./reports-restored
Warning

Only run rclone sync against a dedicated destination prefix. Any object under that destination prefix that does not exist in the local source directory receives a delete marker.

Python (boto3)

Set signature_version="s3v4" and addressing_style="path" in botocore.config.Config. Large files automatically use multipart upload (every non-final part must be at least 5 MiB).

Upload, conditional writes, and download

import os
import boto3
from botocore.config import Config

s3 = boto3.client(
    "s3",
    endpoint_url=os.environ["PGS3_ENDPOINT"],
    aws_access_key_id=os.environ["PGS3_ACCESS_KEY"],
    aws_secret_access_key=os.environ["PGS3_SECRET_KEY"],
    region_name="us-east-1",
    config=Config(
        signature_version="s3v4",
        s3={"addressing_style": "path"},
        retries={"max_attempts": 3},
        request_checksum_calculation="when_supported",
        response_checksum_validation="when_supported",
    ),
)

bucket = os.environ["PGS3_BUCKET"]

# Create only if the key does not exist yet (returns 412 PreconditionFailed otherwise)
put_res = s3.put_object(
    Bucket=bucket,
    Key="python/config.json",
    Body=b'{"mode":"v1"}\n',
    ContentType="application/json",
    Metadata={"service": "worker"},
    IfNoneMatch="*",
)
etag = put_res["ETag"]

# Compare-and-swap update guarded by the current ETag
s3.put_object(
    Bucket=bucket,
    Key="python/config.json",
    Body=b'{"mode":"v2"}\n',
    ContentType="application/json",
    IfMatch=etag,
)

# Read back the latest revision
obj = s3.get_object(Bucket=bucket, Key="python/config.json")
assert obj["Body"].read() == b'{"mode":"v2"}\n'

Presigned GET and PUT URLs

Presigned URLs delegate temporary read or write access to browsers or untrusted workers without sharing the tenant secret. They enforce the exact HTTP method, path, query string, expiry, and the underlying PostgreSQL role’s RLS visibility.

import urllib.request

put_url = s3.generate_presigned_url(
    "put_object",
    Params={"Bucket": bucket, "Key": "python/upload.txt"},
    ExpiresIn=300,
)
get_url = s3.generate_presigned_url(
    "get_object",
    Params={"Bucket": bucket, "Key": "python/upload.txt"},
    ExpiresIn=300,
)

req = urllib.request.Request(put_url, data=b"uploaded via presigned PUT\n", method="PUT")
with urllib.request.urlopen(req) as resp:
    assert resp.status == 200

with urllib.request.urlopen(get_url) as resp:
    assert resp.read() == b"uploaded via presigned PUT\n"

Always distribute presigned URLs over HTTPS through a TLS-terminating proxy in production.

DuckDB (httpfs)

DuckDB can query Parquet, CSV, or JSON files stored inside pgs3 over range-capable HTTP GET requests.

  1. Generate a Parquet file and upload it with mc:

    duckdb -c "COPY (SELECT i AS id, 'row-' || i AS label FROM range(100) t(i)) TO 'sample.parquet' (FORMAT PARQUET)"
    mc cp sample.parquet "pgs3/$PGS3_BUCKET/analytics/sample.parquet"
  2. Query it directly from DuckDB (ENDPOINT expects host:port without a scheme; set USE_SSL true behind a TLS proxy):

    INSTALL httpfs;
    LOAD httpfs;
    
    CREATE SECRET pgs3_local (
        TYPE s3,
        KEY_ID 'PGS3DEMOACCESS01',
        SECRET '<your-secret-key>',
        REGION 'us-east-1',
        ENDPOINT '127.0.0.1:9000',
        URL_STYLE 'path',
        USE_SSL false
    );
    
    SELECT count(*), min(id), max(id)
    FROM read_parquet('s3://my-artifacts/analytics/sample.parquet');
    ┌──────────────┬─────────┬─────────┐
    │ count_star() │ min(id) │ max(id) │
    │    int64     │  int64  │  int64  │
    ├──────────────┼─────────┼─────────┤
    │          100 │       0 │      99 │
    └──────────────┴─────────┴─────────┘

s3fs (Linux FUSE mount)

On Linux hosts with /dev/fuse and fusermount3, you can mount a pgs3 bucket as a local directory for legacy tools that only read and write filesystem paths:

umask 077
printf '%s:%s\n' "$PGS3_ACCESS_KEY" "$PGS3_SECRET_KEY" > /tmp/pgs3.passwd
mkdir -p /tmp/pgs3-mnt

s3fs "$PGS3_BUCKET" /tmp/pgs3-mnt \
  -o passwd_file=/tmp/pgs3.passwd \
  -o "url=$PGS3_ENDPOINT" \
  -o use_path_request_style

ls -la /tmp/pgs3-mnt
fusermount3 -u /tmp/pgs3-mnt
rm -f /tmp/pgs3.passwd

s3fs translates renames and in-place edits into multiple S3 API calls and does not provide POSIX file locking or atomic directory moves. Do not place databases, Git repositories, or lock-sensitive workloads on an s3fs mount.

3 - SQL workflows, versioning, and multi-tenancy

Go beyond standard S3 with PostgreSQL-native workflows: commit objects in the same transaction as relational rows, restore historical versions, fork whole buckets without copying bytes, and isolate tenants with RLS.

HTTP clients see pgs3 as an S3 endpoint, but inside PostgreSQL the exact same buckets and objects are accessible through SQL functions. That unlocks capabilities a standalone object store cannot offer: atomic cross-table transactions, zero-byte bucket forks, one-call version promotion, and PostgreSQL Row-Level Security (RLS).

How storage and deduplication work

Understanding three storage details explains why pgs3 operations behave the way they do:

  • Content-addressed blobs (pgs3.blob): Every non-delete object version references a physical blob keyed by its SHA-256 digest. Uploading the same bytes twice—or copying, restoring, or forking objects—increments a reference count instead of duplicating payload bytes.
  • Inline vs. chunked layout: Blobs up to pgs3.inline_threshold (default 64 KiB) store one inline copy in pgs3.blob. Larger blobs are split into 4 MiB chunks (pgs3.chunk_size) across hash-partitioned pgs3.chunk tables; completed multipart uploads stitch ordered pgs3.blob_extent references together without rewriting the uploaded parts.
  • Short-transaction concurrency: Same-key writes acquire a key-level lock so precondition checks (If-None-Match, If-Match) and version publication are serialized atomically. Streaming uploads commit each chunk in its own short transaction and stay invisible until the final commit publishes the object version.

For full schema diagrams and design rationale, see design.md, schema.md, and decisions.md.

1. Commit business rows and objects atomically

A classic failure mode with external object stores is writing a file to S3 and then failing to insert the matching database row (or rolling back the database row while leaving an orphan object behind). With pgs3, both live inside one PostgreSQL transaction.

Assume tenant_app is an unprivileged tenant role created as shown in Manage tenants and credentials:

CREATE TABLE app_reports (
    report_id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title       text NOT NULL,
    bucket_name text NOT NULL,
    object_key  text NOT NULL,
    version_id  bigint NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now()
);
GRANT INSERT, SELECT ON app_reports TO tenant_app;

BEGIN;
SET LOCAL ROLE tenant_app;

SELECT pgs3.create_bucket('reports');

WITH uploaded AS (
    SELECT *
    FROM pgs3.put(
        'reports',
        '2026/q4-summary.json',
        convert_to('{"revenue":1280000,"currency":"USD"}', 'UTF8'),
        'application/json',
        '{"author":"billing"}'::jsonb
    )
)
INSERT INTO app_reports (title, bucket_name, object_key, version_id)
SELECT 'Q4 Summary', 'reports', u.key, u.version_id
FROM uploaded AS u
RETURNING report_id, bucket_name, object_key, version_id;

COMMIT;
 report_id | bucket_name |      object_key      | version_id
-----------+-------------+----------------------+------------
         1 | reports     | 2026/q4-summary.json |          1

If anything in the transaction fails before COMMIT, both the app_reports row and the pgs3 object disappear together. Once committed, any S3 client authenticated as tenant_app can immediately download reports/2026/q4-summary.json.

2. Version history and instant rollback

Every overwrite in pgs3 creates a new monotonically ordered version_id, and every ordinary delete inserts a delete marker. Calling pgs3.restore() promotes a chosen historical version back to the latest state by appending a new version row that points to the original SHA-256 blob—history is never rewritten.

BEGIN;
SET LOCAL ROLE tenant_app;

-- Write v1 and capture its version_id in psql
SELECT (pgs3.put('reports', 'prompts/system.txt', convert_to('v1: strict mode', 'UTF8'))).version_id
    AS v1_id \gset

-- Overwrite with a buggy v2
SELECT (pgs3.put('reports', 'prompts/system.txt', convert_to('v2: broken prompt', 'UTF8'))).version_id;

-- Promote v1 back to latest (creates v3 pointing to v1's blob)
SELECT version_id, size, etag
FROM pgs3.restore('reports', 'prompts/system.txt', :v1_id);

-- Verify the latest content is back to v1
SELECT convert_from((pgs3.get('reports', 'prompts/system.txt')).body, 'UTF8') AS current_body;

COMMIT;
 current_body
-----------------
 v1: strict mode

You can also pass p_if_match => '<current-etag>' to pgs3.restore() to abort the rollback if another writer updated the key in the meantime. Over HTTP, pgs3 exposes the same operation via its extension route POST /{bucket}/{key}?restore&versionId={id}.

3. Fork a bucket without copying payload bytes

pgs3.fork_bucket() creates a brand-new bucket populated with the latest object versions (and delete markers) of a source bucket. Underlying SHA-256 blobs are shared via reference counting; only metadata rows and reference counts are written. Subsequent writes to either bucket are completely independent.

This is especially useful for AI agent experiment branches, pre-release staging checkpoints, or reproducible evaluation snapshots:

BEGIN;
SET LOCAL ROLE tenant_app;

-- Fork the latest state of 'reports' into a new experiment bucket
SELECT pgs3.fork_bucket('reports', 'reports-exp-42') AS copied_entries;

-- Mutate the forked bucket freely
SELECT pgs3.put('reports-exp-42', 'prompts/system.txt', convert_to('experiment prompt', 'UTF8'));

-- Confirm the source bucket is untouched
SELECT 'source' AS side, convert_from((pgs3.get('reports', 'prompts/system.txt')).body, 'UTF8') AS body
UNION ALL
SELECT 'fork',   convert_from((pgs3.get('reports-exp-42', 'prompts/system.txt')).body, 'UTF8');

COMMIT;
  side  |       body
--------+-------------------
 source | v1: strict mode
 fork   | experiment prompt

Keep two constraints in mind:

  • The destination bucket must not already exist.
  • Forking shares physical bytes, so disk growth for large blobs is minimal, but it still inserts metadata rows, updates indexes, and generates WAL proportional to the number of latest entries in the source bucket.

4. Multi-tenancy and credential lifecycle

How tenant isolation works

pgs3 separates the runtime service identity from tenant identities:

  1. Service role (pgs3.server_role, default pgs3_server): Created automatically when the extension is installed. HTTP workers connect as this restricted NOLOGIN NOINHERIT role only to look up credentials and switch roles.
  2. Tenant roles: Ordinary, unprivileged NOLOGIN NOINHERIT roles that you create (one per customer, team, or agent workspace). When you bind a credential with pgs3.create_credential(), pgs3 grants pgs3_server SET-only membership in that tenant role.
  3. Per-request RLS: After verifying a request’s SigV4 signature, the HTTP worker executes SET LOCAL ROLE <tenant> inside the request transaction. Row-Level Security policies ensure each tenant only sees and modifies buckets owned by roles it has USAGE membership in.
Caution

Never bind a SUPERUSER, BYPASSRLS, CREATEROLE, CREATEDB, or REPLICATION role to an S3 credential—pgs3.create_credential() rejects elevated roles by design.

Provision two isolated tenants

Run credential administration as a database operator (credential functions are revoked from PUBLIC):

-- Create two isolated, unprivileged tenant roles
CREATE ROLE tenant_alice NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;
CREATE ROLE tenant_bob   NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;

-- Bind distinct access keys (generate secrets externally with openssl rand -hex 32)
SELECT pgs3.create_credential('AKIAALICE0000001', '<alice-secret>', 'tenant_alice');
SELECT pgs3.create_credential('AKIABOB000000001', '<bob-secret>',   'tenant_bob');

Verify isolation in SQL—tenant_bob cannot see or read tenant_alice’s bucket:

BEGIN;
SET LOCAL ROLE tenant_alice;
SELECT pgs3.create_bucket('alice-private');
SELECT pgs3.put('alice-private', 'secret.txt', convert_to('for alice only', 'UTF8'));
COMMIT;

BEGIN;
SET LOCAL ROLE tenant_bob;
SELECT * FROM pgs3.list_buckets();  -- returns 0 rows
COMMIT;

Rotate, suspend, and audit credentials

Issue separate access keys per client or service so you can rotate or revoke one without disrupting others:

-- Rotate the signing secret in place (run over a protected TLS/local session)
SELECT pgs3.rotate_credential('AKIAALICE0000001', '<new-alice-secret>');

-- Temporarily suspend a compromised key (immediately blocks new S3 requests)
SELECT pgs3.set_credential_enabled('AKIAALICE0000001', false);

-- Reassign a key to another unprivileged tenant role
SELECT pgs3.set_credential_role('AKIAALICE0000001', 'tenant_alice_v2');

-- Permanently remove an unused key
SELECT pgs3.delete_credential('AKIAALICE0000001');

-- Audit non-secret credential columns
SELECT access_key, role_name, enabled, created_at
FROM pgs3.credential
ORDER BY access_key;

Tenant SQL functions default to EXECUTE for PUBLIC, which allows any database role with CONNECT to create its own buckets while keeping other tenants’ buckets hidden via RLS. If bucket creation must be allowlisted, revoke EXECUTE on pgs3.create_bucket(text, jsonb) from PUBLIC and grant it only to approved roles. Never grant tenants SELECT on pgs3.credential.

For the full list of SQL signatures, see the SQL reference.

4 - 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.

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.

1. Persistent automatic startup

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):

    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:

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

2. Terminate TLS in Nginx

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.
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

  • 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

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.

5. Monitor and troubleshoot

Inspect live worker status and aggregated S3 request counters from 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.

Common issues

SymptomWhat to check
TCP connects, but HTTP returns 403 / 500Check pgs3.worker_state, pgs3.target_database, and whether pgs3.server_role attributes or grants drifted (launcher stops HTTP listeners on drift).
SignatureDoesNotMatch behind NginxConfirm 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.uploadCheck lease expiry (5 min) and pending retention (24 h), and verify the gc worker is running in pgs3.worker_state.
Writes return 503 ServiceUnavailableTraffic is hitting a read-only standby; route writes to the primary.
Requests return 503 SlowDownQueries hit pgs3.statement_timeout_ms; inspect lock contention or slow disk/WAL checkpoints.

6. Upgrade and rollback

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:

    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.

7. Build from source or Docker

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

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:

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.

5 - Performance and limits

Measured PUT/GET throughput and latency curves comparing pgs3 v0.1.2 against MinIO on the same host, scale benchmarks for LIST and bucket forks, and hard workload boundaries.

All figures below come from the v0.1.2 release acceptance sweep on Apple M5 Max (Docker Desktop arm64, 16 vCPU, PostgreSQL 17.10, 16 pgs3 HTTP workers, shared_buffers = 1GB, fsync = on, synchronous_commit = on, default 4 MiB chunks) compared against single-disk MinIO (RELEASE.2026-08-04) on the same machine, with zero request or integrity errors across all 11 tested sizes.

Full raw curves and environment details: perf.md · acceptance.md.

1. PUT throughput: pgs3 vs. MinIO

Objects up to 64 KiB take the single-transaction direct-PUT path; larger objects stream into 4 MiB chunks.

backgroundColor: transparent
tooltip:
  trigger: axis
  axisPointer:
    type: shadow
legend:
  top: 6
grid:
  left: 16
  right: 20
  top: 48
  bottom: 16
  containLabel: true
xAxis:
  type: category
  data: ["4 KiB", "16 KiB", "64 KiB", "256 KiB", "1 MiB", "4 MiB", "8 MiB", "16 MiB", "64 MiB"]
yAxis:
  type: value
  name: "MiB/s"
series:
  - name: "pgs3"
    type: bar
    barMaxWidth: 26
    itemStyle:
      color: "#3b82f6"
      borderRadius: [4, 4, 0, 0]
    data: [6.1, 38.2, 227.9, 258.4, 284.4, 258.4, 167.9, 170.3, 156.6]
  - name: "MinIO"
    type: bar
    barMaxWidth: 26
    itemStyle:
      color: "#94a3b8"
      borderRadius: [4, 4, 0, 0]
    data: [6.5, 26.6, 105.8, 415.4, 1054.9, 705.2, 393.3, 441.6, 324.0]

2. GET throughput: pgs3 vs. MinIO

pgs3 is strongest on small-to-medium payloads (4 KiB – 4 MiB), peaking at 1.80 GiB/s on 1 MiB reads. Above 8 MiB, full-object GET currently materializes a SQL bytea and a Rust buffer before sending, which caps throughput on very large single-shot reads.

backgroundColor: transparent
tooltip:
  trigger: axis
  axisPointer:
    type: shadow
legend:
  top: 6
grid:
  left: 16
  right: 20
  top: 48
  bottom: 16
  containLabel: true
xAxis:
  type: category
  data: ["4 KiB", "16 KiB", "64 KiB", "256 KiB", "1 MiB", "4 MiB", "8 MiB", "16 MiB", "64 MiB"]
yAxis:
  type: value
  name: "MiB/s"
series:
  - name: "pgs3"
    type: bar
    barMaxWidth: 26
    itemStyle:
      color: "#10b981"
      borderRadius: [4, 4, 0, 0]
    data: [15.9, 62.3, 384.7, 1257.4, 1802.9, 1476.4, 793.2, 506.3, 133.6]
  - name: "MinIO"
    type: bar
    barMaxWidth: 26
    itemStyle:
      color: "#94a3b8"
      borderRadius: [4, 4, 0, 0]
    data: [16.2, 40.3, 286.0, 1375.5, 2927.4, 4373.4, 4271.4, 3071.9, 1008.4]

3. Latency and IOPS summary

Object sizePUT p50PUT ops/sPUT MiB/sGET p50GET ops/sGET MiB/s
4 KiB5.78 ms1,5566.12.86 ms4,06515.9
16 KiB4.66 ms2,44438.23.34 ms3,99062.3
64 KiB2.73 ms3,646227.92.15 ms6,155384.7
256 KiB8.56 ms1,034258.42.81 ms5,0301,257.4
1 MiB31.89 ms284284.45.32 ms1,8031,802.9
8 MiB47.40 ms21167.939.47 ms99793.2
64 MiB395.76 ms2.4156.6444.68 ms2.1133.6

Notice the direct-PUT boundary at 64 KiB: 64 KiB completes in 2.73 ms p50, whereas 65,537 bytes crosses into the staged upload path at 8.16 ms p50.

4. Scale tests and release acceptance gates

CheckTargetMeasuredStatus
8 MiB PUT throughput (1 connection)≥ 150 MiB/s167.9 MiB/sPass
1,000,000-key SQL LIST (flat)< 5 ms2.36 msPass
1,000,000-key SQL LIST (/ delimiter)< 10 ms9.49 msPass
Small-object GET (p50 / ops/s)< 0.5 ms / ≥ 30,000/s3.34 ms / 3,990/sBelow target
Small-object PUT throughput≥ 5,000/s1,556/sBelow target
100,000-object fork_bucket< 1,000 ms1,944 ms (154 MiB WAL)Below target

Always re-benchmark your own object-size distribution, concurrency, and disk durability settings on target hardware before capacity planning.

5. Known limits and boundaries

  • Memory budgeting on full GET: A non-ranged GetObject materializes a SQL bytea and a Rust buffer before streaming out. Use Range GET for partial reads, and enforce a conservative upload cap (client_max_body_size) in your reverse proxy rather than relying on the 5 GiB protocol parser ceiling.
  • Key and chunk limits: Object keys hold up to 1,024 UTF-8 bytes and cannot contain NUL. Each signed aws-chunked chunk is capped at 1 MiB.
  • Single-database Linux listener: One pgs3 worker pool serves one PostgreSQL database on Linux (SO_REUSEPORT). HTTP/1.1 keep-alive connections process requests sequentially per connection.
  • Non-snapshot LIST pagination: Continuation tokens walk indexed key order without holding a cross-page snapshot across concurrent writes.
  • Shared cluster resources: HTTP workers, TOAST storage, and blob writes share CPU, RAM, I/O, and WAL bandwidth with relational queries on the same instance.
  • API subset: Bucket policies, ACLs, CORS, object tagging, lifecycle/TTL rules, virtual-host addressing, and multi-range GET are outside the S3 API subset.

6 - pgs3 reference

Complete lookup for pgs3 v0.1.2: server GUCs, S3 API compatibility subset, SQL functions, and SQLSTATE-to-S3 error mappings.

Server configuration (GUCs)

All nine pgs3.* parameters have SIGHUP context, though some changes only take effect for new requests or require a restart as noted below.

pgs3.enabled , boolean , defaultoff
Register the static launcher on server startup when pgs3 is in shared_preload_libraries. Dynamic pgs3.start() ignores this flag.
pgs3.workers , integer (1–64) , default4
Desired number of HTTP background workers. Each consumes one max_worker_processes slot.
pgs3.listen_addr , string (IP) , default127.0.0.1
IPv4 or IPv6 bind address for HTTP workers. Keep on loopback and terminate TLS in a reverse proxy.
pgs3.port , integer (1–65535) , default9000
Shared SO_REUSEPORT TCP port for HTTP workers.
pgs3.inline_threshold , integer (bytes, 0–1 GiB) , default65536
Largest physical blob stored inline in pgs3.blob for new writes. Direct single-transaction PUT has an additional 64 KiB cap.
pgs3.chunk_size , integer (bytes, 64 KiB–16 MiB) , default4194304
Chunk size for staged uploads exceeding the inline threshold; snapshotted per upload on admission.
pgs3.statement_timeout_ms , integer (ms, 1–3600000) , default30000
PostgreSQL statement/lock timeout for each SPI semantic transaction. Applies to new transactions.
pgs3.target_database , string , defaultpostgres
Database served by the preloaded static launcher. Changing the pool’s database requires a server restart.
pgs3.server_role , string , defaultpgs3_server
Restricted service identity used by HTTP workers. Custom roles must exist beforehand and be NOLOGIN NOINHERIT with no elevated attributes, no inbound members, and SET-only membership in tenant roles.

Inspect live values

SELECT name, setting, unit, context, source, pending_restart
FROM pg_settings
WHERE name LIKE 'pgs3.%'
ORDER BY name;

Reload vs. restart

  • Applies on SIGHUP reload: pgs3.workers, pgs3.listen_addr, pgs3.port, pgs3.statement_timeout_ms, pgs3.inline_threshold (new blobs), and pgs3.chunk_size (new uploads). Existing blobs keep their original physical layout. Always verify a real signed request after a port/address rebind because a failed bind can keep the old listener running.
  • Requires a server restart: Adding pgs3 to shared_preload_libraries, changing pgs3.enabled from off to on when the static launcher was not registered at boot, or changing pgs3.target_database.
  • Service role changes: Reconciling a changed pgs3.server_role on reload requires matching grants and lacks release acceptance testing; prefer a planned restart.

Fixed implementation thresholds

These limits are built into v0.1.2 and have no registered GUC:

  • Upload lease: 5 minutes; body-idle timeout: 60 seconds (renewed on subsequent body progress).
  • Pending upload retention: 24 hours; GC interval: every 60 seconds, up to 1,000 rows per batch.
  • SQL hash fallback limit: Optional pgs3.sql_hash_fallback_limit custom setting defaults to 134217728 bytes (128 MiB); packaged builds use Rust hash helpers instead.

S3 API compatibility

AreaSupported APIsBehavior and boundaries
BucketsListBuckets, CreateBucket, DeleteBucket, HeadBucket, GetBucketLocation, GetBucketVersioningVersioning is permanently Enabled. DeleteBucket requires an empty bucket (including historical versions); pending uploads alone are aborted atomically on delete.
ObjectsPutObject, GetObject, HeadObject, CopyObject, DeleteObject, DeleteObjectsSupports single Range, If-Match/If-None-Match/date conditions, x-amz-meta-* metadata, source versionId copies, and SHA-256 / MD5 / flexible checksums. DeleteObjects accepts up to 1,000 keys per batch.
ListingListObjects (V1), ListObjectsV2, ListObjectVersionsPrefix, delimiter, encoding-type=url, max-keys (0–1000), V1 markers, and V2 continuation tokens.
MultipartCreateMultipartUpload, UploadPart, ListParts, CompleteMultipartUpload, AbortMultipartUploadNon-final parts must be ≥ 5 MiB. UploadPartCopy and ListMultipartUploads are not supported.
Version restorePOST /{bucket}/{key}?restore&versionId={id}pgs3 extension route that publishes an older version as the new latest version (not AWS Glacier archival restore).

Signing and unsupported features

  • Supported auth: Header-based AWS SigV4 (FullHash, UNSIGNED-PAYLOAD, STREAMING-AWS4-HMAC-SHA256-PAYLOAD, STREAMING-UNSIGNED-PAYLOAD-TRAILER) and query-parameter presigned GET/PUT URLs (max expiry 7 days, clock skew ±15 minutes).
  • Outside the subset: Virtual-host bucket addressing, TLS termination, bucket policies, ACLs, CORS, object tagging, lifecycle/TTL rules, object lock/retention, multi-range GET, UploadPartCopy, and ListMultipartUploads.

SQL API

Tenant operations run under the caller’s PostgreSQL role (with RLS isolation); operator functions are revoked from PUBLIC.

Buckets and objects

pgs3.create_bucket(p_name text, p_config jsonb) , bucket_info , defaultp_config = '{}'
Create a bucket owned by the current role (idempotent for the same owner).
pgs3.list_buckets() , setof bucket_info , default—
List buckets visible to the current role.
pgs3.delete_bucket(p_name text) , boolean , default—
Delete an empty bucket (aborts leftover pending uploads).
pgs3.put(p_bucket text, p_key text, p_body bytea, p_content_type text, p_meta jsonb, p_if_none_match text, p_if_match text, p_checksum_sha256 bytea) , object_info , default'application/octet-stream', '{}', NULL, NULL, NULL
Atomically write a new object version; supports ETag preconditions and SHA-256 verification.
pgs3.head(p_bucket text, p_key text, p_version_id bigint, p_if_match text, p_if_none_match text) , object_info , defaultNULL, NULL, NULL
Read object metadata for the latest or specified version.
pgs3.get(p_bucket text, p_key text, p_version_id bigint, p_if_match text, p_if_none_match text) , object_data , defaultNULL, NULL, NULL
Read object metadata and full body bytea.
pgs3.get_range(p_bucket text, p_key text, p_start bigint, p_end bigint, p_version_id bigint, p_if_match text, p_if_none_match text) , bytea , defaultNULL, NULL, NULL, NULL
Read an inclusive 0-based byte slice of an object.
pgs3.copy(p_source_bucket text, p_source_key text, p_destination_bucket text, p_destination_key text, p_source_version_id bigint, p_content_type text, p_meta jsonb, p_if_none_match text, p_if_match text, p_source_if_match text) , object_info , defaultNULL for optional params
Copy an object or version by sharing its canonical SHA-256 blob.
pgs3.delete(p_bucket text, p_key text, p_version_id bigint) , delete_result , defaultp_version_id = NULL
Insert a delete marker when p_version_id is NULL, or permanently delete that version.
pgs3.list(p_bucket text, p_prefix text, p_delimiter text, p_start_after text, p_continuation_token text, p_max_keys integer) , setof list_entry , default'', NULL, NULL, NULL, 1000
List keys and common prefixes in indexed key order.
pgs3.restore(p_bucket text, p_key text, p_version_id bigint, p_if_match text) , object_info , defaultp_if_match = NULL
Publish a historical version’s payload as a new latest version.
pgs3.fork_bucket(p_source_bucket text, p_destination_bucket text, p_destination_config jsonb) , bigint , defaultp_destination_config = NULL
Create a new bucket sharing the source’s latest blobs and return the number of entries copied.

Credentials and runtime operations

pgs3.create_credential(p_access_key text, p_secret text, p_role_name name, p_enabled boolean) , boolean , defaultp_enabled = true
Operator only. Create an S3 key pair bound to an unprivileged tenant role.
pgs3.rotate_credential(p_access_key text, p_new_secret text) , boolean , default—
Operator only. Replace the signing secret for an existing key.
pgs3.set_credential_role(p_access_key text, p_role_name name) , boolean , default—
Operator only. Reassign an access key to another unprivileged tenant role.
pgs3.set_credential_enabled(p_access_key text, p_enabled boolean) , boolean , default—
Operator only. Suspend or re-enable an access key.
pgs3.delete_credential(p_access_key text) , boolean , default—
Operator only. Delete an access key.
pgs3.start() , boolean , default—
Operator only. Start a dynamic worker pool for the current database.
pgs3.stop() , boolean , default—
Operator only. Stop the dynamic worker pool in the current database.
pgs3.extension_version() , text , default—
Return the installed SQL catalog version of pgs3.
pgs3.worker_state , table , default—
Live launcher, GC, and HTTP worker status, listener address, and heartbeats.
pgs3.stats , view , default—
Aggregated HTTP request counters, errors, latency buckets, bytes, and GC/upload backlog.
pgs3.gc_pending_uploads(p_max_age interval, p_limit integer) , bigint , default—
Operator only. Clean up expired pending uploads in bounded batches.
pgs3.gc_blobs(p_limit integer) , bigint , default1000
Operator only. Delete unreferenced zero-refcount blobs in bounded batches.

SQLSTATE to S3 error mapping

SQLSTATEHTTPS3 error code
P3B01404NoSuchBucket
P3K01404NoSuchKey / NoSuchVersion
P3U01404NoSuchUpload
P3C01412PreconditionFailed
P3N01304NotModified (no XML body)
P3R01416InvalidRange
P3E01409BucketAlreadyExists
P3F01409BucketNotEmpty
P3H01400BadDigest
P3P01400InvalidPart / InvalidPartOrder / EntityTooSmall
P3S01400EntityTooLarge
42501403AccessDenied
25006503ServiceUnavailable (read-only standby)
57014503SlowDown (statement timeout)
0A000501NotImplemented
other500InternalError

An allowlisted pgs3.error=<code> diagnostic detail takes precedence to distinguish finer variants such as NoSuchVersion, InvalidBucketName, or EntityTooSmall. HEAD and 304 responses omit XML bodies. For the complete protocol-to-SQL mapping, see api-sql-mapping.md.