Bitrix SQL Query Performance Audit
On a typical high-load Bitrix site, the CMS generates between 200 and 1000 SQL queries per page. Most of them are repetitive, redundant, or contain SELECT *. Before investing in a more expensive server, it pays to understand which queries are slow and why. Over 10 years of working with Bitrix, we have repeatedly seen projects where a single missing index or absent cache consumed 70% of database resources.
SQL query optimization is not a one-time action but an ongoing process. Our clients achieve up to 50% reduction in server load and 2–5x faster page generation. For example, an e‑commerce store with 50,000 catalog items reduced page load from 12 s to 0.4 s by adding a composite index, saving an estimated $2,400 per month in server costs. Such optimization pays for itself within 2–3 months. Let's look at how to identify and eliminate bottlenecks.
How to Identify Slow SQL Queries
Follow these steps:
- Enable the Bitrix SQL tracker in the performance panel (
/bitrix/admin/perfmon_panel.php) or add programmatic logging:
\Bitrix\Main\Diag\SqlTracker::getInstance()->start();
// ... your code ...
$tracker = \Bitrix\Main\Diag\SqlTracker::getInstance();
$tracker->stop();
foreach ($tracker->getQueries() as $query) {
echo $query->getSql() . ' — ' . $query->getTime() . 'ms' . PHP_EOL;
}
-
Analyze the tracker: look for queries slower than 50 ms, duplicates (the same query repeated 10–50 times per page), and queries without WHERE on large tables.
-
Additionally, enable slow_query_log in MySQL/MariaDB (long_query_time = 0.5 in my.cnf) — it provides a real picture under production load.
Why Indexes Are Critical for Bitrix
b_iblock_element can contain from 10,000 to 1,000,000 rows. A query like SELECT * FROM b_iblock_element WHERE IBLOCK_ID = 5 AND ACTIVE = 'Y' ORDER BY SORT without an index on (IBLOCK_ID, ACTIVE, SORT) performs a full table scan. Check with EXPLAIN SELECT ... — if you see ALL in the type column, the index is missing.
Bitrix creates indexes during installation but not for user-defined fields (UTS tables like b_uts_iblock_N_single). Indexes on these tables must be added manually. In our experience, proper indexes speed up specific queries by 2–10 times.
— Based on MySQL documentation and best practices from MySQL Index Optimization.
Excessive Field Selection
CIBlockElement::GetList() by default performs a LEFT JOIN with b_iblock_element_iprop and returns dozens of fields, including DETAIL_TEXT that can be megabytes. If the page only needs ID, NAME, and PREVIEW_PICTURE, specify $select explicitly:
CIBlockElement::GetList(
['SORT' => 'ASC'],
['IBLOCK_ID' => 5, 'ACTIVE' => 'Y'],
false,
['nPageSize' => 20],
['ID', 'NAME', 'PREVIEW_PICTURE']
);
This reduces load by 20–40%.
The N+1 Problem and How to Fix It
The classic scenario: you load 20 elements, then in a loop fetch properties for each with a separate query. That's 21 queries instead of 1–2. In the old API, this is solved with $arSelectFields; in D7, use fetchCollection() with fill(). After optimization, query count drops by 3–5 times.
Repeated Queries for the Same Data
Site settings, user groups, infoblock sections — these are fetched repeatedly on every page. Bitrix's standard cache (BXCache) should handle this, but if caching is disabled or the tagged cache is frequently invalidated, queries hit the database. Bitrix recommends using tagged caching.
What Caching at the Query Level Gives You
If data changes once an hour, there's no need to hit the database on every request. Use \Bitrix\Main\Data\Cache with tagged caching:
$cache = \Bitrix\Main\Data\Cache::createInstance();
$cacheId = 'catalog_top_' . $iblockId;
$cachePath = '/catalog/top/';
if ($cache->initCache(3600, $cacheId, $cachePath)) {
$data = $cache->getVars();
} elseif ($cache->startDataCache()) {
$tagCache = new \Bitrix\Main\Data\TaggedCache();
$tagCache->startTagCache($cachePath);
$data = /* your query */;
$tagCache->registerTag('iblock_id_' . $iblockId);
$tagCache->endTagCache();
$cache->endDataCache($data);
}
When any infoblock element changes, the tag is automatically invalidated. Tagged cache invalidates 3–5 times faster than regular cache.
Optimization Through D7 ORM
D7 ORM allows fine-grained control over queries. Compare:
// Bad: loads all fields and properties
$result = \Bitrix\Iblock\ElementTable::getList([
'filter' => ['IBLOCK_ID' => 5, 'ACTIVE' => 'Y'],
]);
// Better: only needed fields, explicit limit, caching
$result = \Bitrix\Iblock\ElementTable::getList([
'select' => ['ID', 'NAME', 'PREVIEW_PICTURE_ID'],
'filter' => ['IBLOCK_ID' => 5, 'ACTIVE' => 'Y'],
'order' => ['SORT' => 'ASC'],
'limit' => 20,
'offset' => 0,
'cache' => ['ttl' => 3600],
]);
The cache parameter in ORM queries provides built-in caching. D7 ORM is 2–3 times faster than the old API for selections.
Working with Indexes
Adding missing indexes is the quickest fix with the highest impact. Here's a table of the most useful indexes:
| Table |
Recommended Index |
When Needed |
b_iblock_element |
(IBLOCK_ID, ACTIVE, SORT) |
Almost always |
b_iblock_element_property |
(IBLOCK_PROPERTY_ID, VALUE) |
When filtering by properties |
b_sale_order |
(USER_ID, STATUS_ID, DATE_INSERT) |
Customer account area |
b_sale_basket |
(ORDER_ID, FUSER_ID) |
Cart and checkout |
b_search_content_stem |
(PARAM2) |
Search on large catalogs |
An index can be added via SQL or via Bitrix ORM:
$connection = \Bitrix\Main\Application::getConnection();
$connection->queryExecute(
"ALTER TABLE b_iblock_element_property ADD INDEX ix_prop_val (IBLOCK_PROPERTY_ID, VALUE(64))"
);
Be careful with VALUE(64): string fields are indexed by prefix. For numeric values, consider a virtual column. More details in the Wikipedia article on database indexes.
Typical Issues in Projects
- In one company, they couldn't figure out why the cart was slow for 6 months. The culprit was a query to
b_sale_basket without an index on FUSER_ID. Adding the index dropped the time from 10 seconds to 0.1 s.
- Another project: the admin order list page executed 10,000 queries due to N+1 in a custom component. After refactoring, it dropped to 50 queries.
Timeline for Work
| Task |
Scope |
Expected Effect |
| Profiling, identify top 10 queries |
1 day |
Understanding the problem |
| Add missing indexes |
1–2 days |
2–10x speedup on specific queries |
Optimize $select in components |
2–3 days |
20–40% load reduction |
| Fix N+1, add caching |
3–5 days |
3–5x reduction in query count |
| Comprehensive: indexes + selection + cache + ORM |
1–2 weeks |
500+ queries per page → 50–100 |
What's Included
- Audit of current SQL queries and identification of bottlenecks.
- Design and implementation of indexes, optimization of selections.
- Implementation of caching and migration to D7 ORM.
- Documentation of changes and monitoring recommendations.
- Training for your development team.
- 3-month warranty on optimization correctness.
With 10 years of experience, Bitrix certifications, and over 200 successful projects, we guarantee quality. Every day of high load costs your business — optimization pays off in a few months. Our audit starts at $1,500, and typical annual savings exceed $10,000.
Contact us for an audit — we'll analyze your project and propose concrete steps. Order comprehensive optimization and you'll see the difference in speed.
80% of Bitrix sites slow down due to one table
b_iblock_element_property is an EAV structure where each row stores one value of one property of one element. A catalog of 50,000 products with 30 properties yields 1.5 million rows. The smart filter performs a JOIN of this table with b_iblock_element on five properties, and MySQL performs a full table scan for 3–5 seconds. Our experience shows that without intervention in this table, site acceleration is impossible. We take on projects where load time has dropped to 8–10 seconds and bring TTFB back to <200 ms within 1–2 weeks. Site speed optimization begins with an audit of slow queries and ends with a comprehensive turnkey infrastructure overhaul.
Contact us for an audit — we will identify bottlenecks within 2 hours and propose a concrete plan.
How to achieve TTFB below 200 ms?
Server optimization is the first step. Nginx configuration goes beyond simple gzip. Specifically:
-
gzip_comp_level 4-5 — higher is pointless, CPU consumes more than it saves bandwidth.
-
brotli on with brotli_static on for precompressed files.
- HTTP/2 with
http2_max_concurrent_streams 128.
-
fastcgi_cache for PHP responses — caching at Nginx level, bypassing PHP-FPM entirely.
-
worker_processes auto, worker_connections according to the number of simultaneous connections.
PHP-FPM tuning: choose between pm = dynamic and pm = static. Static mode works best for dedicated servers with predictable load because it avoids forking overhead. Dynamic saves RAM under low traffic. Calculate pm.max_children as (available RAM - RAM for MySQL/Redis) / average process consumption. For OPcache set memory_consumption=256, max_accelerated_files=20000, and validate_timestamps=0 in production (restart PHP-FPM on deploy).
MySQL/MariaDB: the main bottleneck is almost always the database. Enable slow_query_log with a threshold of 0.5 sec and analyze every query via EXPLAIN. Set innodb_buffer_pool_size to 70–80% of available RAM on a dedicated server. Create composite indexes for faceted search: (IBLOCK_ID, IBLOCK_PROPERTY_ID, VALUE) on b_iblock_element_property. Run OPTIMIZE TABLE b_iblock_element_property after mass operations.
How to configure three-level caching?
Managed component cache. Set TTL individually for each component. Catalog — 3600 sec, news feed — 300 sec, banners — 86400. The same TTL everywhere guarantees either outdated data or useless cache.
Composite cache. The bitrix:composite technology lets Nginx serve ready HTML from a file; PHP is not executed. Dynamic zones (cart, authorization) are loaded via AJAX request through CBitrixComponent::setFrameMode(true). TTFB drops below 50 ms. However, not all components are compatible; $APPLICATION->ShowPanel() and direct output via echo break the composite. We check every page through the panel 'Performance → Composite Site'. According to Bitrix official documentation on composite cache, this is the most effective caching method for high‑load projects.
Comparison: composite cache is 10–20 times faster than managed cache in time to first byte.
Memcached / Redis. Transfer cache from the file system: sessions go to Redis (session.save_handler = redis) — 10–50 times faster than files, plus cluster support. Component cache goes to Memcached via .settings.php: 'cache' => ['type' => 'memcache']. Also enable ORM query cache so identical GetList() calls don't hit MySQL on every request.
What is the fastest way to optimize Bitrix database?
Default MySQL settings are insufficient. Indexes — composite for faceted search, covering for frequent queries. MySQL responds from the index without accessing the data. Partial indexes (MariaDB) for filtering by ACTIVE = 'Y'. Audit unused indexes — each slows down INSERT/UPDATE.
Partitioning. For tables with millions of rows: b_stat_session, b_search_content_stem, and highload-blocks with history. Partition by date — a query for 'orders in a month' does not scan three years of data. Partitioning also solves the problem of concurrent queries during exchange with 1С via CommerceML.
Real case: a catalog of 200,000 products, 50 properties. Filtering by 10 properties took 12 seconds. After creating composite indexes on (IBLOCK_ID, IBLOCK_PROPERTY_ID, VALUE) and partitioning b_iblock_element_property by IBLOCK_ID, execution time dropped to 0.3 seconds. MySQL load decreased by 40 times.
Cleanup. Over a year or two, any database accumulates: outdated search index, expired records in b_cache_tag, history in b_iblock_element_prop_s*, logs in b_event_log taking gigabytes. We set up regular cleanup via agents.
Frontend and CDN
Images account for 60–80% of page weight. Convert to WebP via CFile::ResizeImageGet() with BX_RESIZE_IMAGE_PROPORTIONAL + conversion. Use srcset + sizes — never load a 3000px image into a 400px block. Add loading="lazy" for everything below the fold. AVIF offers another 20–30% savings vs WebP.
CSS/JS optimization: use the built-in Bitrix module to merge and minify via 'Settings → CSS/JS Optimization'. Apply PurgeCSS / UnCSS — in a typical Bitrix project, 60–70% of CSS is unused. Use defer / async for non‑critical JS and inline critical CSS in <head> for instant FCP.
Fonts: add <link rel="preload" as="font" crossorigin> for the main font. Set font-display: swap — text visible immediately. Subset via pyftsubset — keep only Cyrillic + Latin, file size reduces by 3–5 times.
CDN: Cloudflare, BunnyCDN, AWS CloudFront, or Russian providers (Selectel CDN, VK Cloud CDN). Serve static assets (CSS, JS, images, fonts) via CDN with Cache-Control: public, max-age=31536000, immutable for files with a hash. Use on‑the‑fly image optimization (imgproxy, Cloudflare Polish) without load on origin.
Why is load testing necessary?
Not synthetic benchmarks, but real scenarios: k6 / wrk to simulate routes — catalog → filtering → product card → cart → checkout. Measure RPS, response time (p50, p95, p99), error rate. Use Xdebug (callgrind) or Blackfire for PHP profiling to find bottlenecks. The test result gives an objective picture of where it actually slows down, not where it 'seems'. After optimization, run again to record improvements.
Results
| Metric |
Before |
After |
| TTFB |
800–2000 ms |
50–200 ms |
| Full load |
4–8 sec |
1.5–2.5 sec |
| PageSpeed (mobile) |
30–50 |
80–95 |
| Concurrent users |
50–100 |
500–2000+ |
What is included in the work?
-
Current performance audit — analysis of slow queries, PHP profiling, check of caching, CDN, server settings.
-
Server configuration — Nginx, PHP-FPM, MySQL, Redis/Memcached, OPcache.
-
Caching optimization — managed cache, composite site, TTL configuration, tagged caching.
-
Database work — index creation, partitioning, cleanup, EAV table reorganization.
-
Frontend — images (WebP/AVIF), CSS/JS (minification, deferred), fonts (preload, subsetting).
-
CDN — connection, caching rule setup.
-
Load testing — real user scenarios, metric report.
-
Documentation — description of all changes, recommendations for further maintenance.
-
Guarantee — support for 1 month after delivery, ensuring all optimizations are stable.
Monitoring
Without monitoring, everything degrades in six months. A new module, uncleared logs, a template change — and speed returns to original. Use web-vitals API for Real User Monitoring from actual visitors. Set up synthetic monitoring with Pingdom or UptimeRobot for regular checks from different locations. Configure alerts — TTFB > 500 ms or LCP > 3 sec triggers notification.
Timelines and cost
| Type of work |
Timeline |
| Basic optimization (cache, images, minification) |
2–3 days |
| Database optimization (indexes, slow queries, configuration) |
3–5 days |
| Server infrastructure (Nginx, PHP-FPM, Redis) |
2–3 days |
| Comprehensive (server + database + frontend + CDN) |
1–3 weeks |
| Load testing and profiling |
2–3 days |
| Cluster architecture (balancing, replication) |
1–2 weeks |
Cost is calculated individually after the audit. Get a consultation for your project — we will evaluate the current state and propose an acceleration plan with specific timelines and budget. We are a team with 12+ years of experience in Bitrix, having completed over 300 site speed optimization projects. Contact us to start the performance audit today.