Skip to content

OLTP streams ​

The OLTP pipeline streams DynamoDB change events into Aurora PostgreSQL in near real-time. The andi service is the reference implementation; examples below use a hypothetical shoutout service to illustrate the pattern for new services.

Architecture ​

Service DDB Table
       │
       │ DynamoDB Streams (NEW_AND_OLD_IMAGES)
       ▼
streams Lambda
       │
       │ Forwards Request
       ▼
oltp-streams Lambda
       │
       │ Drizzle ORM + RDS Data API
       ▼
Aurora PostgreSQL (oltp database)

We forward the request in order to avoid read throttles from having too many DDB Streams for a DynamoDB table.

The OLTP is conditionally deployed at the moment, If required to deploy to your environment add the environment name.

Code Structure ​

The oltp-streams/src/ directory follows this layout:

oltp-streams/src/
├── handler.ts               # entry point — routes by record type
├── db.ts                    # db client initialisation
├── handlers/
│   └── shoutout.ts          # handler for type
├── services/
│   ├── shoutoutBuilders.ts  # "builds" the record to upsert - essentially the transformer
│   └── shoutoutService.ts   # runs the db transactions
└── repositories/
    └── shoutoutCoreRepository.ts   # runs the actual SQL

handler.ts — routing ​

typescript
import { DynamoDBStreamEvent } from 'aws-lambda';
import { Logger } from '@bhag-business-platform/luna-logger';
import handleShoutoutRecord from './handlers/shoutout';

export const handler = async (event: DynamoDBStreamEvent): Promise<boolean> => {
  for (const record of event.Records) {
    const type = record.dynamodb?.Keys?.type?.S;

    // no try catch — want to throw errors for retry
    switch (type) {
    case 'SHOUTOUT':
      await handleShoutoutRecord(record);
      break;
    default:
      Logger.Log('received non-SHOUTOUT event. Skipping');
      break;
    }
  }

  return true;
};

handlers/shoutout.ts — event type filter ​

typescript
import { DynamoDBRecord } from 'aws-lambda';
import { Logger } from '@bhag-business-platform/luna-logger';
import { shoutoutService } from '../services/shoutoutService';

export default async (record: DynamoDBRecord) => {
  Logger.Log(`Received ${record.eventName} shoutout event for id ${record.dynamodb?.Keys?.id?.S}`);

  if (record.eventName === 'MODIFY' || record.eventName === 'INSERT') {
    await shoutoutService.processRecord(record);
    Logger.Log(`Processed shoutout ${record.dynamodb?.Keys?.id?.S}`);
  } else {
    Logger.Log(`Unhandled ${record.eventName} shoutout record event. Skipping...`);
  }
};

services/shoutoutBuilders.ts — DynamoDB image mapping ​

Builders extract fields from the DynamoDB NewImage and return plain objects. Timestamps stored as numbers (N) must be converted to Date.

typescript
import { DynamoDBRecord } from 'aws-lambda';

export const buildShoutoutCoreRecord = (record: DynamoDBRecord) => {
  const img = record.dynamodb?.NewImage;

  return {
    shoutoutId: record.dynamodb.Keys.id.S,
    senderId: img?.senderId?.S,
    recipientId: img?.recipientId?.S,
    message: img?.message?.S,
    createdAt: new Date(parseInt(img?.createdAt.N)),
    updatedAt: new Date(parseInt(img?.updatedAt.N)),
  };
};

services/shoutoutService.ts — transaction ​

All upserts for a single record run inside a single DB transaction so they succeed or fail atomically.

typescript
import { DynamoDBRecord } from 'aws-lambda';
import db from '../db';
import { shoutoutCoreRepository } from '../repositories/shoutoutCoreRepository';
import { buildShoutoutCoreRecord } from './shoutoutBuilders';

export const shoutoutService = {
  async processRecord(record: DynamoDBRecord): Promise<void> {
    const id = record.dynamodb?.Keys?.id?.S;
    const type = record.dynamodb?.Keys?.type?.S;

    if (!id || type !== 'SHOUTOUT') {
      throw new Error('Invalid record: missing required fields or incorrect type');
    }

    return db.transaction(async (tx) => {
      await shoutoutCoreRepository.upsert(tx, buildShoutoutCoreRecord(record));
    });
  },
};

repositories/shoutoutCoreRepository.ts — Drizzle upsert ​

typescript
import { shoutout_core } from '@bhag-business-platform/luna-oltp-schema';
import { DbClient } from '../db';

type NewShoutoutCore = typeof shoutout_core.$inferInsert;

export const shoutoutCoreRepository = {
  async upsert(tx: DbClient, data: NewShoutoutCore) {
    return tx.insert(shoutout_core)
      .values(data)
      .onConflictDoUpdate({
        target: shoutout_core.shoutoutId,
        set: {
          updatedAt: data.updatedAt,
          message: data.message,
        },
      })
      .returning();
  },
};

Infrastructure ​

The stream function is conditionally deployed. The condition is defined in application.yml:

yaml
Conditions:
  ShouldDeployOLTPDataPipeline: !Or
    - !Equals [ !Ref Environment, 'staging' ]
    - !Equals [ !Ref Environment, 'production' ]
    - !Equals [ !Ref Environment, 'polaris' ]

The Lambda resource:

yaml
ShoutoutOltpStreamsFunction:
  Type: AWS::Serverless::Function
  Condition: ShouldDeployOLTPDataPipeline
  Properties:
    FunctionName: !Sub ${Environment}-shoutout-oltp-streams-function
    CodeUri: build/oltp-streams/src
    Layers:
      - !Ref ShoutoutModulesLambdaLayer
    Timeout: 300
    Policies:
      - DynamoDBStreamReadPolicy:
          TableName: !Ref ShoutoutDatabase
          StreamName: !GetAtt ShoutoutDatabase.StreamArn
      - Statement:
        - Effect: Allow
          Action:
            - rds-data:ExecuteStatement
            - rds-data:BatchExecuteStatement
            - rds-data:BeginTransaction
            - rds-data:CommitTransaction
            - rds-data:RollbackTransaction
          Resource:
            Fn::ImportValue:
              !Sub ${Environment}-aurora-infrastructure-ClusterArn
        - Effect: Allow
          Action:
            - secretsmanager:GetSecretValue
          Resource:
            Fn::ImportValue:
              !Sub ${Environment}-aurora-infrastructure-SecretArn
    Environment:
      Variables:
        DATABASE_URL: "" # overridden by env.local.json for local SAM invocation
        DB_CLUSTER_ARN:
          Fn::ImportValue:
            !Sub ${Environment}-aurora-infrastructure-ClusterArn
        DB_SECRET_ARN:
          Fn::ImportValue:
            !Sub ${Environment}-aurora-infrastructure-SecretArn
        DB_NAME: oltp

The DynamoDB event source mapping is added to the main streams function so it can optionally forward to the OLTP function:

yaml
- !If
  - ShouldDeployOLTPDataPipeline
  - LambdaInvokePolicy:
      FunctionName: !Ref ShoutoutOltpStreamsFunction
  - !Ref AWS::NoValue

Tests ​

Unit tests ​

Unit tests cover builders, handlers, and the service with mocked repositories. They live alongside the source in __test__/.

Builders — assert that DynamoDB S, N, and SS fields are mapped correctly:

typescript
describe('buildShoutoutCoreRecord', () => {
  it('should return correct id and timestamps as Date objects', () => {
    const result = buildShoutoutCoreRecord(mockRecord);

    expect(result.shoutoutId).toBe('shoutout-001');
    expect(result.createdAt).toEqual(new Date(1706540000000));
  });
});

Handler — asserts routing by type key and skipping of unknown types:

typescript
jest.mock('../src/handlers/shoutout');

it('should call the shoutout record handler', async () => {
  const result = await oltpStreamsHandler(mockShoutoutDDBEvent as DynamoDBStreamEvent);

  expect(shoutoutRecordHandler).toHaveBeenCalledWith(mockShoutoutDDBEvent.Records[0]);
  expect(result).toBeTruthy();
});

Service — mock repositories, assert that processRecord calls them with correct data and throws on invalid records.

Integration tests ​

Integration tests use PGlite (an in-process PostgreSQL) via setupTestDb / teardownTestDb from @bhag-business-platform/luna-utils/aurora. These run the actual handler against a real schema without any mocks on the database layer.

typescript
import { shoutout_core } from '@bhag-business-platform/luna-oltp-schema';
import {
  setupTestDb,
  teardownTestDb,
  getTestDb,
} from '@bhag-business-platform/luna-utils/aurora';
import handleShoutoutRecord from '../../src/handlers/shoutout';

jest.mock('@bhag-business-platform/luna-factories', () => {
  const actual = jest.requireActual('@bhag-business-platform/luna-factories');
  const { getTestDbProxy } = jest.requireActual('@bhag-business-platform/luna-utils/aurora');

  return {
    ...actual,
    AuroraDatabase: {
      getClient: jest.fn(() => ({
        db: getTestDbProxy(),
        close: jest.fn(),
      })),
    },
  };
});

beforeEach(async () => { await setupTestDb({ shoutout_core }); });
afterEach(async () => { await teardownTestDb(); });

it('should write a shoutout_core record on INSERT', async () => {
  await handleShoutoutRecord({ ...baseRecord, eventName: 'INSERT' });

  const db = getTestDb();
  const result = await db.select().from(shoutout_core);

  expect(result).toHaveLength(1);
  expect(result[0].shoutoutId).toBe('shoutout-001');
});

Key things to verify in integration tests:

  • INSERT creates rows in all tables
  • MODIFY updates the correct fields without creating duplicate rows
  • REMOVE does not write anything
  • Foreign key constraints are satisfied (parent table upserted before child tables)

luna-oltp-schema package ​

@bhag-business-platform/luna-oltp-schema is the single source of truth for the OLTP database schema. It is a shared package because multiple services read from the same oltp database and all need consistent table definitions.

The package exports Drizzle table definitions from packages/luna-oltp-schema/src/schema/:

  • andi_* tables — andi_core, andi_sensitive, andi_personal, andi_contact, andi_integrations, andi_payroll, andi_employment, andi_practices, andi_reporting_lines, andi_document
  • kudos_* tables — kudos_core, kudos

The AuroraDatabase client factory is separate — it lives in @bhag-business-platform/luna-factories, not this package. Services import it from there and pass the schema object to AuroraDatabase.getClient(schema).

Schema definitions use Drizzle's pgTable. A simple table with a primary key and timestamps looks like this:

typescript
import { pgTable, text, timestamp } from 'drizzle-orm/pg-core';

export const kudos_core = pgTable('kudos_core', {
  kudosId: text('kudos_id').primaryKey(),
  senderId: text('sender_id'),
  recipientId: text('recipient_id'),
  message: text('message'),
  createdAt: timestamp('created_at', { withTimezone: true }).notNull(),
  updatedAt: timestamp('updated_at', { withTimezone: true }).notNull(),
});

End-to-end process ​

When adding a new table or modifying an existing one, follow these steps in order:

  1. Update the schema in packages/luna-oltp-schema/src/schema/
  2. Generate the migration:
    bash
    cd packages/luna-oltp-schema
    yarn db:migrations:generate
  3. Publish a new package version — bump version in package.json and follow the Managing Package Versions guide
  4. Run the migration remotely:
    bash
    luna -e <env> aurora run-migration --database oltp
  5. Update the consuming service — bump @bhag-business-platform/luna-oltp-schema to the new version in the service's package.json
  6. Implement stream handler changes — add/update builders, repositories, and service
  7. Deploy the service

Made with ❤️ by the Luna team