Moodle Performance logo

Moodle Performance

Community
SaadRahman01
moodle-performance

Use when optimizing Moodle plugin performance — MUC caching definitions, query optimization, recordsets vs records, ad-hoc and scheduled tasks, lazy loading, OPcache, query log analysis, $PERF, and performance debug toolbar.

Overview

PublisherSaadRahman01
Repositoryclaude-moodle-dev
Skill namemoodle-performance
Stars
42
Forks
7
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by SaadRahman01 on GitHub. Read the source before you install it.

Installation

Install the Moodle Performance AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-performance
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/SaadRahman01/claude-moodle-dev.git /tmp/claude-moodle-dev
mkdir -p .claude/skills
cp -r /tmp/claude-moodle-dev/skills/moodle-performance .claude/skills/moodle-performance
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Moodle Performance in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Moodle Performance on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Moodle Performance is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Moodle Performance

Overview

Moodle bottlenecks: too many DB queries per request, full-table scans, loading large recordsets into memory, blocking work on the request path. Mitigations: MUC caching, indexes, recordsets, ad-hoc tasks, careful capability checks.

When to Use

  • Page renders slowly / hits per-page query limits
  • N+1 query pattern in loops
  • Memory-blow on large datasets
  • Long-running operations on POST handlers
  • Tuning a custom report or scheduled task

Diagnosis

Performance debug

config.php:

php
$CFG->debug = (E_ALL | E_STRICT);
$CFG->debugdisplay = 1;
$CFG->perfdebug = 15;     // shows query count + timings in footer

Site admin > Development > Debugging > Performance info: enables the footer toolbar (queries, time, memory, MUC hits/misses, sessions reads/writes).

$PERF

php
global $PERF;
$start = microtime(true);
// ... work ...
$PERF->dbqueries++;       // your manual counter
mtrace('Took ' . round(microtime(true) - $start, 3) . 's');

Slow query log

Postgres / MySQL slow-query log — turn on in dev. Moodle prefixes queries with the source class via $CFG->dboptions['debug'].

MUC — Moodle Universal Cache

3 cache modes:

ModeStorageLifetimeUse
MODE_APPLICATIONPersistent (file/Redis/Memcached)Until invalidatedShared computed values
MODE_SESSIONSessionSession lifetimePer-user computed values
MODE_REQUESTPHP requestSingle requestMemoize within request

Define a cache

db/caches.php:

php
<?php
defined('MOODLE_INTERNAL') || die();

$definitions = [
    'active_announcements' => [
        'mode'         => cache_store::MODE_APPLICATION,
        'simplekeys'   => true,
        'simpledata'   => true,
        'ttl'          => 600,
        'invalidationevents' => ['changesin_local_announcements'],
    ],
    'user_dashboard' => [
        'mode'       => cache_store::MODE_SESSION,
        'simplekeys' => true,
    ],
];

Bump version.php after edits.

Use the cache

php
$cache = \cache::make('local_announcements', 'active_announcements');
$value = $cache->get('all');
if ($value === false) {
    $value = $this->compute_announcements();
    $cache->set('all', $value);
}
return $value;

Invalidate

php
\cache_helper::invalidate_by_event('changesin_local_announcements', ['all']);
// or
$cache->delete('all');
$cache->purge();

Trigger invalidation from a settings save or an observer.

simplekeys / simpledata

  • simplekeys: true — keys are alphanum (skips hashing) — faster
  • simpledata: true — values are scalars/arrays of scalars (skips serialization) — much faster

Use both whenever possible.

Static cache (per-request)

php
$cache = \cache::make('local_announcements', 'request_lookup');
// MODE_REQUEST in caches.php — auto-cleared at end of request

DB optimization

Recordsets for large data

php
// BAD — loads everything into memory
$rows = $DB->get_records('huge_table');
foreach ($rows as $r) { /* ... */ }

// GOOD — streams
$rs = $DB->get_recordset('huge_table');
foreach ($rs as $r) { /* ... */ }
$rs->close();      // ALWAYS close

Use get_recordset_sql with LIMIT + offset for batched processing of millions of rows.

Avoid N+1

php
// BAD
foreach ($courses as $c) {
    $teacher = $DB->get_record('user', ['id' => $c->teacherid]);
}

// GOOD — single query
$tids = array_column($courses, 'teacherid');
[$insql, $params] = $DB->get_in_or_equal($tids);
$teachers = $DB->get_records_sql("SELECT * FROM {user} WHERE id $insql", $params);

Indexes

xml
<INDEX NAME="userid-courseid" UNIQUE="false" FIELDS="userid, courseid"/>

Edit via XMLDB editor. Composite index column order matters — most-selective first, leftmost-prefix usable for partial queries.

EXPLAIN your queries

bash
mysql> EXPLAIN SELECT ... ;
postgres=# EXPLAIN ANALYZE SELECT ... ;

Look for:

  • type: ALL (full scan) — needs index
  • Using filesort / Using temporary — sort spilling
  • High rows estimate — selectivity issue

Move work off the request

Ad-hoc task — fire-and-forget

php
// classes/task/send_report.php
namespace local_example\task;
class send_report extends \core\task\adhoc_task {
    public function execute(): void {
        $data = $this->get_custom_data();
        // do work
    }
}

// trigger:
$task = new \local_example\task\send_report();
$task->set_custom_data(['userid' => $user->id, 'reportid' => $r->id]);
$task->set_userid($user->id);     // runs as that user
\core\task\manager::queue_adhoc_task($task);

Tasks run via cron. Long jobs don't block HTTP request.

Scheduled task — recurring

db/tasks.php:

php
$tasks = [[
    'classname' => 'local_example\task\cleanup',
    'blocking'  => 0,
    'minute'    => '0',
    'hour'      => '3',
    'day'       => '*',
    'month'     => '*',
    'dayofweek' => '*',
]];
php
class cleanup extends \core\task\scheduled_task {
    public function get_name(): string {
        return get_string('task:cleanup', 'local_example');
    }
    public function execute(): void {
        // ...
    }
}

Run cron: php admin/cli/cron.php. Production: cron entry every minute.

Locks for non-overlapping execution

php
$locktype = 'local_example_cleanup';
$lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
if (!$lock = $lockfactory->get_lock('main', 5)) {
    return;     // another instance running
}
try {
    // ...
} finally {
    $lock->release();
}

Capability check optimization

has_capability() is expensive at scale. For lists:

php
// BAD — N capability checks
foreach ($users as $u) {
    if (has_capability('mod/quiz:attempt', $context, $u)) { /* ... */ }
}

// GOOD — single batched query
$users = get_users_by_capability($context, 'mod/quiz:attempt', 'u.id, u.firstname, u.lastname');

Output / page

php
$PAGE->set_pagelayout('embedded');     // skips heavy regions when appropriate
$PAGE->add_body_class('skip-some-blocks');

Lazy-load AMD modules:

javascript
// only load when needed
const onClick = async () => {
    const {init} = await import('local_example/heavy');
    init();
};

OPcache + APCu

php.ini:

ini
opcache.enable = 1
opcache.memory_consumption = 256
opcache.max_accelerated_files = 20000
opcache.validate_timestamps = 0    # production only
opcache.revalidate_freq = 0

Moodle benefits massively from OPcache. With validate_timestamps=0, restart PHP after deploys.

APCu for Moodle config cache: $CFG->localcachedir = '/var/cache/moodle';

Sessions

  • Use Redis sessions in production ($CFG->session_handler_class = '\core\session\redis')
  • File sessions don't scale past one app server
  • Session writes — see "session lock" issues if multiple AJAX requests block on session
php
// release session lock early when only reading
\core\session\manager::write_close();

Frontend

  • Run npx grunt amd — production builds are minified
  • Enable browser caching: $CFG->cachejs = true; $CFG->cachetemplates = true;
  • Theme designer mode ($CFG->themedesignermode) — OFF in production (disables CSS cache)

Common Mistakes

MistakeFix
get_records on huge tableget_recordset + close
N+1 in loopsBatch with get_in_or_equal
Sending email on POSTMove to ad-hoc task
has_capability per rowget_users_by_capability
MUC without simplekeys/simpledataSet both true when possible
MUC MODE_REQUEST for cross-request dataUse MODE_APPLICATION
Long lock without try/finallyRelease in finally block always
Theme designer mode on prodOff — kills CSS caching
validate_timestamps = 1OFF in prod, restart on deploy
Forgetting $rs->close()Recordset leaks — always close
File sessions on multi-app-serverSwitch to Redis/Memcached

Profiling

xhprof / tideways:

php
// quick on-demand profile
$CFG->profilingenabled = true;
$CFG->profilingautostart = false;
// add ?PROFILEME to URL — view in admin/tool/profiling

Per-request: Site admin > Development > Profiling.

References

Frequently asked questions

What does the Moodle Performance AI skill do?

Use when optimizing Moodle plugin performance — MUC caching definitions, query optimization, recordsets vs records, ad-hoc and scheduled tasks, lazy loading, OPcache, query log analysis, $PERF, and performance debug toolbar.

Why use Moodle Performance on TypingMind?

Because you install it once and use it with any model. Moodle Performance is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Moodle Performance in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-performance. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Moodle Performance?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Moodle Performance?

As many as you like. As long as a model supports skills, you can use Moodle Performance with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Moodle Performance AI skill free?

Yes. It is published on GitHub by SaadRahman01 under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇