Keel by ChimpLabs
Jump to page or section Esc
Backends & Operations

Storage & Messaging Backends

Memory, SQLite, PostgreSQL 17, SurrealDB 4, Garage S3, Cloudflare R2, and AWS S3 adapter guide.

Domain code depends only on capability interfaces in R. You select concrete infrastructure once at your application entrypoint by composing Effect Layers.

Three Environment Backend Topology


1. Unit tests and local prototyping (zero external services)

One-line in-memory stack (KeelMemoryLive and makeKeelMemoryLive)

For deterministic unit tests and local prototyping with no setup, wire the core Keel capability stack in one line:

import { KeelMemoryLive, makeKeelMemoryLive } from "@chimp-labs/keel"

// Zero-config default:
export const DefaultTestLive = KeelMemoryLive

// Pre-seeded with secrets, feature flags, and custom presigner base URL:
export const TestAppLive = makeKeelMemoryLive({
  secrets: { STRIPE_API_KEY: "sk_test_123" },
  flags: { "new-checkout": true },
  presignerBaseUrl: "https://memory-s3.local",
})

Real SQLite override for SQL constraints, foreign keys, and ACID rollbacks

When you need real SQLite (node:sqlite :memory: or file-backed) for Table, TransactionalOutbox, and (with @chimp-labs/keel-workflow) WorkflowStore, override RelationalStore on top of makeKeelMemoryLive:

import { Layer } from "effect"
import {
  makeKeelMemoryLive,
  RelationalStoreSqlite,
} from "@chimp-labs/keel"
import { WorkflowStoreFromTable } from "@chimp-labs/keel-workflow"

const SqliteLive = RelationalStoreSqlite() // real node:sqlite :memory:

export const SqliteTestLive = Layer.mergeAll(
  makeKeelMemoryLive({ secrets: { STRIPE_API_KEY: "sk_test_123" } }),
  SqliteLive,
  WorkflowStoreFromTable.pipe(Layer.provide(SqliteLive)),
)

2. Effect.Config-driven wiring (KeelPostgresConfigLive, KeelSurrealConfigLive, and BucketS3ConfigLive)

Instead of reading process.env manually, use Keel’s redaction-safe Effect Config layers. Credentials (url, password, token, secretAccessKey, and sessionToken) stay wrapped in Redacted<string> so they never leak in logs or error reports. All loaders respect Effect’s active ConfigProvider, so tests can inject configuration with ConfigProvider.fromEnv.

import { Layer } from "effect"
import {
  BucketS3ConfigLive,
  makeBucketS3ConfigLive,
  CacheStoreMemory,
  DistributedLockMemory,
  RateLimiterMemory,
  SecretStoreChain,
  SecretStoreConfig,
  SecretStoreDir,
} from "@chimp-labs/keel"
import {
  KeelPostgresConfigLive,
  makeKeelPostgresConfigLive,
} from "@chimp-labs/keel-postgres"
import {
  KeelSurrealConfigLive,
  makeKeelSurrealConfigLive,
} from "@chimp-labs/keel-surreal"

// PostgreSQL 17 stack (`DATABASE_URL` / `POSTGRES_*` and `S3_*`) —
// includes multi-replica Cache, Lock, and RateLimit on Postgres (zero Redis):
export const PostgresAppLive = Layer.mergeAll(
  KeelPostgresConfigLive,
  BucketS3ConfigLive,
  SecretStoreChain(SecretStoreDir("/run/secrets"), SecretStoreConfig),
)

// SurrealDB 4 stack (`SURREAL_*` and `S3_*`):
export const SurrealAppLive = Layer.mergeAll(
  KeelSurrealConfigLive,
  BucketS3ConfigLive,
  CacheStoreMemory,
  DistributedLockMemory,
  RateLimiterMemory,
  SecretStoreChain(SecretStoreDir("/run/secrets"), SecretStoreConfig),
)

// Custom prefixes (e.g. `KEEL_PG_*`, `KEEL_SURREAL_*`, `KEEL_S3_*`):
export const CustomPrefixLive = Layer.mergeAll(
  makeKeelPostgresConfigLive({ prefix: "KEEL_PG_" }),
  makeBucketS3ConfigLive({ prefix: "KEEL_S3_" }),
)

Other config helpers include postgresConfigFromEnv, PostgresClientConfigLive, and makePostgresClientConfigLive from @chimp-labs/keel-postgres; surrealConfigFromEnv, SurrealClientConfigLive, and makeSurrealClientConfigLive from @chimp-labs/keel-surreal; and s3ConfigFromEnv from @chimp-labs/keel.

Default Effect.Config environment variables

Loader Key Required Default Redacted
postgresConfigFromEnv (POSTGRES_) POSTGRES_URL (falls back to DATABASE_URL) No* None Yes
postgresConfigFromEnv (POSTGRES_) POSTGRES_HOST No None No
postgresConfigFromEnv (POSTGRES_) POSTGRES_PORT No 5432 No
postgresConfigFromEnv (POSTGRES_) POSTGRES_USER No None No
postgresConfigFromEnv (POSTGRES_) POSTGRES_PASSWORD No None Yes
postgresConfigFromEnv (POSTGRES_) POSTGRES_DATABASE No None No
postgresConfigFromEnv (POSTGRES_) POSTGRES_SSL No None No
postgresConfigFromEnv (POSTGRES_) POSTGRES_MAX_CONNECTIONS No 10 No
postgresConfigFromEnv (POSTGRES_) POSTGRES_MAX_RETRIES No 3 No
surrealConfigFromEnv (SURREAL_) SURREAL_URL Yes None No
surrealConfigFromEnv (SURREAL_) SURREAL_NAMESPACE Yes None No
surrealConfigFromEnv (SURREAL_) SURREAL_DATABASE Yes None No
surrealConfigFromEnv (SURREAL_) SURREAL_USERNAME No None No
surrealConfigFromEnv (SURREAL_) SURREAL_PASSWORD No None Yes
surrealConfigFromEnv (SURREAL_) SURREAL_TOKEN No None Yes
surrealConfigFromEnv (SURREAL_) SURREAL_AUTO_CREATE No true No
surrealConfigFromEnv (SURREAL_) SURREAL_MAX_RETRIES No 3 No
s3ConfigFromEnv (S3_) S3_ENDPOINT Yes None No
s3ConfigFromEnv (S3_) S3_REGION No us-east-1 No
s3ConfigFromEnv (S3_) S3_ACCESS_KEY_ID Yes None No
s3ConfigFromEnv (S3_) S3_SECRET_ACCESS_KEY Yes None Yes
s3ConfigFromEnv (S3_) S3_SESSION_TOKEN No None Yes
s3ConfigFromEnv (S3_) S3_FORCE_PATH_STYLE No true No

*Provide either POSTGRES_URL / DATABASE_URL, or discrete POSTGRES_HOST, POSTGRES_USER, and POSTGRES_DATABASE parameters.


3. PostgreSQL 17 (@chimp-labs/keel-postgres)

@chimp-labs/keel-postgres provides the full Keel capability stack over a single pg.Pool and one lazily opened, auto-reconnecting LISTEN/NOTIFY multiplexer connection. It runs identically against Docker postgres:17-alpine or any managed PostgreSQL 17 service.

Capability PostgreSQL 17 implementation
RelationalStore, PgCapabilities Real SQL tables with native JSONB GIN & expression indexes, dot-path queries & @> containment, foreign keys, typed joins, ACID BEGIN/COMMIT/ROLLBACK with nested SAVEPOINTs, LISTEN/NOTIFY watches, and FOR UPDATE SKIP LOCKED
EventBus, EventStore Durable BIGSERIAL event log with wildcard matching and live LISTEN/NOTIFY fan-out
QueueStore, DelayedQueue Atomic FOR UPDATE SKIP LOCKED claiming, delayed jobs, DLQ, and LISTEN/NOTIFY worker wakeups
OutboxNotifier Transactional pg_notify delivered atomically on COMMIT (zero notifications on rollback)
WorkflowStore (@chimp-labs/keel-workflow/postgres) Durable step journal and multi-replica LISTEN/NOTIFY signal wakeups (WorkflowStorePostgresLive)
KeyValueStore, AtomicKV, FeatureFlags Single-statement atomic UPSERT / CAS / incr and flag evaluation (setPostgresFlag)
CacheStore, DistributedLock, RateLimiter Multi-replica singleflight cache (with tag invalidation), token-safe CAS leases, and sliding-window rate limits on AtomicKV (PostgresCoordinationLive, zero Redis required)

The package also exports individual coordination layers: PostgresCacheLive, PostgresLockLive, PostgresRateLimitLive, and PostgresCoordinationLive. All four are bundled into KeelPostgresLive and createKeel({ backend: "postgres" }). It also exports PostgreSQL schema management helpers: runPostgresMigrations, getPostgresMigrationStatus, introspectPostgresSchema, diffPostgresSchema, and pushPostgresSchema.

import { Layer } from "effect"
import { BucketS3Live, SecretStoreEnv } from "@chimp-labs/keel"
import {
  KeelPostgresConfigLive,
  KeelPostgresLive,
  makeKeelPostgresConfigLive,
} from "@chimp-labs/keel-postgres"

// Explicit config (e.g. local Docker PostgreSQL 17 on :5439):
// KeelPostgresLive provides all core Postgres capabilities including multi-replica
// CacheStore, DistributedLock, and RateLimiter (zero Redis required).
export const LocalPostgresLive = Layer.mergeAll(
  KeelPostgresLive({
    url: process.env.DATABASE_URL ?? "postgresql://keel:[email protected]:5439/keel",
    max: 10,
  }),
  BucketS3Live({
    endpoint: process.env.S3_ENDPOINT ?? "http://127.0.0.1:3900",
    region: process.env.S3_REGION ?? "garage",
    accessKeyId: process.env.S3_ACCESS_KEY_ID ?? "GK0123456789abcdef01234567",
    secretAccessKey:
      process.env.S3_SECRET_ACCESS_KEY ??
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
    forcePathStyle: true,
  }),
  SecretStoreEnv,
)

// Or zero-config via Effect's ConfigProvider (`DATABASE_URL` / `POSTGRES_*`):
export const EnvPostgresLive = KeelPostgresConfigLive
export const CustomPgLive = makeKeelPostgresConfigLive({ prefix: "APP_PG_" })

4. Secrets backends (SecretStore)

Keel provides composable SecretStore layers that return Effect’s Redacted<string>:

Layer Source Best for
SecretStoreMemory(entries) In-memory map Unit tests
SecretStoreEnv process.env Quick local scripts
SecretStoreConfig / SecretStoreConfigFrom(cp) Effect ConfigProvider (Config.Redacted) 12-factor / test ConfigProvider
SecretStoreDir(dirPath) Mounted files (<dir>/<NAME>) Docker Compose secrets: and Kubernetes /run/secrets
SecretStoreChain(...layers) Priority fallback chain Layered overrides (for example, Mounted Dir, then Effect Config)

Composing SecretStoreChain and boot preflight

import {
  SecretStoreChain,
  SecretStoreConfig,
  SecretStoreDir,
  verifySecrets,
} from "@chimp-labs/keel"

export const SecretsLive = SecretStoreChain(
  SecretStoreDir("/run/secrets"),
  SecretStoreConfig,
)

// Boot preflight: verifies every declared Secret (including ExternalSystem.secrets)
const preflight = verifySecrets([StripeKey, PaymentsSystem])

5. Local Docker (PostgreSQL 17, SurrealDB 4.0.1, and Garage v2.1.0)

Start all local backing containers and bootstrap Garage’s layout, deterministic dev S3 credentials, and default buckets in one command:

pnpm infra:up    # starts PostgreSQL 17 (:5439), surrealdb/surrealdb:v4.0.1 (:8000) & dxflrs/garage:v2.1.0 (:3900 / :3903)
pnpm infra:down
Service Endpoint Default local credentials Storage
PostgreSQL 17 postgresql://keel:[email protected]:5439/keel keel / keel (DB keel) keel_postgres_data (Docker volume)
SurrealDB 4.0.1 ws://127.0.0.1:8000 root / root surrealkv:///data/keel.db (Docker volume)
Garage v2.1.0 (S3) http://127.0.0.1:3900 GK0123456789abcdef01234567 / 0123...cdef Region garage, path-style
Garage Admin API http://127.0.0.1:3903 Bearer keel-local-garage-admin-token Bootstrapped by docker/init-garage.mjs

Wire SurrealDB 4 explicitly with KeelSurrealLive and BucketS3Live, or swap in KeelPostgresLive from Section 3:

import { Layer } from "effect"
import {
  BucketS3Live,
  CacheStoreMemory,
  DistributedLockMemory,
  RateLimiterMemory,
  SecretStoreEnv,
} from "@chimp-labs/keel"
import { KeelSurrealLive } from "@chimp-labs/keel-surreal"

export const LocalDockerLive = Layer.mergeAll(
  KeelSurrealLive({
    url: process.env.SURREAL_URL ?? "ws://127.0.0.1:8000",
    namespace: process.env.SURREAL_NAMESPACE ?? "keel",
    database: process.env.SURREAL_DATABASE ?? "local",
    username: process.env.SURREAL_USERNAME ?? "root",
    password: process.env.SURREAL_PASSWORD ?? "root",
  }),
  BucketS3Live({
    endpoint: process.env.S3_ENDPOINT ?? "http://127.0.0.1:3900",
    region: process.env.S3_REGION ?? "garage",
    accessKeyId: process.env.S3_ACCESS_KEY_ID ?? "GK0123456789abcdef01234567",
    secretAccessKey:
      process.env.S3_SECRET_ACCESS_KEY ??
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
    forcePathStyle: true,
  }),
  CacheStoreMemory,
  DistributedLockMemory,
  RateLimiterMemory,
  SecretStoreEnv,
)

6. Production (PostgreSQL 17 or SurrealDB Earth with Cloudflare R2 or AWS S3)

KeelPostgresConfigLive, KeelSurrealConfigLive, and BucketS3ConfigLive run unchanged in production. Point the environment variables at Managed PostgreSQL 17 (or SurrealDB Earth) and Cloudflare R2 (or AWS S3):

Env var Example (production)
DATABASE_URL / POSTGRES_URL postgresql://user:[email protected]:5432/prod
POSTGRES_SSL / POSTGRES_MAX_CONNECTIONS true / 20
SURREAL_URL wss://<instance>.surreal.cloud
SURREAL_TOKEN Scoped SurrealDB Cloud token (SURREAL_AUTO_CREATE=false)
SURREAL_NAMESPACE / SURREAL_DATABASE prod / orders
S3_ENDPOINT https://<account-id>.r2.cloudflarestorage.com
S3_REGION auto (R2) or us-east-1 (S3)
S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY R2 / S3 API credentials

PostgreSQL 17 operational notes

  1. Single shared LISTEN/NOTIFY multiplexer. PostgresClientLive lazily opens one dedicated listener client per pool for all live subscriptions (Topic, Queue, Outbox, DocumentWatch, and @chimp-labs/keel-workflow/postgres signals). It reconnects and re-issues LISTEN on disconnect.
  2. Standard postgres:17-alpine. Core PostgreSQL capabilities run on vanilla postgres:17-alpine with no custom extensions required.
  3. Built-in transient retries. PostgresClientLive retries non-transactional transient deadlock and connection errors with jittered exponential backoff, configurable via maxRetries or POSTGRES_MAX_RETRIES.

SurrealDB Earth guardrails

  1. Use push mode (mode: "push") on startWorker and startOutboxRelay. Tight polling keeps SurrealDB Earth awake past its 60s scale-to-zero threshold and burns database hours and request quota.
  2. Keep Bucket on R2 or S3. SurrealDB Earth does not support DEFINE BUCKET yet, and R2 provides native presigned URLs with zero egress fees.
  3. Keep hot-path Cache, RateLimit, and Lock off SurrealDB Earth. Use in-process layers for a single instance, or Redis, Upstash, or Durable Objects so bursty traffic does not consume database request units.
  4. Built-in 503 retries. SurrealClientLive retries non-transactional 503 cell-saturation responses with jittered exponential backoff, configurable via maxRetries or SURREAL_MAX_RETRIES.