> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fjall.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Database Factory

> Create AWS Aurora, RDS, DynamoDB, and Global Aurora databases with the Fjall DatabaseFactory pattern.

## Overview

The `DatabaseFactory` creates database resources with type-safe configurations. It supports Aurora (Serverless v2 clusters), RDS instances, Global Aurora, and DynamoDB tables.

<Note>
  For S3 storage buckets, use the [StorageFactory](/patterns/storage-factory) instead.
</Note>

## Basic Usage

```typescript theme={null}
import { App, DatabaseFactory } from "@fjall/components-infrastructure";

const app = App.getApp("myapp");

const database = app.addDatabase(
  DatabaseFactory.build("Main", {
    type: "Aurora",
    databaseName: "myapp",
  }),
);
```

## Database Types

### Aurora

Aurora Serverless v2 cluster running PostgreSQL or MySQL:

```typescript theme={null}
const db = app.addDatabase(
  DatabaseFactory.build("Main", {
    type: "Aurora",
    databaseName: "myapp",
    databaseEngine: "postgresql", // or "mysql"
  }),
);
```

**Features:**

* Serverless v2 writer and optional read replicas
* Capacity scales automatically with load
* High availability across Availability Zones
* Automatic backups with snapshot removal policy

### RDS Instance

Traditional database instance for predictable workloads:

```typescript theme={null}
const db = app.addDatabase(
  DatabaseFactory.build("Main", {
    type: "Instance",
    databaseName: "myapp",
    databaseEngine: "postgresql",
    instanceType: "t4g.micro",
  }),
);
```

**Features:**

* Fixed instance size
* Lower baseline cost for small workloads
* Free tier eligible (t4g.micro)

### Global Aurora

Multi-region database for global applications:

```typescript theme={null}
const db = app.addDatabase(
  DatabaseFactory.build("Main", {
    type: "GlobalAurora",
    databaseName: "myapp",
    primaryRegion: "us-east-1",
    secondaryRegions: ["eu-west-1", "ap-southeast-2"],
  }),
);
```

**Features:**

* Cross-region replication
* Low-latency global reads
* Automatic failover

### DynamoDB

Serverless NoSQL database:

```typescript theme={null}
const cache = app.addDatabase(
  DatabaseFactory.build("Cache", {
    type: "DynamoDB",
    partitionKey: { name: "id", type: "S" },
    sortKey: { name: "timestamp", type: "N" },
  }),
);
```

**Features:**

* Serverless (pay per request)
* Single-digit millisecond latency
* Automatic scaling
* Global tables support

## Configuration Parameters

### Common Parameters (Relational)

| Parameter                    | Type                                       | Description                                      | Default        |
| ---------------------------- | ------------------------------------------ | ------------------------------------------------ | -------------- |
| `type`                       | `"Aurora" \| "Instance" \| "GlobalAurora"` | Database type                                    | Required       |
| `databaseName`               | `string`                                   | Database name                                    | Required       |
| `databaseEngine`             | `"postgresql" \| "mysql"`                  | Database engine (simple string)                  | `"postgresql"` |
| `engine`                     | `IClusterEngine \| IInstanceEngine`        | CDK engine object (advanced override)            | -              |
| `port`                       | `number`                                   | Database port                                    | Engine default |
| `monitoringInterval`         | `number`                                   | Enhanced monitoring interval (seconds)           | `0` (disabled) |
| `preferredMaintenanceWindow` | `string`                                   | Maintenance window (e.g., "Sun:23:00-Mon:01:00") | -              |

<Note>
  Use `databaseEngine` for simple string-based configuration. Use `engine` only when you need to pass a CDK engine object with custom parameters.
</Note>

### Aurora Parameters

| Parameter                          | Type                      | Description                                        | Default                                              |
| ---------------------------------- | ------------------------- | -------------------------------------------------- | ---------------------------------------------------- |
| `databaseEngine`                   | `"postgresql" \| "mysql"` | Database engine                                    | `"postgresql"`                                       |
| `deletionProtection`               | `boolean`                 | Prevent accidental deletion                        | `true` in prod                                       |
| `backupRetention`                  | `number`                  | Backup retention in days                           | `14` (Standard), `30` (Resilient), `35` (Enterprise) |
| `databaseInsights`                 | `object \| false`         | Database Insights config, or `false` to disable    | -                                                    |
| `databaseInsights.retentionPeriod` | `number`                  | Retention days (7, 31, 62, etc.)                   | `7`                                                  |
| `writer`                           | `object`                  | Writer instance configuration                      | Auto                                                 |
| `readers`                          | `object[] \| false`       | Read replica configurations, or `false` to disable | `[]`                                                 |
| `proxy`                            | `object \| false`         | RDS Proxy configuration, or `false` to disable     | -                                                    |
| `credentials`                      | `object`                  | Username and rotation config                       | Auto                                                 |
| `encryption`                       | `object`                  | Storage encryption with KMS                        | Default key                                          |
| `publiclyAccessible`               | `boolean`                 | Allow public access (dev only)                     | `false`                                              |
| `allowedIpCidr`                    | `string`                  | CIDR for public access                             | -                                                    |
| `snapshotIdentifier`               | `string`                  | Restore from snapshot                              | -                                                    |

### Instance Parameters

| Parameter            | Type      | Description                    | Default                                              |
| -------------------- | --------- | ------------------------------ | ---------------------------------------------------- |
| `instanceType`       | `string`  | Instance type                  | `"t4g.large"`                                        |
| `allocatedStorage`   | `number`  | Storage in GB                  | `20`                                                 |
| `multiAz`            | `boolean` | Enable Multi-AZ                | `false`                                              |
| `backupRetention`    | `number`  | Backup retention in days       | `14` (Standard), `30` (Resilient), `35` (Enterprise) |
| `databaseInsights`   | `object`  | Database Insights config       | -                                                    |
| `readReplica`        | `object`  | Read replica configuration     | -                                                    |
| `proxy`              | `object`  | RDS Proxy configuration        | -                                                    |
| `publiclyAccessible` | `boolean` | Allow public access (dev only) | `false`                                              |
| `snapshotIdentifier` | `string`  | Restore from snapshot          | -                                                    |

### DynamoDB Parameters

| Parameter                | Type                                                                | Description                        | Default             |
| ------------------------ | ------------------------------------------------------------------- | ---------------------------------- | ------------------- |
| `partitionKey`           | `{ name, type }`                                                    | Partition key definition           | Required            |
| `sortKey`                | `{ name, type }`                                                    | Sort key definition                | -                   |
| `billingMode`            | `"PAY_PER_REQUEST" \| "PROVISIONED"`                                | Billing mode                       | `"PAY_PER_REQUEST"` |
| `readCapacity`           | `number`                                                            | Read capacity units (provisioned)  | -                   |
| `writeCapacity`          | `number`                                                            | Write capacity units (provisioned) | -                   |
| `globalSecondaryIndexes` | `array`                                                             | GSI definitions                    | -                   |
| `timeToLiveAttribute`    | `string`                                                            | TTL attribute name                 | -                   |
| `pointInTimeRecovery`    | `boolean`                                                           | Enable PITR                        | `true`              |
| `stream`                 | `"NEW_IMAGE" \| "OLD_IMAGE" \| "NEW_AND_OLD_IMAGES" \| "KEYS_ONLY"` | DynamoDB Streams view type         | -                   |
| `encryption`             | `"AWS_OWNED" \| "AWS_MANAGED" \| "CUSTOMER_MANAGED"`                | Table encryption mode              | `"AWS_OWNED"`       |
| `removalPolicy`          | `"DESTROY" \| "RETAIN" \| "SNAPSHOT"`                               | What happens on delete             | `"RETAIN"`          |

## Common Patterns

### Production Aurora

```typescript theme={null}
const db = app.addDatabase(
  DatabaseFactory.build("Production", {
    type: "Aurora",
    databaseName: "myapp",
    databaseEngine: "postgresql",
    databaseInsights: { retentionPeriod: 31 },
    deletionProtection: true,
  }),
);
```

### Development Database

```typescript theme={null}
const db = app.addDatabase(
  DatabaseFactory.build("Dev", {
    type: "Instance",
    databaseName: "myapp_dev",
    instanceType: "t4g.micro", // Free tier eligible
  }),
);
```

### Cache Table

```typescript theme={null}
const cache = app.addDatabase(
  DatabaseFactory.build("Cache", {
    type: "DynamoDB",
    partitionKey: { name: "key", type: "S" },
    timeToLiveAttribute: "expiresAt",
  }),
);
```

### Session Store

```typescript theme={null}
const sessions = app.addDatabase(
  DatabaseFactory.build("Sessions", {
    type: "DynamoDB",
    partitionKey: { name: "sessionId", type: "S" },
    timeToLiveAttribute: "expiresAt",
    pointInTimeRecovery: true,
  }),
);
```

## Accessing Database Information

### Relational Databases

```typescript theme={null}
const db = app.addDatabase(
  DatabaseFactory.build("Main", {
    type: "Aurora",
    databaseName: "myapp",
  }),
);

// Get connection info
const host = db.getHostEndpoint();
const port = db.getHostPort();
const name = db.getDatabaseName();

// Get credentials (Secret)
const credentials = db.getCredentials();
```

### DynamoDB

```typescript theme={null}
const table = app.addDatabase(
  DatabaseFactory.build("Cache", {
    type: "DynamoDB",
    partitionKey: { name: "id", type: "S" },
  }),
);

// Get table info
const tableName = table.getTableName();
const tableArn = table.getTableArn();
```

## Connecting to Compute

### Lambda with Database

```typescript theme={null}
const db = app.addDatabase(
  DatabaseFactory.build("Main", { type: "Aurora", databaseName: "myapp" }),
);

app.addCompute(
  ComputeFactory.build("Api", {
    type: "lambda",
    deployment: "code",
    handler: "api.handler",
    connections: [db],
  }),
);
```

### ECS with Database

```typescript theme={null}
const db = app.addDatabase(
  DatabaseFactory.build("Main", { type: "Aurora", databaseName: "myapp" }),
);

app.addCompute(
  ComputeFactory.build("Api", {
    type: "ecs",
    services: [
      {
        name: "api",
        capacityProvider: "FARGATE",
        containers: [
          {
            environment: {
              DATABASE_HOST: db.getHostEndpoint(),
              DATABASE_NAME: db.getDatabaseName(),
            },
            secretsImport: {
              DATABASE_PASSWORD: db.getCredentials().getImport("password"),
            },
          },
        ],
      },
    ],
    connections: [db],
  }),
);
```

## Granting Access

### Relational Databases

Access is automatically granted when using `connections`. For manual grants:

```typescript theme={null}
db.grantConnect(lambdaFunction);
```

### DynamoDB

```typescript theme={null}
// Read only
table.grantReadData(lambdaFunction);

// Write only
table.grantWriteData(lambdaFunction);

// Read/Write
table.grantReadWriteData(lambdaFunction);

// Full access
table.grantFullAccess(lambdaFunction);
```

## Security

### Automatic Security Features

* **Encryption at rest**: All databases encrypted by default
* **Encryption in transit**: SSL/TLS enforced
* **Secrets Manager**: Credentials stored securely
* **VPC isolation**: Databases in private subnets
* **Security groups**: Automatic least-privilege rules

### Database Insights

```typescript theme={null}
const db = app.addDatabase(
  DatabaseFactory.build("Main", {
    type: "Aurora",
    databaseName: "myapp",
    databaseInsights: {
      retentionPeriod: 31, // days (7, 31, 62, 93, 124, 155, 186, 217, 248, 279, 310, 341, 372, 403, 434, 465, 496, 527, 558, 589, 620, 651, 682, 713, 731)
    },
  }),
);
```

## Best Practices

1. **Use Aurora Serverless** for variable workloads
2. **Use Instance** for predictable, small workloads
3. **Enable Database Insights** in production
4. **Use DynamoDB** for key-value and session data
5. **Use `connections`** for automatic IAM and security group setup
6. **Enable deletion protection** in production

## Next Steps

<CardGroup cols={2}>
  <Card title="Storage Factory" icon="box-archive" href="/patterns/storage-factory">
    Create S3 buckets for file storage
  </Card>

  <Card title="Compute Factory" icon="microchip" href="/patterns/compute-factory">
    Deploy Lambda and ECS compute resources
  </Card>

  <Card title="Payload Pattern" icon="cube" href="/patterns/payload-pattern">
    Full-stack Payload CMS deployment
  </Card>

  <Card title="Standard Pattern" icon="layer-group" href="/patterns/standard-pattern">
    Production web application pattern
  </Card>
</CardGroup>
