Skip to content

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

Return to the regular view of this page

Design

Why pgsilo exists and the decisions that shaped it.

This section documents the engineering rationale and internal architecture of pgsilo: why the project pairs the Silo S3 frontend with a PostgreSQL ObjectLayer backend, how S3 and SQL share a single transactional state machine, and how multi-gateway caches and background workers maintain consistency.

Design documents

DocumentTopic
Why a PostgreSQL backendTarget workloads, lessons from pgs3, when to choose PostgreSQL vs. erasure-coded storage, and capacity bounds
Design decisionsThe ObjectLayer seam, 8 MiB bytea segments, commit_seq version ordering, lock hierarchy, and rejected alternatives
Integration with SiloAuditing erasure-coded assumptions in Silo, .minio.sys persistence, S3 Select snapshots, and why iam_and_pg intersects IAM
SQL API designSeparating silo, silo_api, and silo_bucket, session_user security hardening, and per-bucket security_barrier ACL views
IAM control planePool isolation, the 5-second freshness lease, standby heartbeats, and the schema 14 revision_token split-brain fix
Lifecycle and Object LockDatabase-enforced WORM retention, keyset lifecycle scanning, and epoch-fenced maintenance leases
MVP goal2026-11-08: ship as an experimental Silo backend; support tiers, release checklist, merge prerequisites
Status review and baseline, 2026-11-08Why testing did not close, the runtime baseline on 299378b, the IAM snapshot experiment and the request queue fix

1 - Why a PostgreSQL backend

Who it is for, when it beats erasure-coded storage, and the alternatives that were evaluated.

Many small-to-medium applications already run a managed or high-availability PostgreSQL cluster, yet still need an S3 endpoint for user attachments, avatars, PDF exports, or CI artifacts. Running a separate object storage cluster splits operational state across two systems: backups, point-in-time recovery (PITR), database clones, and access control must be coordinated twice and can drift apart.

pgsilo solves this by adding a PostgreSQL ObjectLayer backend to Silo (PGSTY’s fork of MinIO), storing all object data, versions, bucket configurations, multipart uploads, and IAM state inside a single PostgreSQL database.

Lessons from pgs3

Before building pgsilo, PGSTY built pgs3, an in-process PostgreSQL extension in Rust/pgrx that speaks S3 from a background worker. pgs3 (v0.1.1) passed 195 of 195 Ceph s3-tests cases and proved that S3 versioning, delete markers, conditional writes, and multipart semantics map cleanly onto PostgreSQL tables. However, it also exposed three structural trade-offs:

  1. Protocol surface maintenance: implementing SigV4 variants, aws-chunked streaming, presigned URLs, POST policies, and modern SDK trailing checksums (CRC32C, CRC64NVME) from scratch inside a C/Rust extension is a major ongoing cost. Silo already implements the full HTTP and S3 wire layer.
  2. Write-path deduplication overhead: pgs3 used content-addressed SHA-256 chunk deduplication and reference counting, which added index lookups and row-lock contention on small-object writes. pgsilo drops deduplication: each segment belongs to a single object version or active upload and is deleted by cascade.
  3. Process isolation and managed PostgreSQL compatibility: a compiled extension cannot be installed on locked-down managed PostgreSQL services, and an HTTP parser bug in a background worker runs inside the database process tree. pgsilo runs as a stateless external Go binary and installs only standard SQL tables and PL/pgSQL functions (PostgreSQL 16+).
Note

The initial October 2026 PRD targeted PostgreSQL 18 as the baseline version, but the implemented schema 14 tables and PL/pgSQL functions avoid PostgreSQL 18-only DDL dependencies and run on PostgreSQL 16, 17, and 18.

Target scenarios vs. anti-patterns

PriorityUser / ScenarioWhy pgsilo fits
P1Business apps (Odoo, ERP, CRM)Invoices, attachments, and business rows are backed up and restored together to the exact same PITR timestamp
P1Self-hosted Supabase / app platformsPoints Supabase Storage’s S3 backend at the existing PostgreSQL cluster without provisioning dedicated object disks
P1Local development & CI pipelinesOne PostgreSQL database backs both SQL tables and S3 buckets; DROP DATABASE resets the entire test environment
P2Private / on-premises appliance deliveryShips S3 storage on customer infrastructure that only permits standard PostgreSQL instances
P2Transactional SQL + S3 workflowsReads and writes objects inside Read Committed SQL transactions via silo_api and joins metadata with business tables

When NOT to use pgsilo (use Silo erasure-coded mode instead):

  • Backing up the hosting PostgreSQL cluster itself: never point a PostgreSQL cluster’s own pgBackRest repository at a pgsilo instance stored inside that same cluster—if the database fails, the backup is unreachable.
  • Large objects (> 256 MiB default, > 1 GiB hard ceiling): video archives, LLM weights, and large Parquet lakes belong on erasure-coded disks.
  • High-throughput observability sinks: continuous high-bandwidth write streams (Loki, Tempo, Mimir, Thanos) or CDN origin workloads.

Silo PostgreSQL mode vs. Silo erasure-coded mode

Both modes ship in the same silo binary and share the same S3 HTTP frontend, SigV4 authentication, IAM engine, and Console:

DimensionSilo PostgreSQL mode (pgsilo)Silo erasure-coded mode
StartupSILO_PG_DSN="postgresql://..." silo serversilo server /data{1...4}
Recommended scale<= 200 GB per database, <= 10M object versions, <= 256 MiB per object (max 1 GiB)Terabytes to petabytes; up to 5 TiB per object
Where state lives100% in PostgreSQL tables (silo schema)Local/distributed disks (xl.meta + erasure shards)
Unique strengthsTransactional SQL API (silo_api), unified pgBackRest PITR, stateless gatewaysHigh streaming throughput, erasure coding, site replication, remote tiering
Rule of thumbChoose when objects must share backup, PITR, or SQL transactions with relational dataChoose when object volume exceeds 200 GB or sustained write throughput exceeds 50 MB/s

Capacity and sizing rationale

  • Database object volume (<= 200 GB recommended): at typical pgBackRest restore speeds (200–500 MB/s), a 200 GB database restores in 7–17 minutes, keeping RTO predictable.
  • Object version count (<= 10M versions): at roughly 0.6 KB of row and B-tree index metadata per version, 10 million versions occupy ~6 GB of catalog metadata, keeping ListObjectsV2 and lifecycle index scans fast.
  • Segment size (8 MiB default, 1–64 MiB configurable): PostgreSQL TOAST supports values up to 1 GB, but buffering a single large bytea requires 2–3x its size in gateway and backend memory. Splitting objects into 8 MiB rows bounds per-request memory to two segment buffers (16 MiB) regardless of total object size while matching the AWS CLI’s default 8 MiB multipart chunk size.

2 - Design decisions

The ObjectLayer seam, the data model and the rejected alternatives.

This page summarizes the core architectural decisions behind pgsilo, including how initial design assumptions were refined during implementation and verification.

1. The ObjectLayer seam

Silo’s architecture separates HTTP request parsing, SigV4 authentication, and XML serialization (cmd/) from storage operations via the ObjectLayer interface (44 methods). Below ObjectLayer, the erasure-coded backend uses StorageAPI to read and write reed-solomon shards and binary xl.meta files across disks.

pgsilo implements ObjectLayer directly (internal/pgstore + cmd/object-api-pg*.go) rather than StorageAPI:

  • Implementing StorageAPI would still run the erasure-coding engine and store opaque xl.meta blobs in PostgreSQL, making object metadata unreadable from SQL.
  • At the ObjectLayer level, 26 methods carry object, bucket, multipart, and system-file semantics, while the remaining 18 erasure-specific methods (disk healing, pool decommissioning, rebalancing, remote tiering) cleanly return NotImplemented.
  • Server configuration, IAM users/policies, and bucket metadata (.minio.sys/*) already read and write through ObjectLayer, so redirecting .minio.sys to a silo.sys_files table persists control-plane state in PostgreSQL automatically.

2. Data model and 8 MiB bytea segments

All buckets share a single set of tables in the private silo schema (silo.meta, silo.buckets, silo.objects, silo.object_segments, silo.uploads, silo.upload_parts, silo.sys_files, plus annotation and control tables):

Design choiceRationale
Shared tables keyed by bucket_idCreating or deleting a bucket performs ordinary row DML rather than CREATE TABLE ... PARTITION OF, which would acquire an ACCESS EXCLUSIVE lock on the parent table and block concurrent S3 traffic
key COLLATE "C"S3 lists keys in raw UTF-8 byte order; C collation lets prefix queries (key >= prefix AND key < upper_bound) use standard B-tree index range scans
Separate metadata (silo.objects) and payload (silo.object_segments) tablesHEAD, ListObjectsV2, and tag updates never touch segment pages; silo.object_segments tunes autovacuum independently
Fixed-size bytea segments (8 MiB default) with TOAST lz4Bounds per-request gateway memory to 2 * segment_size; PostgreSQL TOAST compresses compressible text/JSON with lz4 (falling back to pglz if built without lz4) and stores incompressible JPEG/PDF segments uncompressed without hurting byte-range slicing
No content-addressed deduplicationEvery segment row belongs to one object version or one active upload (ON DELETE CASCADE), eliminating refcount hot spots

3. Version ordering (commit_seq) and lock hierarchy

Early design drafts considered ordering object versions by their auto-increment id or mod_time. Implementation audits identified a flaw: streaming PUT transactions pre-allocate object_id before streaming segments, so two concurrent uploads to the same key can finish in the reverse order of their id allocation, and gateway wall clocks can skew.

To guarantee linearizable version ordering across S3 and SQL writers:

  • commit_seq ordering: object_id is allocated when segment streaming begins, but the version publication order is defined by a dedicated commit_seq assigned after acquiring the per-key transaction advisory lock (silo.lock_key). Deleting the latest version promotes the remaining version with the highest commit_seq.
  • Strict lock hierarchy: every mutation acquires locks in a fixed order to prevent deadlocks:
    1. Bucket row lock: FOR SHARE for object writes/uploads/deletes; FOR UPDATE for bucket deletion or bucket configuration changes.
    2. Upload row lock (multipart only): FOR SHARE for UploadPart; FOR UPDATE for CompleteMultipartUpload and AbortMultipartUpload.
    3. Part advisory lock (multipart UploadPart only): serializes concurrent uploads of the same (upload_id, part_no).
    4. Per-key transaction advisory lock: pg_advisory_xact_lock(1936288879, hashtext(bucket_id || '/' || key)) held only during the final metadata publication and precondition check (If-Match / If-None-Match).
  • Shared SQL state machine: S3 gateway writes and silo_api SQL functions call the same PL/pgSQL state-transition functions (silo.commit_version, silo.delete_version, silo.complete_upload), ensuring identical versioning, quota, and Object Lock behavior.

4. Read snapshots, CopyObject budgets, and empty-bucket deletion

  • Snapshot-isolated reads: multi-segment GET and SelectObjectContent open a REPEATABLE READ READ ONLY transaction before querying silo.objects. Even if another client overwrites or deletes the object while segments are streaming, the reader sees a consistent object body until completion or timeout.
  • Deadlock-free CopyObject connection budget: a server-side copy reads from a source snapshot while writing to a destination transaction. To prevent 16 concurrent CopyObject calls from acquiring 16 source connections and deadlocking while waiting for destination connections, the data pool uses a FIFO weighted semaphore that atomically reserves two data connections before opening the source snapshot (which is why data_conns must be at least 2).
  • Connection liveness on checkout: pgxpool by default only pings connections idle for more than 1 second, which allowed a sub-second PostgreSQL restart to leave stale connections that failed the first S3 GET with HTTP 500. pgsilo enables connection health checks on checkout bounded by SILO_PG_ACQUIRE_TIMEOUT.
  • Empty-bucket DeleteBucket with unfinished multipart uploads: verified against both AWS S3 general-purpose bucket semantics and Silo’s erasure-coded implementation, DeleteBucket acquires FOR UPDATE on the bucket row, rejects deletion with HTTP 409 if any published object version or delete marker exists, and otherwise cascades deletion of any unfinished multipart uploads and parts in the same transaction.

5. Rejected alternatives

AlternativeWhy it was rejected
Hooking PostgreSQL at StorageAPI (disk layer)Still runs erasure coding and stores binary xl.meta blobs, preventing SQL queries and adding unnecessary CPU overhead
Single unsegmented bytea column per objectRequires buffering the entire object (up to 256 MiB–1 GiB) in both gateway and PostgreSQL backend memory; forces CompleteMultipartUpload to copy and concatenate all parts
PostgreSQL Large Objects (pg_largeobject)Stored in a cluster-wide system catalog (pg_largeobject), unfriendly to per-bucket permissions, requires vacuumlo for orphan cleanup, and complicates logical dumps
Storing large object bodies on local filesystemBreaks unified pgBackRest backup, PITR, and stateless gateway failover
One PostgreSQL table or partition per bucketCREATE TABLE ... PARTITION OF requires an ACCESS EXCLUSIVE lock on the parent table, blocking concurrent reads/writes during bucket creation or deletion
Content-addressed deduplication and reference countingIntroduces hash-lookup overhead and reference-count row contention on small writes (observed in pgs3)
Compiled C or Rust PostgreSQL extensionCannot be installed on managed PostgreSQL services; standard SQL + PL/pgSQL suffices for all state transitions

3 - Integration with Silo

Where Silo assumes erasure coding, and why IAM and native authorization both apply.

Replacing the newObjectLayer() constructor in Silo is only the first step of integrating a PostgreSQL backend. Although Silo routes object and configuration storage through ObjectLayer, several startup routines, background workers, HTTP handlers, and IAM entry points in cmd/ implicitly assume a distributed erasure-coded (erasureServerPools) deployment.

This page documents the coupling points identified during the Stage 0 source audit and how pgsilo resolves each one without breaking erasure-coded mode.

Startup, DSN parsing, and concurrency budgets

Subsystem in cmd/Original erasure-coded assumptionPostgreSQL backend adaptation
Command-line / env argument parsing (server-main.go, common-main.go)Requires positional disk directory arguments or MINIO_VOLUMES; normalizes arguments as filesystem pathsDetects SILO_PG_DSN or a single postgres:// / postgresql:// URI before disk parsing; rejects mixing disk paths with PostgreSQL mode; redacts DSN passwords from debug output
Peer RPC grid (grid.go, internal/grid)Unconditionally initializes peer-to-peer WebSocket grids and distributed lock grids across globalEndpointsSkips grid and lock-grid initialization when globalIsPGBackend is set; gateways coordinate solely through PostgreSQL transactions and LISTEN/NOTIFY
Default request concurrency (handler-api.go: apiConfig.init)When api requests_max <= 0, computes memory limits using slices.Max(setDriveCounts)—which panics on an empty drive-count slice in PostgreSQL modeBounds concurrent S3 requests by min(SILO_PG_MAX_CONNS, memlimit / (2 * SILO_PG_SEGMENT_SIZE), api requests_max) coupled with the SILO_PG_QUEUE_TIMEOUT admission queue
Bucket metadata batch loader (bucket-metadata-sys.go)Computes batch step as globalEndpoints.ESCount() * 10, causing an infinite 0-step loop when ESCount() == 0Enforces max(1, ...) batch sizing so empty and non-empty bucket catalogs load cleanly on startup
Deployment identity and readiness (erasure-server-pool.go, server-main.go)Generates deployment UUID inside newErasureServerPools and logs single-drive parity warningsPersists a stable deployment_id in silo.meta, publishes setObjectLayer after schema check/migration, suppresses erasure parity warnings, and separates /minio/health/cluster/read from /minio/health/cluster

Guarding the 20 .(*erasureServerPools) type assertions

A static audit of cmd/ found 20 .(*erasureServerPools) type assertions across 9 files (admin-handlers-pools.go, admin-handlers.go, background-newdisks-heal-ops.go, data-usage.go, erasure-multipart-listing.go, global-heal.go, notification.go, peer-rest-server.go, and site-replication.go), plus several non-assertion handlers that reference erasure-only state:

  • Pool decommission, rebalance, and drive healing: all pool status, decommission, rebalance, and heal endpoints return NotImplemented at the handler boundary in PostgreSQL mode rather than reaching uninitialized globalAllHealState pointers.
  • Replication and remote tiering: background replication resync, site replication, and remote tier transition workers are not started in PostgreSQL mode, while global wrapper pointers remain nil-safe when DeleteBucket or metrics handlers run.
  • Admin server and storage info (madmin): StorageInfo and /minio/metrics/v3/pg report PostgreSQL database usage, logical bucket quotas, and minio_pg_capacity_known = 0 (Unknown exclusive disk capacity in Console) instead of fabricating fake erasure drives.

.minio.sys persistence in silo.sys_files

Silo stores server configuration (config.json and configuration history), IAM users/groups/policies/service accounts, and per-bucket metadata (.minio.sys/buckets/<bucket>/.metadata.bin) as objects inside the reserved .minio.sys bucket.

In PostgreSQL mode, operations on .minio.sys route to silo.sys_files:

  1. Exact prefix-object delete vs. subtree delete: deleteConfig passes DeletePrefix=true, DeletePrefixObject=true to delete an exact configuration key without deleting adjacent keys sharing that string prefix (a vs. ab).
  2. Asynchronous Walk for IAM startup: IAMObjectStore.listIAMConfigItems invokes ObjectLayer.Walk and reads from the returned channel; pgsilo implements ordered prefix walking over silo.sys_files (including IAM tombstones) and closes the channel on completion or cancellation.
  3. Read-only standby startup: on a read-only gateway (SILO_PG_READ_ONLY=on or pg_is_in_recovery() = true), startup loads existing .minio.sys records in read-only mode without writing default configuration files or IAM format markers.

SelectObjectContent multi-seek snapshot consistency

In Silo’s SelectObjectContentHandler, the handler first calls GetObjectInfo to inspect the object and then passes a NewObjectReadSeekCloser to the S3 Select engine (especially for Parquet and CSV streams), which invokes GetObjectNInfo repeatedly across seek callbacks without pinning a VersionID.

On an erasure-coded cluster, an in-process read lock prevents local overwrites during the query. In PostgreSQL mode, however, another gateway or a silo_api SQL transaction can overwrite the key or replace a null version between seeks. To prevent S3 Select from splicing bytes from two different object generations, pgsilo pins a single REPEATABLE READ READ ONLY transaction snapshot before the initial metadata lookup and reuses that snapshot across all subsequent seek callbacks until the request closes.

Why iam_and_pg cannot use globalAuthZPlugin directly

Early architecture notes proposed implementing PostgreSQL native authorization (iam_and_pg) by registering an in-process globalAuthZPlugin. Auditing cmd/iam.go (IAMSys.IsAllowed) revealed a critical security flaw with that approach:

if authz := newGlobalAuthZPluginFn(); authz != nil {
    ok, err := authz.IsAllowed(args)
    return ok
}

When globalAuthZPlugin is non-nil, IAMSys.IsAllowed short-circuits and returns the plugin’s boolean immediately—skipping built-in owner checks, service-account parent and inline policy intersections (IsAllowedServiceAccount), STS session policy restrictions (IsAllowedSTS), and explicit IAM Deny statements.

To preserve full S3 IAM semantics, pgsilo evaluates PostgreSQL native role privileges as an additional AND gate after built-in IAM evaluation succeeds:

  1. The request must first pass full S3 IAM evaluation (including explicit Deny, bucket policies, service-account restrictions, and STS session policies).
  2. When silo.set_native_auth_mode('iam_and_pg') is active, the gateway resolves the authenticated S3 principal (or the parent IAM user for a service account / STS token) in silo.native_auth_principals and verifies that the bound PostgreSQL role holds the required privilege (SELECT, INSERT, UPDATE, DELETE, or EXECUTE on silo_api.create_bucket) on the target bucket’s silo_bucket ACL relation.
  3. Both checks must return allow; a PostgreSQL GRANT never overrides an S3 IAM Deny.

4 - SQL API design

Why objects are reachable from SQL and how per-bucket ACL relations work.
Note

The public silo_api SQL interface and silo_bucket ACL relations are Preview features in the MVP release.

Storing objects inside PostgreSQL unlocks a capability that external object stores cannot provide: applications can read, write, copy, and delete S3 objects inside the same Read Committed SQL transaction as ordinary relational tables. This page explains how pgsilo exposes that SQL interface without compromising the internal version state machine or tenant isolation.

Three-schema separation (silo, silo_api, silo_bucket)

Early design drafts placed public SQL functions directly in the silo schema. Implementation reviews separated the database surface into three schemas:

SchemaPurposeAccess policy
siloPrivate storage tables (buckets, objects, object_segments, sys_files, bucket_acl) and internal SECURITY INVOKER state-machine helpers (commit_version, delete_version, lock_key)Owned by silo_owner; REVOKE ALL FROM PUBLIC; never granted to application roles
silo_apiThe 11 public SECURITY DEFINER functions (put_object, get_object, read_object, stat_object, list_objects, delete_object, copy_object, create_bucket, bucket_info, list_buckets, drop_bucket)REVOKE ALL FROM PUBLIC at creation; administrators explicitly GRANT USAGE and per-function EXECUTE to application SQL logins
silo_bucketPer-bucket ACL relations (silo_bucket.b_<bucket_id>) created automatically when a bucket is createdNon-updatable security_barrier views carrying SELECT, INSERT, UPDATE, and DELETE grants

Public silo_api functions return flat RETURNS TABLE (...) columns or bytea rather than composite types from silo.*, so application roles never need USAGE on the private silo schema.

Per-bucket ACL relations (silo_bucket.b_<bucket_id>)

Why represent bucket permissions with a view named b_<bucket_id> in silo_bucket?

  1. Identifier length and collision safety: S3 bucket names can be up to 63 bytes (and internal table columns allow up to 255 bytes) with dots and hyphens, whereas PostgreSQL identifiers are capped at 63 bytes (NAMEDATALEN - 1). Naming the relation silo_bucket.b_<bucket_id> avoids truncation collisions while silo.bucket_acl maps each immutable bucket_id to its exact relation_oid (regclass).
  2. Non-updatable security_barrier views: each silo_bucket.b_<bucket_id> view is a security_barrier = true join over silo.objects and silo.buckets without INSTEAD OF triggers. Granting INSERT or DELETE on the view serves purely as an authorization bit checked via has_table_privilege(session_user_oid, relation_oid, priv) IS TRUE; an application role cannot execute raw INSERT, UPDATE, or DELETE statements against the view to bypass the version state machine.
  3. Clean lifecycle on bucket recreation: dropping a bucket drops its silo_bucket.b_<bucket_id> view in the same transaction. Recreating a bucket with the same name allocates a new bucket_id and a new ACL relation with no stale grants carried over.

Caller identity (session_user) and SECURITY DEFINER hardening

Inside a SECURITY DEFINER function, current_user and current_role resolve to the function owner (silo_owner), not the caller. Checking privileges against current_user would grant every caller full owner access.

To prevent privilege escalation:

  • Fixed session_user principal: every silo_api entry point authenticates session_user (resolved to its role OID) and explicitly verifies has_function_privilege(session_user_oid, '<function_signature>'::regprocedure, 'EXECUTE') IS TRUE.
  • Rejecting SET ROLE and owner logins: if current_setting('role') is not 'none', or if session_user is the installation owner (silo_owner) or a member of it, the function rejects the call with SQLSTATE 42501. An unprivileged user cannot wrap a silo_api call inside their own SECURITY DEFINER function or use SET ROLE to impersonate another role.
  • Locked search_path: all silo_api functions set search_path = pg_catalog, pg_temp and schema-qualify every table, function, and operator reference so user-created objects in pg_temp or public cannot hijack execution.
  • Immediate REVOKE visibility: cached PL/pgSQL plans do not always process PostgreSQL catalog invalidation messages before evaluating has_table_privilege. Every silo_api call first runs a lightweight dynamic EXECUTE 'SELECT 1 FROM silo.meta LIMIT 0' to force syscache invalidation acceptance, ensuring a committed REVOKE takes effect on the very next statement.

Transactional semantics and synchronized bucket policies

  • Read Committed write contract: put_object, delete_object, copy_object, create_bucket, and drop_bucket require Read Committed isolation. Under Repeatable Read or Serializable, a transaction waiting on silo.lock_key would still see its pre-lock snapshot and miss a concurrent latest version; write functions therefore reject higher isolation levels with SQLSTATE 0A000.
  • Deadlock-safe copy_object: silo_api.copy_object acquires FOR SHARE on the source and destination bucket rows in ascending bucket_id order, reads the source metadata, segments, and annotations from a single snapshot without holding a source key lock across the destination write, and publishes the destination version atomically.
  • Policy synchronization (policy_ready): S3 stores bucket configuration in .minio.sys/buckets/<bucket>/.metadata.bin, while SQL functions inspect structured columns on silo.buckets (versioning, object_lock, default_sse, policy_ready). Whenever a gateway updates .metadata.bin, it decodes and updates those structured columns in the same FOR UPDATE transaction. SQL write functions require policy_ready = true, enforce default Object Lock retention and hard bucket quotas, and reject plaintext writes to buckets with default SSE enabled.

5 - IAM control plane

Pools, advisory locks, the 5-second bound and the revision token added in schema 14.

In a multi-gateway pgsilo deployment, gateways cache IAM users, groups, policies, service accounts, STS sessions, and bucket metadata in memory so ordinary S3 requests do not query .minio.sys tables on every packet. However, an unbounded or loosely synchronized cache creates a security gap: a revoked credential or deleted policy could remain usable on another gateway for minutes.

This page explains how pgsilo bounds IAM and control-plane cache staleness to 5 seconds, isolates control traffic from slow object streams, validates standby gateways, and prevents split-brain cache renewal after asynchronous PostgreSQL failover (schema 14).

1. Three-pool connection isolation

If S3 object uploads, IAM refreshes, health checks, and LISTEN notifications shared a single database connection pool, a burst of slow 256 MiB uploads could exhaust all connections and starve health checks or credential revocations.

pgsilo splits each gateway’s connection budget (SILO_PG_MAX_CONNS, default 32) into three isolated pools:

PoolDefault sizeConfigurable rangeResponsibilities
Control pool (SILO_PG_CONTROL_CONNS)41–64Atomic IAM snapshot reloads, bucket metadata refreshes, revision polling, and /minio/health/cluster* probes
Coordination pool (SILO_PG_COORD_CONNS)22–64One dedicated LISTEN silo_control_rev connection plus serialized IAM control-plane write transactions
Data pool (MAX - CONTROL - COORD)26>= 2Streaming S3 object reads, writes, multipart uploads, and 2-connection CopyObject reservations

Data-pool saturation never borrows connections from the control or coordination pools.

2. Serialized IAM mutations and atomic snapshot reloads

Silo’s upstream IAMObjectStore loads users, groups, policy mappings, and STS tokens across separate file reads and merges partial maps in memory. Against a shared PostgreSQL database, separate reads could observe a half-applied multi-file IAM update.

pgsilo replaces both sides of the IAM persistence lifecycle:

  • Serialized IAM writes: every administrative IAM mutation acquires a connection from the coordination pool, begins a READ COMMITTED transaction, takes a fixed global IAM transaction advisory lock, performs the compare/merge and silo.sys_files updates inside that single transaction, and bumps silo.sys_revision before COMMIT. If the connection drops, the lock and file mutations roll back together.
  • Single-snapshot IAM reload: when a gateway reloads IAM state, it opens a REPEATABLE READ READ ONLY transaction on the control pool, reads silo.sys_revision and all IAM records from silo.sys_files in one consistent snapshot (bounded by file count and byte limits), decodes the complete identity and policy graph, and swaps the in-memory IAM cache atomically.

3. The 5-second freshness lease

Every gateway enforces a hard 5-second lease on its installed IAM snapshot:

  1. Monotonic start-of-query anchor: the 5-second timer starts at the monotonic wall-clock instant before the gateway sends its database observation query (SELECT revision, revision_token, pg_is_in_recovery() ...), not when a slow query finishes.
  2. 1-second polling + LISTEN/NOTIFY hints: gateways poll silo.sys_revision every 1 second and also subscribe to LISTEN silo_control_rev. A NOTIFY wakes the poller immediately, but notifications are never trusted as a durable stream; listener connect or reconnect always forces a full snapshot reload.
  3. Fail-closed expiration: before authorizing any IAM-dependent S3 or admin request, the middleware checks whether the current snapshot lease is still valid. If the lease has expired and a shared refresh cannot verify database authority within the deadline, the gateway fails closed with HTTP 503 rather than evaluating stale permissions.

4. Physical standby freshness and the 500 ms clock contract

Polling silo.sys_revision on a physical PostgreSQL standby is not sufficient by itself: if streaming replication is paused or lagging by 10 minutes, the standby still returns a valid-looking old revision row.

To bound staleness on read-only standby gateways (SILO_PG_READ_ONLY=on):

  • A writable gateway connected to the primary periodically writes a timestamped authority heartbeat row that replicates through WAL without incrementing silo.sys_revision or triggering full IAM reloads.
  • Primary and standby host clocks must stay synchronized within 500 milliseconds.
  • When a standby gateway polls its replica database, it subtracts (now - heartbeat_timestamp) + 500 ms from the 5-second lease budget. If replication stalls, the primary writable gateway stops, or clock skew exceeds bounds, the standby lease expires within 5 seconds and IAM-authenticated requests fail closed (503).

5. Schema 14: revision_token for divergent failover histories

Testing asynchronous PostgreSQL failover exposed a subtle split-brain edge case with integer revisions:

  1. Suppose the primary is at revision = 42. An administrator revokes a user’s policy (revision = 43), and Gateway A caches revision = 43.
  2. Before WAL for revision = 43 replicates to the standby, the primary crashes and the standby is promoted at revision = 42.
  3. On the newly promoted primary, an unrelated control-plane change (such as creating a bucket) increments revision from 42 to 43.
  4. Gateway A polls the new primary, sees revision = 43 (equal to its cached integer 43), and—if it checked only the integer—would renew its lease while holding a divergent IAM state from the old timeline.

The Schema 14 fix (revision_token):

Schema 14 adds a revision_token uuid column to the singleton silo.sys_revision row, updated by a BEFORE UPDATE trigger to a fresh random UUID (gen_random_uuid()) whenever revision changes.

  • Gateways record (revision, revision_token, in_recovery) alongside every installed IAM snapshot.
  • A poll renews the 5-second lease only if both revision and revision_token match the installed snapshot and in_recovery has not changed.
  • After an asynchronous failover, even if the promoted primary reaches the same integer revision = 43, its revision_token UUID differs, immediately forcing every gateway to discard its old timeline cache and perform a full REPEATABLE READ reload.

6 - Lifecycle and Object Lock

How lifecycle rules and retention work under leases.
Note

Object Lock (GOVERNANCE / COMPLIANCE retention and legal hold) and bucket lifecycle rules (version expiration, expired delete-marker cleanup, and incomplete multipart upload abort) are Preview features in the MVP release.

In Silo’s erasure-coded backend, lifecycle expiration and Object Lock checks rely on the distributed disk scanner (NSScanner), in-memory expiry queues, and handler-level pre-checks. Directly enabling those paths on a shared PostgreSQL backend would fail in four ways:

  1. MultiDelete TOCTOU window: Silo’s DeleteObjects handler pre-checked Object Lock retention before calling the backend delete loop, leaving a race window where a concurrent request could enable a legal hold or extend retention before the row was deleted.
  2. Unbounded version slices in Evaluator.Eval: the upstream lifecycle evaluator expects all versions of a key in a single in-memory slice, which would allocate unbounded gateway memory on keys with deep version histories.
  3. Subtree vs. exact-key delete mismatch: erasure-coded lifecycle DeleteAll passes DeletePrefix=true, DeletePrefixObject=true to delete all versions of an exact key, which a naive prefix delete would misinterpret as deleting an entire / key subtree.
  4. Missing AbortIncompleteMultipartUpload rule wiring: upstream rule structs lacked complete AbortIncompleteMultipartUpload evaluation fields and relied on a global stale-upload timer rather than per-bucket prefix and initiation-age rules.

This page describes how pgsilo implements authoritative Object Lock enforcement and fenced lifecycle execution directly in PostgreSQL.

1. Authoritative Object Lock in the database state machine

Rather than trusting unvalidated JSON headers in user_defined, pgsilo stores normalized lock columns on silo.objects (retention_mode, retain_until, legal_hold) and default retention settings on silo.buckets (synchronized transactionally whenever .metadata.bin is saved under the bucket FOR UPDATE lock):

  • Database UTC clock: all retention expiration checks compare retain_until against PostgreSQL’s clock_timestamp() inside the key lock, ensuring S3 requests, silo_api SQL calls, and background lifecycle workers agree on a single clock.
  • Every mutation path shares one check:
    • Single DeleteObject and batch DeleteObjects: each key deletion runs inside the per-key advisory lock (silo.lock_key), re-reading the target version’s retention_mode, retain_until, and legal_hold atomically so no TOCTOU window exists between pre-check and deletion.
    • PutObjectMetadata (?retention / ?legal-hold): modifies retention and legal hold in place on the target version without creating a new version or altering the object ETag. Shortening COMPLIANCE retention or switching COMPLIANCE to GOVERNANCE before expiration is rejected even for the S3 root user.
    • Governance bypass: requires both an explicit x-amz-bypass-governance-retention: true header and s3:BypassGovernanceRetention authorization evaluated per target version (plus UPDATE on the bucket ACL relation under iam_and_pg). Governance bypass never overrides COMPLIANCE retention or an active legal_hold.
    • SQL silo_api integration: silo_api.put_object and copy_object automatically apply default bucket retention on object-lock buckets, while silo_api.delete_object enforces retention and legal hold with no governance bypass parameter.
    • Force bucket deletion blocked: DELETE /{bucket} with x-minio-force-delete is rejected with HTTP 405 on any object-lock-enabled bucket, even when the bucket is empty.

2. Streaming keyset lifecycle scanner and executor

Instead of running the erasure-coded NSScanner, writable pgsilo gateways run a PostgreSQL-native lifecycle worker covering four rule actions (remote storage tiering Transition and RestoreObject are rejected at configuration time):

  1. Current version expiration (Expiration by Days or Date): deletes the current object in an unversioned bucket, inserts a delete marker in a versioned bucket (without duplicating an existing latest delete marker), or applies null-version expiration in a suspended bucket.
  2. Noncurrent version expiration (NoncurrentVersionExpiration): computes noncurrent age from the creation timestamp of the version’s successor (noncurrent_since), not the old version’s own mod_time, and preserves at least NewerNoncurrentVersions newer historical versions before deleting eligible versions.
  3. Expired object delete marker cleanup (ExpiredObjectDeleteMarker): removes a current delete marker when it is the only remaining version row for that key.
  4. Incomplete multipart upload cleanup (AbortIncompleteMultipartUpload): matches active uploads in silo.uploads by rule prefix and initiated age and aborts them atomically, cascading deletion of uploaded parts and segments.

To keep memory bounded, the scanner iterates over buckets and keys using keyset pagination ((key COLLATE "C", commit_seq) for objects and (key, initiated, upload_id) for multipart uploads) reading only metadata columns—never decrypting or loading SSE-C / SSE-S3 object bodies.

Before executing any deletion or marker insertion, the worker locks the target key (silo.lock_key), re-reads the current version chain and bucket lifecycle configuration revision, and re-verifies Object Lock protections. If a concurrent PUT, tag change, legal hold, or rule update occurred after the scan pass, the stale candidate becomes a safe no-op.

3. Multi-gateway maintenance leases and epoch fencing

When multiple writable gateways share a PostgreSQL primary, only one gateway should execute background lifecycle and annotation cleanup at a time, and a partitioned or paused leader must never commit stale deletions after another gateway takes over.

pgsilo coordinates background workers through a database lease table (silo.TryLifecycleLock) rather than a long-lived session advisory lock on the coordination pool:

  • Short-transaction lease claims and renewals: a writable primary gateway claims or renews the maintenance lease in a short transaction using PostgreSQL’s clock. Whenever a different gateway takes over an expired lease, the database increments a monotonic epoch counter.
  • Transactional epoch fencing: every destructive lifecycle or annotation-cleanup batch locks the lease row (FOR SHARE) inside the same transaction as the object/annotation deletion and verifies that (owner_id, epoch) still matches the worker’s lease and has not expired. If a new leader has incremented epoch, the old worker’s transaction aborts before committing.
  • Standby and read-only safety: gateways with SILO_PG_READ_ONLY=on or connected to a database where pg_is_in_recovery() = true never claim the maintenance lease. Lease ownership and errors are exported at /minio/metrics/v3/pg via minio_pg_lifecycle_leader and minio_pg_lifecycle_errors_total.

7 - Status review and baseline, 2026-11-08

Where pgsilo stood on 2026-11-08, why testing did not close, the runtime baseline on 299378b and the two fixes that followed.
Date
2026-11-08
Applies to
Frozen local delivery 3c7fdc03; baseline on 299378b; fixes up to 1d387725c (all on Silo branch feat/pg-backend, not pushed)
Finding
The feature scope was broad and well tested in October, but the evidence was split across candidates and the current source had never run. A GA-level gate set had kept testing open.
Led to
MVP goal
Replaces
Nothing; this is a review record

State before the review

Candidate identity was split. No single commit carried complete runtime evidence:

CommitWhat had run
dca464e5 (2026-10-07, schema 14)All functional gates: mint full HTTP 872 pass / 8 NA and HTTPS 947 pass / 7 NA, Ceph s3-tests 195/195, pgstore kernel 185 top-level / 326 tests on PostgreSQL 16, 17 and 18, cmd and erasure-coded regression 1,336 top-level / 6,913 tests, 32 application checks, 28 Console checks, 10 Pigsty checks, 35 upgrade and recovery checks, 11 STS, 15 native authorization, 36 A/Z and 5 multi-gateway checks
3c7fdc03 (2026-10-07, frozen delivery)Eight files (+99/−34) after dca464e5. Focused regression tests, the formal 3-round performance run (with SILO_PG_MAX_CONNS=72 and a Go SDK client for the 64-concurrency rows) and a 20-minute mixed preflight
299378b (2026-10-26)October upstream sync plus two review fixes: 158 files, +19,000/−2,035 lines after 3c7fdc03. Compiled and vetted only; no test had been executed

The frozen delivery was not publishable. 3c7fdc03 was based on Silo code from 2026-09-26 and lacked the October upstream fixes (IAM credential boundaries, scoped STS revocation, Object Lock authorization and others), built for ARM64 only, and reported the version DEVELOPMENT.GOGET. It had never been pushed.

Source entry points were broken. The working checkouts the delivery records pointed to had been removed, the documented compile script referred to missing paths, and the October test environment no longer existed.

The fork kept drifting. Against the synced upstream (RELEASE.2026-10-25), the backend added about 17,200 production lines (Go store, 14 SQL migrations, gateway code), modified 79 upstream production files (+1,922/−425), and added about 22,400 test lines. By 2026-11-08 Silo main had 138 further commits; 16 of the files they changed were also modified by the backend, including new ObjectOptions semantics.

Why testing did not close

  1. The goal was GA-level. It required stages 0–5, mint full, every application integration, HA, PITR and performance gates, and a 72-hour endurance run on the frozen candidate, with any later change to a persistence or concurrency path requiring the affected endurance to run again.
  2. Every change produced a new candidate. At least six candidates followed each other, and results were never carried across candidates without a fresh run.
  3. The performance gate measured the client. The 64-concurrency 4 KiB PUT target of 500 ops/s failed repeatedly with the Python client and passed only after the concurrency rows switched to the Go SDK.
  4. Most failures came from the test harness. Of 14 preflight runs, 2 passed, 11 failed (mostly fixture errors such as port timing, parameter encoding and credential limits; one real race, later fixed) and 1 was stopped. Of about 45 performance-related runs, 1 was a formal pass and about 25 tested the harness itself.
  5. Evidence outgrew the work. The run directory held 29,823 files (5.8 GB), including 95 self-verification receipts and 342 review documents.
  6. A real defect arrived late. On 2026-10-07 an IAM cache defect after failover (same revision, different content) led to schema 14 and a rerun of almost every gate.
  7. The endurance run came last. It could start only after everything else passed, and it was stopped at the user’s request after about 4.05 hours. It is not a 72-hour pass.

Decision

Three release forms were compared. Merging into Silo as an experimental backend was chosen, because it stops the fork drift and reuses the Silo release pipeline. A standalone release would make the drift permanent. An extension-only release is not possible, because the project has no PostgreSQL extension. The goal itself is recorded in MVP goal.

Runtime baseline on 299378b

The release checklist ran on 299378b on 2026-11-08 with PostgreSQL 18.6 and 16.15. Seven items passed: pgstore on both versions, mint core and full over HTTP and HTTPS (no failures; full-mode counts match October), Ceph 195/195, four client smokes, the Silo Console 2.6.0 smoke and an amd64 smoke under emulation. The cmd regression had one failing test. Details and the performance numbers are on Status.

Two environment effects were separated from product results: erasure-coded tests fail in bulk when the temporary directory’s disk is nearly full, and seven file-permission tests fail when run as root.

IAM snapshot assertion

TestPGIAMPolicyReadersKeepCompleteSnapshot failed in every run. Its last assertion, added during the October sync and never executed, expected a policy written directly with pgstore.PutSystem to stay outside the cache after ListPolicies. A control experiment wrote one policy and deleted another installed policy directly in storage, then compared two paths:

GroupOperationAdded policy visibleDeleted policy visibleInstalled / stored revisionCache replaced
Start—NoYes2 / 4—
AListPolicies onlyYesNo4 / 4Yes
BDeletePolicy onlyNoYes2 / 5No

The user, group, service-account and temporary-account list paths neither reloaded nor merged records.

Conclusion: PutSystem and DeleteSystem advance the stored revision, so the record was not outside it. In PostgreSQL mode, a policy listing reloads the complete snapshot at the stored revision and replaces the cache: additions and deletions appear together, and nothing is merged record by record. The behavior was the same on 3c7fdc03. Commit ca158fb6 rewrote the assertion to test that invariant, including the deleted record; product code was not changed.

Request queue

In PostgreSQL mode the request budget equals SILO_PG_MAX_CONNS (32 by default). Above it, builds up to 299378b answered HTTP 429 TooManyRequests at once, and the default retry rules of the AWS SDK for Go v2 and boto3 do not cover that response, so ordinary 64-client bursts failed.

Commit 1d387725c makes a request wait up to SILO_PG_QUEUE_TIMEOUT (5 s by default) for a free slot without holding a database connection, stops waiting when the client disconnects, and answers HTTP 503 SlowDown when the wait expires. Erasure-coded mode is unchanged. With the default pool, 64 clients ran PUT and GET for 90 s each with no failed request; with the wait disabled, the SDK retried the 503 responses but 160 PUT and 188 GET requests still failed. Ceph 195/195 and mint core over HTTPS (644 pass, 6 NA) showed no regression. Numbers are on Status.

What remained open

  • Merge prerequisites: the Silo release, the public silo-pkg annotation actions, and the user’s decision.
  • Release engineering: formal version string, amd64 and arm64 builds, DEB and RPM.
  • Known issues listed on Status.

8 - MVP goal

The 2026-11-08 goal: ship pgsilo as an experimental Silo backend, with a release checklist sized for an MVP.
Date
2026-11-08, approved by the user
Applies to
Silo branch feat/pg-backend from 299378b onward; current candidate 1d387725c
Replaces
The completion criteria of the original development goal (stages 0–5 up to a GA-level release candidate, including a 72-hour endurance run) and the 2026-10-08 local delivery freeze
Status
Current

Decision

The only completion criterion is an MVP release candidate. When it is reached, work stops and the result is reported; later phases do not start automatically. The stages and the GA-level release candidate of the original goal remain a roadmap after the MVP, not a completion criterion.

The reasons are recorded in Status review and baseline: by 2026-11-08 the feature work was broad, but no single commit carried complete runtime evidence, and a GA-level gate set kept the testing from closing.

Release form

  • pgsilo merges into Silo main as an experimental PostgreSQL storage backend and ships with standard Silo releases. A postgres:// or postgresql:// DSN, or SILO_PG_DSN, selects PostgreSQL mode.
  • There is no standalone pgsilo executable and no SQL-only release. An extension-only release was rejected: the project has no PostgreSQL extension, because the gateway installs and migrates the schema itself.
  • The frozen local delivery 3c7fdc03 stays an internal ARM64 preview and is not published.

Support tiers

TierScope
SupportedOne PostgreSQL primary with one or more writable gateways; PostgreSQL 16–18; linux/amd64 and linux/arm64
SupportedBucket and object CRUD, ListObjects V1/V2, versions and delete markers, conditional requests, Range, copy, tagging, multipart upload, checksums, presigned URLs, POST policy, CORS
SupportedIAM users, groups, policies and service accounts; SSE-C and static-key SSE-S3; object backup through PostgreSQL backup and PITR
PreviewSQL transaction API, PostgreSQL native authorization, STS, lifecycle, Object Lock, quotas, annotations and ZIP extraction, hot standby gateways
Not supportedSSE-KMS and external KMS, replication, tiering, erasure-coded disk management, S2 compression, etcd IAM, objects above 1 GiB, high-throughput workloads, RPO guarantees under automatic HA

The MVP uses the general Silo Console, without an annotation interface. Preview features ship with the release but may change without compatibility guarantees. The current tier table is on Compatibility.

Working principles

  1. Scope freeze. Only the listed work items and fixes for MVP-blocking problems. No new features, test layers, evidence formats or infrastructure.
  2. Proportional verification. Only functional and smoke tests that finish in minutes; the whole release checklist finishes in one to two hours. Long-running stability or endurance runs, full instrumentation matrices, repeated benchmark rounds, consistency tests that need a large external environment to be rebuilt, and diagnostic campaigns for rare intermittent failures are not done and are not gates after the MVP. The user raises them separately if needed.
  3. Honest results. Each check is recorded as pass, fail or not applicable, with the command and the location of the raw output. A failure is fixed or listed as a known issue with a statement of whether it blocks; the user decides. Failures are never hidden or silently waived.
  4. Performance. The MVP publishes measured baseline numbers and the test environment. There is no SLA, and performance does not block the release.
  5. Authorization. Local commits with DCO sign-off are allowed. Pushing, merging into Silo main, publishing packages or images, and deploying sites each need separate approval.

Release checklist

The checklist runs in full once the release candidate is frozen; during development only the items affected by a change run.

#Item
1internal/pgstore tests on PostgreSQL 18 and on PostgreSQL 16
2Regular Silo unit tests (go test, no race detector) to show that erasure-coded mode did not regress
3mint core once over HTTPS (covers SSE-C)
4Ceph s3-tests, 195 pinned cases
5Client smoke: mcli, AWS CLI v2, boto3, AWS SDK for Go v2
6Reduced performance smoke that takes minutes; numbers are recorded only
7General Silo Console 2.6.0 smoke against PostgreSQL mode
8Runtime smoke on linux/amd64

Items 2, 3 and 6 were narrowed on 2026-11-08 from an earlier draft that asked for race-enabled regression, mint full over both HTTP and HTTPS, and a 20-minute mixed preflight.

Merge prerequisites

  1. The current Silo release is published. feat/pg-backend is then synced to that release tag; upstream changes to files the backend also modifies, and new ObjectOptions semantics such as DeleteAllVersions, are implemented or explicitly rejected in PostgreSQL mode; the checklist runs again.
  2. The four annotation policy actions the server uses are published in the public silo-pkg, coordinated with the Server and Console releases, or handled another way. This needs the user’s approval.
  3. The user decides the merge.

Work items

#Work itemState on 2026-11-08
1Restore a working source checkout of feat/pg-backend that contains no unpublished Silo main commits, and repair broken build pathsDone
2Set up a lean test environment with PostgreSQL and gateways; rebuild the pinned mint and Ceph inputsDone
3Run the release checklist on 299378b to catch problems from the October upstream syncDone; see Status. Two fixes followed in ca158fb6 and 1d387725c
4Sync to the Silo release and rerun the checklistWaiting for the Silo release
5Release engineering (formal version string, amd64/arm64 builds, DEB and RPM) and release notes stating the experimental status, tiers, mint fixture revisions and not-applicable casesNot started

Deferred beyond the MVP

  • Automatic high availability: define the scope and the validation when it is needed.
  • The brief HTTP 503 window after an IAM change on another gateway, and Python client throughput.
  • The annotation interface in the general Console, and promoting Preview features to Supported.
  • Objects above 1 GiB, higher throughput, multi-architecture container images, and running the test harness in CI.