Non-OLTP services
Some services need their own relational database but do not use the shared oltp database. These services have a named database in the Aurora cluster, and their Drizzle schema lives inside the service itself rather than in the shared luna-oltp-schema package.
There are two variants:
- Aurora as source of truth (no DynamoDB) — e.g. activities. The service writes to Aurora directly via the RDS Data API.
- Aurora as a search projection of DynamoDB — e.g. contacts. DynamoDB remains the source of truth; a stream indexer maintains a denormalised Aurora copy used for flexible search/filtering, then hydrates results from DynamoDB.
Overview (source-of-truth variant)
- No DynamoDB stream involved — the service writes to Aurora directly via the RDS Data API
- Schema and migrations are owned by the service, living in
schema/andmigrations/at the service root - The service has its own
docker-compose.ymlfor local development - The database is created once per environment using the Luna CLI
Search projection variant (contacts)
Contacts keeps DynamoDB as the system of record and uses a service-owned contacts Aurora database as the flexible search index that previously lived on EFS/SQLite.
- Stream indexer (
ContactsStreamsSearchIndexerFunction) dual-writes contact and connection changes into Aurora (and temporarily into SQLite during cutover) GET /v2/contactsqueries Aurora for IDs / counts / presets, then hydrates full documents via DynamoDBBatchGetItem+ connection queries- Cutover is controlled by the SAM parameter
ContactsAuroraSearch:off→index-only→on - Historical load:
luna -e <env> script run src/scripts/contacts/backfill-contacts-search.ts - Schema / migrations live in
services/contacts(same layout as activities) - Migrations that install
pg_trgmuse the Aurora master credentials vialuna aurora run-migration --database contacts
See services/contacts/README.md for the full rollout and cleanup checklist.
Create the database
luna -e <env> aurora create-database --name <service_db>This creates a new named database in the Aurora cluster. Run this once when setting up a new environment.
Create users
Same create-user command as OLTP, targeting the new database:
luna -e <env> aurora create-user \
--username <name> \
--database <service_db> \
--file <filename>See Remote Clusters for full details including available SQL templates and how credentials are stored.
Run migrations
luna -e <env> aurora run-migration --database <service_db>Local development
Each non-OLTP service ships its own docker-compose.yml. Start the local container from the service directory:
cd services/<service-name>
yarn db:local:startThen set DATABASE_URL to point at the local container with your service's database name:
postgresql://luna_user:luna_pass@localhost:5432/<service_db>Refer to docker-compose.yml in the service for the exact database name (POSTGRES_DB) and host port, as the container name and the drizzle config default may differ (contacts uses port 5433).
Service directory layout
The activities service is the reference implementation for Aurora-as-source-of-truth. Contacts follows the same schema/migrations layout for its search projection. Both follow the standard CQRS service layout (one Lambda per responsibility), with schema and migrations sitting at the service root alongside the rest of the service code:
services/<service-name>/
├── commands/
│ └── src/ # write API Lambda handler source
├── querier/
│ └── src/ # read API Lambda handler source
├── streams/
│ └── src/ # DDB/CDC stream Lambda handler source
├── models/ # DynamoDB data-access layer (shared Lambda layer)
├── utils/ # transformers + domain helpers (shared Lambda layer)
├── schema/
│ └── <table>.ts # Drizzle table definitions
├── migrations/ # generated migration SQL files
├── drizzle.config.ts # drizzle-kit config (used for both local and remote)
├── docker-compose.yml # local Postgres container
└── application.yml # SAM templateThere is no separate schema Lambda layer: build.sh bundles the compiled schema into a shared Lambda layer (build/schema → utils layer for activities, common layer for contacts) rather than giving it a dedicated layer of its own. Dependencies (node_modules) are packaged as a Lambda layer via build/dependencies as usual.
Drizzle config
A single drizzle.config.ts at the service root handles both local and remote use. It reads DATABASE_URL from the environment:
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './schema/*',
out: './migrations',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL || 'postgresql://luna_user:luna_pass@localhost:5432/<service_db>',
},
});Generate migrations with:
yarn db:migrations:generateStreams (Change Data Capture)
Services that need to react to database changes can invoke a Lambda function directly from Aurora using the aws_lambda PostgreSQL extension. A trigger fires per-row after any write and passes a JSON payload to the streams Lambda asynchronously.
How it works
- An Aurora trigger fires after an
INSERT,UPDATE, orDELETEon a watched table. - The trigger function looks up the streams Lambda name from a
<service>_configtable. - If a record exists it invokes the Lambda via
aws_lambda.invoke; if not, the trigger is a no-op. - The Lambda receives a payload describing the change.
Payload
{
"eventName": "INSERT | UPDATE | DELETE",
"tableName": "<table>",
"oldImage": { "...row" } | null,
"newImage": { "...row" } | null
}oldImage is null for INSERT; newImage is null for DELETE.
Setup
1. Add a config table to the schema
export const serviceConfig = pgTable('<service>_config', {
key: text('key').primaryKey(),
value: text('value').notNull(),
});This table is used to store the streams function name per environment at runtime rather than baking it into the migration.
2. Create a custom migration
cd services/<service-name>
yarn db:migrations:generate --custom --name <service>_triggersPopulate the generated SQL file with three parts separated by --> statement-breakpoint:
Install the extension (the pg_available_extensions guard makes this a no-op on local PostgreSQL):
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_available_extensions WHERE name = 'aws_lambda') THEN
CREATE EXTENSION IF NOT EXISTS aws_lambda CASCADE;
END IF;
END $$;Declare the trigger function — one function can be reused across all watched tables; TG_TABLE_NAME identifies the source:
CREATE OR REPLACE FUNCTION notify_<service>_change()
RETURNS TRIGGER AS $$
DECLARE
function_name TEXT;
BEGIN
SELECT value INTO function_name FROM <service>_config WHERE key = '<service>_streams_function';
IF function_name IS NULL THEN
RETURN NULL;
END IF;
PERFORM aws_lambda.invoke(
aws_commons.create_lambda_function_arn(function_name),
jsonb_build_object(
'eventName', TG_OP,
'tableName', TG_TABLE_NAME,
'oldImage', CASE WHEN TG_OP = 'INSERT' THEN NULL ELSE to_jsonb(OLD) END,
'newImage', CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE to_jsonb(NEW) END
),
'Event'
);
RETURN NULL;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;SECURITY DEFINER means the function runs as the master user (its creator), so it can invoke the extension even though the db-migrater user does not have rds_superuser.
Attach a trigger to each watched table:
CREATE OR REPLACE TRIGGER <table>_change_trigger
AFTER INSERT OR UPDATE OR DELETE ON <table>
FOR EACH ROW EXECUTE FUNCTION notify_<service>_change();To add triggers for new tables later, create a new migration with just an additional CREATE OR REPLACE TRIGGER pointing to the existing function — no changes to the function itself are needed.
3. Register the database in the CLI migration service
Installing aws_lambda (or pg_trgm) requires rds_superuser, which db-migrater does not have. The CLI's run-migration.service.ts must use the master credentials secret (${environment}-aurora-credentials) when the target database is your service's database, rather than the default ${environment}/aurora/users/db-migrater. Add a condition for the new database name following the same pattern already in place for activities and contacts. See cli/src/commands/aurora/commands/run-migration/run-migration.service.ts for the reference implementation.
4. Configure the streams function per environment
After deploying, insert the Lambda function name into the config table for each environment:
INSERT INTO <service>_config (key, value)
VALUES ('<service>_streams_function', '<environment>-<service>-streams-function')
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;Local development
The aws_lambda extension is not available in local PostgreSQL, so the migration skips the CREATE EXTENSION step and triggers are no-ops. No local configuration is needed.
