cr-coalesce
cr-coalesce
A lightweight, zero-dependency Crystal singleflight and request coalescing library with optional TTL caching, fluent builder, and @[Coalesce::Singleflight] annotation-based method coalescing.
Inspired by Go's singleflight and TypeScript's @gwash3189/coalesce, cr-coalesce deduplicates concurrent in-flight asynchronous operations sharing the same key so downstream databases, external APIs, and expensive calculations are only hit once during traffic spikes or cache stampedes.
Features
- Concurrent In-Flight Coalescing: When multiple fibers request the same key concurrently, only one execution runs downstream; all other callers wait and receive the shared result.
- Annotation-Based Method API: Simply
include Coalesce(in aclassorstruct) and annotate instance methods with@[Coalesce::Singleflight(...)]using proc, symbol, static, or automatic default key generation. - Fluent Builder API: Chain
.key(...),.ttl(...),.on_hit(...),.on_miss(...), and.work { ... }. - Direct Block API: Lightweight
Coalesce.coalesce(key) { ... }orCoalesce.singleflight(key) { ... }. - Optional TTL Caching: Cache resolved results for a duration (
Time::Spanor numeric milliseconds) to protect against rapid repeated queries. - Fail-Fast Error Propagation: If downstream work raises an exception, the failure is broadcast to all waiting callers and the key is evicted immediately (errors are never cached).
- Thread-Safe & Fiber-Native: Engineered for Crystal's CSP concurrency model using buffered channels and mutexes with zero race conditions.
Installation
Add this to your application's shard.yml:
dependencies:
cr-coalesce:
github: Gwash3189/cr-coalesce
Then install dependencies:
shards install
Usage
1. Annotation API (include Coalesce + @[Coalesce::Singleflight])
Annotate any instance method on a class or struct to automatically deduplicate concurrent invocations (per-overload, preserving visibility, return types, and forall generics):
require "cr-coalesce"
class UserRepository
include Coalesce
# Key generated from method arguments via a Proc:
@[Coalesce::Singleflight(
key: ->(id : String) { "user:#{id}" },
ttl: 30.seconds,
on_hit: :record_hit,
on_miss: :record_miss
)]
def fetch_user(id : String) : User
# Hit downstream database or API
Database.users.find(id)
end
private def record_hit(key : String)
Log.info { "Shared in-flight or cached result for #{key}" }
end
private def record_miss(key : String)
Log.info { "Executing fresh work for #{key}" }
end
end
Flexible Key Options
@[Coalesce::Singleflight] supports multiple key strategies:
- Proc literal:
@[Coalesce::Singleflight(key: ->(id : String) { "user:#{id}" })] def fetch_user(id : String) : User ... end - Instance method symbol:
@[Coalesce::Singleflight(key: :build_search_key)] def search(query : String, tags : Array(String)) : Array(Result) ... end def build_search_key(query : String, tags : Array(String)) : String "search:#{query}:#{tags.join(",")}" end - Static String (positional or named):
@[Coalesce::Singleflight("global_trending", ttl: 1.minute)] def trending_topics : Array(String) ... end - Automatic Default Key: If no key is specified,
cr-coalesceautomatically constructs a key fromClassName#method_nameorClassName#method_name:{args}:@[Coalesce::Singleflight] def calculate_stats(window : Int32) : Stats ... end
2. Direct Block API (Coalesce.coalesce / singleflight)
Wrap arbitrary code blocks anywhere in your application:
require "cr-coalesce"
# Concurrent calls share a single execution
results = Coalesce.coalesce("exchange_rates", ttl: 10.seconds) do
fetch_rates_from_api
end
# Alias: singleflight
user = Coalesce.singleflight("user:42") do
db.query_user(42)
end
3. Fluent Builder API
Construct coalesced operations with chaining and lifecycle hooks:
require "cr-coalesce"
profile = Coalesce.key("profile:42")
.ttl(5.seconds)
.timeout(2.seconds)
.on_hit { |key| Log.info { "Hit: #{key}" } }
.on_miss { |key| Log.info { "Miss: #{key}" } }
.work do
fetch_user_profile(42)
end
Management & Inspection
# Check if work is actively executing
Coalesce.in_flight?("user:42") # => Bool
# Check if a valid unexpired cached result exists
Coalesce.cached?("user:42") # => Bool
# Evict a specific key immediately
Coalesce.invalidate("user:42") # => Bool
# Clear all in-flight and cached entries
Coalesce.reset # => Nil
How It Works
sequenceDiagram
autonumber
actor CallerA as Fiber A
actor CallerB as Fiber B
participant Reg as Coalesce::Registry
participant Flight as Coalesce::Flight
participant DB as Downstream Service
CallerA->>Reg: coalesce("user:42")
Note over Reg: Key not found (Miss)
Reg->>Flight: Create Flight
Reg->>DB: Execute work block
CallerB->>Reg: coalesce("user:42")
Note over Reg: Key in flight (Hit)
Reg->>Flight: Register waiter channel
DB-->>Reg: Return User payload
Reg->>Flight: broadcast_success(result)
Flight-->>CallerA: Return User payload
Flight-->>CallerB: Return User payload
- Stampede Deduplication: The first fiber to request a key starts the downstream task. Any fibers arriving concurrently for the same key suspend on a channel without hitting downstream systems.
- Result Broadcast: When the first fiber completes, all waiting fibers receive the result and resume execution.
- Automatic Cleanup on Failure: If downstream work raises an exception, the error is immediately broadcast to all waiters and the key is evicted so subsequent calls can retry without delay.
- Optional TTL Caching: If
ttlis configured, successful results remain cached for subsequent callers within the TTL window.
Benchmarks
Benchmark executed on Crystal 1.21.0 (Apple M-series):
user system total real
sequential direct coalesce 0.004661 0.000447 0.005108 ( 0.006188) # ~1.6M ops/sec
concurrent singleflight stampede (100 fibers) 0.008699 0.004592 0.013291 ( 0.009616) # ~10k stampedes/sec
annotated method (cached hit) 0.002534 0.000711 0.003245 ( 0.002515) # ~4.0M ops/sec
Run benchmarks locally:
crystal run bench/coalesce_bench.cr --release
Development & Testing
Ensure you have Crystal >= 1.21 installed.
# Run test suite
crystal spec --error-on-warnings
# Check formatting
crystal tool format --check src spec bench
# Run with multiple worker threads
CRYSTAL_WORKERS=4 crystal spec --error-on-warnings
Contributing
- Fork the repository (https://github.com/Gwash3189/cr-coalesce/fork)
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request
License
MIT License. Copyright (c) 2026 Adam Beck.
cr-coalesce
- 0
- 0
- 0
- 0
- 0
- about 1 hour ago
- November 3, 2026
MIT License
Sun, 29 Nov 2026 05:35:34 GMT