1. Bounded retry with jitter before downstream call
Use case. Calling a dependency on every failure turns transient blips into outages. A bounded retry policy limits attempts, applies backoff and refuses permanent errors instead of retrying forever.
# attempt starts at 1 for original call.
const MAX_ATTEMPTS = 3
const BASE_MS = 200
function retry_decision(attempt, classified_permanent) {
if classified_permanent {
return {"retry": false, "reason": "PERMANENT"}
}
if attempt >= MAX_ATTEMPTS {
return {"retry": false, "reason": "EXHAUSTED"}
}
let delay = BASE_MS * attempt
return {"retry": true, "reason": "TRANSIENT", "delay_ms": delay}
}
print "RETRY={retry_decision(2, false).retry}"
Save as distributed-resilience_01.pea; check pea fmt --check distributed-resilience_01.pea && pea check distributed-resilience_01.pea; run pea run distributed-resilience_01.pea.
2. Bulkhead saturation decision in worker pool
Use case. One overloaded noisy tenant can consume the entire worker pool. Limit in-flight slots per tenant class before dequeueing the next job so good tenants retain capacity.
# Per-tenant queue capacity enforced before claim.
const TENANT_LIMITS = {"shared": 20, "large": 100, "isolated": 400}
function claim_slot(tier, inflight) {
let limit = TENANT_LIMITS[tier]
if inflight >= limit {
return {"ok": false, "reason": "BULKHEAD_FULL"}
}
return {"ok": true, "reason": "OK", "inflight": inflight + 1}
}
print "CLAIM={claim_slot("shared", 20).ok}"
Save as distributed-resilience_02.pea; check pea fmt --check distributed-resilience_02.pea && pea check distributed-resilience_02.pea; run pea run distributed-resilience_02.pea.
3. Lease expiry and fencing guard
Use case. Workers must not act on stale leadership after a partition. Require a monotonic fencing token before writes, and reject any older token even if it was once valid.
# Host persists last_seen_token in the target store.
function fencing_ok(last_seen, candidate) {
if candidate > last_seen {
return {"ok": true, "reason": "NEWER_TOKEN"}
}
return {"ok": false, "reason": "STALE_FENCING_TOKEN"}
}
print "FENCE={fencing_ok(42, 41).ok}"
Save as distributed-resilience_03.pea; check pea fmt --check distributed-resilience_03.pea && pea check distributed-resilience_03.pea; run pea run distributed-resilience_03.pea.
4. Transactional outbox relay eligibility
Use case. A service commits business state and must publish the side effect reliably. The relay can claim only validated, unsent, non-expired outbox rows to avoid duplicate or phantom events.
# Row arrived from SQL adapter pre-validated for types.
function relay_eligible(row) {
if row.status != "PENDING" { return {"ok": false, "reason": "NOT_PENDING"} }
if row.attempts >= 10 { return {"ok": false, "reason": "MAX_ATTEMPTS"} }
if row.next_attempt_ms > row.now_ms { return {"ok": false, "reason": "NOT_DUE"} }
return {"ok": true, "reason": "CLAIMABLE"}
}
print "OUTBOX={relay_eligible({"status":"PENDING","attempts":2,"next_attempt_ms":100,"now_ms":200}).ok}"
Save as distributed-resilience_04.pea; check pea fmt --check distributed-resilience_04.pea && pea check distributed-resilience_04.pea; run pea run distributed-resilience_04.pea.
5. Saga compensation eligibility
Use case. A multi-step order saga must undo only completed reversible steps, in reverse dependency order. Never compensate unstarted or already-undone steps, and never rely on ad hoc operator judgment.
# Steps are ordered by completion time ascending.
let steps = [
{"id":"reserve_inventory","done":true,"compensatable":true,"undone":false},
{"id":"charge_card","done":true,"compensatable":true,"undone":false},
{"id":"notify_warehouse","done":false,"compensatable":true,"undone":false}
]
let i = 0
let count = 0
while i < len(steps) {
let s = steps[len(steps) - 1 - i]
if s.done and s.compensatable and not s.undone { count += 1 }
i += 1
}
print "COMPENSATIONS={count}"
Save as distributed-resilience_05.pea; check pea fmt --check distributed-resilience_05.pea && pea check distributed-resilience_05.pea; run pea run distributed-resilience_05.pea.
6. Cache stampede single-flight decision
Use case. On cache expiry, hundreds of workers may stampede the database. Elect an owner using a lock key; other workers serve stale value or wait rather than all recomputing.
# lock_result comes from the cache itself.
function single_flight(lock_acquired, stale_available) {
if lock_acquired {
return {"action": "RECOMPUTE"}
}
if stale_available {
return {"action": "SERVE_STALE"}
}
return {"action": "WAIT_OR_FAIL"}
}
print "CACHE={single_flight(false, true).action}"
Save as distributed-resilience_06.pea; check pea fmt --check distributed-resilience_06.pea && pea check distributed-resilience_06.pea; run pea run distributed-resilience_06.pea.
7. Deterministic retry scheduling with jitter
Use case. Backoff without jitter synchronises all clients to thunder herd after an outage. Add a bounded jitter value derived from the request ID so retries desynchronise while remaining reproducible for tests.
# id_hash is produced by the host; no random in rules.
const FACTOR = 37
const MAX_JITTER_MS = 250
function jitter_ms(id_hash, attempt) {
let base = 100 * attempt
let jitter = id_hash % MAX_JITTER_MS
return base + jitter
}
print "DELAY_MS={jitter_ms(104729, 2)}"
Save as distributed-resilience_07.pea; check pea fmt --check distributed-resilience_07.pea && pea check distributed-resilience_07.pea; run pea run distributed-resilience_07.pea.
8. Poison message quarantine decision
Use case. A consumer receiving a malformed message must park it before head-of-line blocking kills the partition. Classify shape and decode errors separately from business rejection so replay tools can distinguish them.
# decode_error and schema_error are strings from host.
function quarantine(decode_error, schema_error) {
if decode_error != "" { return {"action":"QUARANTINE","reason":"DECODE"} }
if schema_error != "" { return {"action":"QUARANTINE","reason":"SCHEMA"} }
return {"action":"PROCESS","reason":"VALID"}
}
print "MSG={quarantine("bad-json", "").action}"
Save as distributed-resilience_08.pea; check pea fmt --check distributed-resilience_08.pea && pea check distributed-resilience_08.pea; run pea run distributed-resilience_08.pea.
9. Graceful degradation policy for search
Use case. When the search service is unavailable, the storefront still needs categories and static pages. The decision must be explicit enough to log and alert, not an accidental fallback through unrelated error paths.
# search_health is {"p95_ms": int, "error_rate": float}.
const MAX_P95_MS = 400
const MAX_ERR = 0.02
function search_mode(health) {
if health.error_rate > MAX_ERR {
return {"mode": "DEGRADED", "reason": "ERROR_RATE"}
}
if health.p95_ms > MAX_P95_MS {
return {"mode": "DEGRADED", "reason": "LATENCY"}
}
return {"mode": "NORMAL", "reason": "OK"}
}
print "SEARCH={search_mode({"p95_ms": 350, "error_rate": 0.01}).mode}"
Save as distributed-resilience_09.pea; check pea fmt --check distributed-resilience_09.pea && pea check distributed-resilience_09.pea; run pea run distributed-resilience_09.pea.
10. Leader lease acquisition
Use case. A background job must run singleton even across pods. Lease acquisition uses fencing tokens and TTL so stale pods stop acting when the lease moves after a partition.
# lease state is {holder, token, ttl_ms, now_ms}.
function acquire_lease(lease, candidate, now) {
if now >= lease.expires_at {
return {"ok": true, "new_token": lease.token + 1, "action": "ACQUIRE"}
}
if lease.holder == candidate and now < lease.expires_at {
return {"ok": true, "new_token": lease.token, "action": "RENEW"}
}
return {"ok": false, "action": "WAIT", "holder": lease.holder}
}
print "LEASE={acquire_lease({"holder":"pod-a","token":9,"expires_at":500}, "pod-b", 600).ok}"
Save as distributed-resilience_10.pea; check pea fmt --check distributed-resilience_10.pea && pea check distributed-resilience_10.pea; run pea run distributed-resilience_10.pea.
← Back to the Code Library