Profile picture
An illustration featuring a clock icon over a database symbol, with lines of code and a Supabase logo in the background.

Stop Supabase Projects From Being Paused

September 27, 2024

17 min read

Keep Your Supabase Projects Active with Supabase Inactive Fix and Supabase Pause Prevention

Supabase is a powerful backend-as-a-service platform built on top of Postgres, providing developers with database hosting, authentication, and other essential services. However, if you're running multiple side projects on Supabase, you've probably encountered the dreaded inactivity pause: if 7 days pass without activity, your Supabase project is paused, and the database becomes inactive.

To help you avoid this, I've created two GitHub projects that automate database activity to prevent pauses: Supabase Inactive Fix, written in Python, and Supabase Pause Prevention, designed for Next.js projects. In this post, I'll walk you through how to set up and use these tools to keep your side projects running smoothly without manual intervention.

Why Supabase Pauses Inactive Projects

Supabase pauses any project that doesn't see activity for 7 consecutive days. While this is a great cost-saving measure, it can cause frustration for developers with side projects or apps that aren't accessed frequently. When a project is paused, it takes some time for the database to come back online when you need it, slowing down development and user experience.

The good news is you can keep your databases active by making automated calls to your projects, ensuring that activity is logged before the 7-day window ends.

Supabase Inactive Fix is a Python script designed to prevent your Supabase databases from going inactive. It works by making unique calls to each Supabase Postgres database you configure it to watch, ensuring that the necessary activity is logged. You can easily set it up to run as a cron job on any server or computer.

Key Features:

  • Written in Python for flexibility and ease of use.
  • Can be configured to watch multiple databases.
  • Runs as a scheduled cron job to automate the process.

Note: Supabase Inactive Fix will keep any Supabase project active — it's not limited to Python projects by any means

How to Set Up Supabase Inactive Fix:

1. Clone the repository:

Start by cloning the Supabase Inactive Fix GitHub repo.

git clone https://github.com/travisvn/supabase-inactive-fix

2. Install Dependencies:

Navigate to the project folder and install the required dependencies using pip.

cd supabase-inactive-fix
python -m venv venv
source venv/bin/activate  # On Windows use `venv\Scripts\activate`
pip install -r requirements.txt

3. Configure Your Databases:

Inside the project, there's a configuration file config.json where you can add the Supabase databases you want to keep active. You'll need your Supabase project URL and API keys.

[
  {
    "name": "Database1",
    "supabase_url": "https://your-supabase-url-1.supabase.co",
    "supabase_key_env": "SUPABASE_KEY_1",  // Use environment variable for the key
    "table_name": "KeepAlive"
  },
  {
    "name": "Database2",
    "supabase_url": "https://your-supabase-url-2.supabase.co",
    "supabase_key": "your-direct-supabase-key",  // Directly define the key
    "table_name": "keep-alive"
  }
]

4. Set Up a Cron Job:

To ensure your databases stay active, schedule the script to run at least once a week. If you're using a Linux or Mac system, you can set up a cron job like this:

crontab -e

Add the following line to run the script every day at midnight:

0 0 * * 1,4 cd /path/to/your/project && /path/to/your/project/venv/bin/python main.py >> /path/to/your/project/logfile.log 2>&1

This ensures that your Supabase databases will always have activity within the 7-day window, keeping them from being paused.

View the README for a detailed explanation and walkthrough

Supabase Pause Prevention: An Alternative Using Next.js

For those who prefer working with Next.js, Supabase Pause Prevention is another option. While not as streamlined as the Python solution, it serves the same purpose by making calls to the APIs of other projects in your Supabase setup, ensuring that each project records activity.

Key Features:

  • Designed specifically for Next.js projects using Supabase.
  • Prevents project pauses by making API calls to keep databases active.
  • Easy integration with your existing Next.js setup.

How to Set Up Supabase Pause Prevention:

Solution / How it works

  • Creating a cron job (scheduled task) that makes a simple database call
    • (This keeps your Supabase project active)
  • Fetching keep-alive.ts API endpoints for the other projects, as Vercel limits free-tier users to one cron job.

Getting Started

Super simple to add to your existing Supabase project!

Configure your main project

Only 3 files matter

utils/supabase folder contains files provided in the Supabase docs for the Next.js Web App demo — Supabase

Everything else is boilerplate from Next.js create-next-app

Configuring your other Supabase projects

After selecting your primary project (the one that implements the code provided in this repository), you'll want to add an API endpoint to your other Supabase projects

The only requirement is that this endpoint is reachable and makes a call to your Supabase database

API endpoint must make database call
Ensure the server doesn't cache this

Example of a setup using Prisma as an ORM

/pages/api/keep-alive.ts

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
import { prisma } from 'src/server/db'

// See next example for contents of @/utils/helper
import { generateRandomString } from '@/utils/helper'

export default async function handler(
  _req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    const randomString = generateRandomString()
    const dbResponse = await prisma.keepAlive.findMany({
      where: {
        name: {
          equals: randomString,
        }
      }
    })
    const successMessage = (dbResponse != null) ? `Success - found ${dbResponse.length} entries` : "Fail"
    res.status(200).json(successMessage)
  } catch (e) {
    res.status(401).send("There was an error")
  }
}

/prisma/schema.prisma

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["postgresqlExtensions"]
}

datasource db {
  provider   = "postgresql"
  url        = env("DATABASE_URL")
  extensions = [uuidOssp(map: "uuid-ossp")]
}

model KeepAlive {
  id     BigInt  @id @default(autoincrement())
  name   String? @default("")
  random String? @default(dbgenerated("gen_random_uuid()")) @db.Uuid
}
Helper function for '/pages' directory (legacy support)

/utils/helper.ts

const defaultRandomStringLength: number = 12

const alphabetOffset: number = 'a'.charCodeAt(0)
export const generateRandomString = (length: number = defaultRandomStringLength) => {
  let newString = ''

  for (let i = 0; i < length; i++) {
    newString += String.fromCharCode(alphabetOffset + Math.floor(Math.random() * 26))
  }

  return newString
}

Sample SQL

Any table and column can be called, but if you'd rather go with a generic, here's a SQL query for a keep-alive table

CREATE TABLE "keep-alive" (
  id BIGINT generated BY DEFAULT AS IDENTITY,
  name text NULL DEFAULT '':: text,
  random uuid NULL DEFAULT gen_random_uuid (),
  CONSTRAINT "keep-alive_pkey" PRIMARY key (id)
);

INSERT INTO
  "keep-alive"(name)
VALUES
  ('placeholder'),
  ('example');

It is now strongly recommended to use a keep-alive table like the one above.
This is in light of the added features for optional database insertion & deletion actions

View the README for a detailed explanation and walkthrough

Wrapping it up

Whether you choose to use Python or integrate into your existing Next.js project, Supabase Inactive Fix and Supabase Pause Prevention are both excellent ways to keep your Supabase databases from being paused due to inactivity. With just a few steps, you can set up automated scripts to ensure your projects are always online and ready for use.

Check out the repositories on GitHub:

Both of these tools are easy to set up and will save you the hassle of manually unpausing your databases every week. Happy coding!

This post was originally published on Basics Guide