Skip to content
Search

Last updated

Find slow Doctrine queries in Symfony in production

Let's say the price page of our shop is fast on our machine, with fifty products. In production the table has three hundred thousand rows, and the page takes a quarter of a second. Which query is it? The profiler would tell us, and the profiler is off in production.

Doesn't look like a complicated task, right?

These steps need a Symfony application and a collector, so they run only on your machine, not in the playground.

Log slow queries in Symfony with a timer

The first idea is always a timer around the query, and a line in the log when it took too long.

#[Route('/prices', name: 'prices', methods: ['GET'])]
public function prices(Connection $connection, LoggerInterface $logger): Response
{
    $start = hrtime(true);

    $prices = $connection->fetchAllAssociative(
        'SELECT category_id, AVG(price) AS average FROM product GROUP BY category_id ORDER BY average DESC',
    );

    $milliseconds = (hrtime(true) - $start) / 1e6;

    if ($milliseconds > 100) {
        $logger->warning('slow query', ['route' => 'prices', 'duration' => $milliseconds]);
    }

    return $this->json($prices);
}

It works, for this one query.

Why a timer in the controller is not enough

We put the timer where we already suspect the problem. The slow query is usually somewhere else.

  • Most queries are not in a controller. The ORM writes them, in a repository, a listener or a lazy relation in a template.
  • A page that loads twenty products and then one category for each of them has no slow query. It has twenty-one fast ones, and no timer sees that.
  • The slow query log of the database knows the query, but not the page that asked for it.

We want every query measured, without touching the code that runs it, and connected to its request.

Trace every Doctrine query in Symfony

flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP, and it is not a wrapper around the official SDK. The bundle needs PHP 8.3 or newer, Symfony 6.4, 7.4 or 8.0 and DoctrineBundle. The only PHP extension it needs is curl.

composer require flow-php/symfony-telemetry-bundle flow-php/telemetry-otlp-bridge

The guide about Symfony monitoring with OpenTelemetry shows the installation step by step. This is the whole configuration:

# config/packages/flow_telemetry.yaml
flow_telemetry:
  resource:
    custom:
      service.name: shop

  exporters:
    collector:
      otlp:
        transport:
          type: curl
          endpoint: 'http://localhost:4318'
          timeout_ms: 200
          connect_timeout_ms: 50

  tracer_provider:
    processor:
      type: batching
      exporter: collector

  meter_provider:
    processor:
      type: batching
      exporter: collector

  instrumentation:
    http_kernel:
      enabled: true
    dbal:
      enabled: true

dbal puts itself between Doctrine and the database driver. Every query of the DBAL and of the ORM becomes a span with its SQL and its duration, inside the trace of its request. We remove the timer from the controller. No code of the application changes.

The SQL is recorded with ? in place of the values, so no data of a customer leaves the database.

Show only the slow queries

The spans go to an OpenTelemetry Collector on the same machine. The guide about the collector for PHP shows how to start one in Docker. We tell it to drop every span that is not a query, and every query faster than 100ms:

receivers:
  otlp:
    protocols:
      http:
        endpoint: 0.0.0.0:4318

processors:
  filter/slow-queries:
    error_mode: ignore
    traces:
      span:
        - 'attributes["db.query.text"] == nil'
        - 'end_time_unix_nano - start_time_unix_nano < 100000000'

exporters:
  debug:
    verbosity: normal

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [filter/slow-queries]
      exporters: [debug]

Now we open three pages of the shop: the product list, the search and the price page. Together they run 39 queries. The collector prints one line:

ScopeTraces #0 flow.symfony.dbal@4.6.0
SELECT product 2a69ccff0e69681fa58541211bbbacbe 5a988c30b722ff39 db.system.name=sqlite db.namespace=default server.address=localhost db.operation.name=SELECT db.collection.name=product db.query.text=SELECT category_id, AVG(price) AS average FROM product GROUP BY category_id ORDER BY average DESC

That's the query of the price page: an average over the whole product table, on every page view. The second value in the line is the trace id. In a monitoring tool the same id opens the whole request, with the route and the controller.

100ms is 100000000 in the filter, because the collector counts in nanoseconds.

Find a page with too many queries

The other half of the problem has no slow query at all. For that the bundle counts: with meter_provider in the configuration, every query adds to a histogram named db.client.operation.duration.

We add metrics to the collector, with no filter:

service:
  pipelines:
    metrics:
      receivers: [otlp]
      exporters: [debug]

This is what one view of the product list sends, with the long lines cut:

db.client.operation.duration{db.operation.name=SELECT,db.collection.name=product} count=1 sum=0.000163042
db.client.operation.duration{db.operation.name=SELECT,db.collection.name=category} count=20 sum=0.000539291

One query for twenty products, and then twenty queries for their categories, one by one. Every one of them is fast, and together they are the classic N+1 problem. The price page looks different in the same metric:

db.client.operation.duration{db.operation.name=SELECT,db.collection.name=product} count=1 sum=0.261899958

One query, 0.26 seconds. The sum is in seconds.

A monitoring tool draws both as a chart for each table: how many queries, and how long they take. A new release that doubles one of them is visible the same day.

What to set for Doctrine tracing

All of these are options of dbal, and none is needed to start:

Option Default What it does
max_sql_length 1000 Cuts the SQL text in the span
include_parameters false Adds the bound values. They can be personal data, so leave it off
transaction_spans grouped One span for a whole transaction, or per_operation, or off
exclude_tables none Queries of these tables are not traced
collect_metrics true The histogram from the section above

Where to go from here

The same bundle traces requests, console commands and more: see Symfony monitoring with OpenTelemetry. To keep whole traces of slow requests and drop the rest, read about tail sampling in the OpenTelemetry Collector for PHP. All the options are in the bundle documentation. Without Doctrine, the PostgreSQL client of Flow traces its own queries: see trace SQL queries in PHP.

Found a typo or an outdated section? Edit this guide on GitHub

scroll back to top