Artı Teknoloji - Teknolojiye Artı
MyBB Load Testing and Bottleneck Analysis: k6 Simulations & PHP Profiling - Baskı Önizleme

+- Artı Teknoloji - Teknolojiye Artı (https://www.artiteknoloji.com)
+-- Forum: Web Tabanlı Uygulamalar (https://www.artiteknoloji.com/forumdisplay.php?fid=44)
+--- Forum: MyBB (https://www.artiteknoloji.com/forumdisplay.php?fid=48)
+--- Konu Başlığı: MyBB Load Testing and Bottleneck Analysis: k6 Simulations & PHP Profiling (/showthread.php?tid=574)



MyBB Load Testing and Bottleneck Analysis: k6 Simulations & PHP Profiling - Wertomy® - 19-11-2026

MyBB Load Testing and Bottleneck Analysis: k6 Simulations & PHP Profiling

Every forum administrator discovers their infrastructure's true breaking point eventually—either proactively inside a controlled staging benchmark or catastrophically at 21:00 UTC when a viral announcement drives 8,000 simultaneous readers onto showthread.php and turns every page into a 504 Gateway Timeout error. Simple HTTP ping utilities like ApacheBench (ab) or wrk lie about real-world forum capacity because they hammer a single cached URL without maintaining session cookies, parsing my_post_key CSRF tokens, or simulating authenticated quick-replies. By modeling realistic multi-persona traffic mixes in Grafana k6, capturing flamegraphs via XHProf / Blackfire, and tracing slow MariaDB locks, engineers pinpoint exact CPU, RAM, and SQL bottlenecks before live members ever experience lag.



Modeling Realistic Multi-Persona Forum Traffic vs. Naive Single-URL Pings

A production MyBB forum never experiences uniform traffic. Instead, concurrent Virtual Users (VUs) split across distinct behavioral personas that stress completely different subsystems—from Nginx FastCGI guest cache to MariaDB row-level locks on mybb_posts and mybb_sessions:

[table]
[tr]
[td]Traffic Persona[/td]
[td]Typical Traffic Share[/td]
[td]Target MyBB Endpoints[/td]
[td]Primary Bottleneck Stressed[/td]
[/tr]
[tr]
[td]Anonymous Search Reader[/td]
[td]72% of VUs[/td]
[td]index.php, forumdisplay.php, showthread.php[/td]
[td]Nginx FastCGI cache, Cloudflare edge, network bandwidth[/td]
[/tr]
[tr]
[td]Authenticated Browser[/td]
[td]20% of VUs[/td]
[td]showthread.php, usercp.php, private.php[/td]
[td]PHP-FPM workers, Redis Datacache, mybb_sessions writes[/td]
[/tr]
[tr]
[td]Active Contributor[/td]
[td]5% of VUs[/td]
[td]newreply.php, xmlhttp.php, newthread.php[/td]
[td]InnoDB row locks, BBCode parser regex, webhook queues[/td]
[/tr]
[tr]
[td]Deep Search & Archive Bot[/td]
[td]3% of VUs[/td]
[td]search.php, paginated ?page=40 threads[/td]
[td]MariaDB CPU, temp disk filesorts, full-text search daemon[/td]
[/tr]
[/table]

Building a Stateful Grafana k6 Load Test Script for MyBB

Grafana k6 executes JavaScript-authored load scenarios compiled in Go, allowing a single load-generator node to simulate tens of thousands of stateful virtual users complete with cookie jars, HTML regex extractors for MyBB’s dynamic my_post_key, and realistic human think times (sleep()):

Kod:
// mybb-load-test.js — Stateful Multi-Persona k6 Benchmark for MyBB
import http from 'k6/http';
import { check, sleep, group } from 'k6';
import { Rate, Trend } from 'k6/metrics';

const errorRate = new Rate('mybb_errors');
const threadRenderTrend = new Trend('showthread_ttfb_ms');

export const options = {
  scenarios: {
    guest_readers: {
      executor: 'ramping-vus',
      exec: 'guestBrowseFlow',
      startVUs: 10,
      stages: [
        { duration: '2m', target: 300 },
        { duration: '5m', target: 800 },
        { duration: '2m', target: 0 },
      ],
    },
    active_members: {
      executor: 'ramping-vus',
      exec: 'authenticatedReplyFlow',
      startVUs: 2,
      stages: [
        { duration: '2m', target: 40 },
        { duration: '5m', target: 120 },
        { duration: '2m', target: 0 },
      ],
    },
  },
  thresholds: {
    http_req_failed: ['rate<0.005'],        // Strictly < 0.5% HTTP errors
    showthread_ttfb_ms: ['p(95)<250'],      // 95th percentile TTFB under 250ms
  },
};

export function guestBrowseFlow() {
  group('Guest Thread Discovery', () => {
    const res = http.get('https://staging-forum.example.com/showthread.php?tid=1042');
    threadRenderTrend.add(res.timings.waiting);
    const ok = check(res, {
      'status is 200': (r) => r.status === 200,
      'contains postbit markup': (r) => r.body.includes('class="post_body"'),
    });
    errorRate.add(!ok);
    sleep(Math.random() * 4 + 2); // 2-6s realistic reading pause
  });
}

export function authenticatedReplyFlow() {
  const jar = http.cookieJar();
  group('Member Login & Quick Reply', () => {
    // 1. Authenticate test member account
    const loginRes = http.post('https://staging-forum.example.com/member.php', {
      action: 'do_login',
      username: `loadtester_${__VU}`,
      password: 'StagingTestPassword2026!',
      submit: 'Login',
    });
    check(loginRes, { 'logged in cleanly': (r) => r.status === 200 });

    // 2. Load thread & extract dynamic my_post_key CSRF token
    const threadRes = http.get('https://staging-forum.example.com/showthread.php?tid=1042');
    const tokenMatch = threadRes.body.match(/var my_post_key = "([a-f0-9]{32})";/);
    if (!tokenMatch) {
      errorRate.add(1);
      return;
    }

    sleep(3);

    // 3. Submit stateful AJAX quick-reply via xmlhttp.php
    const replyRes = http.post('https://staging-forum.example.com/xmlhttp.php?action=quick_reply', {
      my_post_key: tokenMatch[1],
      tid: '1042',
      message: `Automated k6 benchmark reply from VU ${__VU} at ${Date.now()}`,
    });
    const posted = check(replyRes, {
      'quick reply accepted': (r) => r.status === 200 && !r.body.includes('error'),
    });
    errorRate.add(!posted);
    sleep(5);
  });
}
Alıntı:Always run authenticated k6 load tests strictly against an isolated staging clone—never against production—because stateful POST scenarios generate thousands of test replies and distort member post counters.

Pinpointing Slow PHP Hooks with XHProf and Flamegraphs

When your k6 benchmark reveals that p95 showthread.php response time spikes from 45ms to 680ms under 120 concurrent authenticated members, guessing which plugin caused the slowdown wastes hours. Attach a low-overhead PHP profiler such as XHProf (Tideways extension) or Blackfire.io to capture function-level wall-time and CPU call graphs:

  1. Trigger Conditional Profiling via HTTP Header or Query Flag: Configure your staging prepend script to invoke tideways_xhprof_enable(TIDEWAYS_XHPROF_FLAGS_CPU | TIDEWAYS_XHPROF_FLAGS_MEMORY) strictly when an incoming request carries a secret X-Profile-Trace: 1 header—keeping normal k6 virtual users uninstrumented while capturing exact microsecond traces on sampled requests.
  2. Analyze Inclusive vs. Exclusive Wall Time: Open the generated flamegraph and sort functions by Exclusive Wall Time (time spent inside the function itself rather than its children). Nine times out of ten, you will immediately spot a single third-party plugin hook—such as an uncached badge lookup inside postbit, a synchronous curl_exec() webhook inside newreply_do_newreply_end, or an unanchored PCRE regex inside parse_message_end—consuming 70% of total PHP execution time.
  3. Inspect Memory High-Water Marks: Check peak PHP memory allocation per request; healthy MyBB thread views consume 6–14 MB, whereas spikes past 45 MB indicate plugins loading entire unpaginated user or thread arrays into PHP RAM.

Diagnosing Database Lock Contention and Slow Queries Under Load

Simultaneously during your k6 stress window, inspect MariaDB/MySQL’s internal telemetry to verify whether database lock waits—not PHP CPU—are throttling throughput:

Kod:
-- Enable temporary 100ms slow query capture during k6 stress test
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 0.10;
SET GLOBAL log_queries_not_using_indexes = 'ON';

-- Inspect real-time InnoDB row lock waits & metadata locks under load
SELECT
    r.trx_id AS waiting_trx_id,
    r.trx_mysql_thread_id AS waiting_thread,
    r.trx_query AS waiting_query,
    b.trx_id AS blocking_trx_id,
    b.trx_mysql_thread_id AS blocking_thread,
    b.trx_query AS blocking_query
FROM information_schema.innodb_lock_waits w
INNER JOIN information_schema.innodb_trx b ON b.trx_id = w.blocking_trx_id
INNER JOIN information_schema.innodb_trx r ON r.trx_id = w.requesting_trx_id;
If innodb_lock_waits surfaces contention on mybb_forums or mybb_users during high-frequency xmlhttp.php reply bursts, verify that Delayed Thread View Updates is active, confirm zero legacy MyISAM tables remain in the schema, and ensure innodb_flush_log_at_trx_commit = 2 is configured on NVMe-backed database nodes.

Establishing Capacity Baselines and Automated CI Regression Gates

Once tuning resolves your top bottlenecks, record your final k6 benchmark results—maximum sustainable requests per second, p95 TTFB, PHP-FPM worker saturation threshold, and MariaDB CPU headroom—as your community’s official capacity baseline. Integrating a compact 60-second k6 smoke benchmark into your staging deployment workflow ensures no future plugin update or theme modification silently reintroduces N+1 database queries or doubles thread rendering latency before reaching live users.