Recreating Real Traffic: From Logs to k6 Scenarios

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Recreating Real Traffic: From Logs to k6 Scenarios
Medium
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Recreating Real Traffic: From Logs to k6 Scenarios

A typical mistake in load testing is using uniform request pacing with a fixed number of virtual users. In reality, traffic has peaks (morning and evening), different user types (mobile browsers, API clients), random pauses, and an 80/20 distribution. For example, 80% of requests hit 20% of pages. Synthetic tests often miss issues with caching, session state, and concurrency.

We offer an approach based on analyzing real traffic from Nginx logs or Google Analytics, and generating k6 scenarios that accurately reproduce real user behavior. Realistic testing is 3 times better than uniform load in identifying performance issues. Clients achieve significant savings on debugging by catching issues early. Contact us to discuss your project.

How Log Analysis Works

# Extract patterns from nginx access log
import re
from collections import Counter, defaultdict
import json

def analyze_access_log(log_file: str):
    pattern = re.compile(
        r'(?P<ip>\S+) .+ \[(?P<time>[^\]]+)\] '
        r'"(?P<method>\w+) (?P<path>[^"]+) HTTP/\d+" '
        r'(?P<status>\d+) (?P<bytes>\d+)'
    )

    endpoint_counts = Counter()
    method_counts = Counter()
    hourly_traffic = defaultdict(int)

    with open(log_file) as f:
        for line in f:
            m = pattern.match(line)
            if not m:
                continue

            # Normalize path (remove IDs)
            path = re.sub(r'/\d+', '/{id}', m.group('path').split('?')[0])
            endpoint_counts[f"{m.group('method')} {path}"] += 1
            method_counts[m.group('method')] += 1

            # Hourly distribution
            hour = m.group('time').split(':')[1]
            hourly_traffic[hour] += 1

    total = sum(endpoint_counts.values())

    print("=== Top Endpoints (% of traffic) ===")
    for endpoint, count in endpoint_counts.most_common(20):
        pct = count / total * 100
        print(f"  {pct:.1f}% {endpoint}")

    print("\n=== Hourly Distribution ===")
    for hour in sorted(hourly_traffic):
        bar = '█' * (hourly_traffic[hour] // 100)
        print(f"  {hour}:00 {bar} {hourly_traffic[hour]}")

    # Export for k6 scenario
    weights = {ep: round(cnt/total, 3) for ep, cnt in endpoint_counts.most_common(20)}
    return weights

The extracted weights are exported to JSON and used to generate k6 scenarios. Analyzing access logs lets us identify the 20% of endpoints generating 80% of traffic, following the Pareto principle.

Limitations of Uniform Traffic

Uniform load doesn't create the "crowd" effect: when 1000 users simultaneously navigate to a product after a social media post. It doesn't test session caching, database locks under concurrent writes, or degradation under sustained peaks. Realistic simulation with a Pareto (80/20) distribution and session behavior reproduces such scenarios, uncovering bottlenecks before production deployment.

How to Build a Scenario Based on Logs

From the extracted weights we generate k6 scenarios. For each user type we create a separate executor with different intensity. For example, 40% traffic – anonymous browsers, 50% – logged-in users, 10% – API clients. Scenarios include random pauses, branching, and probabilistic transitions.

// tests/realistic/user-journey.js
import http from 'k6/http'
import { check, sleep } from 'k6'
import { SharedArray } from 'k6/data'
import { randomItem, randomIntBetween } from 'https://jslib.k6.io/k6-utils/1.4.0/index.js'

// Load test data from CSV
const users = new SharedArray('users', function() {
  return open('./data/test-users.csv').split('\n')
    .slice(1)
    .map(row => {
      const [email, token, userId] = row.split(',')
      return { email, token, userId }
    })
})

const searchTerms = new SharedArray('searches', function() {
  return open('./data/popular-searches.txt').split('\n').filter(Boolean)
})

export const options = {
  scenarios: {
    // Anonymous browsers (40% of traffic)
    anonymous_browse: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '5m', target: 40 },
        { duration: '30m', target: 40 },
        { duration: '5m', target: 0 }
      ],
      exec: 'anonymousBrowse'
    },

    // Logged-in users (50% of traffic)
    logged_in_users: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '5m', target: 50 },
        { duration: '30m', target: 50 },
        { duration: '5m', target: 0 }
      ],
      exec: 'loggedInJourney'
    },

    // API clients (10% of traffic)
    api_clients: {
      executor: 'constant-arrival-rate',
      rate: 10,
      timeUnit: '1s',
      duration: '40m',
      preAllocatedVUs: 20,
      exec: 'apiClient'
    }
  },

  thresholds: {
    http_req_duration: ['p(95)<800'],
    http_req_failed: ['rate<0.01'],
  }
}

const BASE = __ENV.BASE_URL || 'https://staging.example.com'

// Scenario: anonymous browser
export function anonymousBrowse() {
  // Landing → catalog → product → exit
  http.get(`${BASE}/`)
  sleep(randomIntBetween(1, 4))

  const category = randomItem(['electronics', 'clothing', 'books', 'sports'])
  http.get(`${BASE}/api/products?category=${category}&limit=20`)
  sleep(randomIntBetween(2, 8))

  // 30% leave immediately, 70% view product
  if (Math.random() > 0.3) {
    const productId = randomIntBetween(1, 500)
    http.get(`${BASE}/api/products/${productId}`)
    sleep(randomIntBetween(3, 15))
  }

  // 20% perform a search
  if (Math.random() < 0.2) {
    const term = randomItem(searchTerms)
    http.get(`${BASE}/api/search?q=${encodeURIComponent(term)}`)
    sleep(randomIntBetween(1, 5))
  }
}

// Scenario: logged-in user
export function loggedInJourney() {
  const user = randomItem(users)
  const headers = {
    'Authorization': `Bearer ${user.token}`,
    'Content-Type': 'application/json'
  }

  // Profile
  http.get(`${BASE}/api/me`, { headers })
  sleep(randomIntBetween(1, 3))

  // Browse products
  for (let i = 0; i < randomIntBetween(2, 8); i++) {
    const productId = randomIntBetween(1, 500)
    http.get(`${BASE}/api/products/${productId}`, { headers })
    sleep(randomIntBetween(2, 10))
  }

  // 40% add to cart
  if (Math.random() < 0.4) {
    http.post(`${BASE}/api/cart/items`, JSON.stringify({
      productId: randomIntBetween(1, 500),
      quantity: randomIntBetween(1, 3)
    }), { headers })
    sleep(randomIntBetween(1, 3))

    // 60% of those who added — checkout
    if (Math.random() < 0.6) {
      http.get(`${BASE}/api/cart`, { headers })
      sleep(randomIntBetween(2, 5))

      const checkout = http.post(`${BASE}/api/orders`, JSON.stringify({
        paymentMethod: 'saved_card',
        shippingAddressId: 1
      }), { headers })
      check(checkout, { 'order created': (r) => r.status === 201 })
    }
  }
}

// Scenario: API client (integration)
export function apiClient() {
  const apiKey = __ENV.API_KEY
  const headers = {
    'X-API-Key': apiKey,
    'Content-Type': 'application/json'
  }

  // Sync products
  const r = http.get(`${BASE}/api/v1/products?since=${Date.now() - 3600000}`,
    { headers })
  check(r, { 'api: 200': (r) => r.status === 200 })
}

A realistic scenario provides 1.5 times more accurate modeling compared to uniform load.

Pareto Distribution in k6

Real traffic: 20% of pages receive 80% of traffic. This is modeled in k6 with a function that generates IDs according to a power law:

// Pareto distribution ID generator
function paretoId(maxId, shape = 1.5) {
  const u = Math.random()
  return Math.ceil(maxId * Math.pow(1 - u, 1 / shape))
}

// Usage
const productId = paretoId(10000)  // mostly IDs 1-200, rarely ID 9000+

Comparison: Synthetic vs Realistic Testing

Characteristic Synthetic Testing Realistic Testing
Traffic pattern Uniform, manually set Reproduces real patterns (peaks, sessions)
User behavior Same scenario for all VUs Different scenarios (anonymous, logged-in, API)
User journey Linear (home → product → cart) Branching with probabilistic transitions
Bottleneck detection Only throughput Caching, slow endpoints, concurrency
Preparation time Hours Days (requires log analysis)

How We Work

  1. Log analysis: Collect Nginx access logs or Google Analytics data, extract patterns (endpoints, statuses, hourly distribution).
  2. Scenario design: Determine user types (anonymous, logged-in, API), build probabilistic behavior models.
  3. k6 implementation: Write JavaScript scenarios with executors, random pauses, and branching.
  4. Test run: Execute test on staging environment, collect metrics (LCP, CLS, TTFB, errors).
  5. Analysis and report: Identify bottlenecks, compare with baseline, provide optimization recommendations.
Stage Duration Result
Log analysis 0.5–1 day JSON profile of endpoints and distributions
Scenario design 0.5–1 day Probabilistic models for each user type
k6 implementation 1–2 days Working k6 scripts with executors
Test run 1 day Metrics, graphs, thresholds
Report and recommendations 0.5 day Document with analysis and optimization plan
Example hourly load profileTraffic is distributed unevenly: peak at 10-11 AM and 6-7 PM. Other times decline. We assign weights for each hour and generate k6 stages to match the real daily cycle.

What's Included

  • Scenario documentation describing behavior of each user type.
  • k6 configurations (options, thresholds, threshold values).
  • Test results report: load graphs, response time percentiles, errors.
  • Performance optimization recommendations (database indexes, caching, async queues).
  • Support during first run and result interpretation.

Company Metrics

With 5+ years of experience in performance testing and 200+ projects delivered, we guarantee all scenarios are verified on our test benches. Our clients report 15–30% improvement in response times after implementing our recommendations.

Pricing and Timelines

Development of a realistic load test scenario based on real traffic analysis takes 2 to 5 working days. Pricing starts from $2500 for a basic scenario and goes up to $7500 for complex multi-user tests. Typical savings: $15000 on early bug detection.

Order a realistic load testing scenario turnkey. Get a consultation from engineers.

Why are unit tests important but not a panacea?

A bug found by a unit test costs minutes to fix. The same bug in production costs hours of incident response, compensations, and lost trust. In an online store project, a discount calculation error passed manual testing, went to production, and processed 37 orders at zero price in 4 hours. An automated test for edge cases would have caught it on the first push. With 7+ years in web application testing and over 200 projects delivered, we’ve seen this pattern repeat across industries.

Jest is the standard for JavaScript/TypeScript, but unit tests are justified only where there is isolated logic: transformation functions, validators, business rules, utilities. Testing React components with Jest + Testing Library is correct for behavioral tests: "button appears after loading", "form shows error on empty email". Snapshot tests (toMatchSnapshot) are a trap: they break on any layout change and become noise that developers update without looking. Code coverage is a poor quality metric: 80% coverage can be achieved with tests that check nothing. Coverage shows that code executed, not that it works correctly.

Criteria Jest Vitest
Speed for large projects Medium (Babel transformation) 10–20x faster (ES modules)
Integration with Vite Via plugin Native
Monorepos Requires configuration Out of the box

Vitest as an alternative to Jest for Vite projects: 10–20x faster due to native ES modules without Babel transformation. For monorepos with thousands of tests, the speed difference is noticeable. Wikipedia on unit testing describes the theoretical foundation — we apply it with real CI pipelines.

How to set up E2E tests that are not flaky?

Playwright outperforms Cypress on key parameters: native multi-tab, multi-origin, iframe support; parallel execution at test level; WebKit, Firefox, Chromium out of the box; no iframe for the app — tests run in a real browser.

Playwright codegen records actions and generates a test — a good starting point, but generated code needs refactoring. Locators by text content are fragile: getByRole('button', { name: 'Place order' }) is more robust than locator('.btn-primary').

Page Object Model is the standard for organizing E2E tests. Each page is a separate class with methods instead of direct locators. When a button moves from header to sidebar — change in one place, not across all tests.

Flaky tests typically arise from race conditions between request and render, animations without wait, and dependency on external APIs. Solution: page.waitForResponse() instead of page.waitForTimeout(), mocking external APIs via page.route().

// Bad
await page.click('#submit');
await page.waitForTimeout(2000);
await expect(page.locator('.success')).toBeVisible();

// Good
await page.click('#submit');
await page.waitForResponse(resp =>
  resp.url().includes('/api/orders') && resp.status() === 201
);
await expect(page.getByRole('alert', { name: /order created/i })).toBeVisible();

Our engineers guarantee test stability in CI. Playwright’s official documentation covers all API details — we use it daily on projects with millions of users.

How do Core Web Vitals affect ranking?

Google uses Core Web Vitals in ranking. Lighthouse CLI in CI pipeline: on every deploy we check that LCP < 2.5s, CLS < 0.1, INP < 200ms. Google Chrome study: 53% of users leave a site if it takes longer than 3 seconds to load — our tests prevent such losses.

Real problems that Lighthouse finds:

  • Hero image without width/height attributes: CLS 0.35 on load.
  • JavaScript bundle 2.1MB synchronously blocking parsing: INP 450ms.
  • Fonts without font-display: swap: invisible text until font loads (FOIT).
  • Unoptimized hero image 4MB: LCP 8.2s.

Lighthouse CI (lhci) saves metric history and posts a comment to PR with degradation. For one e‑commerce client, optimizing these metrics improved conversion by 18% and reduced server costs by $12k annually.

What does load testing solve?

k6 is a load testing tool with a JavaScript API. Scenarios are written as code, versioned in git, run in CI. Three main scenarios:

  • Spike test — sharp load increase: 0 → 1000 users in 30 seconds. Simulates a campaign launch. Shows system's ability to handle spikes.
  • Soak test — stable load for 2–4 hours. Detects memory leaks, connection pool exhaustion, performance degradation.
  • Stress test — load above expected (150–200% of peak). Shows breaking point and graceful degradation.

Thresholds:

thresholds: {
  http_req_duration: ['p95<500', 'p99<1000'],
  http_req_failed: ['rate<0.01'],
}

p95 < 500ms means 95% of requests respond faster than half a second. If threshold is not met, k6 exits with error code, CI pipeline fails.

In one online store project, we detected API degradation at the 4th hour of the test: p95 increased from 200ms to 2s due to connection leaks. After optimization, the client saved $15k per year on incident response and extra infrastructure.

Testing pyramid in a project

Level Tool Quantity Speed
Unit Vitest/Jest Many (thousands) <5 min
Integration Vitest + supertest Medium 5–15 min
E2E Playwright Few (happy path) 10–30 min
Load k6 On schedule 30–60 min
Performance Lighthouse CI On every deploy 5 min

What does the work include?

  • Audit of current coverage and identification of critical user flows.
  • Writing unit tests for key business logic, integration tests for API, E2E for user scenarios.
  • Setting up parallel execution in CI (sharded workers for Playwright).
  • Load testing with report and recommendations.
  • Test case documentation, training your team on test practices.
  • 1-month warranty support after implementation.
  • Delivery of all test artefacts (code, CI configs, run histories).

How do we work?

  1. Analysis — audit of current testing, identification of weak spots, priority setting.
  2. Design — tool selection, test plan writing, approval.
  3. Implementation — writing tests, CI integration.
  4. Testing — running all levels, result analysis, bug fixing.
  5. Deployment — going live, metric monitoring, team training.

Timeline

Setting up a full test pipeline (Jest + Playwright + k6 + Lighthouse CI) from scratch: 2–4 weeks. E2E test coverage of an existing project (20–30 scenarios): 3–6 weeks. Load testing with report and recommendations: 1–2 weeks. Cost calculated individually after audit.

Ready to discuss your project? Leave a request — we will audit your current web application testing for free and propose a plan that can save up to 60% on incident costs. Get a consultation on web application testing — contact us today.