NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / SETUP SCRIPTS / TABLES STORED IN S3

Tables stored in S3

Keeps chosen tables in an S3 bucket instead of local files: large, rarely changed or archival tables, on a machine with little disk. The script defines a key/value store on a running server with STORAGE ADD STORE, then puts tables on it, either before they are created (STORAGE PLACE TABLE) or by moving existing ones (STORAGE MOVE TABLE). Everything else about the tables stays the same: the same SQL, the same results. Any S3-compatible store works: AWS, MinIO, Ceph, Cloudflare R2, Backblaze B2, Wasabi.

Before you start

  • A running server (any recipe), and psql on the machine running the script.
  • A superuser role's password in PGPASSWORD, for example the rasterized role's.
  • A bucket. Credentials for it either in the server's environment (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY set where the server was started), which is the default, or given to the store itself with RDB_STORE_OWN_KEYS=1.
  • A prefix in the bucket that no other server uses. Two servers writing one prefix corrupt each other's tables, and nothing stops them.

Settings

bash variablePowerShell parameterDefaultWhat it does
RDB_PG_URL-PgUrlpostgresql://rasterized@127.0.0.1:5432/postgres?sslmode=requireThe server to configure.
RDB_STORE_NAME-StoreNamearchiveThe store's name; tables are placed at kv:<name>.
RDB_STORE_ENDPOINT-Endpointhttps://s3.us-east-1.amazonaws.comThe store's URL, for example http://minio.internal:9000.
RDB_STORE_REGION-Regionus-east-1The region requests are signed for.
RDB_STORE_BUCKET-BucketrequiredThe bucket.
RDB_STORE_PREFIX-Prefixrdb/archiveThe key prefix in the bucket. One server per prefix.
RDB_STORE_ADDRESSING-Addressingvirtualpath for MinIO and bucket names that are not DNS-safe.
RDB_STORE_CACHE-Cache256MiBMemory for this store's pages.
RDB_STORE_OWN_KEYS=1-OwnKeysoffGive the store AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY from the shell running the script, so it does not use the server's.
RDB_PLACE_TABLES-PlaceTablesnoneTables to create on the store. Place them, then CREATE TABLE them.
RDB_MOVE_TABLES-MoveTablesnoneExisting tables to move onto the store.

Credentials given to a store are kept in db_kv_secrets.cfg in the data directory (mode 0600), never in db_kv.cfg or in SHOW output. The statements are sent to psql on standard input, so the keys do not appear in the process list.

Run it

sh
export PGPASSWORD='use-a-long-secret'
RDB_STORE_BUCKET=my-tables RDB_PLACE_TABLES="events audit_log" ./setup.sh
# MinIO, moving an existing table:
RDB_STORE_ENDPOINT=http://minio.internal:9000 RDB_STORE_ADDRESSING=path RDB_STORE_BUCKET=tables \
  RDB_MOVE_TABLES=old_orders ./setup.sh
powershell
$env:PGPASSWORD = 'use-a-long-secret'
.\setup.ps1 -Bucket my-tables -PlaceTables events, audit_log

Defining a store does not contact the bucket. A wrong endpoint, bucket or key shows up when the first table on it is created or opened; SHOW STORAGE STORES has an opened column that says whether a store has been reached yet.

Check that it works

sql
CREATE TABLE events (id BIGINT PRIMARY KEY, kind TEXT, body TEXT);  -- after placing it
INSERT INTO events VALUES (1, 'signup', '{}');
SHOW TABLES;              -- events: backend s3
SHOW TABLE STATS events;  -- includes the store's page cache; misses are requests sent to the bucket
SHOW STORAGE STORES;

Objects appear in the bucket under the prefix.

Stop or undo

Move a table back onto local files: STORAGE MOVE TABLE events TO '/var/lib/rasterizeddb' (a directory that is one of the database's storage locations), or into memory with 'memory:'. A store with no tables on it can be removed with STORAGE DROP STORE archive; a store that still holds tables cannot be dropped, and the error names them.

Limits

  • One server per prefix. There is no lease yet: a second server writing tables under the same prefix corrupts both.
  • A table on a store has no write-ahead log; its durability comes from the objects it writes. Writes outside a transaction are flushed within about 200 ms.
  • A store's address (endpoint, bucket, prefix) cannot be changed while tables are on it. Move them off first. Keys can be replaced at any time with STORAGE ALTER STORE archive SET ACCESS_KEY_ID = '…', SECRET_ACCESS_KEY = '…'; a store that is already open keeps the old ones until the server restarts.
  • In an S3 backup these tables are copied as of each snapshot, with no point-in-time replay between snapshots, and a restore brings them back as ordinary local tables.

The files

setup.sh · Linux and macOS (Bash)DOWNLOAD ↓
#!/usr/bin/env bash
# RasterizedDB: keep chosen tables in an S3 bucket instead of local files.
# Defines a key/value store on a running server, then places new tables on it
# or moves existing ones there. The store is defined with IF NOT EXISTS, so
# running this again with the same settings does not change it.
#
# Every setting can be overridden from the environment, for example:
#   RDB_STORE_BUCKET=my-tables RDB_PLACE_TABLES="events audit" ./setup.sh
#   RDB_STORE_ENDPOINT=http://minio.internal:9000 RDB_STORE_ADDRESSING=path RDB_MOVE_TABLES=logs ./setup.sh
set -euo pipefail

RDB_PG_URL="${RDB_PG_URL:-postgresql://rasterized@127.0.0.1:5432/postgres?sslmode=require}"
RDB_STORE_NAME="${RDB_STORE_NAME:-archive}"
RDB_STORE_ENDPOINT="${RDB_STORE_ENDPOINT:-https://s3.us-east-1.amazonaws.com}"
RDB_STORE_REGION="${RDB_STORE_REGION:-us-east-1}"
RDB_STORE_BUCKET="${RDB_STORE_BUCKET:-}"                 # required
RDB_STORE_PREFIX="${RDB_STORE_PREFIX:-rdb/archive}"      # one server per prefix
RDB_STORE_ADDRESSING="${RDB_STORE_ADDRESSING:-virtual}"  # path for MinIO and non-DNS-safe bucket names
RDB_STORE_CACHE="${RDB_STORE_CACHE:-256MiB}"             # page cache for this store's tables
RDB_STORE_OWN_KEYS="${RDB_STORE_OWN_KEYS:-0}"            # 1: the store keeps AWS_ACCESS_KEY_ID/SECRET from this shell
RDB_PLACE_TABLES="${RDB_PLACE_TABLES:-}"                 # tables not created yet, space-separated
RDB_MOVE_TABLES="${RDB_MOVE_TABLES:-}"                   # existing tables to move onto the store

die() { echo "error: $*" >&2; exit 1; }

command -v psql >/dev/null 2>&1 || die "psql is needed"
[ -n "$RDB_STORE_BUCKET" ] || die "set RDB_STORE_BUCKET to the bucket that will hold the tables"
[ -n "${PGPASSWORD:-}" ] || die "set PGPASSWORD to the password of the role in RDB_PG_URL (a superuser)"
for v in "$RDB_STORE_NAME" "$RDB_STORE_ENDPOINT" "$RDB_STORE_REGION" "$RDB_STORE_BUCKET" "$RDB_STORE_PREFIX" "$RDB_STORE_ADDRESSING" "$RDB_STORE_CACHE"; do
  case "$v" in *"'"*) die "settings may not contain a single quote: $v" ;; esac
done

credentials=""
if [ "$RDB_STORE_OWN_KEYS" = 1 ]; then
  : "${AWS_ACCESS_KEY_ID:?set AWS_ACCESS_KEY_ID for the store}"
  : "${AWS_SECRET_ACCESS_KEY:?set AWS_SECRET_ACCESS_KEY for the store}"
  case "$AWS_ACCESS_KEY_ID$AWS_SECRET_ACCESS_KEY" in *"'"*) die "the keys may not contain a single quote" ;; esac
  credentials=", ACCESS_KEY_ID = '$AWS_ACCESS_KEY_ID', SECRET_ACCESS_KEY = '$AWS_SECRET_ACCESS_KEY'"
fi

# The statements go to psql on standard input, so no key appears in the process list.
sql() { psql "$RDB_PG_URL" -v ON_ERROR_STOP=1 -X -q "$@"; }

sql <<EOF
STORAGE ADD STORE IF NOT EXISTS $RDB_STORE_NAME S3 WITH (ENDPOINT = '$RDB_STORE_ENDPOINT', REGION = '$RDB_STORE_REGION', BUCKET = '$RDB_STORE_BUCKET', PREFIX = '$RDB_STORE_PREFIX', ADDRESSING = '$RDB_STORE_ADDRESSING', CACHE_BYTES = '$RDB_STORE_CACHE'$credentials);
EOF
echo "Store $RDB_STORE_NAME: s3 bucket $RDB_STORE_BUCKET, prefix $RDB_STORE_PREFIX"

for t in $RDB_PLACE_TABLES; do
  if sql -c "STORAGE PLACE TABLE $t AT 'kv:$RDB_STORE_NAME'"; then
    echo "placed: $t (create it now; it is made on the store)"
  else
    echo "warning: $t was not placed (the error is above)" >&2
  fi
done
for t in $RDB_MOVE_TABLES; do
  if sql -c "STORAGE MOVE TABLE $t TO 'kv:$RDB_STORE_NAME'"; then
    echo "moved:  $t"
  else
    echo "warning: $t was not moved (the error is above)" >&2
  fi
done

sql -c "SHOW STORAGE STORES"
echo "Tables on the store show backend s3 in SHOW TABLES."
setup.ps1 · Windows (PowerShell)DOWNLOAD ↓
#Requires -Version 5.1
<#
.SYNOPSIS
  RasterizedDB: keep chosen tables in an S3 bucket instead of local files.
  Defines a key/value store on a running server, then places new tables on it
  or moves existing ones there. The store is defined with IF NOT EXISTS, so
  running this again with the same settings does not change it.
.EXAMPLE
  $env:PGPASSWORD = 'use-a-long-secret'
  .\setup.ps1 -Bucket my-tables -PlaceTables events, audit
.EXAMPLE
  .\setup.ps1 -Bucket tables -Endpoint http://minio.internal:9000 -Addressing path -MoveTables logs
#>
[CmdletBinding()]
param(
    [string]$PgUrl = $(if ($env:RDB_PG_URL) { $env:RDB_PG_URL } else { 'postgresql://rasterized@127.0.0.1:5432/postgres?sslmode=require' }),
    [string]$StoreName = $(if ($env:RDB_STORE_NAME) { $env:RDB_STORE_NAME } else { 'archive' }),
    [string]$Endpoint = $(if ($env:RDB_STORE_ENDPOINT) { $env:RDB_STORE_ENDPOINT } else { 'https://s3.us-east-1.amazonaws.com' }),
    [string]$Region = $(if ($env:RDB_STORE_REGION) { $env:RDB_STORE_REGION } else { 'us-east-1' }),
    [string]$Bucket = $env:RDB_STORE_BUCKET,
    # One server per prefix.
    [string]$Prefix = $(if ($env:RDB_STORE_PREFIX) { $env:RDB_STORE_PREFIX } else { 'rdb/archive' }),
    # path for MinIO and bucket names that are not DNS-safe.
    [ValidateSet('virtual', 'path')]
    [string]$Addressing = $(if ($env:RDB_STORE_ADDRESSING) { $env:RDB_STORE_ADDRESSING } else { 'virtual' }),
    # Page cache for this store's tables.
    [string]$Cache = $(if ($env:RDB_STORE_CACHE) { $env:RDB_STORE_CACHE } else { '256MiB' }),
    # The store keeps $env:AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY from this session.
    [switch]$OwnKeys = ($env:RDB_STORE_OWN_KEYS -eq '1'),
    # Tables not created yet.
    [string[]]$PlaceTables = @(),
    # Existing tables to move onto the store.
    [string[]]$MoveTables = @()
)
$ErrorActionPreference = 'Stop'

if (-not (Get-Command psql -ErrorAction SilentlyContinue)) { throw 'psql is needed.' }
if (-not $Bucket) { throw 'Pass -Bucket with the bucket that will hold the tables.' }
if (-not $env:PGPASSWORD) { throw 'Set $env:PGPASSWORD to the password of the role in -PgUrl (a superuser).' }
foreach ($v in @($StoreName, $Endpoint, $Region, $Bucket, $Prefix, $Cache)) {
    if ($v.Contains("'")) { throw "Settings may not contain a single quote: $v" }
}

$credentials = ''
if ($OwnKeys) {
    if (-not $env:AWS_ACCESS_KEY_ID -or -not $env:AWS_SECRET_ACCESS_KEY) { throw 'Set $env:AWS_ACCESS_KEY_ID and $env:AWS_SECRET_ACCESS_KEY for the store.' }
    if (($env:AWS_ACCESS_KEY_ID + $env:AWS_SECRET_ACCESS_KEY).Contains("'")) { throw 'The keys may not contain a single quote.' }
    $credentials = ", ACCESS_KEY_ID = '$($env:AWS_ACCESS_KEY_ID)', SECRET_ACCESS_KEY = '$($env:AWS_SECRET_ACCESS_KEY)'"
}

# Statements go to psql on standard input, so no key appears in the process list.
function Invoke-Sql([string]$Statement) {
    $Statement | & psql $PgUrl -v ON_ERROR_STOP=1 -X -q
    return ($LASTEXITCODE -eq 0)
}

$define = "STORAGE ADD STORE IF NOT EXISTS $StoreName S3 WITH (ENDPOINT = '$Endpoint', REGION = '$Region', BUCKET = '$Bucket', PREFIX = '$Prefix', ADDRESSING = '$Addressing', CACHE_BYTES = '$Cache'$credentials);"
if (-not (Invoke-Sql $define)) { throw 'The store was not defined; the error is above.' }
Write-Host "Store ${StoreName}: s3 bucket $Bucket, prefix $Prefix"

foreach ($t in $PlaceTables) {
    if (Invoke-Sql "STORAGE PLACE TABLE $t AT 'kv:$StoreName';") { Write-Host "placed: $t (create it now; it is made on the store)" }
    else { Write-Warning "$t was not placed (the error is above)" }
}
foreach ($t in $MoveTables) {
    if (Invoke-Sql "STORAGE MOVE TABLE $t TO 'kv:$StoreName';") { Write-Host "moved:  $t" }
    else { Write-Warning "$t was not moved (the error is above)" }
}

[void](Invoke-Sql 'SHOW STORAGE STORES;')
Write-Host 'Tables on the store show backend s3 in SHOW TABLES.'
✓ page rendered in 203 µs axum + tera + htmx · no other javascript