2026-10-03 20:34:27 +00:00
2026-09-30 01:23:23 +00:00
2026-09-30 01:23:23 +00:00
2026-09-30 01:23:23 +00:00
2026-09-30 01:23:23 +00:00
2026-09-30 01:23:23 +00:00
2026-09-30 01:23:23 +00:00
2026-09-30 01:23:23 +00:00
2026-09-30 01:23:23 +00:00

Diamond 💎✨

Diamond is a Go session proxy plus a PostgreSQL sharding topology provisioner. it supports shard-key routing and cross-shard SQL by using a PostgreSQL 18 coordinator with native hash partitioning and postgres_fdw workers.

flowchart LR
    client[PostgreSQL client] --> Proxy[Go session proxy]
    proxy --> Coordinator[PostgreSQL coordinator]
    coordinator -->|hash partition 0| Worker0[PostgreSQL worker 0]
    coordinator -->|hash partition 1| Worker1[PostgreSQL worker 1]

run the example

requires Docker with Compose. the example is for local development, uses an administrator role, and disables database TLS. The exposed port is loopback-only.

export DIAMOND_DB_PASSWORD="$(openssl rand -hex 24)"
docker compose up -d --build coordinator worker0 worker1 proxy
docker compose run --rm provision
PGPASSWORD="$DIAMOND_DB_PASSWORD" psql -v ON_ERROR_STOP=1 -h 127.0.0.1 -p 6432 -U diamond -d diamond -f examples/schema.sql
PGPASSWORD="$DIAMOND_DB_PASSWORD" psql -h 127.0.0.1 -p 6432 -U diamond -d diamond -f examples/queries.sql

provision once on fresh databases. Named volumes retain the topology and data; keep the same password when restarting. docker compose down stops the example. changing the environment variable does not change existing database passwords.

to run the Go program directly:

go build -o bin/diamond ./cmd/diamond
bin/diamond plan -config examples/diamond.json
export DIAMOND_COORDINATOR_DSN='host=127.0.0.1 port=5432 user=admin dbname=app sslmode=verify-full'
# Set PGPASSWORD and the workers' password-env variables in your environment.
# Edit worker hosts, ports, identities, coordinator-role, and TLS settings first.
bin/diamond apply -config diamond.json
bin/diamond serve -listen 127.0.0.1:6432 -coordinator 127.0.0.1:5432

the proxy itself needs only the coordinator address. PostgreSQL authenticates each client; client credentials and TLS remain end to end. the server certificate must be valid for the hostname the client uses to reach the proxy. worker TLS is configured separately in the topology; use verify-full with trusted CA material available to both the provisioner and coordinator in production.

Kubernetes

the Diamond Helm chart deploys the proxy, a persistent postgreSQL 18 coordinator and workers, and an installation-only provisioning Job. it also supports deploying only the proxy against an existing coordinator. see the chart guide for image builds, credentials, storage and native coordination.

live DDL

provision the worker connections first, then issue ordinary DDL through the proxy as the configured ddl-role (defaults to coordinator-role). no schema-sql or table column definitions are required in configuration. JSON and YAML both use the same hyphenated keys; see examples/diamond.json and examples/diamond.yaml.

CREATE TYPE public.state AS ENUM ('new', 'done');

CREATE TABLE public.events (
    tenant_id bigint NOT NULL,
    id bigint NOT NULL,
    state public.state DEFAULT 'new'
) PARTITION BY HASH (tenant_id);

ALTER TABLE public.events ADD COLUMN description text;
ALTER TYPE public.state ADD VALUE 'archived';
CREATE INDEX events_state_idx ON public.events(state);

the coordinator forwards each supported DDL statement to every worker. For CREATE TABLE ... PARTITION BY HASH, it also creates the real worker partitions and matching coordinator foreign partitions. ordinary non-partitioned tables have their definitions copied, but their data is coordinator-local. temporary tables remain session-local. existing installations can enable this without reprovisioning tables using the original administrator credentials:

bin/diamond enable-ddl -config diamond.yaml

DDL propagation uses PostgreSQL event triggers and private foreign command tables. a worker trigger executes DDL on its FDW connection, in the same remote transaction used by the coordinator. worker errors abort the statement; rollback and savepoints undo its DDL on the participating nodes. the original search path (including resolved $user) and relevant parsing settings are carried to the workers. the TCP proxy remains transparent, including TLS and extended queries. a transaction-scoped advisory lock serializes migrations. Without the optional coordination module, failures during commit can leave partial commits. enable the module below for a durable distributed commit protocol.

send one top-level DDL statement per client message. Transactions may contain many statements, sent separately; psql -f and psql --single-transaction -f do this. batches such as CREATE TYPE ...; CREATE TABLE ... in one driver call are rejected before worker execution. DDL inside DO, functions, extension scripts, and SQL-standard BEGIN ATOMIC function bodies is not supported; dollar-quoted function definitions with semicolons are supported.

forwarded command families are CREATE/ALTER/DROP for schemas, types, domains, tables, indexes, functions, procedures, views and sequences, plus COMMENT, GRANT and REVOKE. PostgreSQL/FDW restrictions still apply, including foreign-partition constraints and some ALTER TABLE operations. extensions, materialized views and other event-trigger command families currently return an explicit unsupported error for the migration role. global commands such as CREATE ROLE, CREATE DATABASE, tablespaces and ALTER SYSTEM do not generate PostgreSQL DDL events and are not forwarded; manage those per node. manual changes to the generated partition topology are rejected.

ordinary CREATE INDEX on a distributed table builds a physical index on each worker shard. expressions, partial indexes, INCLUDE, access methods and index options use PostgreSQL's normal syntax. ALTER INDEX and DROP INDEX propagate too. index definitions use PostgreSQL's deparser and the coordinator's chosen name, so unnamed indexes have consistent names across nodes. IF NOT EXISTS does nothing when the name already exists on the coordinator; it does not repair missing worker indexes. ON ONLY retains PostgreSQL's metadata-only behavior. CONCURRENTLY is rejected before index DDL runs. with coordination enabled, ordinary CREATE UNIQUE INDEX enforces global uniqueness on single or composite column keys, even without the shard key. it supports WHERE predicates, INCLUDE and NULLS NOT DISTINCT; expression keys and explicit collation/operator-class overrides are currently rejected. the visible index and worker indexes serve lookups; uniqueness lives in a private coordinator key table. see the unique-index lifecycle and catalog limits. existing installations should run enable-ddl after upgrading; unique indexes also require the updated native module and enable-coordination in maintenance.

for example, CREATE UNIQUE INDEX only_active_users ON users(id) WHERE activated = true enforces uniqueness across workers only for active users. updates that activate a user claim its key; deactivation or deletion releases it. a false or NULL predicate excludes the row. partial unique indexes cannot be foreign-key targets.

ddl-role must already exist and have normal PostgreSQL ownership/CREATE privileges for its migrations. it is a trusted administrator identity: worker DDL runs as the configured worker login, and object ownership there follows that login. prefer a separate migration role from the application runtime role. only DDL executed as this exact effective role is propagated; other roles retain coordinator-local DDL behavior. internal helpers and command tables are private. the installer needs coordinator superuser privileges to create event triggers; enable-ddl is intended for a maintenance window and refuses changes to the registered worker order/count.

cross-shard foreign keys

the optional PostgreSQL 18 diamond_fdw module keeps writes as ordinary SQL through the proxy. it prepares worker transactions, records a durable coordinator commit decision, and recovers incomplete commits before allowing dependent access. typed key tables provide global primary/unique keys and cross-shard foreign keys, including composite keys and deferred foreign-key checks.

install with make native-install, disconnect coordinator clients for maintenance, then run diamond enable-coordination -config diamond.yaml. the Compose coordinator already includes the library; after provisioning, run:

docker compose run --rm provision enable-coordination -config /config/diamond.json

declare PRIMARY KEY, UNIQUE and REFERENCES inline, or use table constraints:

CREATE TABLE bar (id bigint PRIMARY KEY) PARTITION BY HASH (id);
CREATE TABLE foo (
    id bigint PRIMARY KEY,
    bar_id bigint REFERENCES bar(id)
) PARTITION BY HASH (id);

named ALTER TABLE ... ADD CONSTRAINT ... PRIMARY KEY/UNIQUE/FOREIGN KEY remains supported for existing tables. existing installations should rebuild the native module and run enable-ddl followed by enable-coordination during maintenance. this initial mode serializes distributed transactions, requires READ COMMITTED/read-write sessions, and supports self-referential foreign keys with NO ACTION, RESTRICT, ON DELETE CASCADE and ON UPDATE CASCADE. cascades update the actual rows across workers in the same transaction. referenced keys may be Diamond global keys or native primary/unique keys on permanent ordinary coordinator tables. updates that would move rows between shards remain unsupported, including cascaded updates. SET NULL/DEFAULT actions, general schema changes while constraints exist, and transparent constraint catalog/backup equivalence are not implemented. run diamond recover -interval 1s with the administrator DSN for recovery during idle periods. the decision log must be retained.

see installation, protocol, supported SQL and operational limits before enabling it. workers require prepared transactions and durable WAL; application writes must all use the coordinator.

routing and execution

each configured table becomes a partitioned table on the coordinator, with one foreign hash partition per worker. every worker has a matching local parent and one real partition that enforces the same hash bound. hashing is PostgreSQL's native hashing, including composite keys; it is not key % workers or a Go hash function. nullable keys follow PostgreSQL's native partition rules. Shard-key types must have hash functions that produce identical results on every node. use built-in value types such as bigint, text or UUID; enum keys and other keys hashed using node-local OIDs are unsuitable when those OIDs differ. custom types in non-key columns do not have this hash restriction.

predicates on the shard key can prune irrelevant workers at planning or execution time, including generic prepared statements with bound parameters. predicates that cannot be pruned safely scan all relevant partitions. inserts and supported updates are routed using the same partition bounds. an unavailable required worker produces an error, never a successful partial result.

postgreSQL evaluates global ordering, limits, aggregates, joins, window frames, subqueries and other supported constructs on the complete logical relation. postgres_fdw pushes down eligible operations; other work runs on the coordinator. cross-shard joins and windows can transfer substantial data to the coordinator, which is a capacity bottleneck and a single point of failure.

custom type DDL is forwarded to all nodes; columns accept PostgreSQL type declarations. the coordinator owns the client-visible type IDs. worker type IDs may differ because postgres_fdw handles conversion. enum, domain, composite and custom-type array round trips are exercised in the integration suite. matching type definitions, collations, extensions and versions remain the operator's responsibility. arbitrary extensions are not certified.

the transport streams bytes without buffering entire messages or switching a session between servers. this preserves transaction/session state, simple and extended queries, prepared statements, pipelining, COPY, notifications, errors, TLS, authentication and cancellation. Keep the upstream address pinned to one coordinator: a round-robin address could send cancellation to the wrong server. at the connection limit new connections are closed, including cancellation connections; reserve capacity accordingly. SIGINT/SIGTERM closes active sessions and waits for relay goroutines. this is immediate shutdown, not transaction drain.

limitations

Feature Behavior / limitation
GROUP BY, HAVING, window functions, joins, CTEs, set operations Executed by the PostgreSQL planner across foreign partitions; tested against an independent local reference table.
transactions and savepoints stock mode has no atomic cross-worker commit. optional diamond_fdw coordination uses prepared worker transactions and durable recovery, serializing distributed transactions; see coordination.
constraints bounds and NOT NULL/domain checks work in stock mode. coordination adds global primary/unique keys and cross-shard FKs through CREATE TABLE or named ALTER TABLE constraints and typed coordinator key tables. supported forms and limitations are documented below.
upserts / MERGE coordination supports INSERT ... ON CONFLICT with DO NOTHING/DO UPDATE and RETURNING using registered global keys; see supported forms and limits. stock postgres_fdw restrictions still apply without coordination. MERGE is unsupported.
changing a shard key moving a row out of a foreign partition with UPDATE is unsupported. a move is rejected by the worker partition constraint; this failure and savepoint recovery are tested. use an explicit delete/insert migration with the transaction limitations above.
DDL supported DDL from ddl-role is forwarded to every worker. hash-partitioned tables are sharded automatically; see the live-DDL restrictions above.
defaults, sequences, triggers, functions use explicit distributed designs. sequences and node-local side effects are not globally coordinated. Avoid independent sequence defaults on workers.
row security and permissions client auth and coordinator grants are preserved, but remote execution uses the configured mapped worker identity. do not assume worker RLS sees the original client role.
LISTEN/NOTIFY, advisory locks, catalogs, temporary tables coordinator-local semantics. notifications and locks are not broadcast to workers.
replication / backup wire transport is opaque, but coordinator replication or backup alone does not include worker data. no cluster-wide replication/restore implementation.
rebalancing and high availability fixed worker order and hash modulus. no automatic resharding, worker discovery, pooling, failover, or query retries.

these are architectural limits, not TODOs that a more permissive SQL parser would fix. see PostgreSQL's foreign data wrapper documentation and partitioning documentation.

configuration and provisioning

examples/diamond.json demonstrates connection configuration. worker order fixes hash remainders. a table named orders gets generated relations orders_shard_0, orders_shard_1, etc.; names are validated against PostgreSQL's 63-byte identifier limit and collisions.

for compatibility, the old optional schema-sql and tables bootstrap fields still work. within those legacy tables, shard-key is a list of column names, and column type and default contain trusted administrator SQL. new setups can omit both fields and use normal SQL migrations instead. identifiers and connection values are quoted. unknown JSON/YAML fields and invalid topology entries are rejected.

plan prints DDL and user-mapping metadata as JSON without resolving passwords. apply obtains passwords from the named environment variables, applies each worker in a local transaction, then publishes the coordinator in its own local transaction. it grants table/schema/server access and creates a user mapping for coordinator-role, which must already exist. provisioning requires suitable DDL privileges, including coordinator superuser access for event triggers. it also creates private DDL receivers and mappings for the migration role and installer. the automatic path uses the configured worker identity to create worker tables. for separate runtime/administrator identities, review the plan, provision with administrator accounts and grant the runtime identity the required permissions.

provisioning is not atomic across nodes. If a later node fails, earlier worker DDL stays committed; the error identifies the failing node. Inspect the topology before cleanup and retry. existing tables and servers deliberately cause an error; apply does not migrate, drop, overwrite, or change an existing topology. never change worker order or count without an explicit data migration.

tests

requires Go 1.27.1. Unit tests cover forwarding concurrent arbitrary byte streams, half-closes, blocked-write shutdown, backend loss, connection limits, validation, SQL quoting and configuration fuzz seeds. No database is required for these.

go test -race ./...
go test ./shard -fuzz=FuzzDecode -fuzztime=10s

the integration suite requires PostgreSQL 18 binaries, postgres_fdw, server development headers, libpq headers, a C compiler and Python 3. make check builds the native module with test-only crash hooks. it creates three independent temporary clusters, with SCRAM passwords, certificates, worker TLS and a real running Go proxy. It starts and stops its own servers; no existing database or Docker is needed. missing binaries cause a failure rather than a silently skipped test.

the crash tests intentionally terminate servers and their connections. SSL EOF and connection-reset messages are expected around those crashes. each server start waits up to two minutes for recovery, with a longer enclosing process deadline; make check, make integration and the root CI run allow 15 minutes for the suite. these limits accommodate recovery fsyncs on slow container storage while keeping fsync and full_page_writes enabled.

root CI runners are supported: the harness runs initdb, pg_ctl and the servers as the existing OS account postgres. Set PG_TEST_USER to use a different non-root account. Cluster directories are private, owned by that account and created under /var/tmp by default; passwords, TLS keys and a copy of the native module receive the same ownership. The checkout's permissions are unchanged. Non-root runners continue to use their own identity and respect TMPDIR.

set PG_TEST_TMPDIR to choose the storage directory for PostgreSQL clusters for either kind of runner. it takes precedence over TMPDIR; the directory must already exist and, when running as root, be traversable by PG_TEST_USER, including all its parent directories. CI uses /var/tmp to avoid a small /tmp tmpfs. clusters are stopped and removed by test cleanup, including failed starts. on No space left on device, check both free bytes (df -h) and free inodes (df -i) on the selected filesystem, or choose a larger mounted volume. the harness reports both when a PostgreSQL command fails. /var/tmp can also fill up; this setting does not increase the runner's storage capacity.

PG_BIN=/usr/lib/postgresql/18/bin PG_TEST_TMPDIR=/var/tmp make check

integration coverage includes comparisons against independently populated local tables for global SQL semantics, physical row placement, partition pruning with constants and generic prepared parameters, compound/nullable shard keys, binary custom-type results with different type IDs on workers, commit/rollback/savepoints, rejected shard-key movement, binary COPY IN and text COPY OUT, COPY failure recovery, TLS verification, invalid passwords, pipeline results, error recovery, session state, notifications, cancellation, concurrent clients, partial worker failure, and provisioning failures. a separate live-DDL cluster suite tests SQL-only schema setup, automatic hash partitions, ALTER/DROP, custom types, quoted names, function bodies, search paths, TLS/extended queries, rollback/savepoints, worker errors/outages, unsupported batches, private helpers and repeatable upgrades. CI runs the same real-cluster suite with the race detector, including a run with a root test process to verify privilege dropping, file ownership and cleanup. passing these tests is not a claim of support for every PostgreSQL feature or every extension.

S
Description
a postgres session proxy + sharding topology provisioner that glitters and glows! ✨
Readme
714 KiB
Languages
C 67.6%
Go 25.2%
PLpgSQL 4.5%
Python 2%
Go Template 0.4%
Other 0.2%