A sharded cluster on one machine
Starts a small sharded cluster on one machine so you can see how sharding works: three shard servers, each owning a third of the key space, a table whose rows are split across them by their primary key, and a gateway in front that speaks PostgreSQL and sends each statement to the shard that owns its key. Clients connect to the gateway as if it were one database. The links between the gateway and the shards use mutual TLS with certificates from one private authority. Everything runs in the background.
This is a test cluster on one host, not a multi-host production deployment.
Before you start
- The server and the gateway, 1.1.0 or later, from the
rasterizeddb-server-<version>-<platform>andrasterizeddb-gateway-<version>-<platform>release archives, which name themrasterizeddbandrasterizeddb-gateway(see Install and run a cluster). A build from source names themrasterizeddb_coreandrasterizeddb_gateway, so pass those withRDB_BINandRDB_GATEWAY_BIN. The script checks the server's--helpfor the sharding flags. opensslandpsql. On Windows, Git for Windows ships anopenssl.exe.- Free ports: 5440-5442 (PostgreSQL on each shard), 61180-61182 (native), 7400-7402 (gateway to shard) and 6432 (the gateway).
- A password in
RASTERIZEDDB_PG_PASSWORD. Every shard creates the rolerasterizedwith it, and the gateway checks logins against the first shard's roles.
Settings
| bash variable | PowerShell parameter | Default | What it does |
|---|---|---|---|
RDB_BIN | -RdbBin | rasterizeddb / rasterizeddb.exe | The server binary. |
RDB_GATEWAY_BIN | -GatewayBin | rasterizeddb-gateway / rasterizeddb-gateway.exe | The gateway binary. |
RDB_WORK | -Work | ./cluster | Holds tls/, cluster.map, gateway.conf, each shard's data directory, the logs and the .pid files. |
RDB_GATEWAY_PORT | -GatewayPort | 6432 | Where clients connect. |
RDB_PG_BASE | -PgBase | 5440 | Shard n's PostgreSQL port is this plus n. |
RDB_NATIVE_BASE | -NativeBase | 61180 | Shard n's native port is this plus n. |
RDB_RSHARD_BASE | -RshardBase | 7400 | Shard n's port for the gateway is this plus n. |
What the script does
-
Certificates. A private authority, and a certificate for each shard and for the gateway, valid for
localhostand127.0.0.1and for both server and client use. -
The shard map (
cluster.map): the cluster's id, and which shard owns which range of the 2^48 key space:textrasterizeddb shard map format 1 cluster 3f0c9a… epoch 1 route_v 1 shard 0 127.0.0.1:7400 shard 1 127.0.0.1:7401 shard 2 127.0.0.1:7402 range 0x0 0 range 0x555555555555 1 range 0xaaaaaaaaaaaa 2 -
Three shards, each started with
--role shard --cluster-map cluster.map --shard-id N --cluster-id <id> --shard-listen 127.0.0.1:740N, its certificate (--shard-cert,--shard-key), and the authority that signs the gateway's and the other shards' certificates (--gateway-ca,--peer-ca). A shard refuses reads and writes of keys outside its ranges. -
The schema on every shard:
CREATE TABLE orders (id INT PRIMARY KEY, store INT NOT NULL, v INT NOT NULL) PARTITION BY HASH (id). ThePARTITION BY HASHcolumn is the route key. The gateway refuses DDL, so schema changes go to every shard directly. -
The gateway, from
gateway.conf:textlisten = 127.0.0.1:6432 map = <work>/cluster.map home_shard = 0 shard_trust = ca:<work>/tls/ca.pem shard_cert = <work>/tls/gateway.pem shard_key = <work>/tls/gateway.key auth = scram unrouted = fan_out two_phase = onunrouted = fan_outlets a statement without a route key read every shard;two_phase = oncommits a write that spans shards with two-phase commit.home_shardis where logins are checked and global statements go.
Run it
export RASTERIZEDDB_PG_PASSWORD='change-me'
RDB_BIN=./rasterizeddb RDB_GATEWAY_BIN=./rasterizeddb-gateway ./setup.sh$env:RASTERIZEDDB_PG_PASSWORD = 'change-me'
.\setup.ps1 -RdbBin .\rasterizeddb.exe -GatewayBin .\rasterizeddb-gateway.exeRunning the script again reuses the certificates and the map and starts only what is not running.
Check that it works
Through the gateway, as one database. The gateway has no TLS of its own in this setup, hence sslmode=disable:
export PGPASSWORD='change-me'
psql "postgresql://rasterized@127.0.0.1:6432/postgres?sslmode=disable" \
-c "INSERT INTO orders (id, store, v) VALUES (37, 2, 370)" \
-c "INSERT INTO orders (id, store, v) VALUES (1001, 1, 10)" \
-c "SELECT v FROM orders WHERE id = 37" \
-c "SELECT count(*), sum(v) FROM orders"The keyed SELECT goes to one shard; the count(*) fans out to all three. To see where a row landed, ask the shards directly (they require TLS):
for n in 0 1 2; do psql "postgresql://rasterized@127.0.0.1:544$n/postgres?sslmode=require" -Atc "SELECT count(*) FROM orders"; doneSHOW GATEWAY, sent through the gateway, reports the map's epoch, the sessions and how many statements were routed and fanned out.
Stop or undo
kill $(cat cluster/*.pid)Get-Content .\cluster\*.pid | ForEach-Object { Stop-Process -Id $_ }Delete the cluster directory to start again from nothing.
Limits
- One machine, three shards, one gateway: enough to try routing, fan-out and two-phase commit, not a layout for production.
- A statement with no route key is refused (
0A000) unless it is a read underunrouted = fan_out. A multi-rowINSERT … VALUESis split by shard and committed in one two-phase transaction. - The gateway relays PostgreSQL clients only (and native clients through
native_listen, not set up here).LISTEN/NOTIFYand replication connections are not available through it.
The files
#!/usr/bin/env bash
# RasterizedDB: a sharded cluster on one machine, to try sharding. Three shard
# servers that trust one certificate authority, a shard map, a table split
# across them by its key, and a gateway in front that speaks PostgreSQL and
# routes each statement by key. Needs release 1.1.0 or later.
#
# Everything runs in the background, with logs and process ids in RDB_WORK.
# Running it again starts whatever is not running. Stop with:
# kill $(cat cluster/*.pid)
set -euo pipefail
RDB_BIN="${RDB_BIN:-rasterizeddb}"
RDB_GATEWAY_BIN="${RDB_GATEWAY_BIN:-rasterizeddb-gateway}"
RDB_WORK="${RDB_WORK:-./cluster}" # certificates, map, data, logs
RDB_GATEWAY_PORT="${RDB_GATEWAY_PORT:-6432}"
RDB_PG_BASE="${RDB_PG_BASE:-5440}" # shard n's PostgreSQL port is base + n
RDB_NATIVE_BASE="${RDB_NATIVE_BASE:-61180}" # shard n's native port is base + n
RDB_RSHARD_BASE="${RDB_RSHARD_BASE:-7400}" # shard n's gateway-facing port is base + n
SHARDS=(0 1 2)
die() { echo "error: $*" >&2; exit 1; }
command -v "$RDB_BIN" >/dev/null 2>&1 || die "'$RDB_BIN' not found; set RDB_BIN to the server binary (1.1.0 or later)"
command -v "$RDB_GATEWAY_BIN" >/dev/null 2>&1 || die "'$RDB_GATEWAY_BIN' not found; set RDB_GATEWAY_BIN to the gateway binary"
case "$("$RDB_BIN" --help)" in *--shard-listen*) ;; *) die "this $RDB_BIN has no sharding; it needs server 1.1.0 or later, built with the sharding feature" ;; esac
command -v openssl >/dev/null 2>&1 || die "openssl is needed for the certificates"
command -v psql >/dev/null 2>&1 || die "psql is needed to create the schema"
: "${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD; every shard gets the role rasterized with it}"
export RASTERIZEDDB_PG_PASSWORD PGPASSWORD="$RASTERIZEDDB_PG_PASSWORD"
mkdir -p "$RDB_WORK/tls"
cd "$RDB_WORK"
work="$PWD"
RDB_BIN="$(command -v "$RDB_BIN")"; RDB_BIN="$(cd "$(dirname "$RDB_BIN")" && pwd)/$(basename "$RDB_BIN")"
RDB_GATEWAY_BIN="$(command -v "$RDB_GATEWAY_BIN")"; RDB_GATEWAY_BIN="$(cd "$(dirname "$RDB_GATEWAY_BIN")" && pwd)/$(basename "$RDB_GATEWAY_BIN")"
running() { [ -f "$1.pid" ] && kill -0 "$(cat "$1.pid")" 2>/dev/null; }
wait_for() { # wait_for <port> <sslmode> <what> <pidfile>
for _ in $(seq 1 60); do
if psql "postgresql://rasterized@127.0.0.1:$1/postgres?sslmode=$2" -Atqc "SELECT 1" >/dev/null 2>&1; then
return 0
fi
kill -0 "$(cat "$4")" 2>/dev/null || die "$3 exited; see $work/${4%.pid}.log"
sleep 1
done
die "$3 did not answer on port $1 within 60 s; see $work/${4%.pid}.log"
}
# 1. Certificates: a CA, one for each shard and one for the gateway.
if [ ! -f tls/ca.pem ]; then
(
cd tls
umask 077
openssl req -x509 -newkey rsa:2048 -nodes -days 365 -subj /CN=rdb-cluster-ca -keyout ca.key -out ca.pem
printf 'subjectAltName=DNS:localhost,IP:127.0.0.1\nextendedKeyUsage=serverAuth,clientAuth\n' > ext.cnf
for name in shard0 shard1 shard2 gateway; do
openssl req -newkey rsa:2048 -nodes -subj "/CN=$name" -keyout "$name.key" -out "$name.csr"
openssl x509 -req -in "$name.csr" -CA ca.pem -CAkey ca.key -CAcreateserial -days 365 -extfile ext.cnf -out "$name.pem"
done
rm -f ./*.csr
)
fi
# 2. The shard map: which shard owns which slice of the 2^48 key space.
if [ ! -f cluster.map ]; then
cluster_id="$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')"
{
echo "rasterizeddb shard map"
echo "format 1"
echo "cluster $cluster_id"
echo "epoch 1"
echo "route_v 1"
for n in "${SHARDS[@]}"; do echo "shard $n 127.0.0.1:$((RDB_RSHARD_BASE + n))"; done
echo "range 0x0 0"
echo "range 0x555555555555 1"
echo "range 0xaaaaaaaaaaaa 2"
} > cluster.map
fi
cluster_id="$(sed -n 's/^cluster //p' cluster.map)"
# 3. Three shards.
for n in "${SHARDS[@]}"; do
if running "shard$n"; then echo "shard $n is running"; continue; fi
mkdir -p "shard$n"
nohup "$RDB_BIN" --location "$work/shard$n" --protocol both \
--pg-port $((RDB_PG_BASE + n)) --rdb-port $((RDB_NATIVE_BASE + n)) \
--role shard --cluster-map "$work/cluster.map" --shard-id "$n" --cluster-id "$cluster_id" \
--shard-listen "127.0.0.1:$((RDB_RSHARD_BASE + n))" \
--shard-cert "$work/tls/shard$n.pem" --shard-key "$work/tls/shard$n.key" \
--gateway-ca "$work/tls/ca.pem" --peer-ca "$work/tls/ca.pem" \
--log-level info > "shard$n.log" 2>&1 &
echo $! > "shard$n.pid"
echo "started shard $n (pid $!)"
done
for n in "${SHARDS[@]}"; do wait_for $((RDB_PG_BASE + n)) require "shard $n" "shard$n.pid"; done
# 4. The schema, on every shard. A table's PARTITION BY HASH column is its
# route key. The gateway refuses DDL, so schema changes go to every shard.
for n in "${SHARDS[@]}"; do
psql "postgresql://rasterized@127.0.0.1:$((RDB_PG_BASE + n))/postgres?sslmode=require" -v ON_ERROR_STOP=1 -q \
-c "CREATE TABLE IF NOT EXISTS orders (id INT PRIMARY KEY, store INT NOT NULL, v INT NOT NULL) PARTITION BY HASH (id)"
done
# 5. The gateway.
cat > gateway.conf <<EOF
listen = 127.0.0.1:$RDB_GATEWAY_PORT
map = $work/cluster.map
home_shard = 0
shard_trust = ca:$work/tls/ca.pem
shard_cert = $work/tls/gateway.pem
shard_key = $work/tls/gateway.key
auth = scram
unrouted = fan_out
two_phase = on
EOF
if running gateway; then
echo "the gateway is running"
else
nohup "$RDB_GATEWAY_BIN" --config "$work/gateway.conf" > gateway.log 2>&1 &
echo $! > gateway.pid
echo "started the gateway (pid $!)"
fi
wait_for "$RDB_GATEWAY_PORT" disable gateway gateway.pid
echo
echo "Cluster $cluster_id is up. Connect through the gateway, as one database:"
echo " psql \"postgresql://rasterized@127.0.0.1:$RDB_GATEWAY_PORT/postgres?sslmode=disable\""
echo "Logs and pids: $work. Stop with: kill \$(cat $work/*.pid)"#Requires -Version 5.1
<#
.SYNOPSIS
RasterizedDB: a sharded cluster on one machine, to try sharding. Three shard
servers that trust one certificate authority, a shard map, a table split
across them by its key, and a gateway in front that speaks PostgreSQL and
routes each statement by key. Needs release 1.1.0 or later.
.DESCRIPTION
Everything runs in the background, with logs and process ids in -Work.
Running it again starts whatever is not running. Stop with:
Get-Content .\cluster\*.pid | ForEach-Object { Stop-Process -Id $_ }
.EXAMPLE
$env:RASTERIZEDDB_PG_PASSWORD = 'change-me'
.\setup.ps1 -RdbBin .\rasterizeddb.exe -GatewayBin .\rasterizeddb-gateway.exe
#>
[CmdletBinding()]
param(
[string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }),
[string]$GatewayBin = $(if ($env:RDB_GATEWAY_BIN) { $env:RDB_GATEWAY_BIN } else { 'rasterizeddb-gateway.exe' }),
# Certificates, map, data, logs.
[string]$Work = $(if ($env:RDB_WORK) { $env:RDB_WORK } else { '.\cluster' }),
[int]$GatewayPort = $(if ($env:RDB_GATEWAY_PORT) { [int]$env:RDB_GATEWAY_PORT } else { 6432 }),
# Shard n's ports are base + n.
[int]$PgBase = $(if ($env:RDB_PG_BASE) { [int]$env:RDB_PG_BASE } else { 5440 }),
[int]$NativeBase = $(if ($env:RDB_NATIVE_BASE) { [int]$env:RDB_NATIVE_BASE } else { 61180 }),
[int]$RshardBase = $(if ($env:RDB_RSHARD_BASE) { [int]$env:RDB_RSHARD_BASE } else { 7400 })
)
$ErrorActionPreference = 'Stop'
$shards = 0, 1, 2
$server = Get-Command $RdbBin -ErrorAction SilentlyContinue
if (-not $server) { throw "'$RdbBin' not found; pass -RdbBin with the server binary (1.1.0 or later)." }
$gateway = Get-Command $GatewayBin -ErrorAction SilentlyContinue
if (-not $gateway) { throw "'$GatewayBin' not found; pass -GatewayBin with the gateway binary." }
if (-not ((& $server.Source --help) -match '--shard-listen')) { throw "This $RdbBin has no sharding; it needs server 1.1.0 or later, built with the sharding feature." }
$openssl = Get-Command openssl -ErrorAction SilentlyContinue
if (-not $openssl) { throw 'openssl is needed for the certificates (Git for Windows has one in C:\Program Files\Git\usr\bin).' }
if (-not (Get-Command psql -ErrorAction SilentlyContinue)) { throw 'psql is needed to create the schema.' }
if (-not $env:RASTERIZEDDB_PG_PASSWORD) { throw 'Set $env:RASTERIZEDDB_PG_PASSWORD; every shard gets the role rasterized with it.' }
$env:PGPASSWORD = $env:RASTERIZEDDB_PG_PASSWORD
New-Item -ItemType Directory -Force -Path (Join-Path $Work 'tls') | Out-Null
$Work = (Resolve-Path -LiteralPath $Work).Path
$tls = Join-Path $Work 'tls'
function Join-Args([string[]]$Items) {
($Items | ForEach-Object {
if ($_ -notmatch '[\s"]') { $_ } else { '"' + ($_ -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"' }
}) -join ' '
}
function Test-Running([string]$Name) {
$pidFile = Join-Path $Work "$Name.pid"
if (-not (Test-Path -LiteralPath $pidFile)) { return $false }
return [bool](Get-Process -Id ([int](Get-Content -LiteralPath $pidFile)) -ErrorAction SilentlyContinue)
}
function Start-Background([string]$Name, [string]$Exe, [string[]]$Arguments) {
$p = Start-Process -FilePath $Exe -ArgumentList (Join-Args $Arguments) -WindowStyle Hidden -PassThru `
-RedirectStandardOutput (Join-Path $Work "$Name.out.log") -RedirectStandardError (Join-Path $Work "$Name.log")
Set-Content -LiteralPath (Join-Path $Work "$Name.pid") -Value $p.Id
Write-Host "started $Name (pid $($p.Id))"
}
function Wait-For([int]$Port, [string]$SslMode, [string]$Name) {
for ($i = 0; $i -lt 60; $i++) {
# Windows PowerShell turns a native program's stderr into errors when
# it is redirected, so relax the preference around the probe.
$saved = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
& psql "postgresql://rasterized@127.0.0.1:$Port/postgres?sslmode=$SslMode" -Atqc 'SELECT 1' 2>$null | Out-Null
$code = $LASTEXITCODE
$ErrorActionPreference = $saved
if ($code -eq 0) { return }
if (-not (Test-Running $Name)) { throw "$Name exited; see $Work\$Name.log" }
Start-Sleep -Seconds 1
}
throw "$Name did not answer on port $Port within 60 s; see $Work\$Name.log"
}
# 1. Certificates: a CA, one for each shard and one for the gateway.
if (-not (Test-Path -LiteralPath (Join-Path $tls 'ca.pem'))) {
Push-Location $tls
try {
& $openssl.Source req -x509 -newkey rsa:2048 -nodes -days 365 -subj /CN=rdb-cluster-ca -keyout ca.key -out ca.pem
if ($LASTEXITCODE -ne 0) { throw 'openssl could not make the CA.' }
Set-Content -LiteralPath ext.cnf -Value "subjectAltName=DNS:localhost,IP:127.0.0.1`nextendedKeyUsage=serverAuth,clientAuth`n" -Encoding ascii -NoNewline
foreach ($name in 'shard0', 'shard1', 'shard2', 'gateway') {
& $openssl.Source req -newkey rsa:2048 -nodes -subj "/CN=$name" -keyout "$name.key" -out "$name.csr"
if ($LASTEXITCODE -ne 0) { throw "openssl could not make the key for $name." }
& $openssl.Source x509 -req -in "$name.csr" -CA ca.pem -CAkey ca.key -CAcreateserial -days 365 -extfile ext.cnf -out "$name.pem"
if ($LASTEXITCODE -ne 0) { throw "openssl could not sign the certificate for $name." }
Remove-Item -LiteralPath "$name.csr"
}
}
finally { Pop-Location }
}
# 2. The shard map: which shard owns which slice of the 2^48 key space.
$mapFile = Join-Path $Work 'cluster.map'
if (-not (Test-Path -LiteralPath $mapFile)) {
$clusterId = -join ((1..32) | ForEach-Object { '{0:x}' -f (Get-Random -Maximum 16) })
$lines = @('rasterizeddb shard map', 'format 1', "cluster $clusterId", 'epoch 1', 'route_v 1')
$lines += $shards | ForEach-Object { "shard $_ 127.0.0.1:$($RshardBase + $_)" }
$lines += @('range 0x0 0', 'range 0x555555555555 1', 'range 0xaaaaaaaaaaaa 2')
Set-Content -LiteralPath $mapFile -Value $lines -Encoding ascii
}
$clusterId = ((Get-Content -LiteralPath $mapFile) | Where-Object { $_ -match '^cluster ' }) -replace '^cluster ', ''
# 3. Three shards.
foreach ($n in $shards) {
if (Test-Running "shard$n") { Write-Host "shard $n is running"; continue }
$dir = Join-Path $Work "shard$n"
New-Item -ItemType Directory -Force -Path $dir | Out-Null
Start-Background "shard$n" $server.Source @(
'--location', $dir, '--protocol', 'both',
'--pg-port', "$($PgBase + $n)", '--rdb-port', "$($NativeBase + $n)",
'--role', 'shard', '--cluster-map', $mapFile, '--shard-id', "$n", '--cluster-id', $clusterId,
'--shard-listen', "127.0.0.1:$($RshardBase + $n)",
'--shard-cert', (Join-Path $tls "shard$n.pem"), '--shard-key', (Join-Path $tls "shard$n.key"),
'--gateway-ca', (Join-Path $tls 'ca.pem'), '--peer-ca', (Join-Path $tls 'ca.pem'),
'--log-level', 'info')
}
foreach ($n in $shards) { Wait-For ($PgBase + $n) 'require' "shard$n" }
# 4. The schema, on every shard. A table's PARTITION BY HASH column is its
# route key. The gateway refuses DDL, so schema changes go to every shard.
foreach ($n in $shards) {
& psql "postgresql://rasterized@127.0.0.1:$($PgBase + $n)/postgres?sslmode=require" -v ON_ERROR_STOP=1 -q `
-c 'CREATE TABLE IF NOT EXISTS orders (id INT PRIMARY KEY, store INT NOT NULL, v INT NOT NULL) PARTITION BY HASH (id)'
if ($LASTEXITCODE -ne 0) { throw "Could not create the table on shard $n." }
}
# 5. The gateway.
$conf = Join-Path $Work 'gateway.conf'
@(
"listen = 127.0.0.1:$GatewayPort",
"map = $mapFile",
'home_shard = 0',
"shard_trust = ca:$(Join-Path $tls 'ca.pem')",
"shard_cert = $(Join-Path $tls 'gateway.pem')",
"shard_key = $(Join-Path $tls 'gateway.key')",
'auth = scram',
'unrouted = fan_out',
'two_phase = on'
) | Set-Content -LiteralPath $conf -Encoding ascii
if (Test-Running 'gateway') { Write-Host 'the gateway is running' }
else { Start-Background 'gateway' $gateway.Source @('--config', $conf) }
Wait-For $GatewayPort 'disable' 'gateway'
Write-Host ''
Write-Host "Cluster $clusterId is up. Connect through the gateway, as one database:"
Write-Host " psql `"postgresql://rasterized@127.0.0.1:$GatewayPort/postgres?sslmode=disable`""
Write-Host "Logs and pids: $Work. Stop with: Get-Content $Work\*.pid | ForEach-Object { Stop-Process -Id `$_ }"