Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/visible/cruel/llms.txt

Use this file to discover all available pages before exploring further.

What is Chaos Injection?

Chaos injection is the core concept of Cruel. It wraps your functions to randomly inject failures, delays, timeouts, and other chaos conditions based on probability rates. This helps you test how your application handles real-world failures.

Basic Usage

The main cruel() function wraps any function and applies chaos options:
import { cruel } from 'cruel'

const unreliableFunction = cruel(myFunction, {
  fail: 0.1,    // 10% chance of failure
  delay: 500,   // 500ms delay
  timeout: 0.05 // 5% chance of timeout
})

Chaos Options

All chaos options use probability rates between 0 and 1, where:
  • 0 = never inject chaos
  • 1 = always inject chaos
  • 0.1 = 10% probability

fail

Injects random failures by throwing a CruelError:
const flaky = cruel(fetchData, { fail: 0.2 })

try {
  await flaky()
} catch (error) {
  if (error.name === 'CruelError') {
    console.log('Injected failure:', error.code) // CRUEL_FAILURE
  }
}
The fail option throws errors randomly based on the probability rate. Use this to test error handling logic.

delay

Adds latency to function execution. Accepts a fixed number or a range:
const slow = cruel(process, { delay: 1000 })
// Always adds 1000ms delay

timeout

Creates infinite timeouts that never resolve:
const stuck = cruel(query, { timeout: 0.1 })

// 10% chance this never resolves
const result = await Promise.race([
  stuck(),
  new Promise((_, reject) => 
    setTimeout(() => reject('Timeout'), 5000)
  )
])
Timeout chaos creates hanging promises that never resolve or reject. Always use timeout handlers in production.

jitter

Adds random variability on top of the delay:
const jittery = cruel(request, {
  delay: 1000,
  jitter: 500  // Adds 0-500ms extra random delay
})
// Total delay will be between 1000-1500ms

corrupt

Corrupts string return values by injecting invalid characters:
const corrupted = cruel(async () => "Hello World", { 
  corrupt: 0.3 
})

const result = await corrupted()
// 30% chance: "Hello �orld" (corrupted character)

spike

Creates occasional dramatic latency spikes:
const spiky = cruel(handler, {
  delay: 100,
  spike: 5000  // Occasional 5 second spike
})

Combining Options

All chaos options work together:
const chaotic = cruel(criticalFunction, {
  fail: 0.15,         // 15% failures
  delay: [200, 2000], // 200-2000ms latency
  timeout: 0.05,      // 5% timeouts
  jitter: 500,        // Extra 0-500ms variance
  corrupt: 0.1,       // 10% data corruption
  spike: [1000, 5000] // Occasional 1-5s spikes
})

Convenience Wrappers

Cruel provides pre-configured wrappers for common patterns:
const flaky = cruel.fail(myFunction, 0.2)
// Equivalent to: cruel(myFunction, { fail: 0.2 })

Pre-built Patterns

Unreliable

Simulates a highly unreliable service:
const unreliable = cruel.unreliable(fetchData)
// fail: 0.3, timeout: 0.1, delay: [200, 2000], jitter: 500

Nightmare

Creates worst-case scenarios for stress testing:
const nightmare = cruel.nightmare(processPayment)
// fail: 0.5, timeout: 0.2, delay: [500, 5000], jitter: 1000

Global Chaos

Enable chaos globally for all wrapped functions:
import { cruel } from 'cruel'

// Wrap functions
const fn1 = cruel(function1)
const fn2 = cruel(function2)

// Enable chaos globally
cruel.enable({ fail: 0.1, delay: [100, 500] })

await fn1() // Has chaos
await fn2() // Has chaos

// Disable globally
cruel.disable()

Scoped Chaos

Apply chaos only within a specific scope:
await cruel.scope(async () => {
  // Chaos only applies here
  await fetchData()
  await processData()
}, { fail: 0.2, delay: 1000 })

// No chaos here
await fetchData()

Fluent API

Chain chaos methods for readable code:
const wrapped = cruel.wrap(myFunction)
  .fail(0.1)
  .slow(500)
  .timeout(0.05)

// Or use custom options
const custom = cruel.wrap(myFunction)
  .with({ fail: 0.2, delay: [100, 1000], jitter: 200 })

Statistics

Track chaos injection statistics:
const fn = cruel(myFunction, { fail: 0.1, delay: 500 })

for (let i = 0; i < 100; i++) {
  try {
    await fn()
  } catch (e) {
    // Handle errors
  }
}

const stats = cruel.stats()
console.log(stats)
// {
//   calls: 100,
//   failures: 11,
//   timeouts: 0,
//   delays: 100,
//   corrupted: 0,
//   p50: 501,  // 50th percentile latency
//   p95: 505,  // 95th percentile
//   p99: 507,  // 99th percentile
//   avg: 502,  // Average latency
// }

Error Types

Cruel provides specific error types for different chaos conditions:
import { cruel } from 'cruel'

const fn = cruel(myFunction, { fail: 0.5, timeout: 0.2 })

try {
  await fn()
} catch (error) {
  if (error.name === 'CruelError') {
    console.log('General failure:', error.code)
  }
  if (error.name === 'CruelTimeoutError') {
    console.log('Timeout injected:', error.code) // CRUEL_TIMEOUT
  }
}

Next Steps

Presets

Use pre-configured chaos profiles for different environments

Scenarios

Simulate real-world failure scenarios over time

Chaos Types

Explore domain-specific chaos injection (network, http, ai)

Resilience Patterns

Combine with circuit breakers and retries