• Stars
    star
    190
  • Rank 203,739 (Top 5 %)
  • Language
    Elixir
  • License
    MIT License
  • Created 12 months ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Postgres strategy for libcluster

libcluster Postgres Strategy

Hex version badge License badge Elixir CI

Postgres Strategy for libcluster which is used by Supabase on the realtime, supavisor and logflare projects.

You can test it out by running docker compose up

example.png

Installation

The package can be installed by adding libcluster_postgres to your list of dependencies in mix.exs:

def deps do
  [{:libcluster_postgres, "~> 0.1"}]
end

How to use it

To use it, set your configuration file with the informations for your database:

config :libcluster,
  topologies: [
    example: [
      strategy: LibclusterPostgres.Strategy,
      config: [
          hostname: "localhost",
          username: "postgres",
          password: "postgres",
          database: "postgres",
          port: 5432,
          parameters: [],
          # optional, defaults to node cookie
          channel_name: "cluster"
      ],
    ]
  ]

Then add it to your supervision tree:

defmodule MyApp do
  use Application

  def start(_type, _args) do
    topologies = Application.get_env(:libcluster, :topologies)
    children = [
      # ...
      {Cluster.Supervisor, [topologies]}
      # ...
    ]
    Supervisor.start_link(children, strategy: :one_for_one)
  end
end

Why do we need a distributed Erlang Cluster?

At Supabase, we use clustering in all of our Elixir projects which include Logflare, Supavisor and Realtime. With multiple servers connected we can load shed, create globally distributed services and provide the best service to our customers so we’re closer to them geographically and to their instances, reducing overall latency.

Example of Realtime architecture where a customer from CA will connect to the server closest to them and their Supabase instance

Example of Realtime architecture where a customer from CA will connect to the server closest to them and their Supabase instance To achieve a connected cluster, we wanted to be as cloud-agnostic as possible. This makes our self-hosting options more accessible. We don’t want to introduce extra services to solve this single issue - Postgres is the logical way to achieve it.

The other piece of the puzzle was already built by the Erlang community being the defacto library to facilitate the creation of connected Elixir servers: libcluster.

What is libcluster?

libcluster is the go-to package for connecting multiple BEAM instances and setting up healing strategies. libcluster provides out-of-the-box strategies and it allows users to define their own strategies by implementing a simple behavior that defines cluster formation and healing according to the supporting service you want to use.

How did we use Postgres?

Postgres provides an event system using two commands: NOTIFY and LISTEN so we can use them to propagate events within our Postgres instance.

To use this features, you can use psql itself or any other Postgres client. Start by listening on a specific channel, and then notify to receive a payload.

postgres=# LISTEN channel;
LISTEN
postgres=# NOTIFY channel, 'payload';
NOTIFY
Asynchronous notification "channel" with payload "payload" received from server process with PID 326.

Now we can replicate the same behavior in Elixir and Postgrex within IEx (Elixir's interactive shell).

Mix.install([{:postgrex, "~> 0.17.3"}])
config = [
  hostname: "localhost",
  username: "postgres",
  password: "postgres",
  database: "postgres",
  port: 5432
]
{:ok, db_notification_pid} = Postgrex.Notifications.start_link(config)
Postgrex.Notifications.listen!(db_notification_pid, "channel")
{:ok, db_conn_pid} = Postgrex.start_link(config)
Postgrex.query!(db_conn_pid, "NOTIFY channel, 'payload'", [])

receive do msg -> IO.inspect(msg) end
# Mailbox will have a message with the following content:
# {:notification, #PID<0.223.0>, #Reference<0.57446457.3896770561.212335>, "channel", "test"}

Building the strategy

Using the libcluster Strategy behavior, inspired by this GitHub repository and knowing how NOTIFY/LISTEN works, implementing a strategy becomes straightforward:

  1. We send a NOTIFY to a channel with our node() address to a configured channel
# lib/cluster/strategy/postgres.ex:52
def handle_continue(:connect, state) do
    with {:ok, conn} <- Postgrex.start_link(state.meta.opts.()),
         {:ok, conn_notif} <- Postgrex.Notifications.start_link(state.meta.opts.()),
         {_, _} <- Postgrex.Notifications.listen(conn_notif, state.config[:channel_name]) do
      Logger.info(state.topology, "Connected to Postgres database")

      meta = %{
        state.meta
        | conn: conn,
          conn_notif: conn_notif,
          heartbeat_ref: heartbeat(0)
      }

      {:noreply, put_in(state.meta, meta)}
    else
      reason ->
        Logger.error(state.topology, "Failed to connect to Postgres: #{inspect(reason)}")
        {:noreply, state}
    end
  end
  1. We actively listen for new {:notification, pid, reference, channel, payload} messages and connect to the node received in the payload
# lib/cluster/strategy/postgres.ex:80
def handle_info({:notification, _, _, _, node}, state) do
    node = String.to_atom(node)

    if node != node() do
      topology = state.topology
      Logger.debug(topology, "Trying to connect to node: #{node}")

      case Strategy.connect_nodes(topology, state.connect, state.list_nodes, [node]) do
        :ok -> Logger.debug(topology, "Connected to node: #{node}")
        {:error, _} -> Logger.error(topology, "Failed to connect to node: #{node}")
      end
    end

    {:noreply, state}
  end
  1. Finally, we configure a heartbeat that is similar to the first message sent for cluster formation so libcluster is capable of heal if need be
# lib/cluster/strategy/postgres.ex:73
def handle_info(:heartbeat, state) do
    Process.cancel_timer(state.meta.heartbeat_ref)
    Postgrex.query(state.meta.conn, "NOTIFY #{state.config[:channel_name]}, '#{node()}'", [])
    ref = heartbeat(state.config[:heartbeat_interval])
    {:noreply, put_in(state.meta.heartbeat_ref, ref)}
end

These three simple steps allow us to connect as many nodes as needed, regardless of the cloud provider, by utilising something that most projects already have: a Postgres connection.

Acknowledgements

A special thank you to @gotbones for creating libcluster and @kevinbuch_ for the original inspiration for this strategy.

More Repositories

1

supabase

The open source Firebase alternative. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript
72,511
star
2

realtime

Broadcast, Presence, and Postgres Changes via WebSockets
Elixir
6,756
star
3

supabase-js

An isomorphic Javascript client for Supabase. Query your Supabase database, subscribe to realtime events, upload and download files, browse typescript examples, invoke postgres functions via rpc, invoke supabase edge functions, query pgvector.
TypeScript
3,211
star
4

pg_graphql

GraphQL support for PostgreSQL
Rust
2,888
star
5

supavisor

A cloud-native, multi-tenant Postgres connection pooler.
Elixir
1,731
star
6

supabase-py

Python Client for Supabase. Query Postgres from Flask, Django, FastAPI. Python user authentication, security policies, edge functions, file storage, and realtime data streaming. Good first issue.
Python
1,680
star
7

index_advisor

PostgreSQL Index Advisor
PLpgSQL
1,612
star
8

ui

Supabase UI Library
TypeScript
1,563
star
9

auth

A JWT based API for managing users and issuing JWT tokens
Go
1,484
star
10

postgres

Unmodified Postgres with some useful plugins
Shell
1,366
star
11

cli

Supabase CLI. Manage postgres migrations, run Supabase locally, deploy edge functions. Postgres backups. Generating types from your database schema.
Go
1,042
star
12

postgrest-js

Isomorphic JavaScript client for PostgREST.
TypeScript
1,036
star
13

pg_jsonschema

PostgreSQL extension providing JSON Schema validation
Rust
1,008
star
14

postgres-meta

A RESTful API for managing your Postgres. Fetch tables, add roles, and run queries
TypeScript
912
star
15

auth-helpers

A collection of framework specific Auth utilities for working with Supabase.
TypeScript
905
star
16

storage

S3 compatible object storage service that stores metadata in Postgres
TypeScript
776
star
17

supabase-flutter

Flutter integration for Supabase. This package makes it simple for developers to build secure and scalable products.
Dart
719
star
18

supabase-swift

A Swift client for Supabase
Swift
696
star
19

edge-runtime

A server based on Deno runtime, capable of running JavaScript, TypeScript, and WASM services.
Rust
671
star
20

supa_audit

Generic Table Auditing
PLpgSQL
647
star
21

pg_replicate

Build Postgres replication apps in Rust
Rust
564
star
22

wrappers

Postgres Foreign Data Wrapper development framework in Rust.
Rust
549
star
23

stripe-sync-engine

Sync your Stripe account to you Postgres database.
TypeScript
490
star
24

auth-ui

Pre-built Auth UI for React
TypeScript
405
star
25

supabase-dart

A Dart client for Supabase
Dart
399
star
26

pg_crdt

POC CRDT support in Postgres
Rust
395
star
27

dbdev

Database Package Registry for Postgres
PLpgSQL
368
star
28

auth-js

An isomorphic Javascript library for Supabase Auth.
CSS
357
star
29

realtime-js

An isomorphic Javascript client for Supabase Realtime server.
TypeScript
318
star
30

examples-archive

Supabase Examples Archive
TypeScript
287
star
31

pg_netstat

PostgreSQL extension to monitor database network traffic
Rust
247
star
32

postgrest-py

PostgREST client for Python. This library provides an ORM interface to PostgREST
Python
230
star
33

pg_net

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL
C
223
star
34

vecs

Postgres/pgvector Python Client
Python
219
star
35

grid

A react component to display your Postgresql table data. Used in Supabase Dashboard app.
TypeScript
202
star
36

supabase-grafana

Observability for your Supabase project, using Prometheus/Grafana
Shell
187
star
37

vault

Extension for storing encrypted secrets in the Vault
PLpgSQL
174
star
38

headless-vector-search

Supabase Toolkit to perform vector similarity search on your knowledge base embeddings.
TypeScript
155
star
39

workflows

Elixir
139
star
40

postgrest-dart

Dart client for PostgREST
Dart
136
star
41

realtime-py

A Python Client for Phoenix Channels
Python
130
star
42

storage-js

JS Client library to interact with Supabase Storage
TypeScript
129
star
43

walrus

Applying RLS to PostgreSQL WAL
PLpgSQL
119
star
44

setup-cli

A GitHub action for interacting with your Supabase projects using the CLI.
TypeScript
113
star
45

postgres-deno

A PostgreSQL extension for Deno: run Typescript in PostgreSQL functions and triggers.
107
star
46

embeddings-generator

GitHub Action to generate embeddings from the markdown files in your repository.
TypeScript
87
star
47

realtime-dart

A dart client for Supabase Realtime server.
Dart
84
star
48

splinter

Supabase Postgres Linter: Performance and Security Advisors
PLpgSQL
83
star
49

repository.surf

🏄
JavaScript
80
star
50

supabase-ui-web

TypeScript
74
star
51

auth-py

Python client implementation for Supabase Auth
Python
73
star
52

self-hosted-edge-functions-demo

A demo of how to self-host Supabase Edge Functions on Fly.io
TypeScript
72
star
53

ssr

Supabase clients for use in server-side rendering frameworks.
TypeScript
65
star
54

functions-js

TypeScript
62
star
55

supabase-action-example

TypeScript
61
star
56

supautils

PostgreSQL extension that secures a cluster on a cloud environment
C
59
star
57

supabase-admin-api

API to administer the Supabase server (KPS)
Go
51
star
58

nix-postgres

Experimental port of supabase/postgres to Nix
Nix
47
star
59

gotrue-dart

A dart client library for GoTrue.
Dart
46
star
60

benchmarks

SCSS
45
star
61

storage-py

Python
42
star
62

grafana-agent-fly-example

Deploy a Grafana Agent on Fly to scrape Prometheus metrics from Supabase and send them to Grafana Cloud
Shell
36
star
63

functions-relay

API Gateway for Supabase Edge functions
TypeScript
35
star
64

benchmarks-archive

Infrastucture benchmarks
Nix
31
star
65

hibp

Go library for HaveIBeenPwned.org's pwned passwords API.
Go
31
star
66

supabase.ai

iykyk
HTML
27
star
67

terraform-provider-supabase

Go
23
star
68

livebooks

A collection of Elixir Livebooks for Supabase
Dockerfile
21
star
69

storage-dart

Dart client library to interact with Supabase Storage
Dart
21
star
70

orb-sync-engine

TypeScript
12
star
71

functions-py

Python
12
star
72

auth-elements

Components to add Supabase Auth to any application
TypeScript
11
star
73

rfcs

11
star
74

.github

Org-wide default community health files & templates.
10
star
75

scoop-bucket

8
star
76

functions-dart

Dart
8
star
77

test-reports

Repository to store test reports data and host reporting in gh-pages
7
star
78

plug_caisson

An Elixir Plug library for handling compressed requests
Elixir
7
star
79

flyswatter

Deploy a global pinger on Fly
Elixir
6
star
80

tests

TypeScript
4
star
81

mailme

A clone of Netlify's mailme package used in Supabase Auth / GoTrue.
Go
4
star
82

pgextkit

Rust
3
star
83

homebrew-tap

Ruby
3
star
84

fly-preview

TypeScript
3
star
85

shared-types

TypeScript
3
star
86

supa_type

The Missing PostgreSQL Data Types
Nix
3
star
87

test-inspector

Check your test results against the reference run and compare coverage for multiple client libraries
Go
2
star
88

productions

Supabase SynthWave. The best soundtrack to build an app in a weekend and scale to billions.
TypeScript
2
star
89

design-tokens

1
star