Skip to content

Functional Chaos

Functional Chaos injects real Java exceptions into the application journey at targeted places in the code. Unlike Performance Chaos which degrades the infrastructure, this chaos degrades the code itself: NPE, StackOverflow, OutOfMemory, and silent data corruption.

The pedagogical goal is for students to learn to identify the faulty method through APM (Tempo, Pyroscope) and to understand the exception type without access to the source code.

Service and endpoint

Class: FunctionalChaosService.java Controller: FunctionalChaosController.java Admin endpoint: POST /api/admin/chaos/functional body {"level": 0-4} Trainer read (session or X-Admin-Token): GET /api/chaos/public/functional/{status,logs,anomalies}

Levels

Level Label Active anomalies Cumulative
0 Disabled none 0
1 Junior F1 1
2 Intermediate F1, F2 2
3 Expert F1, F2, F3 3
4 Master F1, F2, F3, F4 4

As with all other families, levels are cumulative: going from level 2 to level 3 adds F3 without disabling F1 and F2.

At levels 2 and above, F1 and F2 share the orders, because an order can fail only once: one order in two reaches F2 — the first after each level setting, then the third, the fifth… — and the others take F1. The count is shared by the whole stack. At level 1, every order takes F1.

F1 — Payment NullPointerException

Required level: 1+ (Junior) Injection method: applyF1PaymentNpe(String paymentMethod) Metric: chaos_functional_f1_npe Counter: cntF1

Simulated anomaly

NullPointerException raised in the payment service (processPaymentPublic) — the order fails with HTTP 500: every order at level 1, one in two at levels 2 and above. The exact exception message is:

Payment gateway configuration is null — service 'PaymentGatewayConfig'
not initialized (injected fault)

Observable symptoms

  • POST /api/orders answers HTTP 500, body {"error": "Erreur serveur: [FunctionalChaos][F1] Payment gateway configuration is null — …"}; no order is recorded
  • Tempo: span OrderController.createOrder marked ERROR, carrying an exception event (exception.type = java.lang.NullPointerException) whose stack trace leads to OrderService.processPaymentPublic; the server span POST /api/orders only has the 500 code
  • Loki logs: [FunctionalChaos][F1] NullPointerException injected into processPaymentPublic — method={paymentMethod}
  • Activity log: F1_NPE entry with severity ERROR

Associated pedagogy

Diagnosis of a non-trivial root cause through the Tempo stack. Students must identify that the NPE is inside an injected (null) dependency and not in the business code — a classic case of missing external config.

F2 — Order calculation StackOverflowError

Required level: 2+ (Intermediate) Injection method: applyF2CalculationStackOverflow(String orderRef) Metric: chaos_functional_f2_stackoverflow

Simulated anomaly

StackOverflowError raised while the order total is being calculated, by an endless recursion:

private void triggerRecursion(int depth) {
    triggerRecursion(depth + 1);
}

It hits one order in two: the first after each level setting, then the third, the fifth… The others take F1. An order that a business rule rejects before the calculation (insufficient stock, double click) has used its turn.

Observable symptoms

  • POST /api/orders answers HTTP 500, but not with the F1 body: it is the server's default error page, {"timestamp": "…", "status": 500, "error": "Internal Server Error", "message": "No message available", "path": "/api/orders"}
  • No order is recorded, and the stock reservation is rolled back with the transaction (measured: stock unchanged)
  • Tempo: the OrderController.createOrder and POST /api/orders spans are in ERROR and carry an exception event of type java.lang.StackOverflowError, without a message. The stack has 1,024 frames, all FunctionalChaosService.triggerRecursion: the JVM truncates it at that depth, and the calling method is not in it. The trace also shows the SQL queries of the order (product read, stock reservation) and the BasicErrorController.error span
  • Loki logs: [FunctionalChaos][F2] StackOverflowError injectee dans calculateOrderTotal — ref={orderRef} (calculateOrderTotal is a label of the log, not a method of the code)
  • Activity log: F2_STACKOVERFLOW severity ERROR

Differential diagnosis with F1: both produce an HTTP 500 on /api/orders, at a level where they alternate. Yet everything tells them apart: the response body, the exception type, the shape of the stack (short and causal for the NPE, 1,024 identical frames for the recursion), the SQL queries present in the F2 trace and absent from the F1 trace, the duration (measured: about ten milliseconds for F1, over a hundred for F2). The student learns to read a truncated stack: it says where the recursion runs, not who started it.

F3 — Catalog OutOfMemoryError

Required level: 3+ (Expert) Injection method: applyF3CatalogOom() Metric: chaos_functional_f3_oom

Simulated anomaly

On every call to the catalog list or search, a loop allocates 8 MB blocks until OutOfMemoryError:

java.util.ArrayList<byte[]> leak = new java.util.ArrayList<>();
while (true) {
    leak.add(new byte[8 * 1024 * 1024]); // 8 MB per iteration
}

This is not a memory leak, despite the name of the variable: the list is local to the request. Once the error is raised, the memory is freed and the backend stays in service. For a leak that climbs in steps, see the "Memory" lever of Performance Chaos.

Observable symptoms

  • GET /api/products (list) and GET /api/products/search answer HTTP 500 in less than three seconds, body {"timestamp": "…", "status": 500, "error": "Internal Server Error", "message": "Java heap space", "path": "…"}
  • GET /api/products/{id} is not affected
  • JVM heap (jvm_memory_used_bytes{area="heap"}): it climbs to its maximum during the request, then falls back (measured: 988 MB out of 990, then 57 MB)
  • Tempo: ERROR span with exception.type = java.lang.OutOfMemoryError; under a burst of calls the stack may be missing (the JVM then returns a preallocated error)
  • Heap dump: the delivered stack does not enable -XX:+HeapDumpOnOutOfMemoryError, so there is no automatic dump; a dump requested afterwards no longer shows the blocks, already freed

Reading a memory spike without mistaking it for a leak: under F3 the heap draws a sawtooth (climb to the maximum, fall back) on every catalog call, whereas a leak climbs in steps and does not come down. It is also an opportunity to connect three signals of the same incident: the client's 500, the exception in the trace and the heap curve.

F4 — Silent product data corruption

Required level: 4 (Master) Injection method: applyF4DataCorruption(Product product) Metric: chaos_functional_f4_corruption

Simulated anomaly

This is the trickiest anomaly in functional chaos. No exception is raised. The method returns a corrupted Product object:

Field Applied transformation
price Multiplied by 1.5 (rounded HALF_UP, scale 2)
stock Forced to 0
description Truncated to 30 characters + suffix [ERROR: truncated data]
id, name, category, imageUrl, dates Unchanged (keeps visual identity)

Observable symptoms

  • HTTP 200 on GET /api/products/{id} — no error
  • Tempo green — no exception propagated
  • No error metric moves
  • Only way to diagnose: manual payload inspection — compare returned prices to expected prices, check that descriptions are not truncated, and that stock is not systematically zero
  • Loki logs (the only hint): [FunctionalChaos][F4] Silent product corruption id={id} name='{name}' — price {old} -> {new}, stock {old} -> 0

Associated pedagogy

This is the anomaly that demonstrates the limits of automatic observability. APM, monitoring, alerting: everything is green. Diagnosing it requires either an assertion test suite (Robot Framework, Cucumber) or a manual database analysis. Ideal for discussing the functional coverage of automated tests.

API — trainer read

Reserved to the trainer (session or X-Admin-Token, 401 otherwise) since Lot E: the live state (active anomalies, counters, log) is the answer key of the hunt labs; "public" is a historical name. Students read their level with GET /api/chaos/student/status.

Endpoint Description
GET /api/chaos/public/functional/status Current level + counters F1–F4
GET /api/chaos/public/functional/logs Activity log (last 200 entries)
GET /api/chaos/public/functional/anomalies?level=N Pedagogical catalog for level N

The trainer's monitoring reads them with its token.

API — admin endpoints

These routes require the trainer: their session, or the X-Admin-Token header (401 otherwise).

# Enable Expert level
curl -X POST http://localhost:9080/api/admin/chaos/functional \
  -H "X-Admin-Token: <token>" \
  -H "Content-Type: application/json" \
  -d '{"level": 3}'

# Reset (level 0, counters set to 0)
curl -X POST http://localhost:9080/api/admin/chaos/functional/reset \
  -H "X-Admin-Token: <token>"

# Clear the activity log
curl -X POST http://localhost:9080/api/admin/chaos/functional/logs/clear \
  -H "X-Admin-Token: <token>"

Student activation

POST /api/chaos/student/functional body {"level": N} — requires student mode and a valid license for level > 0. Without a license, it returns HTTP 402 LICENSE_REQUIRED.

POST /api/chaos/student/functional/reset resets the functional family for the whole room: level 0, counters (Prometheus gauges) and log; same guard as the level setting (student mode, 403 otherwise), no license required. "↺ Reset" button of the student page.