Skip to content

Load balancer tweaks #180

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,12 @@ jobs:
cmake --version
cargo install cargo-nextest --version "0.9.78" --locked
bash integration/toxi/setup.sh
sudo curl -SL https://github.com/docker/compose/releases/download/v2.36.1/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
- name: Build PgDog
run: cargo build --release
- name: Load balancer
run: bash integration/load_balancer/run.sh
- name: pgbench
run: bash integration/pgbench/run.sh
- name: Go
Expand Down
8 changes: 5 additions & 3 deletions integration/go/go_pgx/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@ module pg_tests
go 1.24.3

require (
github.com/jackc/pgx/v5 v5.7.4
github.com/jackc/pgx/v5 v5.7.5
github.com/stretchr/testify v1.10.0
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
golang.org/x/crypto v0.31.0 // indirect
golang.org/x/text v0.21.0 // indirect
golang.org/x/crypto v0.37.0 // indirect
golang.org/x/sync v0.13.0 // indirect
golang.org/x/text v0.24.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
8 changes: 8 additions & 0 deletions integration/go/go_pgx/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7Ulw
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/jackc/pgx/v5 v5.7.5 h1:JHGfMnQY+IEtGM63d+NGMjoRpysB2JBwDr5fsngwmJs=
github.com/jackc/pgx/v5 v5.7.5/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
Expand All @@ -25,10 +27,16 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOf
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
Expand Down
238 changes: 238 additions & 0 deletions integration/go/go_pgx/load_balancer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
package main

import (
"context"
"fmt"
"testing"

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/stretchr/testify/assert"
)

const createTables = `
CREATE TABLE IF NOT EXISTS companies (
company_id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS users (
user_id BIGSERIAL PRIMARY KEY,
company_id BIGINT NOT NULL,
username TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS notes (
note_id BIGSERIAL PRIMARY KEY,
company_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
content TEXT NOT NULL
);
`

const dropTables = `
DROP TABLE IF EXISTS notes;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS companies;
`

func migrate(t *testing.T, pool *pgxpool.Pool) error {
ctx := context.Background()
_, err := pool.Exec(ctx, createTables)
assert.NoError(t, err)
_, err = pool.Exec(ctx, "INSERT INTO companies(name) VALUES($1) ON CONFLICT DO NOTHING;", "TestCo")
assert.NoError(t, err)
_, err = pool.Exec(ctx, "INSERT INTO users(company_id, username) VALUES($1, $2) ON CONFLICT DO NOTHING", 1, "bob")
assert.NoError(t, err)
_, err = pool.Exec(ctx, "INSERT INTO notes(company_id, user_id, content) VALUES($1, $2, $3) ON CONFLICT DO NOTHING;", 1, 1, "Initial Note")
assert.NoError(t, err)

return err
}

func dropAll(pool *pgxpool.Pool) error {
_, err := pool.Exec(context.Background(), dropTables)
return err
}

var readQueries = []struct {
q string
args []any
}{
{"SELECT * FROM companies WHERE company_id = $1;", []any{1}},
{"SELECT username FROM users WHERE user_id = $1;", []any{1}},
{"SELECT COUNT(*) FROM notes WHERE company_id = $1;", []any{1}},
{"SELECT note_id, content FROM notes WHERE company_id = $1;", []any{1}},
{"SELECT u.username, n.content FROM users u JOIN notes n ON u.user_id = n.user_id WHERE u.company_id = $1", []any{1}},
{"SELECT company_id FROM companies WHERE name LIKE $1", []any{"A%"}},
{"SELECT EXISTS(SELECT 1 FROM users WHERE username = $1);", []any{"bob"}},
{"SELECT n.content FROM notes n JOIN users u ON n.user_id = u.user_id WHERE u.username = $1;", []any{"bob"}},
{"SELECT * FROM users WHERE company_id IN (SELECT company_id FROM companies WHERE name = $1);", []any{"TestCo"}},
{"SELECT COUNT(*) FROM companies WHERE name = $1;", []any{"TestCo"}},
}

var writeQueries = []struct {
q string
args []any
}{
{"INSERT INTO companies(name) VALUES($1)", []any{"ACME Inc."}},
{"INSERT INTO users(company_id, username) VALUES($1, $2);", []any{1, "bob"}},
{"INSERT INTO notes(company_id, user_id, content) VALUES($1, $2, $3);", []any{1, 1, "Hello!"}},
{"UPDATE users SET username = $1 WHERE user_id = $2;", []any{"alice", 1}},
{"UPDATE notes SET content = $1 WHERE note_id = $2;", []any{"Updated", 1}},
{"DELETE FROM notes WHERE note_id = $1", []any{1}},
{"DELETE FROM users WHERE user_id = $1;", []any{1}},
{"TRUNCATE notes;", nil},
{"INSERT INTO companies(name) VALUES($1);", []any{"Globex"}},
{"UPDATE companies SET name = $1 WHERE company_id = $2;", []any{"MegaCorp", 1}},
}

func getPool(t *testing.T) *pgxpool.Pool {
ctx := context.Background()
dsn := "postgres://pgdog:[email protected]:6432/pgdog?sslmode=disable"

config, err := pgxpool.ParseConfig(dsn)
assert.NoError(t, err)
config.MaxConns = 32 // increase pool size for heavy test concurrency

pool, err := pgxpool.NewWithConfig(ctx, config)

assert.NoError(t, err)

return pool

}

func runTest(t *testing.T, pool *pgxpool.Pool) {
ctx := context.Background()

t.Run("Read queries are handled as reads", func(t *testing.T) {
for i, q := range readQueries {
t.Run(fmt.Sprintf("read_query_%d", i), func(t *testing.T) {
// t.Parallel()
rows, err := pool.Query(ctx, q.q, q.args...)
rows.Close()
assert.NoError(t, err, "Query failed: %s", q.q)
})
}
})

t.Run("Write queries are handled as writes", func(t *testing.T) {
for i, q := range writeQueries {
t.Run(fmt.Sprintf("write_query_%d", i), func(t *testing.T) {
// DO NOT parallelize writes! Leave out t.Parallel() here.
if q.args == nil {
_, err := pool.Exec(ctx, q.q)
assert.NoError(t, err, "Query failed: %s", q.q)
} else {
_, err := pool.Exec(ctx, q.q, q.args...)
assert.NoError(t, err, "Query failed: %s", q.q)
}
})
}
})
}

func TestRoundRobinWithPrimary(t *testing.T) {
adminCommand(t, "RELOAD")
adminCommand(t, "SET load_balancing_strategy TO 'round_robin'")
pool := getPool(t)

migrate(t, pool)

defer func() {
_ = dropAll(pool)
}()

prewarm(t, pool)

transPrimaryBefore, queriesPrimaryBefore := getTransactionsAndQueries(t, "primary")
transReplicaBefore, queriesReplicaBefore := getTransactionsAndQueries(t, "replica")

runTest(t, pool)

transPrimaryAfter, queriesPrimaryAfter := getTransactionsAndQueries(t, "primary")
transReplicaAfter, queriesReplicaAfter := getTransactionsAndQueries(t, "replica")

fmt.Printf("%d %d %d %d\n%d %d %d %d\n", transPrimaryBefore, queriesPrimaryBefore, transReplicaBefore, queriesReplicaBefore, transPrimaryAfter, queriesPrimaryAfter, transReplicaAfter, queriesReplicaAfter)
}

func adminCommand(t *testing.T, command string) {
conn, err := pgx.Connect(context.Background(), "postgres://admin:[email protected]:6432/admin")
assert.NoError(t, err)
defer conn.Close(context.Background())

rows, err := conn.Query(context.Background(), command, pgx.QueryExecModeSimpleProtocol)
Copy link
Preview

Copilot AI May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add an assert.NoError(t, err) after this query to catch any errors during the admin command execution.

Suggested change
rows, err := conn.Query(context.Background(), command, pgx.QueryExecModeSimpleProtocol)
rows, err := conn.Query(context.Background(), command, pgx.QueryExecModeSimpleProtocol)
assert.NoError(t, err)

Copilot uses AI. Check for mistakes.

defer rows.Close()
}

func getTransactionsAndQueries(t *testing.T, role string) (int64, int64) {
conn, err := pgx.Connect(context.Background(), "postgres://admin:[email protected]:6432/admin")
assert.NoError(t, err)
defer conn.Close(context.Background())

rows, err := conn.Query(context.Background(), "SHOW STATS", pgx.QueryExecModeSimpleProtocol)
defer rows.Close()

assert.NoError(t, err)

var totalQueryCount float64
var totalTransactionCount float64

outer:
for rows.Next() {
values, err := rows.Values()
if err != nil {
panic(err)
}

for i, description := range rows.FieldDescriptions() {
if description.Name == "database" {
db := values[i].(string)
if db != "pgdog" {
continue outer
}
}

if description.Name == "user" {
db := values[i].(string)
if db != "pgdog" {
continue outer
}
}

if description.Name == "role" {
db_role := values[i].(string)
if db_role != role {
continue outer
}
}

if description.Name == "total_xact_count" {
transactions := values[i].(pgtype.Numeric)
v, err := transactions.Float64Value()
assert.NoError(t, err)
totalTransactionCount = v.Float64
}

if description.Name == "total_query_count" {
queries := values[i].(pgtype.Numeric)
v, err := queries.Float64Value()
assert.NoError(t, err)
totalQueryCount = v.Float64
}
}
}

return int64(totalQueryCount), int64(totalTransactionCount)
}

func prewarm(t *testing.T, pool *pgxpool.Pool) {
for range 25 {
for _, q := range []string{"BEGIN", "SELECT 1", "COMMIT", "SELECT 1"} {
_, err := pool.Exec(context.Background(), q)
assert.NoError(t, err)
}
}
}
14 changes: 12 additions & 2 deletions integration/go/go_pgx/pg_tests_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,33 @@ package main
import (
"context"
"fmt"
"math/big"
"math/rand"
"os"
"testing"
"time"

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/stretchr/testify/assert"
)

func assertNoOutOfSync(t *testing.T) {
zero := pgtype.Numeric{
Int: big.NewInt(0),
Exp: 0,
NaN: false,
Valid: true,
}

conn, err := pgx.Connect(context.Background(), "postgres://admin:[email protected]:6432/admin")
if err != nil {
panic(err)
}
defer conn.Close(context.Background())

rows, err := conn.Query(context.Background(), "SHOW POOLS", pgx.QueryExecModeSimpleProtocol)
assert.NoError(t, err)
defer rows.Close()

for rows.Next() {
Expand All @@ -30,8 +40,8 @@ func assertNoOutOfSync(t *testing.T) {

for i, description := range rows.FieldDescriptions() {
if description.Name == "out_of_sync" {
out_of_sync := values[i].(int64)
assert.Equal(t, out_of_sync, int64(0), "No connections should be out of sync")
out_of_sync := values[i].(pgtype.Numeric)
assert.Equal(t, out_of_sync, zero, "No connections should be out of sync")
return
}
}
Expand Down
2 changes: 2 additions & 0 deletions integration/load_balancer/admin.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/bash
PGPASSWORD=pgdog psql -h 127.0.0.1 -p 6432 -U pgdog admin
14 changes: 11 additions & 3 deletions integration/load_balancer/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,28 @@ services:
volumes:
- ./docker/primary.sh:/docker-entrypoint-initdb.d/setup.sh
ports:
- 5433:5432
- 45000:5432
replica_1:
image: postgres:17
environment:
POSTGRES_PASSWORD: postgres
volumes:
- ./docker/replica.sh:/docker-entrypoint-initdb.d/setup.sh
user: postgres
entrypoint:
- bash
- /docker-entrypoint-initdb.d/setup.sh
ports:
- 5434:5432
- 45001:5432
replica_2:
image: postgres:17
environment:
POSTGRES_PASSWORD: postgres
volumes:
- ./docker/replica.sh:/docker-entrypoint-initdb.d/setup.sh
user: postgres
entrypoint:
- bash
- /docker-entrypoint-initdb.d/setup.sh
ports:
- 5435:5432
- 45002:5432
1 change: 1 addition & 0 deletions integration/load_balancer/docker/postgresql.auto.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
shared_preload_libraries = 'pg_stat_statements'
5 changes: 4 additions & 1 deletion integration/load_balancer/docker/primary.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,7 @@ DATA_DIR=/var/lib/postgresql/data

# Enable replication connection
echo "host replication all all scram-sha-256" >> ${DATA_DIR}/pg_hba.conf
pg_ctl -D ${DATA_DIR} reload
echo "shared_preload_libraries = 'pg_stat_statements'" >> ${DATA_DIR}/postgresql.auto.conf
pg_ctl -D ${DATA_DIR} restart

psql -c 'CREATE EXTENSION pg_stat_statements'
Loading
Loading