Fastabase

repository·main·Indexed 41 days ago

https://github.com/drizzle-team/fastabase

A solution for self-hosting Supabase on AWS using PlanetScale Postgres as the database provider. It leverages SST for deployment orchestration, OpenNext for serverless Supabase Studio, and Amazon ECS Fargate for core components like Auth, Storage, and PostgREST.

Tokens
9.2K
Snippets
28
Records
41
Agent score
52%

What's inside Fastabase

  1. How Fastabase architecture works

    main

    Fastabase provides a self-hosted Supabase experience on AWS with PlanetScale Postgres. The architecture consists of the following components:

    • Database: PlanetScale Postgres.
    • Supabase Components: Most components (Auth, Storage, PostgREST, Imgproxy, Pg-meta, Logs) are deployed as Docker containers to Amazon ECS Fargate.
    • Supabase API Entrypoint: An Application Load Balancer (ALB) positioned behind a CloudFront distribution.
    • Supabase Studio: Deployed as a serverless component using OpenNext. It is protected by user/password authentication via a CloudFront function.
    • Email: Amazon SES SMTP servers are used for email delivery.
    • SSL Proxying: Because the Logs and Realtime components do not yet support direct SSL connections to Postgres, an Envoy service is deployed as an ECS service to act as an SSL proxy for PlanetScale.
  2. Deploy Fastabase to AWS

    main

    Follow these steps to deploy a self-hosted Supabase instance on AWS using PlanetScale Postgres as the database provider. This process uses SST for orchestration and OpenNext for deploying Supabase Studio.

    1. Prerequisites

    • Node.js: Version 22 must be installed.
    • Package Manager: pnpm must be installed.
    • PlanetScale Configuration:
      • Enable pg_stat_statements and pg_cron extensions in Cluster configuration -> Extensions.
      • Set max_client_conn to at least 50 in Cluster configuration -> Parameters.

    2. Deployment Steps

    1. Clone the repository and enter the directory.
    2. Initialize Git submodules:
      git submodule update --init
    3. Create your configuration file:
      cp config.yaml.example config.yaml
    4. Populate config.yaml with your specific values.
    5. Install dependencies:
      pnpm i
    6. Configure your AWS credentials in your terminal:
      export AWS_PROFILE=<profile>
    7. Execute the deployment:
      pnpm run deploy
    TIP

    By default, the SST stage name is your local machine's username. To use a specific stage name, use: pnpm run deploy --stage <name>.

    git submodule update --init
    cp config.yaml.example config.yaml
    pnpm i
    export AWS_PROFILE=<profile>
    pnpm run deploy
  3. Remove a Fastabase deployment

    main

    To tear down a deployed Fastabase instance and its associated AWS resources, use the remove command.

    If you deployed using a custom stage name, you must provide that same stage name during removal.

    pnpm run remove
    # Or if using a custom stage:
    pnpm run remove --stage <name>
    pnpm run remove
  4. How Fastabase manages database secrets

    main

    Fastabase automatically manages database credentials in AWS Secrets Manager. During deployment, the script performs an 'upsert' operation:

    1. It constructs a JSON secret string containing host, port, username, password, dbname, and psBranchId.
    2. It attempts to describe the secret using the name specified in POSTGRES_SECRET_NAME (or the default /Supabase/user/${POSTGRES_USER}).
    3. If the secret exists, it updates the value using PutSecretValueCommand.
    4. If the secret does not exist (ResourceNotFoundException), it creates a new one using CreateSecretCommand.
    5. The resulting dbSecretArn is then passed to the SupabaseDatabase and SupabaseStack constructs to allow other AWS resources to securely access the database.
  5. Configure environment variables for Fastabase deployment

    main

    Fastabase uses environment variables to configure the PostgreSQL connection and AWS deployment settings. These variables are validated using znv. Ensure the following variables are set in your environment before running the deployment script:

    # Required variables
    POSTGRES_HOST=<host>
    POSTGRES_PORT=<port>
    POSTGRES_USER=<user>
    POSTGRES_PASSWORD=<password>
    POSTGRES_DB=<dbname>
    PLANETSCALE_BRANCH_ID=<branch_id>
    
    # Optional variables
    POSTGRES_SECRET_NAME=<secret_name>
    
    # CDK environment variables (usually provided by CDK CLI)
    CDK_DEFAULT_ACCOUNT=<account>
    CDK_DEFAULT_REGION=<region>
  6. Configure the SupabaseStack via CloudFormation Parameters

    main

    When deploying the SupabaseStack, you can customize the behavior and infrastructure through several CloudFormation parameters. These are grouped into logical categories in the AWS Console.

    Auth Settings

    • DisableSignup: Set to 'true' to disable public signups (users must be invited).
    • SiteUrl: The base URL of your application (used for email links).
    • RedirectUrls: A list of URLs permitted for post-authentication redirects.
    • JwtExpiryLimit: Token validity duration in seconds (300 to 604,800).
    • PasswordMinLength: Minimum password length (8 to 128).

    SMTP Settings

    • Email: The sender email address.
    • SenderName: The name displayed in emails.
    • SesRegion: The Amazon SES region (e.g., us-east-1, us-west-2).
    • EnableWorkMail: Enables Amazon WorkMail test domains (requires specific SES regions).

    Container Image Versions

    You can override the default Docker image URIs for the following services:

    • AuthImageUri (GoTrue)
    • RestImageUri (PostgREST)
    • RealtimeImageUri (Realtime)
    • StorageImageUri (Storage API)
    • ImgproxyImageUri (imgproxy)
    • PostgresMetaImageUri (postgres-meta)
    • StudioBranch: The branch or tag for Supabase Studio.

    Infrastructure & Database

    • EnableHighAvailability: Set to 'true' to enable Multi-AZ clustering and auto-scaling.
    • WebAclArn: The ARN for an AWS WAF Web ACL to protect CloudFront.
    • MinACU / MaxACU: Aurora Serverless v2 capacity units (0.5 to 128).
    • Task Size: Individual sizing for Kong, Auth, Rest, Storage, Imgproxy, and Meta services.
  7. Configure environment variables for SupabaseVPC

    main

    The SupabaseVPC stack requires several environment variables to be present during deployment to configure the PlanetScale peering connection. These are validated using znv.

    Required environment variables:

    • PLANETSCALE_ACCOUNT_ID: The AWS Account ID of the PlanetScale peer.
    • PLANETSCALE_REGION: The AWS region where the PlanetScale VPC resides.
    • PLANETSCALE_VPC_ID: The ID of the PlanetScale VPC.
    • PLANETSCALE_VPC_CIDR: The CIDR block of the PlanetScale VPC.
    • PLANETSCALE_PEERING_ROLE_ARN: The ARN of the IAM role used for peering.
    • POSTGRES_PORT: The TCP port used by the Postgres database.
  8. Configure Fastabase deployment via sst.config.ts

    main

    Fastabase uses SST (Serverless Stack) for infrastructure deployment. The configuration is defined in sst.config.ts using the $config function.

    Key deployment behaviors:

    • Removal Policy: Resources are set to retain if the stage is production, otherwise they are set to remove.
    • Runtime Defaults: All sst.aws.Function resources are automatically configured with nodejs22.x runtime, arm64 architecture, and a 10 seconds timeout unless explicitly overridden.
    • CloudFront Permissions: CloudFront distributions are automatically wrapped with permissions to allow cloudfront:CreateInvalidation on their own ARNs.
    • Configuration Source: The infrastructure is driven by a config.yaml file, which is validated against a configSchema before deployment.
    export default $config({
      app(input) {
        return {
          name: 'fastabase',
          removal: input?.stage === 'production' ? 'retain' : 'remove',
          home: 'aws',
          providers: {
            aws: '6.83.0',
            awsx: '2.22.0',
            random: '4.18.2',
            command: '1.1.0',
          },
        };
      },
      async run() {
        // ... infrastructure logic
      },
    });
  9. SupabaseDatabaseProps configuration

    main

    When instantiating the SupabaseDatabase stack, you must provide the following properties:

    KeyTypeDescription
    vpcec2.IVpcThe Virtual Private Cloud where the migration and password functions will run.
    dbSecretArnstringThe full ARN of the AWS Secrets Manager secret that holds the primary database administrative credentials.
  10. Configure SesSmtpProps

    main

    When instantiating the SesSmtp construct, you must provide the following properties:

    PropertyTypeDescription
    regionstringThe AWS region where SES and WorkMail will be deployed.
    emailstringThe fallback email address to use if WorkMail is not enabled.
    workMailEnabledcdk.CfnConditionA CDK condition that determines whether to deploy the Amazon WorkMail stack and use WorkMail SMTP settings.

    Note on workMailEnabled: If this condition is met, the SMTP host will be smtp.mail.<region>.awsapps.com and the username will be the WorkMail user's email. If not met, the host will be email-smtp.<region>.amazonaws.com and the username will be the IAM Access Key.

  11. Configure Drizzle Kit for Fastabase

    main

    To manage database migrations and schema synchronization for Fastabase, use a drizzle.config.ts file. This file uses defineConfig from drizzle-kit to specify the database dialect, the location of your schema definitions, and the connection credentials.

    Required configuration keys:

    • dialect: Set this to 'postgresql' for Fastabase.
    • schema: The relative path to your TypeScript schema file (e.g., './src/schema.ts').
    • dbCredentials: An object containing the connection url in the format postgresql://user:password@host:port/dbname.
    import { defineConfig } from 'drizzle-kit';
    
    export default defineConfig({
      dialect: 'postgresql',
      schema: './src/schema.ts',
      dbCredentials: {
        url: 'postgresql://user:password@host:port/dbname',
      },
    });
  12. Important notes for Fastabase users

    main

    Amazon SES Sandbox

    By default, Amazon SES operates in sandbox mode. In this mode, you can only send emails to and from verified email addresses. You must request to exit the sandbox mode in the AWS Console to send emails to unverified users.

    SSL and Envoy

    Currently, the Logs and Realtime components require an Envoy service to connect to PlanetScale via SSL. This is a temporary architectural requirement that will be removed once native SSL support is implemented in those components.