Moodle database read replicas

Moodle can send selected read queries to PostgreSQL or MySQL replicas through its readonly database settings, but replicas only help when reads are the bottleneck. This page covers the configuration, latency trade-offs and what to confirm first.

On this page

When Moodle database read replicas help a slow site

When a Moodle site slows under load, the question of adding a database read replica often arrives early, sometimes before anyone has checked where the time goes. Read replicas only help when database reads are the actual constraint. In Moodle, the supported way to send read queries to a replica is the readonly section of config.php, which lets the site direct selected read traffic to replica hosts while writes continue to go to the primary. If the slowness comes from PHP workers waiting on sessions, from cache misses, from a locked cron task, or from heavy file downloads, a replica will leave those symptoms untouched. The first step is evidence, not configuration.

Moodle's core documentation describes the readonly settings, the replica lag tolerance that controls how stale data a read may return, and the option to exclude specific tables from replica reads. Those settings are where the work starts, not where it ends. Before changing them, collect profiling output from the profiling admin tool and the performance report, and enable slow query logging on the primary so you can see which statements dominate wall-clock time and whether they are reads. Ask the team to confirm that the replica engine and version match the primary, since replication lag and read consistency depend on it. The companion pages on profiling slow Moodle pages and on the shared directories and session handling for a cluster explain how to separate database pressure from the other causes of slowness, and this section should be read alongside them.

What read replicas do and do not fix in Moodle

This is the case where a read replica helps. When most of the slow queries are SELECT statements that run against large course, log or grade tables, and the primary server's CPU or I/O is saturated by those reads, Moodle can send eligible reads to a replica through the readonly settings in config.php. The gain depends on how much of the read load is safe to move. Reports, grade views and some course pages are common candidates, while anything that must reflect a write made seconds earlier is not.

  • Measure first: Confirm from slow query logs or the profiling tool that reads, not writes, dominate the database time before adding a replica.
  • Set readonly dboptions: Define the replica host in the $CFG->dboptions readonly block so Moodle routes eligible reads there.
  • Check replication latency: Set latency to reflect how far the replica may trail the primary, since reads inside that window can return stale data.
  • Exclude sensitive tables: Use the excluded tables list for tables where a stale read would cause a wrong answer, such as session-adjacent or lock data.
  • Size the replica: Give the replica enough memory and I/O to serve the read volume, and confirm failover behaviour with your database team.

Before going live, ask your team to confirm the replica lag under peak write load and test the pages that must show fresh data.

Configuration options and when each fits

This table compares the settings and database engines that decide how a Moodle site sends reads to a replica. Read each row as a decision: what the option does, when it fits and what it costs in data freshness or operations. The main takeaway is that the latency setting and the exclusion list decide whether users see stale data, so test both before any production read traffic goes to a replica.

OptionWhat it doesWhen it fitsTrade-off
Readonly instance split (dboptions readonly)Sends read queries to one or more replica hosts while writes stay on the primaryRead-heavy sites where reports, course views and browsing dominate database loadAdds a second database to configure, monitor and keep healthy
Replication latency settingKeeps reads on the primary for a set window after a write so users see their own changesSites with asynchronous replicas that lag behind the primary during busy periodsLonger windows send more traffic back to the primary and reduce offload
Table exclusion listForces named tables to always read from the primaryTables where a stale read would break logic, such as sessions, locks, queues or grades in progressEach excluded table adds load to the primary, so keep the list short
PostgreSQL 15 (Moodle 5.1)Streaming replicas can serve reads for Moodle 5.1 on the supported PostgreSQL versionSites already running PostgreSQL 15 that want replicas without a major engine changeConfirm the replica setup and lag behavior against the PostgreSQL 15 documentation
PostgreSQL 17 (Moodle 5.3)Required on the primary and replicas for Moodle 5.3 on the supported PostgreSQL versionSites moving to Moodle 5.3 that plan replicas as part of the upgradeReplica and primary versions must be aligned, so the database upgrade and the Moodle upgrade need one plan
MySQL 8.4 (Moodle 5.1 and 5.3)Supported database engine for both 5.1 and 5.3 with replica setupsOrganizations with existing MySQL operations skills and toolingConfirm the replication mode, lag metrics and failover steps with your database team before go-live
Single primary only (no replicas)All reads and writes go to one database hostSmaller sites, or sites where profiling shows the bottleneck is PHP, cache or file servingRead load grows on one host, so headroom must be tested before peak events

Setting up replicas for Moodle in sequence

This sequence moves read traffic from a Moodle primary database to one or more replicas in a controlled order, so each change is verified before the next one is made. The end result is a site where reads go to replicas, write-after-read pages still show current data, and the performance evidence confirms the change helped.

  1. Confirm Moodle and database versions

    Check the Moodle release you run against the Moodle 5.1 or 5.3 release notes, and confirm that your PostgreSQL or MySQL version is on the supported list for that release. The Moodle 5.1 notes list PostgreSQL 15, MySQL 8.4 and MariaDB 10.11 as supported database versions, and the Moodle 5.3 notes list PostgreSQL 17, MySQL 8.4 and MariaDB 11.4. Also confirm the upgrade path if you are behind. Record the versions in the change ticket. The step is done when the versions are written down and confirmed against the release notes for the exact Moodle build you run, not only the major version.

  2. Build and verify database replication

    Your database team builds the replica using the replication method your database platform supports, such as streaming replication for PostgreSQL or source-replica replication for MySQL or MariaDB. Confirm that the replica accepts connections from the Moodle web and cron nodes, that it is read-only at the database level, and that it is current. Measure replication lag under normal write load for several business days, not one quick test. The step is done when you have a documented lag baseline and a failover owner for the replica.

  3. Configure readonly dboptions in config.php

    Add a readonly section to the dboptions array in config.php, with the replica host or hosts listed under it, and keep the primary as the main connection. Moodle sends reads to the replica and writes to the primary. Deploy the change to one web node first and keep a copy of the previous config.php for rollback. Confirm the setting by loading a course page and checking the database connection in the logs or the performance report. The step is done when one node reads from the replica without errors and the primary still takes all writes.

  4. Set replication latency and write-after-read handling

    Set the replication latency tolerance in Moodle so that pages which must show data just written, such as a grade just saved or a submission just uploaded, are read from the primary. Review which of your pages depend on immediate consistency and test each one after a write. Monitor replica lag alongside Moodle's behavior. The step is done when a test user saves a grade or submits an assignment and sees the new value immediately on the next page, across several repeated trials.

  5. Exclude tables that must read from the primary

    Identify tables that must always be read from the primary, such as session-related or lock-related tables, and any tables that change constantly and would produce stale reads if served from a lagging replica. Add these to the excluded table list in the readonly configuration. Keep the list short and documented, and review it after each Moodle upgrade because table use changes between releases. The step is done when the exclusion list is in config, each entry has a stated reason, and an outage test on the replica does not break logins or cron.

  6. Roll out to all nodes and monitor lag

    Once one node behaves correctly, apply the same configuration to the remaining web and cron nodes, one at a time, with a rollback step ready for each. Keep replica lag on an alert so that a lagging replica is noticed before users report stale data. The step is done when every node reads from the replica, lag alerts are live, and the rollback has been tested once.

  7. Verify with the performance report and slow query logs

    Compare page timings and database load before and after the change using Moodle's performance report and your database slow query log, over the same kind of working period. Check that reads moved to the replica, that primary load fell as expected, and that no new errors or stale-data reports appeared. Record the findings, including pages that did not improve, since replicas do not fix every slow page. The step is done when the before and after evidence is written up and any remaining slow pages are assigned to a profiling or code fix.

How queries route between the primary and replicas

The path starts at the Moodle web nodes, which send writes and any read that must see fresh data to the primary database. Ordinary reads go to a replica, and the primary streams changes to replicas, so a replica can trail behind by the replication lag you configure. Check the tables you exclude from replica reads, because those queries always return to the primary and keep load on it.

Writes and excluded tables go to the primary, ordinary reads go to replicas.

Where replica setups go wrong

A read replica moves some load off the primary, but it also introduces timing, routing and failover behavior that a single database never had. The cards below cover the places where Moodle installs most often break after a replica is added, and the checks that catch each one before users do.

Stale reads after writes

A student submits an assignment or finishes a quiz attempt, then the next page reads that data from a replica that has not applied the write yet. The student may see a missing submission or an unfinished attempt and retry. Test the exact flows that write and immediately read back: quiz attempt submission, assignment submission, forum posts and grade views. Confirm which of these pages Moodle sends to the primary under your configuration.

Replica lag under peak load

Replication lag is usually small on a quiet site and grows during exam starts, bulk enrolments or large backups, which are the moments when reads matter most. Measure lag on the replica during a realistic load test, not only at idle. Ask your database team which lag threshold triggers an alert and what happens to reads when the replica falls behind.

Tables that must stay on the primary

Some tables are written and read in the same request, or hold state that other sessions depend on, so sending them to a replica produces inconsistent results. Moodle's configuration lets you exclude specific tables from read routing. Review each exclusion against the code paths that touch it, and retest after every Moodle upgrade, since new features add new tables and queries.

Session and lock traffic on the primary

Sessions, cache locks and task locks are written on almost every request, so a replica does not remove that load. A site that adds a replica but keeps sessions in the database may see little improvement. Check where session and lock data is stored before you measure results, and plan the session and lock stores as separate work.

Failover handling for the replica

When a replica fails or is promoted, Moodle must be pointed at a working host, and the configuration has to change without a long outage. Decide in advance whether reads fall back to the primary, how the replica is rebuilt, and who approves the switch. Rehearse the failover in a non-production environment and record the steps as a runbook.

Security and operations for replica-backed Moodle

The first decision for a replica-backed Moodle is which database accounts Moodle uses and what each one can do. The primary account needs the full set of rights Moodle uses for installs, upgrades, cron and task writes. The replica account should be read-only at the database level, not just in Moodle configuration, so that a misrouted write fails in the database instead of silently diverging. Confirm with your database vendor's documentation how read-only grants work for your engine and version, and test that an insert attempted through the replica account is refused. Keep the credentials for both accounts in your secrets store, and rotate them through the same process you use for the primary.

Network and transport controls matter as much as accounts. Moodle web and cron nodes must reach the replicas over a private path, with firewall rules that allow the replica port only from application subnets. Encrypt those connections with TLS and verify the server certificate on the client side, using the connection options your PHP database driver supports; confirm the exact settings against the Moodle installation documentation for your database. Monitor replication lag as a production signal: track the delay between primary and each replica, and decide in advance which pages may read stale data and which must always read the primary, because the read-only database options only route reads that you have explicitly allowed. Alert on lag and on replica disconnects, and test what Moodle does when a replica is unavailable.

Backups and upgrades change the picture in two ways. Replicas are not backups: a dropped table replicates within seconds, so point-in-time recovery must be planned on the primary, and replica snapshots are useful mainly for fast failover or reporting. Restore tests should cover both. Before any Moodle upgrade, check the database versions in the release notes for the target branch, because the minimum PostgreSQL or MySQL version can change between releases, and a replica must be upgraded to the same supported level as the primary. Schedule these steps in a single change window, and rerun the lag and routing tests afterward, since upgrades can alter the tables and queries that your exclusion list depends on.

Limits to confirm in your environment

A read replica changes where Moodle sends some queries, not how much work the site does or how its plugins behave. The items below are the assumptions that decide whether a replica helps your site, and each one should be confirmed against the exact Moodle version, database platform and plugin set you run.

Exact dboptions behaviour in your version

The readonly block in config.php and the options inside it control which connections Moodle treats as read-only and how lag is handled. Behaviour and option names can change between releases, so read the settings reference for the Moodle version you run rather than copying examples from older sites. Test on a staging copy that writes and reads are routed where you expect, and that a write followed by a read in the same request returns current data.

Moodle 5.1 notes

Engine and replication method support

Confirm that your PostgreSQL or MySQL version is on Moodle's supported list for your release, and that your replication method (streaming, logical, binlog-based or a managed service feature) is one Moodle and your vendor both support. For example, Moodle 5.1 requires PostgreSQL 15 or later, and Moodle 5.3 requires PostgreSQL 17. Ask the vendor in writing whether the replica type you plan to use is supported with that Moodle release.

Moodle 5.3 notes

Replica lag your workload tolerates

Replicas trail the primary by a variable delay, and that delay grows under heavy write load, long transactions or network trouble. Decide which pages can show slightly old data (course listings, reports, dashboards) and which must never do so (quiz attempts, grade submission, enrolment checks). Measure lag under exam-day or peak conditions on your own hardware before you set any tolerance in configuration.

Licensing and hosting limits

Read replicas can be restricted by your database license, edition, or managed-service tier. Some platforms charge for replica instances, limit the number of replicas, or require specific networking, so the cost of an extra node can recur every month. Confirm with the database vendor or managed-service provider what the replica costs, where it may run, and whether it can sit inside the network zone your security team has approved.

Plugin queries that bypass routing

Core Moodle code and third-party plugins do not all use the same database API calls. A plugin that writes through a read-only handle, runs its own connection, or reads data it has just changed can return stale results or fail. Inventory the plugins you run, review how each one queries the database, and check their release notes for read-after-write assumptions before you assign any tables or connections to a replica.

Moodle plugin types

Whether a replica fixes your slowness

Before you buy or build a replica, confirm the bottleneck. If slow pages are caused by PHP workers, sessions, cache misses, heavy cron tasks or missing indexes, a replica moves some read load but leaves those causes in place. Profile the site, check slow query logs and separate read load from write load. Ask the team who will run the replica what it will and will not fix, and write that down before the work starts.

Read replica questions buyers ask before hiring help

Will a read replica fix a slow Moodle?

Only when the slowness comes from read load on the database. A replica takes read queries off the primary, which can help when reports, course views and background reads are competing with writes. It does not speed up slow PHP code, missing indexes on the primary, slow cron tasks that write heavily, or a session or cache layer that is misconfigured. Before buying a replica, profile where the time goes, check slow query logs and confirm that database CPU or I/O on the primary is the constraint. If it is not, a replica adds cost and a second database to operate without removing the bottleneck.

What drives the cost of setting up Moodle read replicas?

The main cost is engineering time for the database, the Moodle configuration and the testing. Those costs rise with the number of web nodes, the database engine and version, whether replication already exists, how many tables need to be excluded from replica reads, and how much testing the team needs to prove that stale reads do not affect users. Ongoing costs include the replica hardware or cloud instances, monitoring, backups for the replica, and upgrades that must be coordinated across both servers. Ask any provider to split one-time setup from recurring support and to state which parts depend on your existing infrastructure.

How long does a read replica setup take?

Duration depends on the environment more than on Moodle itself. A team with a replication topology already running, a staging copy of production and automated deployment will move faster than one that must first build replication, network paths and monitoring. Other drivers include change control windows, the number of Moodle nodes that read the configuration, how much load testing is needed, and whether the replica must sit in a different data center or air-gapped network. Ask for a timeline built from a written scope with named milestones, and confirm which of your own approvals sit on the critical path.

What does our team need to provide for a replica project?

You need someone who owns the database platform, someone who runs the Moodle site, and access to a staging environment that mirrors production closely enough to test replica behavior. The database owner must confirm replication type, failover expectations, backup scope and network rules between web nodes and replicas. The Moodle owner must confirm which features depend on fresh data, such as quiz attempts, grade entry, enrolment changes and admin reports. Without these inputs, the work tends to stall in discovery, so list them as prerequisites in the scope.

Can our own administrators set up Moodle read replicas?

Yes, if they already run PostgreSQL or MySQL replication, can edit Moodle's configuration safely and can test changes in staging. The hard parts are not the configuration keys. They are choosing which queries may read from a replica, excluding tables that need read-after-write consistency, handling replication lag, and checking the result under realistic load. Teams new to replication often underestimate failover and monitoring. A reasonable test is whether your admins can explain, for each excluded table, why it must read from the primary.

Which Moodle settings and tables need the most care?

The readonly database options and replication latency settings decide which reads go to the replica and how long Moodle tolerates lag. Tables that hold data written and read within the same request, such as session-related or quiz attempt data, need careful review before any change. Confirm your Moodle version against the supported database versions in the release notes before you start, since the minimum database version changes with each major release. Document each exclusion and test it, because a wrong exclusion shows up as confusing user-facing errors rather than a clear failure.

What should a quote for Moodle read replicas include?

A quote should list the assessment of the current bottleneck, the replica topology and hosting, the database engine and version check, the Moodle configuration changes, the excluded tables with reasons, the test plan with load and lag scenarios, the monitoring and backup changes, the rollback plan and the handover. It should name what the client provides and what happens after go-live. Ask for the fixed scope, deliverables and timeline in writing, and for separate pricing for any retainer covering upgrades and ongoing support. Any quote that skips the profiling step should prompt a question about how the bottleneck was confirmed.

How DeployOpen scopes Moodle read replica work

Replica work starts with profiling evidence, not with a replica. DeployOpen plans, implements and documents self-hosted Moodle inside the client's own infrastructure, and for a read replica the first deliverable is a finding: which pages and background tasks generate the slow reads, how much of that load is read-only, and whether the database server is actually the bottleneck. That evidence comes from the profiling admin tool, the performance report, slow query logs and the database's own metrics. A replica built before this step often moves the problem rather than removing it, so the scope should name the pages and tasks in question before any database topology is chosen.

Each engagement runs under a written fixed scope. Scope, deliverables and timelines are agreed in writing before work starts, and the document should list the replica topology, the Moodle settings the team will change, the tables to be excluded from replica reads, the test cases used to verify behavior, and the runbook for failover and lag incidents. The client's database, network and operations teams should confirm early which platform, version and hosting model they run, because the supported PostgreSQL or MySQL versions for the Moodle release in use are set by Moodle's requirements for that release and must be checked against the current release notes. Anything that depends on the client's own environment, such as replication lag tolerance or maintenance windows, belongs in the scope as a stated assumption.

Ongoing work is available as a retainer, and DeployOpen does not publish a price list. A quote follows from the written scope, so the cost depends on how much profiling, configuration, testing and documentation the client needs and on how many database servers and Moodle nodes are involved. Once replicas are running, replica lag monitoring, failover testing, Moodle upgrades that may change which queries are safe to route to a replica, and periodic reviews of excluded tables are recurring tasks that a retainer can cover. Ask any provider for the deliverables, the assumptions behind the timeline, and which parts recur after handover.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.