Skip to content

Performance Chaos

Performance Chaos groups nine backend infrastructure levers exposed by ChaosService and executed by six technical components: ChaosInterceptor (thread pool, slow query, network), CpuChaosScheduler (CPU), MemoryLeakSimulator (memory leak), GcPressureSimulator (GC pressure), DbPoolChaosScheduler (HikariCP saturation) and LockContentionSimulator (lock contention). OrderService additionally carries the deadlock injection specific to checkout.

Each lever is an independent 0 – 100 slider (except memory, which uses two coupled sliders) driven by POST /api/admin/chaos/<lever>.

Lever overview

Lever Range Technical class Admin endpoint
CPU 0 – 100 CpuChaosScheduler POST /api/admin/chaos/cpu
CPU ratio 1 – 5 CpuChaosScheduler POST /api/admin/chaos/cpu
Memory leak 0 – 105 MemoryLeakSimulator POST /api/admin/chaos/memory
Memory guardrail 0 – 100 MemoryLeakSimulator POST /api/admin/chaos/memory
GC pressure 0 – 100 GcPressureSimulator POST /api/admin/chaos/gc-pressure
DB pool 0 – 100 DbPoolChaosScheduler POST /api/admin/chaos/db-pool
Thread pool 0 – 100 ChaosInterceptor POST /api/admin/chaos/thread-pool
Slow query 0 – 100 ChaosInterceptor POST /api/admin/chaos/slow-queries
Deadlock 0 – 100 OrderService POST /api/admin/chaos/deadlock
Network timeout 0 – 100 ChaosInterceptor POST /api/admin/chaos/network
Lock contention 0 – 100 LockContentionSimulator POST /api/admin/chaos/lock-contention

All endpoints require the X-Admin-Token header or a valid admin session, and a license: without a license, the whole /api/admin/ prefix answers 402. The returned value follows the { success, message, status } schema where status is the full state from ChaosService.getStatus().

CPU — CpuChaosScheduler

Class: CpuChaosScheduler.java Metrics: chaos_intensity{type="cpu"}, docker_container_cpu_percent{container="perfshop-app"}, process_cpu_usage

Every 100 ms (@Scheduled(fixedRate = 100)), the scheduler hands the busyLoop method to ratio threads of a dedicated pool (Executors.newFixedThreadPool(5)): a SHA-256 hashing loop that stops as soon as the thread has consumed its CPU time budget (measured with ThreadMXBean), or at the end of the tick:

CPU budget per thread and per tick = 100 ms × intensity / 100
target load = intensity % of one core × ratio (1 – 5)

The intensity is therefore a percentage of one core whatever the machine (no more calibration on a reference processor). Measured on 2026-09-25, container limited to 1 CPU: student level 1 (intensity 40) → 41.8 % of one core; student level 4 (intensity 95) → 97.1 %. The ratio multiplies the threads; beyond one core, the container's cpus limit caps the load.

Activation

curl -X POST https://perfshop-api.perfshop.io/api/admin/chaos/cpu \
  -H "X-Admin-Token: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"intensity": 80, "ratio": 2}'

Observation

  • Main metric: docker_container_cpu_percent{container="perfshop-app"} (in % of one core); process_cpu_usage (0 – 1, JVM view)
  • Profile: CpuChaosScheduler.busyLoop frame in the CPU flamegraph (see Pyroscope)
  • Side effect: latency only rises when requests run short of CPU — not measured since the 2026-09-25 recalibration
  • Logs: [BackendChaos] CPU intensity set to: 80 on every change

Memory — MemoryLeakSimulator

Class: MemoryLeakSimulator.java (version v4-retained-target) Metrics: chaos_intensity{type="memory"}, chaos_guardrail{type="memory"}, jvm_memory_used_bytes{area="heap"}

The memory simulator uses two coupled sliders to allow a progressive, bounded memory leak:

Slider Range Meaning
memoryLeakTarget 0 – 100 Percentage of the guardrail capacity to fill
memoryLeakTarget 105 Special value — intentional OOM with no cap
memoryGuardrail 0 – 100 Safety cap as % of max heap (-Xmx), default 80

Effective formula

effective_target_pct   = target × guardrail / 100
targeted_heap_floor    = heap_max × effective_target_pct / 100
retained_memory_target = targeted_heap_floor − starting_live_heap

At activation, one GC measures the application's live heap (baseline). The leak then retains exactly the difference, in 16 KB fragments: a ramp of 5 % of the max heap per second, then a plateau — no System.gc() in steady state. The floor of the heap graph (right after a GC) settles on the target. Measured on 2026-09-25 (N2-05, 42 % target): 345 MB retained, stable; live heap ≈ 415 MB (42 % of 989 MB); 0 System.gc() in steady state.

The previous version (v3) decided on the instantaneous heap — dead eden objects included — and oscillated: 318 → 417 MiB in a loop, about one System.gc() every 3 s.

Intentional OOM mode

The combination target = 105 + guardrail = 100 disables the guardrail and allocates until it triggers an OutOfMemoryError. This is the only configuration that can crash the JVM — all other combinations are bounded by the guardrail.

Examples on -Xmx1g (990 MiB seen by the JVM)

target guardrail Targeted heap floor Behavior
0 80 — Disabled — releases all memory
50 80 396 MiB (40 %) Plateau at 40 % of heap
60 70 416 MiB (42 %) Plateau at 42 % (scenario N2-05)
100 80 792 MiB (80 %) Plateau at 80 % — guardrail active
100 50 495 MiB (50 %) Plateau at 50 %
105 80 792 MiB (80 %) OOM mode capped by 80 % guardrail
105 100 ∞ Intentional OOM — JVM crash

Bidirectional behavior

The slider is reactive in both directions. When the instructor lowers memoryLeakTarget from 100 to 50 %, the simulator releases the extra fragments in one tick to go back to the new target. At 0, all leaked memory is released at once and System.gc() is called (a transition, not steady state).

Activation

curl -X POST https://perfshop-api.perfshop.io/api/admin/chaos/memory \
  -H "X-Admin-Token: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"intensity": 100, "guardrail": 80}'

The intensity field maps to memoryLeakTarget, guardrail to memoryGuardrail. The latter is optional — if omitted, the current value is preserved (default 80).

GC Pressure — GcPressureSimulator

Class: GcPressureSimulator.java (version v3-sawtooth-25s) Metric: chaos_intensity{type="gc_pressure"}

Unlike MemoryLeakSimulator which produces a plateau (leaked memory is not released as long as the slider stays high), the GC pressure simulator cyclically allocates then releases, producing a characteristic sawtooth pattern on the Grafana heap graph.

FILL → RELEASE → PAUSE cycle

gantt
    title GC pressure cycle (25 s)
    dateFormat  s
    axisFormat  %Ss
    section Phase
    FILL (20 ticks)          :a1, 0, 20s
    RELEASE + System.gc()    :crit, a2, 20, 1s
    PAUSE                    :a3, 21, 4s
Phase Duration Action
FILL 20 ticks Allocate heap_max × 0.70 × intensity / 100 / 20 per tick (16 KB fragments)
RELEASE 1 tick clear() the buffer + System.gc() — the drop of the tooth
PAUSE 4 ticks No action

The full cycle lasts 25 seconds regardless of -Xmx: at Prometheus' 5 s scrape, each tooth gets 5 points (the 7 s cycle of the previous version folded the teeth onto one or two points). Tooth height: about 0.70 × intensity % of the max heap above the baseline — at intensity = 60 on -Xmx1g (990 MiB), ≈ 416 MiB in 20 s. Measured on 2026-09-25 (N2-06): 430 MB amplitude, 3 System.gc() in 75 s.

Activation

curl -X POST https://perfshop-api.perfshop.io/api/admin/chaos/gc-pressure \
  -H "X-Admin-Token: $TOKEN" \
  -d '{"intensity": 50}'

Observation

  • Main metric: jvm_memory_used_bytes{area="heap"} — 25 s sawtooth
  • GC metrics: jvm_gc_pause_seconds_count{cause="System.gc()"} +1 per tooth; the JVM sees 1 CPU ⇒ SerialGC: gc="Copy" (minor), gc="MarkSweepCompact" (major)
  • Profile: GcPressureSimulator.pressureGc frame in the allocation profile
  • Logs: [BackendChaos] GcPressure: FILL +20 MB — tenu=… MB / heap max … MB (intensity=60%, tick 1/25) on the first and last filling ticks, then GcPressure: RELEASE — … MB libérés

DB Pool — DbPoolChaosScheduler

Class: DbPoolChaosScheduler.java Metrics: chaos_intensity{type="db_pool"}, hikaricp_connections_active, hikaricp_connections_pending

The scheduler steals a proportional number of HikariCP connections by keeping them open with setAutoCommit(false) (uncommitted transaction). The pool's maximum size is read from spring.datasource.hikari.maximum-pool-size (default 20).

Formula

target_blocked = floor(intensity / 100 × (hikari_max_pool − 1))

At least 1 connection remains free so that the scheduler itself does not deadlock. At intensity = 100 with a pool of 20, the scheduler blocks 19 connections — all new requests wait until the HikariCP timeout (default 30 s).

Tomcat thread pool — ChaosInterceptor

Class: ChaosInterceptor.applyThreadPoolChaos() Metrics: chaos_intensity{type="thread_pool"}, tomcat_threads_busy_threads

For every non-excluded HTTP request, the interceptor applies a Thread.sleep proportional to the intensity — calibrated to progressively saturate the Tomcat pool (default 200 threads). The formula:

Intensity Applied delay
1 – 24 % intensity × 20 ms
25 – 49 % intensity × 30 ms
50 – 74 % 1 500 ms fixed
75 – 99 % 3 000 ms fixed
100 % 5 000 ms fixed

At 25 % the delay is 750 ms, at 50 % it jumps to 1 500 ms: the formula is deliberately progressive at the lower steps and fixed-plateau beyond, to produce a gradual degradation visible in Grafana rather than an abrupt jump. The exact shape is documented in the ChaosInterceptor source code.

Slow Query — ChaosInterceptor

Class: ChaosInterceptor.applySlowQueryChaos() Metrics: chaos_intensity{type="slow_query"}, http_server_requests_seconds{quantile="0.99"}

Identical in principle to the thread pool (similar formula) but applied only to endpoints outside /api/products — the latter is handled by ProductService.applySlowQueryChaos() to avoid double-counting.

Intensity Applied delay
1 – 24 % intensity × 15 ms
25 – 49 % intensity × 25 ms
50 – 74 % 2 000 ms fixed
75 – 99 % 4 000 ms fixed
100 % 6 000 ms fixed

Deadlock — OrderService

Metric: chaos_intensity{type="deadlock"} Endpoint: POST /api/admin/chaos/deadlock

The deadlock injection is carried by OrderService at checkout time. It simulates two concurrent transactions acquiring locks in reverse order (classic anti-pattern: SELECT … FOR UPDATE on two products in opposite orders). At high intensity, the transaction is aborted by MySQL with the error Deadlock found when trying to get lock and the client receives an HTTP 500 with the i18n message order.error.deadlock.

Since deadlocks are inherently probabilistic, the slider level tunes the trigger probability per checkout, not a fixed duration.

Network timeout — ChaosInterceptor

Class: ChaosInterceptor.applyNetworkChaos() Metrics: chaos_intensity{type="network"}, HTTP 503 count

Network Chaos covers every endpoint in the user journey: /api/orders, /api/auth, /api/products, /api/cart, /api/checkout. The trigger probability is proportional to the intensity (at intensity = 30, 30 % of targeted requests are impacted).

Intensity Applied delay
1 – 49 % intensity × 20 ms
50 – 74 % 1 500 ms fixed
75 – 99 % 3 000 ms fixed
100 % 6 000 ms fixed

From 75 % upward, the interceptor additionally has a 20 % chance of sending an HTTP 503 with a Retry-After: 5 header, simulating an unavailable upstream service. The max delay is capped at 6 seconds to stay compatible with the delays added by OrderService.processPaymentPublic() (+ 4 s max), within the usual 15 s client timeout.

Lock contention — LockContentionSimulator

Class: LockContentionSimulator.java Metrics: chaos_intensity{type="lock_contention"}, jvm_threads_states_threads{state="blocked"}; Pyroscope profile mutex:contentions:count:mutex:count Endpoint: POST /api/admin/chaos/lock-contention ({"intensity": 0-100})

Every catalog read (GET /api/products, GET /api/products/{id}) goes through one shared synchronized section, held for 20 ms × intensity / 100 (at least 1 ms as soon as the lever is active). Only one thread at a time reads the catalog: under concurrent load, the other Tomcat threads wait for the monitor — BLOCKED state.

Measured on 2026-09-25, 20 clients on /api/products: intensity 70 (scenario N3-07) → 19 BLOCKED threads at peak (control without chaos: 1); LockContentionSimulator.holdCatalogLock frame in the contention profile. Without concurrency, nothing shows: several simultaneous requests are needed, and the profile only records waits ≥ 10 ms.

curl -X POST https://perfshop-api.perfshop.io/api/admin/chaos/lock-contention \
  -H "X-Admin-Token: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"intensity": 70}'

Global reset

curl -X POST https://perfshop-api.perfshop.io/api/admin/chaos/reset \
  -H "X-Admin-Token: $TOKEN"

POST /api/admin/chaos/reset returns all Performance intensities to zero (memory, GC, DB pool, threads, CPU, slow query, deadlock, network, lock contention), immediately releases the leaked memory and the GC buffer, and additionally resets Frontend Chaos, Scripting Chaos, Business, Functional, and Security. This is the equivalent of the instructor's "Reset all chaos" button.

Default values after reset:

Lever Post-reset value
cpuRatio 1
memoryGuardrail 80 %
All others 0

Pedagogical relevance

Each lever is modeled on a real cause of production incident:

Lever Real-world cause illustrated
CPU Heavy synchronous computation not offloaded (hashing, cryptography)
Memory Cache without eviction, undetached JPA listeners, growing statics
GC pressure Excessive per-request allocations, no object pooling
DB pool FetchType.EAGER on large collections, transactions kept too long
Thread pool Synchronous calls to a slow external service, no timeout
Slow query Missing indexes discovered under load
Deadlock Transactions acquiring locks in opposite orders
Network Degraded downstream payment service with no circuit breaker
Lock contention synchronized section too wide on a hot path (home-made cache, shared singleton)

Status endpoints

Endpoint Access Content
GET /api/chaos/student/status student, no account levels per family and active scenario — without the lever values
GET /api/admin/chaos/status instructor {"backend": {…}, "frontend": {…}}
GET /api/admin/chaos/public/status instructor (session or X-Admin-Token) — 401 otherwise backend + frontend + business + functional

The backend keys are camelCase: memory, memoryGuardrail, gcPressure, dbPool, threadPool, cpu, cpuRatio, slowQuery, deadlock, network, lockContention (e.g. {"backend":{"dbPool":70,…}}).

GET /api/chaos/public/status does not exist (404). The word "public" in /api/admin/chaos/public/status is historical: since 2026-09-25, this endpoint requires an instructor session — its values are the answer key of the students' diagnostics. The instructor console and the monitoring admin call it with the instructor token.