Chuyển đến nội dung

Bài 34 · Deployment and Performance

Performance Tuning and Updates

Make Drupal fast and keep it healthy: PHP and database tuning, aggregation, image optimization, Redis, CDN, queues, cron, Views caching, monitoring and a measuring stand-in.

Drupal can serve millions of page views, but only when it is configured for production and kept healthy. Speed comes from layers: efficient PHP and database, good caching (caching and cache tags), light pages and a CDN. Health comes from cron, updates, logs and monitoring. This lesson gives you a practical checklist, ordered by effect.

Drupal cannot run on this site, so configuration and commands are read-only. The TryIt blocks measure and reason about performance ideas with JavaScript stand-ins.

1. Measure first

Do not tune blindly. Use:

  • Browser tools (Lighthouse, network panel) for page weight and Core Web Vitals.
  • Response headers with cacheability debugging to see cache hits.
  • Web Profiler / Devel on development sites for queries per request and slow components. Remove them in production.
  • Slow query log in MySQL (long_query_time = 1) and EXPLAIN for the worst queries.
  • APM tools such as Blackfire, New Relic or Tideways for real PHP profiles.
Node.js Stand-in: percentiles beat averages

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 node:readline or process.stdin), it gets the next line from this box.

2. Production settings

  • Performance page (/admin/config/development/performance): enable page cache, set a browser/proxy max-age (for example 1 hour to 1 day), and turn on CSS and JavaScript aggregation.
  • Install Internal Dynamic Page Cache and Internal Page Cache (both are standard) and, for logged-in traffic, BigPipe.
  • Use PHP 8.3+ with OPcache (opcache.memory_consumption=256, opcache.validate_timestamps=0 with a reset on deploy) and enough memory_limit (256M+).
  • twig.config: debug: false, auto_reload: false and cache: true in production.
  • Disable dev modules (Devel, Kint, Webprofiler, Field UI and Views UI if not needed).

3. Database and Redis

Keep MySQL/MariaDB or PostgreSQL tuned: enough InnoDB buffer pool (innodb_buffer_pool_size about 50 to 70 percent of RAM on a dedicated database server), indexes on columns you filter and sort by, and a connection pool sized for your PHP workers.

Move caches out of the database with Redis (module redis) or Memcache:

PHP
$settings['redis.connection']['interface'] = 'PhpRedis';
$settings['redis.connection']['host'] = getenv('REDIS_HOST') ?: '127.0.0.1';
$settings['cache']['default'] = 'cache.backend.redis';
$settings['cache']['bins']['bootstrap'] = 'cache.backend.chainedfast';

This removes thousands of small reads and writes from the database and speeds up every request, especially cache rebuilds.

4. Views and queries

  • Enable Views caching (tag-based) on blocks and pages, and use pagers instead of "all items".
  • Avoid fetching many fields or relationships you do not display; add exposed filters on indexed columns.
  • Do not load full entities in loops (the N+1 problem). Use loadMultiple() and render with view modes, or use Views fields rather than rendered entities.
  • Prefer entity queries to raw SQL, and add indexes with hook_schema or a hook_update_N for custom tables.
Node.js Stand-in: the N+1 query problem

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 node:readline or process.stdin), it gets the next line from this box.

5. Make pages light

  • Images: use image styles and responsive images with srcset, serve WebP/AVIF (the core image toolkit can convert with the webp image style effect), set loading="lazy" (on by default for image fields) and always provide width and height.
  • JavaScript and CSS: attach libraries only where needed (preprocess and libraries), avoid jQuery-only dependencies in new code, and defer third-party scripts.
  • Fonts: self-host, subset and font-display: swap.
  • Core Web Vitals: reserve space for images and embeds to avoid layout shift; keep the largest above-the-fold element simple.

6. CDN and reverse proxy

Put a CDN (Cloudflare, Fastly, CloudFront) or Varnish in front of anonymous traffic. Drupal sends Cache-Control: public, max-age=... and X-Drupal-Cache-Tags, so modules such as Purge can invalidate the edge when content changes. Serve /sites/default/files and static assets from the CDN. Make sure personalised pages send Cache-Control: private (Drupal does this for logged-in users) and that cookies on anonymous pages do not defeat caching.

7. Cron, queues and background work

Cron runs housekeeping: clearing caches, indexing for search, sending queued mail, scheduled publishing and any module's hook_cron. Do not rely on Automated Cron on a busy site; trigger it from the system:

Terminal
# crontab -e
*/10 * * * * cd /var/www/site && vendor/bin/drush cron

For heavy tasks (sending 10,000 emails, importing files), put work in a queue: a Queue Worker plugin processes items in small batches during cron or with drush queue:run my_queue. This keeps web requests quick and gives retries and rate limits. The Batch API does the same for interactive operations with a progress bar.

Node.js Stand-in: a queue worker with time limit

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 node:readline or process.stdin), it gets the next line from this box.

8. Keep the site healthy

  • Updates: subscribe to security advisories and apply core and module updates with Composer on a schedule; test on staging (deployment). Use drush pm:security and the Status report.
  • Logging: send logs to syslog or an external service instead of the database (dblog grows). Set drush watchdog:delete all regularly if you must keep it.
  • Monitoring: uptime checks, error-rate alerts, disk space, queue length and cron success.
  • Search: use Search API with Solr or Elasticsearch for large sites instead of core search.
  • Backups: automatic, off-server, restore-tested.
Terminal
drush status
drush core:requirements
drush watchdog:show --count=20 --severity=Error
drush sql:dump --gzip --result-file=../backups/site-$(date +%F).sql

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is the first step in performance work?

    Measurements show where time is lost, so you fix the right thing.
  2. 2. Why move cache bins to Redis?

    A fast in-memory store cuts database load for every request.
  3. 3. What is the N+1 problem?

    loadMultiple and joins avoid the many repeated queries.
  4. 4. Where should heavy background work go?

    Queues keep requests fast and allow retries and batching.

Summary

  • Measure with percentiles and profilers before tuning.
  • Enable aggregation, page caches, OPcache and Redis in production; turn Twig debug and dev modules off.
  • Avoid N+1 queries, cache Views, serve light and responsive assets, and use a CDN with cache tags.
  • Run cron from the system and move slow jobs into queues.
  • Keep the site healthy with updates, log management, monitoring and tested backups.

Next: Project: Event Listing Site

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.