Choosing a lock factory for Moodle clusters starts with what runs twice
Pick the lock factory that your shared infrastructure can support reliably, and make that choice before the cluster takes traffic. In a Moodle cluster, cron and adhoc tasks can be triggered from any web or cron node, so two nodes can start the same scheduled job at the same moment. Moodle uses locks so that a task holding a lock runs while other nodes wait or skip it, which only works if every node can see the same lock. Teams need a deliberate choice as soon as they run more than one web node or a separate cron node. A single server can usually keep the default, but the default assumes shared state that a cluster may not provide.
The factories depend on different parts of your stack. The file lock factory writes lock files to disk, so it works only when every node reads and writes the same path reliably. That makes network file systems such as NFS a weak fit, because lock files can be delayed or left behind after a node fails, and a stale lock can quietly stop tasks. The database record lock factory keeps locks in a table, which avoids shared file storage but adds writes to your database. The PostgreSQL and MySQL advisory lock factories ask the database server for a named lock, so the lock lives with the database rather than with any file path. Confirm how each factory behaves in the Moodle version you run, and set the choice in $CFG->lock_factory only after you have checked it.
SQL Server needs its own decision. Confirm which lock factories Moodle supports on Microsoft SQL Server in your version before you design around one, since the options there may not match PostgreSQL or MySQL. Then test the choice on the real topology: run two nodes against the same database, start a long task on one, and confirm that the other waits or skips it as expected. Record the factory, the timeouts and the node that runs cron in your runbook, and review the decision whenever you change database engine or file storage. The database version matters too, since Moodle 5.1 requires PostgreSQL 15, MySQL 8.4, MariaDB 10.11 or Microsoft SQL Server 2017 or later.
Which lock factory fits which cluster
This table compares the four lock factories Moodle can use for cron and scheduled tasks in a cluster, by shared infrastructure, failure behavior, database dependency and operational visibility. Read each row against your own topology, then use the confirmation column to check the points that depend on your environment.
| Factor | File lock factory | Database record lock factory | MySQL and PostgreSQL advisory locks |
|---|---|---|---|
| Shared infrastructure needed | A filesystem every web and cron node can write to at the same path, such as a shared volume | Only the database that Moodle already uses | Only the database that Moodle already uses, with a single database session holding the lock |
| Fit with NFS | Poor fit when NFS locking behaves inconsistently across nodes; confirm lock semantics with your storage team before choosing | Works without depending on NFS lock behavior | Works without depending on NFS lock behavior |
| Failure behavior if a node dies | A stale lock file can remain until it expires or is cleared; confirm the expiry setting for your version | Lock row is held by a transaction and is released when the connection closes; confirm timeout settings | Lock is released when the database session ends; confirm connection pooling does not hold sessions open |
| Database dependency | None beyond normal Moodle storage | Adds rows and writes to the Moodle database for every lock | Uses database lock primitives, so the database must be reachable and healthy for locking to work |
| Operational visibility | Lock files can be inspected on disk, but ownership is not visible in Moodle | Lock rows can be queried in the database, which helps during incidents | Active locks can be seen in database session views; confirm the query your database version supports |
| Best fit | Single-site clusters with a reliable shared filesystem that every node can access consistently | Clusters with no reliable shared filesystem, where the database is well sized and monitored | Clusters on MySQL or PostgreSQL where the database is the common dependency and session pooling is understood |
| Poor fit | Multi-node setups using NFS with unclear locking, or where storage latency is unpredictable | Very busy sites where extra lock writes compete with ordinary queries; test under expected load | Microsoft SQL Server deployments, which do not offer the same advisory lock option; confirm the supported factory for your version |
| Confirm in your environment | Storage locking guarantees, mount options, and who clears stale locks | Table sizing, lock row cleanup, and query load during scheduled tasks | Connection pooler mode, database version, and alerting on long-held sessions |
When NFS or SQL Server makes the default a poor fit
The default lock factory works well when the cluster shares a database and a local or well-understood file system. Two setups change the picture: shared storage mounted over NFS, where file locks depend on the mount and server settings, and Microsoft SQL Server, which offers different database-side locking than MySQL and PostgreSQL. Each card names a risk and a check to run before you commit.
File locks on NFS mounts
File-based locks rely on the file system granting exclusive creation or locking semantics across nodes. On NFS, behavior depends on the client and server versions, the mount options and whether the server enforces locking through its lock manager. A lock file can appear held after a node crashes, or two nodes can briefly both believe they hold it. Test by killing a node mid-task, then confirming that another node takes over after the lock timeout and that no task runs twice.
Lock directory placement
Where the lock files live matters as much as the factory choice. A lock directory on a shared network mount adds a network round trip to every lock operation and widens the failure surface during storage hiccups. Confirm with your storage team which mount options apply, whether the lock directory can sit on node-local disk for single-node tasks, and what happens to pending locks when the NFS server restarts.
Clock and timeout alignment
Lock expiry in a cluster depends on each node agreeing on time, and NFS or storage latency can stretch the period in which a lock is held without anyone noticing. Set the lock timeout with headroom above your longest expected task, and verify that node clocks are synchronized with NTP or your platform's time service. Ask the storage vendor how long a stalled mount can hide a dead client.
SQL Server locking options
Moodle's database lock factory uses the advisory lock support that MySQL and PostgreSQL offer. SQL Server does not expose the same session-level advisory lock behavior, so the database-side option differs and the equivalent needs to be confirmed against the Moodle version you run. Review the Moodle source for the database lock implementation in your release, and ask the database team whether lock timeouts and isolation settings match what cron expects.
Testing SQL Server under cron load
Before choosing a database-backed lock on SQL Server, run scheduled tasks on two or more web nodes at the same time while user traffic continues. Watch for blocked sessions, deadlocks and tasks that wait longer than expected. Record which task runs on which node, confirm that each task executes once per schedule, and keep the database lock wait metrics in your monitoring so a regression is visible after upgrades.
Fallback and change control
If NFS or SQL Server tests fail, the decision is between changing the lock factory, moving the lock directory, or reducing the number of nodes that run cron. Each option has a different ongoing cost. Record the chosen configuration, the test results and the owner of the setting in your change log, and repeat the duplicate-run test after every Moodle upgrade and storage change.
Setting up and testing the lock factory on a cluster
This sequence takes a chosen lock factory from version checks to a verified configuration in which scheduled tasks run once across every node. The output is a documented setting applied consistently, plus test evidence that concurrent cron runs do not duplicate work.
Confirm supported database and PHP versions
Before touching configuration, the platform team checks the target Moodle release's requirements for 64-bit PHP and the database engine, and confirms the site can upgrade from its current version. For Moodle 5.1, the release notes list PHP 8.2 or later, PostgreSQL 15, MySQL 8.4, MariaDB 10.11 or SQL Server 2017 or later. Moodle 5.3 raises the minimums to PHP 8.3, PostgreSQL 17, MariaDB 11.4 and SQL Server 2019. Done when every node reports the same PHP version and the database version is written into the change record with the release notes it was checked against. Confirm any newer release against its own notes before you rely on these figures.
Choose the lock factory for your topology
The architect selects the lock factory from the options the cluster can actually support: file locks on shared storage, database record locks, or the MySQL or PostgreSQL advisory lock types. Record the reasons in the design note, including whether the shared file system is NFS and whether the database is SQL Server, since those are the cases where the default is a poor fit. Done when the design note names one factory, lists the nodes that will use it, and states how a stuck lock is cleared. Ask your Moodle engineers to confirm the factory's current behavior for your release in the Moodle documentation on lock factories.
Apply the same configuration on every node
The platform engineer sets the chosen factory in the site configuration on every web and cron node, and checks that no node still runs a different value from an older file or environment override. Each node should read the same lock factory and any related timeout settings. The exact configuration keys are listed in the Moodle lock factory documentation, so copy them from there rather than from memory. Done when a diff of the effective configuration across all nodes shows identical lock settings and the admin settings page reports the same value on each node.
Run a concurrent scheduled-task test
The QA or platform engineer starts the same scheduled task on at least two nodes at the same moment, using a test task or a non-destructive task in a staging copy of the site. Only one run should proceed while the other waits or skips. Repeat the test with the lock held deliberately to confirm the second node backs off. Done when the test log shows exactly one execution per start attempt and the second node records a lock wait or skip rather than a parallel run. Keep the test scripts and timestamps as evidence for the design record.
Check logs for duplicate runs
The operations engineer reviews the cron output, the web server and PHP logs, and the Moodle task logs from every node for the test window. Matching task names with overlapping start and end times indicate that the lock did not hold. Confirm that lock acquisition messages and timeouts appear on the expected nodes and nowhere else. Done when the log review shows no overlapping executions of the same task and every skipped run has a matching lock message. Record the query or filter used so the check can be repeated after upgrades.
Test failure and stale lock recovery
The platform engineer simulates a node that dies while holding a lock, by stopping a cron process during a test task in staging. The engineer then confirms that the lock is released or expires according to the factory's behavior, and that the next scheduled run proceeds on a healthy node. Confirm the recovery steps with the Moodle documentation for your factory before relying on them. Done when the test shows the task resuming without manual database or file edits and the runbook lists the exact steps to clear a stuck lock if one persists.
Document the runbook and sign off
The project lead writes the final configuration record, the test results, the log filters, and the stale lock recovery steps into the operations runbook, then gets sign-off from the Moodle administrators and infrastructure owners. Any later node added to the cluster or any upgrade to a new Moodle release must repeat the version check and the concurrent task test before going live. Done when the runbook is stored with the infrastructure documentation and each node added after go-live has a signed checklist entry showing the same lock configuration and a passing test.
How nodes contend for one scheduled task lock
Each Moodle web or cron node asks the shared lock source for the same named lock before it runs a scheduled task. The first node to get the lock runs the task, while the others back off, skip the run or wait until the lock is released or times out. Check that every node points at the same lock store, that the lock timeout is longer than a normal task run, and that a crashed node's lock expires instead of blocking the cluster.
Cluster nodes competing for one scheduled task lock on a shared source.
Security and operational risks of lock storage
Whichever lock factory you choose, the lock layer touches database privileges, filesystem permissions, failure recovery and configuration consistency. The cards below cover the checks that connect those areas, so that a lock problem does not turn into duplicate cron runs or a stuck site.
Database privileges for lock queries
Advisory and table locks need the Moodle database account to run the functions or write to the lock table that the chosen factory uses. Confirm that the account can take and release advisory locks on PostgreSQL or MySQL, or can insert and delete rows in the lock table, without gaining rights to drop or alter schema objects. Review the grants after every database upgrade, because a restored or rebuilt account can silently lose them. Ask your DBA to test the grant set against a staging copy before cutover.
Moodle 5.1 notesFile permissions on lock directories
A file lock factory writes lock files into a directory that every web node and cron runner must reach. Each of those processes must run as the same user or a shared group, with write access to the directory and read access to the files it creates. Mismatched ownership after a deployment, container rebuild or manual fix is a common cause of locks that never release or never get created. Check ownership and mode on every node, and keep the directory outside the web root so that lock files are not served.
Stale lock recovery after a crash
If a node dies while holding a lock, the lock may stay held until its timeout expires or until someone clears it by hand. Advisory locks are released when the database session ends, which limits this risk, but file locks and table locks depend on your cleanup logic. Decide who clears stale locks, how the runbook confirms that the owning process is gone, and how long a task can be blocked before an alert fires. Rehearse this path on a non-production cluster so that the first crash is not the first test.
Monitoring for duplicate task runs
A lock that fails open lets two nodes run the same scheduled task at the same time, which can duplicate emails, reports or data writes. Log the lock acquisition and release for each scheduled task, and alert when a task starts twice within its expected window or when lock wait times rise. Compare task logs across nodes after each change. Ask your vendor or partner to show how the chosen factory behaves when the lock backend is unreachable, since that behavior determines what a duplicate run looks like.
Identical lock configuration on every node
Every web and cron node must read the same lock factory, lock type and timeout settings, or the cluster will disagree about who owns a task. Keep these settings in one versioned configuration source and deploy it to all nodes together, rather than editing each node by hand. Include a check in your health tooling that compares the effective configuration across nodes after each deployment. Mixed configuration is hard to spot in normal traffic, so test it directly with a forced task run on each node.
Questions teams ask before choosing a Moodle lock factory
Is the default lock factory enough for a two-node Moodle cluster?
For many two-node sites on a single database server with a local or shared dataroot that behaves well with file locking, the default can be enough, but you should confirm it rather than assume it. The default is chosen to work across many setups, so it is not tuned to your storage or database. Check three things first: where lockfactory points, whether the shared directory supports reliable locking, and whether your database offers advisory locks that you already run in production. If any of those is unclear, a short review of cron and scheduled task behavior on both nodes will show whether duplicate or stuck runs are already happening.
How much effort does a Moodle cluster lock review take, and what drives it?
The effort depends mainly on how many nodes run cron, what storage sits under the shared directories, and how many custom or third-party tasks hold locks. A review on a simple setup is a bounded exercise: read the current configuration, confirm the storage behavior, test lock acquisition and release across nodes, and document the result. Effort rises when the storage is network filesystem based, when the database is SQL Server, or when you need to prove behavior under load. Ask any provider for a written scope that lists the environments covered, the tests run, and the deliverable, because that is what a quote should follow from.
What does the work need from our DBA and platform team?
The DBA is needed to confirm which database engine and version you run, how advisory locks behave on it, and whether connection pooling or failover could affect lock ownership. The platform team is needed to describe the web and cron nodes, the shared storage mounts, the load balancer, and how restarts and deployments happen. Plan for a few working sessions with each group and access to a non-production environment that resembles production. Without those inputs, any lock choice is a guess about your infrastructure.
Can our own team test the lock factory choice before changing production?
Yes, if you have two or more Moodle web or cron nodes in a staging environment that matches production storage and database settings. Run scheduled tasks on both nodes at the same time, watch for duplicate executions and lock timeouts in the logs, and simulate a node failure during a long task. Confirm the result with the Moodle documentation for your release before you change lockfactory in production. Your team can run these tests alone, but an independent reviewer often catches assumptions about storage that the team no longer questions.
Does the lock factory choice affect session and cache configuration?
Yes. Session handling, cache stores and cron all compete for locks and shared storage, so changing one can shift contention to another. If you move sessions to Redis or change cache stores, locks taken for cron and tasks may behave differently from locks used for sessions, and both should be reviewed together. Decide the session and cache design first where possible, then choose the lock factory that fits the resulting topology. Review the three together so that a fix in one area does not create a timeout in another.
What goes wrong when the lock factory does not fit the storage?
The usual symptoms are scheduled tasks running twice, tasks that never start because a stale lock remains, or long waits that show up as slow cron runs. On network filesystems such as NFS, file-based locks can behave unexpectedly when clients lose connectivity or when the server handles locks differently from a local disk. On SQL Server, the database-level options are different from PostgreSQL and MySQL, so a choice that works on one engine may not transfer. Record the symptoms, the node logs and the storage type before changing anything, so you can confirm whether the fix worked.
Who pays for the review, and what recurs after it?
The one-time cost is the review itself: reading configuration, testing across nodes, and writing the decision record. Recurring cost appears when the topology changes, such as adding nodes, moving storage, upgrading the database, or upgrading Moodle, because each change can alter lock behavior. Ask whether the scope includes a retest after those events and whether the decision record is kept current. Ongoing support is available as a retainer, so you can decide whether to keep that review in-house or with a partner.
How DeployOpen scopes a Moodle cluster lock review
DeployOpen scopes a lock factory review in writing before any work starts. The scope document names the target architecture: how many web and cron nodes run Moodle, which database engine and version the cluster uses, where the dataroot and temporary directories sit, and whether any of those paths cross an NFS share. It also records which lock factory is under review, which Moodle tasks depend on locking, and which failure modes the client has already seen, such as stuck cron runs or duplicated scheduled tasks. The scope is agreed per engagement, so the reader should expect the document to reflect their own topology rather than a generic template, and no price or duration is given in this section.
The rest of the scope covers the database and file-share setup, the test plan and the rollback path. For the database side, the document lists the engine, the connection pooling in front of it, and the lock behavior the team will exercise, including how the chosen factory behaves under node restarts and network partitions. For the file-share side, it states the mount options, the locking semantics of each share, and the paths that will stay local. The test plan defines which concurrent cron and task scenarios run in a staging copy, what evidence proves a lock is held once and released cleanly, and who signs off. The rollback section describes how the previous lock_factory setting is restored, how cron is paused during the switch, and what the team checks before traffic returns.
Before the scope is signed, the client should confirm the Moodle version and the exact database versions they run, since those set which factories are available and which vendor documentation applies. Ask whether the client needs staging capacity that mirrors production, who holds administrator access to the database and the file share during testing, and how change approval works inside their own organization. The quote then follows from the written scope, so a clear list of nodes, paths, test cases and rollback steps is what makes the estimate comparable across partners.
How DeployOpen works on this
DeployOpen plans and implements Moodle clusters inside infrastructure you control, so the lock factory choice is made against your actual database, file storage and task schedule. We scope the decision in writing, build and test it in your environment, and hand over documentation your operations team can run.
How we scope
- Written scope lists the web nodes, database platform and shared storage the lock factory must work with
- Scope names which cron and adhoc tasks must run exactly once across nodes
- Engagements are fixed-scope, with deliverables and timelines agreed before work starts
How we build
- Configure the chosen lock factory in config.php and confirm it on every web and cron node
- Test concurrent cron runs and task failover against your database and storage layout
- Check NFS or SQL Server behavior directly where the default lock factory is a poor fit
How we hand over
- Documentation records the chosen lock factory, the reasons for it and the rejected alternatives
- Runbook covers lock timeouts, stale lock recovery and what to check after a failed node
- Handover includes a verification checklist your team can rerun after each Moodle upgrade
How we support
- Ongoing support, upgrades and continuous testing are available as retainers
- Retainer work can re-check lock behavior when Moodle versions, databases or storage change
- Confirm with us during scoping which support level and response expectations apply to your cluster

