Connect to a read replica database

⚠️ This tutorial is for SQL databases only.

A read replica is a copy of the master that reflects changes to the master instance in almost real time. For performance reasons, you can specify one or more servers to act as read replicas, and one server to act as the write master, which handles all writes and updates and propagates them to the replicas. For example, your read replica will be used while displaying the table view of your records or accessing your Forest Admin dashboard.

As your Admin Backend relies on the Sequelize ORM, it's quite easy to configure a read replication.

This code snippet is an example. It is strongly advised to use environment variables for your database connection credentials.

models/index.js
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
let databaseOptions = {
logging: process.env.NODE_ENV === 'development' ? console.log : false,
dialect: 'postgresql',
port: 5435,
replication: {
read: [{
host: 'ec2-52-219-116-175.us-west-1.compute.amazonaws.com',
username: 'userRead',
password: 'passwordUserRead',
database: 'databaseReplicate',
}],
write: {
host: 'ec2-52-219-125-185.eu-west-1.compute.amazonaws.com',
username: 'userWrite',
password: 'passwordUserWrite',
database: 'databaseMaster',
}
},
pool: {
maxConnections: 10,
minConnections: 1,
},
dialectOptions: {}
};
if (process.env.DATABASE_SSL && JSON.parse(process.env.DATABASE_SSL.toLowerCase())) {
databaseOptions.dialectOptions.ssl = true;
}
let sequelize = new Sequelize(databaseOptions);
let db = {};
fs
.readdirSync(__dirname)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js');
})
.forEach(function (file) {
try {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
} catch (error) {
console.error('Model creation error: ' + error);
}
});
Object.keys(db).forEach(function(modelName) {
if ('associate' in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;