Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 42 ยท Quality and Production

Performance and Security

Avoid N+1 queries and slow collection loads, cache wisely, profile before tuning, and secure Magento 2.4 code with escaping, form keys, ACL checks, bound queries and patching.

A store that is fast and safe is rarely the result of one clever trick. It comes from many small habits in every module: loading only the data you need, asking the database once instead of a hundred times, escaping every value that reaches a page, checking permissions before an action, and keeping the platform patched. A single careless module can slow down every product page or open a hole into customer data, and Magento stores are valuable targets because they hold orders and personal information.

This lesson collects the habits that matter most when you write custom code. The real Magento snippets are read-only, and two runnable stand-ins make the two most common mistakes visible: counting the queries of an N+1 problem, and watching a bound query defeat an injection.

Measure first

Do not tune by guessing. Before changing code, find out where the time goes:

  • Developer mode and the toolbar-style tools. In developer mode you can enable the database profiler in app/etc/env.php to log every SQL statement of a request (the profiler is for development only; it slows things down).
  • A real profiler. Tools such as Blackfire, Tideways, New Relic or Xdebug profiling show which functions use the time. Look for the few calls that dominate.
  • MySQL's slow query log and EXPLAIN show which queries lack indexes.
  • Count queries per request. A page that runs 500 queries is almost always repeating one query in a loop.

Test with production-sized data. A module that is fine with 20 products can be unusable with 200,000.

The N+1 problem and collection loads

The most common Magento performance bug is the N+1 query: one query loads a list of N rows, then the code runs one more query per row inside a loop. Calling $productRepository->getById() or $customerRepository->getById() inside a foreach is the classic example, because each call can hit the database.

Prefer these patterns:

PHP
// Slow: one extra query per order.
foreach ($orders as $order) {
    $customer = $this->customerRepository->getById($order->getCustomerId());
    // ...
}

// Better: load all customers in one query with an IN filter.
$ids = array_unique(array_map(fn ($o) => $o->getCustomerId(), $orders));
$this->searchCriteriaBuilder->addFilter('entity_id', $ids, 'in');
$customers = $this->customerRepository
    ->getList($this->searchCriteriaBuilder->create())
    ->getItems();

Other rules for collections, which Collections, Filters and SearchCriteria covers in detail:

  • Select only the attributes you need (addAttributeToSelect(['name', 'price'])) instead of *.
  • Set a page size with setPageSize() and setCurPage(), and process big sets in batches.
  • Filter in the database, not in PHP after loading everything.
  • Do not load models inside loops. Do not call ->load() on a collection twice.
  • Use getSize() for counts, not count($collection) after a full load.
  • For product lists on the storefront use the indexed data and search, not a custom EAV query.
PHP Counting queries: N+1 versus one query

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Six orders cost seven queries in the first version and two in the second. With 5,000 orders the difference is 5,001 against 2, and network latency to the database makes each query visible.

Caching strategy

Caching is the biggest lever, and Indexers and Caching explains the tools. The performance rules for your code:

  • Keep the full page cache working. Do not put customer-specific output in a cacheable block.
  • Cache expensive computed values with the cache frontend, using a stable id, a lifetime and tags.
  • Use Redis for the cache and sessions in production, and run OpenSearch properly sized.
  • Do not cache what is cheap, and never cache anything that depends on the current user without keying on it.
  • Keep bin/magento in production mode on live stores, with compiled code and deployed static content (see Deployment and Upgrades).

Security habits

Escape output for its context

Any value that came from a user or a database and reaches a page must be escaped for the place it lands. Templates receive an $escaper object (older templates use $block->escapeHtml()), and each context has its own method:

PHP
<h2><?= $escaper->escapeHtml($block->getTitle()) ?></h2>
<a href="<?= $escaper->escapeUrl($block->getLink()) ?>"
   title="<?= $escaper->escapeHtmlAttr($block->getTooltip()) ?>">
    <?= $escaper->escapeHtml(__('Read more')) ?>
</a>
<script>
    var name = "<?= $escaper->escapeJs($block->getName()) ?>";
</script>

Escape late, at output, and use the method that matches the context: HTML text, an attribute, a URL, or JavaScript. Raw output with <?= $block->getBody() ?> is acceptable only for content you generated and know is safe, such as HTML built by another block.

Form keys and CSRF

Cross-site request forgery tricks a logged-in user's browser into sending a request they did not intend. Magento defends storefront and admin forms with a form key, a random token stored in the session. Every POST form should include <?= $block->getBlockHtml('formkey') ?>, and the framework validates the key before your controller runs. Actions that change data must not be reachable by plain GET links. Controllers that need special handling implement CsrfAwareActionInterface; use that only when you have a good reason, such as an external webhook that cannot hold a form key, and then verify the request another way, for example by a signature.

Authorization

Authentication tells you who the user is; authorization says what they may do. Admin controllers must declare a resource through const ADMIN_RESOURCE = 'Acme_Module::manage'; and the resource must exist in acl.xml, as covered in Admin Controllers, Menus and ACL. REST routes in webapi.xml need a <resource> too. Never rely on hiding a menu item; the endpoint itself must check.

SQL: always bind parameters

Magento's database adapter supports bound values. Never put a request value into SQL text:

PHP
// Dangerous: the value becomes part of the SQL.
$select->where("sku = '" . $sku . "'");

// Safe: the adapter binds or quotes the value.
$select->where('sku = ?', $sku);
$connection->fetchRow('SELECT * FROM acme_item WHERE sku = :sku', ['sku' => $sku]);

Collections and the repository SearchCriteria API also bind values for you, which is another reason to prefer them over hand-written SQL. Use the adapter's quoteInto() or quoteIdentifier() when you must build a fragment, and never build table or column names from user input.

The stand-in below compares the two styles with SQLite. The attacker enters x' OR '1'='1 as an SKU. Concatenation turns that into a condition that is always true. A bound parameter treats the whole text as one harmless value.

PHP String concatenation versus bound parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The attack input returns every row through the concatenated query and none through the bound one. In a real store those rows could be customer data. The last lines show the other half of the job: escaping is for output, binding is for queries, and neither replaces the other.

Keep the platform patched

Adobe publishes security patches and patch releases such as 2.4.x-pN. Attackers scan the internet for stores that have not applied them, sometimes within days. Subscribe to Adobe's security bulletins, apply patches promptly in a staging environment first, keep third-party extensions updated, remove modules you do not use, protect the admin URL and use two-factor authentication for admins (enabled by default in modern 2.4 releases). Store secrets in env.php or environment configuration, never in templates or the repository.

Treat security as a review checklist for every pull request: Does it escape output? Does it check permissions? Does it bind queries? Does it avoid trusting request data for file paths, URLs or class names?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is an N+1 query problem?

    One query loads the list and one more query runs for each of the N rows. Loading related data in one IN query avoids it.
  2. 2. Which escaping method fits a value placed inside an HTML attribute?

    Each context has its own rules. Attribute values use escapeHtmlAttr, element text uses escapeHtml, URLs use escapeUrl and JavaScript strings use escapeJs.
  3. 3. How do you prevent SQL injection when you write a custom query?

    Bound parameters keep data separate from SQL text, so input can never change the structure of the query.
  4. 4. Why does a POST form in Magento include a form key?

    The form key is a session-bound token. A forged request from another site does not know it, so the framework rejects the request.
  5. 5. What should you do before tuning a slow page?

    Guessing wastes time. Profilers and query logs show the few hot spots that explain most of the cost.

Summary

  • Measure with profilers and query counts before tuning, using realistic data volumes.
  • Avoid N+1 queries: load related data in one IN query, select only needed attributes, page large sets and filter in the database.
  • Keep the full page cache effective and cache expensive results with tags.
  • Escape output for its context, include form keys in POST forms, declare ACL resources for admin and API access, and always bind query parameters.
  • Apply Adobe security patches promptly and remove unused modules.

Next: Deployment and Upgrades