# Design decisions

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

---

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

---

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

## 1. The `ObjectLayer` seam {#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 {#data-model}

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 choice | Rationale |
| --- | --- |
| Shared tables keyed by `bucket_id` | Creating 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`) tables | `HEAD`, `ListObjectsV2`, and tag updates never touch segment pages; `silo.object_segments` tunes `autovacuum` independently |
| Fixed-size `bytea` segments (`8 MiB` default) with TOAST `lz4` | Bounds 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 deduplication | Every segment row belongs to one object version or one active upload (`ON DELETE CASCADE`), eliminating refcount hot spots |
{.wide}

## 3. Version ordering (`commit_seq`) and lock hierarchy {#state-machine-and-locks}

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 {#reads-copy-deletebucket}

- **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 {#rejected-alternatives}

| Alternative | Why 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 object | Requires 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 filesystem | Breaks unified `pgBackRest` backup, PITR, and stateless gateway failover |
| One PostgreSQL table or partition per bucket | `CREATE 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 counting | Introduces hash-lookup overhead and reference-count row contention on small writes (observed in `pgs3`) |
| Compiled C or Rust PostgreSQL extension | Cannot be installed on managed PostgreSQL services; standard SQL + PL/pgSQL suffices for all state transitions |
{.wide}

---

Backlinks:

- [Design](/docs/s3/design/)
