← Back to Official Package Registry
Tier 2: Distributed & Wire Protocols • Caching, Rate Limits & Breakersv1.0.0 • 28 KB • Ed25519 Verified

resilience@1.0.0

Bounded ORO LRU+TTL cache, GCRA token-bucket rate limiter, 3-state circuit breaker, jittered backoff, and channel-backed singleflight.

use [resilience]
veko pkg add resilience@1.0.0
Run in Browser PlaygroundDownload 1.0.0.vkpRaw demo.vk

resilience

Pure-Veko ORO-native bounded LRU/TTL cache, GCRA & token-bucket rate limiters, 3-state Circuit Breaker, Full-Jitter exponential backoff + hedged retry, and channel-backed thread-safe Singleflight request coalescer (use [res = resilience]).

Overview

resilience provides production traffic-shaping, caching, and fault-isolation primitives tailored to Veko's single-owner ORO memory model and shared-nothing spawn concurrency:

  • Bounded LRU + TTL Cache: Deterministic recency tracking (new-cache, cache-put, cache-get, cache-delete, cache-sweep, cache-stats) with lazy TTL eviction on read, eager expiration sweeps, and zero reference cycles.
  • GCRA & Token-Bucket Rate Limiters: Keyed Generic Cell Rate Algorithm (new-gcra, allow-gcra?) computing exact IETF RateLimit-* / Retry-After telemetry (allowed, remaining, retry_after_ms, reset_after_ms) alongside monotonic TokenBucket (new-token-bucket, allow-tokens?).
  • 3-State Circuit Breaker: Deterministic .closed -> .open -> .half_open -> .closed state machine (new-breaker, call-with-breaker, breaker-state) that fails fast while .open and probes recovery after reset_timeout_ns.
  • Exponential Backoff + Full Jitter & Hedged Retry: Capped min(max_ms, base_ms * 2^attempt) delay calculation with AWS-style uniform [0, cap] Full Jitter (backoff-delay-ms), retry-with, and hedged-call.
  • Channel-Backed Thread-Safe Singleflight: Lock-free/channel-coordinated in-flight request deduplicator (new-singleflight, singleflight-do) safe to pass by value across concurrent spawn tasks so thundering-herd cache misses collapse into a single upstream execution.

Installation

powershell
veko pkg add resilience@1.0.0

Import the module in .vk source files:

rebol
use [res = resilience]

Architecture Notes

Generic Cell Rate Algorithm (GCRA)

For sustained rate R (rate_per_sec) and burst capacity B (burst), each unit cell has emission interval T = 1s / R and maximum Theoretical Arrival Time (TAT) offset L = B * T. For a request arriving at t with previous TAT:

text
new_tat  = max(TAT, t) + cost * T
allow_at = new_tat - B * T
  • When t >= allow_at, the arrival is permitted, TAT advances to new_tat, remaining = (B * T - (new_tat - t)) / T, and reset_after_ms = ceil((new_tat - t) / 1ms).
  • When t < allow_at, TAT is left unchanged and retry_after_ms = ceil((allow_at - t) / 1ms).

Channel-Backed Singleflight Across Shared-Nothing spawn Workers

Veko spawn workers forbid capturing outer mut bindings. Singleflight encapsulates a 1-buffered state channel (chan/new 1) holding a map of in-flight keys to per-waiter 1-slot reply channels. Only the first arriving task executes work_fn (outside the channel lock so distinct keys run concurrently); subsequent concurrent callers for the same key enqueue a reply channel and receive the leader's result (shared = true).

Complete API Reference

  • Bounded LRU + TTL Cache:
  • Structs: CacheEntry, CacheStats, LruCache
  • new-cache [max_entries i64, default_ttl_ns i64] LruCache
  • cache-put [mut c LruCache, key str, val any /ttl ttl_ns i64 = -1 /now now_ns i64 = -1] enum
  • cache-get [mut c LruCache, key str /now now_ns i64 = -1] any
  • cache-delete [mut c LruCache, key str] bool
  • cache-sweep [mut c LruCache /now now_ns i64 = -1] i64
  • cache-stats [c LruCache] CacheStats
  • GCRA & Token-Bucket Rate Limiters:
  • Structs: RateDecision, GcraLimiter, TokenBucket
  • new-gcra [rate_per_sec i64, burst i64] GcraLimiter
  • allow-gcra? [mut g GcraLimiter, key str /cost cells i64 = 1 /now now_ns i64 = -1] RateDecision
  • new-token-bucket [capacity i64, refill_per_sec i64 /now now_ns i64 = -1] TokenBucket
  • allow-tokens? [mut tb TokenBucket, cost i64 /now now_ns i64 = -1] bool
  • 3-State Circuit Breaker:
  • Struct: CircuitBreaker
  • new-breaker [failure_threshold i64, reset_timeout_ns i64, half_open_successes i64] CircuitBreaker
  • breaker-state [cb CircuitBreaker /now now_ns i64 = -1] enum
  • call-with-breaker [mut cb CircuitBreaker, action fn[-> any] /now now_ns i64 = -1] any
  • Backoff, Retry & Hedging:
  • Struct: RetryPolicy
  • backoff-delay-ms [base_delay_ms i64, max_delay_ms i64, attempt i64 /jitter full_jitter bool = false /seed rng_seed i64 = -1] i64
  • retry-with [policy RetryPolicy, action fn[i64 -> any]] any
  • hedged-call [primary fn[-> any], backup fn[-> any]] any
  • Singleflight:
  • Structs: Singleflight, SingleflightResult
  • new-singleflight [] Singleflight
  • singleflight-do [sf Singleflight, key str, work_fn fn[-> any]] SingleflightResult

Idiomatic Veko Examples

Bounded LRU/TTL Cache & GCRA Rate Limiting

rebol
use [res = resilience]

mut cache = res/new-cache 256 (as-i64 30s)
_ = res/cache-put mut cache 'user:42' { name = 'Ada', tier = 'pro' }
user = res/cache-get/or mut cache 'user:42' [ { name = 'guest' } ]

mut limiter = res/new-gcra 100 20
dec = res/allow-gcra? mut limiter 'ip:203.0.113.9'
if not dec.allowed [
    print (str/join ['rate limited; retry in ' (mold dec.retry_after_ms) 'ms'] '')
]

Circuit Breaker + Singleflight Coalescing

rebol
use [res = resilience]

mut breaker = res/new-breaker 5 (as-i64 10s) 2
sf = res/new-singleflight

result = res/call-with-breaker/or mut breaker fn [] [
    sf_out = res/singleflight-do sf 'catalog:featured' fn [] [
        ['sku-1' 'sku-2' 'sku-3']
    ]
    sf_out.val
] [
    ['cached-fallback-sku']
]
print (len result)
packages/resilience/examples/demo.vkSelf-contained runnable example & assertion suite
Raw .vk
// packages/resilience/examples/demo.vk
// Self-contained verification suite & runnable example for `resilience`.

use [res = resilience]

assert-true = fn [cond bool, label str] enum [
	if not cond [
		println (str/join ['[FAIL] ' label] '')
		os/exit 1
	]
	print (str/join ['[PASS] ' label] '')
	.ok
]

// --- 1. Bounded LRU + TTL Cache (`new-cache`, `cache-put`, `cache-get`, `cache-stats`) ---
// Capacity = 3 entries, default TTL = 500ms (500_000_000 ns)
mut cache = res/new-cache 3 500000000
_ = res/cache-put/now mut cache 'k1' 'v1' 0
_ = res/cache-put/now mut cache 'k2' 'v2' 0
_ = res/cache-put/now mut cache 'k3' 'v3' 0

// Touch `k1` so recency order becomes [k2 (LRU), k3, k1 (MRU)]
got_k1 = res/cache-get/now/or mut cache 'k1' 10000000 [ '' ]
// Inserting `k4` must evict `k2` (the oldest LRU key)
_ = res/cache-put/now mut cache 'k4' 'v4' 20000000
miss_k2 = res/cache-get/now/or mut cache 'k2' 30000000 [ 'MISS' ]
keep_k3 = res/cache-get/now/or mut cache 'k3' 30000000 [ 'MISS' ]
st1 = res/cache-stats cache
_ = assert-true (got_k1 == 'v1' and miss_k2 == 'MISS' and keep_k3 == 'v3' and st1.evictions == 1 and st1.size == 3) 'bounded LRU cache promotes accessed keys to MRU and evicts oldest LRU entry'

// Advance clock to t = 600ms (past 500ms TTL for k1, k3, k4) and verify lazy + sweep expiration
exp_k1 = res/cache-get/now/or mut cache 'k1' 600000000 [ 'EXPIRED' ]
swept  = res/cache-sweep/now mut cache 600000000
st2    = res/cache-stats cache
_ = assert-true (exp_k1 == 'EXPIRED' and swept == 2 and st2.size == 0 and st2.expirations == 3) 'TTL cache lazy expiration on get and eager sweep purge'

// --- 2. GCRA & Token-Bucket Rate Limiters ---
// 10 req/sec (100ms emission interval), burst = 3 (300ms tolerance window)
mut gcra = res/new-gcra 10 3
d1 = res/allow-gcra?/now mut gcra 'tenant:acme' 0
d2 = res/allow-gcra?/now mut gcra 'tenant:acme' 0
d3 = res/allow-gcra?/now mut gcra 'tenant:acme' 0
d4 = res/allow-gcra?/now mut gcra 'tenant:acme' 0
d5 = res/allow-gcra?/now mut gcra 'tenant:acme' 40000000   // t = +40ms -> 60ms remaining wait
d6 = res/allow-gcra?/now mut gcra 'tenant:acme' 100000000  // t = +100ms -> 1 cell recovered

gcra_ok_1 = d1.allowed and d1.remaining == 2 and d2.allowed and d2.remaining == 1 and d3.allowed and d3.remaining == 0 and d3.reset_after_ms == 300
gcra_ok_2 = (not d4.allowed) and d4.retry_after_ms == 100 and (not d5.allowed) and d5.retry_after_ms == 60 and d6.allowed and d6.retry_after_ms == 0
_ = assert-true (gcra_ok_1 and gcra_ok_2) 'GCRA burst capacity, retry_after_ms, and reset_after_ms cell recovery math'

mut tb = res/new-token-bucket/now 2 10 0
tb_ok = (res/allow-tokens?/now mut tb 2 0) and (not (res/allow-tokens?/now mut tb 1 0)) and (res/allow-tokens?/now mut tb 1 100000000)
_ = assert-true tb_ok 'token-bucket burst consumption and monotonic refill'

// --- 3. 3-State Circuit Breaker (`.closed -> .open -> .half_open -> .closed`) ---
// Trips after 2 failures, stays open 500ms, requires 2 half-open probe successes to close
mut cb = res/new-breaker 2 500000000 2
cb_calls_ch = chan/new 16

_ = res/call-with-breaker/now/or mut cb fn [] [
	_ = chan/send cb_calls_ch 1
	err 'upstream 503'
] 0 [ .err ]

_ = res/call-with-breaker/now/or mut cb fn [] [
	_ = chan/send cb_calls_ch 1
	err 'upstream 503'
] 10000000 [ .err ]

state_open = cb.state
// Fast-fail while `.open` at t = 100ms (must NOT invoke the closure!)
fast_reject = res/call-with-breaker/now/or mut cb fn [] [
	_ = chan/send cb_calls_ch 1
	'should-not-run'
] 100000000 [ 'FAST_REJECTED' ]

mut backend_invocations = 0
while true [
	c_tick = chan/recv/timeout/or cb_calls_ch 2ms [ 0 ]
	if c_tick == 0 [ break ]
	backend_invocations = backend_invocations + c_tick
]

// At t = 510ms (> 500ms reset timeout), breaker enters `.half_open`; first probe fails -> trips back to `.open`!
probe_fail_state = res/breaker-state/now cb 510000000
_ = res/call-with-breaker/now/or mut cb fn [] [ err 'still-down' ] 510000000 [ .err ]
reopened = cb.state == .open

// At t = 1020ms, two consecutive `.half_open` probes succeed -> transitions `.half_open -> .closed`!
p1 = res/call-with-breaker/now mut cb fn [] [ 'probe-1-ok' ] 1020000000
mid_state = cb.state
p2 = res/call-with-breaker/now mut cb fn [] [ 'probe-2-ok' ] 1030000000
final_state = cb.state

cb_ok = state_open == .open and fast_reject == 'FAST_REJECTED' and backend_invocations == 2 and cb.total_rejected == 1 and probe_fail_state == .half_open and reopened and p1 == 'probe-1-ok' and mid_state == .half_open and p2 == 'probe-2-ok' and final_state == .closed
_ = assert-true cb_ok 'Circuit Breaker full .closed -> .open -> .half_open (probe fail/recover) -> .closed lifecycle'

// --- 4. Exponential Backoff + Full Jitter & Hedged Retry Policy ---
b0 = res/backoff-delay-ms 25 150 0
b2 = res/backoff-delay-ms 25 150 2
b4 = res/backoff-delay-ms 25 150 4
bj = res/backoff-delay-ms/jitter/seed 25 150 3 true 99

tries_ch = chan/new 16
pol = res/RetryPolicy { max_attempts = 4, base_delay_ms = 5, max_delay_ms = 50, full_jitter = true, sleep_enabled = false, seed = 7 }
ret_val = res/retry-with pol fn [attempt] [
	_ = chan/send tries_ch 1
	if attempt < 2 [ err 'transient-timeout' ] else [ 'recovered-on-3rd' ]
]
mut tries = 0
while true [
	t_tick = chan/recv/timeout/or tries_ch 2ms [ 0 ]
	if t_tick == 0 [ break ]
	tries = tries + t_tick
]
hedged_val = res/hedged-call fn [] [ err 'primary-slow' ] fn [] [ 'backup-replica-ok' ]
_ = assert-true (b0 == 25 and b2 == 100 and b4 == 150 and bj >= 0 and bj <= 150 and ret_val == 'recovered-on-3rd' and tries == 3 and hedged_val == 'backup-replica-ok') 'exponential backoff, Full Jitter bounds, retry-with recovery, and hedged-call fallback'

// --- 5. Channel-Backed Thread-Safe Singleflight Across Concurrent `spawn` Workers ---
sf = res/new-singleflight
loads_ch = chan/new 16

mut tasks = []
mut wi = 0
while wi < 5 [
	t = spawn [
		res/singleflight-do sf 'profile:42' fn [] [
			_ = chan/send loads_ch 1
			_ = time/sleep 40ms
			'user-profile-42'
		]
	]
	push mut tasks t
	wi = wi + 1
]

mut shared_cnt = 0
mut all_match = true
mut ti = 0
while ti < (len tasks) [
	out = task/await tasks[ti]
	if out.val != 'user-profile-42' [ all_match = false ]
	if out.shared [ shared_cnt = shared_cnt + 1 ]
	ti = ti + 1
]

// Count how many times the slow loader actually ran
mut actual_loads = 0
while true [
	tick = chan/recv/timeout/or loads_ch 5ms [ 0 ]
	if tick == 0 [ break ]
	actual_loads = actual_loads + tick
]

_ = assert-true (all_match and actual_loads == 1 and shared_cnt >= 1) 'Singleflight coalesces 5 concurrent spawn workers into 1 upstream execution'

print 'resilience: all verification checks passed'
Cryptographic Provenance

Ed25519 Signature & Merkle Integrity

Registry URL: https://veko-lang.org/pkg/resilience/1.0.0.vkp
Archive SHA-256: 1d77970cb16e506258d8767b6ad168ba65c8cd786abdf369b822966645fe7c23
Merkle Root: ebe4c9261af9f50d3ac2d767f5829c9221c214f2cc81224f2a7393db6f121674
Signer Trust Key: ed25519:27406074d8681da1d4e6420f5d887cac15c313334c249ac047ba9d4e2df72b70
Embedded VKP1 Manifest

manifest.json

{"name":"resilience","version":"1.0.0","tier":2.0,"tier_label":"Tier 2: Distributed & Wire Protocols","category":"Caching, Rate Limits & Breakers","description":"Bounded ORO LRU+TTL cache, GCRA token-bucket rate limiter, 3-state circuit breaker, jittered backoff, and channel-backed singleflight.","modules":["resilience"],"homepage":"https://veko-lang.org/packages/resilience"}
Bundle Entry PathSizeLeaf SHA-256 Digest
README.md5 KBb660d319319ab15053abf7f38b2dfc6e7bfe7692d9c24d4b550f4a562d8ed13d
examples/demo.vk6 KB44bc87e063e96e2dc751475d5ec9b5942c49839f027f898e532286a9234d4220
mod.vk15 KB59582897a0eaaa990260a819e107b4bd5da928eeba82ce897c59216820501010