AlgoViz

Introduction to data replication

easy 25 min

Replication keeps the same data on several machines and keeps the copies up to date.

A pool that splits reads and writes

Read it, run it, change a line and run it again.

Loading editor…

The nodes are simulated in memory so that the code runs here. `replicate` plays the part of the change log.

The same in TypeScript
interface DatabaseNode { host: string; port: number; region: string; role: "primary" | "replica"; priority: number }interface ReplicationConfig {  primary: DatabaseNode;  replicas: DatabaseNode[];  replicationMode: "sync" | "async" | "semi-sync";  failoverMode: "automatic" | "manual";}interface Connection { execute(query: string, params: unknown[]): Promise<unknown> }class ReplicatedDatabasePool {  private primary: Connection;  private replicas: Connection[];  private next = 0;  constructor(config: ReplicationConfig, connect: (node: DatabaseNode) => Connection) {    this.primary = connect(config.primary);    this.replicas = config.replicas.map(connect);  }  // Writes always go to the primary.  write(query: string, params: unknown[]) { return this.primary.execute(query, params); }  // Reads take turns over the replicas.  read(query: string, params: unknown[]) {    if (this.replicas.length === 0) return this.primary.execute(query, params);    const replica = this.replicas[this.next];    this.next = (this.next + 1) % this.replicas.length;    return replica.execute(query, params);  }  // Reads that must be current.  readFromPrimary(query: string, params: unknown[]) { return this.primary.execute(query, params); }}const node = (host: string, region: string, role: "primary" | "replica", priority: number): DatabaseNode =>  ({ host, port: 5432, region, role, priority });const connect = (n: DatabaseNode): Connection => ({ execute: async (q) => `${n.host}: ${q}` });const pool = new ReplicatedDatabasePool({  primary: node("db-primary.example.com", "us-east-1", "primary", 1),  replicas: [node("db-replica-1.example.com", "us-east-1", "replica", 2), node("db-replica-2.example.com", "us-west-2", "replica", 3)],  replicationMode: "async",  failoverMode: "automatic",}, connect);async function main() {  console.log(await pool.write("INSERT INTO users (name) VALUES ($1)", ["Alice"]));  console.log(await pool.read("SELECT * FROM users WHERE id = $1", [123]));  console.log(await pool.readFromPrimary("SELECT balance FROM accounts WHERE id = $1", [456]));}main();
The same in Go
package databaseimport (	"context"	"database/sql"	"fmt"	"sync/atomic")type Node struct {	Host     string	Port     int	Region   string	Role     string // "primary" or "replica"	Priority int}type Pool struct {	primary  *sql.DB	replicas []*sql.DB	turn     uint64}// Open expects that the caller has imported a PostgreSQL driver named "postgres".func Open(primary Node, replicas []Node) (*Pool, error) {	connect := func(n Node) (*sql.DB, error) {		dsn := fmt.Sprintf("host=%s port=%d dbname=mydb sslmode=require", n.Host, n.Port)		db, err := sql.Open("postgres", dsn)		if err != nil {			return nil, err		}		db.SetMaxOpenConns(20)		return db, nil	}	p, err := connect(primary)	if err != nil {		return nil, err	}	pool := &Pool{primary: p}	for _, r := range replicas {		db, err := connect(r)		if err != nil {			return nil, err		}		pool.replicas = append(pool.replicas, db)	}	return pool, nil}func (p *Pool) Write(ctx context.Context, q string, args ...any) (sql.Result, error) {	return p.primary.ExecContext(ctx, q, args...)}func (p *Pool) Read(ctx context.Context, q string, args ...any) (*sql.Rows, error) {	if len(p.replicas) == 0 {		return p.primary.QueryContext(ctx, q, args...)	}	i := atomic.AddUint64(&p.turn, 1)	return p.replicas[i%uint64(len(p.replicas))].QueryContext(ctx, q, args...)}func (p *Pool) ReadFromPrimary(ctx context.Context, q string, args ...any) (*sql.Rows, error) {	return p.primary.QueryContext(ctx, q, args...)}
The same in Java
import java.sql.*;import java.util.*;import java.util.concurrent.atomic.AtomicInteger;import javax.sql.DataSource;/** One pooled DataSource per node. Connections are closed after use, so the pool never runs dry. */public class ReplicatedDatabasePool {    private final DataSource primary;    private final List<DataSource> replicas;    private final AtomicInteger turn = new AtomicInteger();    public ReplicatedDatabasePool(DataSource primary, List<DataSource> replicas) {        this.primary = primary;        this.replicas = replicas;    }    public int write(String sql, Object... args) throws SQLException {        try (Connection c = primary.getConnection(); PreparedStatement s = c.prepareStatement(sql)) {            bind(s, args);            return s.executeUpdate();        }    }    /** A read that may be slightly old. */    public List<Object> read(String sql, Object... args) throws SQLException {        if (replicas.isEmpty()) return firstColumn(primary, sql, args);        int i = Math.floorMod(turn.getAndIncrement(), replicas.size());        return firstColumn(replicas.get(i), sql, args);    }    /** A read that must be current. */    public List<Object> readFromPrimary(String sql, Object... args) throws SQLException {        return firstColumn(primary, sql, args);    }    private static List<Object> firstColumn(DataSource d, String sql, Object... args) throws SQLException {        try (Connection c = d.getConnection(); PreparedStatement s = c.prepareStatement(sql)) {            bind(s, args);            List<Object> out = new ArrayList<>();            try (ResultSet r = s.executeQuery()) {                while (r.next()) out.add(r.getObject(1));            }            return out;        }    }    private static void bind(PreparedStatement s, Object... args) throws SQLException {        for (int i = 0; i < args.length; i++) s.setObject(i + 1, args[i]);    }}