Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 30 ยท Quality and Production

Security and Performance

Make Shopware plugins safe and fast: ACL, input validation, avoiding N+1 reads and unbounded associations, cache invalidation, indexers and queue limits, with runnable demos.

A plugin that works on your laptop with ten products can bring down a shop with half a million. It can also open a hole that lets anonymous visitors read or change data. Security and performance are the two ways a plugin fails in production, and both are mostly about habits: asking "who may do this?" and "how many queries does this run?" every time you write code.

This lesson collects the habits that matter most in Shopware plugins: permissions, validating input, writing escape-safe templates, keeping DAL reads small, understanding the cache layers and indexers, and keeping long-running handlers well-behaved. The Shopware code is read-only, because Shopware cannot run on this site. The runnable examples are stand-ins: an N+1 query counter on SQLite and a tiny tag-based cache. Shared ideas such as shop security basics are covered in Shop Security. Here we focus on the Shopware-specific parts.

Security habits

Permissions on every entry point

Every way into your code needs a rule. In Shopware there are a few distinct entry points, and each has its own guard.

  • Admin API routes. These are for authenticated admin users and integrations. Declare the privileges the route needs, and Shopware refuses callers whose role lacks them (read-only):
PHP
#[Route(
    path: '/api/_action/swag-badge/recalculate',
    name: 'api.action.swag_badge.recalculate',
    defaults: ['_routeScope' => ['api'], '_acl' => ['swag_badge:update']],
    methods: ['POST'],
)]
public function recalculate(Context $context): JsonResponse
{
    // ...
}
  • Store API routes and storefront controllers. Anonymous visitors can call these. Decide what a guest may see, and if data belongs to a customer, load it through the customer from the sales channel context, never through an id the client sends. Reading /wishlist/{customerId} straight from a URL is the classic "insecure direct object reference" mistake.
  • The admin UI. Privileges hide buttons, but the server check is the real one. See Building an Admin Module for the privilege mapping.
  • Webhooks and app endpoints. Verify the signature before you trust anything, as in Apps, Webhooks and Signatures.

Validate input at the boundary

Treat everything from outside as untrusted: request bodies, query strings, uploaded files, config values and webhook payloads. Check type, length and allowed values before you use them. Shopware's validation helpers (a DataValidationDefinition with constraints, run through the DataValidator) throw a structured exception with all violations at once, which the API turns into a clean error response. Your own check can be as plain as comparing against a list of allowed values.

The DAL itself also validates writes through the field flags and field types you chose in Custom Entities and Definitions. That protects the database, but it does not know your business rules, such as "a color must be a hex value".

SQL and output

Use the DAL where possible. When you must write SQL with the DBAL connection, always bind parameters (read-only):

PHP
$rows = $connection->fetchAllAssociative(
    'SELECT LOWER(HEX(id)) AS id, name FROM swag_badge WHERE name LIKE :term LIMIT 50',
    ['term' => '%' . $term . '%'],
);

Never glue a variable into the SQL string. For output, Twig escapes variables automatically. Treat the |raw filter as a loud warning: use it only for HTML you built and escaped yourself. Putting a customer's name or a product's custom field into |raw is a cross-site scripting hole.

Secrets and logs

API keys belong in the plugin configuration (see Plugin Configuration) or environment variables, never in Git. Do not log full request bodies, tokens or customer data. Log ids and outcomes.

Performance habits

The N+1 problem

The N+1 problem means one query to get a list, then one more query for each item. With 24 products on a listing page you pay 25 round trips instead of 1 or 2. In Shopware it usually appears in a loop that calls a repository inside a foreach (read-only):

PHP
// Slow: one search per product
foreach ($products as $product) {
    $badge = $this->badgeRepository->search(
        (new Criteria())->addFilter(new EqualsFilter('productId', $product->getId())),
        $context,
    )->first();
}

// Better: one search for all products, then group in memory
$criteria = (new Criteria())->addFilter(new EqualsAnyFilter('productId', $productIds));
$badges = $this->badgeRepository->search($criteria, $context);

The fix is almost always the same: collect the ids, load everything with a single query (an EqualsAnyFilter, or an association on the original criteria), then group the results in PHP.

flowchart LR
    subgraph Naive["N+1: 1 + N queries"]
        A["Load 24 products"] --> B1["Badge for product 1"]
        A --> B2["Badge for product 2"]
        A --> B3["... 22 more"]
    end
    subgraph Batched["Batched: 2 queries"]
        C["Load 24 products"] --> D["Load all badges<br/>IN (24 ids)"]
    end

Batching trades many tiny queries for one query that takes slightly longer.

Associations and limits

addAssociation() loads related records in the same read, which is the right tool for reading a product with its manufacturer. But an association loads all matching children. A product with 5,000 reviews, or a category with 80,000 products, loads them all unless you restrict the association. Two protections:

  • Give nested criteria a limit: $criteria->getAssociation('reviews')->setLimit(10).
  • Load only the associations the code really uses. Each one adds joins and memory.

Also avoid unbounded outer reads. A search without setLimit() can return an entire table. Page through big sets as shown in the order export project later in the track, and request searchIds() when you only need ids.

Cache layers and invalidation

Shopware caches at several levels, and a plugin should know which one it touches:

Layer What it stores Who cares
HTTP cache Whole storefront pages for guests Page-level plugins, dynamic content
Object cache Results of routes such as Store API routes Plugins that add routes or change what a route returns
Application cache Whatever your services put in it Your own services
Opcache and compiled container PHP code and service wiring Deploy and cache:clear

The hard part is invalidation. A cached page is correct only until something it depends on changes. Shopware solves this with tags: cached items carry tags (for example a product id) and writing the entity invalidates items with that tag. If your plugin changes data without going through the DAL, such as a raw SQL update, or adds data to a cached route from a custom table, you must invalidate the right tags yourself. Otherwise merchants see stale badges until the cache expires. Note that pages with a logged-in customer or a filled cart bypass the HTTP cache by design, so personal data should not be added to cached responses without knowing the cache rules.

The second stand-in below models tagged caching in a few lines.

Indexers

Many fields are computed ahead of time so reads stay fast: product variant data, category assignments, search keywords. Indexers recompute them when entities are written, usually asynchronously through the queue. If your entity has such derived data, plan for it, and keep in mind that heavy indexing on every write slows imports. Registering your own indexer is an advanced topic, but you should know the symptoms: data that is correct in the database but stale in listings usually means the indexer queue has not run yet.

Finding the slow spot

Do not guess. In development, the Symfony profiler shows the queries, time and memory for each request, including repeated identical queries, which is the signature of an N+1. In production, use logs and an APM tool. Measure before and after a change, with realistic data, not three demo products.

Long-running queue handlers

Messages are handled by workers that may run for hours. A handler that loads every order into memory will exhaust it. Process in bounded batches, commit progress, make the job safe to run twice and prefer sending small messages with ids over large payloads. See Scheduled Tasks and the Message Queue.

Counting queries with a stand-in

This stand-in uses SQLite and a wrapper that counts how many statements run. It loads badges for 24 products three ways. The numbers are what matter, since they are the same pattern you would see in the profiler.

PHP Counting queries: N+1 versus batching

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.

All three give the same answer, but the first runs 25 queries and the others one or two. At 24 products the difference is invisible. With a category page of 500 products, or 100 pages served per second, it is the difference between a fast shop and a slow one.

A tag-based cache stand-in

Tagged invalidation is easier to grasp when you can see it. Items are stored with tags. Invalidating a tag removes every item that carries it.

PHP Cache items with tags and invalidation

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 "stale" line is the bug every plugin author meets once: the data changed and the cache did not know. In a real Shopware plugin, writes through the DAL invalidate for you. Raw SQL and external changes do not, which is why you should prefer the DAL, and invalidate tags yourself when you cannot.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a loop that calls a repository once per product a problem?

    Each iteration adds a database round trip. Collect ids and load once with EqualsAnyFilter or an association instead.
  2. 2. A store API route returns a customer's saved items. Where should the customer id come from?

    Ids sent by the client can be changed by anyone. The context identifies the logged-in customer, which prevents reading other people's data.
  3. 3. What is the main risk of addAssociation('reviews') on a product with thousands of reviews?

    Associations load all children by default. Restrict them with a nested limit and load only the associations you use.
  4. 4. Your plugin updates a table with raw SQL and merchants still see old data on cached pages. What is the likely cause?

    DAL writes trigger cache invalidation for the entities they change. Raw SQL does not, so invalidate the tags yourself or use the DAL.

Summary

  • Guard every entry point: declare ACL privileges on API routes, take the customer from the context, verify webhook signatures and never trust client ids.
  • Validate input at the boundary, bind SQL parameters and avoid |raw for data you did not escape.
  • Fix N+1 by collecting ids and loading in one query or through an association, then grouping in memory.
  • Limit associations and searches, and fetch only the data you use.
  • Know the cache layers: tags invalidate cached items, DAL writes invalidate automatically, raw SQL does not.
  • Expect derived data to be refreshed by indexers, and keep queue handlers batched and safe to repeat.
  • Measure with the profiler and realistic data before and after changes.

Next: Packaging, Deployment and Updates.